react-semaphor 0.1.110 → 0.1.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/chunks/{dashboard-controls-BYAphgOD.js → dashboard-controls-au5vGH7o.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-cLWit6bH.js → dashboard-controls-i6Wbe7nf.js} +1 -1
  3. package/dist/chunks/{dashboard-json-DqxQUnfm.js → dashboard-json-DzFuErre.js} +1 -1
  4. package/dist/chunks/{dashboard-json-BFFNgT76.js → dashboard-json-RDd6wMsW.js} +1 -1
  5. package/dist/chunks/edit-dashboard-visual-BrJPT6U4.js +170 -0
  6. package/dist/chunks/{edit-dashboard-visual-_unvQdbT.js → edit-dashboard-visual-zQT9UpcS.js} +3420 -3459
  7. package/dist/chunks/{editor-action-buttons-1iAFRYvs.js → editor-action-buttons-B6bgTDgU.js} +1 -1
  8. package/dist/chunks/{editor-action-buttons-XRl_GLPH.js → editor-action-buttons-BehEDUE0.js} +2 -2
  9. package/dist/chunks/{index-Dbjhjr4S.js → index--DLrWJ82.js} +4 -4
  10. package/dist/chunks/{index-D4GRKodP.js → index-BjaJfJko.js} +1 -1
  11. package/dist/chunks/{resource-management-panel-CsMaAMxK.js → resource-management-panel-59R5lAiD.js} +1 -1
  12. package/dist/chunks/{resource-management-panel-cdW-DFtz.js → resource-management-panel-DSlY17bM.js} +2 -2
  13. package/dist/chunks/{schedule-dashboard-kWXZiUDD.js → schedule-dashboard-CTX2mzOI.js} +1 -1
  14. package/dist/chunks/{schedule-dashboard-Dkma2RUp.js → schedule-dashboard-DXKqgTXP.js} +3 -3
  15. package/dist/chunks/{use-visual-utils-BhQcVYo4.js → use-visual-utils-BuSSJYD4.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-BF9XvM4A.js → use-visual-utils-Dcb72nce.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/style.css +1 -1
  22. package/dist/surfboard/index.cjs +1 -1
  23. package/dist/surfboard/index.js +1 -1
  24. package/package.json +1 -1
  25. package/dist/chunks/edit-dashboard-visual-CbwhVEin.js +0 -170
@@ -1063,7 +1063,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1063
1063
 
1064
1064
  `)},flush(e){e.enqueue(`data: [DONE]
1065
1065
 
1066
- `)}})}});var wKe=pZe(()=>jJ(Ar([Wn({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:$e()}),Wn({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Wn({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Wn({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Wn({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Wn({type:vJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:wr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function SKe(e){return e.type.startsWith("data-")}function IJ(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=IJ(o,s):n[r]=s}return n}function CKe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function AJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ew({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ew({text:CKe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Oy(e){return e.type.startsWith("tool-")}function NKe(e){return e.type==="dynamic-tool"}function JE(e){return Oy(e)||NKe(e)}function eL(e){return e.type.split("-").slice(1).join("-")}function jKe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function kKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Oy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Oy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?IJ(u.message.metadata,w):w;t!=null&&await Z$({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Oy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await AJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:eL(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:eL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(SKe(a)){(n==null?void 0:n[a.type])!=null&&await Z$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function EKe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Mx({prefix:"aitxt",size:24});Mx({prefix:"aiobj",size:24});var _Ke=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Mx({prefix:"aiobj",size:24});var DKe={};dKe(DKe,{object:()=>TKe,text:()=>MKe});var MKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),TKe=({schema:e})=>{const t=cKe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await AJ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Ew({text:n});if(!s.success)throw new Q$({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await dI({value:s.value,schema:t});if(!o.success)throw new Q$({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},RKe=Ff({name:$e(),version:$e()}),hI=Ff({_meta:pr(Wt({}).loose())}),pb=hI,IKe=Wt({method:$e(),params:pr(hI)}),AKe=Ff({experimental:pr(Wt({}).loose()),logging:pr(Wt({}).loose()),prompts:pr(Ff({listChanged:pr(wr())})),resources:pr(Ff({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr(Ff({listChanged:pr(wr())}))});pb.extend({protocolVersion:$e(),capabilities:AKe,serverInfo:RKe,instructions:pr($e())});var PKe=pb.extend({nextCursor:pr($e())}),OKe=Wt({name:$e(),description:pr($e()),inputSchema:Wt({type:ut("object"),properties:pr(Wt({}).loose())}).loose()}).loose();PKe.extend({tools:eu(OKe)});var FKe=Wt({type:ut("text"),text:$e()}).loose(),$Ke=Wt({type:ut("image"),data:pJ(),mimeType:$e()}).loose(),PJ=Wt({uri:$e(),mimeType:pr($e())}).loose(),LKe=PJ.extend({text:$e()}),zKe=PJ.extend({blob:pJ()}),BKe=Wt({type:ut("resource"),resource:Ar([LKe,zKe])}).loose();pb.extend({content:eu(Ar([FKe,$Ke,BKe])),isError:wr().default(!1).optional()}).or(pb.extend({toolResult:co()}));var KS="2.0",VKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()])}).merge(IKe).strict(),HKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()]),result:pb}).strict(),UKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()]),error:Wt({code:fb().int(),message:$e(),data:pr(co())})}).strict(),WKe=Wt({jsonrpc:ut(KS)}).merge(Wt({method:$e(),params:pr(hI)})).strict();Ar([VKe,WKe,HKe,UKe]);async function qKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var YKe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await vf(this.body),l=await vf(this.headers),u=await vf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:G$({"Content-Type":"application/json",...h},`ai-sdk/${J$}`,Y$()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await vf(this.body),a=await vf(this.headers),l=await vf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:G$(f,`ai-sdk/${J$}`,Y$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},pI=class extends YKe{constructor(e={}){super(e)}processResponseStream(e){return bZe({stream:e,schema:wKe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},GKe=class{constructor({generateId:e=oZe,id:t=e(),transport:n=new pI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new _Ke,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await qKe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>JE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>JE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:jKe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await EKe({stream:kKe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function ZKe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(JE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function KKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var XKe=KKe;const QKe=Fc(XKe);var OJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(OJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Bi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ol=(e,t,n,r)=>(OJ(e,t,"write to private field"),t.set(e,n),n);function JKe(e,t){return t!=null?QKe(e,t):e}var jo,Fy,$y,Fm,$m,Lm,kf,e_,t_,eXe=class{constructor(e=[]){Bi(this,jo,void 0),Bi(this,Fy,"ready"),Bi(this,$y,void 0),Bi(this,Fm,new Set),Bi(this,$m,new Set),Bi(this,Lm,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,kf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,kf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,kf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?JKe(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Bi(this,kf,()=>{Tn(this,Fm).forEach(t=>t())}),Bi(this,e_,()=>{Tn(this,$m).forEach(t=>t())}),Bi(this,t_,()=>{Tn(this,Lm).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Fy)}set status(e){Ol(this,Fy,e),Tn(this,e_).call(this)}get error(){return Tn(this,$y)}set error(e){Ol(this,$y,e),Tn(this,t_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,kf).call(this)}};jo=new WeakMap;Fy=new WeakMap;$y=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;kf=new WeakMap;e_=new WeakMap;t_=new WeakMap;var Ef,tL=class extends GKe{constructor({messages:e,...t}){const n=new eXe(e);super({...t,state:n}),Bi(this,Ef,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Ef)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Ef)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Ef)["~registerErrorCallback"](r),Ol(this,Ef,n)}};Ef=new WeakMap;function FJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new tL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new tL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function tXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function nXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function rXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function sXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function $J(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:sXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function LJ(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function oXe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Hw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=FJ({transport:new pI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Pi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:fW(x)}})}),onToolCall:p,sendAutomaticallyWhen:ZKe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:$J(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=LJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function zJ(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Hw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function BJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(t8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function _w(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(W_,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(_ie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(Z_,{className:r});case"url":return c.jsx(f8,{className:r});default:return c.jsx(Kw,{className:r})}}const VJ=_.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(xa,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:J("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));VJ.displayName=us.Input.displayName;const ay=e=>e.label||(e==null?void 0:e.name),nL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function iXe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=ay(C).toLowerCase(),D=nL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ay(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ay(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(DS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(VJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(MS,{className:"min-h-60",children:[c.jsx(TS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(RS,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ay(C);return c.jsxs(IS,{value:E,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:_w(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nL(C)})]}),D&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const n_=e=>e.name||e.name,aXe=e=>{const t=n_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function lXe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Yn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[_w(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:n_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:aXe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(i8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:_w(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:n_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function HJ(e){return e.type==="dataset"&&e.label||e.name}function cXe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function uXe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),HJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function dXe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function fXe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function hXe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ai(e),s=_e(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function pXe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ai(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function UJ(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ai(e),s=_e(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function mXe(){var S,C,j;const e=_e(D=>D.card.dataSource);_e(D=>D.actions.updateDirectSource);const t=_e(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ai(),{databases:i,isPending:a,error:l,label:u}=hXe(),{schemas:d,isPending:f,error:h,label:p}=pXe(),{error:m}=UJ(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function gXe(){const e=_e(l=>l.card.dataSource),t=_e(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(Z_,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ni,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function bXe(){const e=_e(f=>f.card.dataSource),t=_e(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Kw,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function xXe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ai(t),o=_e(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Dw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(hd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function yXe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ai(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=xXe("table"),{dataModels:x,isPending:y,error:v}=UJ(),w=E=>{const M=s.find(O=>O.id===E);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var T,I;const M=n||[],R=M.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=M.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...M,F]}t==null||t(O)},C=E=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===E.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===E.name)):O=[...M,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let M=[...E];if(d==="tables"){const O=j.filter(T=>!E.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[...E,...O]}else if(d==="datamodels"){const R=D.filter(O=>!E.some(T=>T.name===O.name&&T.type==="model"));M=[...E,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(sl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(gXe,{}),e.connectionType==="url"&&c.jsx(bXe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mXe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Dw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const M=n.some(R=>R.name===E.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(dn,{id:`table-${E.name}`,checked:M,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(E=>{const M=n.some(R=>R.name===E.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(E),children:[c.jsx(dn,{id:`dataModel-${E.name}`,checked:M,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function vXe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=dXe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=fXe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(D)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,E]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(E=>!C.some(M=>M.id===E.id&&M.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Dw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function mI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function E(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ms,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(vXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(yXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(uXe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ds,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function wXe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=$a-n;if(l.length>u){Le.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=kQ(l);if(f.forEach(({file:h,error:p})=>{Le.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>nI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Le.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=$a}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=$a,title:n>=$a?`Maximum ${$a} files allowed`:"Attach files",children:c.jsx(B_,{className:"h-4 w-4 text-muted-foreground"})})]})}function SXe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=$a-r;if(h.length>p){Le.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=kQ(h);if(g.forEach(({file:b,error:x})=>{Le.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>nI(x)));t(b),Le.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Le.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(Z_,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[$a-r," slot(s) available"]})]})})]})}const gI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=_p();_Ce(),ECe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=L1(),{queueMessage:C}=Dp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:E}=IM(),M=RM(l),R=_e(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(Y(),f(!0))},B=N.useCallback(H=>{const q=OUe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const K=await nI(X);j(l,K)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(K=>!(K.id&&K.id===H.id||K.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var K;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(K=b.current)==null||K.focus()},U=H=>{const q=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:q});const K=`@${"label"in H?H.label:H.name}`;e.includes(K)&&t(e.replace(K,"").trim())},G=H=>{const q=new Set(H.map(Z=>Z.id||Z.name)),X=x.selectedEntities.filter(Z=>!q.has(Z.id||Z.name));y({selectedEntities:X});let K=e;H.forEach(Z=>{const ne=`@${"label"in Z?Z.label:Z.name}`;K=K.replace(ne,"").trim()}),t(K)},Y=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(SXe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(lXe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:G}),M.length>0&&c.jsx(FUe,{files:M,onRemove:V,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:B,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ss,{open:d,onOpenChange:H=>{H&&Y(),f(H)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Sie,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(iXe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(wXe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx($ie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(y8,{className:"size-4"})})]})]})]}),c.jsx(mI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||YS,dialogMode:"aiContext"})]})});gI.displayName="ChatInputWithContext";function WJ({assistantType:e,className:t}){const n=hW(e),{removeFromQueue:r}=Dp();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function qJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=hW(e),{dequeueMessage:o}=Dp();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function YJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const E=g.current,M=k.scrollTop,R=M-E;if(g.current=M,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const E=w.current,M=e[e.length-1],R=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>E.count,I=R!==E.key,F=O>E.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-E.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const E=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function GJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function ZJ(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:EQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CXe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function NXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState($w),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:M,setShowReasoning:R}=L1(),{clearQueue:O}=Dp(),{clearFileAttachments:T,getFileAttachments:I}=IM(),F=RM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=_e(Ve=>Ve.card.dataSource),{assistantProfile:$}=zJ(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:G,errorMessage:Y,clearError:H}=oXe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[K,Z]=N.useState(""),Q=Ve=>{Z(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:ke,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:ke,dataSource:Te}),!v)return;const ze={id:Mr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:Te,config:ke,connectionId:He},nt={id:Mr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=K.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:ht}),Z(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),qJ({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=ZJ(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:Ce,loadMoreMessages:je,resetMessageWindow:de}=GJ(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=YJ(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ze(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),Le.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),Le.error("Unable to copy conversation")}},[A]);function Ze(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const $t=(K==null?void 0:K.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Zh,{className:"size-3.5"})})}),c.jsxs(Bd,{align:"end",children:[c.jsx(Uf,{children:"Options"}),c.jsx(md,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(z_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,Ce-fe.length)," ","more messages (",Ce-fe.length," ","hidden)"]})}),c.jsx(DQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(_Q,{status:U,errorMessage:Y})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(qs,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&$t&&c.jsx(MQ,{onClick:Se,placeholders:CXe}),c.jsx("div",{children:$t&&$&&c.jsx(BJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(WJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(gI,{ref:y,setInput:Z,stop:G,input:K,handleInputChange:Q,handleSubmit:Ve=>{Ze(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(mI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||YS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:hn})}),s):hn}function jXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Le.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=BT(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Le.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function kXe(e,t){switch(e.interactionMode){case"drillToDetail":EXe(e,t);break;case"drillThrough":_Xe(e,t);break;case"drillToURL":DXe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function EXe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function _Xe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function DXe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function MXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ms,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(VZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(UZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function TXe(){const e=Lt(w=>w.interactionStates),t=Lt(w=>w.setInteractionState),n=Lt(w=>w.clearLastInteractionEvent),r=Lt(w=>w.replaceCardWithInsight),s=Lt(w=>w.setPendingDrillThrough),o=Lt(w=>w.pendingDrillThrough),i=Lt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Eb(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=tfe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=WZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const E={sourceCardId:ra,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(ra,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{kXe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(MXe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function RXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function AXe(e){return e?`Back to ${e}`:"Back"}function PXe(){var x,y,v,w,S;const e=Lt(C=>C.interactionStates[ra]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Eb(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};RXe(f);const b=AXe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(B6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function KJ(){var Z;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=ip(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=td(Q=>Q.setFullscreen),d=td(Q=>Q.setPanelOpen),f=td(Q=>Q.setContainer),h=cW("dashboard"),p=uW(),m=dW("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:E,clearDefaultSheetId:M}=w6(C),[R,O]=N.useState(null);m1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();jXe(i);const{setActiveAssistantType:B}=L1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:Mr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),Le.success("Default sheet cleared")):(E(Q),O(Q),Le.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},G=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[fe]=ie.splice(parseInt(ae),1);ie.splice(ne,0,fe),z(ie)},Y=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Ur,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&Y&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(J6,{className:"h-4 w-4"}):c.jsx(e8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const fe=S===ae.id,xe=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>G(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(Yg,{enabled:w&&fe,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(v8,{className:J("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(QLe,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(M6e,{open:a,setOpen:l})]})}const K=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(TXe,{}),c.jsx(PXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(AR,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ob,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(D6e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(ob,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(NXe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:K,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(U_,{className:"h-5 w-5"})})})]})]}):null}function bI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(Nre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function XJ({children:e,preferences:t}){const{currentUser:n}=_s(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(h9.Provider,{value:r,children:c.jsx(lR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function QJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:aS,children:c.jsx(__,{dashboardProps:e,children:c.jsx(bI,{children:c.jsx(XJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(AM,{...e,type:"dashboard",children:c.jsx(KJ,{})})})})})})})}function xI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function JJ(e,t,n){if(t==="source")return{isValid:!0};const r=Zs(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function eee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const tee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=xI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=_e(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:BH(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){Le.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),E=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=Q1e(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&$H();return}const z=tSe(T,I,h);if(!z){Le.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=JJ(T,z,h);if(!B.isValid){Le.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(LH(T,$))return;const P=VH(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&eee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Tx(e,t){var Pe,Qe,Nt,Ze,$t;const{tokenProps:n}=qe(),r=Ks(),s=qe().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=ope(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),p=_e(Ne=>Ne.actions.setSelectedConnectionId),m=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ai(e),{refetch:E,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:G,isLoading:Y,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:K,isColumnsLoading:Z,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=HH(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function je(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function de(Ne){p(Ne)}function Re(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),mt=(Ze=M==null?void 0:M.datamodels)==null?void 0:Ze.map(Ne=>({id:Ne.id,name:Ne.name})),be=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),ue=G==null?void 0:G.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=($t=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:$t.name,Se=Hy({schemaName:fe,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:Y||H,isTableError:q,columns:K,isColumnsLoadingOrFetching:Z||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:je,handleSchemaChange:Ce,handleTableChange:xe}}function ly(e){return`${e}-${Mr()}`}function rL(e,t){const n=qo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function OXe(e,t){const n=qo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function yI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function nee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function ree(){const e=_e(C=>C.sqlGen),t=_e(C=>C.isDevMode),n=_e(C=>C.card.dataSource),r=_e(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=yI(n),a=nee(n),l=_e(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Tx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=y_(j,e);p(k);const E=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=x_(k,di(o||""),di(s),E||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(jb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:ly(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:ly(j.column_name),name:j.column_name,label:rL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if($c(j.data_type)){const k={...j,role:"groupby",id:ly(j.column_name),name:j.column_name,type:j.data_type,label:OXe(j.column_name,"month"),granularity:"month"};d(k)}if(Bo(j.data_type)){const k={...j,role:"metric",id:ly(j.column_name),name:j.column_name,label:rL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Hy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Hy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Bo(C.dataType)}}function see(){const e=_e(m=>m.selectedConnectionId),t=_e(m=>m.selectedDatamodelId),n=_e(m=>m.selectedDatabaseName),r=_e(m=>m.selectedSchemaName),s=_e(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Tx();function p(m,g="sheet",b){var k;const x=di(m.column_name),y=di(n||""),v=di(r||""),w=di(f);let S=Lw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Mje(o,C,w,n||"",y,i):D=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),D)u(D.id),l(D.id);else{const E=Mr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:j4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:j4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function FXe({column:e}){const[t,n]=N.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=yI(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=Tx(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),p=_e(x=>x.actions.setRunSql),m=nee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=y_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=x_(v,di(o||""),di(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Zh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Yd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function $Xe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function LXe({field:e,context:t="editor",fieldState:n}){const r=_e(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=see(),f=s?Gc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=ES({id:e.id,disabled:o}),[E,M]=N.useState(!1),R=_e(L=>L.card),{handleFieldClick:O}=tee(R),{handleDevModeFieldClick:T,isNumberField:I}=ree(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[Qg(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx($Xe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(FXe,{column:B})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(w8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Vie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const zXe="SEMAPHOR_CALCULATED_FIELD",BXe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function oee(e){return!!e.expression}function VXe(e){return!!e.expression}function HXe(e){return!!e.expression}var iee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(iee||{}),jl="Accordion",UXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[vI,WXe,qXe]=t1(jl),[XS]=Er(jl,[qXe,ZZ]),wI=ZZ(),aee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(vI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(KXe,{...o,ref:t}):c.jsx(ZXe,{...s,ref:t})})});aee.displayName=jl;var[lee,YXe]=XS(jl),[cee,GXe]=XS(jl,{collapsible:!1}),ZXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(lee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(cee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(uee,{...i,ref:t})})})}),KXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(lee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(cee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(uee,{...o,ref:t})})})}),[XXe,QS]=XS(jl),uee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=WXe(n),f=Fd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!UXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(XXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(vI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Mw="AccordionItem",[QXe,SI]=XS(Mw),dee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=QS(Mw,n),i=YXe(Mw,n),a=wI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(QXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(QZ,{"data-orientation":o.orientation,"data-state":bee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});dee.displayName=Mw;var fee="AccordionHeader",hee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(fee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":bee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});hee.displayName=fee;var r_="AccordionTrigger",pee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(r_,n),i=GXe(r_,n),a=wI(n);return c.jsx(vI.ItemSlot,{scope:n,children:c.jsx(t3e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});pee.displayName=r_;var mee="AccordionContent",gee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(mee,n),i=wI(n);return c.jsx(n3e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});gee.displayName=mee;function bee(e){return e?"open":"closed"}var JXe=aee,eQe=dee,tQe=hee,xee=pee,yee=gee;const vee=JXe,CI=_.forwardRef(({className:e,...t},n)=>c.jsx(eQe,{ref:n,className:J("border-b",e),...t}));CI.displayName="AccordionItem";const NI=_.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tQe,{className:"flex",children:c.jsxs(xee,{ref:r,className:J("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(qs,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));NI.displayName=xee.displayName;const jI=_.forwardRef(({className:e,children:t,...n},r)=>c.jsx(yee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:J("pb-4 pt-0",e),children:t})}));jI.displayName=yee.displayName;function nQe({context:e="editor"}={}){var E,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");_e(T=>T.isDevMode);const o=_e(T=>T.card.dataSource),i=_e(T=>T.card.config),a=_e(T=>T.card),{autoJoinMetadata:l}=ha(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=gM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=xI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,ree();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&oee(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Zs(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:w_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Es,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(ls,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(Gh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(P_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(vee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(CI,{value:T,className:"border-none",children:[c.jsx(NI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(jI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=bM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(LXe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function wee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(nQe,{context:e})," "]})}function See(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=yI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function rQe(){See();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=cr(),i=_e(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function sQe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=rQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(YZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(jS,{collisionDetection:wS,children:c.jsx(kS,{items:[],strategy:CR,children:c.jsx(wee,{context:"filter"})})})})]})}function oQe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(uR,{filter:r}),c.jsx(bS,{filter:r})]},r.id))}):null}function iQe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(oQe,{}),c.jsx(KJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(sQe,{})})]})}const aQe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-cLWit6bH.js"))),lQe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-CbwhVEin.js"))),cQe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-DqxQUnfm.js"))),uQe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CsMaAMxK.js")).then(e=>({default:e.ResourceManagementPanel})));function dQe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(m=>m.isDashboardPanelOpen),s=ee(m=>m.isVisualEditing),o=ee(m=>m.showDashboardJSON),i=ee(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(wl,{FallbackComponent:aS,children:c.jsxs(__,{dashboardProps:n,children:[c.jsx(gde,{}),c.jsx(bI,{children:c.jsxs(XJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(cQe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(aQe,{})}),c.jsxs(AR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ob,{ref:f,className:J("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uQe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(dX,{className:J("",{"w-0":!d})}),c.jsx(ob,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(AM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(lQe,{})}),c.jsx(iQe,{})]})})]})]})]})})]})})}var fQe=Object.defineProperty,hQe=(e,t,n)=>t in e?fQe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,cy=(e,t,n)=>hQe(e,typeof t!="symbol"?t+"":t,n);const pQe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},mQe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},gQe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},bQe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},xQe={stringify:e=>e,parse:e=>e},q2={string:xQe,number:bQe,boolean:pQe,function:mQe,json:gQe};function yQe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const uy=Symbol.for("r2wc.render"),dy=Symbol.for("r2wc.connected"),pu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function vQe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=yQe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),cy(this,o,!0),cy(this,s),cy(this,r,{}),cy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ta].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?q2[x]:null;y!=null&&y.parse&&b&&(this[Ta][m]=y.parse(b,g,this))}for(const m of a)this[Ta][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[dy]=!0,this[uy]()}disconnectedCallback(){this[dy]=!1,this[pu]&&n.unmount(this[pu]),delete this[pu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?q2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[uy]())}[(o=dy,s=pu,r=Ta,uy)](){this[dy]&&(this[pu]?n.update(this[pu],this[Ta]):this[pu]=n.mount(this.container,e,this[Ta]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ta][p]},set(b){this[Ta][p]=b;const x=g?q2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[uy]()}})}return h}function wQe(e,t,n){const r=oj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SQe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function CQe({root:e}){e.unmount()}function NQe(e,t={}){return vQe(e,t,{mount:wQe,update:SQe,unmount:CQe})}const jQe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},kQe=NQe(QJ,{props:jQe});function EQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function oL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sL(Object(n),!0).forEach(function(r){EQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _Qe(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function DQe(e,t){if(e==null)return{};var n=_Qe(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function MQe(e,t){return TQe(e)||RQe(e,t)||IQe(e,t)||AQe()}function TQe(e){if(Array.isArray(e))return e}function RQe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function IQe(e,t){if(e){if(typeof e=="string")return iL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return iL(e,t)}}function iL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function AQe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1066
+ `)}})}});var wKe=pZe(()=>jJ(Ar([Wn({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:$e()}),Wn({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Wn({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Wn({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Wn({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Wn({type:vJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:wr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function SKe(e){return e.type.startsWith("data-")}function IJ(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=IJ(o,s):n[r]=s}return n}function CKe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function AJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ew({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ew({text:CKe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Oy(e){return e.type.startsWith("tool-")}function NKe(e){return e.type==="dynamic-tool"}function JE(e){return Oy(e)||NKe(e)}function eL(e){return e.type.split("-").slice(1).join("-")}function jKe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function kKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Oy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Oy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?IJ(u.message.metadata,w):w;t!=null&&await Z$({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Oy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await AJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:eL(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:eL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(SKe(a)){(n==null?void 0:n[a.type])!=null&&await Z$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function EKe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Mx({prefix:"aitxt",size:24});Mx({prefix:"aiobj",size:24});var _Ke=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Mx({prefix:"aiobj",size:24});var DKe={};dKe(DKe,{object:()=>TKe,text:()=>MKe});var MKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),TKe=({schema:e})=>{const t=cKe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await AJ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Ew({text:n});if(!s.success)throw new Q$({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await dI({value:s.value,schema:t});if(!o.success)throw new Q$({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},RKe=Ff({name:$e(),version:$e()}),hI=Ff({_meta:pr(Wt({}).loose())}),pb=hI,IKe=Wt({method:$e(),params:pr(hI)}),AKe=Ff({experimental:pr(Wt({}).loose()),logging:pr(Wt({}).loose()),prompts:pr(Ff({listChanged:pr(wr())})),resources:pr(Ff({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr(Ff({listChanged:pr(wr())}))});pb.extend({protocolVersion:$e(),capabilities:AKe,serverInfo:RKe,instructions:pr($e())});var PKe=pb.extend({nextCursor:pr($e())}),OKe=Wt({name:$e(),description:pr($e()),inputSchema:Wt({type:ut("object"),properties:pr(Wt({}).loose())}).loose()}).loose();PKe.extend({tools:eu(OKe)});var FKe=Wt({type:ut("text"),text:$e()}).loose(),$Ke=Wt({type:ut("image"),data:pJ(),mimeType:$e()}).loose(),PJ=Wt({uri:$e(),mimeType:pr($e())}).loose(),LKe=PJ.extend({text:$e()}),zKe=PJ.extend({blob:pJ()}),BKe=Wt({type:ut("resource"),resource:Ar([LKe,zKe])}).loose();pb.extend({content:eu(Ar([FKe,$Ke,BKe])),isError:wr().default(!1).optional()}).or(pb.extend({toolResult:co()}));var KS="2.0",VKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()])}).merge(IKe).strict(),HKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()]),result:pb}).strict(),UKe=Wt({jsonrpc:ut(KS),id:Ar([$e(),fb().int()]),error:Wt({code:fb().int(),message:$e(),data:pr(co())})}).strict(),WKe=Wt({jsonrpc:ut(KS)}).merge(Wt({method:$e(),params:pr(hI)})).strict();Ar([VKe,WKe,HKe,UKe]);async function qKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var YKe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await vf(this.body),l=await vf(this.headers),u=await vf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:G$({"Content-Type":"application/json",...h},`ai-sdk/${J$}`,Y$()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await vf(this.body),a=await vf(this.headers),l=await vf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:G$(f,`ai-sdk/${J$}`,Y$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},pI=class extends YKe{constructor(e={}){super(e)}processResponseStream(e){return bZe({stream:e,schema:wKe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},GKe=class{constructor({generateId:e=oZe,id:t=e(),transport:n=new pI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new _Ke,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await qKe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>JE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>JE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:jKe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await EKe({stream:kKe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function ZKe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(JE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function KKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var XKe=KKe;const QKe=Fc(XKe);var OJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(OJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Bi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Ol=(e,t,n,r)=>(OJ(e,t,"write to private field"),t.set(e,n),n);function JKe(e,t){return t!=null?QKe(e,t):e}var jo,Fy,$y,Fm,$m,Lm,kf,e_,t_,eXe=class{constructor(e=[]){Bi(this,jo,void 0),Bi(this,Fy,"ready"),Bi(this,$y,void 0),Bi(this,Fm,new Set),Bi(this,$m,new Set),Bi(this,Lm,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,kf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,kf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,kf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?JKe(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Bi(this,kf,()=>{Tn(this,Fm).forEach(t=>t())}),Bi(this,e_,()=>{Tn(this,$m).forEach(t=>t())}),Bi(this,t_,()=>{Tn(this,Lm).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Fy)}set status(e){Ol(this,Fy,e),Tn(this,e_).call(this)}get error(){return Tn(this,$y)}set error(e){Ol(this,$y,e),Tn(this,t_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,kf).call(this)}};jo=new WeakMap;Fy=new WeakMap;$y=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;kf=new WeakMap;e_=new WeakMap;t_=new WeakMap;var Ef,tL=class extends GKe{constructor({messages:e,...t}){const n=new eXe(e);super({...t,state:n}),Bi(this,Ef,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,Ef)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,Ef)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,Ef)["~registerErrorCallback"](r),Ol(this,Ef,n)}};Ef=new WeakMap;function FJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new tL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new tL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function tXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function nXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function rXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function sXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function $J(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:sXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function LJ(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function oXe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Hw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=FJ({transport:new pI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Pi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:fW(x)}})}),onToolCall:p,sendAutomaticallyWhen:ZKe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:$J(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=LJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function zJ(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Hw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function BJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(t8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function _w(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(W_,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(_ie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(sl,{className:r});case"upload":return c.jsx(Z_,{className:r});case"url":return c.jsx(f8,{className:r});default:return c.jsx(Kw,{className:r})}}const VJ=_.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(xa,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:J("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));VJ.displayName=us.Input.displayName;const ay=e=>e.label||(e==null?void 0:e.name),nL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function iXe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=ay(C).toLowerCase(),D=nL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ay(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ay(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(DS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(VJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(MS,{className:"min-h-60",children:[c.jsx(TS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(RS,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ay(C);return c.jsxs(IS,{value:E,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:_w(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nL(C)})]}),D&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const n_=e=>e.name||e.name,aXe=e=>{const t=n_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function lXe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Yn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[_w(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:n_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:aXe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(i8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:_w(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:n_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function HJ(e){return e.type==="dataset"&&e.label||e.name}function cXe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function uXe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),HJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function dXe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function fXe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function hXe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ai(e),s=_e(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function pXe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ai(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function UJ(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ai(e),s=_e(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function mXe(){var S,C,j;const e=_e(D=>D.card.dataSource);_e(D=>D.actions.updateDirectSource);const t=_e(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ai(),{databases:i,isPending:a,error:l,label:u}=hXe(),{schemas:d,isPending:f,error:h,label:p}=pXe(),{error:m}=UJ(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function gXe(){const e=_e(l=>l.card.dataSource),t=_e(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(Z_,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ni,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function bXe(){const e=_e(f=>f.card.dataSource),t=_e(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Kw,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function xXe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ai(t),o=_e(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=_e(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Dw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(hd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function yXe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ai(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=xXe("table"),{dataModels:x,isPending:y,error:v}=UJ(),w=E=>{const M=s.find(O=>O.id===E);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var T,I;const M=n||[],R=M.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=M.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...M,F]}t==null||t(O)},C=E=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===E.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===E.name)):O=[...M,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let M=[...E];if(d==="tables"){const O=j.filter(T=>!E.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[...E,...O]}else if(d==="datamodels"){const R=D.filter(O=>!E.some(T=>T.name===O.name&&T.type==="model"));M=[...E,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(sl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(gXe,{}),e.connectionType==="url"&&c.jsx(bXe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mXe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Dw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const M=n.some(R=>R.name===E.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(dn,{id:`table-${E.name}`,checked:M,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(E=>{const M=n.some(R=>R.name===E.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(E),children:[c.jsx(dn,{id:`dataModel-${E.name}`,checked:M,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function vXe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=dXe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=fXe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(D)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,E]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(E=>!C.some(M=>M.id===E.id&&M.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Dw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function mI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function E(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ms,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(vXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(yXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(uXe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ds,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function wXe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=$a-n;if(l.length>u){Le.error(`You can only attach ${$a} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=kQ(l);if(f.forEach(({file:h,error:p})=>{Le.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>nI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Le.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=$a}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=$a,title:n>=$a?`Maximum ${$a} files allowed`:"Attach files",children:c.jsx(B_,{className:"h-4 w-4 text-muted-foreground"})})]})}function SXe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=$a-r;if(h.length>p){Le.error(`You can only attach ${$a} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=kQ(h);if(g.forEach(({file:b,error:x})=>{Le.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>nI(x)));t(b),Le.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Le.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(Z_,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[$a-r," slot(s) available"]})]})})]})}const gI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=_p();_Ce(),ECe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=L1(),{queueMessage:C}=Dp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:E}=IM(),M=RM(l),R=_e(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(Y(),f(!0))},B=N.useCallback(H=>{const q=OUe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const K=await nI(X);j(l,K)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(K=>!(K.id&&K.id===H.id||K.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var K;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(K=b.current)==null||K.focus()},U=H=>{const q=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:q});const K=`@${"label"in H?H.label:H.name}`;e.includes(K)&&t(e.replace(K,"").trim())},G=H=>{const q=new Set(H.map(Z=>Z.id||Z.name)),X=x.selectedEntities.filter(Z=>!q.has(Z.id||Z.name));y({selectedEntities:X});let K=e;H.forEach(Z=>{const ne=`@${"label"in Z?Z.label:Z.name}`;K=K.replace(ne,"").trim()}),t(K)},Y=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(SXe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(lXe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:G}),M.length>0&&c.jsx(FUe,{files:M,onRemove:V,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:B,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ss,{open:d,onOpenChange:H=>{H&&Y(),f(H)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Sie,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(iXe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(wXe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx($ie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(y8,{className:"size-4"})})]})]})]}),c.jsx(mI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||YS,dialogMode:"aiContext"})]})});gI.displayName="ChatInputWithContext";function WJ({assistantType:e,className:t}){const n=hW(e),{removeFromQueue:r}=Dp();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(dl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function qJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=hW(e),{dequeueMessage:o}=Dp();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function YJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const E=g.current,M=k.scrollTop,R=M-E;if(g.current=M,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const E=w.current,M=e[e.length-1],R=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>E.count,I=R!==E.key,F=O>E.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-E.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const E=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function GJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function ZJ(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:EQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CXe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function NXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState($w),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:M,setShowReasoning:R}=L1(),{clearQueue:O}=Dp(),{clearFileAttachments:T,getFileAttachments:I}=IM(),F=RM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=_e(Ve=>Ve.card.dataSource),{assistantProfile:$}=zJ(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:G,errorMessage:Y,clearError:H}=oXe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[K,Z]=N.useState(""),Q=Ve=>{Z(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:ke,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:ke,dataSource:Te}),!v)return;const ze={id:Mr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:Te,config:ke,connectionId:He},nt={id:Mr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=K.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:ht}),Z(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),qJ({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=ZJ(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:Ce,loadMoreMessages:je,resetMessageWindow:de}=GJ(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=YJ(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ze(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),Le.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),Le.error("Unable to copy conversation")}},[A]);function Ze(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const $t=(K==null?void 0:K.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Zh,{className:"size-3.5"})})}),c.jsxs(Bd,{align:"end",children:[c.jsx(Uf,{children:"Options"}),c.jsx(md,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(z_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,Ce-fe.length)," ","more messages (",Ce-fe.length," ","hidden)"]})}),c.jsx(DQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(_Q,{status:U,errorMessage:Y})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(qs,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&$t&&c.jsx(MQ,{onClick:Se,placeholders:CXe}),c.jsx("div",{children:$t&&$&&c.jsx(BJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(WJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(gI,{ref:y,setInput:Z,stop:G,input:K,handleInputChange:Q,handleSubmit:Ve=>{Ze(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(mI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||YS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:hn})}),s):hn}function jXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Le.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=BT(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Le.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function kXe(e,t){switch(e.interactionMode){case"drillToDetail":EXe(e,t);break;case"drillThrough":_Xe(e,t);break;case"drillToURL":DXe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function EXe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function _Xe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function DXe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function MXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ms,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(VZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(UZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function TXe(){const e=Lt(w=>w.interactionStates),t=Lt(w=>w.setInteractionState),n=Lt(w=>w.clearLastInteractionEvent),r=Lt(w=>w.replaceCardWithInsight),s=Lt(w=>w.setPendingDrillThrough),o=Lt(w=>w.pendingDrillThrough),i=Lt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Eb(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=tfe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=WZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const E={sourceCardId:ra,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(ra,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{kXe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(MXe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function RXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function AXe(e){return e?`Back to ${e}`:"Back"}function PXe(){var x,y,v,w,S;const e=Lt(C=>C.interactionStates[ra]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Eb(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};RXe(f);const b=AXe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(B6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function KJ(){var Z;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=ip(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=td(Q=>Q.setFullscreen),d=td(Q=>Q.setPanelOpen),f=td(Q=>Q.setContainer),h=cW("dashboard"),p=uW(),m=dW("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:E,clearDefaultSheetId:M}=w6(C),[R,O]=N.useState(null);m1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();jXe(i);const{setActiveAssistantType:B}=L1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:Mr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),Le.success("Default sheet cleared")):(E(Q),O(Q),Le.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},G=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[fe]=ie.splice(parseInt(ae),1);ie.splice(ne,0,fe),z(ie)},Y=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Ur,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&Y&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(J6,{className:"h-4 w-4"}):c.jsx(e8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const fe=S===ae.id,xe=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>G(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(Yg,{enabled:w&&fe,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(v8,{className:J("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(QLe,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(M6e,{open:a,setOpen:l})]})}const K=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(TXe,{}),c.jsx(PXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(AR,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ob,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(D6e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(ob,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(NXe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:K,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(U_,{className:"h-5 w-5"})})})]})]}):null}function bI({children:e}){return c.jsx(wa,{style:{height:"100%",width:"100%"},children:c.jsx(Nre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function XJ({children:e,preferences:t}){const{currentUser:n}=_s(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(h9.Provider,{value:r,children:c.jsx(lR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function QJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:aS,children:c.jsx(__,{dashboardProps:e,children:c.jsx(bI,{children:c.jsx(XJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(AM,{...e,type:"dashboard",children:c.jsx(KJ,{})})})})})})})}function xI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function JJ(e,t,n){if(t==="source")return{isValid:!0};const r=Zs(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function eee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const tee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=xI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=_e(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:BH(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){Le.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),E=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=Q1e(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&$H();return}const z=tSe(T,I,h);if(!z){Le.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=JJ(T,z,h);if(!B.isValid){Le.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(LH(T,$))return;const P=VH(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&eee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Tx(e,t){var Pe,Qe,Nt,Ze,$t;const{tokenProps:n}=qe(),r=Ks(),s=qe().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=ope(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),p=_e(Ne=>Ne.actions.setSelectedConnectionId),m=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ai(e),{refetch:E,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:G,isLoading:Y,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:K,isColumnsLoading:Z,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=HH(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function je(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function de(Ne){p(Ne)}function Re(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),mt=(Ze=M==null?void 0:M.datamodels)==null?void 0:Ze.map(Ne=>({id:Ne.id,name:Ne.name})),be=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),ue=G==null?void 0:G.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=($t=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:$t.name,Se=Hy({schemaName:fe,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:Y||H,isTableError:q,columns:K,isColumnsLoadingOrFetching:Z||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:je,handleSchemaChange:Ce,handleTableChange:xe}}function ly(e){return`${e}-${Mr()}`}function rL(e,t){const n=qo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function OXe(e,t){const n=qo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function yI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function nee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function ree(){const e=_e(C=>C.sqlGen),t=_e(C=>C.isDevMode),n=_e(C=>C.card.dataSource),r=_e(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=yI(n),a=nee(n),l=_e(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Tx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=y_(j,e);p(k);const E=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=x_(k,di(o||""),di(s),E||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(jb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:ly(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:ly(j.column_name),name:j.column_name,label:rL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if($c(j.data_type)){const k={...j,role:"groupby",id:ly(j.column_name),name:j.column_name,type:j.data_type,label:OXe(j.column_name,"month"),granularity:"month"};d(k)}if(Bo(j.data_type)){const k={...j,role:"metric",id:ly(j.column_name),name:j.column_name,label:rL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Hy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Hy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Bo(C.dataType)}}function see(){const e=_e(m=>m.selectedConnectionId),t=_e(m=>m.selectedDatamodelId),n=_e(m=>m.selectedDatabaseName),r=_e(m=>m.selectedSchemaName),s=_e(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Tx();function p(m,g="sheet",b){var k;const x=di(m.column_name),y=di(n||""),v=di(r||""),w=di(f);let S=Lw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Mje(o,C,w,n||"",y,i):D=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),D)u(D.id),l(D.id);else{const E=Mr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:j4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:j4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function FXe({column:e}){const[t,n]=N.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=yI(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=Tx(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),p=_e(x=>x.actions.setRunSql),m=nee(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=y_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=x_(v,di(o||""),di(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Zh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Yd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function $Xe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function LXe({field:e,context:t="editor",fieldState:n}){const r=_e(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=see(),f=s?Gc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=ES({id:e.id,disabled:o}),[E,M]=N.useState(!1),R=_e(L=>L.card),{handleFieldClick:O}=tee(R),{handleDevModeFieldClick:T,isNumberField:I}=ree(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[Qg(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx($Xe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(FXe,{column:B})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(w8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Vie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const zXe="SEMAPHOR_CALCULATED_FIELD",BXe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function oee(e){return!!e.expression}function VXe(e){return!!e.expression}function HXe(e){return!!e.expression}var iee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(iee||{}),jl="Accordion",UXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[vI,WXe,qXe]=t1(jl),[XS]=Er(jl,[qXe,ZZ]),wI=ZZ(),aee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(vI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(KXe,{...o,ref:t}):c.jsx(ZXe,{...s,ref:t})})});aee.displayName=jl;var[lee,YXe]=XS(jl),[cee,GXe]=XS(jl,{collapsible:!1}),ZXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(lee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(cee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(uee,{...i,ref:t})})})}),KXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(lee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(cee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(uee,{...o,ref:t})})})}),[XXe,QS]=XS(jl),uee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=WXe(n),f=Fd(s)==="ltr",h=Ee(e.onKeyDown,p=>{var D;if(!UXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(XXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(vI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Mw="AccordionItem",[QXe,SI]=XS(Mw),dee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=QS(Mw,n),i=YXe(Mw,n),a=wI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(QXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(QZ,{"data-orientation":o.orientation,"data-state":bee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});dee.displayName=Mw;var fee="AccordionHeader",hee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(fee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":bee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});hee.displayName=fee;var r_="AccordionTrigger",pee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(r_,n),i=GXe(r_,n),a=wI(n);return c.jsx(vI.ItemSlot,{scope:n,children:c.jsx(t3e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});pee.displayName=r_;var mee="AccordionContent",gee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=QS(jl,n),o=SI(mee,n),i=wI(n);return c.jsx(n3e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});gee.displayName=mee;function bee(e){return e?"open":"closed"}var JXe=aee,eQe=dee,tQe=hee,xee=pee,yee=gee;const vee=JXe,CI=_.forwardRef(({className:e,...t},n)=>c.jsx(eQe,{ref:n,className:J("border-b",e),...t}));CI.displayName="AccordionItem";const NI=_.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tQe,{className:"flex",children:c.jsxs(xee,{ref:r,className:J("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(qs,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));NI.displayName=xee.displayName;const jI=_.forwardRef(({className:e,children:t,...n},r)=>c.jsx(yee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:J("pb-4 pt-0",e),children:t})}));jI.displayName=yee.displayName;function nQe({context:e="editor"}={}){var E,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");_e(T=>T.isDevMode);const o=_e(T=>T.card.dataSource),i=_e(T=>T.card.config),a=_e(T=>T.card),{autoJoinMetadata:l}=ha(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=gM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=xI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,ree();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&oee(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Zs(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:w_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Es,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(xa,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(ls,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(Gh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(P_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(vee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(CI,{value:T,className:"border-none",children:[c.jsx(NI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(jI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=bM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(LXe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function wee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(nQe,{context:e})," "]})}function See(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=yI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function rQe(){See();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=cr(),i=_e(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function sQe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=rQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(YZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(sl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(jS,{collisionDetection:wS,children:c.jsx(kS,{items:[],strategy:CR,children:c.jsx(wee,{context:"filter"})})})})]})}function oQe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(uR,{filter:r}),c.jsx(bS,{filter:r})]},r.id))}):null}function iQe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(oQe,{}),c.jsx(KJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(sQe,{})})]})}const aQe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-i6Wbe7nf.js"))),lQe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BrJPT6U4.js"))),cQe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-DzFuErre.js"))),uQe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-59R5lAiD.js")).then(e=>({default:e.ResourceManagementPanel})));function dQe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(m=>m.isDashboardPanelOpen),s=ee(m=>m.isVisualEditing),o=ee(m=>m.showDashboardJSON),i=ee(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(wl,{FallbackComponent:aS,children:c.jsxs(__,{dashboardProps:n,children:[c.jsx(gde,{}),c.jsx(bI,{children:c.jsxs(XJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(cQe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(aQe,{})}),c.jsxs(AR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ob,{ref:f,className:J("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uQe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(dX,{className:J("",{"w-0":!d})}),c.jsx(ob,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(AM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(lQe,{})}),c.jsx(iQe,{})]})})]})]})]})})]})})}var fQe=Object.defineProperty,hQe=(e,t,n)=>t in e?fQe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,cy=(e,t,n)=>hQe(e,typeof t!="symbol"?t+"":t,n);const pQe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},mQe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},gQe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},bQe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},xQe={stringify:e=>e,parse:e=>e},q2={string:xQe,number:bQe,boolean:pQe,function:mQe,json:gQe};function yQe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const uy=Symbol.for("r2wc.render"),dy=Symbol.for("r2wc.connected"),pu=Symbol.for("r2wc.context"),Ta=Symbol.for("r2wc.props");function vQe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=yQe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),cy(this,o,!0),cy(this,s),cy(this,r,{}),cy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ta].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?q2[x]:null;y!=null&&y.parse&&b&&(this[Ta][m]=y.parse(b,g,this))}for(const m of a)this[Ta][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[dy]=!0,this[uy]()}disconnectedCallback(){this[dy]=!1,this[pu]&&n.unmount(this[pu]),delete this[pu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?q2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ta][x]=v.parse(b,m,this),this[uy]())}[(o=dy,s=pu,r=Ta,uy)](){this[dy]&&(this[pu]?n.update(this[pu],this[Ta]):this[pu]=n.mount(this.container,e,this[Ta]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ta][p]},set(b){this[Ta][p]=b;const x=g?q2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[uy]()}})}return h}function wQe(e,t,n){const r=oj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SQe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function CQe({root:e}){e.unmount()}function NQe(e,t={}){return vQe(e,t,{mount:wQe,update:SQe,unmount:CQe})}const jQe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},kQe=NQe(QJ,{props:jQe});function EQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function oL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sL(Object(n),!0).forEach(function(r){EQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _Qe(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function DQe(e,t){if(e==null)return{};var n=_Qe(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function MQe(e,t){return TQe(e)||RQe(e,t)||IQe(e,t)||AQe()}function TQe(e){if(Array.isArray(e))return e}function RQe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function IQe(e,t){if(e){if(typeof e=="string")return iL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return iL(e,t)}}function iL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function AQe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1067
1067
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function aL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function lL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?aL(Object(n),!0).forEach(function(r){PQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function OQe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function zm(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function Tw(e){return{}.toString.call(e).includes("Object")}function FQe(e){return!Object.keys(e).length}function mb(e){return typeof e=="function"}function $Qe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function LQe(e,t){return Tw(t)||mc("changeType"),Object.keys(t).some(function(n){return!$Qe(e,n)})&&mc("changeField"),t}function zQe(e){mb(e)||mc("selectorType")}function BQe(e){mb(e)||Tw(e)||mc("handlerType"),Tw(e)&&Object.values(e).some(function(t){return!mb(t)})&&mc("handlersType")}function VQe(e){e||mc("initialIsRequired"),Tw(e)||mc("initialType"),FQe(e)&&mc("initialContent")}function HQe(e,t){throw new Error(e[t]||e.default)}var UQe={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},mc=zm(HQe)(UQe),fy={changes:LQe,selector:zQe,handler:BQe,initial:VQe};function WQe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};fy.initial(e),fy.handler(t);var n={current:e},r=zm(GQe)(n,t),s=zm(YQe)(n),o=zm(fy.changes)(e),i=zm(qQe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return fy.selector(u),u(n.current)}function l(u){OQe(r,s,o,i)(u)}return[a,l]}function qQe(e,t){return mb(t)?t(e.current):t}function YQe(e,t){return e.current=lL(lL({},e.current),t),t}function GQe(e,t,n){return mb(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var ZQe={create:WQe},KQe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function XQe(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function QQe(e){return{}.toString.call(e).includes("Object")}function JQe(e){return e||cL("configIsRequired"),QQe(e)||cL("configType"),e.urls?(eJe(),{paths:{vs:e.urls.monacoBase}}):e}function eJe(){console.warn(Cee.deprecation)}function tJe(e,t){throw new Error(e[t]||e.default)}var Cee={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1068
1068
  You are using deprecated way of configuration.
1069
1069