1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="61fda6a0-3fcb-e60e-5b71-a12ea85c92c7")}catch(e){}}(); 2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,385296,e=>{"use strict";var t=e.i(610995),r=e.i(174721),i=e.i(283587),s=class extends r.Removable{#e;#t;#r;#i;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#r=e.mutationCache,this.#t=[],this.state=e.state||a(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||("pending"===this.state.status?this.scheduleGc():this.#r.remove(this))}continue(){return this.#i?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#s({type:"continue"})},r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#i=(0,i.createRetryer)({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(Error("No mutationFn found")),onFail:(e,t)=>{this.#s({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#s({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)});let s="pending"===this.state.status,a=!this.#i.canStart();try{if(s)t();else{this.#s({type:"pending",variables:e,isPaused:a}),await this.#r.config.onMutate?.(e,this,r);let t=await this.options.onMutate?.(e,r);t!==this.state.context&&this.#s({type:"pending",context:t,variables:e,isPaused:a})}let i=await this.#i.start();return await this.#r.config.onSuccess?.(i,e,this.state.context,this,r),await this.options.onSuccess?.(i,e,this.state.context,r),await this.#r.config.onSettled?.(i,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(i,null,e,this.state.context,r),this.#s({type:"success",data:i}),i}catch(t){try{await this.#r.config.onError?.(t,e,this.state.context,this,r)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,r)}catch(e){Promise.reject(e)}try{await this.#r.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,r)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,r)}catch(e){Promise.reject(e)}throw this.#s({type:"error",error:t}),t}finally{this.#r.runNext(this)}}#s(e){this.state=(t=>{switch(e.type){case"failed":return{...t,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...t,isPaused:!0};case"continue":return{...t,isPaused:!1};case"pending":return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}})(this.state),t.notifyManager.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#r.notify({mutation:this,type:"updated",action:e})})}};function a(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}e.s(["Mutation",0,s,"getDefaultState",0,a])},120563,e=>{"use strict";let t=new WeakMap;function r(e){return e?.queryKey?JSON.stringify({queryKey:e.queryKey,exact:e.exact??null,refetchType:e.refetchType??null,type:e.type??null,stale:e.stale??null}):null}function i(e){let r=t.get(e);return r||(r=new Map,t.set(e,r)),r}function s(e,t,r){for(let[i,s]of e)t-s>r&&e.delete(i)}e.s(["recordRecentInvalidation",0,function(e,t,a=Date.now()){let n=r(t);if(!n)return;let o=i(e);s(o,a,500),o.set(n,a)}
2,"wasRecentlyInvalidated",0,function(e,t,a=500,n=Date.now()){let o=r(t);if(!o)return!1;let l=i(e);s(l,n,a);let c=l.get(o);return null!=c&&n-c<=a}])},270331,e=>{"use strict";var t=e.i(405680),r=e.i(982472),i=e.i(602356);let s=(0,r.createContext)(null);e.s(["WorkspaceProvider",0,function({workspaceId:e,children:a}){let n=(0,r.useMemo)(()=>(0,i.createSessionCoworkClient)(e),[e]);return(0,t.jsx)(s.Provider,{value:{workspaceId:e,wyatt:n,cowork:n},children:a})},"useWorkspace",0,function(){let e=(0,r.useContext)(s);if(!e)throw Error("useWorkspace must be used within a WorkspaceProvider");return e}])},593463,e=>{"use strict";e.i(60243);var t=e.i(599177),r=e.i(999e3),i=e.i(221745),s=e.i(667229);let a=new Map,n=new Set;function o(e){return`wyatt.analytics.userActivated.${e}`}function l({workspaceId:e,activationScore:t,activationMilestone:s}){if(!(0,r.hasAnalyticsConsent)()||function(e){let t=o(e);if(n.has(t))return!0;try{return"1"===window.localStorage.getItem(t)}catch{return!1}}(e))return!1;let a=o(e);n.add(a);try{window.localStorage.setItem(a,"1")}catch{}return(0,i.trackConversionEvent)("user_activated",{workspace_id:e,activation_score:t,activation_milestone:s,event_id:`user_activated:${e}`}),!0}async function c({workspaceId:e,milestoneId:r}){let a=await (0,t.makeWyattClient)(e).onboarding.completeTask({workspaceId:e,milestoneId:r,signal:AbortSignal.timeout(1500)});return!function({workspaceId:e,completion:t}){t.completed&&((0,i.trackConversionEvent)("activation_milestone_completed",{workspace_id:e,milestone:t.milestone_id,completed_count:t.completed_count,total_milestones:t.total_milestones,activation_score:t.activation_score,activation_score_total:t.activation_score_total,is_activated:t.is_activated,event_id:(0,s.createAnalyticsEventId)("activation_milestone_completed")}),t.activated_now&&(0,i.trackConversionEvent)("onboarding_completed",{workspace_id:e,completed_count:t.completed_count,total_milestones:t.total_milestones,activation_score:t.activation_score,activation_score_total:t.activation_score_total,event_id:(0,s.createAnalyticsEventId)("onboarding_completed")}),1===t.completed_count&&l({workspaceId:e,activationScore:t.activation_score,activationMilestone:t.milestone_id}))}({workspaceId:e,completion:a.data}),a.data}async function u({workspaceId:e,milestoneId:t}){await a.get(`${e}:${t}`)}e.s(["queueActivationMilestoneCompletion",0,function({workspaceId:e,milestoneId:t}){let r=`${e}:${t}`;if(a.has(r))return;let i=c({workspaceId:e,milestoneId:t}).then(()=>void 0).catch(r=>{console.error("[Wyatt:Activation] milestone completion failed",{workspaceId:e,milestoneId:t,error:r})}).finally(()=>{a.get(r)===i&&a.delete(r)});a.set(r,i)},"trackUserActivatedOnce",0,l,"waitForQueuedActivationMilestoneCompletion",0,u])},480723,e=>{"use strict";var t=e.i(221745),r=e.i(999e3),i=e.i(466809),s=e.i(667229);let a="wyatt.analytics.firstSessionAttempts",n="wyatt.analytics.firstSessionRetries",o=!1;function l(){try{return window.sessionStorage}catch{return null}}function c(e){let t=l();if(!t)return{};try{let r=JSON.parse(t.getItem(e)??"{}");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}catch{return{}}}function u(e,t){let r=l();if(r)try{0===Object.keys(t).length?r.removeItem(e):r.setItem(e,JSON.stringify(t))}catch{}}function d({workspaceId:e,step:t,surface:r}){return`${e??"none"}:${t}:${r}`}function p(e){return{attempt_id:e.attemptId,...e.workspaceId?{workspace_id:e.workspaceId}:{},step:e.step,surface:e.surface,retry_count:e.retryCount,elapsed_time_bucket:function(e,t=Date.now()){let r=Math.max(0,Math.min(t-e,9e5));return r<5e3?"under_5s":r<3e4?"5s_to_30s":r<12e4?"30s_to_2m":"2m_to_15m"}(e.startedAt)}}function y(e){let t=c(a),r=Object.entries(t).find(([,t])=>t.attemptId===e);return r?(delete t[r[0]],u(a,t),r[1]):null}function h(e,t){let r=c(n),i=d(e);null===t?delete r[i]:r[i]=Math.min(Math.max(t,0),3),u(n,r)}function f(){let e=c(a);for(let[r,i]of Object.entries(e))i.abandonOnPageHide&&((0,t.trackEvent)("first_session_action_abandoned",{...p(i),cancel_reason:"navigation"}),h(i,i.retryCount+1),delete e[r]);u(a,e)}function m(e){let t=e&&"object"==typeof e?e:{},r="number"==typeof t.status?t.status:"number"==typeof t.statusCode?t.statusCode:void 0,i="string"==typeof t.code?t.code.toLowerCase():"",s="string"==typeof t.name?t.name.toLowerCase():"",a=e instanceof Error?e.message.toLowerCase():"string"==typeof e?e.toLowerCase():"";
2return 401===r?{category:"unauthorized",retriable:!1}:403===r?{category:"permission",retriable:!1}:409===r?{category:"conflict",retriable:!1}:429===r?{category:"rate_limited",retriable:!0}:r&&r>=500?{category:"server",retriable:!0}:r&&r>=400?{category:"validation",retriable:!1}:"aborterror"===s||a.includes("timeout")||a.includes("timed out")?{category:"timeout",retriable:!0}:i.includes("oauth")||i.includes("provider")||a.includes("provider")?{category:"provider",retriable:!1}:"typeerror"===s||a.includes("network")||a.includes("failed to fetch")||a.includes("connection")?{category:"network",retriable:!0}:{category:"unknown",retriable:!0}}e.s(["beginFirstSessionAction",0,function({workspaceId:e,step:l,surface:y,abandonOnPageHide:h=!0}){if(!(0,r.hasAnalyticsConsent)()||!0!==(0,i.getAiOutcomeSessionTiming)().isFirstSession)return null;let m=null==e||""===e?void 0:String(e),g=d({workspaceId:m,step:l,surface:y}),w=c(a),k=w[g];k&&(0,t.trackEvent)("first_session_action_abandoned",{...p(k),cancel_reason:"replaced"});let b=c(n),_=k?Math.min(k.retryCount+1,3):Math.min(Math.max(b[g]??0,0),3),v={attemptId:(0,s.createAnalyticsEventId)("first_session_action"),workspaceId:m,step:l,surface:y,retryCount:_,startedAt:Date.now(),abandonOnPageHide:h};return w[g]=v,u(a,w),o||(window.addEventListener("pagehide",f),o=!0),(0,t.trackEvent)("first_session_action_attempted",{attempt_id:v.attemptId,...v.workspaceId?{workspace_id:v.workspaceId}:{},step:l,surface:y,retry_count:_}),v.attemptId},"cancelFirstSessionAction",0,function(e,r){if(!e)return!1;let i=y(e);return!!i&&(h(i,null),(0,t.trackEvent)("first_session_action_cancelled",{...p(i),cancel_reason:r}),!0)},"classifyFirstSessionFailure",0,m,"failFirstSessionAction",0,function(e,r,i={}){if(!e)return!1;let s=y(e);if(!s)return!1;let a=i.category?{category:i.category,retriable:i.retriable??["rate_limited","network","timeout","server","unknown"].includes(i.category)}:m(r);return h(s,s.retryCount+1),(0,t.trackEvent)("first_session_action_failed",{...p(s),failure_category:a.category,retriable:a.retriable}),!0},"succeedFirstSessionAction",0,function(e){if(!e)return!1;let r=y(e);return!!r&&(h(r,null),(0,t.trackEvent)("first_session_action_succeeded",p(r)),!0)}])},143732,e=>{"use strict";e.s(["getVisibility",0,function(e){return"user"===e?"private":"workspace"},"resolveContentParentForCreate",0,function({workspaceId:e,folderId:t,visibility:r,ownerMemberId:i}){if(null!=t)return{parent_type:"folder",parent_id:String(t)};if("private"===r){if(!i)throw Error("Could not resolve your workspace membership");return{parent_type:"user",parent_id:i}}return{parent_type:"workspace",parent_id:e}}])},898665,210321,e=>{"use strict";var t=e.i(982472),r=e.i(385296),i=e.i(610995),s=e.i(589522),a=e.i(190985),n=class extends s.Subscribable{#e;#a=void 0;#n;#o;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#l()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,a.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,a.hashKey)(t.mutationKey)!==(0,a.hashKey)(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#l(),this.#c(e)}getCurrentResult(){return this.#a}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#l(),this.#c()}mutate(e,t){return this.#o=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#l(){let e=this.#n?.state??(0,r.getDefaultState)();this.#a={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#c(e){i.notifyManager.batch(()=>{if(this.#o&&this.hasListeners()){let t=this.#a.variables,r=this.#a.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#o.onSuccess?.(e.data,t,r,i)}catch(e){Promise.reject(e)}try{this.#o.onSettled?.(e.data,null,t,r,i)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#o.onError?.(e.error,t,r,i)}catch(e){Promise.reject(e)}try{this.#o.onSettled?.(void 0,e.error,t,r,i)}catch(e){Promise.reject(e)}}}
2this.listeners.forEach(e=>{e(this.#a)})})}},o=e.i(580107);function l(e,r){let s=(0,o.useQueryClient)(r),[l]=t.useState(()=>new n(s,e));t.useEffect(()=>{l.setOptions(e)},[l,e]);let c=t.useSyncExternalStore(t.useCallback(e=>l.subscribe(i.notifyManager.batchCalls(e)),[l]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),u=t.useCallback((e,t)=>{l.mutate(e,t).catch(a.noop)},[l]);if(c.error&&(0,a.shouldThrowError)(l.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:u,mutateAsync:c.mutate}}e.s(["useMutation",0,l],898665);var c=e.i(37700);e.i(66818);var u=e.i(534167),d=e.i(498922),p=e.i(599177);e.i(478539);var y=e.i(495238),h=e.i(8551),f=e.i(979762);let m=(0,h.createQueryKeyFactory)("workspaces"),g=e=>["workspace_allowed_domains","list",e??"none"];class w extends Error{status;constructor(e,t){super(e),this.status=t,this.name="WorkspaceLookupError"}}async function k(){let e=await fetch("/api/v1/my-workspaces",{credentials:"include",cache:"no-store",headers:{Accept:"application/json"},signal:AbortSignal.timeout(15e3)});if(!e.ok){let t="Workspace service is unavailable. Could not verify workspace memberships.";try{let r=await e.json();"string"==typeof r.error&&r.error.trim()&&(t=r.error)}catch{}throw new w(t,e.status)}return[...(await e.json()).data??[]].map(e=>({id:e.id,name:e.name,slug:e.slug,role:e.role,settings:e.settings??{},created_at:e.created_at,updated_at:e.updated_at??e.created_at,membership_status:e.membership_status??"member",invite_code:e.invite_code,invite_role:e.invite_role,invited_at:e.invited_at})).sort((e,t)=>e.name.localeCompare(t.name))}function b(e){if(!Array.isArray(e))return[];let t=new Set,r=[];for(let i of e){let e="string"==typeof i?i:i&&"object"==typeof i&&"domain"in i?i.domain:null;if("string"!=typeof e)continue;let s=e.toLowerCase().trim();!s||t.has(s)||(t.add(s),r.push(s))}return r}function _(){let{user:e,isLoading:t}=(0,y.useAuth)();return(0,c.useQuery)({queryKey:[...m.all,e?.id??"guest"],queryFn:async()=>e?k():[],retry:!1,enabled:!t})}async function v(){let e=(0,p.makeBootstrapCoworkClient)();try{return((await e.discovery.discoverWorkspaces()).data??[]).map(e=>({workspace_id:e.id,workspace_name:e.name,workspace_icon:null}))}catch(e){if(e instanceof u.CoworkApiError&&401===e.status)return[];throw e}}async function I(e){let t=String(e),r=(0,p.makeBootstrapCoworkClient)(),i=await r.discovery.joinWorkspace({workspaceId:t}),s=i.data?.workspace_id??t;return(0,f.setStoredLastWorkspaceId)(s),new d.PreferencesClient().setLastWorkspaceId({workspaceId:s}).catch(()=>void 0),{workspace_id:s,role_id:0}}e.s(["addWorkspaceToWorkspaceListCache",0,function(e,t){return void 0===e?[t]:!Array.isArray(e)||e.some(e=>e.id===t.id)?e:[...e,t].sort((e,t)=>e.name.localeCompare(t.name))},"joinWorkspaceViaRoute",0,I,"useAddAllowedDomain",0,function(){let e=(0,o.useQueryClient)();return l({mutationFn:async({workspaceId:e,domain:t})=>{let r=String(e),i=t.toLowerCase().trim(),s=(0,p.makeCoworkClient)(r);if(((await s.discovery.listTrustedDomains({workspaceId:r})).data??[]).map(e=>e.domain).includes(i))throw Error("Domain already added");return await s.discovery.addTrustedDomain({workspaceId:r,domain:i}),{workspaceId:r,domain:i}},onSuccess:({workspaceId:t})=>{let r=String(t);e.invalidateQueries({queryKey:g(r)}),e.invalidateQueries({queryKey:["workspaces","detail",r,"allowed_domains"]}),e.invalidateQueries({queryKey:["workspaces","detail",r]})}})},"useAllowedEmailDomains",0,function(e){let t=e?String(e):null;return(0,c.useQuery)({queryKey:g(t),queryFn:async()=>{if(!t)return[];try{let e=(0,p.makeCoworkClient)(t),r=await e.discovery.listTrustedDomains({workspaceId:t});return b(r.data)}catch(e){if(e instanceof u.CoworkApiError&&403===e.status)return[];throw e}},enabled:!!t,select:b})},"useCurrentUserRole",0,function(e){var t;let r=e??null,{data:i=[],isLoading:s,error:a}=_(),n=i.find(e=>e.id===r&&(e.membership_status??"member")==="member");return{data:r&&(t=n?.role)?{role:t,roleId:null,roleName:t,rolePosition:null,isOwner:"owner"===t,isAdmin:"owner"===t||"admin"===t,canEditWorkspace:"owner"===t||"admin"===t}:null,isLoading:s,error:a}},"useDeleteWorkspace",0,function(){let e=(0,o.useQueryClient)();return l({mutationFn:async e=>{let t=(0,p.makeCoworkClient)(e);return await t.workspaces.delete({workspaceId:e}),e},onSuccess:t=>{e.removeQueries({queryKey:m.detail(t)}
2),e.invalidateQueries({queryKey:m.all})}})},"useJoinViaAllowedDomain",0,function(){let e=(0,o.useQueryClient)();return l({mutationFn:async({workspaceId:e})=>I(e),onSuccess:t=>{e.invalidateQueries({queryKey:m.all}),e.invalidateQueries({queryKey:["workspace_members","list",t.workspace_id]}),e.invalidateQueries({queryKey:["joinable_workspaces"]})}})},"useJoinableWorkspaces",0,function(e={}){let{user:t,isLoading:r}=(0,y.useAuth)(),{enabled:i=!0}=e;return(0,c.useQuery)({queryKey:["joinable_workspaces",t?.id??"guest"],queryFn:async()=>{if(!t)return[];try{return await v()}catch(e){if(e instanceof Error&&"Unauthorized"===e.message)return[];throw e}},enabled:!r&&i})},"useRemoveAllowedDomain",0,function(){let e=(0,o.useQueryClient)();return l({mutationFn:async({workspaceId:e,domain:t})=>{let r=String(e),i=t.toLowerCase().trim(),s=(0,p.makeCoworkClient)(r);return await s.discovery.removeTrustedDomain({workspaceId:r,domain:i}),{workspaceId:r,domain:i}},onSuccess:({workspaceId:t})=>{let r=String(t);e.invalidateQueries({queryKey:g(r)}),e.invalidateQueries({queryKey:["workspaces","detail",r,"allowed_domains"]}),e.invalidateQueries({queryKey:["workspaces","detail",r]})}})},"useUpdateWorkspace",0,function(){let e=(0,o.useQueryClient)();return l({mutationFn:async e=>{let t=(0,p.makeCoworkClient)(e.id);return(await t.workspaces.update({workspaceId:e.id,name:e.data.name,settings:e.data.settings})).data},onSuccess:t=>{e.invalidateQueries({queryKey:["workspaces","detail",t.id]}),e.invalidateQueries({queryKey:m.all})}})},"useWorkspaces",0,_,"workspaceKeys",0,m],210321)},142533,922324,e=>{"use strict";var t=e.i(599177);let r=null;function i(){return r}async function s(e){var r;let s,a,n=(r=e.workspaceId,(s=i())||("string"==typeof r&&r.length>0?r:null));if(!n)return;let o=(0,t.makeCoworkClient)(n);await o.analytics.trackEvent({workspaceId:n,event:(a={...e.metadata??{}},{category:e.category,action:e.action,entityType:e.entityType??null,entityId:void 0===e.entityId||null===e.entityId?null:String(e.entityId),metadata:a})})}async function a(e){try{await s(e)}catch(t){let e;e=t instanceof Error?`${t.name}: ${t.message}`:"string"==typeof t?t:"unknown error",console.debug(`[Event Tracking] Dropped optional analytics event: ${e}`)}}e.s(["getActiveWorkspacePublicId",0,i,"setActiveWorkspacePublicId",0,function(e){r=e}],922324),e.s(["trackEventClient",0,a],142533)},328188,669780,485407,643436,938603,602668,272893,506715,434659,355129,230605,583818,798574,187177,e=>{"use strict";e.s(["createDocumentViaRoute",()=>rK,"documentKeys",()=>rP,"fetchDocumentRecordViaRoute",()=>rM,"updateDocumentViaRoute",()=>rO,"useCreateDocument",()=>rB,"useDeleteDocument",()=>r$,"useDocument",()=>rR,"useDocuments",()=>rQ,"useDocumentsWithFolders",()=>rW,"useUpdateDocument",()=>rj],328188);var t=e.i(982472),r=e.i(898665),i=e.i(623128),s=e.i(599177),a=e.i(8551),n=e.i(221745),o=e.i(593463),l=e.i(480723),c=e.i(723103);function u(e){let t=(0,c.useWorkspaceCollections)(),r=(0,c.useCollectionsFor)(e);return e?r:t}function d(e){return u(e)?.documents??null}function p(e){return u(e)?.whiteboards??null}function y(e){return u(e)?.pdfs??null}function h(e){return u(e)?.databases??null}function f(e){return u(e)?.folders??null}function m(e){return u(e)?.notifications??null}function g(e){return u(e)?.conversations??null}e.s(["useConversationsCollection",()=>g,"useDatabasesCollection",()=>h,"useDocumentsCollection",()=>d,"useFoldersCollection",()=>f,"useNotificationsCollection",()=>m,"usePdfsCollection",()=>y,"useWhiteboardsCollection",()=>p],669780);let w=Object.freeze([]);function k(){return w}function b(e){let r=t.useRef(k()),i=t.useCallback(t=>{if(!e)return()=>void 0;e.startSyncImmediate();let i=e.subscribeChanges(()=>{r.current=e.toArray,t()});return r.current=e.toArray,t(),()=>i.unsubscribe()},[e]),s=t.useCallback(()=>e?r.current:k(),[e]),a=t.useSyncExternalStore(i,s,k),n=e?.status,o=!!e&&"ready"!==n&&"error"!==n,l=t.useCallback(()=>{e?.utils.refetch()},[e]);return t.useMemo(()=>{let t;return{data:a,isPending:o,isLoading:o,isError:"error"===n,error:(t=e?.utils.lastError)?t instanceof Error?t:Error(String(t)):null,refetch:l}},[e,o,l,a,n])}function _(e,r){let i=b(e),s=t.useMemo(()=>r?i.data.find(e=>e.id===r)??null:null,[r,i.data]);return{...i,data:s}}function v(){let e="u">typeof globalThis?globalThis.crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();if(e&&"function"==typeof e.getRandomValues){let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[];for(let e=0;e<16;e++)r.push(t[e].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}throw Error("No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.")}e.s(["useCollectionRow",0,_,"useCollectionRows",0,b],485407);
2class I extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class S extends I{constructor(e,t,r){const i=`${"insert"===e?"Insert":"Update"} validation failed: ${t.map(e=>` 3- ${e.message} - path: ${e.path}`).join("")}`;super(r||i),this.name="SchemaValidationError",this.type=e,this.issues=t}}class C extends I{constructor(e){super(e),this.name="CollectionConfigurationError"}}class x extends C{constructor(){super("Collection requires a config")}}class F extends C{constructor(){super("Collection requires a sync config")}}class T extends C{constructor(){super("Schema must implement the standard-schema interface")}}class A extends C{constructor(){super("Schema validation must be synchronous")}}class E extends I{constructor(e){super(e),this.name="CollectionStateError"}}class D extends E{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class M extends E{constructor(e,t,r){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${r}"`)}}class K extends E{constructor(){super("Collection is in error state")}}class q extends E{constructor(){super("Active subscribers count is negative - this should never happen")}}class O extends I{constructor(e){super(e),this.name="CollectionOperationError"}}class P extends O{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class Q extends O{constructor(e,t){super(`getKey returned an invalid key type. Expected string or number, but got ${null===e?"null":typeof e}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class R extends O{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class W extends O{constructor(e,t,r){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;r?.hasCustomGetKey&&r.hasDistinct?super(`${i}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):r?.hasCustomGetKey&&r.hasJoins?super(`${i}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(i)}}class B extends O{constructor(){super("The first argument to update is missing")}}class j extends O{constructor(){super("No keys were passed to update")}}class $ extends O{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class N extends O{constructor(e,t){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${t}". Please delete the old item and create a new one if a key change is necessary.`)}}class L extends O{constructor(){super("No keys were passed to delete")}}class U extends O{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class z extends I{constructor(e){super(e),this.name="MissingHandlerError"}}class V extends z{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class G extends z{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class J extends z{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class H extends I{constructor(e){super(e),this.name="TransactionError"}}class Y extends H{constructor(){super("mutationFn is required when creating a transaction")}}class Z extends H{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class X extends H{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class ee extends H{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class et extends H{constructor(){super("No pending sync transaction to write to")}}class er extends H{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class ei extends H{constructor(){super("No pending sync transaction to commit")}}class es extends H{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class ea extends I{constructor(e){super(e),this.name="QueryCompilationError"}}class en extends ea{constructor(e){super(`Unknown expression type: ${e}`)}}class eo extends ea{constructor(){super("Reference path cannot be empty")}}class el extends ea{constructor(e){super(`Unknown function: ${e}`)}}class ec extends I{constructor(e,t){const r=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${r}`),this.name="SyncCleanupError"}}var eu=e.i(198475);function ed(e,t){return function e(t,r,i){if(t===r)return!0;
3if(null==t||null==r||typeof t!=typeof r)return!1;if(t instanceof Date)return r instanceof Date&&t.getTime()===r.getTime();if(r instanceof Date)return!1;if(t instanceof RegExp)return r instanceof RegExp&&t.source===r.source&&t.flags===r.flags;if(r instanceof RegExp)return!1;if(t instanceof Map){if(!(r instanceof Map)||t.size!==r.size)return!1;if(i.has(t))return i.get(t)===r;i.set(t,r);let s=Array.from(t.entries()).every(([t,s])=>r.has(t)&&e(s,r.get(t),i));return i.delete(t),s}if(r instanceof Map)return!1;if(t instanceof Set){if(!(r instanceof Set)||t.size!==r.size)return!1;if(i.has(t))return i.get(t)===r;i.set(t,r);let e=Array.from(t),s=Array.from(r);if(e.every(e=>"object"!=typeof e))return i.delete(t),e.every(e=>r.has(e));let a=e.length===s.length;return i.delete(t),a}if(r instanceof Set)return!1;if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)&&!(t instanceof DataView)&&!(r instanceof DataView)){if(t.length!==r.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==r[e])return!1;return!0}if(ArrayBuffer.isView(r)&&!(r instanceof DataView)&&!ArrayBuffer.isView(t))return!1;if(ey(t)&&ey(r))return t[Symbol.toStringTag]===r[Symbol.toStringTag]&&("function"==typeof t.equals?t.equals(r):t.toString()===r.toString());if(ey(r))return!1;if(Array.isArray(t)){if(!Array.isArray(r)||t.length!==r.length)return!1;if(i.has(t))return i.get(t)===r;i.set(t,r);let s=t.every((t,s)=>e(t,r[s],i));return i.delete(t),s}if(Array.isArray(r))return!1;if("object"==typeof t){if(i.has(t))return i.get(t)===r;i.set(t,r);let s=Object.keys(t),a=Object.keys(r);if(s.length!==a.length)return i.delete(t),!1;let n=s.every(s=>s in r&&e(t[s],r[s],i));return i.delete(t),n}return!1}(e,t,new Map)}let ep=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function ey(e){if(null==e||"object"!=typeof e)return!1;let t=e[Symbol.toStringTag];return"string"==typeof t&&ep.has(t)}let eh={direction:"asc",nulls:"first",stringSort:"locale"},ef=new WeakMap,em=1;function eg(e){if(ef.has(e))return ef.get(e);let t=em++;return ef.set(e,t),t}function ew(e){return"number"==typeof e&&Number.isNaN(e)||e instanceof Date&&Number.isNaN(e.getTime())}let ek=(e,t,r)=>{let{nulls:i}=r;if(null==e&&null==t)return 0;if(null==e)return"first"===i?-1:1;if(null==t)return"first"===i?1:-1;let s=ew(e),a=ew(t);if(s&&a)return 0;if(s)return 1;if(a)return -1;if("string"==typeof e&&"string"==typeof t&&"locale"===r.stringSort)return e.localeCompare(t,r.locale,r.localeOptions);if(Array.isArray(e)&&Array.isArray(t)){for(let i=0;i<Math.min(e.length,t.length);i++){let s=ek(e[i],t[i],r);if(0!==s)return s}return e.length-t.length}if(e instanceof Date&&t instanceof Date)return e.getTime()-t.getTime();if(ey(e)&&ey(t)){let r=e.toString(),i=t.toString();return r<i?-1:+(r>i)}let n="object"==typeof e,o="object"==typeof t;if(n||o){if(n&&o)return eg(e)-eg(t);if(n)return 1;if(o)return -1}return e<t?-1:+(e>t)};function eb(e){return(t,r)=>{if("asc"===e.direction)return ek(t,r,e);return ek(r,t,{...e,nulls:"first"===e.nulls?"last":"first"})}}function e_(e){return"object"!=typeof e||null===e?e:e instanceof Date?e.getTime():ey(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(void 0!==eu.Buffer&&e instanceof eu.Buffer||e instanceof Uint8Array)&&e.byteLength<=128?`__u8__${Array.from(e).join(",")}`:e}function ev(e){return null==e}function eI(e,t){return ew(e)||ew(t)?ew(e)&&ew(t):function(e,t){if(e===t)return!0;let r=void 0!==eu.Buffer&&e instanceof eu.Buffer||e instanceof Uint8Array,i=void 0!==eu.Buffer&&t instanceof eu.Buffer||t instanceof Uint8Array;
3if(r&&i){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}return!1}(e,t)}function eS(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}eb({direction:"asc",nulls:"first",stringSort:"locale"});function eC(e,t){switch(e.type){case"val":{let t=e.value;return()=>t}case"ref":let r;return t?(r=e.path,e=>{let t=e;for(let e of r){if(null==t)break;t=t[e]}return t}):function(e){let[t,...r]=e.path;if(!t)throw new eo;if("$selected"===t)if(0===r.length)return e=>e.$selected;else{if(1!==r.length)return e=>{let t=e.$selected;if(void 0===t)return;let i=t;for(let e of r){if(null==i)break;i=i[e]}return i};let e=r[0];return t=>{let r=t.$selected;return r?.[e]}}if(0===r.length)return e=>e[t];if(1!==r.length)return e=>{let i=e[t];if(void 0===i)return;let s=i;for(let e of r){if(null==s)break;s=s[e]}return s};{let e=r[0];return r=>{let i=r[t];return i?.[e]}}}(e);case"func":return function(e,t){let r=e.args.map(e=>eC(e,t));switch(e.name){case"eq":{let e=r[0],t=r[1];return r=>{let i=e_(e(r)),s=e_(t(r));return ev(i)||ev(s)?null:eI(i,s)}}case"gt":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ew(i)||ew(s)?ew(i)&&!ew(s):i>s}}case"gte":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ew(i)||ew(s)?ew(i):i>=s}}case"lt":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ew(i)||ew(s)?ew(s)&&!ew(i):i<s}}case"lte":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ew(i)||ew(s)?ew(s):i<=s}}case"and":return e=>{let t=!1;for(let i of r){let r=i(e);if(!1===r)return!1;ev(r)&&(t=!0)}return!t||null};case"or":return e=>{let t=!1;for(let i of r){let r=i(e);if(!0===r)return!0;ev(r)&&(t=!0)}return!!t&&null};case"not":{let e=r[0];return t=>{let r=e(t);return ev(r)?null:!r}}case"in":{let e=r[0],t=r[1];return r=>{let i=e_(e(r)),s=t(r);return ev(i)?null:!!Array.isArray(s)&&s.some(e=>eI(e_(e),i))}}case"like":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ex(i,s,!1)}}case"ilike":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r);return ev(i)||ev(s)?null:ex(i,s,!0)}}case"upper":{let e=r[0];return t=>{let r=e(t);return"string"==typeof r?r.toUpperCase():r}}case"lower":{let e=r[0];return t=>{let r=e(t);return"string"==typeof r?r.toLowerCase():r}}case"length":{let e=r[0];return t=>{let r=e(t);return"string"==typeof r||Array.isArray(r)?r.length:0}}case"concat":return e=>r.map(t=>{let r=t(e);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return e=>{for(let t of r){let r=t(e);if(null!=r)return r}return null};case"caseWhen":{let e=r.length%2==1,t=Math.floor(r.length/2);if(r.length<2)throw Error("caseWhen() requires at least two arguments");return i=>{for(let e=0;e<t;e++){var s;if(null!=(s=(0,r[2*e])(i))&&!1!==s&&(!0===s||("number"==typeof s?0!==s&&!Number.isNaN(s):"bigint"==typeof s?0n!==s:!!s)))return(0,r[2*e+1])(i)}return e?r[r.length-1](i):null}}case"add":{let e=r[0],t=r[1];return r=>(e(r)??0)+(t(r)??0)}case"subtract":{let e=r[0],t=r[1];return r=>(e(r)??0)-(t(r)??0)}case"multiply":{let e=r[0],t=r[1];return r=>(e(r)??0)*(t(r)??0)}case"divide":{let e=r[0],t=r[1];return r=>{let i=e(r),s=t(r)??0;return 0!==s?(i??0)/s:null}}case"date":{let e=r[0];return t=>{let r=eS(e(t));return r?r.toISOString().slice(0,10):null}}case"datetime":{let e=r[0];return t=>{let r=eS(e(t));return r?r.toISOString():null}}case"strftime":{let e=r[0],t=r[1];return r=>{let i=e(r);if("string"!=typeof i)return null;let s=eS(t(r));return s?"%Y-%m-%d"===i?s.toISOString().slice(0,10):s.toISOString():null}}case"isUndefined":{let e=r[0];return t=>void 0===e(t)}case"isNull":{let e=r[0];return t=>null===e(t)}default:throw new el(e.name)}}(e,t);default:throw new en(e.type)}}function ex(e,t,r){if("string"!=typeof e||"string"!=typeof t)return!1;let i=r?e.toLowerCase():e,s=(r?t.toLowerCase():t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s=(s=s.replace(/%/g,".*")).replace(/_/g,"."),RegExp(`^${s}$`,"s").test(i)}class eF{constructor(e){this.originalIndex=e}lookup(e,t){return this.originalIndex.lookup("gt"===e?"lt":"gte"===e?"lte":"lt"===e?"gt":"lte"===e?"gte":e,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,t,r){return this.originalIndex.takeReversed(e,t,r)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}takeReversed(e,t,r){return this.originalIndex.take(e,t,r)}takeReversedFromEnd(e,t){return this.originalIndex.takeFromStart(e,t)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}matchesField(e){return this.originalIndex.matchesField(e)}matchesCompareOptions(e){return this.originalIndex.matchesCompareOptions(e)}matchesDirection(e){return this.originalIndex.matchesDirection(e)}getStats(){return this.originalIndex.getStats()}add(e,t){this.originalIndex.add(e,t)}remove(e,t){this.originalIndex.remove(e,t)}update(e,t,r){this.originalIndex.update(e,t,r)}build(e){this.originalIndex.build(e)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(e){return this.originalIndex.equalityLookup(e)}inArrayLookup(e){return this.originalIndex.inArrayLookup(e)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}}function eT(e,t,r,i,s){return{...e,$synced:e.$synced??i(),$origin:e.$origin??s(),$key:e.$key??t,$collectionId:e.$collectionId??r}}let eA=["$synced","$origin","$key","$collectionId"];function eE(e){return e.some(e=>eA.includes(e))}function eD(e,t,r){if(eE(t))return;let i=r??{...eh,...e.compareOptions};for(let r of e.indexes.values())if(r.matchesField(t)&&r.matchesCompareOptions(i)){if(!r.matchesDirection(i.direction))return new eF(r);return r}}function eM(e,t,r){return!function(e,t){switch(typeof e){case"number":case"bigint":case"boolean":default:return!1;case"string":return"locale"===({...eh,...t.compareOptions}
3).stringSort;case"object":if(null===e)return!1;return!(e instanceof Date)}}(e,r)&&t.supportsRangeOptimization}var eK=e.i(680433);function eq(e){return"eager"===e.config.autoIndex}function eO(e,t,r,i,s){if(eE(t)||!eq(r))return;let a=i??{...eh,...r.compareOptions};if(!Array.from(r.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a)))try{r.createIndex(e=>{let r=e;for(let e of t)r=r[e];return r},{name:`auto:${t.join(".")}`,options:s?{compareFn:s,compareOptions:a}:{}})}catch(e){console.warn(`${r.id?`[${r.id}] `:""}Failed to create auto-index for field path "${t.join(".")}":`,e)}}class eP extends Map{constructor(e,t){super(t),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,t){let r=t(this.get(e));return this.set(e,r),r}}function eQ(e,t){if(t.length<=3e4)e.push(...t);else for(let r=0;r<t.length;r+=3e4){let i=t.slice(r,r+3e4);e.push(...i)}}let eR=new class{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if("object"!=typeof e||null===e){let t=String(e),r=0;for(let e=0;e<t.length;e++)r=(r<<5)-r+t.charCodeAt(e),r&=r;return r}return this.objectIds.has(e)||this.objectIds.set(e,this.nextId++),this.objectIds.get(e)}getStringId(e){return null===e?"null":void 0===e?"undefined":"object"!=typeof e?`str_${String(e)}`:`obj_${this.getId(e)}`}};function eW(e,t){return typeof e==typeof t?e<t?-1:+(e>t):"string"==typeof e?-1:1}let eB=eU(),ej=eU(),e$=eU(),eN=eU(),eL=eU();function eU(){return Math.random()*(0x80000000-1)>>>0}let ez=new ArrayBuffer(8),eV=new DataView(ez),eG=new Uint8Array(ez);class eJ{constructor(){this.hash=eB,this.length=0,this.carry=0,this.carryBytes=0}_mix(e){e=Math.imul(e=(e=Math.imul(e,0xcc9e2d51))<<15|e>>>17,0x1b873593),this.hash^=e,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+0xe6546b64}writeByte(e){this.carry|=(255&e)<<8*this.carryBytes,this.carryBytes++,this.length++,4===this.carryBytes&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}update(e){switch(typeof e){case"symbol":{this.update(eL);let t=e.description;if(!t)return;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);this.writeByte(255&r),this.writeByte(r>>>8&255)}return}case"string":this.update(ej);for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);this.writeByte(255&r),this.writeByte(r>>>8&255)}return;case"number":eV.setFloat64(0,e,!0),this.writeByte(eG[0]),this.writeByte(eG[1]),this.writeByte(eG[2]),this.writeByte(eG[3]),this.writeByte(eG[4]),this.writeByte(eG[5]),this.writeByte(eG[6]),this.writeByte(eG[7]);return;case"bigint":{let t=e;for(t<0n?(t=-t,this.update(eN)):this.update(e$);t>0n;)this.writeByte(Number(255n&t)),t>>=8n;0n===e&&this.writeByte(0);return}default:throw TypeError(`Unsupported input type: ${typeof e}`)}}digest(){if(this.carryBytes>0){let e=this.carry>>>0;e=Math.imul(e=(e=Math.imul(e,0xcc9e2d51))<<15|e>>>17,0x1b873593),this.hash^=e}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,0x85ebca6b),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,0xc2b2ae35),this.hash^=this.hash>>>16,this.hash>>>0}}let eH=eU(),eY=eU(),eZ=eU(),eX=eU(),e0=eU(),e1=eU(),e2=eU(),e5=eU(),e3=eU(),e8=eU(),e7=eU(),e4=eU(),e6=eU(),e9=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]),te=new WeakMap;function tt(e){let t=new eJ;return function e(t,r){if(null===r)return void t.update(eZ);switch(typeof r){case"undefined":t.update(eX);return;case"boolean":t.update(r?eH:eY);return;case"number":t.update(isNaN(r)?NaN:0===r?0:r);return;case"bigint":case"string":case"symbol":t.update(r);return;case"object":var i;let s;t.update((i=r,void 0===(s=te.get(i))&&(s=function(t){var r,i;let s,a=te.get(t);if(void 0!==a)return a;if(t instanceof Date){let e;r=t,(e=new eJ).update(e2),e.update(r.getTime()),s=e.digest()}else if(void 0!==eu.Buffer&&t instanceof eu.Buffer||t instanceof Uint8Array)if(!(t.byteLength<=128))return ti(t);else s=function(e){let t=new eJ;t.update(e4),t.update(e.byteLength);for(let r=0;r<e.byteLength;r++)t.writeByte(e[r]);return t.digest()}(t);else{let r;if(t instanceof File)return ti(t);if("string"==typeof(r=t[Symbol.toStringTag])&&e9.has(r)){let e;i=t,(e=new eJ).update(e6),e.update(i[Symbol.toStringTag]),e.update(i.toString()),s=e.digest()}else{let r=t,i=e5;t instanceof Array&&(i=e3),t instanceof Map&&(i=e8,r=[...t.entries()]),t instanceof Set&&(i=e7,r=[...t.entries()]),s=function(t,r){let i=new eJ;i.update(r);let s=Object.keys(t);for(let r of(s.sort(ts),s))i.update(e0),i.update(r),e(i,t[r]);return i.digest()}
3(r,i)}}return te.set(t,s),s}(i)),s));return;case"function":t.update(ti(r));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof r} which is not supported`)}}(t,e),t.digest()}let tr=1;function ti(e){let t=te.get(e);return void 0===t&&(t=tr^e1,tr++,te.set(e,t)),t}function ts(e,t){return e.localeCompare(t)}class ta{#u;constructor(e=[]){this.#u=e}toString(e=!1){return`MultiSet(${JSON.stringify(this.#u,null,e?2:void 0)})`}toJSON(){return JSON.stringify(Array.from(this.getInner()))}static fromJSON(e){return new ta(JSON.parse(e))}map(e){return new ta(this.#u.map(([t,r])=>[e(t),r]))}filter(e){return new ta(this.#u.filter(([t,r])=>e(t)))}negate(){return new ta(this.#u.map(([e,t])=>[e,-t]))}concat(e){let t=[];return eQ(t,this.#u),eQ(t,e.getInner()),new ta(t)}consolidate(){if(this.#u.length>0){let e=this.#u[0]?.[0];if(Array.isArray(e)&&2===e.length)return this.#d()}return this.#p()}#d(){let e=new Map,t=new Map,r=e=>{if(2!==e.length)throw Error("Expected tuple of length 2");let[t,r]=e;return`${eR.getStringId(t)}|${eR.getStringId(r)}`};for(let[i,s]of this.#u){if(!Array.isArray(i)||2!==i.length)return this.#p();let[a,n]=i;if("string"!=typeof a&&"number"!=typeof a)return this.#p();let o=a+"|"+(Array.isArray(n)&&2===n.length?r(n):eR.getStringId(n));e.set(o,(e.get(o)||0)+s),t.has(o)||t.set(o,i)}let i=[];for(let[r,s]of e)0!==s&&i.push([t.get(r),s]);return new ta(i)}#p(){let e=new eP(()=>0),t=new Map,r=!1,i=!1,s=!1;for(let[e,t]of this.#u)if("string"==typeof e)r=!0;else if("number"==typeof e)i=!0;else{s=!0;break}let a=s||r&&i;for(let[r,i]of this.#u){let s=a?tt(r):r;a&&!t.has(s)&&t.set(s,r),e.update(s,e=>e+i)}let n=[];for(let[r,i]of e.entries())if(0!==i){let e=a?t.get(r):r;n.push([e,i])}return new ta(n)}extend(e){let t=e instanceof ta?e.getInner():e;eQ(this.#u,t)}add(e,t){0!==t&&this.#u.push([e,t])}getInner(){return this.#u}}let tn=Symbol("NO_PREFIX");class to extends Map{addValue(e,t){if(0===t)return 0===this.size;let r=tu(e),i=this.get(r);if(td(i)){let[s,a]=i;if(tu(s)!==r)throw Error("Mismatching prefixes, this should never happen");if(s===e||tt(s)===tt(e)){let i=a+t;0===i?this.delete(r):this.set(r,[e,i])}else{let a=new tl;a.set(tt(s),i),a.set(tt(e),[e,t]),this.set(r,a)}}else void 0===i?this.set(r,[e,t]):i.addValue(e,t)&&this.delete(r);return 0===this.size}}class tl extends Map{addValue(e,t){if(0===t)return 0===this.size;let r=tt(e),i=this.get(r);if(i){let[,s]=i,a=s+t;0===a?this.delete(r):this.set(r,[e,a])}else this.set(r,[e,t]);return 0===this.size}}class tc{#u;#y=new Map;constructor(){this.#u=new Map}static fromMultiSets(e){let t=new tc;for(let r of e)for(let[e,i]of r.getInner()){let[r,s]=e;t.addValue(r,[s,i])}return t}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return this.#u.size}has(e){return this.#u.has(e)}hasPresence(e){return 0!==(this.#y.get(e)||0)}getConsolidatedMultiplicity(e){return this.#y.get(e)||0}getPresenceKeys(){return this.#y.keys()}get(e){return[...this.getIterator(e)]}*getIterator(e){let t=this.#u.get(e);if(td(t))yield t;else if(void 0===t)return;else if(t instanceof tl)for(let e of t.values())yield e;else for(let e of t.values())if(td(e))yield e;else for(let t of e.values())yield t}*entries(){for(let e of this.#u.keys())for(let t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(let e of this.#u.keys())yield[e,this.getIterator(e)]}addValue(e,t){let[r,i]=t;if(0===i)return;let s=(this.#y.get(e)||0)+i;0===s?this.#y.delete(e):this.#y.set(e,s);let a=this.#u.get(e);if(void 0===a)return void this.#u.set(e,t);if(td(a))return void this.#h(e,a,r,i);if(a instanceof tl){let s=tu(r);if(s!==tn){let r=new to;r.set(tn,a),r.set(s,t),this.#u.set(e,r)}else a.addValue(r,i)&&this.#u.delete(e)}else a.addValue(r,i)&&this.#u.delete(e)}#h(e,t,r,i){let[s,a]=t;if(s===r){let t=a+i;0===t?this.#u.delete(e):this.#u.set(e,[r,t]);return}let n=tu(r),o=tu(s);if(o===n&&(s===r||tt(s)===tt(r))){let t=a+i;0===t?this.#u.delete(e):this.#u.set(e,[r,t]);return}if(o===tn&&n===tn){let a=new tl;a.set(tt(s),t),a.set(tt(r),[r,i]),this.#u.set(e,a)}else{let a=new to;if(o===n){let e=new tl;e.set(tt(s),t),e.set(tt(r),[r,i]),a.set(o,e)}else a.set(o,t),a.set(n,[r,i]);this.#u.set(e,a)}}append(e){for(let[t,r]of e.entries())this.addValue(t,r)}join(e){let t=[];if(this.size<=e.size)for(let[r,i]of this.entriesIterators()){if(!e.has(r))continue;let s=e.get(r);
3for(let[e,a]of i)for(let[i,n]of s)0!==a&&0!==n&&t.push([[r,[e,i]],a*n])}else for(let[r,i]of e.entriesIterators()){if(!this.has(r))continue;let e=this.get(r);for(let[s,a]of i)for(let[i,n]of e)0!==n&&0!==a&&t.push([[r,[i,s]],n*a])}return new ta(t)}}function tu(e){return Array.isArray(e)&&("string"==typeof e[0]||"number"==typeof e[0]||"bigint"==typeof e[0])?e[0]:tn}function td(e){return Array.isArray(e)}class tp{}class ty extends tp{constructor(e){super(),this.path=e,this.type="ref"}}class th extends tp{constructor(e){super(),this.value=e,this.type="val"}}class tf extends tp{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}let{sum:tm,count:tg,avg:tw,min:tk,max:tb}={sum:function(e=e=>e){return{preMap:t=>e(t),reduce:e=>{let t=0;for(let[r,i]of e)t+=r*i;return t}}},count:function(e=e=>e){return{preMap:t=>+(null!=e(t)),reduce:e=>{let t=0;for(let[r,i]of e)t+=r*i;return t}}},avg:function(e=e=>e){return{preMap:t=>({sum:e(t),count:0}),reduce:e=>{let t=0,r=0;for(let[i,s]of e)t+=i.sum*s,r+=s;return{sum:t,count:r}},postMap:e=>e.sum/e.count}},min:function(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[r,i]of e)(!t||r&&r<t)&&(t=r);return t}}},max:function(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[r,i]of e)(!t||r&&r>t)&&(t=r);return t}}},median:function(e=e=>e){return{preMap:t=>[e(t)],reduce:e=>{let t=[];for(let[r,i]of e)for(let e of r)for(let r=0;r<i;r++)t.push(e);return 0===t.length?[]:(t.sort((e,t)=>e-t),t)},postMap:e=>{if(0===e.length)return 0;let t=Math.floor(e.length/2);return e.length%2==0?(e[t-1]+e[t])/2:e[t]}}},mode:function(e=e=>e){return{preMap:t=>{let r=e(t),i=new Map;return i.set(r,1),i},reduce:e=>{let t=new Map;for(let[r,i]of e)for(let[e,s]of r.entries()){let r=t.get(e)||0;t.set(e,r+s*i)}return t},postMap:e=>{if(0===e.size)return 0;let t=0,r=0;for(let[i,s]of e.entries())s>r&&(r=s,t=i);return t}}}};function t_(e){let t=eC(e,!0);return e=>{try{var r;return r=t(e),!0===r}catch{return!1}}}function tv(e,t){if("ref"===t.type){let r=e;for(let e of t.path)r=r?.[e];return r}return"val"===t.type?t.value:eC(t,!0)(e)}class tI{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let r=0,i=this.sortedKeys.length;if(!this.comparator){for(;r<i;){let t=Math.floor((r+i)/2),s=eW(e,this.sortedKeys[t]);if(s<0)i=t;else{if(!(s>0))return t;r=t+1}}return r}for(;r<i;){let s=Math.floor((r+i)/2),a=this.sortedKeys[s],n=this.map.get(a),o=this.comparator(t,n);if(o<0)i=s;else if(o>0)r=s+1;else{let t=eW(e,a);if(t<0)i=s;else{if(!(t>0))return s;r=s+1}}}return r}set(e,t){if(this.map.has(e)){let t=this.map.get(e),r=this.indexOf(e,t);this.sortedKeys.splice(r,1)}let r=this.indexOf(e,t);return this.sortedKeys.splice(r,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){let t=this.map.get(e),r=this.indexOf(e,t);return this.sortedKeys.splice(r,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(let e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(let t of this.sortedKeys)e(this.map.get(t),t,this.map)}}let tS="__tanstack_db_direct";class tC{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let e=!1;for(let t of this.transactions.values())if("persisting"===t.state){e=!0;break}let{committedSyncedTransactions:t,uncommittedSyncedTransactions:r,hasTruncateSync:i,hasImmediateSync:s}=this.pendingSyncedTransactions.reduce((e,t)=>
3(t.committed?(e.committedSyncedTransactions.push(t),t.truncate&&(e.hasTruncateSync=!0),t.immediate&&(e.hasImmediateSync=!0)):e.uncommittedSyncedTransactions.push(t),e),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!e||i||s){let e,s;this.isCommittingSyncTransactions=!0;let a=i?t.find(e=>e.truncate)?.optimisticSnapshot:null,n=new Set;for(let e of t){for(let t of e.operations)n.add(t.key);for(let[t]of e.rowMetadataWrites)n.add(t)}let o=new Set(n);for(let e of this.pendingOptimisticDirectUpserts)o.add(e);for(let e of this.pendingOptimisticDirectDeletes)o.add(e);let l=this.snapshotRowOriginsForKeys(o),c=new Map(this.optimisticUpserts),u=new Set(this.optimisticDeletes),d=this.preSyncVisibleState;if(0===d.size)for(let e of(d=new Map,n)){let t=this.get(e);void 0!==t&&d.set(e,t)}let p=[],y=this.config.sync.rowUpdateMode||"partial",h=new Map;for(let e of this.transactions.values())if("completed"===e.state)for(let t of e.mutations)this.isThisCollection(t.collection)&&t.optimistic&&h.set(t.key,{type:t.type,value:t.modified});for(let r of t){if(r.truncate){for(let e of new Set([...this.syncedData.keys(),...a?.upserts.keys()||[]])){if(a?.deletes.has(e))continue;let t=a?.upserts.get(e)||this.syncedData.get(e);void 0!==t&&p.push({type:"delete",key:e,value:t})}for(let t of(e=new Set(this.pendingLocalChanges),s=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState(),n))d.delete(t);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(let t of r.operations){let r=t.key;this.syncedKeys.add(r);let i=this.isLocalOnly||this.pendingLocalChanges.has(r)||this.pendingLocalOrigins.has(r)||e?.has(r)===!0||s?.has(r)===!0?"local":"remote";switch(t.type){case"insert":this.syncedData.set(r,t.value),this.rowOrigins.set(r,i),this.pendingLocalChanges.delete(r),this.pendingLocalOrigins.delete(r),this.pendingOptimisticUpserts.delete(r),this.pendingOptimisticDeletes.delete(r),this.pendingOptimisticDirectUpserts.delete(r),this.pendingOptimisticDirectDeletes.delete(r);break;case"update":if("partial"===y){let e=Object.assign({},this.syncedData.get(r),t.value);this.syncedData.set(r,e)}else this.syncedData.set(r,t.value);this.rowOrigins.set(r,i),this.pendingLocalChanges.delete(r),this.pendingLocalOrigins.delete(r),this.pendingOptimisticUpserts.delete(r),this.pendingOptimisticDeletes.delete(r),this.pendingOptimisticDirectUpserts.delete(r),this.pendingOptimisticDirectDeletes.delete(r);break;case"delete":this.syncedData.delete(r),this.syncedMetadata.delete(r),this.rowOrigins.delete(r),this.pendingLocalChanges.delete(r),this.pendingLocalOrigins.delete(r),this.pendingOptimisticUpserts.delete(r),this.pendingOptimisticDeletes.delete(r),this.pendingOptimisticDirectUpserts.delete(r),this.pendingOptimisticDirectDeletes.delete(r)}}for(let[e,t]of r.rowMetadataWrites){if("delete"===t.type){this.syncedMetadata.delete(e);continue}this.syncedMetadata.set(e,t.value)}for(let[e,t]of r.collectionMetadataWrites){if("delete"===t.type){this.syncedCollectionMetadata.delete(e);continue}this.syncedCollectionMetadata.set(e,t.value)}}if(i){let e=new Set;for(let r of t)for(let t of r.operations)("insert"===t.type||"update"===t.type)&&e.add(t.key);let r=new Map(a.upserts),i=new Set(a.deletes);for(let[t,s]of r)if(!i.has(t))if(e.has(t)){let e=!1;for(let r=p.length-1;r>=0;r--){let i=p[r];if(i.key===t&&"insert"===i.type){i.value=s,e=!0;break}}e||p.push({type:"insert",key:t,value:s})}else p.push({type:"insert",key:t,value:s});if(p.length>0&&i.size>0){let e=[];for(let t of p)"insert"===t.type&&i.has(t.key)||e.push(t);p.length=0,p.push(...e)}"ready"!==this.lifecycle.status&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,i&&a){for(let[e,t]of a.upserts)this.optimisticUpserts.set(e,t);for(let e of a.deletes)this.optimisticDeletes.add(e)}for(let e of this.transactions.values())if(!["completed","failed"].includes(e.state)){for(let t of e.mutations)if(this.isThisCollection(t.collection)&&t.optimistic)switch(t.type){case"insert":case"update":this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case"delete":this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}}
3for(let e of this.pendingOptimisticDirectUpserts)if(!n.has(e)){if(n.add(e),!d.has(e)){let t=c.get(e);void 0!==t&&d.set(e,t)}this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e)}for(let e of this.pendingOptimisticDirectDeletes)n.has(e)||n.add(e),this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);for(let e of(this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),n)){let t=d.get(e),r=this.get(e),i=this.getVirtualPropsSnapshotForState(e,{rowOrigins:l,optimisticUpserts:c,optimisticDeletes:u,completedOptimisticKeys:h}),s=this.getVirtualPropsSnapshotForState(e),a=i.$synced!==s.$synced||i.$origin!==s.$origin,n=void 0!==t?eT(t,e,this.collection.id,()=>i.$synced,()=>i.$origin):void 0,o=h.get(e),y=!1;o&&("delete"===o.type&&void 0!==t&&void 0===r&&ed(o.value,t)?y=!0:void 0!==r&&ed(o.value,r)&&(y=!0));let f=a&&void 0!==t&&void 0!==r&&ed(t,r);if(!y||f)if(void 0===t&&void 0!==r){let t=h.get(e);if(t){let s=eT(t.value,e,this.collection.id,()=>i.$synced,()=>i.$origin);p.push({type:"update",key:e,value:r,previousValue:s})}else p.push({type:"insert",key:e,value:r})}else void 0!==t&&void 0===r?p.push({type:"delete",key:e,value:n??t}):void 0!==t&&void 0!==r&&(!ed(t,r)||f)&&p.push({type:"update",key:e,value:r,previousValue:n??t})}this.size=this.calculateSize(),p.length>0&&this.indexes.updateIndexes(p),this.changes.emitEvents(p,!0),this.pendingSyncedTransactions=r,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=e,this.transactions=new tI((e,t)=>e.compareCreatedAt(t)),this.syncedData=new tI(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return!!this.isLocalOnly||!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?"local":this.rowOrigins.get(e)??"remote"}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:"local"});let r=t?.optimisticUpserts??this.optimisticUpserts,i=t?.optimisticDeletes??this.optimisticDeletes,s=r.has(e)||i.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!s,$origin:s?"local":(t?.rowOrigins??this.rowOrigins).get(e)??"remote"})}snapshotRowOriginsForKeys(e){let t=new Map;for(let r of e){let e=this.rowOrigins.get(r);void 0!==e&&t.set(r,e)}return t}enrichWithVirtualPropsSnapshot(e,t){let r=e.$synced??t.$synced,i=e.$origin??t.$origin,s=e.$key??t.$key,a=e.$collectionId??t.$collectionId,n=this.virtualPropsCache.get(e);if(n&&n.synced===r&&n.origin===i&&n.key===s&&n.collectionId===a)return n.enriched;let o={...e,$synced:r,$origin:i,$key:s,$collectionId:a};return this.virtualPropsCache.set(e,{synced:r,origin:i,key:s,collectionId:a,enriched:o}),o}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){let{__virtualProps:t}=e,r=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),i=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:r,previousValue:i,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(void 0!==t)return this.enrichWithVirtualProps(t,e)}get(e){let{optimisticDeletes:t,optimisticUpserts:r,syncedData:i}=this;if(!t.has(e))return r.has(e)?r.get(e):i.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:r,syncedData:i}=this;return!t.has(e)&&(!!r.has(e)||i.has(e))}*keys(){let{syncedData:e,optimisticDeletes:t,optimisticUpserts:r}=this;for(let r of e.keys())t.has(r)||(yield r);for(let i of r.keys())e.has(i)||t.has(i)||(yield i)}*values(){for(let e of this.keys()){let t=this.get(e);void 0!==t&&(yield t)}}*entries(){for(let e of this.keys()){let t=this.get(e);void 0!==t&&(yield[e,t])}}*[Symbol.iterator](){for(let[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(let[r,i]of this.entries())e(i,r,t++)}map(e){let t=[],r=0;for(let[i,s]of this.entries())t.push(e(s,i,r++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),r=new Set(this.optimisticDeletes),i=this.rowOrigins;for(let e of this.transactions.values()){let t=!0===e.metadata[tS];if("completed"===e.state){for(let r of e.mutations)if(this.isThisCollection(r.collection)&&(this.pendingLocalOrigins.add(r.key),r.optimistic))switch(r.type){case"insert":case"update":this.pendingOptimisticUpserts.set(r.key,r.modified),this.pendingOptimisticDeletes.delete(r.key),t?this.pendingOptimisticDirectUpserts.add(r.key):this.pendingOptimisticDirectUpserts.delete(r.key),this.pendingOptimisticDirectDeletes.delete(r.key);break;case"delete":this.pendingOptimisticUpserts.delete(r.key),this.pendingOptimisticDeletes.add(r.key),t?(this.pendingOptimisticDirectUpserts.delete(r.key),this.pendingOptimisticDirectDeletes.add(r.key)):(this.pendingOptimisticDirectUpserts.delete(r.key),this.pendingOptimisticDirectDeletes.delete(r.key))}}else if("failed"===e.state)for(let t of e.mutations)this.isThisCollection(t.collection)&&(this.pendingLocalOrigins.delete(t.key),t.optimistic&&(this.pendingOptimisticUpserts.delete(t.key),this.pendingOptimisticDeletes.delete(t.key),this.pendingOptimisticDirectUpserts.delete(t.key),this.pendingOptimisticDirectDeletes.delete(t.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();let s=new Set;for(let e of this.pendingSyncedTransactions)for(let t of e.operations)s.add(t.key);let a=[];for(let[e,t]of this.pendingOptimisticUpserts)s.has(e)||this.pendingOptimisticDirectUpserts.has(e)?this.optimisticUpserts.set(e,t):a.push(e);for(let e of a)this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e);let n=[];for(let e of this.pendingOptimisticDeletes)s.has(e)||this.pendingOptimisticDirectDeletes.has(e)?this.optimisticDeletes.add(e):n.push(e);for(let e of n)this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);let o=[];for(let e of this.transactions.values())["completed","failed"].includes(e.state)||o.push(e);for(let e of o)for(let t of e.mutations)if(this.isThisCollection(t.collection)&&(this.pendingLocalChanges.add(t.key),t.optimistic))switch(t.type){case"insert":case"update":this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case"delete":this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}this.size=this.calculateSize();let l=[];this.collectOptimisticChanges(t,r,i,l);
3let c=l.filter(t=>!this.recentlySyncedKeys.has(t.key)||!!e);if(this.pendingSyncedTransactions.length>0&&!e){let t=new Set;for(let e of this.pendingSyncedTransactions)for(let r of e.operations)t.add(r.key);let r=c.filter(e=>(!("delete"===e.type&&t.has(e.key))||!!o.some(t=>t.mutations.some(t=>this.isThisCollection(t.collection)&&t.key===e.key)))&&!0);r.length>0&&this.indexes.updateIndexes(r),this.changes.emitEvents(r,e)}else c.length>0&&this.indexes.updateIndexes(c),this.changes.emitEvents(c,e)}calculateSize(){return this.syncedData.size-Array.from(this.optimisticDeletes).filter(e=>this.syncedData.has(e)&&!this.optimisticUpserts.has(e)).length+Array.from(this.optimisticUpserts.keys()).filter(e=>!this.syncedData.has(e)).length}collectOptimisticChanges(e,t,r,i){for(let s of new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes])){let a=this.get(s),n=this.getPreviousValue(s,e,t),o=this.getVirtualPropsSnapshotForState(s,{rowOrigins:r,optimisticUpserts:e,optimisticDeletes:t}),l=this.getVirtualPropsSnapshotForState(s);void 0!==n&&void 0===a?i.push({type:"delete",key:s,value:n,__virtualProps:{value:o}}):void 0===n&&void 0!==a?i.push({type:"insert",key:s,value:a,__virtualProps:{value:l}}):void 0!==n&&void 0!==a&&n!==a&&i.push({type:"update",key:s,value:a,previousValue:n,__virtualProps:{value:l,previousValue:o}})}}getPreviousValue(e,t,r){if(!r.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}scheduleTransactionCleanup(e){"completed"===e.state?this.transactions.delete(e.id):e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(0===this.pendingSyncedTransactions.length)return;let e=new Set;for(let t of this.pendingSyncedTransactions)for(let r of t.operations)e.add(r.key);for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);void 0!==e&&this.preSyncVisibleState.set(t,e)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function tx(){let e=new Map;return function t(r){let i=r.join(".");if(e.has(i))return e.get(i);let s=new Proxy({},{get:(e,i,s)=>"__refProxy"===i||("__path"===i?r:"__type"===i?void 0:"symbol"==typeof i?Reflect.get(e,i,s):t([...r,String(i)])),has:(e,t)=>"__refProxy"===t||"__path"===t||"__type"===t||Reflect.has(e,t),ownKeys:e=>Reflect.ownKeys(e),getOwnPropertyDescriptor:(e,t)=>"__refProxy"===t||"__path"===t||"__type"===t?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)});return e.set(i,s),s}([])}function tF(e){var t;if((t=e)&&"object"==typeof t&&!0===t.__refProxy)return new ty(e.__path);if(e&&"object"==typeof e&&("ToArrayWrapper"===e.__brand||"ConcatToArrayWrapper"===e.__brand||"CaseWhenWrapper"===e.__brand||"MaterializeWrapper"===e.__brand)){let t="ToArrayWrapper"===e.__brand?"toArray()":"ConcatToArrayWrapper"===e.__brand?"concat(toArray())":"CaseWhenWrapper"===e.__brand?"caseWhen()":"materialize()";throw Error(`${t} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${t} directly as a select field value instead.`)}return e&&"object"==typeof e&&"type"in e&&("func"===e.type||"ref"===e.type||"val"===e.type||"agg"===e.type)?e:new th(e)}function tT(e,t){return new tf("eq",[tF(e),tF(t)])}function tA(e,t){return new tf("gt",[tF(e),tF(t)])}function tE(e,t){return new tf("lt",[tF(e),tF(t)])}function tD(e,t,...r){return new tf("and",[e,t,...r].map(e=>tF(e)))}class tM{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}once(e,t){let r=this.on(e,e=>{t(e),r()});return r}off(e,t){this.listeners.get(e)?.delete(t)}waitFor(e,t){return new Promise((r,i)=>{let s,a=this.on(e,e=>{s&&(clearTimeout(s),s=void 0),r(e),a()});t&&(s=setTimeout(()=>{s=void 0,a(),i(Error(`Timeout waiting for event ${String(e)}`))},t))})}
3emitInner(e,t){this.listeners.get(e)?.forEach(e=>{try{e(t)}catch(e){queueMicrotask(()=>{throw e})}})}clearListeners(){this.listeners.clear()}}class tK extends tM{constructor(e,t,r){super(),this.collection=e,this.callback=t,this.options=r,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status="ready",this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,r.onUnsubscribe&&this.on("unsubscribed",e=>r.onUnsubscribe(e)),r.whereExpression&&function(e,t){if(eq(t)){let r;for(let{fieldName:i,fieldPath:s}of(r=[],!function e(t){if("func"!==t.type)return;if("and"===t.name){for(let r of t.args)e(r);return}if(!["eq","gt","gte","lt","lte","in"].includes(t.name)||t.args.length<1||"ref"!==t.args[0].type)return;let i=t.args[0].path;if(0===i.length)return;let s=i.join("_");r.push({fieldName:s,fieldPath:i})}(e),r))eO(i,s,t)}}(r.whereExpression,this.collection);const i=e=>{t(e),this.trackSentKeys(e)};this.callback=i,this.filteredCallback=r.whereExpression?function(e,t){let r=t_(t.whereExpression);return t=>{let i=[];for(let e of t)if("insert"===e.type)r(e.value)&&i.push(e);else if("update"===e.type){let t=r(e.value),s=!!e.previousValue&&r(e.previousValue);t&&s?i.push(e):t&&!s?i.push({...e,type:"insert"}):!t&&s&&i.push({...e,type:"delete",value:e.previousValue})}else r(e.value)&&i.push(e);(i.length>0||0===t.length)&&e(i)}}(this.callback,r):this.callback,this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){let e=[...this.loadedSubsets],t=null!==this.collection._sync.syncLoadSubsetFn;if(0===e.length||!t){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(let t of e){let e=this.collection._sync.loadSubset(t);this.loadedSubsets.push(t),this.trackLoadSubsetPromise(e),e instanceof Promise&&(this.pendingTruncateRefetches.add(e),e.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(e),this.checkTruncateRefetchComplete()}))}0===this.pendingTruncateRefetches.size&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){0===this.pendingTruncateRefetches.size&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;let e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}setOrderByIndex(e){this.orderByIndex=e}hasOrderByIndex(){return void 0!==this.orderByIndex}setStatus(e){if(this._status===e)return;let t=this._status;this._status=e,this.emitInner("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e});let r=`status:${e}`;this.emitInner(r,{type:r,subscription:this,previousStatus:t,status:e})}trackLoadSubsetPromise(e){e instanceof Promise&&(this.pendingLoadSubsetPromises.add(e),this.setStatus("loadingSubset"),e.finally(()=>{this.pendingLoadSubsetPromises.delete(e),0===this.pendingLoadSubsetPromises.size&&this.setStatus("ready")}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){let t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):this.filteredCallback(t)}requestSnapshot(e){if(this.loadedInitialState)return!1;let t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){let r=e.where;if(t.where){let e=tD(t.where,r);t.where=e}else t.where=r}}else this.loadedInitialState=!0;let r={where:t.where,subscription:this,orderBy:e?.orderBy,limit:e?.limit},i=this.collection._sync.loadSubset(r);e?.onLoadSubsetResult?.(i),this.loadedSubsets.push(r),(e?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(i);let s=this.collection.currentStateAsChanges(t);if(void 0===s)return!1;let a=s.filter(e=>!this.sentKeys.has(e.key));for(let e of a)this.sentKeys.add(e.key);return this.snapshotSent=!0,this.callback(a),!0}requestLimitedSnapshot({orderBy:e,limit:t,minValues:r,offset:i,trackLoadSubsetPromise:s=!0,onLoadSubsetRe
3sult:a}){let n;if(!t)throw Error("limit is required");if(!this.orderByIndex)throw Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");let o=void 0!==r&&r.length>0,l=r?.[0],c=this.orderByIndex,u=this.options.whereExpression,d=u?t_(u):void 0,p=e=>{if(void 0!==e&&this.sentKeys.has(e))return!1;let t=this.collection.get(e);return void 0!==t&&(d?.(t)??!0)},y=l,h=[],f=[];if(o){let{expression:r}=e[0],i=this.collection.currentStateAsChanges({where:tT(r,new th(l))});if(i){let e=i.map(e=>e.key).filter(e=>!this.sentKeys.has(e)&&p(e));f.push(...e);let r=c.take(t-f.length,l,p);f.push(...r)}else f=c.take(t,l,p)}else f=c.takeFromStart(t,p);let m=()=>Math.max(t-h.length,0),g=()=>0===f.length,w=e[0].expression,k="ref"===w.type?function(e,t=!1){return eC(e,t)}(new ty(w.path),!0):null;for(;m()>0&&!g();){let e=new Set;for(let t of f){let r=this.collection.get(t);h.push({type:"insert",key:t,value:r}),y=k?k(r):r,e.add(t)}f=c.take(m(),y,p)}let b=this.limitedSnapshotRowCount;for(let e of h)this.sentKeys.add(e.key);if(this.callback(h),this.limitedSnapshotRowCount+=h.length,h.length>0&&(this.lastSentKey=h[h.length-1].key),void 0!==r&&r.length>0){let t=function(e,t){if(0===t.length||0===e.length)return;if(1===e.length){let{expression:r,compareOptions:i}=e[0];return("asc"===i.direction?tA:tE)(r,new th(t[0]))}let r=[];for(let i=0;i<e.length&&i<t.length;i++){let s=e[i],a=t[i],n=[];for(let r=0;r<i;r++){let i=e[r],s=t[r];n.push(tT(i.expression,new th(s)))}let o=("asc"===s.compareOptions.direction?tA:tE)(s.expression,new th(a));if(0===n.length)r.push(o);else{let e=[...n,o];r.push(e.reduce((e,t)=>tD(e,t)))}}return 1===r.length?r[0]:r.reduce((e,t)=>new tf("or",[e,t].map(e=>tF(e))))}(e,r);if(t){let i,{expression:s}=e[0],a=r[0];if(a instanceof Date){var _;let e=new Date(a.getTime()+1);i=tD((_=new th(a),new tf("gte",[tF(s),tF(_)])),tE(s,new th(e)))}else i=tT(s,new th(a));n={whereFrom:t,whereCurrent:i,lastKey:this.lastSentKey}}}let v={where:u,limit:t,orderBy:e,cursor:n,offset:i??b,subscription:this},I=this.collection._sync.loadSubset(v);a?.(I),this.loadedSubsets.push(v),s&&this.trackLoadSubsetPromise(I)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;let t=this.isBufferingForTruncate,r=[];for(let i of e){let e=i;if(this.sentKeys.has(i.key)){if("insert"===i.type)continue;"delete"===i.type&&this.sentKeys.delete(i.key)}else{if("update"===i.type)e={...i,type:"insert",previousValue:void 0};else if("delete"===i.type&&!t)continue;this.sentKeys.add(i.key)}r.push(e)}return r}trackSentKeys(e){if(!this.loadedInitialState&&!this.skipFiltering){for(let t of e)"delete"===t.type?this.sentKeys.delete(t.key):this.sentKeys.add(t.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){for(let e of(this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.loadedSubsets))this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),this.clearListeners()}}class tq{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){for(let e of this.changeSubscriptions)e.emitEvents([])}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1){if(this.shouldBatchEvents&&!t)return void this.batchedEvents.push(...e);let r=e;if(t&&(this.batchedEvents.length>0&&(r=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),0===r.length)return;let i=r.map(e=>this.enrichChangeWithVirtualProps(e));for(let e of this.changeSubscriptions)e.emitEvents(i)}subscribeChanges(e,t={}){if(this.addSubscriber(),t.where&&t.whereExpression)throw Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");let{where:r,...i}=t,s=i.whereExpression;r&&(s=tF(r(tx())));let a=new tK(this.collection,e,{...i,whereExpression:s,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(a)}});return t.onStatusChange&&a.on("status:change",t.onStatusChange),t.includeInitialState?a.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetRe
3sult:t.onLoadSubsetResult}):!1===t.includeInitialState&&a.markAllStateAsSeen(),this.changeSubscriptions.add(a),a}addSubscriber(){let e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),("cleaned-up"===this.lifecycle.status||"idle"===this.lifecycle.status)&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){let e=this.activeSubscribersCount;if(this.activeSubscribersCount--,0===this.activeSubscribersCount)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new q;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}let tO="u">typeof window&&"requestIdleCallback"in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),tP="u">typeof window&&"cancelIdleCallback"in window?e=>window.cancelIdleCallback(e):e=>{clearTimeout(e)},tQ=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}schedule(e,t,r){let i=Date.now()+t;this.tasks.set(e,{executeAt:i,callback:r}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),0===this.tasks.size)return;let e=1/0;for(let t of this.tasks.values())t.executeAt<e&&(e=t.executeAt);let t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;let e=Date.now();for(let[t,r]of this.tasks.entries())if(e>=r.executeAt){this.tasks.delete(t);try{r.callback()}catch(e){console.error("Error in CleanupQueue task:",e)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){e.instance&&(null!==e.instance.timeoutId&&clearTimeout(e.instance.timeoutId),e.instance=null)}};tQ.instance=null;class tR{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=e,this.id=t}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e!==t&&!({idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["cleaned-up","idle"],"cleaned-up":["loading","error"]})[e].includes(t))throw new M(e,t,this.id)}setStatus(e,t=!1){if("ready"===e&&!t)throw new E("You can't directly call \"setStatus('ready'). You must use markReady instead.");this.validateStatusTransition(this.status,e);let r=this.status;this.status=e,this.events.emitStatusChange(e,r)}validateCollectionUsable(e){switch(this.status){case"error":throw new D(e,this.id);case"cleaned-up":this.sync.startSync()}}markReady(){if(this.validateStatusTransition(this.status,"ready"),"loading"===this.status){if(this.setStatus("ready",!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0);let e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(e=>e())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){let e=this.config.gcTime??3e5;!(e<=0)&&Number.isFinite(e)&&tQ.getInstance().schedule(this,e,()=>{0===this.changes.activeSubscribersCount&&this.scheduleIdleCleanup()})}cancelGCTimer(){tQ.getInstance().cancel(this),null!==this.idleCallbackId&&(tP(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){null!==this.idleCallbackId&&tP(this.idleCallbackId),this.idleCallbackId=tO(e=>{0===this.changes.activeSubscribersCount?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(!(!e||e.timeRemaining()>0||e.didTimeout))return this.scheduleIdleCleanup(),!1;{this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),tQ.getInstance().cancel(this),this.hasBeenReady=!1;let e=[...this.onFirstReadyCallbacks];
3return this.onFirstReadyCallbacks=[],e.forEach(e=>{try{e()}catch(e){console.error(`${this.config.id?`[${this.config.id}] `:""}Error in onFirstReady callback during cleanup:`,e)}}),this.setStatus("cleaned-up"),this.events.cleanup(),!0}}onFirstReady(e){this.hasBeenReady?e():this.onFirstReadyCallbacks.push(e)}cleanup(){null!==this.idleCallbackId&&(tP(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}let tW=Symbol("liveQueryInternal");class tB{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.config=e,this.id=t,this.syncMode=e.syncMode??"eager"}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}startSync(){if("idle"===this.lifecycle.status||"cleaned-up"===this.lifecycle.status){this.lifecycle.setStatus("loading");try{var e;let t=(e=this.config.sync.sync({collection:this.collection,begin:e=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:e?.immediate})},write:e=>{let t,r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!r)throw new et;if(r.committed)throw new er;t="key"in e?e.key:this.config.getKey(e.value),this.state.pendingLocalChanges.has(t)&&this.state.pendingLocalOrigins.add(t);let i=e.type;if("insert"===e.type){let s=this.state.syncedData.has(t),a=r.deletedKeys.has(t),n=!0===r.truncate;if(s&&!a&&!n){let r=this.state.syncedData.get(t);if(void 0!==r&&ed(r,e.value))i="update";else{let e=this.config.utils,r=e?.[tW];throw new W(t,this.id,{hasCustomGetKey:r?.hasCustomGetKey??!1,hasJoins:r?.hasJoins??!1,hasDistinct:r?.hasDistinct??!1})}}}let s={...e,type:i,key:t};r.operations.push(s),"delete"===i?(r.deletedKeys.add(t),r.rowMetadataWrites.set(t,{type:"delete"})):"insert"===i?void 0!==s.metadata?r.rowMetadataWrites.set(t,{type:"set",value:s.metadata}):r.rowMetadataWrites.set(t,{type:"delete"}):void 0!==s.metadata&&r.rowMetadataWrites.set(t,{type:"set",value:s.metadata})},commit:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new ei;if(e.committed)throw new es;e.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new et;if(e.committed)throw new er;e.operations=[],e.deletedKeys.clear(),e.rowMetadataWrites.clear(),e.truncate=!0,e.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}),"function"==typeof e?{cleanup:e}:"object"==typeof e?e:void 0);if(this.syncCleanupFn=t?.cleanup??null,this.syncLoadSubsetFn=t?.loadSubset??null,this.syncUnloadSubsetFn=t?.unloadSubset??null,"on-demand"===this.syncMode&&!this.syncLoadSubsetFn)throw new C(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(e){throw this.lifecycle.setStatus("error"),e}}}getActivePendingSyncTransaction(){let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new et;if(e.committed)throw new er;return e}createSyncMetadataApi(){return{row:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],r=t?.rowMetadataWrites.get(e);return r?"delete"===r.type?void 0:r.value:t?.truncate?void 0:this.state.syncedMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:"set",value:t})},delete:e=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:"delete"})}},collection:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],r=t?.collectionMetadataWrites.get(e);return r?"delete"===r.type?void 0:r.value:this.state.syncedCollectionMetadata.get(e)}
3,set:(e,t)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:"set",value:t})},delete:e=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:"delete"})},list:e=>{let t=new Map(this.state.syncedCollectionMetadata),r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(r)for(let[e,i]of r.collectionMetadataWrites)"delete"===i.type?t.delete(e):t.set(e,i.value);return Array.from(t.entries()).filter(([t])=>!e||t.startsWith(e)).map(([e,t])=>({key:e,value:t}))}}}}preload(){return this.preloadPromise||("on-demand"===this.syncMode&&console.warn(`${this.id?`[${this.id}] `:""}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`),this.preloadPromise=new Promise((e,t)=>{if("ready"===this.lifecycle.status)return void e();if("error"===this.lifecycle.status)return void t(new K);if(this.lifecycle.onFirstReady(()=>{e()}),"idle"===this.lifecycle.status||"cleaned-up"===this.lifecycle.status)try{this.startSync()}catch(e){t(e);return}})),this.preloadPromise}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){let t=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),t&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"}),e.finally(()=>{let t=1===this.pendingLoadSubsetPromises.size&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),t&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})})}loadSubset(e){if("eager"===this.syncMode)return!0;if(this.syncLoadSubsetFn){let t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&(this.syncCleanupFn(),this.syncCleanupFn=null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){let t=new ec(this.id,e);throw t.cause=e,t.stack=e.stack,t}throw new ec(this.id,e)})}this.preloadPromise=null}}function tj(e,t){return e===t?0:e<t?-1:1}function t$(e){if(null==e)return e;switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:null;case"bigint":return{__type:"bigint",value:e.toString()};case"function":case"symbol":case"undefined":return}if(Array.isArray(e))return e.map(e=>t$(e)??null);if(e instanceof Date)return{__type:"date",value:e.toISOString()};if(e instanceof Set)return{__type:"set",values:Array.from(e).map(e=>t$(e)??null).sort((e,t)=>tj(tN(e),tN(t)))};if(e instanceof Map)return{__type:"map",entries:Array.from(e.entries()).map(([e,t])=>({key:t$(e)??null,value:t$(t)??null})).sort((e,t)=>tj(tN(e.key),tN(t.key)))};if(e instanceof RegExp)return{__type:"regexp",value:e.toString()};let t={};for(let[r,i]of Object.entries(e).sort(([e],[t])=>tj(e,t))){let e=t$(i);void 0!==e&&(t[r]=e)}return t}function tN(e){if(null===e)return"null";if(Array.isArray(e))return`[${e.map(tN).join(",")}]`;if("object"!=typeof e)return JSON.stringify(e);let t=Object.keys(e).sort((e,t)=>tj(e,t)).map(t=>`${JSON.stringify(t)}:${tN(e[t])}`);return`{${t.join(",")}}`}class tL{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){var r,i;let s,a,n;this.lifecycle.validateCollectionUsable("createIndex");let o=++this.indexCounter,l=tF(e(tx())),c=t.indexType??this.defaultIndexType;if(!c)throw new C(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection: 4 import { BasicIndex } from '@tanstack/db' 5 createCollection({ defaultIndexType: BasicIndex, ... })`);let u=new c(o,l,t.name,t.options);u.build(this.state.entries()),this.indexes.set(o,u);let d=(r=t.name,i=t.options,s={kind:"constructor",...c.name?{name:c.name}:{}},a=t$(l)??null,n=t$(i),{signatureVersion:1,signature:tN(t$({signatureVersion:1,expression:a,options:n??null})??null),indexId:o,name:r,expression:l,resolver:s,...void 0===n?{}:{options:n}});return this.indexMetadata.set(o,d),this.events.emitIndexAdded(d),u}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");let t="number"==typeof e?e:e.id,r=this.indexes.get(t);if(!r||"number"!=typeof e&&r!==e)return!1;this.indexes.delete(t);let i=this.indexMetadata.get(t);return this.indexMetadata.delete(t),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>
5e.indexId-t.indexId).map(e=>({...e,expression:JSON.parse(JSON.stringify(e.expression)),resolver:{...e.resolver},...void 0===e.options?{}:{options:function e(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>e(t));let r={};for(let[i,s]of Object.entries(t))r[i]=e(s);return r}(e.options)}}))}updateIndexes(e){for(let t of this.indexes.values())for(let r of e)switch(r.type){case"insert":t.add(r.key,r.value);break;case"update":r.previousValue?t.update(r.key,r.previousValue,r.value):t.add(r.key,r.value);break;case"delete":t.remove(r.key,r.value)}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}let tU=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),tz=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),tV=new Set(["set","delete","clear","add"]),tG=new Set(["entries","keys","values","forEach"]);function tJ(e){return null!==e&&"object"==typeof e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!ey(e)}function tH(e,t,r){return function(...i){let s=e.apply(t.copy_,i);return r(t),s}}function tY(...e){let t="u">typeof window&&"u">typeof localStorage;t&&"true"===localStorage.getItem("DEBUG")?console.log("[proxy]",...e):t||void 0===eK.default||"true"!==eK.default.env.DEBUG||console.log("[proxy]",...e)}function tZ(e,t=new WeakMap){if(null==e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e)){let r=[];return t.set(e,r),e.forEach((e,i)=>{r[i]=tZ(e,t)}),r}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)){let r=new(Object.getPrototypeOf(e)).constructor(e.length);t.set(e,r);for(let t=0;t<e.length;t++)r[t]=e[t];return r}if(e instanceof Map){let r=new Map;return t.set(e,r),e.forEach((e,i)=>{r.set(i,tZ(e,t))}),r}if(e instanceof Set){let r=new Set;return t.set(e,r),e.forEach(e=>{r.add(tZ(e,t))}),r}if(ey(e))return e;let r={};for(let i in t.set(e,r),e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=tZ(e[i],t));for(let i of Object.getOwnPropertySymbols(e))r[i]=tZ(e[i],t);return r}let tX=0;function t0(e,t){let r=new Map;function i(e,t){if(tY("Object ID:",e.constructor.name),r.has(e))return r.get(e);{let i=t0(e,t);return r.set(e,i),i}}let s=new Map,a={copy_:tZ(e),originalObject:tZ(e),proxyCount:tX+=1,modified:!1,assigned_:{},parent:t,target:e};function n(e){e.modified||(e.modified=!0),e.parent&&(tY("propagating change to parent"),"updateMap"in e.parent?e.parent.updateMap(e.copy_):"updateSet"in e.parent?e.parent.updateSet(e.copy_):(e.parent.tracker.copy_[e.parent.prop]=e.copy_,e.parent.tracker.assigned_[e.parent.prop]=!0),n(e.parent.tracker))}function o(e){if(tY("checkIfReverted called with assigned keys:",Object.keys(e.assigned_)),0===Object.keys(e.assigned_).length&&0===Object.getOwnPropertySymbols(e.assigned_).length)return tY("No assigned properties, returning true"),!0;for(let t in e.assigned_)if(!0===e.assigned_[t]){let r=e.copy_[t],i=e.originalObject[t];if(tY(`Checking property ${String(t)}, current:`,r,"original:",i),!ed(r,i))return tY(`Property ${String(t)} is different, returning false`),!1}else if(!1===e.assigned_[t])return tY(`Property ${String(t)} was deleted, returning false`),!1;for(let t of Object.getOwnPropertySymbols(e.assigned_))if(!0===e.assigned_[t]){if(!ed(e.copy_[t],e.originalObject[t]))return tY("Symbol property is different, returning false"),!1}else if(!1===e.assigned_[t])return tY("Symbol property was deleted, returning false"),!1;return tY("All properties match original values, returning true"),!0}return tY("createChangeProxy called for target",e,a.proxyCount),{proxy:function(e){if(tY("createObjectProxy",e),s.has(e))return tY("proxyCache found match"),s.get(e);let r=new Proxy(e,{get(e,t){tY("get",e,t);let r=a.copy_[t]??a.originalObject[t],o=a.originalObject[t];tY("value (at top of proxy get)",r);let l=Object.getOwnPropertyDescriptor(e,t);if(l?.get)return r;if("function"==typeof r){if(Array.isArray(e)){let e=t.toString();if(tz.has(e))return tH(r,a,n);let s=function(e,t,r,i){if(tU.has(e))return function(...s){let a=s[0];if("function"!=typeof a)return t.apply(r.copy_,s);let n=(e,t)=>{if(tJ(e)){let{proxy:s}=i(e,{tracker:r,prop:String(t)});return s}return e};if("reduce"===e||"reduceRight"===e)return t.apply(r.copy_,[function(e,t,r,i){let s=n(t,r);return a.call(this,e,s,r,i)},...s.slice(1)]);let o=t.apply(r.copy_,[function(e,t,r){let i=n(e,t);return a.call(this,i,t,r)},...s.slice(1)]);if(("find"===e||"findLast"===e)&&o&&"object"==typeof o){let e=r.copy_.indexOf(o);if(-1!==e)return n(o,e)}return"filter"===e&&Array.isArray(o)?o.map(e=>{let t=r.copy_.indexOf(e);return -1!==t?n(e,t):e}):o}}(e,r,a,i);if(s)return s;if(t===Symbol.iterator)return function(){let e=a.copy_,t=0;return{next(){if(t>=e.length)return{done:!0,value:void 0};let r=e[t],s=r;if(tJ(r)){let{proxy:e}=i(r,{tracker:a,prop:String(t)});s=e}return t++,{done:!1,value:s}},[Symbol.iterator](){return this}}}}if(e instanceof Map||e instanceof Set){let s=t.toString();if(tV.has(s))return tH(r,a,n);
5let o=function(e,t,r,i,s,a,n){if(tG.has(e)||t===Symbol.iterator)return function(...o){let l=r.apply(s.copy_,o);if("forEach"===e){let e=o[0];if("function"==typeof e)return r.apply(i,[function(t,r,i){let a=e.call(this,t,r,i);return n(s),a},...o.slice(1)])}if("entries"===e||"values"===e||e===Symbol.iterator.toString()||t===Symbol.iterator){let r=new Map;if("values"===e&&i instanceof Map)for(let[e,t]of s.copy_.entries())r.set(t,e);let n=new Map;if(i instanceof Set)for(let e of s.copy_.values())n.set(e,e);return{next(){let o=l.next();if(!o.done&&o.value&&"object"==typeof o.value){if("entries"===e&&Array.isArray(o.value)&&2===o.value.length){if(o.value[1]&&"object"==typeof o.value[1]){let e=o.value[0],{proxy:t}=a(o.value[1],{tracker:s,prop:e,updateMap:t=>{s.copy_ instanceof Map&&s.copy_.set(e,t)}});o.value[1]=t}}else if("values"===e||e===Symbol.iterator.toString()||t===Symbol.iterator)if("values"===e&&i instanceof Map){let e=r.get(o.value);if(void 0!==e){let{proxy:t}=a(o.value,{tracker:s,prop:e,updateMap:t=>{s.copy_ instanceof Map&&s.copy_.set(e,t)}});o.value=t}}else if(i instanceof Set){let e=o.value,{proxy:t}=a(o.value,{tracker:s,prop:e,updateSet:t=>{s.copy_ instanceof Set&&(s.copy_.delete(e),s.copy_.add(t),n.set(e,t))}});o.value=t}else{let e=Symbol("iterator-value"),{proxy:t}=a(o.value,{tracker:s,prop:e});o.value=t}}return o},[Symbol.iterator](){return this}}}return l}}(s,t,r,e,a,i,n);if(o)return o}return r.bind(e)}if(tJ(r)){let{proxy:e}=i(o,{tracker:a,prop:String(t)});return s.set(r,e),e}return r},set(e,r,i){let s=a.copy_[r];if(tY(`set called for property ${String(r)}, current:`,s,"new:",i),ed(s,i))tY("Value unchanged, not tracking");else{let e=a.originalObject[r],s=ed(i,e);if(tY("value:",i,"original:",e,"isRevertToOriginal:",s),s){tY(`Reverting property ${String(r)} to original value`),delete a.assigned_[r.toString()],tY(`Updating copy with original value for ${String(r)}`),a.copy_[r]=tZ(e),tY("Checking if all properties reverted");let i=o(a);tY("All reverted:",i),i?(tY("All properties reverted, clearing tracking"),a.modified=!1,a.assigned_={},t&&(tY("Updating parent for property:",t.prop),function e(t,r){tY("checkParentStatus called for child prop:",r);let i=o(t);tY("Parent checkIfReverted returned:",i),i&&(tY("Parent is fully reverted, clearing tracking"),t.modified=!1,t.assigned_={},t.parent&&(tY("Continuing up the parent chain"),e(t.parent.tracker,t.parent.prop)))}(t.tracker,t.prop))):(tY("Some properties still changed, keeping modified flag"),a.modified=!0)}else tY(`Setting new value for property ${String(r)}`),a.copy_[r]=i,a.assigned_[r.toString()]=!0,tY("Marking object and ancestors as modified",a),n(a)}return!0},defineProperty(e,t,r){let i=Reflect.defineProperty(e,t,r);return i&&"value"in r&&(a.copy_[t]=tZ(r.value),a.assigned_[t.toString()]=!0,n(a)),i},getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,t),preventExtensions:e=>Reflect.preventExtensions(e),isExtensible:e=>Reflect.isExtensible(e),deleteProperty(e,t){tY("deleteProperty",e,t);let r="symbol"==typeof t?t.toString():t;if(r in e){let i=r in a.originalObject,s=Reflect.deleteProperty(e,t);return s&&(i?(a.assigned_[r]=!1,n(a)):(delete a.assigned_[r],0===Object.keys(a.assigned_).length&&0===Object.getOwnPropertySymbols(a.assigned_).length?a.modified=!1:a.modified=!0)),s}return!0}});return s.set(e,r),r}
5(a.copy_),getChanges:()=>{if(tY("getChanges called, modified:",a.modified),tY(a),!a.modified)return tY("Object not modified, returning empty object"),{};if("object"!=typeof a.copy_||Array.isArray(a.copy_)||0===Object.keys(a.assigned_).length)return a.copy_;let e={};for(let t in a.copy_)!0===a.assigned_[t]&&t in a.copy_&&(e[t]=a.copy_[t]);return tY("Returning copy:",e),e}}}let t1=new class{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:r,run:i}){if(void 0===e)return void i();let s=this.getOrCreateContext(e);if(s.jobs.has(t)||s.queue.push(t),s.jobs.set(t,i),r){let e=new Set(r);e.delete(t),s.dependencies.set(t,e)}else s.dependencies.has(t)||s.dependencies.set(t,new Set);s.completed.delete(t)}flush(e){let t=this.contexts.get(e);if(!t)return;let{queue:r,jobs:i,dependencies:s,completed:a}=t;for(;r.length>0;){let t=!1,n=r.length;for(let o=0;o<n;o++){let n=r.shift(),o=i.get(n);if(!o){s.delete(n),a.delete(n);continue}let l=s.get(n),c=!l;if(l)for(let t of(c=!0,l)){if(t===n)continue;let r="object"==typeof t&&null!==t&&"function"==typeof t.hasPendingGraphRun&&t.hasPendingGraphRun(e);if(i.has(t)&&!a.has(t)||!i.has(t)&&r){c=!1;break}}c?(i.delete(n),s.delete(n),o(),a.add(n),t=!0):r.push(n)}if(!t)throw Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(let e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(t=>t(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){let t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){let r=this.contexts.get(e);r&&(r.jobs.delete(t),r.dependencies.delete(t),r.completed.delete(t),r.queue=r.queue.filter(e=>e!==t),0===r.jobs.size&&this.contexts.delete(e))}},t2=[],t5=[],t3=0;function t8(e){let t=new t4(e);return t2.push(t),t}function t7(){return t5.length>0?t5.slice(-1)[0]:void 0}class t4{constructor(e){if(void 0===e.mutationFn)throw new Y;this.id=e.id??v(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=function(){let e,t,r=!0;return{promise:new Promise((i,s)=>{e=e=>{r=!1,i(e)},t=e=>{r=!1,s(e)}}),resolve:e,reject:t,isPending:()=>r}}(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=t3++,this.metadata=e.metadata??{}}setState(e){var t;let r;this.state=e,("completed"===e||"failed"===e)&&(t=this,-1!==(r=t2.findIndex(e=>e.id===t.id))&&t2.splice(r,1))}mutate(e){if("pending"!==this.state)throw new Z;t1.clear(this.id),t5.push(this);try{e()}finally{var t=this;try{t1.flush(t.id)}finally{t5=t5.filter(e=>e.id!==t.id)}}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){let t=new Map;for(let e of this.mutations)t.set(e.globalKey,e);for(let r of e){let e=t.get(r.globalKey);if(e){let i=function(e,t){switch(`${e.type}-${t.type}`){case"insert-update":return{...e,type:"insert",original:{},modified:t.modified,changes:{...e.changes,...t.changes},key:e.key,globalKey:e.globalKey,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case"insert-delete":return null;case"update-delete":case"delete-delete":case"insert-insert":return t;case"update-update":return{...t,original:e.original,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}};default:{let r=`${e.type}-${t.type}`;throw Error(`Unhandled mutation combination: ${r}`)}}}(e,r);null===i?t.delete(r.globalKey):t.set(r.globalKey,i)}else t.set(r.globalKey,r)}for(let e of(this.mutations.length=0,t.values()))this.mutations.push(e)}rollback(e){let t=e?.isSecondaryRollback??!1;if("completed"===this.state)throw new X;if(this.setState("failed"),!t){let e=new Set;for(let t of(this.mutations.forEach(t=>e.add(t.globalKey)),t2))"pending"===t.state&&t.mutations.some(t=>e.has(t.globalKey))&&t.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){let e=new Set;for(let t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if("pending"!==this.state)throw new ee;if(this.setState("persisting"),0===this.mutations.length)return this.setState("completed"),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.error={message:e.message,error:e},this.rollback(),e}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return 0!==t?t:this.sequenceNumber-e.sequenceNumber}}class t6{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable("insert");let r=this.state,i=t7();if(!i&&!this.config.onInsert)throw new V;let s=Array.isArray(e)?e:[e],a=[],n=new Set;
5if(s.forEach(e=>{let r=this.validateData(e,"insert"),i=this.config.getKey(r);if(this.state.has(i)||n.has(i))throw new R(i);n.add(i);let s=this.generateGlobalKey(i,e),o={mutationId:v(),original:{},modified:r,changes:Object.fromEntries(Object.keys(e).map(e=>[e,r[e]])),globalKey:s,key:i,metadata:t?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:t?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(o)}),i)return i.applyMutations(a),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;{let e=t8({metadata:{[tS]:!0},mutationFn:async e=>await this.config.onInsert({transaction:e.transaction,collection:this.collection})});return e.applyMutations(a),this.markPendingLocalOrigins(a),e.commit().catch(()=>void 0),r.transactions.set(e.id,e),r.scheduleTransactionCleanup(e),r.recomputeOptimisticState(!0),e}},this.delete=(e,t)=>{let r=this.state;this.lifecycle.validateCollectionUsable("delete");let i=t7();if(!i&&!this.config.onDelete)throw new J;if(Array.isArray(e)&&0===e.length)throw new L;let s=Array.isArray(e)?e:[e],a=[];for(let e of s){if(!this.state.has(e))throw new U(e);let i=this.generateGlobalKey(e,this.state.get(e)),s={mutationId:v(),original:this.state.get(e),modified:this.state.get(e),changes:this.state.get(e),globalKey:i,key:e,metadata:t?.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:t?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(s)}if(i)return i.applyMutations(a),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;let n=t8({autoCommit:!0,metadata:{[tS]:!0},mutationFn:async e=>this.config.onDelete({transaction:e.transaction,collection:this.collection})});return n.applyMutations(a),this.markPendingLocalOrigins(a),n.commit().catch(()=>void 0),r.transactions.set(n.id,n),r.scheduleTransactionCleanup(n),r.recomputeOptimisticState(!0),n},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new T}validateData(e,t,r){if(!this.config.schema)return e;let i=this.ensureStandardSchema(this.config.schema);if("update"===t&&r){let s=this.state.get(r);if(s&&e&&"object"==typeof e&&"object"==typeof s){let r=Object.assign({},s,e),a=i["~standard"].validate(r);if(a instanceof Promise)throw new A;if("issues"in a&&a.issues)throw new S(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let n=a.value;return Object.fromEntries(Object.keys(e).map(e=>[e,n[e]]))}}let s=i["~standard"].validate(e);if(s instanceof Promise)throw new A;if("issues"in s&&s.issues)throw new S(t,s.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return s.value}generateGlobalKey(e,t){if("string"!=typeof e&&"number"!=typeof e){if(void 0===e)throw new P(t);throw new Q(e,t)}return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(let t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,r){let i;if(void 0===e)throw new B;let s=this.state;this.lifecycle.validateCollectionUsable("update");let a=t7();if(!a&&!this.config.onUpdate)throw new G;let n=Array.isArray(e),o=n?e:[e];if(n&&0===o.length)throw new j;let l="function"==typeof t?t:r,c="function"==typeof t?{}:t,u=o.map(e=>{let t=this.state.get(e);if(!t)throw new $(e);return t});i=n?function(e,t){let r,{proxies:i,getChanges:s}={proxies:(r=e.map(e=>t0(e))).map(e=>e.proxy),getChanges:()=>r.map(e=>e.getChanges())};return t(i),s()}(u,l):[function(e,t){let{proxy:r,getChanges:i}=t0(e);return t(r),i()}(u[0],l)];let d=o.map((e,t)=>{let r=i[t];if(!r||0===Object.keys(r).length)return null;let a=u[t],n=Object.assign({},a,this.validateData(r,"update",e)),o=this.config.getKey(a),l=this.config.getKey(n);if(o!==l)throw new N(o,l);let d=this.generateGlobalKey(l,n);return{mutationId:v(),original:a,modified:n,changes:Object.fromEntries(Object.keys(r).map(e=>[e,n[e]])),globalKey:d,key:e,metadata:c.metadata,syncMetadata:s.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}
5).filter(Boolean);if(0===d.length){let e=t8({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),s.scheduleTransactionCleanup(e),e}if(a)return a.applyMutations(d),s.transactions.set(a.id,a),s.scheduleTransactionCleanup(a),s.recomputeOptimisticState(!0),a;let p=t8({metadata:{[tS]:!0},mutationFn:async e=>this.config.onUpdate({transaction:e.transaction,collection:this.collection})});return p.applyMutations(d),this.markPendingLocalOrigins(d),p.commit().catch(()=>void 0),s.transactions.set(p.id,p),s.scheduleTransactionCleanup(p),s.recomputeOptimisticState(!0),p}}class t9 extends tM{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t){this.emit("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e});let r=`status:${e}`;this.emit(r,{type:r,collection:this.collection,previousStatus:t,status:e})}emitSubscribersChange(e,t){this.emit("subscribers:change",{type:"subscribers:change",collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit("index:added",{type:"index:added",collection:this.collection,index:e})}emitIndexRemoved(e){this.emit("index:removed",{type:"index:removed",collection:this.collection,index:e})}cleanup(){this.clearListeners()}}class re{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this._mutations.insert(e,t),this.delete=(e,t)=>this._mutations.delete(e,t),!e)throw new x;if(!e.sync)throw new F;if(e.id?this.id=e.id:this.id=v(),this.config={...e,autoIndex:e.autoIndex??"off"},"eager"===this.config.autoIndex&&!e.defaultIndexType)throw new C(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it: 6 import { BasicIndex } from '@tanstack/db' 7 createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new tq,this._events=new t9,this._indexes=new tL,this._lifecycle=new tR(e,this.id),this._mutations=new t6(e,this.id),this._state=new tC(e),this._sync=new tB(e,this.id),this.comparisonOpts=function(e){if(!e.defaultStringCollation)return{stringSort:"locale"};{let t=e.defaultStringCollation;return{stringSort:t.stringSort??"locale",locale:"locale"===t.stringSort?t.locale:void 0,localeOptions:"locale"===t.stringSort?t.localeOptions:void 0}}}(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),!0===e.startSync&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return"ready"===this._lifecycle.status}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(let e of this._state.keys()){let t=this.get(e);void 0!==t&&(yield t)}}*entries(){for(let e of this._state.keys()){let t=this.get(e);void 0!==t&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(let[r,i]of this.entries())e(i,r,t++)}map(e){let t=[],r=0;for(let[i,s]of this.entries())t.push(e(s,i,r++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,r){return this._mutations.validateData(e,t,r)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,r){return this._mutations.update(e,t,r)}get state(){let e=new Map;for(let[t,r]of this.entries())e.set(t,r);return e}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return function(e,t={}){let r=t=>{let r=[];for(let[i,s]of e.entries())(t?.(s)??!0)&&r.push({type:"insert",key:i,value:s});return r};if(void 0!==t.limit&&!t.orderBy)throw Error("limit cannot be used without orderBy");
7if(t.orderBy){let r=t.where?t_(t.where):void 0,i=function(e,t,r,i,s){if(1===t.length){let s=t[0],a=s.expression;if("ref"===a.type){let t=a.path,n=void 0!==s.compareOptions.stringSort?s.compareOptions:{...e.compareOptions,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls};eO(t[0],t,e,n);let o=eD(e,t,n);if(o&&o.supports("gt"))return o.takeFromStart(r??o.keyCount,t=>{let r=e.get(t);return void 0!==r&&(i?.(r)??!0)})}}if(s)return;let a=[];for(let[t,r]of e.entries())(i?.(r)??!0)&&a.push({key:t,value:r});a.sort((e,r)=>{for(let i of t){let t=eb(i.compareOptions)(tv(e.value,i.expression),tv(r.value,i.expression));if(0!==t)return t}return 0});let n=a.map(e=>e.key);return void 0!==r?n.slice(0,r):n}(e,t.orderBy,t.limit,r,t.optimizedOnly);if(void 0===i)return;let s=[];for(let t of i){let r=e.get(t);void 0!==r&&s.push({type:"insert",key:t,value:r})}return s}if(!t.where)return r();try{let i=t.where,s=function e(t,r){if("func"===t.type)switch(t.name){case"eq":case"gt":case"gte":case"lt":case"lte":return function(e,t){if("func"!==e.type||2!==e.args.length)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let r=e.args[0],i=e.args[1],s=null,a=null,n=e.name;if("ref"===r.type&&"val"===i.type)s=r,a=i;else if("val"===r.type&&"ref"===i.type)switch(s=i,a=r,n){case"gt":n="lt";break;case"gte":n="lte";break;case"lt":n="gt";break;case"lte":n="gte"}if(s&&a){let e=eD(t,s.path);if(e){let r=a.value,i=n;return e.supports(i)&&("gt"!==n&&"gte"!==n&&"lt"!==n&&"lte"!==n||eM(r,e,t))?{canOptimize:!0,matchingKeys:e.lookup(i,r),isExact:"lt"!==n&&"lte"!==n&&null!=r}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}(t,r);case"and":return function(t,r){if("func"!==t.type||t.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let i=function(e,t){if("func"!==e.type||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};let r=new Map;for(let[t,i]of e.args.entries())if("func"===i.type&&["gt","gte","lt","lte"].includes(i.name)&&2===i.args.length){let e=i.args[0],s=i.args[1],a=null,n=null,o=i.name;if("ref"===e.type&&"val"===s.type)a=e,n=s;else if("val"===e.type&&"ref"===s.type)switch(a=s,n=e,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte"}if(a&&n){let e=a.path.join("."),i=n.value;r.has(e)||r.set(e,[]),r.get(e).push({operation:o,value:i,argIndex:t})}}for(let[e,i]of r)if(i.length>=2){let r=eD(t,e.split("."));if(r&&i.some(e=>!eM(e.value,r,t)))continue;if(r&&r.supports("gt")&&r.supports("lt")){let e,s,a=eb({...eh,...t.compareOptions,direction:"asc"}),n=!1,o=!1,l=!0,c=!0,u=!1;for(let{operation:t,value:r}of i){if(null==r){u=!0;continue}switch(t){case"gt":case"gte":{let i=n?a(r,e):1;i>0?(e=r,n=!0,l="gte"===t):0===i&&"gt"===t&&(l=!1);break}case"lt":case"lte":{let e=o?a(r,s):-1;e<0?(s=r,o=!0,c="lte"===t):0===e&&"lt"===t&&(c=!1)}}}let d={};return n&&(d.from=e,d.fromInclusive=l),o&&(d.to=s,d.toInclusive=c),{canOptimize:!0,matchingKeys:r.rangeQuery(d),isExact:n&&!u,coveredArgIndices:new Set(i.map(e=>e.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}(t,r),s=i.canOptimize?i.coveredArgIndices:new Set,a=[];i.canOptimize&&a.push(i);let n=!i.canOptimize||i.isExact;for(let[i,o]of t.args.entries()){if(s.has(i))continue;let t=e(o,r);t.canOptimize?(a.push(t),t.isExact||(n=!1)):n=!1}return a.length>0?{canOptimize:!0,matchingKeys:function(e){if(0===e.length)return new Set;if(1===e.length)return new Set(e[0]);let t=new Set(e[0]);for(let r=1;r<e.length;r++){let i=new Set;for(let s of t)e[r].has(s)&&i.add(s);t=i}return t}(a.map(e=>e.matchingKeys)),isExact:n}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}(t,r);case"or":var i=t,s=r;if("func"!==i.type||i.args.length<2)break;let a=[];for(let t of i.args){let r=e(t,s);if(!r.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};a.push(r)}return{canOptimize:!0,matchingKeys:function(e){let t=new Set;for(let r of e)for(let e of r)t.add(e);return t}(a.map(e=>e.matchingKeys)),isExact:a.every(e=>e.isExact)};case"in":return function(e,t){if("func"!==e.type||2!==e.args.length)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let r=e.args[0],i=e.args[1];if("ref"===r.type&&"val"===i.type&&Array.isArray(i.value)){let e=r.path,s=i.value,a=eD(t,e),n=s.every(e=>null!=e);if(a){if(a.supports("in"))return{canOptimize:!0,matchingKeys:a.lookup("in",s),isExact:n};else if(a.supports("eq")){let e=new Set;for(let t of s)for(let r of a.lookup("eq",t))e.add(r);return{canOptimize:!0,matchingKeys:e,isExact:n}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}(t,r)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}(i,e);if(s.canOptimize){let t=s.isExact?void 0:t_(i),r=[];for(let i of s.matchingKeys){let s=e.get(i);void 0!==s&&(t?.(s)??!0)&&r.push({type:"insert",key:i,value:s})}return r}{if(t.optimizedOnly)return;let e=t_(i);return r(e)}}catch(s){console.warn(`${e.id?`[${e.id}] `:""}Error processing where clause, falling back to full scan:`,s);let i=t_(t.where);if(t.optimizedOnly)return;return r(i)}}(this,e)}
7subscribeChanges(e,t={}){return this._changes.subscribeChanges(e,t)}on(e,t){return this._events.on(e,t)}once(e,t){return this._events.once(e,t)}off(e,t){this._events.off(e,t)}waitFor(e,t){return this._events.waitFor(e,t)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}var rt=e.i(190985),rr=e.i(397482);class ri extends I{constructor(e){super(e),this.name="QueryCollectionError"}}class rs extends ri{constructor(){super("[QueryCollection] queryKey must be provided."),this.name="QueryKeyRequiredError"}}class ra extends ri{constructor(){super("[QueryCollection] queryFn must be provided."),this.name="QueryFnRequiredError"}}class rn extends ri{constructor(){super("[QueryCollection] queryClient must be provided."),this.name="QueryClientRequiredError"}}class ro extends ri{constructor(){super("[QueryCollection] getKey must be provided."),this.name="GetKeyRequiredError"}}class rl extends ri{constructor(){super("[QueryCollection] initialData and initialDataUpdatedAt are only supported when syncMode is 'eager'. Seed or hydrate the exact Query cache key for on-demand subsets instead."),this.name="InitialDataInOnDemandModeError"}}class rc extends ri{constructor(){super("Collection must be in 'ready' state for manual sync operations. Sync not initialized yet."),this.name="SyncNotInitializedError"}}class ru extends ri{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name="DuplicateKeyInBatchError"}}class rd extends ri{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name="UpdateOperationItemNotFoundError"}}class rp extends ri{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name="DeleteOperationItemNotFoundError"}}let ry=new WeakMap;function rh(e,t){let r=function(e,t){let r=Array.isArray(e)?e:[e],i=[];for(let e of r)if("delete"===e.type)for(let t of Array.isArray(e.key)?e.key:[e.key])i.push({type:"delete",key:t});else for(let r of Array.isArray(e.data)?e.data:[e.data]){let s;if("update"===e.type)s=t.getKey(r);else{let i=t.collection.validateData(r,"upsert"===e.type?"insert":e.type);s=t.getKey(i)}i.push({type:e.type,key:s,data:r})}return i}(e,t),i=new Set;for(let e of r){if(i.has(e.key))throw new ru(e.key);if(i.add(e.key),"update"===e.type){if(!t.collection._state.syncedData.has(e.key))throw new rd(e.key)}else if("delete"===e.type&&!t.collection._state.syncedData.has(e.key))throw new rp(e.key)}for(let e of(t.begin({immediate:!0}),r))switch(e.type){case"insert":{let r=t.collection.validateData(e.data,"insert");t.write({type:"insert",value:r});break}case"update":{let r={...t.collection._state.syncedData.get(e.key),...e.data},i=t.collection.validateData(r,"update",e.key);t.write({type:"update",value:i});break}case"delete":{let r=t.collection._state.syncedData.get(e.key);t.write({type:"delete",value:r});break}case"upsert":{let r=t.collection._state.syncedData.has(e.key),i=t.collection.validateData(e.data,r?"update":"insert",e.key);r?t.write({type:"update",value:i}):t.write({type:"insert",value:i})}}t.commit();let s=Array.from(t.collection._state.syncedData.values());t.updateCacheData?t.updateCacheData(s):t.queryClient.setQueryData(t.queryKey,s)}function rf(e){if(!e)return null;switch(e.type){case"val":return{type:"val",value:function e(t){if(void 0===t)return{__type:"undefined"};if("number"==typeof t){if(Number.isNaN(t))return{__type:"nan"};if(t===1/0)return{__type:"infinity",sign:1};if(t===-1/0)return{__type:"infinity",sign:-1}}return null===t||"string"==typeof t||"number"==typeof t||"boolean"==typeof t?t:t instanceof Date?{__type:"date",value:t.toJSON()}:Array.isArray(t)?t.map(t=>e(t)):"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,r])=>[t,e(r)])):t}(e.value)};case"ref":return{type:"ref",path:[...e.path]};case"func":return{type:"func",name:e.name,args:e.args.map(e=>rf(e))};default:return null}}let rm=["enabled","refetchInterval","retry","retryDelay","staleTime","gcTime","refetchOnWindowFocus","refetchOnReconnect","refetchOnMount","networkMode"],rg="queryCollection:gc:";class rw{constructor(e,t,r){this.state=e,this.refetchFn=t,this.refetch=t,this.writeInsert=r.writeInsert,this.writeUpdate=r.writeUpdate,this.writeDelete=r.writeDelete,this.writeUpsert=r.writeUpsert,this.writeBatch=r.writeBatch}async clearError(){this.state.lastError=void 0,this.state.errorCount=0,this.state.lastErrorUpdatedAt=0,await this.refetchFn({throwOnError:!0})}get lastError(){return this.state.lastError}get isError(){return!!this.state.lastError}get errorCount(){return this.state.errorCount}get isFetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isFetching)}get isRefetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isRefetching)}get isLoading(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isLoading)}get dataUpdatedAt(){return Math.max(0,...Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().dataUpdatedAt))}get fetchStatus(){return Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().fetchStatus)}}var rk=e.i(809152);let rb=new WeakMap;function r_(e,t){let r=rb.get(e),i=r?.get(t);return r?.delete(t),i}e.s(["createWyattCollection",0,function(e){var t;let r,{queryClient:i,name:s,scope:a,fetchAll:n,getKey:o=e=>e.id,compare:l,staleTime:c=6e4,gcTime:u=864e5,startSync:d=!1,refetchInterval:p,insert:y,update:h,remove:f}=e,m=[s,...a].join(":"),g=null,w=e=>{let t=e.filter(e=>!!e);0!==t.length&&g&&"ready"===g.status&&g.utils.writeBatch(()=>{for(let e of t)g.utils.writeUpsert(e)})},k=(r=new re(t=function(e){let{queryKey:t,queryFn:r,select:i,queryClient:s,enabled:a,refetchInterval:n,retry:o,retryDelay:l,staleTime:c,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:p,refetchOnMount:y,networkMode:h,initialData:f,initialDataUpdatedAt:m,persistedGcTime:g,getKey:w,onInsert:k,onUpdate:b,onDelete:_,meta:v,...I}=e,S=I.syncMode??"eager";if("on-demand"===S&&(void 0!==f||void 0!==m))throw new rl;let C="eager"===S?{...void 0!==f&&{initialData:f},...void 0!==m&&{initialDataUpdatedAt:m},placeholderData:void 0}:{initialData:()=>void 0,initialDataUpdatedAt:void 0,placeholderData:void 0},x="function"==typeof t?t({}):t;if(!t)throw new rs;if(!r)throw new ra;if(!s)throw new rn;if(!w)throw new ro;let F={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},T=new Map,A=new Map,E=new Map,D=new Map,M=new Map,K=new Map,q=(e,t)=>
7{0===t.size?E.delete(e):(E.set(e,new Set(t)),t.forEach(t=>{let r=A.get(t)||new Set;r.add(e),A.set(t,r)}))},O=(e,t)=>{let r=E.get(e);r?.delete(t),r?.size||E.delete(e);let i=A.get(t);return i?.delete(e),!r?.size},P=async e=>Promise.all([...T.values()].map(t=>F.observers.get((0,rt.hashKey)(t)).refetch({throwOnError:e?.throwOnError}))),Q=(e,t)=>{i?s.setQueryData(e,e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return t;let r=i(e);if(Array.isArray(r)){for(let i of Object.keys(e))if(e[i]===r)return{...e,[i]:t}}if(Array.isArray(e.data))return{...e,data:t};if(Array.isArray(e.items))return{...e,items:t};if(Array.isArray(e.results))return{...e,results:t};for(let r of Object.keys(e))if(Array.isArray(e[r]))return{...e,[r]:t};return e}):s.setQueryData(e,t)},R=e=>{let t=s.getQueryCache().findAll({queryKey:x});if(t.length>0)for(let r of t)Q(r.queryKey,e);else Q(x,e)},W=null,B=function(e){function t(){let t=e();if(!t)throw new rc;return t}return{writeInsert(e){let r={type:"insert",data:e},i=t(),s=ry.get(i);s?.isActive?s.operations.push(r):rh(r,i)},writeUpdate(e){let r={type:"update",data:e},i=t(),s=ry.get(i);s?.isActive?s.operations.push(r):rh(r,i)},writeDelete(e){let r={type:"delete",key:e},i=t(),s=ry.get(i);s?.isActive?s.operations.push(r):rh(r,i)},writeUpsert(e){let r={type:"upsert",data:e},i=t(),s=ry.get(i);s?.isActive?s.operations.push(r):rh(r,i)},writeBatch(e){let r=t(),i=ry.get(r);if(i?.isActive)throw Error("Cannot nest writeBatch calls. Complete the current batch before starting a new one.");let s={operations:[],isActive:!0};ry.set(r,s);try{let t=e();if(t&&"object"==typeof t&&"then"in t&&"function"==typeof t.then)throw Error("writeBatch does not support async callbacks. The callback must be synchronous.");s.operations.length>0&&rh(s.operations,r)}finally{s.isActive=!1,ry.delete(r)}}}}(()=>W),j=k?async e=>{let t=await k(e)??{};return!1!==t.refetch&&await P(),t}:void 0,$=b?async e=>{let t=await b(e)??{};return!1!==t.refetch&&await P(),t}:void 0,N=_?async e=>{let t=await _(e)??{};return!1!==t.refetch&&await P(),t}:void 0,L=new rw(F,P,B);return{...I,getKey:w,syncMode:S,sync:{sync:e=>{let{begin:f,write:m,commit:k,collection:b}=e,_=!1;s.mount(),_=!0,W={collection:b,queryClient:s,queryKey:"function"==typeof t?t({}):t,getKey:w,begin:f,write:m,commit:k,updateCacheData:R};let I=(e=>{let{begin:f,write:m,commit:k,markReady:b,collection:_,metadata:I}=e,P=!1,Q=!1,R=new Set,W=new Map,B=new Map,j=Promise.resolve(),$=e=>I?.row.get(e)??_._state.syncedMetadata.get(e),N=e=>{let t=$(e),r=t?.queryCollection;if(!r||"object"!=typeof r)return new Set;let i=r.owners;return i&&"object"==typeof i?new Set(Object.keys(i)):new Set},L=(e,t)=>{if(!I)return;let r={...$(e)??{}};if(0===t.size){delete r.queryCollection,0===Object.keys(r).length?I.row.delete(e):I.row.set(e,r);return}I.row.set(e,{...r,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},U=(e,t)=>{if(e&&"object"==typeof e&&e.queryHash===t){if("until-revalidated"===e.mode)return{queryHash:t,mode:"until-revalidated"};if("ttl"===e.mode&&"number"==typeof e.expiresAt&&Number.isFinite(e.expiresAt))return{queryHash:t,mode:"ttl",expiresAt:e.expiresAt}}},z=e=>j=j.then(e,e),V=e=>{let t=B.get(e);t&&(clearTimeout(t),B.delete(e))},G=e=>{let t=A.get(e);if(t)return new Set(t);let r=new Set;for(let[t]of _._state.syncedData.entries()){let i=N(t);0!==i.size&&(q(t,i),i.has(e)&&r.add(t))}return r},J=async e=>{let t=A.get(e);if(t&&Array.from(t).every(e=>_.has(e))){let e=new Map;return t.forEach(t=>{let r=_.get(t),i=E.get(t);r&&i&&e.set(t,{value:r,owners:new Set(i)})}),e}let r=I?.row.scanPersisted;if(!r){let t=new Map;return G(e).forEach(e=>{let r=_.get(e),i=E.get(e);r&&i&&t.set(e,{value:r,owners:new Set(i)})}),t}let i=new Map;return(await r()).forEach(t=>{let r=t.metadata,s=r?.queryCollection;if(!s||"object"!=typeof s)return;let a=s.owners;if(!a||"object"!=typeof a)return;let n=new Set(Object.keys(a));0!==n.size&&(q(t.key,n),n.has(e)&&i.set(t.key,{value:t.value,owners:n}))}),i},H=async e=>{if(!I)return;let t=await J(e),r=[];f(),t.forEach(({value:t,owners:i},s)=>{i.delete(e),L(s,i),O(s,e)&&r.push(t)}
7),r.forEach(e=>{m({type:"delete",value:e})}),I.collection.delete(`${rg}${e}`),k(),A.delete(e)},Y=e=>{if("ttl"!==e.mode)return;V(e.queryHash);let t=setTimeout(()=>{B.delete(e.queryHash),z(async()=>{let t=U(I?.collection.get(`${rg}${e.queryHash}`),e.queryHash);!t||"ttl"!==t.mode||t.expiresAt>Date.now()||await H(e.queryHash)})},Math.max(0,e.expiresAt-Date.now()));B.set(e.queryHash,t)},Z=async()=>{if(!I)return;let e=I.collection.list(rg),t=Date.now();for(let{key:r,value:i}of e){let e=U(i,r.slice(rg.length));e&&("ttl"===e.mode&&e.expiresAt<=t?await H(e.queryHash):"ttl"===e.mode&&Y(e))}},X=e=>{if("function"==typeof t)return t(e);if("on-demand"!==S)return t;{let r=function(e){if(!e)return;let t={};return e.where&&(t.where=rf(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:rf(e.expression),direction:e.compareOptions.direction,nulls:e.compareOptions.nulls,stringSort:e.compareOptions.stringSort};return"locale"===e.compareOptions.stringSort?{...t,locale:e.compareOptions.locale,localeOptions:e.compareOptions.localeOptions}:t})),void 0!==e.limit&&(t.limit=e.limit),void 0!==e.offset&&(t.offset=e.offset),0===Object.keys(t).length?void 0:JSON.stringify(t)}(e);return void 0!==r?[...t,r]:t}},ee=I?.collection.list(rg),et=ee&&0!==ee.length?z(async()=>{try{await Z()}finally{Q=!0}}):(Q=!0,Promise.resolve()),er=(e,t)=>new Promise((r,i)=>{let s=e.subscribe(e=>{queueMicrotask(()=>{if(e.isSuccess||e.isError){s();let a=M.get(t);a?.delete(s),a?.size===0&&M.delete(t),e.isSuccess?r():i(e.error)}})}),a=M.get(t)??new Set;a.add(s),M.set(t,a)}),ei=(e={},i=r)=>{if(!Q)return et.then(()=>{let t=ei(e,i);return!0===t?void 0:t});let f=X(e),m=(0,rt.hashKey)(f),w={...v,loadSubsetOptions:function(e){let{subscription:t,...r}=e;return r}(e)};if(void 0!==U(I?.collection.get(`${rg}${m}`),m)&&R.add(m),V(m),"function"!=typeof t||f.length>=x.length&&x.every((e,t)=>ed(e,f[t]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(x)}, Got: ${JSON.stringify(f)}. This can cause stale cache issues.`),F.observers.has(m)){K.set(m,(K.get(m)||0)+1);let e=F.observers.get(m),t=e.getCurrentResult();return!!t.isSuccess||(t.isError?Promise.reject(t.error):void 0!==s.getQueryData(f)||er(e,m))}let k={...function(e){let t={};for(let r of rm)void 0!==e[r]&&(t[r]=e[r]);return t}({enabled:a,refetchInterval:n,retry:o,retryDelay:l,staleTime:c,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:p,refetchOnMount:y,networkMode:h}),...C,queryKey:f,queryFn:i,meta:w,structuralSharing:!0,notifyOnChangeProps:"all"},b=new rr.QueryObserver(s,k),S=s.getQueryCache().find({queryKey:f,exact:!0})?.gcTime,A=g??S;if(T.set(m,f),F.observers.set(m,b),void 0!==A?W.set(m,A):W.delete(m),K.set(m,(K.get(m)||0)+1),void 0!==s.getQueryData(f))return(P||_.subscriberCount>0)&&eo(b,m),!0;let E=er(b,m);return(P||_.subscriberCount>0)&&eo(b,m),E},es=(e,t,r)=>{let s=(0,rt.hashKey)(e);if("cleaned-up"===_.status)return;F.lastError=void 0,F.errorCount=0;let a=t.data,n=i?i(a):a;if(!Array.isArray(n)||n.some(e=>"object"!=typeof e))return void console.error(i?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof n} for queryKey ${JSON.stringify(e)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof n} for queryKey ${JSON.stringify(e)}`);let o=new Map(_._state.syncedData.entries()),l=void 0!==r,c=l?new Set(r.keys()):G(s);A.set(s,A.get(s)??new Set);let u=new Map;n.forEach(e=>{let t=w(e);u.set(t,e)}),f(),I&&I.collection.delete(`${rg}${s}`),c.forEach(e=>{let t=l?r.get(e)?.value:o.get(e);if(!t)return;let i=u.get(e);if(i)ed(t,i)||m({type:"update",value:i});else{let r=N(e);r.delete(s),L(e,r),O(e,s)&&m({type:"delete",value:t})}}),u.forEach((e,t)=>{let r,i,a=N(t);a.has(s)||(a.add(s),L(t,a)),(r=E.get(t)||new Set).add(s),E.set(t,r),(i=A.get(s)||new Set).add(t),A.set(s,i),o.has(t)||m({type:"insert",value:e})}),k(),R.delete(s),V(s),b()},ea=async(e,t)=>{let r=(0,rt.hashKey)(e),i=await J(r);"cleaned-up"!==_.status&&es(e,t,i)},en=e=>{let t=(0,rt.hashKey)(e);return r=>{if(r.isSuccess){if(_.deferDataRefresh)return void _.deferDataRefresh.then(()=>{let e=F.observers.get(t);e&&e.refetch().catch(()=>{})});if(R.has(t)){let i=s.getQueryCache().find({queryKey:e,exact:!0});if(i?.state.dataUpdateCount===0){r.isFetching||F.observers.get(t)?.refetch().catch(()=>{});return}ea(e,r).catch(t=>{console.error(`[QueryCollection] Error reconciling query ${String(e)}:`,t)})}else es(e,r)}else r.isError&&((r.errorUpdatedAt!==F.lastErrorUpdatedAt||r.error!==F.lastError)&&(F.lastError=r.error,F.errorCount++,F.lastErrorUpdatedAt=r.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(e)}:`,r.error),b())}},eo=(e,t)=>{if(!D.has(t)){let r=en(T.get(t)),i=e.subscribe(r);D.set(t,i);let s=e.getCurrentResult();(s.isSuccess||s.isError)&&r(s)}},el=()=>
7{F.observers.forEach(eo)},ec=()=>{D.forEach(e=>{e()}),D.clear()};P=!0;let eu=_.on("subscribers:change",({subscriberCount:e})=>{e>0?el():0===e&&ec()});if("eager"===S){let e=ei({});e instanceof Promise&&e.catch(()=>{})}else Q?b():et.then(()=>{b()});el(),F.observers.forEach((e,t)=>{en(T.get(t))(e.getCurrentResult())});let ep=e=>{M.get(e)?.forEach(e=>{e()}),M.delete(e)},ey=e=>{let t;D.get(e)?.(),D.delete(e),ep(e),V(e),R.delete(e);let r=(t=new Map,(A.get(e)??new Set).forEach(r=>{let i=E.get(r);if(!i)return;let s=new Set(i);s.delete(e),t.set(r,s)}),t),i=[];r.forEach((e,t)=>{0===e.size&&_.has(t)&&i.push(_.get(t))});let s=void 0!==I&&r.size>0,a=s||i.length>0;a&&f(),r.forEach((e,t)=>{0===e.size?E.delete(t):E.set(t,e),s&&L(t,e)}),i.length>0&&i.forEach(e=>{m({type:"delete",value:e})}),a&&k(),F.observers.delete(e),A.delete(e),T.delete(e),K.delete(e),W.delete(e)},eh=e=>{let t=K.get(e)||0,r=F.observers.get(e),i=W.get(e);if(t<=0&&(D.get(e)?.(),D.delete(e),ep(e)),r?.hasListeners())return void K.set(e,0);if(t>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${t} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:e}),void 0!==i&&I&&I?.row.scanPersisted){f(),I.collection.set(`${rg}${e}`,{queryHash:e,mode:i===1/0?"until-revalidated":"ttl",...i===1/0?{}:{expiresAt:Date.now()+i}}),k(),i!==1/0&&Y({queryHash:e,mode:"ttl",expiresAt:Date.now()+i}),D.get(e)?.(),D.delete(e),F.observers.delete(e),T.delete(e),K.set(e,0);return}ey(e)},ef=e=>{ey(e)},em=s.getQueryCache().subscribe(e=>{let t=e.query.queryHash;"removed"===e.type&&T.has(t)&&eh(t)});return{loadSubset:"eager"===S?void 0:ei,unloadSubset:"eager"===S?void 0:e=>{let t=X(e),r=(0,rt.hashKey)(t),i=(K.get(r)||0)-1;i<=0?(K.set(r,0),eh(r)):K.set(r,i)},cleanup:async()=>{eu(),ec(),B.forEach(e=>{clearTimeout(e)}),B.clear();let e=[...T.values()];for(let e of new Set([...F.observers.keys(),...A.keys()]))ef(e);em(),await Promise.all(e.map(async e=>{await s.cancelQueries({queryKey:e,exact:!0}),s.removeQueries({queryKey:e,exact:!0})}))}}})(e),P="function"==typeof I?{cleanup:I}:"object"==typeof I?I:{};return{...P,cleanup:()=>{try{P.cleanup?.()}finally{_&&(s.unmount(),_=!1)}}}}},onInsert:j,onUpdate:$,onDelete:N,utils:L}}({id:m,queryKey:(0,rk.dbQueryKey)(s,a),queryClient:i,getKey:o,compare:l,staleTime:c,gcTime:u,startSync:d,refetchInterval:p,refetchOnWindowFocus:!1,refetchOnReconnect:!0,refetchOnMount:"always",queryFn:async e=>n({signal:e.signal}),onInsert:y?async({transaction:e})=>(w(await Promise.all(e.mutations.map(async e=>{var t,r;let i,s=await y(e.modified);return s&&g&&(t=g,r=String(e.key),(i=rb.get(t))||(i=new Map,rb.set(t,i)),i.set(r,s)),s}))),{refetch:!1}):void 0,onUpdate:h?async({transaction:e})=>(w(await Promise.all(e.mutations.map(e=>h({key:String(e.key),original:e.original,modified:e.modified,changes:e.changes})))),{refetch:!1}):void 0,onDelete:f?async({transaction:e})=>{var t;return await Promise.all(e.mutations.map(e=>f({key:String(e.key),original:e.original}))),0!==(t=e.mutations.map(e=>String(e.key))).length&&g&&"ready"===g.status&&g.utils.writeBatch(()=>{for(let e of t)g.utils.writeDelete(e)}),{refetch:!1}}:void 0})),t.utils?r.utils=t.utils:r.utils={},r);return g=k,k},"takeInsertResult",0,r_],643436);class rv extends Error{constructor(e,t){super(`Row "${t}" is not present in collection "${e}"`),this.name="CollectionRowNotFoundError"}}async function rI(e,t){let r=e.get(t);if(r)return r;await e.preload();let i=e.get(t);if(!i)throw new rv(e.id,t);return i}async function rS(e,t,r){await rI(e,t);let i=e.update.bind(e)(t,r);await i.isPersisted.promise;let s=e.get(t);if(!s)throw new rv(e.id,t);return s}async function rC(e,t){await e.preload();let r=e.insert(t);await r.isPersisted.promise;let i=r_(e,t.id);if(!i)throw new rv(e.id,t.id);return i}async function rx(e,t){await e.preload(),e.utils.writeUpsert(t)}async function rF(e,t){await rI(e,t);let r=e.delete(t);await r.isPersisted.promise}function rT(e){let t=globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`draft-${e}-${t}`}e.s(["deleteCollectionRow",0,rF,"draftKey",0,rT,"insertCollectionRow",0,rC,"updateCollectionRow",0,rS,"upsertCollectionRow",0,rx],938603);var rA=e.i(143732);function rE(e,t){return{id:t.id,workspace_id:e,parent_id:t.parent_id,parent_type:t.parent_type,visibility:t.visibility??("user"===t.parent_type?"private":"workspace"),owner_user_id:t.owner_user_id??("user"===t.parent_type?t.parent_id:null),owner_group_id:t.owner_group_id??("group"===t.parent_type?t.parent_id:null),created_at:t.created_at,updated_at:t.updated_at??t.created_at,title:t.title,public_access:t.public_access??"off",external:t.external,root_block_id:t.root_block_id??null,is_template:t.is_template,tags:t.tags,folder_name:t.folder_name??null}}
7function rD(e,t,r,i){return(0,rA.resolveContentParentForCreate)({workspaceId:e,folderId:t,visibility:r,ownerMemberId:i})}async function rM(e,t){if("number"==typeof e||/^\d+$/.test(String(e)))throw Error("Legacy numeric document IDs are no longer supported");if(!t)throw Error("Document detail requires a workspace id");let r=String(t),i=String(e),a=(0,s.makeCoworkClient)(r),n=(await a.documents.get({workspaceId:r,documentId:i})).data,o=null;if("folder"===n.parent_type&&n.parent_id)try{o=(await a.folders.get({workspaceId:r,folderId:n.parent_id})).data.name}catch{o=null}return{...rE(r,n),folder_name:o}}async function rK(e,t={}){let r=String(e.workspace_id),i=rD(r,e.folder_id,e.visibility,e.owner_member_id),a=await rq({cowork:(0,s.makeCoworkClient)(r),workspaceId:r,title:e.title??"Untitled",parentType:i.parent_type,parentId:i.parent_id,trackCreation:t.trackCreation});return rE(r,a)}async function rq({cowork:e,workspaceId:t,title:r,parentType:i,parentId:s,trackCreation:a=!0}){let c=a?(0,l.beginFirstSessionAction)({workspaceId:t,step:"document_create",surface:"create_dialog"}):null;try{let u=await e.documents.create({workspaceId:t,title:r,parent_type:i,parent_id:s});return a&&((0,l.succeedFirstSessionAction)(c),(0,n.trackEvent)("document_created",{workspace_id:t,document_id:u.data.id}),(0,o.queueActivationMilestoneCompletion)({workspaceId:t,milestoneId:"first_document_created"})),u.data}catch(e){throw(0,l.failFirstSessionAction)(c,e),e}}async function rO(e){let t=String(e.workspaceId),r=(0,s.makeCoworkClient)(t),i=String(e.id),a=(await r.documents.update({workspaceId:t,documentId:i,title:e.data.title,is_template:e.data.is_template,public_access:e.data.public_access})).data;if(void 0!==e.data.folder_id){let s=rD(t,e.data.folder_id);a=(await r.documents.move({workspaceId:t,documentId:i,parent_type:s.parent_type,parent_id:s.parent_id})).data}let n=rE(t,a);return e.data.visibility?{...n,visibility:e.data.visibility}:n}let rP=(0,a.createQueryKeyFactory)("documents");function rQ(e){return b(d(e))}function rR(e,t){return _(d(t),e??null)}function rW(e){let r=d(e),s=f(e),a=b(r),n=b(s),{workspaceId:o}=(0,i.useActiveWorkspace)(),l=e??o,c=(0,t.useMemo)(()=>{if(!l)return[];let e=new Map(n.data.map(e=>[e.id,e.name]));return a.data.map(t=>{let r=rE(l,t);return{...r,folder_name:"folder"===r.parent_type&&r.parent_id?e.get(r.parent_id):void 0}})},[a.data,n.data,l]);return{...a,data:c,isPending:a.isPending||n.isPending,isLoading:a.isLoading||n.isLoading}}function rB(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=t.workspaceId??t.parent_id,i=await rq({cowork:e.client(r),workspaceId:r,title:t.title,parentType:t.parent_type,parentId:t.parent_id});return await rx(e.workspace(r).documents,i),{...i,_workspaceId:r}}})}function rj(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).documents;return{document:await rS(r,t.id,e=>{void 0!==t.data.title&&(e.title=t.data.title),void 0!==t.data.public_access&&(e.public_access=t.data.public_access),void 0!==t.data.is_template&&(e.is_template=t.data.is_template),void 0!==t.data.parent_type&&(e.parent_type=t.data.parent_type),void 0!==t.data.parent_id&&(e.parent_id=t.data.parent_id)}),workspaceId:t.workspaceId}}})}function r$(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).documents;return await rF(r,t.id),(0,n.trackEvent)("document_deleted",{workspace_id:t.workspaceId,document_id:t.id}),{id:t.id,workspaceId:t.workspaceId}}})}e.s(["DASHBOARD_QUERY_STALE_TIME_MS",()=>rH,"createDashboardViaRoute",()=>ip,"dashboardChartDetailQueryKey",()=>r0,"dashboardChartKeys",()=>rV,"dashboardChartListQueryKey",()=>rX,"dashboardDetailQueryKey",()=>rZ,"dashboardKeys",()=>rz,"fetchDashboard",()=>r2,"fetchDashboardCharts",()=>ie,"useBatchUpdateChartPositions",()=>iu,"useCreateDashboard",()=>r4,"useCreateDashboardChart",()=>il,"useDashboard",()=>r3,"useDashboardChart",()=>io,"useDashboardCharts",()=>ia,"useDashboards",()=>r5,"useDeleteDashboard",()=>r9,"useDeleteDashboardChart",()=>id,"useUpdateDashboard",()=>r6,"useUpdateDashboardChart",()=>ic],602668);var rN=e.i(37700),rL=e.i(580107);e.i(478539);var rU=e.i(495238);let rz=(0,a.createQueryKeyFactory)("dashboards"),rV=(0,a.createQueryKeyFactory)("dashboard-charts"),rG="no-workspace",rJ="no-user",rH=6e4;function rY(e,t){return[...rz.list(e??rG),t??rJ]}function rZ(e,t,r){return[...rz.detail(t),e??rG,r??rJ]}function rX(e,t,r){let i=[...rV.all,e??rG,t];return void 0===r?i:[...i,r??rJ]}function r0(e,t,r,i){let s=[...rV.detail(r),e??rG,t];return void 0===i?s:[...s,i??rJ]}async function r1(e){let t=(0,s.makeCoworkClient)(e);return(await t.dashboards.list({workspaceId:e})).data??[]}async function r2(e,t){let r=(0,s.makeCoworkClient)(e);return(await r.dashboards.get({workspaceId:e,dashboardId:t})).data??null}function r5(e){let{user:t}=(0,rU.useAuth)(),{workspaceId:r}=(0,i.useActiveWorkspace)(),s=e??r,a=t?.id??null;return(0,rN.useQuery)({queryKey:rY(s,a),queryFn:async()=>s?r1(s):[],enabled:!!s&&!!a,staleTime:rH,refetchOnMount:!0})}function r3(e,t){let{user:r}=(0,rU.useAuth)(),{workspaceId:s}=(0,i.useActiveWorkspace)(),a=t??s,n=e??null,o=r?.id??null;return(0,rN.useQuery)({queryKey:rZ(a,n??"none",o),queryFn:async()=>a&&n?r2(a,n):null,enabled:!!a&&!!n&&!!o,staleTime:rH,refetchOnMount:!0})}async function r8({workspaceId:e,name:t,parentType:r,parentId:i}){let a=(0,s.makeCoworkClient)(e),o=await a.dashboards.create({workspaceId:e,name:t,parent_type:r,parent_id:i});return(0,n.trackEvent)("dashboard_created",{workspace_id:e,dashboard_id:o.data.id}),o.data}async function r7(e,t){let r=(0,s.makeCoworkClient)(e);await r.dashboards.delete({workspaceId:e,dashboardId:t}),(0,n.trackEvent)("dashboard_deleted",{workspace_id:e,dashboard_id:t})}function r4(){let e=(0,rL.useQueryClient)(),{user:t}=(0,rU.useAuth)();return(0,r.useMutation)({mutationFn:async e=>{let t=e.workspaceId??e.parent_id;return{data:await r8({workspaceId:t,name:e.name,parentType:e.parent_type,parentId:e.parent_id}),workspaceId:t}},onSuccess:({data:r,workspaceId:i})=>{t?.id&&(e.setQueryData(rZ(i,r.id,t.id),r),e.setQueryData(rY(i,t.id),e=>!e||e.some(e=>
7e.id===r.id)?e:[r,...e])),e.invalidateQueries({queryKey:rz.list(i)})}})}function r6(){let e=(0,rL.useQueryClient)(),{user:t}=(0,rU.useAuth)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,s.makeCoworkClient)(e.workspaceId);return{data:(await t.dashboards.update({workspaceId:e.workspaceId,dashboardId:e.id,name:e.data.name,description:e.data.description,layout:e.data.layout})).data,workspaceId:e.workspaceId}},onSuccess:({data:r,workspaceId:i})=>{t?.id&&(e.setQueryData(rZ(i,r.id,t.id),r),e.setQueryData(rY(i,t.id),e=>e?.map(e=>e.id===r.id?r:e))),e.invalidateQueries({queryKey:rz.detail(r.id)}),e.invalidateQueries({queryKey:rz.list(i)})}})}function r9(){let e=(0,rL.useQueryClient)(),{user:t}=(0,rU.useAuth)();return(0,r.useMutation)({mutationFn:async e=>(await r7(e.workspaceId,e.id),{id:e.id,workspaceId:e.workspaceId}),onMutate:async({id:r,workspaceId:i})=>{let s=t?.id??null,a=s?rY(i,s):null;if(!a)return{previousDashboards:void 0,userId:s,workspaceId:i};await e.cancelQueries({queryKey:a});let n=e.getQueryData(a);return n&&e.setQueryData(a,n.filter(e=>e.id!==r)),{previousDashboards:n,userId:s,workspaceId:i}},onError:(t,r,i)=>{i?.previousDashboards!==void 0&&i.userId&&i.workspaceId&&e.setQueryData(rY(i.workspaceId,i.userId),i.previousDashboards)},onSettled:(t,r,{id:i,workspaceId:s},a)=>{a?.userId&&e.removeQueries({queryKey:rZ(s,i,a.userId),exact:!0}),e.invalidateQueries({queryKey:rz.list(s)})}})}async function ie(e,t){let r=(0,s.makeCoworkClient)(e);return(await r.dashboards.listCharts({workspaceId:e,dashboardId:t})).data??[]}async function it(e,t,r){let i=(0,s.makeCoworkClient)(e);return(await i.dashboards.getChart({workspaceId:e,dashboardId:t,chartId:r})).data}async function ir(e,t){let r=(0,s.makeCoworkClient)(e);return(await r.dashboards.createChart({workspaceId:e,dashboardId:t.dashboardId,name:t.name,type:t.type,table_id:t.tableId,config:t.config,position:t.position,order_key:t.orderKey}
7)).data}async function ii(e,t){let r=(0,s.makeCoworkClient)(e);return(await r.dashboards.updateChart({workspaceId:e,dashboardId:t.dashboardId,chartId:t.id,name:t.name,type:t.type,table_id:t.tableId,config:t.config,position:t.position,order_key:t.orderKey})).data}async function is(e,t){let r=(0,s.makeCoworkClient)(e);return await r.dashboards.deleteChart({workspaceId:e,dashboardId:t.dashboardId,chartId:t.id}),{id:t.id,dashboardId:t.dashboardId}}function ia({dashboardId:e,workspaceId:t}){let{user:r}=(0,rU.useAuth)(),{workspaceId:s}=(0,i.useActiveWorkspace)(),a=t??s,n=r?.id??null;return(0,rN.useQuery)({queryKey:rX(a,e,n),queryFn:async()=>a?ie(a,e):[],enabled:!!a&&!!e&&!!n,staleTime:rH,refetchOnMount:!0})}function io({dashboardId:e,id:t,workspaceId:r}){let{user:s}=(0,rU.useAuth)(),{workspaceId:a}=(0,i.useActiveWorkspace)(),n=r??a,o=s?.id??null;return(0,rN.useQuery)({queryKey:r0(n,e,t,o),queryFn:async()=>{if(!n)throw Error("Workspace is required");return it(n,e,t)},enabled:!!n&&!!o&&t.trim().length>0&&e.trim().length>0,staleTime:rH,refetchOnMount:!0})}function il(e){let t=(0,rL.useQueryClient)(),{user:s}=(0,rU.useAuth)(),{workspaceId:a}=(0,i.useActiveWorkspace)(),n=e??a;return(0,r.useMutation)({mutationFn:async e=>{if(!n)throw Error("Workspace is required");return ir(n,e)},onSuccess:(e,r)=>{n&&s?.id&&(t.setQueryData(r0(n,r.dashboardId,e.id,s.id),e),t.setQueryData(rX(n,r.dashboardId,s.id),t=>!t||t.some(t=>t.id===e.id)?t:[...t,e])),t.invalidateQueries({queryKey:rX(n,r.dashboardId)}),t.invalidateQueries({queryKey:rz.detail(r.dashboardId)})}})}function ic(e){let t=(0,rL.useQueryClient)(),{user:s}=(0,rU.useAuth)(),{workspaceId:a}=(0,i.useActiveWorkspace)(),n=e??a;return(0,r.useMutation)({mutationFn:async e=>{if(!n)throw Error("Workspace is required");return ii(n,e)},onSuccess:(e,r)=>{n&&s?.id&&(t.setQueryData(r0(n,r.dashboardId,e.id,s.id),e),t.setQueryData(rX(n,r.dashboardId,s.id),t=>t?.map(t=>t.id===e.id?e:t))),t.invalidateQueries({queryKey:r0(n,r.dashboardId,e.id)}),t.invalidateQueries({queryKey:rX(n,r.dashboardId)}),t.invalidateQueries({queryKey:rz.detail(r.dashboardId)})}})}function iu(e,t){let s=(0,rL.useQueryClient)(),{user:a}=(0,rU.useAuth)(),{workspaceId:n}=(0,i.useActiveWorkspace)(),o=t??n;return(0,r.useMutation)({mutationFn:async t=>{if(!o)throw Error("Workspace is required");return await Promise.all(t.map(({id:t,position:r})=>ii(o,{id:t,dashboardId:e,position:r}))),t},onSuccess:t=>{if(!o||!a?.id)return;let r=new Map(t.map(({id:e,position:t})=>[e,t]));s.setQueryData(rX(o,e,a.id),e=>e?.map(e=>{let t=r.get(e.id);return t?{...e,position:t}:e}))}})}function id(e){let t=(0,rL.useQueryClient)(),{user:s}=(0,rU.useAuth)(),{workspaceId:a}=(0,i.useActiveWorkspace)(),n=e??a;return(0,r.useMutation)({mutationFn:async e=>{if(!n)throw Error("Workspace is required");return is(n,e)},onSuccess:({id:e,dashboardId:r})=>{n&&s?.id&&(t.removeQueries({queryKey:r0(n,r,e,s.id),exact:!0}),t.setQueryData(rX(n,r,s.id),t=>t?.filter(t=>t.id!==e))),t.invalidateQueries({queryKey:rX(n,r)}),t.invalidateQueries({queryKey:rz.detail(r)})}})}async function ip({workspaceId:e,parentId:t,parentType:r,name:i,description:s,visibility:a,layout:n,ownerMemberId:o}){let l=String(e);if(!/^\d+$/.test(l)){let e=null!=t&&r?{parent_type:r,parent_id:String(t)}:(0,rA.resolveContentParentForCreate)({workspaceId:l,visibility:a,ownerMemberId:o});return r8({workspaceId:l,name:i||"Untitled Dashboard",parentType:e.parent_type,parentId:e.parent_id})}throw Error(`Dashboard creation for legacy numeric workspace "${l}" has no typed regional route. Pass a workspace public ID.`)}e.s(["documentBlocksKey",()=>ih],272893),e.i(60243);let iy=(0,a.createQueryKeyFactory)("blocks"),ih=e=>[...iy.all,"document",String(e)];e.s(["documentDetailKey",()=>ig,"useDocumentDetail",()=>iw],506715);let im=(0,a.createQueryKeyFactory)("documents"),ig=e=>[...im.detail(String(e)),"full"];function iw(e,t){let{workspaceId:r}=(0,i.useActiveWorkspace)(),a=t??r,n=String(e);return(0,rN.useQuery)({queryKey:ig(n),queryFn:async()=>{if(!a)throw Error("No workspace available");let e=(0,s.makeCoworkClient)(a),[t,r]=await Promise.all([e.documents.get({workspaceId:a,documentId:n}),e.documents.listBlocks({workspaceId:a,documentId:n,limit:500})]);return{document:t.data,blocks:r.data??[]}},enabled:!!a&&!!n,staleTime:6e4})}e.s(["fetchPdfRecordViaRoute",()=>i_,"pdfKeys",()=>iI,"updatePdfViaRoute",()=>iv,"useDeletePdf",()=>ix,"usePdfs",()=>iS,"useUploadPdf",()=>iC],434659);var ik=e.i(142533);function ib(e,t,r){var i,s;return i={id:t.id,parent_id:t.parent_id,parent_type:t.parent_type,created_at:t.created_at,updated_at:t.updated_at,name:t.name,page_count:t.page_count??null,size_bytes:t.size_bytes??null,mime_type:t.mime_type,is_template:t.is_template},s={visibility:t.visibility??("user"===t.parent_type?"private":"workspace"),owner_user_id:t.owner_user_id??("user"===t.parent_type?t.parent_id:null),owner_group_id:t.owner_group_id??("group"===t.parent_type?t.parent_id:null),description:t.description??null,...r},{id:i.id,workspace_id:e,parent_id:i.parent_id,parent_type:i.parent_type,visibility:"workspace",owner_user_id:null,owner_group_id:null,created_at:i.created_at,updated_at:i.updated_at??i.created_at,name:i.name,storage_path:null,page_count:i.page_count??null,size_bytes:i.size_bytes??null,mime_type:i.mime_type??"application/pdf",is_template:i.is_template,...s}}async function i_(e,t){if(!t)throw Error("workspaceId is required to load a PDF");let r=String(t),i=String(e),a=(0,s.makeCoworkClient)(r),n=(await a.pdfs.get({workspaceId:r,pdfId:i})).data,o=null;if("folder"===n.parent_type&&n.parent_id)try{o=(await a.folders.get({workspaceId:r,folderId:n.parent_id})).data.name}catch{o=null}return{...ib(r,n),description:n.description??null,folder_name:o,is_sealed:!1}}async function iv(e){let t=String(e.workspaceId);if(void 0!==e.data.page_count)throw Error("PDF page-count updates are not supported by the typed PDF client");let r=(0,s.makeCoworkClient)(t),i=String(e.id),a=(await r.pdfs.update({workspaceId:t,pdfId:i,name:e.data.name,is_template:e.data.is_template})).data;if(void 0!==e.data.folder_id){var n;let s=null==(n=e.data.folder_id)?{parent_type:"workspace",parent_id:t}:{parent_type:"folder",parent_id:String(n)};a=(await r.pdfs.move({workspaceId:t,pdfId:i,parent_type:s.parent_type,parent_id:s.parent_id})).data}let o=ib(t,a);return e.data.visibility?{...o,visibility:e.data.visibility}:o}let iI=(0,a.createQueryKeyFactory)("pdfs");function iS(e){return b(y(e))}function iC(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=t.workspaceId??t.parent_id,i=e.client(r),s=(0,l.beginFirstSessionAction)({workspaceId:r,step:"pdf_upload",surface:"sidebar"}),a=await i.pdfs.upload({workspaceId:r,file:t.file,name:t.name,parent_type:t.parent_type,parent_id:t.parent_id}).catch(e=>{throw(0,l.failFirstSessionAction)(s,e),e});(0,l.succeedFirstSessionAction)(s),(0,n.trackEvent)("pdf_uploaded",{workspace_id:r,pdf_id:a.data.id,file_size:t.file.size}),(0,ik.trackEventClient)({workspaceId:r,category:"entity",action:"pdf_uploaded",entityType:"pdf",entityId:a.data.id});try{await rx(e.workspace(r).pdfs,a.data)}catch(e){console.error("[PDFs] Uploaded PDF could not be added to the local catalog",{workspaceId:r,pdfId:a.data.id,error:e})}return{...a.data,_workspaceId:r}}})}function ix(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).pdfs;return await rF(r,t.id),(0,n.trackEvent)("pdf_deleted",{workspace_id:t.workspaceId,pdf_id:t.id}
7),(0,ik.trackEventClient)({workspaceId:t.workspaceId,category:"entity",action:"pdf_deleted",entityType:"pdf",entityId:t.id}),{id:t.id,workspaceId:t.workspaceId}}})}function iF(e,t,r){var i,s;return i={id:t.id,name:t.name,parent_id:t.parent_id,parent_type:t.parent_type,is_template:t.is_template,created_at:t.created_at,updated_at:t.updated_at},s={visibility:t.visibility??("user"===t.parent_type?"private":"workspace"),owner_user_id:t.owner_user_id??("user"===t.parent_type?t.parent_id:null),owner_group_id:t.owner_group_id??("group"===t.parent_type?t.parent_id:null),description:t.description??null,public_access:t.public_access,external:t.external,folder_name:t.folder_name??null,...r},{id:i.id,workspace_id:e,name:i.name,parent_id:i.parent_id,parent_type:i.parent_type,visibility:"workspace",owner_user_id:null,owner_group_id:null,is_template:i.is_template,scene_data:i.scene_data,scene_files:void 0,created_at:i.created_at,updated_at:i.updated_at??i.created_at,...s}}async function iT(e,t){if("number"==typeof e||/^\d+$/.test(String(e)))throw Error("Legacy numeric whiteboard IDs are no longer supported");if(!t)throw Error("Whiteboard detail requires a workspace id");let r=String(t),i=String(e),a=(0,s.makeCoworkClient)(r),n=(await a.whiteboards.get({workspaceId:r,whiteboardId:i})).data,o=null;if("folder"===n.parent_type&&n.parent_id)try{o=(await a.folders.get({workspaceId:r,folderId:n.parent_id})).data.name}catch{o=null}return{...iF(r,n),folder_name:o}}async function iA(e){var t,r,i;let a=String(e.workspace_id),n=(t=e.folder_id,r=e.visibility,i=e.owner_member_id,(0,rA.resolveContentParentForCreate)({workspaceId:a,folderId:t,visibility:r,ownerMemberId:i})),o=await iE({cowork:(0,s.makeCoworkClient)(a),workspaceId:a,name:e.name||"Untitled",parentType:n.parent_type,parentId:n.parent_id});return iF(a,o)}async function iE({cowork:e,workspaceId:t,name:r,parentType:i,parentId:s}){let a=await e.whiteboards.create({workspaceId:t,name:r,parent_type:i,parent_id:s});return(0,n.trackEvent)("whiteboard_created",{workspace_id:t,whiteboard_id:a.data.id}),(0,o.queueActivationMilestoneCompletion)({workspaceId:t,milestoneId:"first_whiteboard_created"}),a.data}e.s(["createWhiteboardViaRoute",()=>iA,"fetchWhiteboardRecordViaRoute",()=>iT,"useCreateWhiteboard",()=>iK,"useDeleteWhiteboard",()=>iq,"useWhiteboards",()=>iM,"whiteboardKeys",()=>iD],355129);let iD=(0,a.createQueryKeyFactory)("whiteboards");function iM(e){return b(p(e))}function iK(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=t.workspaceId??t.parent_id,i=await iE({cowork:e.client(r),workspaceId:r,name:t.name||"Untitled Whiteboard",parentType:t.parent_type,parentId:t.parent_id});return await rx(e.workspace(r).whiteboards,i),{...i,_workspaceId:r}}})}function iq(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).whiteboards;return await rF(r,t.id),(0,n.trackEvent)("whiteboard_deleted",{workspace_id:t.workspaceId,whiteboard_id:t.id}),{id:t.id,workspaceId:t.workspaceId}}})}e.s(["createDatabaseViaRoute",()=>iW,"databaseKeys",()=>iN,"databaseListKeys",()=>iO,"fetchDatabaseRecordViaRoute",()=>iQ,"fetchDatabaseTablesRoute",()=>iR,"updateDatabaseViaRoute",()=>ij,"useCreateDatabase",()=>iL,"useDatabaseList",()=>i$,"useDeleteDatabase",()=>iU],230605),e.i(143092);let iO={all:["database-list"],lists:()=>["database-list","list"],list:e=>[...iO.lists(),e??"none"],details:()=>["database-list","detail"],detail:e=>[...iO.details(),e??"none"]};function iP(e,t,r){return{id:t.id,workspace_id:e,parent_id:t.parent_id,parent_type:t.parent_type,visibility:"workspace",owner_user_id:null,owner_group_id:null,created_at:t.created_at,updated_at:t.updated_at??t.created_at,name:t.name,table_count:0,...r}}async function iQ(e,t){let r=(0,s.makeCoworkClient)(t),i=(await r.databases.get({workspaceId:t,databaseId:e})).data,a=null;if("folder"===i.parent_type)try{a=(await r.folders.get({workspaceId:t,folderId:i.parent_id})).data.name}catch{a=null}return{...iP(t,{id:i.id,parent_id:i.parent_id,parent_type:i.parent_type,created_at:i.created_at,updated_at:i.updated_at,name:i.name}),parent_name:a}}async function iR(e,t){let r=(0,s.makeCoworkClient)(e);return((await r.databases.listTables({workspaceId:e,databaseId:t})).data??[]).map(e=>({id:String(e.id),name:e.name}))}
7async function iW(e){let t=e.workspace_id,r=(0,rA.resolveContentParentForCreate)({workspaceId:t,folderId:e.folder_id,visibility:e.visibility,ownerMemberId:e.owner_member_id}),i=await iB({cowork:(0,s.makeCoworkClient)(t),workspaceId:t,name:e.name||"Untitled Database",parentType:r.parent_type,parentId:r.parent_id});return iP(t,i)}async function iB({cowork:e,workspaceId:t,name:r,parentType:i,parentId:s}){let a=await e.databases.create({workspaceId:t,name:r,parent_type:i,parent_id:s});return(0,n.trackEvent)("database_created",{workspace_id:t,database_id:a.data.id}),(0,o.queueActivationMilestoneCompletion)({workspaceId:t,milestoneId:"first_database_created"}),a.data}async function ij(e){let t=(0,s.makeCoworkClient)(e.workspaceId),r=await t.databases.update({workspaceId:e.workspaceId,databaseId:e.id,name:e.data.name});return iP(e.workspaceId,r.data,{visibility:e.data.visibility??"workspace"})}function i$(e){let r=b(h(e)),i=b(f(e)),s=r.refetch,a=i.refetch,n=(0,t.useCallback)(()=>{s(),a()},[s,a]),o=(0,t.useMemo)(()=>{if(!e)return[];let t=new Map(i.data.map(e=>[e.id,e.name]));return r.data.map(r=>iP(e,r,{folder_name:"folder"===r.parent_type&&r.parent_id?t.get(r.parent_id):void 0}))},[r.data,i.data,e]);return{...r,data:o,isPending:r.isPending||i.isPending,isLoading:r.isLoading||i.isLoading,isError:r.isError||i.isError,error:r.error??i.error,refetch:n}}let iN=(0,a.createQueryKeyFactory)("database-list");function iL(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=t.workspaceId??t.parent_id,i=await iB({cowork:e.client(r),workspaceId:r,name:t.name||"Untitled Database",parentType:t.parent_type,parentId:t.parent_id});return await rx(e.workspace(r).databases,i),{...i,_workspaceId:r}}})}function iU(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).databases;return await rF(r,t.id),(0,n.trackEvent)("database_deleted",{workspace_id:t.workspaceId,database_id:t.id}),{id:t.id,workspaceId:t.workspaceId}}})}(0,a.createQueryKeyFactory)("database-tables"),(0,a.createQueryKeyFactory)("database-views"),e.s(["findWorkspaceMemberByEmail",()=>iG,"useRemoveWorkspaceMember",()=>iX,"useSearchWorkspaceMembers",()=>i0,"useUpdateWorkspaceMemberRole",()=>iZ,"useWorkspaceMemberProfile",()=>iY,"useWorkspaceMembers",()=>iJ,"useWorkspaceMembersWithProfiles",()=>iH,"workspaceMemberKeys",()=>iz],583818);let iz=(0,a.createQueryKeyFactory)("workspace_members");async function iV(e){let t=(0,s.makeCoworkClient)(e),r=[],i=0;for(;;){let s=await t.workspaces.listMembers({workspaceId:e,limit:100,offset:i});if(r.push(...s.data),0===s.data.length||r.length>=s.meta.total)return r;i+=s.data.length}}async function iG(e,t){let r=(0,s.makeCoworkClient)(e),i=t.toLowerCase(),a=0;for(;;){let t=await r.workspaces.listMembers({workspaceId:e,limit:20,offset:a}),s=t.data.find(e=>e.email?.toLowerCase()===i);if(s)return s;if(a+=t.data.length,0===t.data.length||a>=t.meta.total)return null}}function iJ(e){let{workspaceId:t}=(0,i.useActiveWorkspace)(),r=e??t;return(0,rN.useQuery)({queryKey:["workspace_members","list",r??"none"],queryFn:async()=>r?iV(r):[],enabled:!!r})}function iH({workspaceId:e,enabled:t=!0}={}){let{workspaceId:r}=(0,i.useActiveWorkspace)(),s=e??r;return(0,rN.useQuery)({queryKey:["workspace_members","with_profiles",s??"none"],queryFn:async()=>s?iV(s):[],enabled:t&&!!s,staleTime:3e4})}function iY({workspaceId:e,userId:t,enabled:r=!0}){let{workspaceId:a}=(0,i.useActiveWorkspace)(),n=e??a;return(0,rN.useQuery)({queryKey:["workspace_members","profile",n??"none",t??"none"],queryFn:async()=>{if(!n||!t)return null;let e=(0,s.makeCoworkClient)(n),r=await e.workspaces.listMembers({workspaceId:n,userIds:[t],limit:1});return r.data?.[0]??null},enabled:r&&!!n&&!!t,staleTime:3e4})}function iZ(){let e=(0,rL.useQueryClient)();return(0,r.useMutation)({mutationFn:async({workspaceId:e,memberId:t,role:r})=>{let i=(0,s.makeCoworkClient)(e);return(await i.workspaces.updateMember({workspaceId:e,userId:t,role:r})).data},onSuccess:(t,{workspaceId:r})=>{let i=e=>e?.map(e=>e.id===t.id?t:e);e.setQueryData(["workspace_members","list",r],i),e.setQueryData(["workspace_members","with_profiles",r],i),e.invali
7dateQueries({queryKey:["workspace_members","list",r]}),e.invalidateQueries({queryKey:["workspace_members","with_profiles",r]})}})}function iX(){let e=(0,rL.useQueryClient)();return(0,r.useMutation)({mutationFn:async({workspaceId:e,memberId:t})=>{let r=(0,s.makeCoworkClient)(e);await r.workspaces.removeMember({workspaceId:e,userId:t})},onSuccess:(t,{workspaceId:r,memberId:i})=>{let s=e=>e?.filter(e=>e.id!==i);e.setQueryData(["workspace_members","list",r],s),e.setQueryData(["workspace_members","with_profiles",r],s),e.invalidateQueries({queryKey:["workspace_members"]})}})}function i0({search:e,excludeUserIds:t=[],workspaceId:r}){let{workspaceId:s}=(0,i.useActiveWorkspace)(),a=r??s;return(0,rN.useQuery)({queryKey:["workspace_members","search",a??"none",e,t],queryFn:async()=>{if(!a)return[];let r=(await iV(a)).filter(e=>!t.includes(e.id));if(!e.trim())return r;let i=e.toLowerCase();return r.filter(e=>`${e.display_name??""} ${e.email??""}`.toLowerCase().includes(i))},enabled:!!a,staleTime:3e4})}function i1(e,r){let i=(0,c.useDbRegistrySafe)(),s=(0,c.useDbWorkspaceId)(),a=r??s;return t.useMemo(()=>i&&a&&e?i.messages(a,e):null,[e,i,a])}function i2(e,r,i){let s=(0,c.useDbRegistrySafe)(),a=(0,c.useDbWorkspaceId)(),n=i??a;return t.useMemo(()=>s&&n&&e&&r?s.comments(n,e,r):null,[r,e,s,n])}e.s(["CONVERSATION_QUERY_GC_TIME_MS",()=>i7,"CONVERSATION_QUERY_STALE_TIME_MS",()=>i8,"conversationKeys",()=>i5,"conversationMessageKeys",()=>i3,"fetchConversationRecord",()=>i4,"useConversation",()=>i9,"useConversationList",()=>i6,"useConversationMessages",()=>se,"useCreateConversation",()=>st,"useDeleteConversation",()=>si,"useUpdateConversation",()=>sr],187177),e.s(["useCommentsCollection",()=>i2,"useMessagesCollection",()=>i1],798574);let i5={all:["conversations"],lists:()=>["conversations","list"],listPrefix:e=>[...i5.lists(),String(e??"none")],list:(e,t)=>[...i5.listPrefix(e),t??"no-user"],details:()=>["conversations","detail"],detailPrefix:e=>[...i5.details(),String(e??"none")],detail:(e,t,r)=>[...i5.detailPrefix(e),String(t??"none"),r??"no-user"]},i3={all:["conversation-messages"],listPrefix:e=>[...i3.all,"list",e],list:(e,t,r)=>[...i3.listPrefix(e),String(t??"none"),r??"no-user"]},i8=3e4,i7=6e5;async function i4(e,t){try{let r=(0,s.makeCoworkClient)(t);return(await r.chat.getConversation({workspaceId:t,conversationId:e})).data??null}catch(e){if(e&&"object"==typeof e&&"status"in e&&404===e.status)return null;throw e}}function i6(e,t,r={}){let i=e?String(e):null,{user:s}=(0,rU.useAuth)(),a=t??s?.id,n=(r.enabled??!0)&&!!i&&!!a,o=g(i);return b(n?o:null)}function i9(e,t,r={}){let{workspaceId:s}=(0,i.useActiveWorkspace)(),{user:a}=(0,rU.useAuth)(),n=t?String(t):s,o=e?String(e):null,l=(r.enabled??!0)&&!!o&&!!a?.id,c=g(n);return _(l?c:null,o)}function se(e,t){let{workspaceId:r}=(0,i.useActiveWorkspace)(),{user:s}=(0,rU.useAuth)(),a=t?String(t):r,n=i1(e?String(e):null,a);return b(s?.id?n:null)}function st(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).conversations,i=new Date().toISOString(),s=await rC(r,{id:rT("conversation"),title:t.title||"New Conversation",context_type:t.context_type,context_id:t.context_id,model:t.model,system_prompt:t.system_prompt,is_ai_processing:!1,visibility:"sidebar",created_at:i,updated_at:i});return(0,n.trackEvent)("conversation_created",{conversation_id:s.id,workspace_id:t.workspaceId,source:"new_button"}),{data:s,workspaceId:t.workspaceId}}})}function sr(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>{let r=e.workspace(t.workspaceId).conversations;return{data:await rS(r,t.id,e=>{void 0!==t.title&&(e.title=t.title)}),workspaceId:t.workspaceId}}})}function si(){let e=(0,c.useDbRegistry)();return(0,r.useMutation)({mutationFn:async t=>(await rF(e.workspace(t.workspaceId).conversations,t.id),(0,n.trackEvent)("conversation_deleted",{conversation_id:t.id,message_count:0,workspace_id:t.workspaceId}),{id:t.id,workspaceId:t.workspaceId})})}},237770,e=>{"use strict";e.s(["queryOptions",0,function(e){return e}])},751019,74432,e=>{"use strict";e.s(["TaskPriority",()=>O,"TaskResolution",()=>P,"TaskStatus",()=>K,"TaskType",()=>Q,"fetchWorkspaceTasksRoute",()=>M,"getTaskListQueryOptions",()=>j,"getTaskPriorityColor",()=>ei,"getTaskPriorityLabel",()=>er,"getTaskStatusLabel",()=>es,"isTaskActiveWorkStatus",()=>q,"mapTaskToRelations",()=>B,"mergeTaskContext",()=>A,"pendingTaskCountKey",()=>W,"taskKeys",()=>R,"useArchiveTask",()=>X,"useCreateTask",()=>J,"useDeleteTask",()=>Z,"usePendingTaskCount",()=>N,"usePinTask",()=>ee,"useResolveTask",()=>H,"useTask",()=>L,"useTasks",()=>$,"useUnpinTask",()=>et,"useUpdateTask",()=>Y],751019);var t,r,i,s=e.i(982472),a=e.i(237770),n=e.i(898665),o=e.i(580107);e.i(478539);var l=e.i(495238),c=e.i(623128);e.i(60243);var u=e.i(599177),d=e.i(8551),p=e.i(221745),y=e.i(593463),h=e.i(480723),f=e.i(723103),m=e.i(485407);e.s(["filterTaskRows",()=>w,"useTaskRowSource",()=>
7k],74432);let g=new Set(["open","pending","in_progress","blocked"]);function w(e,t,r){let i=e.filter(e=>{var i;return(!(i=t.status)||(Array.isArray(i)?i:[i]).some(t=>"pending"===t?g.has(e.status):"someday"===t?"in_progress"===e.status:e.status===t))&&(!t.type||e.type===t.type)&&(!t.assignee||e.assigned_member_id===t.assignee)&&(!t.groupId||e.group_id===t.groupId)&&function(e,t,r){switch(t.board){case"assigned":return!!r&&e.assigned_member_id===r&&("group"!==e.parent_type||!0===e.pinned);case"team":return t.groupId?e.group_id===t.groupId:!!e.group_id;case"shared":case"all":case void 0:default:return!0;case"mine":return"group"!==e.parent_type||!0===e.pinned}}(e,t,r)}),s=t.offset??0,a="number"==typeof t.limit&&t.limit>0?s+t.limit:void 0;return 0===s&&void 0===a?i:i.slice(s,a)}function k(e,t){let r=(0,f.useDbRegistrySafe)(),i=(0,f.useDbWorkspaceId)(),a=e??i;return s.useMemo(()=>r&&a?"shared"===t?r.taskBoard(a,"shared"):r.workspace(a).tasks:null,[t,r,a])}var b=e.i(938603),_=e.i(21775),v=((t=v||{}).Pending="pending",t.Open="open",t.InProgress="in_progress",t.Blocked="blocked",t.Someday="someday",t.Resolved="resolved",t.Expired="expired",t.Cancelled="cancelled",t),I=((r=I||{}).Low="low",r.Normal="normal",r.High="high",r.Urgent="urgent",r),S=((i=S||{}).Completed="completed",i.WontDo="wont_do",i.Duplicate="duplicate",i.Invalid="invalid",i);function C(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function x(e){return"string"==typeof e&&e.trim()?e:null}function F(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function T(e){let t=C(e?.framework);return C(t.fields)}function A(e,t){let r,i,s=(r={},void 0!==t.isFrog&&(r.is_frog=t.isFrog),void 0!==t.dailyRank&&(r.daily_rank=t.dailyRank),void 0!==t.size&&(r.size=t.size),void 0!==t.scheduledFor&&(r.scheduled_for=t.scheduledFor),void 0!==t.estimatedPomodoros&&(r.estimated_pomodoros=t.estimatedPomodoros),void 0!==t.completedPomodoros&&(r.completed_pomodoros=t.completedPomodoros),void 0!==t.storyPoints&&(r.story_points=t.storyPoints),void 0!==t.columnId&&(r.column_id=t.columnId),void 0!==t.columnPosition&&(r.column_position=t.columnPosition),void 0!==t.deferUntil&&(r.defer_until=t.deferUntil),void 0!==t.paraCategory&&(r.para_category=t.paraCategory),void 0!==t.color&&(r.color=t.color),r);if(!(Object.keys(s).length>0))return;let a=(i={...C(e)},delete i.cowork_status,i),n=C(a.framework),o=C(n.fields);return{...a,framework:{...n,fields:{...o,...s}}}}function E(e){var t,r;return{is_frog:function(e,t=!1){return"boolean"==typeof e?e:t}(e.is_frog),daily_rank:F(e.daily_rank),size:"small"===(t=e.size)||"medium"===t||"large"===t?t:null,scheduled_for:x(e.scheduled_for),estimated_pomodoros:F(e.estimated_pomodoros),completed_pomodoros:F(e.completed_pomodoros)??0,story_points:F(e.story_points),column_id:x(e.column_id),column_position:F(e.column_position)??0,defer_until:x(e.defer_until),para_category:"project"===(r=e.para_category)||"area"===r||"resource"===r||"archive"===r?r:null,color:x(e.color),framework_data:e}}async function D(e){var t=`Cannot list tasks for workspace "${e.workspaceId}" through the legacy Next route.`;throw Error(`TODO: legacy task hook adapters must use typed Wyatt clients; the flat /api/workspaces task route is no longer available from web/lib/cowork/hooks/useTasks. ${t}`)}async function M(e){let t=String(e.workspaceId);if(/^\d+$/.test(t)||e.scopedToCurrentUser)return D(e);let r=(0,u.makeCoworkClient)(t),i=e.limit??50,s=((await r.tasks.list({workspaceId:t,status:e.status,onboardingOnly:e.onboardingOnly,limit:i})).data??[]).map(e=>{let r,i;return r=null==e.group_id?null:String(e.group_id).trim()||null,i=E(T(e.context)),{id:e.id,workspace_id:t,parent_type:e.parent_type,parent_id:e.parent_id,user_id:null==e.assigned_member_id?null:String(e.assigned_member_id),group_id:r,type:e.type,title:e.title,description:e.description??null,status:function(e){switch(e){case"resolved":return"resolved";case"open":default:return"pending";case"in_progress":return"in_progress";case"blocked":return"blocked";case"cancelled":return"cancelled"}}(e.status),blocking:e.blocking,priority:function(e){switch(e){case"low":return"low";case"medium":default:return"normal";case"high":return"high";case"urgent":return"urgent"}}(e.priority),due_at:e.due_at??null,created_by:null,conversation_id:e.conversation_id??null,context:{...e.context??{},cowork_status:e.status},resolved_by:null,resolved_at:e.resolved_at??null,resolution:function(e){if(!e)return null;switch(e){case"completed":return"completed";case"wont_do":return"wont_do";case"duplicate":return"duplicate";
7case"invalid":return"invalid";default:return null}}(e.resolution),resolution_data:e.resolution_data??null,created_at:e.created_at,updated_at:e.updated_at,is_important:e.is_important??!1,is_urgent:e.is_urgent??"urgent"===e.priority,is_frog:i.is_frog,daily_rank:i.daily_rank,size:i.size,scheduled_for:i.scheduled_for,estimated_pomodoros:i.estimated_pomodoros,completed_pomodoros:i.completed_pomodoros,story_points:i.story_points,sprint_id:e.sprint_id??null,column_id:i.column_id,column_position:i.column_position,contexts:e.contexts??[],waiting_for:e.waiting_for??null,defer_until:i.defer_until,para_category:i.para_category,framework_data:i.framework_data,color:i.color,capabilities:e.capabilities,pinned:e.pinned??!1,conversation:null}});return void 0!==e.conversationId&&(s=s.filter(t=>t.conversation_id===e.conversationId)),e.onboardingOnly&&(s=s.filter(e=>!!e.context?.onboarding)),s.slice(0,i)}let K={Pending:"pending",Open:"open",InProgress:"in_progress",Blocked:"blocked",Someday:"someday",Resolved:"resolved",Expired:"expired",Cancelled:"cancelled"};function q(e){return(0,_.isTaskActiveStatus)(e)}let O={Low:"low",Normal:"normal",Medium:"medium",High:"high",Urgent:"urgent"},P={Completed:"completed",WontDo:"wont_do",Duplicate:"duplicate",Invalid:"invalid",Deferred:"wont_do"},Q={Approval:"approval",Review:"review",AccessRequest:"access_request",InputNeeded:"input_needed",Action:"action"},R=(0,d.createQueryKeyFactory)("tasks"),W=e=>["tasks","pending_count",e];function B(e,t){let r=E(T(e.context));return{id:e.id,workspace_id:t,parent_type:e.parent_type,parent_id:e.parent_id,user_id:e.assigned_member_id??null,group_id:e.group_id??null,type:e.type,title:e.title,description:e.description??null,status:"open"===e.status?"pending":e.status,blocking:e.blocking,priority:e.priority,due_at:e.due_at??null,created_by:null,conversation_id:null,context:{...e.context??{},cowork_status:e.status},resolved_by:null,resolved_at:e.resolved_at??null,resolution:e.resolution??null,resolution_data:null,created_at:e.created_at,updated_at:e.updated_at,is_important:e.is_important??!1,is_urgent:e.is_urgent??"urgent"===e.priority,is_frog:r.is_frog,daily_rank:r.daily_rank,size:r.size,scheduled_for:r.scheduled_for,estimated_pomodoros:r.estimated_pomodoros,completed_pomodoros:r.completed_pomodoros,story_points:r.story_points,sprint_id:e.sprint_id??null,column_id:r.column_id,column_position:r.column_position,contexts:e.contexts??[],waiting_for:e.waiting_for??null,defer_until:r.defer_until,para_category:r.para_category,framework_data:r.framework_data,color:r.color,capabilities:e.capabilities,pinned:e.pinned??!1,conversation:null}}function j({workspaceId:e,userId:t,...r}){let i=null!=e&&0!==e&&""!==e?String(e):"none",s=t?.trim()||"none";return(0,a.queryOptions)({queryKey:[...R.list(i),s,r],queryFn:async()=>{if("none"===i||"none"===s)return[];let e=(0,u.makeCoworkClient)(i);return((await e.tasks.list({workspaceId:i,...r,status:"string"==typeof r.status?r.status:r.status?[...r.status]:void 0})).data??[]).map(e=>B(e,i))}})}function $(e){let{workspaceId:t}=(0,c.useActiveWorkspace)(),{user:r}=(0,l.useAuth)(),i=e?.workspaceId,a=null!=i&&0!==i&&""!==i?String(i):t,n=e?.userId??r?.id??null,o=e?.enabled!==!1&&!!a&&!!n,u=k(a,e?.board),d=(0,m.useCollectionRows)(o?u:null),p=e?.status,y=e?.type,h=e?.assignee,f=e?.board,g=e?.groupId,b=e?.limit,_=e?.offset,v=(0,s.useMemo)(()=>o&&a?w(d.data,{status:p,type:y,assignee:h,board:f,groupId:g,limit:b,offset:_},n).map(e=>B(e,a)):[],[h,f,g,o,b,_,d.data,p,y,n,a]);return{...d,data:v}}function N(e,t={}){let{workspaceId:r}=(0,c.useActiveWorkspace)(),i=e??r,a=(t.enabled??!0)&&!!i,n=k(i),o=(0,m.useCollectionRows)(a?n:null),l=(0,s.useMemo)(()=>a?o.data.filter(e=>(0,_.isTaskActiveStatus)(e.status)).length:0,[a,o.data]);return{...o,data:l}}function L(e,t){let r,{workspaceId:i}=(0,c.useActiveWorkspace)(),a=t??i,n=null!=e&&"object"==typeof e?e.taskId:e,o="number"==typeof n?Number.isFinite(n)&&n>0?String(n):null:(r=null!=n?String(n).trim():"")&&"0"!==r?r:null,l=k(a),u=(0,m.useCollectionRows)(o?l:null),d=(0,s.useMemo)(()=>{if(!o||!a)return null;let e=u.data.find(e=>e.id===o);return e?B(e,a):null},[o,u.data,a]);return{...u,data:d}}function U(e,t){return"taskId"in e&&e.taskId?{taskId:e.taskId,workspaceId:e.workspaceId}:{taskId:String(e.id),workspaceId:String(e.workspaceId??e.workspace_id??t??"")}}K.Pending,K.Resolved;let z={assigneeId:"assigned_member_id",completedPomodoros:"completed_pomodoros",dailyRank:"daily_rank",deferUntil:"defer_until",dueAt:"due_at",estimatedPomodoros:"estimated_pomodoros",isFrog:"is_frog",isImportant:"is_important",isUrgent:"is_urgent",paraCategory:"para_category",resolutionData:"resolution_data",scheduledFor:"scheduled_for",sprintId:"sprint_id",storyPoints:"story_points",waitingFor:"waiting_for",columnId:"column_id",columnPosition:"column_position"},V={assigneeId:"user_id",assigned_member_id:"user_id",completedPomodoros:"completed_pomodoros",dailyRank:"daily_rank",deferUntil:"defer_until",dueAt:"due_at",estimatedPomodoros:"estimated_pomodoros",isFrog:"is_frog",isImportant:"is_important",isUrgent:"is_urgent",paraCategory:"para_category",resolutionData:"resolution_data",scheduledFor:"scheduled_for",sprintId:"sprint_id",storyPoints:"story_points",waitingFor:"waiting_for",columnId:"column_id",columnPosition:"column_position"};function G(e){return Array.isArray(e)?[...e].sort():e}function J(){let e=(0,f.useDbRegistry)(),{user:t}=(0,l.useAuth)();return(0,n.useMutation)({mutationFn:async r=>{if(!t?.id)throw Error("Cannot create a task without an authenticated user.");let i=String(r.workspaceId),s=e.workspace(i).tasks,a=A(r.context,r)??r.context,n=new Date().toISOString(),o=(0,h.beginFirstSessionAction)({workspaceId:i,step:"task_create",surface:"tasks"}),l=await (0,b.insertCollectionRow)(s,{id:(0,b.draftKey)("task"),parent_type:"user",parent_id:t.id,title:r.title,de
7scription:r.description,priority:r.priority??"normal",type:r.type??"action",status:"open",blocking:!1,due_at:r.due_at??(r.dueAt?new Date(r.dueAt).toISOString():void 0),is_important:r.isImportant,is_urgent:r.isUrgent,contexts:r.contexts,waiting_for:r.waitingFor??void 0,sprint_id:r.sprintId??void 0,context:a,capabilities:{can_edit:!0,can_delete:!0,can_manage_access:!0,can_create:!1},assigned_member_id:r.assigned_member_id??r.assigneeId,group_id:r.group_id??(null==r.groupId||/^\d+$/.test(String(r.groupId))?void 0:String(r.groupId)),created_at:n,updated_at:n}).catch(e=>{throw(0,h.failFirstSessionAction)(o,e),e});(0,h.succeedFirstSessionAction)(o),(0,p.trackEvent)("task_created",{workspace_id:i,task_id:l.id,source:r.analytics?.source,has_due_date:!!l.due_at,has_assignee:!!l.assigned_member_id,priority:l.priority,framework:r.analytics?.framework});try{await e.refetchTaskBoards(i)}catch(e){console.error("[Tasks] Created task could not refresh the local board cache",{workspaceId:i,taskId:l.id,error:e})}return(0,y.queueActivationMilestoneCompletion)({workspaceId:i,milestoneId:"first_task_created"}),{...l,_workspaceId:i}}})}function H(){let e=(0,f.useDbRegistry)(),{workspaceId:t}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async r=>{let{taskId:i,workspaceId:s}=U(r,t),a=e.workspace(s).tasks,n=a.get(i)?.status,o=await (0,b.updateCollectionRow)(a,i,e=>{e.status="resolved",e.resolution=r.resolution,e.resolved_at=new Date().toISOString(),e.updated_at=new Date().toISOString()});return await e.refetchTaskBoards(s),r.resolution===P.Completed&&"resolved"!==n&&(0,p.trackEvent)("task_completed",{workspace_id:s,task_id:o.id}),n&&"resolved"!==n&&(0,p.trackEvent)("task_status_changed",{workspace_id:s,task_id:o.id,from_status:n,to_status:"resolved"}),{...o,_workspaceId:s}}})}function Y(){let e=(0,f.useDbRegistry)(),{workspaceId:t}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async r=>{var i;let s,{taskId:a,workspaceId:n}=U(r,t),o=e.workspace(n).tasks,l=o.get(a),c=(i=l?B(l,n):void 0,s=new Set(["analytics","id","taskId","workspaceId","workspace_id"]),[...new Set(Object.entries(r).filter(([e,t])=>!s.has(e)&&void 0!==t).filter(([e,t])=>"groupId"!==e||void 0!==(null==t||/^\d+$/.test(String(t))?void 0:String(t))).filter(([e,t])=>{if(!i)return!0;let r=i[V[e]??e];return JSON.stringify(G(t))!==JSON.stringify(G(r))}).map(([e])=>z[e]??e))].sort()),u=l?.status,d=await (0,b.updateCollectionRow)(o,a,e=>{void 0!==r.title&&(e.title=r.title),void 0!==r.description&&(e.description=r.description??void 0),void 0!==r.status&&(e.status=r.status),void 0!==r.priority&&(e.priority=r.priority),void 0!==r.dueAt&&(e.due_at=r.dueAt??void 0),void 0!==r.isImportant&&(e.is_important=r.isImportant),void 0!==r.isUrgent&&(e.is_urgent=r.isUrgent),void 0!==r.contexts&&(e.contexts=r.contexts),void 0!==r.waitingFor&&(e.waiting_for=r.waitingFor??""),void 0!==r.sprintId&&(e.sprint_id=r.sprintId??""),void 0!==r.assigned_member_id&&(e.assigned_member_id=r.assigned_member_id),void 0!==r.assigneeId&&(e.assigned_member_id=r.assigneeId);let t=A(e.context,r);t&&(e.context=t)});return await e.refetchTaskBoards(n),c.length>0&&(0,p.trackEvent)("task_updated",{workspace_id:n,task_id:d.id,fields_changed:c}),r.status&&u&&u!==r.status&&(0,p.trackEvent)("task_status_changed",{workspace_id:n,task_id:d.id,from_status:u,to_status:r.status}),{...d,_workspaceId:n}}})}function Z(){let e=(0,f.useDbRegistry)(),{workspaceId:t}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async r=>{let{taskId:i,workspaceId:s}=U(r,t);return await (0,b.deleteCollectionRow)(e.workspace(s).tasks,i),await e.refetchTaskBoards(s),(0,p.trackEvent)("task_deleted",{workspace_id:s,task_id:i,framework:r.analytics?.framework}),{id:i,_workspaceId:s}}})}function X(){let e=(0,f.useDbRegistry)(),{workspaceId:t}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async r=>{let{taskId:i,workspaceId:s}=U(r,t),a=e.workspace(s).tasks,n=a.get(i)?.status,o=await (0,b.updateCollectionRow)(a,i,e=>{e.status="cancelled",e.resolution=void 0,e.resolved_at=void 0,e.updated_at=new Date().toISOString()});return await e.refetchTaskBoards(s),n&&"cancelled"!==n&&(0,p.trackEvent)("task_status_changed",{workspace_id:s,task_id:o.id,from_status:n,to_status:"cancelled"}),{...o,_workspaceId:s}}})}function ee(){let e=(0,o.useQueryClient)(),t=(0,f.useDbRegistry)(),{workspaceId:r}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async e=>{let t=e.workspaceId??r;if(!t)throw Error("workspaceId is required to pin a task");let i=(0,u.makeCoworkClient)(t);return await i.tasks.pin({workspaceId:t,taskId:e.taskId}),{taskId:e.taskId,workspaceId:t}},onSettled:async r=>{if(e.invalidateQueries({queryKey:R.all}
7),e.invalidateQueries({queryKey:["group_tasks"]}),r?.workspaceId)try{await t.refetchTaskBoards(r.workspaceId)}catch(e){console.error("[Tasks] Pin could not refresh the local board cache",{workspaceId:r.workspaceId,taskId:r.taskId,error:e})}}})}function et(){let e=(0,o.useQueryClient)(),t=(0,f.useDbRegistry)(),{workspaceId:r}=(0,c.useActiveWorkspace)();return(0,n.useMutation)({mutationFn:async e=>{let t=e.workspaceId??r;if(!t)throw Error("workspaceId is required to unpin a task");let i=(0,u.makeCoworkClient)(t);return await i.tasks.unpin({workspaceId:t,taskId:e.taskId}),{taskId:e.taskId,workspaceId:t}},onSettled:async r=>{if(e.invalidateQueries({queryKey:R.all}),e.invalidateQueries({queryKey:["group_tasks"]}),r?.workspaceId)try{await t.refetchTaskBoards(r.workspaceId)}catch(e){console.error("[Tasks] Unpin could not refresh the local board cache",{workspaceId:r.workspaceId,taskId:r.taskId,error:e})}}})}function er(e){return({low:"Low",normal:"Normal",medium:"Medium",high:"High",urgent:"Urgent"})[e]??e}function ei(e){return({low:"text-muted-foreground",normal:"text-foreground",medium:"text-foreground",high:"text-orange-500",urgent:"text-red-500"})[e]??"text-foreground"}function es(e){return({pending:"Pending",someday:"Someday",open:"Open",in_progress:"In Progress",blocked:"Blocked",resolved:"Resolved",expired:"Expired",cancelled:"Cancelled"})[e]??e}},733260,e=>{"use strict";e.s(["useWorkspaceEventSubscription",()=>s]);var t=e.i(982472),r=e.i(623128);e.i(853854);var i=e.i(512825);function s({tables:e,enabled:a=!0,entityIds:n=[],onEvent:o}){let l=(0,i.useOptionalRealtime)(),{currentWorkspace:c}=(0,r.useCurrentWorkspace)(),u=(0,t.useMemo)(()=>new Set(n.map(e=>null==e?"":String(e).trim()).filter(Boolean)),[n]);(0,t.useEffect)(()=>{let t=c?.id;if(a&&l&&t&&0!==e.length)return l.onWorkspaceEvent(t,t=>{if(t.tables?.some(t=>e.includes(t))){if(u.size>0){let e=t.entity_id?.trim(),r=t.parent_id?.trim();if((!e||!u.has(e))&&(!r||!u.has(r)))return}o(t)}})},[c?.id,a,u,o,l,e])}},296255,e=>{"use strict";var t=e.i(405680);e.i(384898);var r=e.i(343778),i=e.i(949078),s=e.i(484272);let a=["#FE5D39","#8662C6","#8DC8E8","#0077D3","#335600","#6FE567"];e.s(["PresenceAvatars",0,function({users:e,maxVisible:a=5,className:n}){if(0===e.length)return null;let o=e.slice(0,a),l=e.length-a;return(0,t.jsxs)("div",{className:(0,s.cn)("flex items-center -space-x-1.5",n),"data-testid":"presence-avatars",children:[o.map(e=>(0,t.jsxs)(i.Tooltip,{children:[(0,t.jsx)(i.TooltipTrigger,{asChild:!0,children:(0,t.jsx)("div",{className:"relative flex items-center justify-center transition-transform hover:scale-110 hover:z-10","aria-label":e.displayName,children:(0,t.jsx)(r.WyattFrog,{size:22,mode:"idle",color:e.color})})}),(0,t.jsx)(i.TooltipContent,{side:"bottom",sideOffset:6,children:e.displayName})]},e.userId)),l>0&&(0,t.jsxs)(i.Tooltip,{children:[(0,t.jsx)(i.TooltipTrigger,{asChild:!0,children:(0,t.jsxs)("div",{className:"relative size-6 rounded-full border-2 border-background bg-muted flex items-center justify-center text-[9px] font-semibold text-muted-foreground","aria-label":`${l} more collaborators`,children:["+",l]})}),(0,t.jsxs)(i.TooltipContent,{side:"bottom",sideOffset:6,children:[l," more collaborators"]})]})]})},"pickPresenceColor",0,function(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return a[Math.abs(t)%a.length]}])},24479,e=>{"use strict";let t=/^ws-[a-z0-9]+-[a-z0-9-]+-[0-9a-z]+$/i;function r(e){return t.test(e)}e.s(["assertWorkspacePublicId",0,function(e,t="workspace id"){let i=e?.trim();if(!i||!r(i))throw Error(`${t} must be a Wyatt public workspace id`);return i},"isWorkspacePublicId",0,r])},973857,180630,e=>{"use strict";var t=e.i(876216);function r(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,16):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}function i(e){return{id:r(),header:`Column ${e+1}`,width:180}}function s(e){return{id:r(),cells:Object.fromEntries(e.map(e=>[e.id,""]))}}function a(e=3,t=3){let r=Array.from({length:e},(e,t)=>i(t));return{columns:r,rows:Array.from({length:t},()=>s(r))}}function n(e){return Math.round(Math.max(64,Math.min(e,720)))}e.s(["DEFAULT_COLUMN_WIDTH",0,180,"MAX_COLUMN_WIDTH",0,720,"MIN_COLUMN_WIDTH",0,64,"applyGrid",0,function(e,t,r,a){if(0===a.length)return e;let n=0;for(let e of a)e.length>n&&(n=e.length);let o=[...e.columns];for(;o.length<r+n;)o.push(i(o.length));let l=e.rows.map(e=>{let t={...e.cells};for(let e of o)e.id in t||(t[e.id]="");return{...e,cells:t}});for(;l.length<t+a.length;)l.push(s(o));for(let e=0;e<a.length;e+=1){let i=l[t+e];if(!i)break;let s=a[e];for(let e=0;e<s.length;
7e+=1){let t=o[r+e];if(!t)break;i.cells[t.id]=s[e]}}return{columns:o,rows:l}},"clampColumnWidth",0,n,"clearCells",0,function(e,t){let r=new Map;for(let{rowId:e,columnId:i}of t){let t=r.get(e)??new Set;t.add(i),r.set(e,t)}return 0===r.size?e:{...e,rows:e.rows.map(e=>{let t=r.get(e.id);if(!t)return e;let i={...e.cells};for(let e of t)i[e]="";return{...e,cells:i}})}},"createTable",0,a,"deleteColumns",0,function(e,t){let r=new Set(t),i=e.columns.filter(e=>!r.has(e.id));return 0===i.length?e:{columns:i,rows:e.rows.map(e=>({...e,cells:Object.fromEntries(i.map(t=>[t.id,e.cells[t.id]??""]))}))}},"deleteRows",0,function(e,t){let r=new Set(t),i=e.rows.filter(e=>!r.has(e.id));return{...e,rows:i.length>0?i:[s(e.columns)]}},"duplicateColumn",0,function(e,t){let i=e.columns.findIndex(e=>e.id===t);if(-1===i)return e;let s=e.columns[i],a={id:r(),header:s.header,width:s.width??180},n=[...e.columns];return n.splice(i+1,0,a),{columns:n,rows:e.rows.map(e=>({...e,cells:{...e.cells,[a.id]:e.cells[t]??""}}))}},"duplicateRow",0,function(e,t){let i=e.rows.findIndex(e=>e.id===t);if(-1===i)return e;let s=[...e.rows];return s.splice(i+1,0,{id:r(),cells:{...e.rows[i].cells}}),{...e,rows:s}},"insertColumn",0,function(e,t){let r=[...e.columns],s=Math.max(0,Math.min(t,r.length)),a=i(r.length);return r.splice(s,0,a),{columns:r,rows:e.rows.map(e=>({...e,cells:{...e.cells,[a.id]:""}}))}},"insertRow",0,function(e,t){let r=[...e.rows],i=Math.max(0,Math.min(t,r.length));return r.splice(i,0,s(e.columns)),{...e,rows:r}},"moveColumn",0,function(e,t,r){let i=e.columns.findIndex(e=>e.id===t);if(-1===i)return e;let s=Math.max(0,Math.min(r,e.columns.length-1));if(s===i)return e;let a=[...e.columns],[n]=a.splice(i,1);return a.splice(s,0,n),{...e,columns:a}},"moveRow",0,function(e,t,r){let i=e.rows.findIndex(e=>e.id===t);if(-1===i)return e;let s=Math.max(0,Math.min(r,e.rows.length-1));if(s===i)return e;let a=[...e.rows],[n]=a.splice(i,1);return a.splice(s,0,n),{...e,rows:a}},"normalizeTable",0,function(e){let t=e??{},a=Array.isArray(t.columns)?t.columns:[],n=Array.isArray(t.rows)?t.rows:[],o=!1,l=a.map(e=>{let t="string"==typeof e?.id&&e.id?e.id:null,i="string"==typeof e?.header?e.header:"",s="number"==typeof e?.width&&Number.isFinite(e.width)?e.width:180;return t&&i===e?.header&&s===e?.width||(o=!0),{id:t??r(),header:i,width:s}});0===l.length&&(l.push(i(0)),o=!0);let c=n.map(e=>{let t="string"==typeof e?.id&&e.id?e.id:null;t||(o=!0);let i={};for(let t of l){let r=e?.cells?.[t.id],s="string"==typeof r?r:"";s!==r&&(o=!0),i[t.id]=s}return Object.keys(e?.cells??{}).length!==l.length&&(o=!0),{id:t??r(),cells:i}});return 0===c.length&&(c.push(s(l)),o=!0),o?{columns:l,rows:c}:e},"parseTsv",0,function(e){return e.replace(/\r\n?/g,"\n").replace(/\n$/,"").split("\n").map(e=>e.split(" "))},"renameColumn",0,function(e,t,r){return{...e,columns:e.columns.map(e=>e.id===t?{...e,header:r}:e)}},"setCell",0,function(e,t,r,i){return{...e,rows:e.rows.map(e=>e.id===t?{...e,cells:{...e.cells,[r]:i}}:e)}},"setColumnWidths",0,function(e,t){let r=!1,i=e.columns.map(e=>{let i=t[e.id];return null==i||n(i)===e.width?e:(r=!0,{...e,width:n(i)})});return r?{...e,columns:i}:e},"sortRowsByColumn",0,function(e,t,r){let i=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),s=[...e.rows].sort((e,s)=>{let a=e.cells[t]??"",n=s.cells[t]??"";if(!a&&!n)return 0;if(!a)return 1;if(!n)return -1;let o=i.compare(a,n);return"asc"===r?o:-o});return{...e,rows:s}},"toTsv",0,function(e){return e.map(e=>e.join(" ")).join("\n")}],180630);class o extends Error{blockType;blockId;field;value;
7constructor(e,t,r,i){super(`[BLOCK_VALIDATION_ERROR] ${e} block "${t}" has invalid ${r}: expected non-empty string, got ${JSON.stringify(i)}`),this.blockType=e,this.blockId=t,this.field=r,this.value=i,this.name="BlockValidationError"}}function l(e,t,r,i){if("string"!=typeof e||""===e.trim())throw new o(t,r,i,e)}let c=[t.BlockType.Text,t.BlockType.Heading,t.BlockType.ListItem,t.BlockType.Todo,t.BlockType.Quote,t.BlockType.Code,t.BlockType.Callout,t.BlockType.Image,t.BlockType.Embed,t.BlockType.Table,t.BlockType.Divider,t.BlockType.Database,t.BlockType.Calendar,t.BlockType.SignatureField,t.BlockType.InitialField,t.BlockType.DateField,t.BlockType.TextField,t.BlockType.CheckboxField,t.BlockType.DropdownField,t.BlockType.RadioField,t.BlockType.NumberField,t.BlockType.EmailField,t.BlockType.AttachmentField];e.s(["BlockValidationError",0,o,"TRANSFORMABLE_BLOCK_TYPES",0,c,"createAttachmentFieldBlock",0,function(e,r){return l(r.fieldName,"AttachmentField",e.blockId,"fieldName"),{...e,type:t.BlockType.AttachmentField,content:r}},"createCalendarBlock",0,function(e,r){return{...e,type:t.BlockType.Calendar,content:r}},"createCalloutBlock",0,function(e,r){return{...e,type:t.BlockType.Callout,content:r}},"createCheckboxFieldBlock",0,function(e,r){return l(r.fieldName,"CheckboxField",e.blockId,"fieldName"),{...e,type:t.BlockType.CheckboxField,content:r}},"createCodeBlock",0,function(e,r){return{...e,type:t.BlockType.Code,content:r}},"createDatabaseBlock",0,function(e,r){return{...e,type:t.BlockType.Database,content:r}},"createDateFieldBlock",0,function(e,r){return l(r.label,"DateField",e.blockId,"label"),l(r.recipientRole,"DateField",e.blockId,"recipientRole"),l(r.fieldName,"DateField",e.blockId,"fieldName"),{...e,type:t.BlockType.DateField,content:r}},"createDividerBlock",0,function(e){return{...e,type:t.BlockType.Divider,content:{}}},"createDropdownFieldBlock",0,function(e,r){return l(r.fieldName,"DropdownField",e.blockId,"fieldName"),{...e,type:t.BlockType.DropdownField,content:r}},"createEmailFieldBlock",0,function(e,r){return l(r.fieldName,"EmailField",e.blockId,"fieldName"),{...e,type:t.BlockType.EmailField,content:r}},"createHeadingBlock",0,function(e,r){return{...e,type:t.BlockType.Heading,content:r}},"createInitialFieldBlock",0,function(e,r){return l(r.label,"InitialField",e.blockId,"label"),l(r.recipientRole,"InitialField",e.blockId,"recipientRole"),l(r.fieldName,"InitialField",e.blockId,"fieldName"),{...e,type:t.BlockType.InitialField,content:r}},"createListItemBlock",0,function(e,r){return{...e,type:t.BlockType.ListItem,content:r}},"createNumberFieldBlock",0,function(e,r){return l(r.fieldName,"NumberField",e.blockId,"fieldName"),{...e,type:t.BlockType.NumberField,content:r}},"createQuoteBlock",0,function(e,r){return{...e,type:t.BlockType.Quote,content:r}},"createRadioFieldBlock",0,function(e,r){return l(r.fieldName,"RadioField",e.blockId,"fieldName"),{...e,type:t.BlockType.RadioField,content:r}},"createSignatureFieldBlock",0,function(e,r){return l(r.label,"SignatureField",e.blockId,"label"),l(r.recipientRole,"SignatureField",e.blockId,"recipientRole"),l(r.fieldName,"SignatureField",e.blockId,"fieldName"),{...e,type:t.BlockType.SignatureField,content:r}},"createTextBlock",0,function(e,r){return{...e,type:t.BlockType.Text,content:r}},"createTextFieldBlock",0,function(e,r){return l(r.fieldName,"TextField",e.blockId,"fieldName"),{...e,type:t.BlockType.TextField,content:r}},"createTodoBlock",0,function(e,r){return{...e,type:t.BlockType.Todo,content:r}},"getDefaultContentForBlockType",0,function(e,r,i="",s=[],n){switch(e){case t.BlockType.Text:case t.BlockType.ListItem:case t.BlockType.Quote:return{text:i};case t.BlockType.Heading:return{text:i,level:n?.headingLevel??t.HeadingLevel.H1};case t.BlockType.Todo:return{text:i,checked:!1};case t.BlockType.Code:return{code:i,language:"javascript"};case t.BlockType.Callout:return{text:i,icon:"💡",color:t.CalloutColor.Yellow};case t.BlockType.Table:return a();case t.BlockType.Divider:return{};case t.BlockType.Database:return{databaseId:null};case t.BlockType.Calendar:return{view:"month",events:[],highlights:[]};case t.BlockType.Embed:return{url:"",embedType:t.EmbedType.Link};case t.BlockType.Image:return{images:[]};case t.BlockType.SignatureField:{let e=s.filter(e=>e.type===t.BlockType.SignatureField).length+1,i=`Signer ${e}`;return{fieldType:"signature",fieldName:`signer${e}_signature_${r}`,recipientRole:i,label:`Signature (${i})`,required:!0}}case t.BlockType.InitialField:{let e=Math.max(1,s.filter(e=>e.type===t.BlockType.SignatureField).length),i=`Signer ${e}`;return{fieldType:"initial",fieldName:`signer${e}_initial_${r}`,recipientRole:i,label:`Initials (${i})`,required:!0}}case t.BlockType.DateField:{let e=Math.max(1,s.filter(e=>e.type===t.BlockType.SignatureField).length),i=`Signer ${e}`;return{fieldType:"date",fieldName:`signer${e}_date_${r}`,recipientRole:i,label:`Date (${i})`,required:!1}}case t.BlockType.TextField:return{fieldType:"text",fieldName:`text_${r}`,required:!1};case t.BlockType.CheckboxField:return{fieldType:"checkbox",fieldName:`checkbox_${r}`,required:!1};case t.BlockType.DropdownField:return{fieldType:"dropdown",fieldName:`dropdown_${r}`,options:["Option 1","Option 2"],required:!1};case t.BlockType.RadioField:return{fieldType:"radio",fieldName:`radio_${r}`,options:["Option 1","Option 2"],required:!1};case t.BlockType.NumberField:return{fieldType:"number",fieldName:`number_${r}`,required:!1};case t.BlockType.EmailField:return{fieldType:"email",fieldName:`email_${r}`,required:!1};case t.BlockType.AttachmentField:return{fieldType:"attachment",fieldName:`attachment_${r}`,required:!1};default:throw Error(`Unhandled block type in transform: ${e}`)}},"hasTextContent",0,function(e){return e.type===t.BlockType.Text||e.type===t.BlockType.Paragraph||e.type===t.BlockType.Heading||e.type===t.BlockType.ListItem||e.type===t.BlockType.Todo||e.type===t.BlockType.Quote||e.type===t.BlockType.Callout||e.type===t.BlockType.Toggle}],973857)},428344,898943,391432,987533,512825,853854,820369,780086,723103,983655,69739,430295,219900,892047,622617,774121,222792,8928
765,683987,270867,988558,e=>{"use strict";e.s(["EMPTY_WORKSPACE_CONTENT",()=>eM,"createFolderViaRoute",()=>eA,"deleteFolderViaRoute",()=>eE,"fetchWorkspaceContentRoute",()=>eD,"useInvalidateWorkspaceContent",()=>eF,"useWorkspaceContent",()=>eK,"workspaceContentKeys",()=>ex],428344);var t,r,i,s,a,n,o=e.i(982472),l=e.i(580107),c=e.i(270331),u=e.i(599177);e.s(["WyattDbProvider",()=>ef,"WyattDbRealtimeBridge",()=>em,"useCollectionsFor",()=>e_,"useDbRegistry",()=>eg,"useDbRegistrySafe",()=>ew,"useDbWorkspaceId",()=>eb,"useWorkspaceCollections",()=>ek],723103);var d=e.i(405680);e.i(549140);var p=e.i(602356);e.s([],853854),e.s(["WyattWebSocketProvider",()=>z,"useOptionalRealtime",()=>U],512825),e.s(["DEFAULT_TABLES",()=>W,"invalidateWorkspaceEventQueries",()=>N,"invalidateWorkspaceQueries",()=>j],987533),e.i(680433),e.i(253650);var y=e.i(328188),h=e.i(210321),f=e.i(602668),m=e.i(272893),g=e.i(506715),w=e.i(434659),k=e.i(355129),b=e.i(230605),_=e.i(583818),v=e.i(187177),I=e.i(751019);e.s(["deletePendingMessageRoute",()=>P,"fetchPendingMessagesRoute",()=>q,"messageQueueKeys",()=>M,"queuePendingMessageRoute",()=>O],391432),e.i(478539),e.i(60243),e.s(["participantKeys",()=>T,"pendingMessageKeys",()=>A,"useConversationMultiplayer",()=>D],898943);var S=e.i(37700),C=e.i(495238),x=e.i(733260),F=e.i(296255);let T={all:["participants"],conversation:(e,t)=>[...T.all,e,t]},A={all:["pendingMessages"],count:(e,t)=>[...A.all,"count",e,t]};async function E(e,t){let r=null!=t?String(t).trim():"";if(r)try{let t=(0,u.makeWyattClient)(r);return(await t.chat.listParticipants({workspaceId:r,conversationId:String(e)})).data}catch(t){let e=t?.status;if(403===e||404===e||409===e)return[];throw t}throw Error("Workspace ID is required to fetch conversation participants")}function D(e,t){let r=function(e){if("number"==typeof e&&Number.isFinite(e)&&e>0)return String(e);if("string"==typeof e){let t=e.trim();return t&&"0"!==t?t:null}return null}(e),i=t?.workspaceId===null||t?.workspaceId===void 0?null:String(t.workspaceId).trim()||null,{user:s}=(0,C.useAuth)(),[a]=(0,o.useState)([]),n=(0,o.useRef)(t?.onNewMessage);(0,o.useEffect)(()=>{n.current=t?.onNewMessage},[t?.onNewMessage]);let{data:l,isLoading:c,refetch:u}=(0,S.useQuery)({queryKey:r&&i?T.conversation(i,r):[...T.all,"disabled"],queryFn:()=>E(r,i),enabled:!!r&&!!i,staleTime:3e4}),d=(0,o.useMemo)(()=>l&&r?l.map(e=>({id:e.id,conversationId:r,userId:String(e.workspace_member_id),color:(0,F.pickPresenceColor)(String(e.workspace_member_id)),role:"owner"===e.role?"owner":"member",joinedAt:e.joined_at,isOnline:!1})):[],[l,r]),p=(0,o.useCallback)(e=>{},[]),y=d.find(e=>e.userId===s?.id);return(0,x.useWorkspaceEventSubscription)({tables:["messages"],enabled:!!r&&!!i,entityIds:[r],onEvent:e=>{let t="string"==typeof e.metadata?.author_user_id?e.metadata.author_user_id:"workspace_event";n.current?.({authorUserId:t!==s?.id?t:"workspace_event",messageId:e.record_id??e.entity_id??r})}}),{participants:d,typingUsers:a,sendTyping:p,currentUserParticipant:y,isLoading:c,isMultiplayer:d.length>1,refetch:u}}let M={all:["message-queue"],list:(e,t)=>[...M.all,"list",e,t],position:(e,t,r)=>[...M.all,"position",e,t,r]};function K(e){let t=e.metadata&&"object"==typeof e.metadata?e.metadata:null;return{id:e.id,conversationId:e.conversation_id,userId:"string"==typeof t?.user_id?t.user_id:"",content:Array.isArray(e.content)?e.content:[{type:"text",text:String(e.content??"")}],isSilent:e.is_silent,createdAt:e.created_at}}async function q({conversationId:e,workspaceId:t}){let r=(0,u.makeWyattClient)(t);return((await r.chat.listPendingMessages({workspaceId:t,conversationId:String(e)})).data??[]).map(K)}async function O({conversationId:e,workspaceId:t,content:r,userId:i,isSilent:s=!1}){let a=(0,u.makeWyattClient)(t);return K((await a.chat.createPendingMessage({workspaceId:t,conversationId:String(e),content:[{type:"text",text:r}],metadata:i?{user_id:i}:void 0,isSilent:s})).data)}async function P({conversationId:e,workspaceId:t,messageId:r}){let i=(0,u.makeWyattClient)(t);await i.chat.deletePendingMessage({workspaceId:t,conversationId:String(e),msgId:r})}var Q=e.i(120563),R=e.i(705777);let W=["block_documents","folders","pdfs","whiteboards","databases","dashboards","workspace_items","workspace_members"];function B(e,t={}){let r=new Set;return i=>{let s=JSON.stringify(i);
7r.has(s)||t.skipRecent&&(0,Q.wasRecentlyInvalidated)(e,i)||(r.add(s),e.invalidateQueries(i))}}function j(e,t,r,i={}){let s=String(t),a=B(e,i),n=i.refreshWorkspaceList??!0;for(let e of r)switch(e){case"block_documents":a({queryKey:y.documentKeys.list(s)}),a({queryKey:ex.workspace(s)});break;case"workspaces":a({queryKey:h.workspaceKeys.detail(t),refetchType:"all"}),a({queryKey:h.workspaceKeys.all,refetchType:"all"});break;case"folders":case"workspace_items":a({queryKey:ex.workspace(s)}),a({queryKey:["folders","list",t]});break;case"pdfs":a({queryKey:w.pdfKeys.list(s)}),a({queryKey:ex.workspace(s)});break;case"whiteboards":a({queryKey:k.whiteboardKeys.list(s)}),a({queryKey:ex.workspace(s)});break;case"databases":a({queryKey:b.databaseListKeys.list(s)}),a({queryKey:ex.workspace(s)});break;case"dashboards":case"dashboard_charts":a({queryKey:f.dashboardKeys.list(t)}),a({queryKey:ex.workspace(s)});break;case"tables":case"columns":case"rows":case"cells":a({queryKey:["table-page"]}),a({queryKey:["chart-data",s]});break;case"tasks":a({queryKey:I.taskKeys.list(s)}),a({queryKey:(0,I.pendingTaskCountKey)(s)});break;case"task_reminders":a({queryKey:["task_reminders"]});break;case"notifications":a({queryKey:["notifications","list",t]});break;case"workspace_members":a({queryKey:_.workspaceMemberKeys.list(t)}),n&&a({queryKey:h.workspaceKeys.all});break;case"runs":a({queryKey:["runs","list",t]});break;case"conversations":a({queryKey:v.conversationKeys.listPrefix(t)});break;case"messages":a({queryKey:v.conversationMessageKeys.all});break;case"conversation_participants":a({queryKey:T.all});break;case"pending_messages":a({queryKey:M.all}),a({queryKey:A.all});break;case"mcp_connections":a({queryKey:["mcp","connections"]});break;case"mcp_clients":a({queryKey:["mcp","clients"]});break;case"mcp_client_tokens":a({queryKey:["mcp","tokens"]}),a({queryKey:["mcp","clients"]})}}function $(e,t,r,i={}){let s=B(e,i),a=null===i.workspaceId||void 0===i.workspaceId?null:String(i.workspaceId),n=null===i.recordId||void 0===i.recordId?null:String(i.recordId);switch(t){case"block_documents":s({queryKey:y.documentKeys.detail(String(r))}),s({queryKey:(0,g.documentDetailKey)(String(r))}),s({queryKey:a?R.routeShellKeys.documents.detail(a,String(r)):["documents-shell","detail"]});break;case"blocks":s({queryKey:(0,m.documentBlocksKey)(String(r))}),s({queryKey:(0,g.documentDetailKey)(String(r))});break;case"workspaces":s({queryKey:h.workspaceKeys.detail(r),refetchType:"all"}),s({queryKey:h.workspaceKeys.all,refetchType:"all"});break;case"pdfs":s({queryKey:w.pdfKeys.detail(String(r))}),s({queryKey:a?["pdfs-shell","detail",a,String(r)]:["pdfs-shell","detail"]});break;case"whiteboards":s({queryKey:k.whiteboardKeys.detail(String(r))}),s({queryKey:a?["whiteboards-shell","detail",a,String(r)]:["whiteboards-shell","detail"]});break;case"databases":s({queryKey:b.databaseListKeys.detail(String(r))});break;case"dashboards":{let e=String(r);s({queryKey:f.dashboardKeys.detail(e)}),s({queryKey:a?(0,f.dashboardChartListQueryKey)(a,e):f.dashboardChartKeys.all});break}case"dashboard_charts":{let e=String(r);s({queryKey:f.dashboardKeys.detail(e)}),s({queryKey:a?(0,f.dashboardChartListQueryKey)(a,e):f.dashboardChartKeys.all}),a&&n?s({queryKey:(0,f.dashboardChartDetailQueryKey)(a,e,n)}):n||s({queryKey:f.dashboardChartKeys.details()});break}case"tasks":s({queryKey:I.taskKeys.detail(String(r))});break;case"conversations":s({queryKey:v.conversationKeys.detailPrefix(r)}),s({queryKey:v.conversationMessageKeys.listPrefix(String(r))});break;case"conversation_participants":s({queryKey:a?T.conversation(a,String(r)):T.all});break;case"pending_messages":s({queryKey:a?M.list(a,String(r)):M.all}),s({queryKey:a?A.count(a,String(r)):A.all});break;default:s({queryKey:[t]})}}function N(e,t,r){let i=(r.tables??[]).filter(Boolean);if(0===i.length)return;let s=i.includes("workspace_items"),a=i.filter(e=>"blocks"!==e&&("block_documents"!==e||!!s));if(a.length>0&&j(e,r.workspace_id||t,a,{skipRecent:!0}),r.entity_id){for(let s of i)$(e,s,r.entity_id,{skipRecent:!0,workspaceId:r.workspace_id||t,recordId:r.record_id});if(r.parent_id)for(let s of i)$(e,s,r.parent_id,{skipRecent:!0,workspaceId:r.workspace_id||t})}}let L=(0,o.createContext)(null);function U(){return(0,o.useContext)(L)}
7function z({workspaceId:e,children:t}){let{wyatt:r}=(0,c.useWorkspace)(),i=(0,l.useQueryClient)();return(0,o.useEffect)(()=>{if(!e)return;let t=r.realtime.onReconnect(()=>{j(i,e,W,{refreshWorkspaceList:!1})}),s=r.realtime.onWorkspaceEventVersionGap(t=>{t===e&&j(i,e,W)}),a=r.realtime.onWorkspaceEvent(e,t=>{N(i,e,t)});return r.realtime.connect(e),r.realtime.subscribeWorkspace(e),()=>{t(),s(),a(),r.realtime.unsubscribeWorkspace(e),r.realtime.disconnect()}},[i,e,r.realtime]),(0,d.jsx)(L.Provider,{value:r.realtime,children:t})}e.i(534);var V=e.i(534167);let G=["block_documents","whiteboards","pdfs","databases","folders","dashboards","tasks","notifications","conversations","messages","comments"];function J(e){return{isReady:()=>"ready"===e.status,has:t=>e.has(t),upsert:t=>e.utils.writeUpsert(t),remove:t=>e.utils.writeDelete(t),batch:t=>e.utils.writeBatch(t),refetch:()=>{e.utils.refetch()}}}let H={block_documents:{sink:e=>J(e.documents),fetchOne:async(e,t,r)=>(await e.documents.get({workspaceId:t,documentId:r})).data},whiteboards:{sink:e=>J(e.whiteboards),fetchOne:async(e,t,r)=>(await e.whiteboards.get({workspaceId:t,whiteboardId:r})).data},pdfs:{sink:e=>J(e.pdfs),fetchOne:async(e,t,r)=>(await e.pdfs.get({workspaceId:t,pdfId:r})).data},databases:{sink:e=>J(e.databases),fetchOne:async(e,t,r)=>(await e.databases.get({workspaceId:t,databaseId:r})).data},folders:{sink:e=>J(e.folders),fetchOne:async(e,t,r)=>(await e.folders.get({workspaceId:t,folderId:r})).data},dashboards:{sink:e=>J(e.dashboards),fetchOne:async(e,t,r)=>(await e.dashboards.get({workspaceId:t,dashboardId:r})).data},tasks:{sink:e=>J(e.tasks),fetchOne:async(e,t,r)=>(await e.tasks.get({workspaceId:t,taskId:r})).data},notifications:{sink:e=>J(e.notifications),fetchOne:async(e,t,r)=>(await e.notifications.get({workspaceId:t,notificationId:r})).data},conversations:{sink:e=>J(e.conversations),fetchOne:async(e,t,r)=>(await e.chat.getConversation({workspaceId:t,conversationId:r})).data}};function Y({registry:e,workspaceId:t,cowork:r,flushDelayMs:i=100}){let s=new Map,a=new Set,n=new Set,o=new Set,l=!1,c=null,u=Promise.resolve(),d=!1,p=()=>e.workspace(t),y=()=>{d||null!==c||(c=setTimeout(()=>{c=null,u=u.then(()=>f())},i))},h=async(e,i)=>{let s=H[e];if(!s)return;let n=s.sink(p());if(!n.isReady())return;let o=await Promise.all([...i].map(async i=>{try{let e=await s.fetchOne(r,t,i);return{entityId:i,row:e,gone:null===e}}catch(t){if(t instanceof V.CoworkApiError&&(403===t.status||404===t.status||410===t.status))return{entityId:i,row:null,gone:!0};return console.error("[wyatt-db] realtime entity refresh failed",{table:e,entityId:i,error:t}),a.add(e),{entityId:i,row:null,gone:!1}}}));n.isReady()&&n.batch(()=>{for(let e of o)e.row?n.upsert(e.row):e.gone&&n.has(e.entityId)&&n.remove(e.entityId)})},f=async()=>{if(d)return;let r=[...s.entries()].map(([e,t])=>[e,new Set(t)]);s.clear();let i=[...n];n.clear();let c=[...o];o.clear();let u=l;for(let s of(l=!1,await Promise.all(r.map(([e,t])=>h(e,t))),i)){let r=e.peekMessages(t,s);r&&r.utils.refetch()}for(let r of c){let i=r.indexOf(":"),s=e.peekComments(t,r.slice(0,i),r.slice(i+1));s&&s.utils.refetch()}let y=[...a];for(let e of(a.clear(),y))H[e]?.sink(p()).refetch();u&&await e.refetchTaskBoards(t)},m=(e,t)=>{var r;if("comments"===e){let e=t.metadata?.entity_type,r=t.entity_id?.trim();"string"==typeof e&&e&&r&&(o.add(`${e}:${r}`),y());return}if("messages"===e){let e=t.entity_id?.trim();e&&(n.add(e),y());return}let i=H[e];if(!i||("tasks"===e&&(l=!0,y()),"block_documents"===e&&(r=t.tables??[]).includes("blocks")&&!r.includes("workspace_items")))return;let c=t.entity_id?.trim();if(!c){a.add(e),y();return}if("deleted"===t.action){let e=i.sink(p());e.isReady()&&e.has(c)&&e.remove(c);return}let u=s.get(e);u||(u=new Set,s.set(e,u)),u.add(c),y()};return{handleEvent(e){if(!d)for(let t of e.tables??[])G.includes(t)&&m(t,e)},async flush(){null!==c&&(clearTimeout(c),c=null),u=u.then(()=>f()),await u},resync(){for(let r of e.allForWorkspace(t))r.refetch()},dispose(){d=!0,null!==c&&(clearTimeout(c),c=null),s.clear(),a.clear(),n.clear(),o.clear(),l=!1}}}
7e.s(["createWorkspaceDbBridge",0,Y],820369);var Z=e.i(643436);async function X(e,t){let r=[];for(let e=0;e<2e3;e+=200){let i=await t({limit:200,offset:e});if(r.push(...i),i.length<200)return r}throw Error(`[wyatt-db] "${e}" exceeds the 2000-row ceiling; refusing to reconcile an incomplete snapshot. This scope needs on-demand loading.`)}function ee(e,t){if(e&&t)throw Error("Catalog metadata and placement must be changed in separate transactions.")}function et(e,t){let r=e.updated_at??e.created_at??"",i=t.updated_at??t.created_at??"";return r===i?e.id.localeCompare(t.id):i.localeCompare(r)}function er(e,t){let r=e.updated_at??e.created_at??"",i=t.updated_at??t.created_at??"";return r===i?e.id.localeCompare(t.id):i.localeCompare(r)}function ei(e,t){return e.created_at===t.created_at?e.id.localeCompare(t.id):e.created_at.localeCompare(t.created_at)}function es(e,t){return e.created_at===t.created_at?e.id.localeCompare(t.id):e.created_at.localeCompare(t.created_at)}function ea(e,t){return e.created_at===t.created_at?e.id.localeCompare(t.id):t.created_at.localeCompare(e.created_at)}function en(e,t){let r=e.created_at??"",i=t.created_at??"";return r===i?e.id.localeCompare(t.id):i.localeCompare(r)}function eo(e,t,r,i,s){return(0,Z.createWyattCollection)({queryClient:e,name:"tasks",scope:s?[t,s,r]:[t,r],compare:en,fetchAll:()=>X("tasks",async({limit:e,offset:r})=>(await i.tasks.list({workspaceId:t,board:s,includeTeamTasks:!0,limit:e,offset:r})).data??[]),insert:async e=>(await i.tasks.create({workspaceId:t,title:e.title,description:e.description,priority:e.priority,type:e.type,due_at:e.due_at,blocking:e.blocking,is_important:e.is_important,is_urgent:e.is_urgent,contexts:e.contexts,waiting_for:e.waiting_for,sprint_id:e.sprint_id,context:e.context,assigned_member_id:e.assigned_member_id,group_id:e.group_id})).data,update:async({key:e,changes:r})=>void 0!==r.resolution?(await i.tasks.resolve({workspaceId:t,taskId:e,resolution:r.resolution,resolution_data:r.resolution_data})).data:(await i.tasks.update({workspaceId:t,taskId:e,title:r.title,description:r.description,status:r.status,priority:r.priority,type:r.type,due_at:r.due_at,blocking:r.blocking,is_important:r.is_important,is_urgent:r.is_urgent,contexts:r.contexts,waiting_for:r.waiting_for,sprint_id:r.sprint_id,context:r.context,assigned_member_id:r.assigned_member_id})).data,remove:async({key:e})=>{await i.tasks.delete({workspaceId:t,taskId:e})}})}let el=["documents","folders","whiteboards","pdfs","databases","tasks"];function ec(e){return{refetch:()=>{e.utils.refetch()},cleanup:()=>e.cleanup().then(()=>void 0)}}function eu(e){let t=e.collections;return[ec(t.documents),ec(t.whiteboards),ec(t.pdfs),ec(t.databases),ec(t.folders),ec(t.dashboards),ec(t.tasks),ec(t.notifications),ec(t.conversations),...[...e.messages.values()].map(e=>ec(e)),...[...e.comments.values()].map(e=>ec(e)),...[...e.taskBoards.values()].map(e=>ec(e))]}class ed{queryClient;createClient;viewerId;workspaces;constructor(e,t=e=>(0,p.createSessionCoworkClient)(e),r="anonymous"){this.queryClient=e,this.createClient=t,this.viewerId=r,this.workspaces=new Map}workspace(e){return this.entry(e).collections}client(e){return this.entry(e).cowork}messages(e,t){var r,i,s;let a=this.entry(e),n=a.messages.get(t);if(n)return n;let o=(r=this.queryClient,i=this.viewerId,s=this.createClient(e),(0,Z.createWyattCollection)({queryClient:r,name:"messages",scope:[e,t,i],compare:ei,fetchAll:()=>X("messages",async({limit:r,offset:i})=>(await s.chat.listMessages({workspaceId:e,conversationId:t,limit:r,offset:i})).data??[]),insert:async r=>(await s.chat.sendMessage({workspaceId:e,conversationId:t,role:r.role,content:r.content,attachment_ids:r.attachments?.map(e=>e.id),metadata:r.metadata,is_silent:r.is_silent})).data}));return a.messages.set(t,o),o}peekMessages(e,t){return this.workspaces.get(e)?.messages.get(t)}peekComments(e,t,r){return this.workspaces.get(e)?.comments.get(`${t}:${r}`)}taskBoard(e,t){let r=this.entry(e),i=r.taskBoards.get(t);if(i)return i;let s=eo(this.queryClient,e,this.viewerId,r.cowork,t);return r.taskBoards.set(t,s),s}async refetchTaskBoards(e){let t=this.workspaces.get(e);t&&await Promise.all([...t.taskBoards.values()].map(e=>e.utils.refetch()))}comments(e,t,r){var i,s,a;let n=this.entry(e),o=`${t}:${r}`,l=n.comments.get(o);if(l)return l;let c=(i=this.queryClient,s=this.viewerId,a=this.createClient(e),(0,Z.createWyattCollection)({queryClient:i,name:"comments",scope:[e,t,r,s],compare:es,fetchAll:()=>X("comments",async({limit:i,offset:s})=>(await a.comments.list({workspaceId:e,entity_type:t,entity_id:r,limit:i,offset:s})).data??[]),insert:async i=>(await a.comments.create({workspaceId:e,entity_type:t,entity_id:r,content:i.content,parent_comment_id:i.parent_comment_id,position:i.position})).data,update:async({key:t,changes:r,original:i})=>{let s,n=void 0!==r.content,o=void 0!==r.resolved&&r.resolved!==i.resolved;if(n&&o)throw Error("Comment content and resolution must be changed in separate transactions.");return n&&(s=(await a.comments.update({workspaceId:e,commentId:t,content:r.content})).data),o&&(s=(await a.comments.resolve({workspaceId:e,commentId:t,resolved:r.resolved})).data),s},remove:async({key:t})=>{await a.comments.delete({workspaceId:e,commentId:t})}}));return n.comments.set(o,c),c}
7allForWorkspace(e){let t=this.workspaces.get(e);return t?eu(t):[]}async preload(e){let t=this.workspace(e);await Promise.all(el.map(e=>t[e].preload().catch(t=>{console.warn("[wyatt-db] preload failed",{name:e,error:t})})))}async destroyWorkspace(e){let t=this.workspaces.get(e);t&&(this.workspaces.delete(e),await Promise.all(eu(t).map(e=>e.cleanup().catch(e=>{console.warn("[wyatt-db] collection cleanup failed",{error:e})}))))}entry(e){var t,r,i,s,a,n,o,l,c,u,d,p,y,h,f,m;let g=this.workspaces.get(e);if(g)return g;let w=this.createClient(e),k={cowork:w,collections:{workspaceId:e,documents:(t=this.queryClient,r=this.viewerId,(0,Z.createWyattCollection)({queryClient:t,name:"documents",scope:[e,r],compare:et,fetchAll:()=>X("documents",async({limit:t,offset:r})=>(await w.documents.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r,modified:i})=>{let s,a=void 0!==r.title||void 0!==r.is_template||void 0!==r.public_access||void 0!==r.tags,n=void 0!==r.parent_id||void 0!==r.parent_type;return ee(a,n),a&&(s=(await w.documents.update({workspaceId:e,documentId:t,title:r.title,is_template:r.is_template,public_access:r.public_access,set_tags:r.tags})).data),n&&(s=(await w.documents.move({workspaceId:e,documentId:t,parent_type:i.parent_type,parent_id:i.parent_id})).data),s},remove:async({key:t})=>{await w.documents.delete({workspaceId:e,documentId:t})}})),whiteboards:(i=this.queryClient,s=this.viewerId,(0,Z.createWyattCollection)({queryClient:i,name:"whiteboards",scope:[e,s],compare:et,fetchAll:()=>X("whiteboards",async({limit:t,offset:r})=>(await w.whiteboards.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r,modified:i})=>{let s,a=void 0!==r.name||void 0!==r.description,n=void 0!==r.parent_id||void 0!==r.parent_type;return ee(a,n),a&&(s=(await w.whiteboards.update({workspaceId:e,whiteboardId:t,name:r.name,description:r.description})).data),n&&(s=(await w.whiteboards.move({workspaceId:e,whiteboardId:t,parent_type:i.parent_type,parent_id:i.parent_id})).data),s},remove:async({key:t})=>{await w.whiteboards.delete({workspaceId:e,whiteboardId:t})}})),pdfs:(a=this.queryClient,n=this.viewerId,(0,Z.createWyattCollection)({queryClient:a,name:"pdfs",scope:[e,n],compare:et,fetchAll:()=>X("pdfs",async({limit:t,offset:r})=>(await w.pdfs.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r,modified:i})=>{let s,a=void 0!==r.name||void 0!==r.description,n=void 0!==r.parent_id||void 0!==r.parent_type;return ee(a,n),a&&(s=(await w.pdfs.update({workspaceId:e,pdfId:t,name:r.name,description:r.description})).data),n&&(s=(await w.pdfs.move({workspaceId:e,pdfId:t,parent_type:i.parent_type,parent_id:i.parent_id})).data),s},remove:async({key:t})=>{await w.pdfs.delete({workspaceId:e,pdfId:t})}})),databases:(o=this.queryClient,l=this.viewerId,(0,Z.createWyattCollection)({queryClient:o,name:"databases",scope:[e,l],compare:et,fetchAll:()=>X("databases",async({limit:t,offset:r})=>(await w.databases.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r})=>{if(void 0!==r.name)return(await w.databases.update({workspaceId:e,databaseId:t,name:r.name})).data},remove:async({key:t})=>{await w.databases.delete({workspaceId:e,databaseId:t})}})),folders:(c=this.queryClient,u=this.viewerId,(0,Z.createWyattCollection)({queryClient:c,name:"folders",scope:[e,u],compare:(e,t)=>e.name.localeCompare(t.name),fetchAll:()=>X("folders",async({limit:t,offset:r})=>(await w.folders.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r,modified:i})=>{let s,a=void 0!==r.name||void 0!==r.icon,n=void 0!==r.parent_id||void 0!==r.parent_type;return ee(a,n),a&&(s=(await w.folders.update({workspaceId:e,folderId:t,name:r.name,icon:r.icon})).data),n&&(s=(await w.folders.move({workspaceId:e,folderId:t,parent_type:i.parent_type,parent_id:i.parent_id})).data),s},remove:async({key:t})=>{await w.folders.delete({workspaceId:e,folderId:t})}})),dashboards:(d=this.queryClient,p=this.viewerId,(0,Z.createWyattCollection)({queryClient:d,name:"dashboards",scope:[e,p],compare:et,fetchAll:()=>X("dashboards",async({limit:t,offset:r})=>(await w.dashboards.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r})=>(await w.dashboards.update({workspaceId:e,dashboardId:t,name:r.name,description:r.description,layout:r.layout})).data,remove:async({key:t})=>{await w.dashboards.delete({workspaceId:e,dashboardId:t})}})),tasks:eo(this.queryClient,e,this.viewerId,w),notifications:(y=this.queryClient,h=this.viewerId,(0,Z.createWyattCollection)({queryClient:y,name:"notifications",scope:[e,h],compare:ea,fetchAll:()=>X("notifications",async({limit:t,offset:r})=>(await w.notifications.list({workspaceId:e,limit:t,offset:r})).data??[]),update:async({key:t,changes:r,original:i})=>{if(null!=r.read_at&&null==i.read_at)return(await w.notifications.markRead({workspaceId:e,notificationId:t})).data},remove:async({key:t})=>{await w.notifications.delete({workspaceId:e,notificationId:t})}})),conversations:(f=this.queryClient,m=this.viewerId,(0,Z.createWyattCollection)({queryClient:f,name:"conversations",scope:[e,m],compare:er,fetchAll:()=>X("conversations",async({limit:t,offset:r})=>(await w.chat.listConversations({workspaceId:e,limit:t,offset:r})).data??[]),insert:async t=>(await w.chat.createConversation({workspaceId:e,title:t.title,context_type:t.context_type,context_id:t.context_id,model:t.model,system_prompt:t.system_prompt,parent_id:t.parent_id,visibility:t.visibility})).data,update:async({key:t,changes:r})=>{if(void 0!==r.title)return(await w.chat.updateConversation({workspaceId:e,conversationId:t,title:r.title})).data},remove:async({key:t})=>{await w.chat.deleteConversation({workspaceId:e,conversationId:t})}}))},messages:new Map,comments:new Map,taskBoards:new Map};return this.workspaces.set(e,k),k}}let ep=new WeakMap;function ey(e,t="anonymous"){let r=ep.get(e);r||(r=new Map,ep.set(e,r));let i=r.get(t);if(i)return i;let s=new ed(e,void 0,t);return r.set(t,s),s}e.s(["getDbRegistry",0,ey],780086);let eh=o.createContext(null);function ef({workspaceId:e,viewerId:t="anonymous",registry:r,children:i}){let s=(0,l.useQueryClient)(),a=o.useMemo(()=>r??ey(s,t),[s,r,t]),n=o.useMemo(()=>e?a.workspace(e):null,[a,e]);o.useEffect(()=>{e&&a.preload(e)},[a,e]);let c=o.useMemo(()=>({registry:a,workspaceId:e,collections:n}),[n,a,e]);return(0,d.jsx)(eh.Provider,{value:c,children:i})}function em(){let e=ew(),t=U(),r=o.useContext(eh)?.workspaceId??null;return o.useEffect(()=>{if(!e||!r||!t)return;let i=Y({registry:e,workspaceId:r,cowork:(0,p.createSessionCoworkClient)(r)}
7),s=t.onWorkspaceEvent(r,e=>{i.handleEvent(e)}),a=t.onReconnect(()=>{i.resync()}),n=t.onWorkspaceEventVersionGap(e=>{e===r&&i.resync()});return()=>{s(),a(),n(),i.dispose()}},[t,e,r]),null}function eg(){let e=ew();if(!e)throw Error("useDbRegistry must be used within a WyattDbProvider");return e}function ew(){return o.useContext(eh)?.registry??null}function ek(){return o.useContext(eh)?.collections??null}function eb(){return o.useContext(eh)?.workspaceId??null}function e_(e){let t=o.useContext(eh);return o.useMemo(()=>t&&e?t.registry.workspace(e):null,[t,e])}var ev=e.i(485407);function eI(e){let t=(0,ev.useCollectionRows)(e?.folders),r=(0,ev.useCollectionRows)(e?.documents),i=(0,ev.useCollectionRows)(e?.databases),s=(0,ev.useCollectionRows)(e?.whiteboards),a=(0,ev.useCollectionRows)(e?.pdfs),n=(0,ev.useCollectionRows)(e?.dashboards),l=[t,r,i,s,a,n],c=o.useCallback(()=>{t.refetch(),r.refetch(),i.refetch(),s.refetch(),a.refetch(),n.refetch()},[n,i,r,t,a,s]);return o.useMemo(()=>({folders:t.data,documents:r.data,databases:i.data,whiteboards:s.data,pdfs:a.data,dashboards:n.data,isPending:l.some(e=>e.isPending),isError:l.some(e=>e.isError),error:l.find(e=>e.error)?.error??null,refetch:c}),[t.data,r.data,i.data,s.data,a.data,n.data,t.isPending,r.isPending,i.isPending,s.isPending,a.isPending,n.isPending,t.isError,r.isError,i.isError,s.isError,a.isError,n.isError,c])}e.s(["useWorkspaceCatalog",0,eI],983655);var eS=e.i(221745),eC=e.i(24479);let ex={all:["workspace-content"],workspace:(e,t)=>t?[...ex.all,e,t]:[...ex.all,e]};function eF(){let e=(0,l.useQueryClient)();return(0,o.useCallback)(t=>{t?e.invalidateQueries({queryKey:ex.workspace(t)}):e.invalidateQueries({queryKey:ex.all})},[e])}function eT(e){return[...e.folders.map(e=>({item_id:e.id,item_type:"folder",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`})),...e.documents.map(e=>({item_id:e.id,item_type:"document",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`})),...e.databases.map(e=>({item_id:e.id,item_type:"database",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`})),...e.whiteboards.map(e=>({item_id:e.id,item_type:"whiteboard",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`})),...e.pdfs.map(e=>({item_id:e.id,item_type:"pdf",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`})),...e.dashboards.map(e=>({item_id:e.id,item_type:"dashboard",parent_id:"folder"===e.parent_type?e.parent_id:null,parent_type:e.parent_type,order_key:`${e.created_at}-${e.id}`}))]}async function eA({workspaceId:e,name:t,parentType:r,parentId:i}){let s=(0,eC.assertWorkspacePublicId)(e,"folder create workspace id"),a=(0,u.makeCoworkClient)(s),n=(await a.folders.create({workspaceId:s,name:t,parent_type:r,parent_id:i})).data;return(0,eS.trackEvent)("folder_created",{workspace_id:s,folder_id:n.id,..."folder"===n.parent_type?{parent_folder_id:n.parent_id}:{}}),n}async function eE({workspaceId:e,folderId:t}){let r=(0,eC.assertWorkspacePublicId)(e,"folder delete workspace id"),i=(0,u.makeCoworkClient)(r);await i.folders.delete({workspaceId:r,folderId:t}),(0,eS.trackEvent)("folder_deleted",{workspace_id:r,folder_id:t})}async function eD(e){let t=(0,eC.assertWorkspacePublicId)(e,"workspace content route workspace id"),r=(0,u.makeCoworkClient)(t),[i,s,a,n,o,l]=await Promise.all([r.folders.list({workspaceId:t}),r.documents.list({workspaceId:t}),r.databases.list({workspaceId:t}),r.whiteboards.list({workspaceId:t}),r.pdfs.list({workspaceId:t}),r.dashboards.list({workspaceId:t})]),c={folders:(i.data??[]).map(e=>({...e,workspace_id:t})),documents:s.data??[],databases:a.data??[],whiteboards:n.data??[],pdfs:o.data??[],dashboards:l.data??[]};return{...c,items:eT(c)}}let eM={items:[],folders:[],documents:[],databases:[],whiteboards:[],pdfs:[],dashboards:[]};function eK({enabled:e=!0,workspaceId:t}={}){let{workspaceId:r}=(0,c.useWorkspace)(),{user:i}=(0,C.useAuth)(),s=t??r,a=(0,l.useQueryClient)(),n=ek(),u=e_(t??void 0),d=t?u:n,p=!!s&&e,y=eI(p?d:null),h=(0,o.useMemo)(()=>
7{if(!p||!s)return eM;let e={folders:y.folders.map(e=>({...e,workspace_id:s})),documents:y.documents,databases:y.databases,whiteboards:y.whiteboards,pdfs:y.pdfs,dashboards:y.dashboards};return{...e,items:eT(e)}},[y.dashboards,y.databases,y.documents,y.folders,y.pdfs,y.whiteboards,p,s]);return(0,o.useEffect)(()=>{p&&s&&i?.id&&!y.isPending&&a.setQueryData(ex.workspace(s,i.id),h)},[y.isPending,h,p,a,s,i?.id]),{data:h,isPending:p&&y.isPending,isLoading:p&&y.isPending,isError:y.isError,error:y.error,refetch:y.refetch}}e.s([],69739),e.s(["GroupMemberRole",()=>eQ,"useAddGroupEntity",()=>e6,"useCreateGroup",()=>e2,"useCreateTeamTask",()=>ts,"useDeleteGroup",()=>e3,"useGroup",()=>e1,"useGroupBoardPreference",()=>ta,"useGroupEntities",()=>e4,"useGroupMembers",()=>e8,"useGroupSummary",()=>e0,"useGroupTasks",()=>ti,"useGroups",()=>eZ,"useGroupsWithMemberCount",()=>eX,"useRemoveGroupEntity",()=>e9,"useUpdateGroup",()=>e5,"useUpdateGroupBoardPreference",()=>tn,"useUserGroups",()=>to],430295);var eq=e.i(898665),eO=e.i(623128),eP=e.i(8551),eQ=((t={}).Lead="lead",t.Member="member",t);let eR=["groups"],eW=e=>[...eR,"list",String(e)],eB=()=>[...eR,"member-count-list"],ej=()=>[...eR,"summary"],e$=(e,t)=>[...eR,"detail",String(e),String(t)],eN=(e,t)=>[...eR,"members",String(e),String(t)],eL=e=>[...eR,"user-list",String(e)];function eU(e,t){let r="team"===t.type||"project"===t.type||"custom"===t.type?t.type:"custom";return{id:t.id,workspace_id:e,name:t.name,type:r,description:t.description||void 0,created_at:t.created_at}}async function ez(e){let t=String(e.workspaceId),r=String(e.groupId),i=(0,u.makeCoworkClient)(t),s=await i.groups.get({workspaceId:t,groupId:r});return eU(t,s.data)}async function eV(e){let t=String(e.workspaceId),r=(0,u.makeCoworkClient)(t),i=await r.groups.create({workspaceId:t,name:e.name,type:e.type});return eU(t,i.data)}async function eG(e){let t=String(e.workspaceId),r=String(e.id),i=(0,u.makeCoworkClient)(t),s=await i.groups.update({workspaceId:t,groupId:r,name:e.name,type:e.type});return eU(t,s.data)}async function eJ(e){let t=String(e.workspaceId),r=String(e.id),i=(0,u.makeCoworkClient)(t);return await i.groups.delete({workspaceId:t,groupId:r}),{id:r,workspaceId:t}}async function eH(e){let t=String(e.workspaceId),r=String(e.groupId),i=(0,u.makeCoworkClient)(t),s=[];for(;;){let e=await i.groups.listMembers({workspaceId:t,groupId:r,limit:100,offset:s.length}),a=e.data??[];if(s.push(...a),0===a.length||s.length>=e.meta.total)break}return s.map(e=>({group_id:r,user_id:e.id,role:"member"===e.role?"member":"lead",created_at:e.joined_at,user:{id:e.id,email:e.email,raw_user_meta_data:{full_name:e.display_name||void 0}}}))}async function eY(e,t=!1){let r=String(e),i=(0,u.makeCoworkClient)(r),s=[],a=0,n=0;do{let e=await i.groups.list({workspaceId:r,membership:t?"mine":void 0,limit:100,offset:a}),o=e.data??[];if(s.push(...o),n=e.meta?.total??s.length,a+=o.length,0===o.length)break}while(s.length<n)return s.map(e=>{let t;return{id:e.id,workspace_id:r,name:e.name,type:"team"===(t=e.type)||"project"===t||"custom"===t?t:"custom",created_at:e.created_at,member_count:e.member_count,current_user_role:e.current_user_role}})}function eZ({workspaceId:e}){let t=null!=e?String(e):null;return(0,S.useQuery)({queryKey:eW(t??"none"),queryFn:async()=>null==e?[]:await eY(e),enabled:!!t})}function eX({workspaceId:e,memberOnly:t=!1}){let r=null!=e?String(e):null;return(0,S.useQuery)({queryKey:((e,t=!1)=>[...eR,"member-count-list",String(e),t?"mine":"visible"])(r??"none",t),queryFn:async()=>null==e?[]:(await eY(e,t)).map(e=>({id:e.id,workspace_id:e.workspace_id,name:e.name,type:e.type,created_at:e.created_at,member_count:e.member_count,current_user_role:e.current_user_role})),enabled:!!r})}function e0({workspaceId:e,memberOnly:t=!1}){let r=null!=e?String(e):null;return(0,S.useQuery)({queryKey:((e,t=!1)=>[...eR,"summary",String(e),t?"mine":"visible"])(r??"none",t),queryFn:async()=>{if(!r)return{team_count:0,project_count:0,custom_count:0,total_group_count:0,unique_member_count:0};let e=(0,u.makeCoworkClient)(r);return(await e.groups.summary({workspaceId:r,membership:t?"mine":void 0})).data},enabled:!!r})}function e1({groupId:e,workspaceId:t}){let{workspaceId:r}=(0,eO.useActiveWorkspace)(),i=t??r,s=null!=e?String(e):null;return(0,S.useQuery)({queryKey:e$(i??"none",s??"none"),queryFn:async()=>
7{if(!i||null==e)throw Error("workspaceId and groupId are required");return ez({workspaceId:i,groupId:e})},enabled:!!i&&!!s})}function e2(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:eV,onSuccess:t=>{e.invalidateQueries({queryKey:eW(t.workspace_id)}),e.invalidateQueries({queryKey:eB()}),e.invalidateQueries({queryKey:ej()}),e.invalidateQueries({queryKey:eL(t.workspace_id)})}})}function e5(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:eG,onSuccess:t=>{e.invalidateQueries({queryKey:e$(t.workspace_id,t.id)}),e.invalidateQueries({queryKey:eW(t.workspace_id)}),e.invalidateQueries({queryKey:eB()}),e.invalidateQueries({queryKey:ej()}),e.invalidateQueries({queryKey:eL(t.workspace_id)})}})}function e3(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:eJ,onSuccess:t=>{e.removeQueries({queryKey:e$(t.workspaceId,t.id)}),e.removeQueries({queryKey:eN(t.workspaceId,t.id)}),e.invalidateQueries({queryKey:eW(t.workspaceId)}),e.invalidateQueries({queryKey:eB()}),e.invalidateQueries({queryKey:ej()}),e.invalidateQueries({queryKey:eL(t.workspaceId)})}})}function e8({groupId:e,workspaceId:t}){let{workspaceId:r}=(0,eO.useActiveWorkspace)(),i=t??r,s=null!=e?String(e):null;return(0,S.useQuery)({queryKey:eN(i??"none",s??"none"),queryFn:async()=>i&&null!=e?eH({workspaceId:i,groupId:e}):[],enabled:!!i&&!!s})}let e7=(e,t)=>["group_entities","list",String(e),String(t)];function e4({groupId:e,workspaceId:t}){let{workspaceId:r}=(0,eO.useActiveWorkspace)(),i=t??r,s=null!=e?String(e):null;return(0,S.useQuery)({queryKey:e7(i??"none",s??"none"),queryFn:async()=>{let e=(0,u.makeCoworkClient)(String(i));return(await e.groups.listEntities({workspaceId:String(i),groupId:s})).data??[]},enabled:!!i&&!!s})}function e6({workspaceId:e}={}){let{workspaceId:t}=(0,eO.useActiveWorkspace)(),r=e??t,i=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{if(!r)throw Error("workspaceId is required");let t=(0,u.makeCoworkClient)(r);return await t.groups.addEntity({workspaceId:r,groupId:String(e.groupId),entity_type:e.entityType,entity_id:e.entityId}),{workspaceId:r,groupId:String(e.groupId)}},onSettled:e=>{e&&i.invalidateQueries({queryKey:e7(e.workspaceId,e.groupId)})}})}function e9({workspaceId:e}={}){let{workspaceId:t}=(0,eO.useActiveWorkspace)(),r=e??t,i=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{if(!r)throw Error("workspaceId is required");let t=(0,u.makeCoworkClient)(r);return await t.groups.removeEntity({workspaceId:r,groupId:String(e.groupId),entityType:e.entityType,entityId:e.entityId}),{workspaceId:r,groupId:String(e.groupId)}},onSettled:e=>{e&&i.invalidateQueries({queryKey:e7(e.workspaceId,e.groupId)})}})}let te=(0,eP.createQueryKeyFactory)("group_tasks"),tt=(0,eP.createQueryKeyFactory)("group_board_preferences");async function tr(e){let t=[],r=0;do{let i=await e({limit:200,offset:t.length}),s=i.data??[];if(t.push(...s),r=i.meta.total,0===s.length)break}while(t.length<r)return t}function ti(e,t={}){let{workspaceId:r}=(0,eO.useActiveWorkspace)(),i=t.workspaceId??r;return(0,S.useQuery)({queryKey:[...te.list(e??""),i??"none"],queryFn:async()=>{let t=(0,u.makeCoworkClient)(i);return tr(({limit:r,offset:s})=>t.tasks.listGroupTasks({workspaceId:i,groupId:e,limit:r,offset:s}))},enabled:!!i&&!!e})}function ts(e){let{workspaceId:t}=(0,eO.useActiveWorkspace)(),r=e??t,i=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t,i=(0,u.makeCoworkClient)(r);return(await i.tasks.create({workspaceId:r,...(t=(0,I.mergeTaskContext)(e.context,e)??e.context,{parent_type:"group",parent_id:e.groupId,title:e.title,description:e.description,priority:e.priority??"medium",type:e.type??"task",due_at:e.due_at??(e.dueAt?new Date(e.dueAt).toISOString():void 0),is_important:e.isImportant,is_urgent:e.isUrgent,contexts:e.contexts,waiting_for:e.waitingFor??void 0,sprint_id:e.sprintId??void 0,context:t,assigned_member_id:e.assigned_member_id??e.assigneeId})})).data},onSettled:(e,t,r)=>{i.invalidateQueries({queryKey:te.list(r.groupId)}),i.invalidateQueries({queryKey:["tasks"]})}})}function ta(e,t){let{workspaceId:r}=(0,eO.useActiveWorkspace)(),i=t??r;return(0,S.useQuery)({queryKey:[...tt.detail(e??""),i??"none"],queryFn:async()=>{let t=(0,u.makeCoworkClient)(i);
7return(await t.groups.getBoardPreference({workspaceId:i,groupId:e})).data},enabled:!!i&&!!e})}function tn(e){let{workspaceId:t}=(0,eO.useActiveWorkspace)(),r=e??t,i=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(r);return(await t.groups.updateBoardPreference({workspaceId:r,groupId:e.groupId,view_mode:e.viewMode})).data},onMutate:async e=>{let t=[...tt.detail(e.groupId),r??"none"];await i.cancelQueries({queryKey:t});let s=i.getQueryData(t);return i.setQueryData(t,{view_mode:e.viewMode}),{previous:s,key:t}},onError:(e,t,r)=>{r&&i.setQueryData(r.key,r.previous)},onSettled:(e,t,r)=>{i.invalidateQueries({queryKey:tt.detail(r.groupId)})}})}function to(e,t={}){let{enabled:r=!0}=t;return(0,S.useQuery)({queryKey:eL(e??"none"),enabled:!!e&&r,queryFn:async()=>e?(await eY(e)).map(t=>({id:String(t.id),name:t.name,type:t.type,workspace_id:String(e),created_at:t.created_at})):[]})}e.s(["useCreateComment",()=>tp,"useEntityComments",()=>td,"useReplyToComment",()=>th,"useResolveComment",()=>ty,"useUnresolveComment",()=>tf],892047);var tl=e.i(798574),tc=e.i(938603);function tu(e){let t,r=/\{\{user:([^}]+)\}\}/g,i=new Set;for(;null!==(t=r.exec(e));)i.add(t[1]);return Array.from(i)}function td(e,t,r){let i=(r?.enabled??!0)&&!!t,s=(0,tl.useCommentsCollection)(e,t,r?.workspaceId);return(0,ev.useCollectionRows)(i?s:null)}function tp(){let e=eg();return(0,eq.useMutation)({mutationFn:async t=>{let r=e.comments(t.workspaceId,t.entityType,t.entityId),i=await (0,tc.insertCollectionRow)(r,{id:(0,tc.draftKey)("comment"),entity_type:t.entityType,entity_id:t.entityId,parent_comment_id:t.parentCommentId??null,position:t.position??null,author_id:"",content:t.content,resolved:!1,resolved_by:null,resolved_at:null,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),s=tu(t.content);return s.length>0&&e.client(t.workspaceId).mentions.process({workspaceId:t.workspaceId,sourceType:"comment",sourcePublicId:i.id,mentionedMemberIds:s}).catch(e=>{console.error("[comments] mention processing failed",e)}),i}})}function ty(){let e=eg();return(0,eq.useMutation)({mutationFn:async t=>{let r=e.comments(t.workspaceId,t.entityType,t.entityId);return{comment:await (0,tc.updateCollectionRow)(r,t.commentId,e=>{e.resolved=t.resolved}),entityType:t.entityType,entityId:t.entityId}}})}e.i(973857),e.s(["extractMentionTokens",0,tu],219900);let th=tp;function tf(){let e=ty();return{...e,mutateAsync:(t,r)=>e.mutateAsync({...t,resolved:!1},r),mutate:(t,r)=>e.mutate({...t,resolved:!1},r)}}e.s(["useAddTagToEntity",()=>tb,"useCreateTag",()=>tk,"useEntityTags",()=>tI,"useRemoveTag",()=>tv,"useRemoveTagFromEntity",()=>t_,"useWorkspaceTags",()=>tw],622617);let tm=(e,t,r)=>["entity_tags","entity",e,t,r],tg=e=>["entity_tags","workspace",e];function tw(e){let{workspaceId:t}=(0,eO.useActiveWorkspace)(),r=e??t;return(0,S.useQuery)({queryKey:tg(r??"none"),queryFn:async()=>{if(!r)return[];let e=(0,u.makeCoworkClient)(r);return(await e.tags.list({workspaceId:r})).data??[]},enabled:!!r})}function tk(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);return{data:(await t.tags.create({workspaceId:e.workspaceId,name:e.name,color:e.color})).data,workspaceId:e.workspaceId}},onSuccess:({workspaceId:t})=>{e.invalidateQueries({queryKey:tg(t)})}})}function tb(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);return await t.tags.addToEntity({workspaceId:e.workspaceId,tagId:e.tagId,entity_type:e.entityType,entity_id:e.entityId}),e},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:tm(r.workspaceId,r.entityType,r.entityId)}),e.invalidateQueries({queryKey:tg(r.workspaceId)})}})}function t_(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);return await t.tags.removeFromEntity({workspaceId:e.workspaceId,tagId:e.tagId,entity_type:e.entityType,entity_id:e.entityId}),e},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:tm(r.workspaceId,r.entityType,r.entityId)}
7),e.invalidateQueries({queryKey:tg(r.workspaceId)})}})}let tv=t_;function tI({entityType:e,entityId:t,workspaceId:r,enabled:i=!0}){let{workspaceId:s}=(0,eO.useActiveWorkspace)(),a=r??s,n=String(t);return(0,S.useQuery)({queryKey:tm(a??"none",e,n),queryFn:async()=>{if(!a)return[];let t=(0,u.makeCoworkClient)(a);return(await t.tags.listForEntity({workspaceId:a,entityType:e,entityId:n})).data??[]},enabled:i&&!!a&&!!n})}let tS=(e,t)=>["workspace",e,"folder",t,"ingest-links"];e.s(["useCreateIngestLink",0,function(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);return(await t.folders.createIngestLink(e)).data},onSettled:(t,r,i)=>{e.invalidateQueries({queryKey:tS(i.workspaceId,i.folderId)})}})},"useDeleteIngestLink",0,function(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);await t.folders.deleteIngestLink(e)},onSettled:(t,r,i)=>{e.invalidateQueries({queryKey:tS(i.workspaceId,i.folderId)})}})},"useIngestLinks",0,function(e,t){return(0,S.useQuery)({queryKey:tS(e??"none",t??"none"),queryFn:async()=>{if(!e||!t)return[];let r=(0,u.makeCoworkClient)(e);return(await r.folders.listIngestLinks({workspaceId:e,folderId:t})).data??[]},enabled:!!e&&!!t})},"useUpdateIngestLink",0,function(){let e=(0,l.useQueryClient)();return(0,eq.useMutation)({mutationFn:async e=>{let t=(0,u.makeCoworkClient)(e.workspaceId);return(await t.folders.updateIngestLink(e)).data},onSettled:(t,r,i)=>{e.invalidateQueries({queryKey:tS(i.workspaceId,i.folderId)})}})}],774121),e.s(["useMarkAllNotificationsRead",()=>tK,"useMarkNotificationRead",()=>tM,"useNotifications",()=>tE,"useUnreadNotificationCount",()=>tD],892865);var tC=e.i(669780),tx=e.i(19433);let tF=["meeting_started","meeting_finished","task_assigned","task_resolved","task_reminder","mention","share"],tT={document:{requiresWorkspace:!0,build:(e,t)=>(0,tx.buildDocumentPath)(e,t)},conversation:{requiresWorkspace:!1,build:e=>`/playground/discover?conversation=${e}`},agent:{requiresWorkspace:!1,build:()=>"/agents"},task:{requiresWorkspace:!0,build:(e,t)=>(0,tx.buildWorkspaceEntityPath)(t,"task",e)},whiteboard:{requiresWorkspace:!0,build:(e,t)=>(0,tx.buildWorkspaceEntityPath)(t,"whiteboard",e)},database:{requiresWorkspace:!0,build:(e,t)=>(0,tx.buildWorkspaceEntityPath)(t,"database",e)}};e.s(["HIGH_SIGNAL_NOTIFICATION_TYPES",0,tF,"getNotificationHref",0,function(e,t){let r=e.link_type||e.entity_type,i=e.link_id||e.entity_id,s=e.workspace_id||e.workspaceId||t;if(!r||!i)return null;let a=tT[r];return!a||a.requiresWorkspace&&(null==s||""===String(s).trim())?null:a.build(i,s)}],222792);let tA={limit:50,unreadOnly:!0,highSignalOnly:!0};function tE({limit:e=50,unreadOnly:t=!1,highSignalOnly:r=!0,workspaceId:i,enabled:s=!0}={}){let a=(0,tC.useNotificationsCollection)(i),n=(0,ev.useCollectionRows)(s?a:null),l=(0,o.useMemo)(()=>s?n.data.filter(e=>!t||null===e.read_at).filter(e=>!r||tF.includes(e.type)).slice(0,e):[],[s,r,e,n.data,t]);return{...n,data:l}}function tD(e){let t=tE({...tA,workspaceId:e});return{...t,data:t.data.length}}function tM(){let e=eg();return(0,eq.useMutation)({mutationFn:async({id:t,workspaceId:r})=>{let i=e.workspace(r).notifications;return(0,tc.updateCollectionRow)(i,t,e=>{e.read_at=new Date().toISOString()})}})}function tK(){let e=eg();return(0,eq.useMutation)({mutationFn:async({workspaceId:t})=>{await e.client(t).notifications.markAllRead({workspaceId:t});let r=e.workspace(t).notifications,i=new Date().toISOString();r.utils.writeBatch(()=>{for(let e of r.toArray)null===e.read_at&&r.utils.writeUpdate({...e,read_at:i})})}})}var tq=e.i(360112);let tO={all:["digests"],workspace:e=>["digests","detail",e],detail:(e,t)=>["digests","detail",e,t],limitsWorkspace:e=>["digests","regeneration-limits",e],limits:(e,t)=>["digests","regeneration-limits",e,t],skillWorkspace:e=>["digests","skill",e],skill:(e,t)=>["digests","skill",e,t]};function tP(e,t=Date.now()){if(!e||"object"!=typeof e||!("status"in e)||429!==e.status)return null;let r=e.details&&"object"==typeof e.details?e.details:null;return{can_generate:!1,remaining_today:"number"==typeof r?.remaining_today&&Number.isFinite(r.remaining_today)?Math.max(0,Math.trunc(r.remaining_today)):0,next_allowed_at:"string"==typeof r?.next_allowed_at?r.next_allowed_at:"number"==typeof e.retryAfterSeconds?new Date(t+1e3*e.retryAfterSeconds).toISOString():null}}function tQ(e){return tP(e)?"Your digest is on cooldown. Check the time shown below.":"We couldn’t generate your digest. Please try again."}e.s(["digestGenerationErrorMessage",0,tQ,"digestKeys",0,tO,"getDigestRateLimit",0,tP,"useDigestRegenerationLimits",0,function(e,t=!0){let{cowork:r}=(0,c.useWorkspace)(),{user:i}=(0,C.useAuth)(),s=i?.id??"anonymous";return(0,S.useQuery)({queryKey:tO.limits(e??"none",s),queryFn:async()=>
7{if(!e)throw Error("A workspace is required for digest regeneration limits.");return(await r.digests.getRegenerationLimits({workspaceId:e})).data},enabled:t&&!!e&&!!i,staleTime:6e4,refetchOnWindowFocus:"always"})},"useDigestSkill",0,function(e,t=!0){let{cowork:r}=(0,c.useWorkspace)(),{user:i}=(0,C.useAuth)(),s=i?.id??"anonymous";return(0,S.useQuery)({queryKey:tO.skill(e??"none",s),queryFn:async()=>{if(!e)throw Error("A workspace is required for digest skill settings.");return(await r.digests.getSkill({workspaceId:e})).data.skill},enabled:t&&!!e&&!!i,staleTime:6e4,refetchOnWindowFocus:"always"})},"useRegenerateDigest",0,function(){let e=(0,l.useQueryClient)(),{cowork:t}=(0,c.useWorkspace)(),{user:r}=(0,C.useAuth)(),i=r?.id??"anonymous";return(0,eq.useMutation)({mutationFn:async e=>(await t.digests.regenerate({workspaceId:e})).data,onSuccess:(t,r)=>{e.setQueryData(tO.detail(r,i),t),e.setQueryData(tO.limits(r,i),t.regeneration_limits)},onError:(t,r)=>{let s=tP(t);s&&(e.setQueryData(tO.limits(r,i),s),e.setQueryData(tO.detail(r,i),e=>e?{...e,regeneration_limits:s}:e),e.invalidateQueries({queryKey:tO.detail(r,i)}),e.invalidateQueries({queryKey:tO.limits(r,i)})),tq.toast.error(tQ(t))}})},"useUpdateDigestSkill",0,function(){let e=(0,l.useQueryClient)(),{cowork:t}=(0,c.useWorkspace)(),{user:r}=(0,C.useAuth)(),i=r?.id??"anonymous";return(0,eq.useMutation)({mutationFn:async e=>(await t.digests.updateSkill(e)).data,onSuccess:(t,{workspaceId:r})=>{e.setQueryData(tO.skill(r,i),t.skill),e.setQueryData(tO.detail(r,i),e=>e?{...e,skill:t.skill}:e)}})},"useWorkspaceDigest",0,function(e){let{cowork:t}=(0,c.useWorkspace)(),{user:r}=(0,C.useAuth)(),i=r?.id??"anonymous";return(0,S.useQuery)({queryKey:tO.detail(e??"none",i),queryFn:async()=>e?(await t.digests.getDigest({workspaceId:e})).data??null:null,enabled:!!e&&!!r,staleTime:6e4,refetchInterval:3e5,refetchOnMount:"always",refetchOnWindowFocus:"always"})}],683987);let tR=(e,t)=>["digest-preferences","detail",e,t],tW=new Map;e.s(["useDigestPreference",0,function(e){let{workspaceId:t,cowork:r}=(0,c.useWorkspace)(),{user:i}=(0,C.useAuth)(),s=e??t,a=i?.id??"anonymous",n=(0,l.useQueryClient)(),u=tR(s??"none",a),d=(0,S.useQuery)({queryKey:u,queryFn:async()=>s?(await r.digests.getPreferences({workspaceId:s})).data??null:null,enabled:!!s&&!!i});return(0,o.useEffect)(()=>{if(!s||!i||!d.data?.timezone_is_default)return;let e=function(){if("u"<typeof Intl)return null;try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!e)return null;return Intl.DateTimeFormat(void 0,{timeZone:e}),e}catch{return null}}();if(!e||e===d.data.timezone)return;let t=`${s}:${a}`;if(tW.has(t))return;let o=r.digests.updatePreferences({workspaceId:s,timezone:e}).then(e=>{n.setQueryData(u,e.data),n.invalidateQueries({queryKey:tO.detail(s,a)}),n.invalidateQueries({queryKey:tO.limits(s,a)})}).catch(()=>{console.warn("[digests] timezone_initialization_failed",{workspaceId:s})}).finally(()=>{tW.get(t)===o&&tW.delete(t)});tW.set(t,o)},[r,d.data?.timezone,d.data?.timezone_is_default,n,u,i,a,s]),d},"useUpdateDigestPreference",0,function(){let e=(0,l.useQueryClient)(),{cowork:t}=(0,c.useWorkspace)(),{user:r}=(0,C.useAuth)(),i=r?.id??"anonymous";return(0,eq.useMutation)({mutationFn:async({workspaceId:e,weekly_enabled:r,monthly_enabled:i,hour_of_day:s,timezone:a,relevant_notifications_enabled:n})=>(await t.digests.updatePreferences({workspaceId:e,weekly_enabled:r,monthly_enabled:i,hour_of_day:s,timezone:a,relevant_notifications_enabled:n})).data,onSuccess:(t,r)=>{e.invalidateQueries({queryKey:tR(r.workspaceId,i)}),e.invalidateQueries({queryKey:tO.detail(r.workspaceId,i)}),e.invalidateQueries({queryKey:tO.limits(r.workspaceId,i)})}})}],270867),(r={}
7).Workspace="workspace",r.Internal="internal",r.AllParties="all_parties",r.SpecificParties="specific_parties",(i={}).User="user",i.Agent="agent",i.System="system",i.ExternalUser="external_user",(s={}).Editing="editing",s.Submitted="submitted",s.Merged="merged",s.Abandoned="abandoned",(a={}).BlockDocument="block_document",a.Pdf="pdf",a.Whiteboard="whiteboard",a.Database="database",(n={}).Insert="insert",n.Update="update",n.Delete="delete",e.s([],988558)},296845,e=>{"use strict";e.s(["prefetchSkillDetail",()=>w,"prefetchSkillList",()=>g,"skillDetailQueryKey",()=>p,"skillKeys",()=>u,"skillListQueryKey",()=>d,"useCreateSkill",()=>_,"useDeleteSkill",()=>I,"useSkill",()=>b,"useSkills",()=>k,"useUpdateSkill",()=>v]);var t=e.i(237770),r=e.i(898665),i=e.i(37700),s=e.i(580107);e.i(478539);var a=e.i(495238),n=e.i(623128),o=e.i(599177);let l="no-workspace",c="no-user",u={all:["skills"],lists:()=>["skills","list"],list:e=>["skills","list",e],details:()=>["skills","detail"],detail:e=>["skills","detail",e]};function d(e,t){return[...u.list(e??l),t??c]}function p(e,t,r){return[...u.detail(t),e??l,r??c]}async function y(e){let t=(0,o.makeCoworkClient)(e);return(await t.skills.list({workspaceId:e,limit:20})).data??[]}async function h(e,t){let r=(0,o.makeCoworkClient)(e);return(await r.skills.get({workspaceId:e,skillId:t})).data}function f(e,r,i=6e4){return(0,t.queryOptions)({queryKey:d(e,r),queryFn:()=>{if(!e||!r)throw Error("Skill list query requires workspace and user");return y(e)},staleTime:i})}function m(e,r,i,s=6e4){return(0,t.queryOptions)({queryKey:p(e,r,i),queryFn:()=>{if(!e||!r||!i)throw Error("Skill detail query requires skill, workspace, and user");return h(e,r)},staleTime:s})}function g(e,t,r){return t&&r?e.prefetchQuery(f(t,r)):Promise.resolve()}function w(e,t,r,i){return t&&r&&i?(!function(e,t,r,i){if(!t||!r||!i)return;let s=p(t,r,i);if(void 0!==e.getQueryData(s))return;let a=e.getQueryState(d(t,i));if(!a)return;let n=a.data?.find(e=>String(e.id)===r);n&&e.setQueryData(s,n,{updatedAt:a.dataUpdatedAt})}(e,t,r,i),e.prefetchQuery(m(t,r,i))):Promise.resolve()}function k(e,t){let{user:r}=(0,a.useAuth)(),{workspaceId:s}=(0,n.useActiveWorkspace)(),o=e??s,l=r?.id??null;return(0,i.useQuery)({...f(o,l,t?.staleTime),enabled:(t?.enabled??!0)&&!!o&&!!l,refetchOnMount:t?.refetchOnMount??!0})}function b(e,t,r){let o=(0,s.useQueryClient)(),{user:l}=(0,a.useAuth)(),{workspaceId:c}=(0,n.useActiveWorkspace)(),u=t??c,p=l?.id??null,y=d(u,p);return(0,i.useQuery)({...m(u,e,p,r?.staleTime),enabled:(r?.enabled??!0)&&!!u&&!!e&&!!p,initialData:()=>o.getQueryData(y)?.find(t=>String(t.id)===e),initialDataUpdatedAt:()=>o.getQueryState(y)?.dataUpdatedAt,refetchOnMount:!0})}function _(){let e=(0,s.useQueryClient)(),{user:t}=(0,a.useAuth)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,o.makeCoworkClient)(e.workspaceId);return(await t.skills.create({workspaceId:e.workspaceId,name:e.name,description:e.description,instructions:e.instructions,icon:e.icon,visibility:e.visibility??"private"})).data},onSuccess:(r,{workspaceId:i})=>{t?.id&&(e.setQueryData(p(i,String(r.id),t.id),r),e.setQueryData(d(i,t.id),e=>e?[r,...e.filter(e=>String(e.id)!==String(r.id))].slice(0,20):e))}})}function v(){let e=(0,s.useQueryClient)(),{user:t}=(0,a.useAuth)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,o.makeCoworkClient)(e.workspaceId);return(await t.skills.update({workspaceId:e.workspaceId,skillId:e.skillId,name:e.name,description:e.description,instructions:e.instructions,icon:e.icon,visibility:e.visibility})).data},onSuccess:(r,{workspaceId:i})=>{t?.id&&(e.setQueryData(p(i,String(r.id),t.id),r),e.setQueryData(d(i,t.id),e=>(function(e,t){if(!e)return e;let r=e.findIndex(e=>String(e.id)===String(t.id));if(-1===r)return e;let i=[...e];return i[r]=t,i})(e,r)))}})}function I(){let e=(0,s.useQueryClient)(),{user:t}=(0,a.useAuth)();return(0,r.useMutation)({mutationFn:async({skillId:e,workspaceId:t})=>{let r=(0,o.makeCoworkClient)(t);await r.skills.delete({workspaceId:t,skillId:e})},onSuccess:(r,{skillId:i,workspaceId:s})=>{t?.id&&(e.setQueryData(d(s,t.id),e=>e?.filter(e=>String(e.id)!==String(i))),e.removeQueries({queryKey:p(s,String(i),t.id),exact:!0}))}})}},295102,677217,e=>{"use strict";e.s(["useCreateEmailInvites",()=>y,"useCreateInviteLink",()=>p,"useInviteLinks",()=>u,"useJoinViaInviteLink",()=>f,"useRejectInviteLink",()=>m,"useRevokeInviteLink",()=>h,"useValidateInviteLink",()=>d],295102);var t=e.i(37700),r=e.i(898665),i=e.i(580107),s=e.i(623128),a=e.i(599177),n=e.i(8551),o=e.i(91251);let l=(0,n.createQueryKeyFactory)("invite_links");(0,n.createQueryKeyFactory)("workspace_roles");let c=e=>["invite_links","code",e];function u(e){let{workspaceId:r}=(0,s.useActiveWorkspace)(),i=e??r;return(0,t.useQuery)({queryKey:l.list(i??"none"),queryFn:async()=>
7{if(!i)return[];let e=(0,a.makeCoworkClient)(i);return(await e.invites.list({workspaceId:i})).data??[]},enabled:!!i})}function d({code:e,enabled:r=!0}){return(0,t.useQuery)({queryKey:c(e),queryFn:async()=>(0,o.getWorkspaceInviteInfo)(e),enabled:r&&e.length>0,staleTime:3e4})}function p(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,a.makeCoworkClient)(e.workspaceId);return{data:(await t.invites.create({workspaceId:e.workspaceId,role:e.role,expires_at:e.expires_at,max_uses:e.max_uses})).data,workspaceId:e.workspaceId}},onSuccess:({workspaceId:t})=>{e.invalidateQueries({queryKey:l.list(t)})}})}function y(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,a.makeCoworkClient)(e.workspaceId);return{data:(await t.invites.createEmailInvites({workspaceId:e.workspaceId,role:e.role,emails:e.emails,expires_at:e.expires_at})).data,workspaceId:e.workspaceId}},onSuccess:({workspaceId:t})=>{e.invalidateQueries({queryKey:l.list(t)})}})}function h(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,a.makeCoworkClient)(e.workspaceId);return await t.invites.revoke({workspaceId:e.workspaceId,inviteId:e.inviteId}),{inviteId:e.inviteId,workspaceId:e.workspaceId}},onSuccess:({workspaceId:t})=>{e.invalidateQueries({queryKey:l.list(t)})}})}function f(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async({code:e})=>(0,o.acceptWorkspaceInvite)(e),onSuccess:()=>{e.invalidateQueries({queryKey:["workspaces"]}),e.invalidateQueries({queryKey:["invite_links"]})}})}function m(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async({code:e})=>{await (0,o.rejectWorkspaceInvite)(e)},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:["workspaces"]}),e.invalidateQueries({queryKey:c(r.code)})}})}e.s([],677217),(0,n.createQueryKeyFactory)("captures")},373977,e=>{"use strict";e.s(["useCreateShareLink",()=>d,"useDeleteShareLink",()=>p,"useEntityLinks",()=>c,"useLegacyAddPermission",()=>f,"useLegacyEntityPermissions",()=>h,"useLegacyRemovePermission",()=>g,"useLegacyUpdatePermission",()=>m,"useShareInfo",()=>u,"useUpdateVisibility",()=>w]);var t=e.i(37700),r=e.i(898665),i=e.i(580107),s=e.i(623128),a=e.i(599177);(0,e.i(8551).createQueryKeyFactory)("entity_permissions");let n=(e,t)=>["entity_permissions","entity",e,t],o=(e,t)=>["entity_permissions","links",e,t],l=(e,t)=>["entity_permissions","share_info",e,t];function c({entityType:e,entityId:r,enabled:i=!0,workspaceId:n}){let{workspaceId:l}=(0,s.useActiveWorkspace)(),u=n??l;return(0,t.useQuery)({queryKey:o(e,r),queryFn:async()=>{if(!u)return[];let t=(0,a.makeCoworkClient)(u);return(await t.permissions.listLinks({workspaceId:u,entityType:e,entityId:r})).data??[]},enabled:i&&!!r&&!!u})}function u({entityType:e,entityId:r,enabled:i=!0,workspaceId:n}){let{workspaceId:o}=(0,s.useActiveWorkspace)(),c=n??o;return(0,t.useQuery)({queryKey:l(e,r),queryFn:async()=>{if(!c)throw Error("No workspace available");let t=(0,a.makeCoworkClient)(c);return(await t.permissions.getShareInfo({workspaceId:c,entityType:e,entityId:r})).data},enabled:i&&!!r&&!!c})}function d(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,a.makeCoworkClient)(e.workspaceId);return(await t.permissions.createLink({workspaceId:e.workspaceId,entityType:e.entityType,entityId:e.entityId,role:e.role,is_public:e.isPublic})).data},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:o(r.entityType,r.entityId)}),e.invalidateQueries({queryKey:l(r.entityType,r.entityId)})}})}function p(){let e=(0,i.useQueryClient)();return(0,r.useMutation)({mutationFn:async e=>{let t=(0,a.makeCoworkClient)(e.workspaceId);return await t.permissions.deleteLink({workspaceId:e.workspaceId,entityType:e.entityType,entityId:e.entityId,linkToken:e.linkToken}),e},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:o(r.entityType,r.entityId)}),e.invalidateQueries({queryKey:l(r.entityType,r.entityId)})}})}function y(e){switch(e){case"write":return"editor";case"comment":return"commenter";default:return"viewer"}}function h({entityType:e,entityId:r,workspaceId:i,enabled:o=!0}){let{workspaceId:l}=(0,s.useActiveWorkspace)(),c=i??l;return(0,t.useQuery)({queryKey:n(e,r),queryFn:async()=>
7{if(!c)return[];let t=(0,a.makeCoworkClient)(String(c)),i=((await t.permissions.listPermissions({workspaceId:String(c),entityType:e,entityId:String(r)})).data??[]).map(e=>({id:e.id,entity_type:e.entity_type,entity_id:e.entity_id,user_id:e.user_id||null,permission:function(e){switch(e){case"editor":return"write";case"commenter":return"comment";default:return"read"}}(e.role),created_at:e.created_at,user:null})),s=[...new Set(i.filter(e=>e.user_id).map(e=>e.user_id))];if(s.length>0&&c)try{let e=(await Promise.allSettled(Array.from({length:Math.ceil(s.length/100)},(e,r)=>{let i=s.slice(100*r,(r+1)*100);return t.workspaces.listMembers({workspaceId:String(c),limit:i.length,userIds:i})}))).flatMap(e=>"rejected"===e.status?(console.error("[useLegacyEntityPermissions] Failed to fetch a user profile batch:",e.reason),[]):e.value.data??[]),r=new Map(e.map(e=>[e.id,e]));i.forEach(e=>{if(e.user_id){let t=r.get(e.user_id);t&&(e.user={id:e.user_id,email:t.email||e.user_id,raw_user_meta_data:{full_name:t.display_name||void 0,avatar_url:t.avatar_url||void 0}})}})}catch(e){console.error("[useLegacyEntityPermissions] Failed to fetch user profiles:",e)}return i},enabled:o&&!!r&&!!c})}function f(){let e=(0,i.useQueryClient)(),{workspaceId:t}=(0,s.useActiveWorkspace)();return(0,r.useMutation)({mutationFn:async e=>{if(!t)throw Error("No workspace available");let r=(0,a.makeCoworkClient)(String(t));return await r.permissions.createPermission({workspaceId:String(t),entityType:e.entityType,entityId:String(e.entityId),user_id:e.userId,role:y(e.permission),share_source_databases:e.shareSourceDatabases}),e},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:n(r.entityType,r.entityId)})}})}function m(){let e=(0,i.useQueryClient)(),{workspaceId:t}=(0,s.useActiveWorkspace)();return(0,r.useMutation)({mutationFn:async e=>{if(!t)throw Error("No workspace available");if(e.entityType&&e.entityId&&e.userId){let r=(0,a.makeCoworkClient)(String(t));await r.permissions.deletePermission({workspaceId:String(t),entityType:e.entityType,entityId:String(e.entityId),userId:e.userId}),await r.permissions.createPermission({workspaceId:String(t),entityType:e.entityType,entityId:String(e.entityId),user_id:e.userId,role:y(e.permission)})}return e},onSettled:()=>{e.invalidateQueries({queryKey:["entity_permissions"]})}})}function g(){let e=(0,i.useQueryClient)(),{workspaceId:t}=(0,s.useActiveWorkspace)();return(0,r.useMutation)({mutationFn:async({id:e,entityType:r,entityId:i,userId:s})=>{if(!t||!s)throw Error("Cannot remove permission without workspace and user context");let n=(0,a.makeCoworkClient)(String(t));return await n.permissions.deletePermission({workspaceId:String(t),entityType:r,entityId:String(i),userId:s}),{id:e,entityType:r,entityId:i}},onSuccess:t=>{e.invalidateQueries({queryKey:n(t.entityType,t.entityId)})}})}function w(){let e=(0,i.useQueryClient)(),{workspaceId:t}=(0,s.useActiveWorkspace)();return(0,r.useMutation)({mutationFn:async({entityType:e,entityId:r,visibility:i,workspaceId:s})=>{let n=s??t;if(!n)throw Error("Cannot update visibility without workspace context");if("skills"!==e)throw Error(`Visibility updates are not supported for ${e}`);let o=(0,a.makeCoworkClient)(String(n)),l=await o.skills.update({workspaceId:String(n),skillId:String(r),visibility:i});return{entityType:e,entityId:r,visibility:i,workspaceId:n,data:l.data}},onSuccess:t=>{e.invalidateQueries({queryKey:[t.entityType,"detail",t.entityId]}),t.workspaceId&&(e.invalidateQueries({queryKey:["skills","list"]}),e.invalidateQueries({queryKey:["workspace-content",t.workspaceId]}))}})}},37159,e=>{"use strict";e.i(270331),e.s([])},253650,110401,958738,799274,353019,568720,667546,790026,669546,31807,503096,248586,574653,503122,971131,693678,e=>{"use strict";e.s([],253650),e.s([],971131),e.i(428344),e.i(69739),e.i(430295),e.i(892047),e.i(622617),e.i(774121),e.i(892865),e.i(270867),e.i(187177),e.i(272893),e.i(988558),e.i(296845),e.i(142533),e.i(328188),e.i(355129),e.i(434659),e.i(295102),e.i(677217),e.i(506715),e.i(602668),e.i(210321),e.i(373977),e.i(583818),e.i(230605);var t=e.i(751019),r=e.i(8551);(0,r.createQueryKeyFactory)("task_reminders");var i=e.i(237770),s=e.i(37700),a=e.i(898665),n=e.i(580107);e.i(478539);var o=e.i(495238);
7async function l(e){let t=await fetch(`/api/workspaces/${e}/task-framework-preferences`,{cache:"no-store"});if(!t.ok)throw Error("Failed to load task framework preference");return(await t.json()).data}async function c({workspaceId:e,activeFramework:t,enabledViews:r,customColumns:i,customContexts:s}){let a=await fetch(`/api/workspaces/${e}/task-framework-preferences`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({...void 0!==t&&{activeFramework:t},...void 0!==r&&{enabledViews:r},...void 0!==i&&{customColumns:i},...void 0!==s&&{customContexts:s}})});if(!a.ok)throw Error("Failed to update task framework preference");return(await a.json()).data}let u={all:["task-framework-preferences"],list:e=>["task-framework-preferences","list",String(e??"none")]},d={active_framework:"simple",enabled_views:["list","kanban","timeline"],custom_columns:[{id:"todo",name:"To Do",color:"bg-slate-500"},{id:"in-progress",name:"In Progress",color:"bg-blue-500"},{id:"review",name:"Review",color:"bg-yellow-500"},{id:"done",name:"Done",color:"bg-green-500"}],custom_contexts:["@phone","@computer","@home","@errands","@office","@anywhere"]};function p(e,t){return(0,i.queryOptions)({queryKey:[...u.list(e),t],queryFn:()=>l(e)})}e.s(["getEffectivePreference",0,function(e){return e?{active_framework:e.active_framework??d.active_framework,enabled_views:e.enabled_views??d.enabled_views,custom_columns:e.custom_columns??d.custom_columns,custom_contexts:e.custom_contexts??d.custom_contexts}:d},"getTaskFrameworkPreferenceQueryOptions",0,p,"taskFrameworkPreferenceKeys",0,u,"useTaskFrameworkPreference",0,function(e){let{user:t}=(0,o.useAuth)(),r=e?String(e):void 0;return(0,s.useQuery)({...p(r??"none",t?.id??"none"),enabled:!!r&&!!t})},"useUpdateTaskFrameworkPreference",0,function(){let e=(0,n.useQueryClient)(),{user:t}=(0,o.useAuth)();return(0,a.useMutation)({mutationFn:async e=>{if(!t)throw Error("Not authenticated");return c(e)},onMutate:async({workspaceId:e})=>({previousValue:void 0,workspaceKey:String(e)}),onError:(r,{workspaceId:i},s)=>{s?.previousValue!==void 0&&e.setQueryData([...u.list(s.workspaceKey??i),t?.id],s.previousValue)},onSettled:(r,i,{workspaceId:s})=>{e.invalidateQueries({queryKey:[...u.list(String(s)),t?.id]})}})}],110401),e.s(["onboardingTaskKeys",()=>b,"useEnsureOnboardingTasks",()=>S,"useOnboardingTasks",()=>I],958738);var y=e.i(982472);let h=[{id:"first_document_created",name:"Created First Document",description:"User created their first document",points:15},{id:"first_ai_conversation",name:"Started First AI Conversation",description:"User started their first AI conversation",points:15},{id:"first_task_created",name:"Created First Task",description:"User created their first task",points:10}],f=h.reduce((e,t)=>e+t.points,0);e.i(60243);var m=e.i(599177),g=e.i(593463);e.i(999e3);var w=e.i(390850);let k=new Set,b={all:["onboarding-tasks"],list:e=>["onboarding-tasks","list",e]};function _(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function v(e,t){let r=_(e.resolved_at),i=_(t.resolved_at);if(null!==r&&null!==i&&r!==i)return r-i;if(null!==r)return -1;if(null!==i)return 1;let s=_(e.updated_at)??1/0,a=_(t.updated_at)??1/0;if(s!==a)return s-a;let n=_(e.created_at)??1/0,o=_(t.created_at)??1/0;return n!==o?n-o:String(e.id).localeCompare(String(t.id))}function I(e){let{user:r}=(0,o.useAuth)(),[i,a]=(0,y.useState)(0),{data:n,isLoading:l}=(0,s.useQuery)({queryKey:b.list(e),queryFn:async()=>e?((await (0,m.makeCoworkClient)(e).tasks.list({workspaceId:e,type:"action",limit:100})).data??[]).filter(e=>"action"===e.type&&!!e.context?.onboarding):[],enabled:!!e&&!!r}),c=n??[],u=c.filter(e=>(0,t.isTaskActiveWorkStatus)(e.status)),d=c.filter(e=>"resolved"===e.status),p=d.reduce((e,t)=>{let r=t.context?.points;return e+("number"==typeof r?r:0)},0),k=c.length>0?c.length:h.length,_=d.toSorted(v)[0],I=_?.context?.milestone_id,S="string"==typeof I?I:"reconciled_content_creation";return(0,y.useEffect)(()=>{e&&!l&&0!==d.length&&(0,g.trackUserActivatedOnce)({workspaceId:e,activationScore:p,activationMilestone:S})},[e,l,d.length,p,S,i]),(0,y.useEffect)(()=>{let e=()=>{a(e=>e+1)},t=t=>{"analytics"===t.detail&&e()},r=t=>{t.key===w.COOKIE_CONSENT_STORAGE_KEY&&"analytics"===t.newValue&&e()};return window.addEventListener(w.COOKIE_CONSENT_CHANGED_EVENT,t),window.addEventListener("storage",r),()=>{window.removeEventListener(w.COOKIE_CONSENT_CHANGED_EVENT,t),window.removeEventListener("storage",r)}},[]),{tasks:c,pendingTasks:u,completedTasks:d,completedCount:d.length,totalCount:k,activationScore:p,isActivated:p>=f,isLoading:l}}function S(e){let{user:r}=(0,o.useAuth)(),i=(0,n.useQueryClient)(),s=(0,y.useRef)(null),l=(0,a.useMutation)({mutationFn:async()=>{e&&r&&await (0,m.makeCoworkClient)(e).onboarding.ensure({workspaceId:e})},onSuccess:()=>{e&&(i.invalidateQueries({queryKey:b.list(e)}),i.invalidateQueries({queryKey:t.taskKeys.list(e)}))},onError:()=>{e&&k.delete(e)}});return(0,y.useEffect)(()=>{!e||!r||l.isPending||(s.current!==e&&(s.current=e),k.has(e)||(k.add(e),l.mutate()))},[e,r,l]),l}e.s(["useDismissPrompt",()=>q,"useFeaturePrompts",()=>K],353019);var C=e.i(623128);let x=[{id:"discover_ai_assistant",title:"Try the AI Assistant",description:"You have several documents now. Ask the AI to summarize, analyze, or answer questions about your content.",ctaLabel:"Start a Conversation",ctaHref:"/conversations",trigger:e=>e.documentCount>=3&&0===e.conversationCount,icon:"sparkles"},{id:"invite_teammates",title:"Invite Your Team",description:"Wyatt is better with teammates. Collaborate on documents and databases together.",ctaLabel:"Invite Members",ctaHref:"/settings/workspace",trigger:e=>1===e.teamMemberCount&&e.workspaceAge>=3,icon:"users"},{id:"discover_integrations",title:"Connect Your Tools",description:"Integrate Wyatt with your existing tools for a seamless workflow.",ctaLabel:"View Integrations",ctaHref:"/settings/integrations",trigger:e=>e.workspaceAge>=7&&e.teamMemberCount>=2,icon:"plug"}];async function F(e,t){let r,i;if(!t)return;let s=`wyatt:dismissed-feature-prompts:${t}:${e}`;try{r=window.localStorage.getItem(s)}catch{return}if(null===r)return;try{let e=JSON.parse(r);i=Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{window.localStorage.removeItem(s);return}
7let a=(0,m.makeWyattClient)(e).workspaces;for(let t of i)await a.dismissFeaturePrompt({workspaceId:e,promptId:t});window.localStorage.removeItem(s)}async function T(e,t,r){return await F(e,r),(await (0,m.makeWyattClient)(e).workspaces.getFeaturePromptEligibility({workspaceId:e,promptId:t})).data}async function A(e,t){return await F(e,t),(await (0,m.makeWyattClient)(e).workspaces.listDismissedFeaturePrompts({workspaceId:e})).data}async function E(e){await (0,m.makeWyattClient)(e.workspaceId).workspaces.dismissFeaturePrompt(e)}async function D(e){let t=String(e),r=(0,m.makeWyattClient)(t),[i,s,a,n,o,l]=await Promise.all([r.documents.list({workspaceId:t,limit:1}),r.databases.list({workspaceId:t,limit:1}),r.whiteboards.list({workspaceId:t,limit:1}),r.chat.listConversations({workspaceId:t,limit:1}),r.workspaces.listMembers({workspaceId:t,limit:1}),r.workspaces.get({workspaceId:t})]),c=l.data.created_at,u=c?Math.max(0,Math.floor((Date.now()-new Date(c).getTime())/864e5)):0;return{documentCount:i.meta?.total??i.data.length,databaseCount:s.meta?.total??s.data.length,whiteboardCount:a.meta?.total??a.data.length,conversationCount:n.meta?.total??n.data.length,automationCount:0,teamMemberCount:o.meta?.total??o.data.length,workspaceAge:u}}e.s(["dismissFeaturePromptViaRoute",0,E,"fetchDismissedFeaturePromptsViaRoute",0,A,"fetchFeaturePromptEligibilityViaRoute",0,T],799274);let M=(0,r.createQueryKeyFactory)("feature-prompts");function K(e){let{workspaceId:t}=(0,C.useActiveWorkspace)(),r=e??t,{user:i}=(0,o.useAuth)();return(0,s.useQuery)({queryKey:[...M.all,r??"none",i?.id],queryFn:async()=>{if(!r||!i)return[];let[e,t]=await Promise.all([D(r),A(r,i.id)]);return x.filter(r=>{if(t.includes(r.id))return!1;try{return r.trigger(e)}catch(e){return console.error(e),!1}})},enabled:!!r&&!!i,refetchInterval:3e5})}function q(){let e=(0,n.useQueryClient)(),{user:t}=(0,o.useAuth)();return(0,a.useMutation)({mutationFn:async({promptId:e,workspaceId:r})=>{if(!t)throw Error("User not authenticated");return await E({workspaceId:r,promptId:e,userId:t.id}),{workspaceId:r}},onSuccess:t=>{t?.workspaceId&&e.invalidateQueries({queryKey:[...M.all,t.workspaceId]})}})}let O=(0,r.createQueryKeyFactory)("table-group-scopes"),P=(0,r.createQueryKeyFactory)("table-group-column-access"),Q="Legacy table authorization same-origin /api adapters are unsupported until Wyatt data-plane table authorization endpoints exist.";async function R(e,t,r){throw Error(Q)}async function W(e){throw Error(Q)}async function B(e){throw Error(Q)}async function j(e){throw Error(Q)}async function $(e,t,r){throw Error(Q)}async function N(e){throw Error(Q)}async function L(e){throw Error(Q)}async function U(e){throw Error(Q)}e.s(["useCreateTableGroupColumnAccess",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:N,onSuccess:(t,r)=>{e.invalidateQueries({queryKey:P.list({tableId:r.tableId})})}})},"useCreateTableGroupScope",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:W,onSuccess:(t,r)=>{e.invalidateQueries({queryKey:O.list({tableId:r.tableId})})}})},"useDeleteTableGroupColumnAccess",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:U,onSuccess:(t,r)=>{e.invalidateQueries({queryKey:P.list({tableId:r.tableId})})}})},"useDeleteTableGroupScope",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:j,onSuccess:(t,r)=>{e.invalidateQueries({queryKey:O.list({tableId:r.tableId})})}})},"useTableGroupColumnAccess",0,function({tableId:e}){return(0,s.useQuery)({queryKey:P.list({tableId:e}),queryFn:async()=>$(e),enabled:!!e})},"useTableGroupScopes",0,function({tableId:e}){return(0,s.useQuery)({queryKey:O.list({tableId:e}),queryFn:async()=>R(e),enabled:!!e})},"useUpdateTableGroupColumnAccess",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:L,onSuccess:t=>{e.invalidateQueries({queryKey:P.list({tableId:t.table_id})})}})},"useUpdateTableGroupScope",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:B,onSuccess:t=>{e.invalidateQueries({queryKey:O.list({tableId:t.table_id})})}})}],568720),e.i(683987);let z=(0,r.createQueryKeyFactory)("bots");e.s(["useBot",0,function(e,t){return(0,s.useQuery)({queryKey:z.detail(t??"none"),queryFn:async()=>
7{if(!e||!t)return null;let r=(0,m.makeCoworkClient)(e);return(await r.bots.get({workspaceId:e,botId:t})).data??null},enabled:!!e&&!!t})},"useBots",0,function(e){return(0,s.useQuery)({queryKey:z.list({workspaceId:e??"none"}),queryFn:async()=>{if(!e)return[];let t=(0,m.makeCoworkClient)(e);return(await t.bots.list({workspaceId:e})).data??[]},enabled:!!e})},"useCreateBot",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.bots.create(e)).data},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:z.list({workspaceId:r.workspaceId})})}})},"useDeleteBot",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return await t.bots.delete(e),e},onSuccess:t=>{e.removeQueries({queryKey:z.detail(t.botId)}),e.invalidateQueries({queryKey:z.list({workspaceId:t.workspaceId})})}})},"useUpdateBot",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.bots.update(e)).data},onSuccess:(t,r)=>{t&&e.setQueryData(z.detail(r.botId),t),e.invalidateQueries({queryKey:z.detail(r.botId)}),e.invalidateQueries({queryKey:z.list({workspaceId:r.workspaceId})})}})}],667546);var V=e.i(534167);let G=e=>["workspace",e??"none","slack-install"];e.s(["useDisconnectSlackInstall",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return await t.integrations.deleteSlackInstall(e),e},onSuccess:t=>{e.setQueryData(G(t.workspaceId),null)}})},"useSlackInstall",0,function(e){return(0,s.useQuery)({queryKey:G(e),queryFn:async()=>{if(!e)return null;let t=(0,m.makeCoworkClient)(e);try{return(await t.integrations.getSlackInstall({workspaceId:e})).data??null}catch(e){if(e instanceof V.CoworkApiError&&404===e.status)return null;throw e}},enabled:!!e})},"useUpdateSlackInstall",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.integrations.updateSlackInstall(e)).data??null},onSuccess:(t,r)=>{e.setQueryData(G(r.workspaceId),t)}})}],790026);let J=(0,r.createQueryKeyFactory)("scorecards"),H={...J,candidate:(e,t)=>[...J.all,"candidate",e,t]};e.s(["useCandidateScorecards",0,function(e,t){return(0,s.useQuery)({queryKey:H.candidate(e??"none",t??"none"),queryFn:async()=>{if(!e||!t)return null;let r=(0,m.makeCoworkClient)(e);return(await r.scorecards.listSubmissions({workspaceId:e,candidateRowId:t})).data},enabled:!!e&&!!t})},"useCreateScorecardSubmission",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.scorecards.createSubmission(e)).data},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:H.candidate(r.workspaceId,r.candidate_row_id)})}})},"useCreateScorecardTemplate",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.scorecards.create(e)).data},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:H.list({workspaceId:r.workspaceId})})}})},"useDeleteScorecardTemplate",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return await t.scorecards.delete(e),e},onSuccess:t=>{e.invalidateQueries({queryKey:H.list({workspaceId:t.workspaceId})})}})},"useScorecardTemplates",0,function(e){return(0,s.useQuery)({queryKey:H.list({workspaceId:e??"none"}),queryFn:async()=>{if(!e)return[];let t=(0,m.makeCoworkClient)(e);return(await t.scorecards.list({workspaceId:e})).data??[]},enabled:!!e})},"useUpdateScorecardTemplate",0,function(){let e=(0,n.useQueryClient)();return(0,a.useMutation)({mutationFn:async e=>{let t=(0,m.makeCoworkClient)(e.workspaceId);return(await t.scorecards.update(e)).data},onSuccess:(t,r)=>{e.invalidateQueries({queryKey:H.list({workspaceId:r.workspaceId})})}})}],669546);var Y=e.i(270331);e.s(["useMeetings",0,function(e={}){let{workspaceId:t,cowork:r}=(0,Y.useWorkspace)();return(0,s.useQuery)({queryKey:["meetings","list",t??"none",e],enabled:!!t,queryFn:async()=>t?(await r.meetings.list({workspaceId:t,...e})).data:[]})}],31807);let Z=e=>["meeting-settings","detail",e];e.s(["useMeetingSettings",0,function(e){let{workspaceId:t,cowork:r}=(0,Y.useWorkspace)(),i=e??t;return(0,s.useQuery)({queryKey:Z(i??"none"),enabled:!!i,queryFn:async()=>i?(await r.meetings.getSettings({workspaceId:i})).data:null})},"useUpdateMeetingSettings",0,function(){let e=(0,n.useQueryClient)(),{cowork:t}=(0,Y.useWorkspace)();return(0,a.useMutation)({mutationFn:async e=>(await t.meetings.updateSettings(e)).data,onMutate:async t=>{let r=Z(t.workspaceId);await e.cancelQueries({queryKey:r});let i=e.getQueryData(r);return i&&e.setQueryData(r,{...i,...t.update}),{previous:i}},onError:(t,r,i)=>{i?.previous&&e.setQueryData(Z(r.workspaceId),i.previous)},onSettled:(t,r,i)=>
7{e.invalidateQueries({queryKey:Z(i.workspaceId)})}})}],503096);e.s(["useMeetingStatsAggregate",0,function(e={}){let{workspaceId:t,cowork:r}=(0,Y.useWorkspace)(),i=e.window??"30d";return(0,s.useQuery)({queryKey:["meeting-stats","aggregate",t??"none",i],enabled:!!t,queryFn:async()=>t?(await r.meetings.getStats({workspaceId:t,window:i})).data:null})}],248586);e.s(["useMeetingSearch",0,function(e){let{workspaceId:t,cowork:r}=(0,Y.useWorkspace)(),i=e.limit??20,a=function(e){let[t,r]=(0,y.useState)(e);return(0,y.useEffect)(()=>{let t=setTimeout(()=>r(e),250);return()=>clearTimeout(t)},[e,250]),t}(e.q.trim()),n=(e.enabled??!0)&&!!t&&a.length>0;return(0,s.useQuery)({queryKey:["meeting-search",t??"none",a,i],enabled:n,queryFn:async()=>t?(await r.meetings.search({workspaceId:t,q:a,limit:i})).data:[]})}],574653);let X=(e,t)=>["meeting-transcripts","detail",e,t];e.s(["useMeetingTranscript",0,function({workspaceId:e,meetingId:t,enabled:r=!0}){let{cowork:i}=(0,Y.useWorkspace)();return(0,s.useQuery)({queryKey:X(e,t),enabled:r&&!!(e&&t),retry:!1,queryFn:()=>i.meetings.transcript({workspaceId:e,meetingId:t}),refetchInterval:e=>{let t=e.state.data?.diarization.status;return("queued"===t||"processing"===t)&&3e3}})},"usePrepareMeetingSpeakers",0,function(){let e=(0,n.useQueryClient)(),{cowork:t}=(0,Y.useWorkspace)();return(0,a.useMutation)({mutationFn:async e=>(await t.meetings.prepareSpeakerDiarization(e)).data,onSuccess:(t,r)=>{e.setQueryData(X(r.workspaceId,r.meetingId),e=>e?{...e,diarization:t}:e)}})},"useUpdateMeetingSpeakers",0,function(){let e=(0,n.useQueryClient)(),{cowork:t}=(0,Y.useWorkspace)();return(0,a.useMutation)({mutationFn:async e=>(await t.meetings.updateSpeakers(e)).data.speakers,onMutate:async t=>{let r=X(t.workspaceId,t.meetingId);await e.cancelQueries({queryKey:r});let i=e.getQueryData(r);if(i){let s=new Map(t.speakers.map(e=>[e.speaker,e]));e.setQueryData(r,{...i,diarization:{...i.diarization,speakers:i.diarization.speakers.map(e=>s.get(e.speaker)??e)}})}return{previous:i}},onError:(t,r,i)=>{i?.previous&&e.setQueryData(X(r.workspaceId,r.meetingId),i.previous)},onSuccess:(t,r)=>{e.setQueryData(X(r.workspaceId,r.meetingId),e=>e?{...e,diarization:{...e.diarization,speakers:t}}:e)}})}],503122),e.i(37159);e.s(["useTrendingFiles",0,function(e){let{workspaceId:t,cowork:r}=(0,Y.useWorkspace)(),i=e??t;return(0,s.useQuery)({queryKey:["workspace",i??"none","trending"],queryFn:async()=>{if(!i)throw Error("workspaceId is required to load trending files");return(await r.analytics.getTrendingFiles({workspaceId:i})).data},enabled:!!i})}],693678)},668454,e=>{"use strict";let t=/^\/workspaces\/[^/?#]+\/documents\/([^/?#]+)(?:[/?#]|$)/,r=/^\/documents\/([^/?#]+)(?:[/?#]|$)/;function i(e){let r=t.exec(e);return!!r&&r[1].includes("-")}e.s(["isDocumentDetailPath",0,function(e){if(i(e))return!0;let t=r.exec(e);return!!t?.[1]?.includes("-")},"isPublicDocumentDetailPath",0,i])},551117,e=>{"use strict";var t=e.i(668454);let r=["/","/login","/registration","/auth","/oauth","/playground","/dev-components","/invite","/join","/share","/join-workspace","/ingest","/docs","/blog","/changelog","/onboarding","/demo","/privacy-policy","/terms-of-use","/terms-of-use-nz","/about","/pricing","/security","/ai-workspace","/ai-agent-workspace","/ai-project-management","/ai-knowledge-management","/document-collaboration","/connectors","/explore","/product","/ai","/solutions","/use-cases","/comparison","/guides"];function i(e){return r.some(t=>e===t||"/"!==t&&e.startsWith(`${t}/`))}function s(e){if(!e)return!1;if(i(e)||(0,t.isPublicDocumentDetailPath)(e))return!0;let r=e.split("/").filter(Boolean);return 2===r.length&&"workspaces"===r[0]}e.s(["isWorkspaceChromeLoading",0,function({workspacesPending:e,acceptedWorkspaceCount:t}){return e&&0===t},"isWorkspaceGuardBypassRoute",0,s,"isWorkspaceIndependentRoute",0,i,"resolveWorkspaceMembershipState",0,function({authLoading:e,hasUser:t,isWorkspaceLoading:r,workspaceCount:i,hasLookupError:s}){return e||r?"loading":t?s?"error":i>0?"ready":"empty":"unauthenticated"},"shouldShowNoWorkspacePrompt",0,function({pathname:e,workspaceState:t}){return"empty"===t&&!s(e)}])},812358,e=>{"use strict";e.s(["NoWorkspaceGuard",()=>y]);var t=e.i(405680),r=e.i(982472),i=e.i(630112),s=e.i(60446),a=e.i(174467),n=e.i(549179),o=e.i(500072);e.i(253650);var l=e.i(210321);e.i(478539);var c=e.i(495238),u=e.i(551117),d=e.i(360112),p=e.i(365985);function y({children:e,workspaces:r,workspaceState:s,onRetry:a}){let n=(0,i.usePathname)(),{user:o,isLoading:l}=(0,c.useAuth)();return l||!o||(0,u.isWorkspaceGuardBypassRoute)(n)?(0,t.jsx)(t.Fragment,{children:e}):"loading"===s?(0,t.jsx)(h,{}):"error"===s?(0,t.jsx)(f,{onRetry:a}):r.length>0||!(0,u.shouldShowNoWorkspacePrompt)({pathname:n,workspaceState:s})?(0,t.jsx)(t.Fragment,{children:e}):(0,t.jsx)(m,{})}function h(){return(0,t.jsx)(o.AuthPageShell,{label:"Workspace access",contentClassName:"max-w-lg space-y-6 text-center",children:(0,t.jsxs)("div",{role:"status",className:"flex flex-col items-center gap-4 py-8",children:[(0,t.jsx)(s.Loader2,{"aria-hidden":"true",className:"size-8 animate-spin text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:"Loading your workspaces"})]})})}function f({onRetry:e}){return(0,t.jsx)(o.AuthPageShell,{label:"Workspace access",contentClassName:"max-w-lg space-y-6 text-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 py-8",children:[(0,t.jsx)("div",{className:"flex size-14 items-center justify-center rounded-full bg-destructive/10",children:(0,t.jsx)(s.AlertTriangle,{"aria-hidden":"true",className:"size-7 text-destructive"})}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:"We couldn't verify your workspaces"}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"Wyatt needs to confirm your workspace access before continuing."})]}),(0,t.jsxs)(a.Button,{onClick:e,size:"lg",className:"h-11",children:[(0,t.jsx)(s.RefreshCw,{"aria-hidden":"true",className:"mr-2 size-4"}),"Try again"]})]})})}function m(){let e=(0,i.useRouter)(),{user:u}=(0,c.useAuth)(),{data:y,isLoading:h}
7=(0,l.useJoinableWorkspaces)(),f=(0,l.useJoinViaAllowedDomain)(),[m,g]=(0,r.useState)(new Set),[w,k]=(0,r.useState)(null),b=u?.email?.split("@")[1]||"",_=y&&y.length>0,v=async(e,t)=>{k(e);try{await f.mutateAsync({workspaceId:e}),g(t=>new Set(t).add(e)),(0,p.trackWorkspaceJoinOutcome)({workspaceId:e,joinMethod:"email_domain",source:"no_workspace_guard"}),d.toast.success(`Successfully joined "${t}"`)}catch(t){(0,p.trackWorkspaceJoinFailure)({workspaceId:e,joinMethod:"email_domain",source:"no_workspace_guard",error:t}),d.toast.error(t instanceof Error?t.message:"Failed to join workspace")}finally{k(null)}},I=()=>{e.push("/onboarding")};return(0,t.jsxs)(o.AuthPageShell,{label:"Workspace selection",contentClassName:"max-w-2xl space-y-8",children:[(0,t.jsxs)("div",{className:"text-center space-y-2",children:[(0,t.jsx)("div",{className:"inline-flex items-center justify-center size-16 rounded-full bg-primary/10 mb-4",children:(0,t.jsx)(s.Sparkles,{"aria-hidden":"true",className:"size-8 text-primary"})}),(0,t.jsx)("h1",{className:"text-3xl font-bold tracking-tight",children:"You need a workspace to continue"}),(0,t.jsx)("p",{className:"text-lg text-muted-foreground",children:h?"Checking for available workspaces...":_?(0,t.jsxs)(t.Fragment,{children:["Your ",(0,t.jsxs)("span",{className:"font-medium text-foreground",children:["@",b]})," email gives you access to ",1===y.length?"a workspace":"these workspaces","."]}):"Create a new workspace to get started."})]}),h&&(0,t.jsxs)("div",{role:"status",className:"flex justify-center py-8",children:[(0,t.jsx)(s.Loader2,{"aria-hidden":"true",className:"size-8 animate-spin text-muted-foreground"}),(0,t.jsx)("span",{className:"sr-only",children:"Checking for available workspaces"})]}),!h&&_&&(0,t.jsx)("ul",{"aria-label":"Workspaces available to join",className:"space-y-4",children:y.map(e=>{let r=m.has(e.workspace_id),i=w===e.workspace_id;return(0,t.jsx)("li",{children:(0,t.jsx)(n.Card,{className:`transition-all ${r?"border-primary/50 bg-secondary/50":"hover:border-primary/50"}`,children:(0,t.jsx)(n.CardHeader,{className:"pb-3",children:(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-4",children:[(0,t.jsx)("div",{"aria-hidden":"true",className:"flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.workspace_icon?(0,t.jsx)("span",{className:"text-2xl",children:e.workspace_icon}):(0,t.jsx)(s.Building2,{className:"size-6 text-primary"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)(n.CardTitle,{role:"heading","aria-level":2,className:"text-xl",children:e.workspace_name}),(0,t.jsx)(n.CardDescription,{className:"mt-1",children:r?"You're now a member":`Join as Editor with your @${b} email`})]})]}),(0,t.jsx)("div",{className:"shrink-0",children:r?(0,t.jsxs)("div",{className:"flex min-h-11 items-center gap-2 text-foreground",children:[(0,t.jsx)(s.CheckCircle2,{"aria-hidden":"true",className:"size-5"}),(0,t.jsx)("span",{className:"text-sm font-medium",children:"Joined"})]}):(0,t.jsx)(a.Button,{onClick:()=>v(e.workspace_id,e.workspace_name),disabled:i,size:"lg",className:"h-11","aria-label":`Join workspace ${e.workspace_name}`,"aria-busy":i,children:i?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(s.Loader2,{"aria-hidden":"true",className:"mr-2 size-4 animate-spin"}),"Joining..."]}):"Join Workspace"})})]})})})},e.workspace_id)})}),(0,t.jsx)("div",{className:"flex flex-col items-center gap-4 pt-4",children:_?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 text-muted-foreground",children:[(0,t.jsx)("div",{className:"h-px w-16 bg-border"}),(0,t.jsx)("span",{className:"text-sm",children:"or"}),(0,t.jsx)("div",{className:"h-px w-16 bg-border"})]}),(0,t.jsxs)(a.Button,{variant:"outline",onClick:I,size:"lg",className:"h-11",children:[(0,t.jsx)(s.Plus,{"aria-hidden":"true",className:"mr-2 size-4"}),"Create a new workspace"]})]}):(0,t.jsxs)(a.Button,{onClick:I,size:"lg",className:"h-11 w-full max-w-xs",children:[(0,t.jsx)(s.Plus,{"aria-hidden":"true",className:"mr-2 size-4"}),"Create a workspace"]})})]})}},439298,346281,e=>{"use strict";e.s([],439298),e.i(812358),e.s(["EntityJoinGate",()=>c],346281);var t=e.i(405680),r=e.i(982472),i=e.i(630112),s=e.i(60446),a=e.i(549179);e.i(478539);var n=e.i(495238);e.i(253650);var o=e.i(210321),l=e.i(373977);function c({workspaceId:e,entityType:u,entityId:d,entityLabel:p,fallback:y}){let h=(0,i.useRouter)(),{user:f,isLoading:m}=(0,n.useAuth)(),g=(0,l.useShareInfo)({entityType:u,entityId:d,workspaceId:e??null,enabled:!!(f&&e&&d)}),{data:w=[]}
7=(0,o.useJoinableWorkspaces)({enabled:!!(f&&e)});if(r.useEffect(()=>{if(!e||!g.data?.domain_match||g.data.is_member)return;let t=`${window.location.pathname}${window.location.search}`;h.replace(`/workspaces/${encodeURIComponent(e)}?next=${encodeURIComponent(t)}`)},[h,g.data,e]),!f||m||!e)return(0,t.jsx)(t.Fragment,{children:y});if(g.isPending)return(0,t.jsx)("div",{className:"flex flex-1 items-center justify-center p-4",children:(0,t.jsx)(s.Loader2,{className:"size-6 animate-spin text-muted-foreground"})});if(g.error||!g.data||g.data.is_member)return(0,t.jsx)(t.Fragment,{children:y});if(!g.data.domain_match)return(0,t.jsx)("div",{className:"flex flex-1 items-center justify-center p-4",children:(0,t.jsxs)(a.Card,{className:"w-full max-w-md",children:[(0,t.jsxs)(a.CardHeader,{className:"text-center",children:[(0,t.jsx)("div",{className:"mx-auto mb-4 size-16 rounded-full bg-muted flex items-center justify-center",children:(0,t.jsx)(s.Lock,{className:"size-8 text-muted-foreground"})}),(0,t.jsx)(a.CardTitle,{className:"text-2xl font-bold",children:"You don't have access"}),(0,t.jsxs)(a.CardDescription,{children:["This ",p,"belongs to a workspace you're not a member of."]})]}),(0,t.jsx)(a.CardContent,{children:(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"Ask the person who shared this link to invite you, or contact a workspace administrator for access."})})]})});let k=w.find(t=>t.workspace_id===e)?.workspace_name??null;return(0,t.jsx)("div",{className:"flex flex-1 items-center justify-center p-4",children:(0,t.jsxs)(a.Card,{className:"w-full max-w-md",children:[(0,t.jsxs)(a.CardHeader,{className:"text-center",children:[(0,t.jsx)("div",{className:"mx-auto mb-4 size-16 rounded-full bg-muted flex items-center justify-center",children:(0,t.jsx)(s.Building2,{className:"size-8 text-muted-foreground"})}),(0,t.jsxs)(a.CardTitle,{className:"text-2xl font-bold",children:["Join ",k??"this workspace"]}),(0,t.jsxs)(a.CardDescription,{children:["This ",p," lives in",k?` ${k}`:" a workspace"," and your email domain is approved to join."]})]}),(0,t.jsxs)(a.CardContent,{className:"space-y-4",children:[(0,t.jsxs)("p",{className:"text-sm text-muted-foreground text-center",children:["Signed in as ",f.email,". Join the workspace to view this"," ",p,"."]}),(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,t.jsx)(s.Loader2,{className:"size-4 animate-spin"}),"Opening join page..."]})]})]})})}},192132,e=>{"use strict";let t=[{id:"default",name:"Default",description:"The standard Wyatt theme",light:{sidebar:"#fafafa",sidebarForeground:"#19191a",sidebarAccent:"#f5f5f5",sidebarAccentForeground:"#19191a",sidebarBorder:"#e5e5e5",sidebarPrimary:"#19191a",sidebarPrimaryForeground:"#fafafa",sidebarRing:"#a1a1a1"},dark:{sidebar:"#19191a",sidebarForeground:"#fafafa",sidebarAccent:"#262626",sidebarAccentForeground:"#fafafa",sidebarBorder:"#282828",sidebarPrimary:"#1447e6",sidebarPrimaryForeground:"#fafafa",sidebarRing:"#525252"},preview:{primary:"#fafafa",secondary:"#19191a"}},{id:"ocean",name:"Ocean",description:"Cool blue tones",light:{sidebar:"#F0F7FF",sidebarForeground:"#1E3A5F",sidebarAccent:"#DBEAFE",sidebarAccentForeground:"#1E3A5F",sidebarBorder:"#BFDBFE",sidebarPrimary:"#2563EB",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#3B82F6"},dark:{sidebar:"#0F172A",sidebarForeground:"#E0F2FE",sidebarAccent:"#1E3A5F",sidebarAccentForeground:"#E0F2FE",sidebarBorder:"#1E40AF",sidebarPrimary:"#60A5FA",sidebarPrimaryForeground:"#0F172A",sidebarRing:"#3B82F6"},preview:{primary:"#3B82F6",secondary:"#1E3A5F"}},{id:"forest",name:"Forest",description:"Natural green tones",light:{sidebar:"#F0FDF4",sidebarForeground:"#14532D",sidebarAccent:"#DCFCE7",sidebarAccentForeground:"#14532D",sidebarBorder:"#BBF7D0",sidebarPrimary:"#16A34A",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#22C55E"},dark:{sidebar:"#052E16",sidebarForeground:"#D1FAE5",sidebarAccent:"#14532D",sidebarAccentForeground:"#D1FAE5",sidebarBorder:"#166534",sidebarPrimary:"#4ADE80",sidebarPrimaryForeground:"#052E16",sidebarRing:"#22C55E"},preview:{primary:"#22C55E",secondary:"#14532D"}},{id:"sunset",name:"Sunset",description:"Warm orange and coral tones",light:{sidebar:"#FFF7ED",sidebarForeground:"#7C2D12",sidebarAccent:"#FFEDD5",sidebarAccentForeground:"#7C2D12",sidebarBorder:"#FED7AA",sidebarPrimary:"#EA580C",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#F97316"},dark:{sidebar:"#1C1410",sidebarForeground:"#FFEDD5",sidebarAccent:"#431407",sidebarAccentForeground:"#FFEDD5",sidebarBorder:"#7C2D12",sidebarPrimary:"#FB923C",sidebarPrimaryForeground:"#1C1410",sidebarRing:"#F97316"},preview:{primary:"#F97316",secondary:"#7C2D12"}},{id:"lavender",name:"Lavender",description:"Soft purple tones",light:{sidebar:"#FAF5FF",sidebarForeground:"#581C87",sidebarAccent:"#F3E8FF",sidebarAccentForeground:"#581C87",sidebarBorder:"#E9D5FF",sidebarPrimary:"#9333EA",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#A855F7"},dark:{sidebar:"#1A0B2E",sidebarForeground:"#F3E8FF",sidebarAccent:"#3B0764",sidebarAccentForeground:"#F3E8FF",sidebarBorder:"#581C87",sidebarPrimary:"#C084FC",sidebarPrimaryForeground:"#1A0B2E",sidebarRing:"#A855F7"},preview:{primary:"#A855F7",secondary:"#581C87"}}
7,{id:"slate",name:"Slate",description:"Cool gray tones",light:{sidebar:"#F8FAFC",sidebarForeground:"#334155",sidebarAccent:"#F1F5F9",sidebarAccentForeground:"#334155",sidebarBorder:"#E2E8F0",sidebarPrimary:"#475569",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#64748B"},dark:{sidebar:"#0F172A",sidebarForeground:"#E2E8F0",sidebarAccent:"#1E293B",sidebarAccentForeground:"#E2E8F0",sidebarBorder:"#334155",sidebarPrimary:"#94A3B8",sidebarPrimaryForeground:"#0F172A",sidebarRing:"#64748B"},preview:{primary:"#64748B",secondary:"#334155"}},{id:"rose",name:"Rose",description:"Soft pink tones",light:{sidebar:"#FFF1F2",sidebarForeground:"#881337",sidebarAccent:"#FFE4E6",sidebarAccentForeground:"#881337",sidebarBorder:"#FECDD3",sidebarPrimary:"#E11D48",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#F43F5E"},dark:{sidebar:"#1C0A10",sidebarForeground:"#FFE4E6",sidebarAccent:"#4C0519",sidebarAccentForeground:"#FFE4E6",sidebarBorder:"#881337",sidebarPrimary:"#FB7185",sidebarPrimaryForeground:"#1C0A10",sidebarRing:"#F43F5E"},preview:{primary:"#F43F5E",secondary:"#881337"}},{id:"midnight",name:"Midnight",description:"Deep navy tones",light:{sidebar:"#F5F5F7",sidebarForeground:"#1E1B4B",sidebarAccent:"#E0E7FF",sidebarAccentForeground:"#1E1B4B",sidebarBorder:"#C7D2FE",sidebarPrimary:"#4338CA",sidebarPrimaryForeground:"#FFFFFF",sidebarRing:"#6366F1"},dark:{sidebar:"#0C0A1D",sidebarForeground:"#E0E7FF",sidebarAccent:"#1E1B4B",sidebarAccentForeground:"#E0E7FF",sidebarBorder:"#312E81",sidebarPrimary:"#818CF8",sidebarPrimaryForeground:"#0C0A1D",sidebarRing:"#6366F1"},preview:{primary:"#6366F1",secondary:"#1E1B4B"}}];e.s(["WORKSPACE_THEMES",0,t,"getThemeColors",0,function(e,t){return t?e.dark:e.light},"getWorkspaceTheme",0,function(e){return t.find(t=>t.id===e)??t[0]}])},774922,e=>{"use strict";e.s(["useWorkspaceTheme",()=>c]);var t=e.i(982472),r=e.i(821957),i=e.i(623128),s=e.i(192132);let a="wyatt:workspace-theme:";function n(e){return"number"==typeof e?Number.isFinite(e)&&e>0:"string"==typeof e&&e.trim().length>0}let o=new Set,l={sidebar:"--sidebar",sidebarForeground:"--sidebar-foreground",sidebarAccent:"--sidebar-accent",sidebarAccentForeground:"--sidebar-accent-foreground",sidebarBorder:"--sidebar-border",sidebarPrimary:"--sidebar-primary",sidebarPrimaryForeground:"--sidebar-primary-foreground",sidebarRing:"--sidebar-ring"};function c(){let e=(0,i.useCurrentWorkspaceSafe)(),{resolvedTheme:c}=(0,r.useTheme)(),u=e?.currentWorkspace,d=u?.id,p="dark"===c,y=(0,t.useSyncExternalStore)(e=>{o.add(e);let t=t=>{let r=t.key??"";("theme"===r||r.startsWith(a))&&e()};return window.addEventListener("storage",t),()=>{o.delete(e),window.removeEventListener("storage",t)}},()=>n(d)?localStorage.getItem(`${a}${d}`)??"default":"default",()=>"default"),h=(0,t.useCallback)((e,t)=>{let r=(0,s.getWorkspaceTheme)(e),i=(0,s.getThemeColors)(r,t);Object.entries(l).forEach(([e,t])=>{let r=i[e];document.documentElement.style.setProperty(t,r)})},[]),f=(0,t.useCallback)(()=>{Object.values(l).forEach(e=>{document.documentElement.style.removeProperty(e)})},[]),m=(0,t.useCallback)(e=>{n(d)&&(localStorage.setItem(`${a}${d}`,e),o.forEach(e=>e()))},[d]);return(0,t.useEffect)(()=>(h(y,p),()=>{f()}),[y,p,h,f]),{currentThemeId:y,isDark:p,setTheme:m,applyTheme:h,resetTheme:f}}},623128,e=>{"use strict";e.s(["WorkspaceProvider",()=>h,"useActiveWorkspace",()=>w,"useCurrentWorkspace",()=>m,"useCurrentWorkspaceSafe",()=>g,"useRequiredWorkspace",()=>k]);var t=e.i(405680),r=e.i(982472);e.i(439298);var i=e.i(812358);e.i(478539);var s=e.i(495238);e.i(534);var a=e.i(498922);e.i(253650);var n=e.i(210321),o=e.i(774922),l=e.i(551117),c=e.i(979762),u=e.i(922324);let d=new a.PreferencesClient,p=[],y=r.createContext(null);function h({children:e}){let{data:a,isPending:o,error:m,refetch:g}=(0,n.useWorkspaces)(),w=a??p,{user:k,isLoading:b}=(0,s.useAuth)(),[_,v]=r.useState(null),[I,S]=r.useState(null),[C,x]=r.useState(null),F=r.useRef(!1),[T,A]=r.useState(!1),E=m instanceof Error?m.status:null,D="number"==typeof E?E:null,[M,K]=r.useState(!1);M||401!==D||K(!0),M&&!m&&void 0!==a&&K(!1);let q=m instanceof Error&&(void 0===a||401===D)||M;r.useEffect(()=>{m instanceof Error&&!q&&console.error("[workspace] membership_revalidation_failed",{status:D,reason:m.message})},[m,q,D]),r.useEffect(()=>
7{let e=(0,c.getStoredLastWorkspaceId)();e&&S(t=>t??e)},[]);let O=r.useCallback(e=>{e?(0,c.setStoredLastWorkspaceId)(e):(0,c.clearStoredLastWorkspaceId)(),k&&d.setLastWorkspaceId({workspaceId:e}).catch(t=>{console.warn("[workspace] preference_persist_failed",{workspaceId:e,reason:t instanceof Error?t.message:String(t)})})},[k]);r.useEffect(()=>{if(b)return;if(!k)return void A(!0);let e=!0;return d.getLastWorkspaceId().then(t=>{e&&t&&S(e=>e??t)}).catch(e=>{console.warn("[workspace] preference_restore_failed",{reason:e instanceof Error?e.message:String(e)})}).finally(()=>{e&&A(!0)}),()=>{e=!1}},[b,k]),r.useEffect(()=>{k&&q&&((0,c.clearStoredLastWorkspaceId)(),F.current=!0,x(null))},[q,k]),r.useEffect(()=>{!C||w.some(e=>e.id===C.id)&&x(null)},[C,w]);let P=r.useMemo(()=>q?[]:w,[q,w]),Q=r.useMemo(()=>P.filter(e=>(e.membership_status??"member")==="member"),[P]),R=r.useMemo(()=>Q.map(e=>e.id),[Q]);r.useEffect(()=>{if(b||!k||o||q)return;if(0===Q.length){let e=null!==_||null!==I;v(null),S(null),F.current=!1,e&&O(null);return}if(null!==_&&Q.some(e=>e.id===_)){F.current&&((0,c.setStoredLastWorkspaceId)(_),F.current=!1),null!==I&&S(null);return}if(C?.id===_)return;let e=I??(0,c.getStoredLastWorkspaceId)(),t=null!==e&&Q.some(t=>t.id===e);if(!t&&!T)return;let r=t?e:Q[0].id;_!==r&&(v(r),S(null),F.current=!1,O(r))},[Q,b,_,q,o,C,O,T,I,k]);let W=r.useMemo(()=>{if(null===_)return null;let e=P.find(e=>e.id===_&&(e.membership_status??"member")==="member");return e||(q||C?.id!==_?null:C)},[P,_,q,C]),B=r.useMemo(()=>P.length>0?q||!C||P.some(e=>e.id===C.id)?P:[...P,C].sort((e,t)=>e.name.localeCompare(t.name)):!q&&C?[C]:[],[P,q,C]),j=(0,l.isWorkspaceChromeLoading)({workspacesPending:o,acceptedWorkspaceCount:Q.length}),$=(0,l.resolveWorkspaceMembershipState)({authLoading:b,hasUser:!!k,isWorkspaceLoading:j,workspaceCount:Q.length+ +(null!==C),hasLookupError:q}),N=r.useCallback(()=>{g()},[g]),L=r.useCallback(e=>{q||(x(e),v(e.id),O(e.id))},[q,O]);r.useEffect(()=>{(0,u.setActiveWorkspacePublicId)(W?.id??null)},[W]);let U=r.useMemo(()=>({currentWorkspace:W,workspaces:B,memberWorkspaceIds:R,isLoading:j,workspaceState:$,setCurrentWorkspace:L}),[W,j,B,R,L,$]);return(0,t.jsxs)(y.Provider,{value:U,children:[(0,t.jsx)(f,{}),(0,t.jsx)(i.NoWorkspaceGuard,{workspaces:B,workspaceState:$,onRetry:N,children:e})]})}function f(){return(0,o.useWorkspaceTheme)(),null}function m(){let e=r.useContext(y);if(!e)throw Error("useCurrentWorkspace must be used within a WorkspaceProvider");return e}function g(){return r.useContext(y)}function w(){let{currentWorkspace:e,isLoading:t}=m();return{workspaceId:e?.id??null,workspace:e,isLoading:t}}function k(){let{currentWorkspace:e,isLoading:t}=m();if(t)throw Error("useRequiredWorkspace called while loading - use useActiveWorkspace instead");if(!e)throw Error("No workspace available - user may not have access to any workspace");return{workspaceId:e.id,workspace:e}}}]); 8 9//# debugId=61fda6a0-3fcb-e60e-5b71-a12ea85c92c7
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.