react-semaphor 0.0.683 → 0.0.684
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-ojEZ3aDl.js → dashboard-plus-DX0nAOrs.js} +7 -7
- package/dist/chunks/{dashboard-plus-6nuyzLrA.js → dashboard-plus-gj5LmuLG.js} +2 -2
- package/dist/chunks/{index-9grXuNPQ.js → index-C1F5fHwS.js} +6 -6
- package/dist/chunks/{index-UnDhE_za.js → index-Dn1kQ6M1.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -982,7 +982,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
982
982
|
|
|
983
983
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
984
984
|
|
|
985
|
-
`)}})}});var _Ye=vGe(()=>xQ(Sr([An({type:tt("text-start"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("text-delta"),id:Pe(),delta:Pe(),providerMetadata:Qn.optional()}),An({type:tt("text-end"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("error"),errorText:Pe()}),An({type:tt("tool-input-start"),toolCallId:Pe(),toolName:Pe(),providerExecuted:fr().optional(),dynamic:fr().optional()}),An({type:tt("tool-input-delta"),toolCallId:Pe(),inputTextDelta:Pe()}),An({type:tt("tool-input-available"),toolCallId:Pe(),toolName:Pe(),input:Lo(),providerExecuted:fr().optional(),providerMetadata:Qn.optional(),dynamic:fr().optional()}),An({type:tt("tool-input-error"),toolCallId:Pe(),toolName:Pe(),input:Lo(),providerExecuted:fr().optional(),providerMetadata:Qn.optional(),dynamic:fr().optional(),errorText:Pe()}),An({type:tt("tool-output-available"),toolCallId:Pe(),output:Lo(),providerExecuted:fr().optional(),dynamic:fr().optional(),preliminary:fr().optional()}),An({type:tt("tool-output-error"),toolCallId:Pe(),errorText:Pe(),providerExecuted:fr().optional(),dynamic:fr().optional()}),An({type:tt("reasoning-start"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("reasoning-delta"),id:Pe(),delta:Pe(),providerMetadata:Qn.optional()}),An({type:tt("reasoning-end"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("source-url"),sourceId:Pe(),url:Pe(),title:Pe().optional(),providerMetadata:Qn.optional()}),An({type:tt("source-document"),sourceId:Pe(),mediaType:Pe(),title:Pe(),filename:Pe().optional(),providerMetadata:Qn.optional()}),An({type:tt("file"),url:Pe(),mediaType:Pe(),providerMetadata:Qn.optional()}),An({type:pQ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Pe().optional(),data:Lo(),transient:fr().optional()}),An({type:tt("start-step")}),An({type:tt("finish-step")}),An({type:tt("start"),messageId:Pe().optional(),messageMetadata:Lo().optional()}),An({type:tt("finish"),messageMetadata:Lo().optional()}),An({type:tt("abort")}),An({type:tt("message-metadata"),messageMetadata:Lo()})])));function jYe(e){return e.type.startsWith("data-")}function _Q(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 o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?n[r]=_Q(s,o):n[r]=o}return n}function RYe(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,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=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){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":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){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(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,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"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,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 jQ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Av({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Av({text:RYe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function H0(e){return e.type.startsWith("tool-")}function MYe(e){return e.type==="dynamic-tool"}function k$(e){return H0(e)||MYe(e)}function _$(e){return e.type.split("-").slice(1).join("-")}function PYe({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 DYe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:c,write:d})=>{var f,h,p,m;function g(w){const E=c.message.parts.filter(H0).find(C=>C.toolCallId===w);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(w){const E=c.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===w);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function b(w){var S;const E=c.message.parts.find(j=>H0(j)&&j.toolCallId===w.toolCallId),C=w,_=E;E!=null?(E.state=w.state,_.input=C.input,_.output=C.output,_.errorText=C.errorText,_.rawInput=C.rawInput,_.preliminary=C.preliminary,_.providerExecuted=(S=C.providerExecuted)!=null?S:E.providerExecuted,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function x(w){var S;const E=c.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===w.toolCallId),C=w,_=E;E!=null?(E.state=w.state,_.toolName=w.toolName,_.input=C.input,_.output=C.output,_.errorText=C.errorText,_.rawInput=(S=C.rawInput)!=null?S:_.rawInput,_.preliminary=C.preliminary,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:C.input,output:C.output,errorText:C.errorText,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}async function v(w){if(w!=null){const S=c.message.metadata!=null?_Q(c.message.metadata,w):w;t!=null&&await w$({value:S,schema:t}),c.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=w,c.message.parts.push(w),d();break}case"text-delta":{const w=c.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=c.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete c.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=w,c.message.parts.push(w),d();break}case"reasoning-delta":{const w=c.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=c.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete c.activeReasoningParts[a.id],d();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{c.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=c.message.parts.filter(H0);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=c.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await jQ(w.text);w.dynamic?x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):b({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):b({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=y(a.toolCallId);x({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:_$(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=y(a.toolCallId);x({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:_$(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{a.messageId!=null&&(c.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":{o==null||o(new Error(a.errorText));break}default:if(jYe(a)){(n==null?void 0:n[a.type])!=null&&await w$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?c.message.parts.find(E=>w.type===E.type&&w.id===E.id):void 0;S!=null?S.data=w.data:c.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function TYe({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()}}zb({prefix:"aitxt",size:24});zb({prefix:"aiobj",size:24});var AYe=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()})}};zb({prefix:"aiobj",size:24});var IYe={};bYe(IYe,{object:()=>FYe,text:()=>OYe});var OYe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),FYe=({schema:e})=>{const t=mYe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await jQ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Av({text:n});if(!o.success)throw new E$({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await oD({value:o.value,schema:t});if(!s.success)throw new E$({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},$Ye=Zd({name:Pe(),version:Pe()}),iD=Zd({_meta:or(Lt({}).loose())}),Cg=iD,LYe=Lt({method:Pe(),params:or(iD)}),zYe=Zd({experimental:or(Lt({}).loose()),logging:or(Lt({}).loose()),prompts:or(Zd({listChanged:or(fr())})),resources:or(Zd({subscribe:or(fr()),listChanged:or(fr())})),tools:or(Zd({listChanged:or(fr())}))});Cg.extend({protocolVersion:Pe(),capabilities:zYe,serverInfo:$Ye,instructions:or(Pe())});var BYe=Cg.extend({nextCursor:or(Pe())}),VYe=Lt({name:Pe(),description:or(Pe()),inputSchema:Lt({type:tt("object"),properties:or(Lt({}).loose())}).loose()}).loose();BYe.extend({tools:mc(VYe)});var HYe=Lt({type:tt("text"),text:Pe()}).loose(),UYe=Lt({type:tt("image"),data:lQ(),mimeType:Pe()}).loose(),RQ=Lt({uri:Pe(),mimeType:or(Pe())}).loose(),WYe=RQ.extend({text:Pe()}),qYe=RQ.extend({blob:lQ()}),GYe=Lt({type:tt("resource"),resource:Sr([WYe,qYe])}).loose();Cg.extend({content:mc(Sr([HYe,UYe,GYe])),isError:fr().default(!1).optional()}).or(Cg.extend({toolResult:Lo()}));var eS="2.0",YYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()])}).merge(LYe).strict(),ZYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()]),result:Cg}).strict(),KYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()]),error:Lt({code:wg().int(),message:Pe(),data:or(Lo())})}).strict(),XYe=Lt({jsonrpc:tt(eS)}).merge(Lt({method:Pe(),params:or(iD)})).strict();Sr([YYe,XYe,ZYe,KYe]);async function QYe(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,o=await new Promise((s,i)=>{const a=new FileReader;a.onload=l=>{var c;s((c=l.target)==null?void 0:c.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:o}}))}var JYe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:s,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=s,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,o,s,i;const a=await Pd(this.body),l=await Pd(this.headers),c=await Pd(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:c,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=(o=d==null?void 0:d.credentials)!=null?o:c,y=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"POST",headers:v$({"Content-Type":"application/json",...h},`ai-sdk/${N$}`,x$()),body:JSON.stringify(p),credentials:m,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,o,s;const i=await Pd(this.body),a=await Pd(this.headers),l=await Pd(this.credentials),c=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=c==null?void 0:c.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(c==null?void 0:c.headers)!==void 0?c.headers:{...a,...e.headers},h=(r=c==null?void 0:c.credentials)!=null?r:l,m=await((o=this.fetch)!=null?o:globalThis.fetch)(d,{method:"GET",headers:v$(f,`ai-sdk/${N$}`,x$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((s=await m.text())!=null?s:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},aD=class extends JYe{constructor(e={}){super(e)}processResponseStream(e){return CGe({stream:e,schema:_Ye}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},eZe=class{constructor({generateId:e=dGe,id:t=e(),transport:n=new aD,messageMetadataSchema:r,dataPartSchemas:o,state:s,onError:i,onToolCall:a,onFinish:l,onData:c,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new AYe,this.sendMessage=async(f,h)=>{var p,m,g,y;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let b;if("text"in f||"files"in f?b={parts:[...Array.isArray(f.files)?f.files:await QYe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:b=f,f.messageId!=null){const x=this.state.messages.findIndex(v=>v.id===f.messageId);if(x===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[x].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,x+1),this.state.replaceMessage(x,{...b,id:f.messageId,role:(m=b.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...b,id:(g=b.id)!=null?g:this.generateId(),role:(y=b.role)!=null?y:"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 y,b;const x=this.state.messages,v=x[x.length-1];this.state.replaceMessage(x.length-1,{...v,parts:v.parts.map(w=>k$(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=>k$(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((y=this.sendAutomaticallyWhen)!=null&&y.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(b=this.lastMessage)==null?void 0:b.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=o,this.state=s,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=c,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:o}){var s,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let c=!1,d=!1,f=!1;try{const h={state:PYe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{c=!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:o});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var y;this.setStatus({status:"streaming"}),h.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await TYe({stream:DYe({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(c||h.name==="AbortError")return c=!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{(s=this.onFinish)==null||s.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,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 tZe(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(...s){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,s)):n=setTimeout(()=>{r=Date.now(),e.apply(this,s)},l)}}var nZe=tZe;const rZe=Hu(nZe);var oZe=l_(),MQ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},wn=(e,t,n)=>(MQ(e,t,"read from private field"),n?n.call(e):t.get(e)),xi=(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)},yl=(e,t,n,r)=>(MQ(e,t,"write to private field"),t.set(e,n),n);function sZe(e,t){return t!=null?rZe(e,t):e}var os,U0,W0,Ip,Op,Fp,$d,Xk,Qk,iZe=class{constructor(e=[]){xi(this,os,void 0),xi(this,U0,"ready"),xi(this,W0,void 0),xi(this,Ip,new Set),xi(this,Op,new Set),xi(this,Fp,new Set),this.pushMessage=t=>{yl(this,os,wn(this,os).concat(t)),wn(this,$d).call(this)},this.popMessage=()=>{yl(this,os,wn(this,os).slice(0,-1)),wn(this,$d).call(this)},this.replaceMessage=(t,n)=>{yl(this,os,[...wn(this,os).slice(0,t),this.snapshot(n),...wn(this,os).slice(t+1)]),wn(this,$d).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?sZe(t,n):t;return wn(this,Ip).add(r),()=>{wn(this,Ip).delete(r)}},this["~registerStatusCallback"]=t=>(wn(this,Op).add(t),()=>{wn(this,Op).delete(t)}),this["~registerErrorCallback"]=t=>(wn(this,Fp).add(t),()=>{wn(this,Fp).delete(t)}),xi(this,$d,()=>{wn(this,Ip).forEach(t=>t())}),xi(this,Xk,()=>{wn(this,Op).forEach(t=>t())}),xi(this,Qk,()=>{wn(this,Fp).forEach(t=>t())}),yl(this,os,e)}get status(){return wn(this,U0)}set status(e){yl(this,U0,e),wn(this,Xk).call(this)}get error(){return wn(this,W0)}set error(e){yl(this,W0,e),wn(this,Qk).call(this)}get messages(){return wn(this,os)}set messages(e){yl(this,os,[...e]),wn(this,$d).call(this)}};os=new WeakMap;U0=new WeakMap;W0=new WeakMap;Ip=new WeakMap;Op=new WeakMap;Fp=new WeakMap;$d=new WeakMap;Xk=new WeakMap;Qk=new WeakMap;var Ld,j$=class extends eZe{constructor({messages:e,...t}){const n=new iZe(e);super({...t,state:n}),xi(this,Ld,void 0),this["~registerMessagesCallback"]=(r,o)=>wn(this,Ld)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>wn(this,Ld)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>wn(this,Ld)["~registerErrorCallback"](r),yl(this,Ld,n)}};Ld=new WeakMap;function PQ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new j$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new j$(n));const s="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,s]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),c=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:c,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function aZe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function lZe(e){return e.filter((n,r,o)=>r===o.findIndex(s=>s.tableName===n.tableName&&s.datamodelName===n.datamodelName))}function cZe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function uZe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function DQ(e){return e.map(r=>{const o=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:o,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:o,tableReferenceFormat:uZe(o)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function TQ(e){var n,r;if(!e)return"";let t="";try{const o=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=o==null?void 0:o.error)==null?void 0:n.lastError)==null?void 0:r.message)||(o==null?void 0:o.error)||e.message}catch{t=e.message}return t}function dZe(){const{authToken:e,tokenProps:t}=qe(),n=ee(g=>g.dashboard.aiScopeTables),{sendMessage:r,messages:o,setMessages:s,regenerate:i,status:a,addToolResult:l,error:c,stop:d,clearError:f}=PQ({transport:new aD({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const g=di.getState();return{assistantId:"dashboard-assistant",aiContext:g.currentAIContext,reasoningEffort:g.reasoningEffort,showReasoning:g.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:g,body:y})=>({body:{...y,messages:P6(g)}})}),onToolCall:h,onFinish({isAbort:g,isDisconnect:y,isError:b}){console.log(g?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":b?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(g){var y;if(g.name==="AbortError"||(y=g.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",g)}});async function h({toolCall:g}){g.toolName==="getCurrentTableScope"&&l({tool:g.toolName,toolCallId:g.toolCallId,output:{tables:DQ(n||[])}})}const p=!["ready","error"].includes(a),m=TQ(c);return{sendMessage:r,regenerate:i,isLoading:p,messages:o,setMessages:s,status:a,stop:d,errorMessage:m,clearError:f}}const Lc=N.forwardRef(({children:e,className:t,tooltip:n,onClick:r,openDelay:o=300,buttonProps:s,...i},a)=>u.jsx(rd,{children:u.jsxs(si,{delayDuration:o,children:[u.jsx(ii,{asChild:!0,children:u.jsx(le,{ref:a,size:"sm",variant:"ghost",onClick:r,...i,...s,className:Z(`${ef}`,t),children:e})}),n&&u.jsx(Xi,{side:"bottom",sideOffset:10,children:n})]})}));Lc.displayName="IconButton";function AQ(){const{authToken:e,tokenProps:t}=qe(),n=dne(e==null?void 0:e.accessToken);function r(){if(!n||!(e!=null&&e.accessToken))return!1}const{data:o,isLoading:s,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:o==null?void 0:o.assistantProfile,isLoading:s,isFetching:i,isError:a}}function IQ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:u.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[u.jsxs("div",{className:"mb-3 flex items-center",children:[u.jsx(lL,{className:"mr-2 h-4 w-4 text-muted-foreground"}),u.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),u.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>u.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}const fZe=e=>{switch(e){case"table":return u.jsx(Qv,{className:"h-4 w-4"});case"view":return u.jsx(fh,{className:"h-4 w-4"});case"model":return u.jsx(R_,{className:"h-4 w-4"});case"file":return u.jsx(Zo,{className:"h-4 w-4"});case"dataset":return u.jsx(ou,{className:"h-4 w-4"});case"upload":return u.jsx(Jv,{className:"h-4 w-4"});case"url":return u.jsx(M_,{className:"h-4 w-4"});default:return u.jsx(Xv,{className:"h-4 w-4"})}},p0=e=>e.label||(e==null?void 0:e.name),R$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function hZe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:o,selectedEntities:s,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:c}){const[d,f]=N.useState(""),[h,p]=N.useState(""),m=o.filter(w=>{if(!d)return!0;const S=p0(w).toLowerCase(),E=R$(w).toLowerCase(),C=d.toLowerCase();return S.includes(C)||E.includes(C)});N.useEffect(()=>{e||(f(""),p(""))},[e]),N.useEffect(()=>{m.length>0&&!h&&p(p0(m[0]))},[m,h]);const g=()=>{if(!h)return;const w=m.find(S=>p0(S)===h);w&&(s.some(E=>"id"in w&&"id"in E?w.id===E.id:w.name===E.name&&w.connectionId===E.connectionId)||t(w),i(w),r())},y=w=>{(w.key==="Tab"||w.key==="Enter")&&(w.preventDefault(),g())};if(!e)return null;const b=w=>s.some(S=>"id"in w&&"id"in S?w.id===S.id:w.name===S.name&&w.connectionId===S.connectionId),x=s.length===o.length,v=s.length>0;return u.jsx(u.Fragment,{children:u.jsxs(Lw,{shouldFilter:!1,value:h,onValueChange:p,onKeyDown:y,children:[u.jsx(zw,{placeholder:"Search entities...",value:d,onValueChange:f,className:"border-0",autoFocus:!0}),u.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-xs",children:[u.jsxs(W_,{children:[s.length," ",s.length===1?"entity":"entities"," selected",x&&" (all)"]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:w=>{w.preventDefault(),w.stopPropagation(),a==null||a()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},disabled:x,className:"flex items-center gap-1 text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",title:x?"All entities already selected":"Select all entities",children:[u.jsx(xre,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"All"})]}),v&&u.jsxs("button",{onClick:w=>{w.preventDefault(),w.stopPropagation(),l==null||l()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},className:"flex items-center gap-1 text-red-600 hover:text-red-800",title:"Remove all selected entities",children:[u.jsx(vre,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Clear"})]})]})]}),u.jsxs(Bw,{className:"min-h-60",children:[u.jsx(Vw,{children:u.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[u.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),u.jsxs(le,{onClick:w=>{w.preventDefault(),w.stopPropagation(),c==null||c()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[u.jsx(ks,{className:"h-4 w-4"}),"Add Datasets"]})]})}),u.jsx(Hw,{children:m.map((w,S)=>{const E=b(w),C="id"in w?w.id:`${w.connectionId}-${w.name}`,_=p0(w);return u.jsxs(Uw,{value:_,onSelect:()=>{E?n==null||n(w):t(w)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},className:Z("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[u.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:fZe(w.type)}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate font-medium",children:_}),u.jsx("div",{className:"truncate text-xs text-muted-foreground",children:R$(w)})]}),E&&u.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:u.jsx(Lr,{className:"h-3 w-3 text-background"})})]},C)})})]})]})})}const M$=e=>{switch(e){case"table":return u.jsx(Qv,{className:"h-3 w-3"});case"view":return u.jsx(fh,{className:"h-3 w-3"});case"model":return u.jsx(R_,{className:"h-3 w-3"});case"file":return u.jsx(Zo,{className:"h-3 w-3"});case"dataset":return u.jsx(ou,{className:"h-3 w-3"});case"upload":return u.jsx(Jv,{className:"h-3 w-3"});case"url":return u.jsx(M_,{className:"h-3 w-3"});default:return u.jsx(Xv,{className:"h-3 w-3"})}},Jk=e=>e.name||e.name,pZe=e=>{const t=Jk(e),n="description"in e?e.description:"",r=e.database||"",o=e.schema||"";return u.jsxs("div",{className:"space-y-1",children:[u.jsx("div",{className:"font-medium",children:t}),n&&u.jsx("div",{className:"text-sm text-muted-foreground",children:n}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,o&&` • Schema: ${o}`]})]})};function mZe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[o,s]=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):[],c=l.length>0;return u.jsx(rd,{children:u.jsx("div",{className:"space-y-2",children:i&&u.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 u.jsxs(si,{children:[u.jsx(ii,{asChild:!0,children:u.jsxs(Mt,{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:[M$(d.type),u.jsx("span",{className:"max-w-24 truncate text-xs",children:Jk(d)}),u.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:u.jsx(Mn,{className:"h-3 w-3"})})]})}),u.jsx(Xi,{side:"top",className:"max-w-xs",children:pZe(d)})]},h)}),c&&u.jsxs(si,{open:o,onOpenChange:s,children:[u.jsx(ii,{asChild:!0,children:u.jsxs(Mt,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>s(!0),children:[u.jsx(dL,{className:"h-3 w-3"}),u.jsxs("span",{className:"text-xs",children:[l.length," more"]}),u.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:u.jsx(Mn,{className:"h-3 w-3"})})]})}),u.jsx(Xi,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),u.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return u.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:M$(d.type)}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate text-sm font-medium",children:Jk(d)}),u.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&s(!1)},children:u.jsx(Mn,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function OQ(e){return e.type==="dataset"&&e.label||e.name}function gZe(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 bZe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:u.jsxs("div",{className:"mb-4 space-y-2",children:[u.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),u.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:u.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>u.jsxs(Mt,{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:[u.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),OQ(n),u.jsx("button",{onClick:o=>{o.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:u.jsx(Mn,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQ(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;Ae(l=>l.selectedConnectionId),Ae(l=>{var c,d;return(d=(c=l==null?void 0:l.card)==null?void 0:c.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:o,data:s,isLoading:i,isError:a}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:o,error:a,semanticDomainsData:s,semanticDomains:(s==null?void 0:s.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function yZe(e,t){const{tokenProps:n}=qe(),r=ee(c=>c.authToken)||t,{refetch:o,isPending:s,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:s,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:o}}function xZe(e){var g,y;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=ra(e),o=Ae(b=>{var x,v;return(v=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:v.connectionId}),s=r==null?void 0:r.find(b=>b.id===o),i=s==null?void 0:s.type,a=s==null?void 0:s.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function c(b){return o&&b?!(b==="API"||b==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["databases",o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:o}),enabled:c(i)}),m=(y=d==null?void 0:d.databases)==null?void 0:y.map(b=>({id:b.database_name,name:b.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function vZe(e){var g;const{tokenProps:t}=qe(),n=ee(y=>y.authToken)||e,{connections:r}=ra(e),o=Ae(y=>{var b,x;return(x=(b=y==null?void 0:y.card)==null?void 0:b.dataSource)==null?void 0:x.connectionId}),s=Ae(y=>{var b,x,v;return(v=(x=(b=y==null?void 0:y.card)==null?void 0:b.dataSource)==null?void 0:x.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(y=>y.id===o),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function c(){return!(!o||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!s||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["schemas",o,s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:o,database_name:s}),enabled:c()}),m=d==null?void 0:d.schemas.map(y=>({id:y.schema_name,name:y.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function $Q(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=ra(e),o=Ae(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),s=r.find(h=>h.id===o);function i(){return!(!(n!=null&&n.accessToken)||!o)}const{data:a,isPending:l,error:c,refetch:d}=bn({queryKey:["dataModels",o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:o}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:o,dialect:h.dialect,connectionType:s==null?void 0:s.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:c,dataModels:f||[],refetch:d}}function wZe(){var S,E,C;const e=Ae(_=>_.card.dataSource);Ae(_=>_.actions.updateDirectSource);const t=Ae(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:o,error:s}=ra(),{databases:i,isPending:a,error:l,label:c}=xZe(),{schemas:d,isPending:f,error:h,label:p}=vZe(),{error:m}=$Q(),g=o==null?void 0:o.capabilities.path.includes("schema"),y=o==null?void 0:o.capabilities.path.includes("database"),b=c==null?void 0:c.toLowerCase(),x=p==null?void 0:p.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var R;if(!((R=e==null?void 0:e.dbSelection)!=null&&R.database))return;const j=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...j,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return u.jsxs(u.Fragment,{children:[(s||l||h||m)&&u.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[u.jsx("div",{className:"flex items-center",children:u.jsxs("div",{className:"text-sm text-red-800",children:[u.jsx("strong",{children:"Error loading data:"}),u.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[s&&u.jsxs("li",{children:["Connections: ",s]}),l&&u.jsxs("li",{children:[c,": ",l.message]}),h&&u.jsxs("li",{children:[p,": ",h.message]}),m&&u.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),u.jsx(le,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),u.jsxs("div",{className:"space-y-4",children:[y&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:c}),u.jsxs(Dt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[u.jsx(jt,{className:"w-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[a&&u.jsx(Ns,{className:"h-4 w-4 animate-spin"}),u.jsx($t,{placeholder:l?`Error loading ${b}`:a?`Loading ${b}...`:`Select ${b}...`})]})}),u.jsx(Rt,{children:i.map(_=>u.jsx(Se,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((E=e==null?void 0:e.dbSelection)==null?void 0:E.database)&&g&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:p}),u.jsxs(Dt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.schema)||"",onValueChange:w,disabled:f,children:[u.jsx(jt,{className:"w-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[f&&u.jsx(Ns,{className:"h-4 w-4 animate-spin"}),u.jsx($t,{placeholder:h?`Error loading ${x}`:f?`Loading ${x}...`:`Select ${x}...`})]})}),u.jsx(Rt,{children:d.map(_=>u.jsx(Se,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function SZe(){const e=Ae(l=>l.card.dataSource),t=Ae(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),o=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const c=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,...c]})},s=l=>{if(!e)return;const c=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:c})},i=l=>{if(l===0)return"0 Bytes";const c=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(c));return Number.parseFloat((l/Math.pow(c,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),u.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),o(l.dataTransfer.files)},children:[u.jsx(Jv,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),u.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),u.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>o(l.target.files),accept:".csv,.json,.xlsx,.xls"}),u.jsx(le,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),u.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>u.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(Zo,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),u.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>s(l.id),children:u.jsx(Mn,{className:"h-3 w-3"})})]},l.id))})]})]})}function CZe(){const e=Ae(f=>f.card.dataSource),t=Ae(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[o,s]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!o.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:o.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),s(""),a("api")},c=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 u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),u.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),u.jsx(wr,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),u.jsx(wr,{placeholder:"https://api.example.com/data",value:o,onChange:f=>s(f.target.value),className:"h-8 text-sm"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),u.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:[u.jsx("option",{value:"api",children:"API Endpoint"}),u.jsx("option",{value:"csv",children:"CSV File"}),u.jsx("option",{value:"json",children:"JSON File"})]})]}),u.jsxs(le,{onClick:l,disabled:!n.trim()||!o.trim(),size:"sm",className:"w-full",children:[u.jsx(ks,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>u.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(Xv,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),u.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>c(f.id),children:u.jsx(Mn,{className:"h-3 w-3"})})]},f.id))})]})]})}function EZe(e,t){var x,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:o}=ra(t),s=Ae(w=>{var S,E;return(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.connectionId}),i=Ae(w=>{var S,E,C;return(C=(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.dbSelection)==null?void 0:C.database}),a=Ae(w=>{var S,E,C;return(C=(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.dbSelection)==null?void 0:C.schema}),l=o==null?void 0:o.find(w=>w.id===s),c=l==null?void 0:l.capabilities,d=((x=c==null?void 0:c.labels)==null?void 0:x.schema)||"Schema";function f(){return s?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||c!=null&&c.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:y}=bn({queryKey:[e,s,i,a],queryFn:()=>qn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:s,database_name:i,schema_name:a}),enabled:f()}),b=(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:b||[],refetch:y,label:d}}function Iv({title:e,message:t}){return u.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:u.jsxs("div",{className:"flex items-start gap-4",children:[u.jsx(If,{className:"h-6 w-6 flex-shrink-0"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("h4",{className:"text-base font-semibold",children:e}),t&&u.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function NZe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:o,isPending:s}=ra(),[i,a]=N.useState(""),[l,c]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ko(),{entities:m,isLoading:g,error:y}=EZe("table"),{dataModels:b,isPending:x,error:v}=$Q(),w=R=>{const D=o.find(I=>I.id===R);if(!D)return;const M=D.type==="upload"?"upload":D.type==="url"?"url":"database";h({...e,connectionId:R,connectionType:D.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),p(R)},S=R=>{var O,A;const D=n||[],M=D.some(F=>F.name===R.name&&F.type===R.type);let I;if(M)I=D.filter(F=>!(F.name===R.name&&F.type===R.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:R.type,dbObjectType:R.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:R.name,dialect:R.dialect};I=[...D,F]}t==null||t(I)},E=R=>{const D=n||[],M=D.some(O=>O.type==="model"&&O.name===R.name);let I;M?I=D.filter(O=>!(O.type==="model"&&O.name===R.name)):I=[...D,R],t==null||t(I)},C=m.filter(R=>R.name.toLowerCase().includes(i.toLowerCase())),_=b.filter(R=>R.name.toLowerCase().includes(l.toLowerCase())),j=N.useCallback(()=>{if(!t)return;const R=n||[];let D=[...R];if(d==="tables"){const I=C.filter(O=>!R.some(A=>A.name===O.name&&A.type==="table")).map(O=>{var A,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:O.name,dialect:O.dialect}});D=[...R,...I]}else if(d==="datamodels"){const M=_.filter(I=>!R.some(O=>O.name===I.name&&O.type==="model"));D=[...R,...M]}t(D)},[d,C,_,n,e,t]);return N.useEffect(()=>{r&&r(j)},[r,j]),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),u.jsxs(Dt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:s,children:[u.jsx(jt,{className:"w-full",children:u.jsx($t,{placeholder:s?"Loading connections...":"Select connection..."})}),u.jsx(Rt,{children:o.map(R=>u.jsx(Se,{className:"hover:bg-muted",value:R.id,children:u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(ou,{className:"h-4 w-4 flex-shrink-0"}),u.jsx("span",{className:"truncate",children:R.name}),u.jsx(Mt,{variant:"secondary",className:"flex-shrink-0 text-xs",children:R.type})]})},R.id))})]})]}),(e==null?void 0:e.connectionId)&&u.jsxs(u.Fragment,{children:[e.connectionType==="upload"&&u.jsx(SZe,{}),e.connectionType==="url"&&u.jsx(CZe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&u.jsxs(u.Fragment,{children:[u.jsx(wZe,{}),u.jsx("div",{className:"space-y-4",children:u.jsx("div",{className:"space-y-2",children:u.jsxs(fi,{defaultValue:"tables",value:d,onValueChange:R=>f(R),className:"w-full",children:[u.jsxs(Ds,{className:"grid w-full grid-cols-2",children:[u.jsx(Fn,{value:"tables",children:"Tables & Views"}),u.jsx(Fn,{value:"datamodels",children:"Data Models"})]}),u.jsxs(xr,{value:"tables",className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search tables and views...",value:i,onChange:R=>a(R.target.value),className:"h-8 text-sm",disabled:g}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?u.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):y?u.jsx(Iv,{title:"Error loading tables",message:y.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):C.length===0?u.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):C.map(R=>{const D=n.some(M=>M.name===R.name&&M.type==="table");return u.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(R),children:[u.jsx(hn,{id:`table-${R.name}`,checked:D,onCheckedChange:()=>S(R),onClick:M=>M.stopPropagation(),disabled:g}),u.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[R.name,R.dbObjectType==="view"&&u.jsx(Mt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"})]})]},R.name)})})]}),u.jsxs(xr,{value:"datamodels",className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search data models...",value:l,onChange:R=>c(R.target.value),className:"h-8 text-sm",disabled:x}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:x?u.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?u.jsx(Iv,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?u.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(R=>{const D=n.some(M=>M.name===R.name&&M.type==="model");return u.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>E(R),children:[u.jsx(hn,{id:`dataModel-${R.name}`,checked:D,onCheckedChange:()=>E(R),onClick:M=>M.stopPropagation(),disabled:x}),u.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[u.jsx(de,{className:"cursor-pointer",children:R.name}),u.jsx("span",{className:"text-xs text-muted-foreground",children:R.description})]})]},R.name)})})]})]})})})]})]})]})}function kZe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:o=[],isRestricted:s=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,c]=N.useState(""),d=N.useCallback(E=>{const C={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:E};t({...C})},[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}=FQ(),m=s?f.filter(E=>o.includes(E.id)):f,{datasets:g,isPending:y,error:b}=yZe(e==null?void 0:e.semanticDomainId),x=E=>{const C=r||[],_=C.some(R=>R.id===E.id&&R.type==="dataset");let j;if(_)j=C.filter(R=>!(R.id===E.id&&R.type==="dataset"));else{const R={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};j=[...C,R]}n==null||n(j)},v=g.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const E=r||[],_=v.filter(R=>!E.some(D=>D.id===R.id&&D.type==="dataset")).map(R=>({id:R.id,datasetType:R.type,name:R.name||R.table,label:R.label,domainId:R.domainId,description:R.description,database:R.database,schema:R.schema,type:"dataset",connectionId:R.connectionId,connectionType:R.connectionType,dialect:R.dialect,datamodelId:R.datamodelId,sql:R.sql})),j=[...E,..._];n(j)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),u.jsxs(Dt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||s&&!!i,children:[u.jsx(jt,{className:"w-full",children:u.jsx($t,{placeholder:h?"Loading semantic domains...":s&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(E=>E.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),u.jsx(Rt,{children:m.map(E=>u.jsx(Se,{className:"hover:bg-muted",value:E.id,children:u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{className:"font-medium",children:E.label}),u.jsx("span",{className:"text-xs",children:E.description})]})},E.id))})]}),p&&u.jsx(Iv,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search datasets...",value:l,onChange:E=>c(E.target.value),className:"h-8 text-sm",disabled:y}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?u.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):b?u.jsx(Iv,{title:"Error loading datasets",message:b.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?u.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(E=>{const C=r.some(_=>_.id===E.id&&_.type==="dataset");return u.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>x(E),children:[u.jsx(hn,{id:`dataset-${E.id}`,checked:C,onCheckedChange:()=>x(E),onClick:_=>_.stopPropagation(),disabled:y}),u.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[u.jsx(de,{className:"cursor-pointer font-medium",children:E.label||E.name}),u.jsx("span",{className:"text-xs text-gray-500",children:E.description})]})]},E.label||E.name)})})]})]})]})}function lD({open:e,onOpenChange:t,dataSource:n,fallbackDataSource:r,dialogMode:o,incomingSelectedEntities:s}){const{tokenProps:i}=qe(),{allowedSemanticDomains:a}=i,[l,c]=N.useState([]),{updateDataSource:d}=ko(),f=ee(M=>M.isVisualEditing),h=ee(M=>M.dashboard.aiContext),{setAiContext:p}=nn(),m=N.useRef(null),[g,y]=N.useState(!1);FQ();const b=a&&a.length>0,x=!b,v=b&&a.length===1?a[0]:void 0,w=N.useCallback(M=>{d({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:M,selectedEntities:(n==null?void 0:n.selectedEntities)||[]})},[n,d]),S=N.useCallback(M=>{d({...n,...M})},[n,d]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&w("semanticDomain")},[b,n.mode,w]),N.useEffect(()=>{v&&!n.semanticDomainId&&S({semanticDomainId:v})},[v,n.semanticDomainId,S]),N.useEffect(()=>{e?c(s||[]):(m.current=null,y(!1))},[e,n==null?void 0:n.selectedEntities,o,d,s,n]);const E=M=>{const I=l.filter(O=>!(O.name===M.name&&O.type===M.type));c(I)},C=()=>{c([]),o==="aiContext"&&(p({...h,selectedEntities:[]}),t(!1)),o==="dataSource"&&(d({...r,...n,selectedEntities:[]}),t(!1))},_=N.useCallback(M=>{c(M)},[]),j=N.useCallback(()=>{m.current&&m.current()},[]),R=N.useCallback(M=>{m.current=M,y(!0)},[]);function D(){var M,I;if(o==="aiContext")f&&d(n),p({...h,selectedEntities:l}),t(!1);else if(o==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=l==null?void 0:l[0])==null?void 0:M.connectionId,A=(I=l==null?void 0:l[0])==null?void 0:I.connectionType;d({...n,connectionId:O,connectionType:A,selectedEntities:l})}else d({...n,selectedEntities:l});t(!1)}}return u.jsx(Ms,{open:e,onOpenChange:t,children:u.jsx(es,{className:"flex max-w-2xl flex-col",children:u.jsxs("div",{children:[u.jsxs(ts,{className:"flex-shrink-0",children:[u.jsx(ns,{children:o==="aiContext"?"Data Context":"Select Data Source"}),u.jsx(ui,{children:o==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),u.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:u.jsxs("div",{className:"space-y-4",children:[x&&u.jsx("div",{className:"space-y-2",children:u.jsx(fi,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:w,className:"w-full",children:u.jsxs(Ds,{className:"grid w-full grid-cols-2",children:[u.jsx(Fn,{value:"database",children:"Direct Source"}),u.jsx(Fn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&u.jsx(kZe,{dataSource:n,onDataSourceUpdate:S,selectedEntities:l,onSelectionChange:_,allowedDomainIds:a||[],isRestricted:b,autoSelectedDomainId:v,onRegisterSelectAll:R}),(n==null?void 0:n.mode)==="database"&&x&&u.jsx(NZe,{dataSource:n,onDataSourceUpdate:S,selectedEntities:l,onSelectionChange:_,onRegisterSelectAll:R})]})}),u.jsx(bZe,{selectedEntities:l,onDeselectEntity:E}),u.jsx(Ps,{className:"flex-shrink-0",children:u.jsx("div",{className:"flex w-full justify-between",children:u.jsxs("div",{className:"flex grow justify-end gap-2",children:[u.jsx(le,{variant:"outline",onClick:j,disabled:!g,children:"Select All"}),u.jsx(le,{variant:"outline",onClick:C,disabled:l.length===0,children:"Clear All"}),u.jsx(le,{variant:"outline",onClick:()=>t(!1),children:"Close"}),u.jsx(le,{onClick:D,disabled:l.length===0,children:"Add"})]})})})]})})})}function _Ze({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const o=N.useRef(null),s=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const c=Ca-n;if(l.length>c){Ue.error(`You can only attach ${Ca} files per message. You have ${c} slot(s) remaining.`);return}const{valid:d,errors:f}=gX(l);if(f.forEach(({file:h,error:p})=>{Ue.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>VP(p)));e(h)}catch(h){console.error("Failed to process files:",h),Ue.error("Failed to process one or more files")}o.current&&(o.current.value="")},i=()=>{var a;(a=o.current)==null||a.click()};return u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:o,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:s,className:"hidden",disabled:t||n>=Ca}),u.jsx(le,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ca,title:n>=Ca?`Maximum ${Ca} files allowed`:"Attach files",children:u.jsx(T_,{className:"h-4 w-4 text-muted-foreground"})})]})}function jZe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:o}){const[s,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)},[]),c=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=Ca-r;if(h.length>p){Ue.error(`You can only attach ${Ca} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=gX(h);if(g.forEach(({file:y,error:b})=>{Ue.error(`${y.name}: ${b}`)}),m.length>0)try{const y=await Promise.all(m.map(b=>VP(b)));t(y),Ue.success(`${y.length} file(s) attached successfully`)}catch(y){console.error("Failed to process files:",y),Ue.error("Failed to process one or more files")}},[n,r,t]);return u.jsxs("div",{className:Z("relative",o),onDragEnter:a,onDragLeave:l,onDragOver:c,onDrop:d,children:[e,s&&!n&&u.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:u.jsxs("div",{className:"flex flex-col items-center gap-2",children:[u.jsx(Jv,{className:"h-8 w-8 text-primary"}),u.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),u.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ca-r," slot(s) available"]})]})})]})}const cD=k.forwardRef(({className:e,...t},n)=>u.jsx(Ww,{className:Z("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(h7,{className:Z("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));cD.displayName=Ww.displayName;function LQ(e,[t,n]){return Math.min(n,Math.max(t,e))}function Kd(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function P$(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function RZe(...e){return t=>{let n=!1;const r=e.map(o=>{const s=P$(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():P$(e[o],null)}}}}function nc(...e){return k.useCallback(RZe(...e),e)}function zQ(e,t=[]){let n=[];function r(s,i){const a=k.createContext(i),l=n.length;n=[...n,i];const c=f=>{var b;const{scope:h,children:p,...m}=f,g=((b=h==null?void 0:h[e])==null?void 0:b[l])||a,y=k.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=k.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>k.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return k.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,MZe(o,...t)]}function MZe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var BQ=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},PZe=k[" useInsertionEffect ".trim().toString()]||BQ;function DZe({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=TZe({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=k.useRef(e!==void 0);k.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=k.useCallback(d=>{var f;if(a){const h=AZe(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function TZe({defaultProp:e,onChange:t}){const[n,r]=k.useState(e),o=k.useRef(n),s=k.useRef(t);return PZe(()=>{s.current=t},[t]),k.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function AZe(e){return typeof e=="function"}var IZe=k.createContext(void 0);function OZe(e){const t=k.useContext(IZe);return e||t||"ltr"}function FZe(e){const t=k.useRef({value:e,previous:e});return k.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function $Ze(e){const[t,n]=k.useState(void 0);return BQ(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var LZe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Bb=LZe.reduce((e,t)=>{const n=ei(`Primitive.${t}`),r=k.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function zZe(e){const t=e+"CollectionProvider",[n,r]=zQ(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:b}=g,x=N.useRef(null),v=N.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:v,collectionRef:x,children:b})};i.displayName=t;const a=e+"CollectionSlot",l=ei(a),c=N.forwardRef((g,y)=>{const{scope:b,children:x}=g,v=s(a,b),w=nc(y,v.collectionRef);return u.jsx(l,{ref:w,children:x})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=ei(d),p=N.forwardRef((g,y)=>{const{scope:b,children:x,...v}=g,w=N.useRef(null),S=nc(y,w),E=s(d,b);return N.useEffect(()=>(E.itemMap.set(w,{ref:w,...v}),()=>void E.itemMap.delete(w))),u.jsx(h,{[f]:"",ref:S,children:x})});p.displayName=d;function m(g){const y=s(e+"CollectionConsumer",g);return N.useCallback(()=>{const x=y.collectionRef.current;if(!x)return[];const v=Array.from(x.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((E,C)=>v.indexOf(E.ref.current)-v.indexOf(C.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var VQ=["PageUp","PageDown"],HQ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],UQ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Vh="Slider",[e_,BZe,VZe]=zZe(Vh),[WQ,UQe]=zQ(Vh,[VZe]),[HZe,tS]=WQ(Vh),qQ=k.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:m,...g}=e,y=k.useRef(new Set),b=k.useRef(0),v=i==="horizontal"?UZe:WZe,[w=[],S]=DZe({prop:d,defaultProp:c,onChange:D=>{var I;(I=[...y.current][b.current])==null||I.focus(),f(D)}}),E=k.useRef(w);function C(D){const M=KZe(w,D);R(D,M)}function _(D){R(D,b.current)}function j(){const D=E.current[b.current];w[b.current]!==D&&h(w)}function R(D,M,{commit:I}={commit:!1}){const O=eKe(s),A=tKe(Math.round((D-r)/s)*s+r,O),F=LQ(A,[r,o]);S((V=[])=>{const H=YZe(V,F,M);if(JZe(H,l*s)){b.current=H.indexOf(F);const $=String(H)!==String(V);return $&&I&&h(H),$?H:V}else return V})}return u.jsx(HZe,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:b,thumbs:y.current,values:w,orientation:i,form:m,children:u.jsx(e_.Provider,{scope:e.__scopeSlider,children:u.jsx(e_.Slot,{scope:e.__scopeSlider,children:u.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Kd(g.onPointerDown,()=>{a||(E.current=w)}),min:r,max:o,inverted:p,onSlideStart:a?void 0:C,onSlideMove:a?void 0:_,onSlideEnd:a?void 0:j,onHomeKeyDown:()=>!a&&R(r,0,{commit:!0}),onEndKeyDown:()=>!a&&R(o,w.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:M})=>{if(!a){const A=VQ.includes(D.key)||D.shiftKey&&HQ.includes(D.key)?10:1,F=b.current,V=w[F],H=s*A*M;R(V+H,F,{commit:!0})}}})})})})});qQ.displayName=Vh;var[GQ,YQ]=WQ(Vh,{startEdge:"left",endEdge:"right",size:"width",direction:1}),UZe=k.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...d}=e,[f,h]=k.useState(null),p=nc(t,v=>h(v)),m=k.useRef(void 0),g=OZe(o),y=g==="ltr",b=y&&!s||!y&&s;function x(v){const w=m.current||f.getBoundingClientRect(),S=[0,w.width],C=uD(S,b?[n,r]:[r,n]);return m.current=w,C(v-w.left)}return u.jsx(GQ,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:u.jsx(ZQ,{dir:g,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const w=x(v.clientX);i==null||i(w)},onSlideMove:v=>{const w=x(v.clientX);a==null||a(w)},onSlideEnd:()=>{m.current=void 0,l==null||l()},onStepKeyDown:v=>{const S=UQ[b?"from-left":"from-right"].includes(v.key);c==null||c({event:v,direction:S?-1:1})}})})}),WZe=k.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=e,d=k.useRef(null),f=nc(t,d),h=k.useRef(void 0),p=!o;function m(g){const y=h.current||d.current.getBoundingClientRect(),b=[0,y.height],v=uD(b,p?[r,n]:[n,r]);return h.current=y,v(g-y.top)}return u.jsx(GQ,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:u.jsx(ZQ,{"data-orientation":"vertical",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const y=m(g.clientY);s==null||s(y)},onSlideMove:g=>{const y=m(g.clientY);i==null||i(y)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=UQ[p?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:b?-1:1})}})})}),ZQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=e,d=tS(Vh,n);return u.jsx(Bb.span,{...c,ref:t,onKeyDown:Kd(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):VQ.concat(HQ).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:Kd(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Kd(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:Kd(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),KQ="SliderTrack",XQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=tS(KQ,n);return u.jsx(Bb.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});XQ.displayName=KQ;var t_="SliderRange",QQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=tS(t_,n),s=YQ(t_,n),i=k.useRef(null),a=nc(t,i),l=o.values.length,c=o.values.map(h=>tJ(h,o.min,o.max)),d=l>1?Math.min(...c):0,f=100-Math.max(...c);return u.jsx(Bb.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});QQ.displayName=t_;var n_="SliderThumb",JQ=k.forwardRef((e,t)=>{const n=BZe(e.__scopeSlider),[r,o]=k.useState(null),s=nc(t,a=>o(a)),i=k.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return u.jsx(qZe,{...e,ref:s,index:i})}),qZe=k.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=tS(n_,n),a=YQ(n_,n),[l,c]=k.useState(null),d=nc(t,x=>c(x)),f=l?i.form||!!l.closest("form"):!0,h=$Ze(l),p=i.values[r],m=p===void 0?0:tJ(p,i.min,i.max),g=ZZe(r,i.values.length),y=h==null?void 0:h[a.size],b=y?XZe(y,m,a.direction):0;return k.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),u.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${m}% + ${b}px)`},children:[u.jsx(e_.ItemSlot,{scope:e.__scopeSlider,children:u.jsx(Bb.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:Kd(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&u.jsx(eJ,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});JQ.displayName=n_;var GZe="RadioBubbleInput",eJ=k.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=k.useRef(null),s=nc(o,r),i=FZe(t);return k.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Bb.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});eJ.displayName=GZe;function YZe(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function tJ(e,t,n){const s=100/(n-t)*(e-t);return LQ(s,[0,100])}function ZZe(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function KZe(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function XZe(e,t,n){const r=e/2,s=uD([0,50],[0,r]);return(r-s(t)*n)*n}function QZe(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function JZe(e,t){if(t>0){const n=QZe(e);return Math.min(...n)>=t}return!0}function uD(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function eKe(e){return(String(e).split(".")[1]||"").length}function tKe(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var nJ=qQ,nKe=XQ,rKe=QQ,oKe=JQ;const rJ=k.forwardRef(({className:e,...t},n)=>u.jsxs(nJ,{ref:n,className:Z("relative flex w-full touch-none select-none items-center",e),...t,children:[u.jsx(nKe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:u.jsx(rKe,{className:"absolute h-full bg-primary"})}),u.jsx(oKe,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));rJ.displayName=nJ.displayName;const pp=["low","medium","high"],D$={low:"Low",medium:"Medium",high:"High"},sKe={low:"bg-green-100 text-green-700 dark:bg-green-950 dark:text-green-300",medium:"bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",high:"bg-orange-100 text-orange-700 dark:bg-orange-950 dark:text-orange-300"};function iKe({value:e,onValueChange:t}){const n=l=>pp.indexOf(l),r=l=>pp[l],[o,s]=N.useState([n(e)]);N.useEffect(()=>{const l=pp.indexOf(e);s([l])},[e]);const i=l=>{s(l),t(r(l[0]))},a=pp[o[0]];return u.jsxs("div",{className:"w-full space-y-3",children:[u.jsxs("div",{className:"flex justify-between items-center",children:[u.jsx("span",{className:"text-sm font-medium",children:"Reasoning Effort"}),u.jsx("span",{className:`text-xs px-2 py-0.5 rounded-md font-medium ${sKe[a]}`,children:D$[a]})]}),u.jsx(rJ,{className:"[&_[role=slider]]:focus:outline-none [&_[role=slider]]:focus:ring-0 [&_[role=slider]]:focus:ring-offset-0 [&_[role=slider]]:focus-visible:outline-none [&_[role=slider]]:focus-visible:ring-0 [&_[role=slider]]:focus-visible:ring-offset-0",value:o,min:0,max:2,step:1,onValueChange:i}),u.jsx("div",{className:"flex justify-between text-xs text-muted-foreground px-1",children:pp.map(l=>u.jsx("span",{children:D$[l]},l))})]})}const dD=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:o,stop:s,onFocus:i,status:a,assistantType:l},c)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),y=N.useRef(null),b=$g(),x=Uie(),v=Hie(),{setCurrentAIContext:w,updateSelectedEntities:S,setReasoningEffort:E,setShowReasoning:C}=ow(),{queueMessage:_}=gh(),{addFileAttachment:j,removeFileAttachment:R,clearFileAttachments:D,getFileAttachments:M}=Y_(),I=G_(l),O=Ae(U=>U.card.dataSource),A=ee(U=>{var G;return(G=U.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{c&&"current"in c&&(c.current=y.current)},[c]);const F=N.useCallback(()=>{const U=y.current;if(U){if(!e||e.length===0){U.style.height="10px";return}U.style.height="auto";const G=Math.min(Math.max(U.scrollHeight,10),200);U.style.height=`${G}px`}},[e]);N.useEffect(()=>{F()},[F]),N.useEffect(()=>{const U=setTimeout(()=>{F()},0);return()=>clearTimeout(U)},[F]);const V=()=>{const U=e.trim();!U&&I.length===0||(a!=="ready"?(_(l,U,I),t(""),D(l)):r({preventDefault:()=>{}}))},H=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),V()),U.key==="@"&&f(!0)},$=N.useCallback(U=>{const G=OVe(U.nativeEvent);G.length>0&&(U.preventDefault(),G.forEach(async X=>{const re=await VP(X);j(l,re)}))},[j,l]),T=N.useCallback(U=>{U.forEach(G=>{j(l,G)})},[j,l]),z=N.useCallback(U=>{U.forEach(G=>{j(l,G)})},[j,l]),L=N.useCallback(U=>{R(l,U)},[R,l]),P=U=>{if(b.selectedEntities.some(X=>X.id&&X.id===U.id||X.name===U.name)){const X=b.selectedEntities.filter(re=>!(re.id&&re.id===U.id||re.name===U.name));w({selectedEntities:X})}else{const X=[...b.selectedEntities,U];w({selectedEntities:X})}},B=U=>{P(U)},W=U=>{var re;if(!b.selectedEntities.some(J=>J.id&&J.id===U.id||J.name===U.name)){const J=[...b.selectedEntities,U];w({selectedEntities:J})}const X="label"in U?U.label:U.name;t(e+`@${X} `),f(!1),(re=y.current)==null||re.focus()},Y=U=>{const G=b.selectedEntities.filter(J=>!(J.id&&J.id===U.id||J.name===U.name));w({selectedEntities:G});const re=`@${"label"in U?U.label:U.name}`;e.includes(re)&&t(e.replace(re,"").trim())},q=U=>{const G=new Set(U.map(J=>J.id||J.name)),X=b.selectedEntities.filter(J=>!G.has(J.id||J.name));w({selectedEntities:X});let re=e;U.forEach(J=>{const te=`@${"label"in J?J.label:J.name}`;re=re.replace(te,"").trim()}),t(re)};return u.jsxs(jZe,{onFilesDropped:T,currentFileCount:I.length,disabled:o,className:"space-y-4",children:[u.jsx(mZe,{entities:b.selectedEntities,availableEntities:A||[],onRemoveEntity:Y,onRemoveEntities:q}),I.length>0&&u.jsx(FVe,{files:I,onRemove:L,showRemove:!o,className:"mb-2"}),u.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[u.jsx("textarea",{ref:y,value:e,onChange:n,onKeyDown:H,onPaste:$,onFocus:()=>{F(),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"}}),u.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs(bs,{open:d,onOpenChange:f,children:[u.jsx(ys,{asChild:!0,children:u.jsx(le,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:u.jsx(ore,{className:"h-4 w-4 text-muted-foreground"})})}),u.jsx(xs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:U=>U.preventDefault(),children:u.jsx(hZe,{isOpen:!0,onSelect:P,onDeselect:B,onClose:()=>{var U;f(!1),(U=y.current)==null||U.focus()},availableEntities:A||[],selectedEntities:b.selectedEntities,onTabComplete:W,onSelectAll:()=>{A&&w({selectedEntities:A})},onRemoveAll:()=>{w({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),u.jsx(_Ze,{onFilesSelected:z,disabled:o,currentFileCount:I.length}),u.jsxs(bs,{open:m,onOpenChange:g,children:[u.jsx(ys,{asChild:!0,children:u.jsx(le,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Reasoning settings",children:u.jsx(sx,{className:"h-4 w-4 text-muted-foreground"})})}),u.jsx(xs,{className:"w-72",align:"start",side:"top",sideOffset:8,children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(iKe,{value:v,onValueChange:U=>{E(U)}}),u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(cD,{id:"show-reasoning",checked:x,onCheckedChange:C}),u.jsx(de,{htmlFor:"show-reasoning",className:"font-normal",children:"Show reasoning"})]})]})})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[o&&u.jsx(le,{className:"rounded-full",size:"sm",onClick:s,children:u.jsx(bre,{className:"size-3.5 bg-background"})}),!o&&u.jsx(le,{disabled:!e.trim()&&I.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:V,title:a!=="ready"?"Message will be queued":void 0,children:u.jsx(_L,{className:"size-4"})})]})]})]}),u.jsx(lD,{incomingSelectedEntities:b.selectedEntities,open:h,onOpenChange:p,dataSource:O||uh,fallbackDataSource:uh,dialogMode:"aiContext"})]})});dD.displayName="ChatInputWithContext";function oJ({assistantType:e,className:t}){const n=T6(e),{removeFromQueue:r}=gh();return n.length===0?null:u.jsxs("div",{className:Z("space-y-2",t),children:[u.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[u.jsx(Ga,{className:"h-3 w-3"}),u.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),u.jsx("div",{className:"space-y-2",children:n.map(o=>u.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:u.jsxs("div",{className:"flex items-start justify-between gap-2",children:[u.jsx("div",{className:"flex-1 space-y-1",children:u.jsx("p",{className:"break-words text-foreground/70",children:o.text})}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,o.id),title:"Remove from queue",children:u.jsx(Mn,{className:"h-3 w-3"})})]})},o.id))})]})}function sJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const o=T6(e),{dequeueMessage:s}=gh();N.useEffect(()=>{if(t!=="ready"||n||!(o&&o.length>0))return;const a=s(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,o,s,r,e])}function iJ(e,t={}){const{threshold:n=50,delay:r=0,dependencies:o=[],forceScrollOnStream:s=!0}=t,i=N.useRef(null),[a,l]=N.useState(!0),[c,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(),y=N.useRef(e.length),b=N.useRef(!1),x=N.useRef(!1),v=N.useRef(0),w=N.useRef(0),S=N.useRef(),E=N.useCallback(()=>{const R=i.current;if(!R)return!0;const{scrollTop:D,scrollHeight:M,clientHeight:I}=R;return M-D-I<=n},[n]),C=N.useCallback((R={})=>{const D=i.current;if(!D)return;const{force:M=!1,instant:I=!1}=R;if(!a&&!M)return;const A=Date.now()-w.current;if(!M&&!I&&A<10)return;g.current&&clearTimeout(g.current),S.current&&clearTimeout(S.current);const F=()=>{x.current=!0,w.current=Date.now(),requestAnimationFrame(()=>{D&&(D.scrollTop=D.scrollHeight,d(!0),h(!1),m(0),setTimeout(()=>{x.current=!1},20))})};!I&&r>0?S.current=setTimeout(F,r):F()},[a,r]),_=N.useCallback(()=>{const R=i.current;if(!R||x.current)return;const D=R.scrollTop,M=Math.abs(D-v.current);v.current=D,M>5&&(b.current=!0);const I=E();d(I),I?(l(!0),h(!1),m(0),b.current=!1):b.current&&l(!1),b.current&&setTimeout(()=>{b.current=!1},200)},[E]),j=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{let R=!1;if(s&&e.length>0){const I=e[e.length-1];(I==null?void 0:I.role)==="assistant"&&(R=!0,b.current=!1)}if((a||R)&&!b.current){const I=e.length>50&&!R;C({instant:I})}const D=e.length!==y.current,M=e.length>y.current;D&&(y.current=e.length,!a&&!R&&M&&(h(!0),m(I=>I+1)))},5),()=>{S.current&&clearTimeout(S.current)}),[e,o,C,a,s]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>()=>{g.current&&clearTimeout(g.current),S.current&&clearTimeout(S.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:c,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:_,resetNewMessageCount:j}}function aJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:o=10}=t,[s,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=s)return e;const h=Math.max(0,e.length-s);return e.slice(h)},[e,s]),l=e.length>s,c=s>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+o,n))},[o,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{c&&e.length>s&&s<n&&i(Math.min(e.length,n))},[e.length,s,c,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:c}}function lJ(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 o=r,s=o.state;return{hasActiveTools:!0,activeToolText:bX(o.type,s),toolType:o.type}}}return{hasActiveTools:!1}}const aKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function lKe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=N.useState(!1),[a,l]=N.useState(Sm),[c,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:y,isConsoleMode:b}=L1(),x=N.useRef(null);ee(fe=>fe.dashboard.aiScopeTables);const v=ee(fe=>fe.isDashboardEditing),w=ee(fe=>fe.selectedSheetId),{setDataSource:S}=ko(),{addFrame:E,setSelectedFrameId:C,setIsDashboardEditing:_}=nn(),j=$g(),{setCurrentAIContext:R,updateSelectedEntities:D,setReasoningEffort:M,setShowReasoning:I}=ow(),{clearQueue:O}=gh(),{clearFileAttachments:A,getFileAttachments:F}=Y_(),V=G_("dashboard"),H=ee(fe=>fe.dashboard.aiContext),$=Ae(fe=>fe.card.dataSource),{assistantProfile:T}=AQ(),z=ee(fe=>fe.handleOpenAssistantProfile),{sendMessage:L,isLoading:P,messages:B,setMessages:W,status:Y,stop:q,errorMessage:U,clearError:G}=dZe(),X=N.useCallback(fe=>{r==null||r(fe),n===void 0&&m(fe)},[n,r]),re=N.useCallback(()=>{X(!g)},[g,X]);N.useEffect(()=>{if(!g)return;function fe(we){we.key==="Escape"&&X(!1)}return window.addEventListener("keydown",fe),()=>{window.removeEventListener("keydown",fe)}},[g,X]);const[J,ce]=N.useState(""),te=fe=>{ce(fe.target.value)};function se({sql:fe,data:we,cardTitle:Re,connectionId:Oe,cardType:Ie,python:$e,cardConfig:Ye,dataSource:et}){if(console.log("handleAddNewFrame",{sql:fe,data:we,cardTitle:Re,connectionId:Oe,cardType:Ie,python:$e,cardConfig:Ye,dataSource:et}),!w)return;const Ot={id:br(),title:Re||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ie==="horizontalBar"?"y":"x"}},type:Ie,sql:fe,python:$e,dataSource:et,config:Ye,connectionId:Oe},vt={id:br(),cards:[Ot],activeCardId:Ot.id};_(!0),E(w,vt,"end"),C(vt.id)}const oe=fe=>{fe.preventDefault();const we=J.trim();if(!we&&V.length===0)return;const Re=[];we&&Re.push({type:"text",text:we}),V.forEach(Oe=>{Oe.data&&Re.push({type:"file",mediaType:Oe.type,filename:Oe.name,url:`data:${Oe.type};base64,${Oe.data}`})}),L({role:"user",parts:Re}),ce(""),A("dashboard"),ge({force:!0})};N.useEffect(()=>{var fe;e&&((fe=x.current)==null||fe.focus())},[e]),sJ({assistantType:"dashboard",status:Y,isLoading:P,sendMessage:L});const{hasActiveTools:ke}=lJ(B),{visibleMessages:ue,hasMoreMessages:be,totalMessageCount:De,loadMoreMessages:it,resetMessageWindow:Ve}=aJ(B,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:We,isAtBottom:xn,hasNewMessages:zn,newMessageCount:ie,scrollToBottom:ge,handleScroll:Me,resetNewMessageCount:Be}=iJ(ue,{threshold:50,delay:0,dependencies:[Y,B.length]});function Ze(fe){ye();const we={role:"user",parts:[{type:"text",text:fe.title+" "+fe.subtitle}]};L(we)}function Et(fe){ye(),L({role:"user",parts:[{type:"text",text:fe}]})}function on(fe){ye(),L({role:"user",parts:[{type:"text",text:fe}]}),ge({force:!0})}const qt=N.useCallback(async()=>{const fe=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(fe),Ue.success("Conversation copied")}catch(we){console.error("Failed to copy conversation",we),Ue.error("Unable to copy conversation")}},[B]);function Qt(){var Re;const fe=(Re=H==null?void 0:H.selectedEntities)==null?void 0:Re[0],we={connectionId:(fe==null?void 0:fe.connectionId)||"",connectionType:(fe==null?void 0:fe.connectionType)||"",mode:(fe==null?void 0:fe.type)==="dataset"?"semanticDomain":"database",dbSelection:{database:(fe==null?void 0:fe.database)||"",schema:(fe==null?void 0:fe.schema)||"",entityType:(fe==null?void 0:fe.type)||"table"},selectedEntities:(H==null?void 0:H.selectedEntities)||[]};S(we),h(!0)}function ye(){j.selectedEntities.length===0&&R({selectedEntities:(H==null?void 0:H.selectedEntities)||[]})}const bt=(J==null?void 0:J.length)===0&&(B==null?void 0:B.filter(fe=>fe.role==="user").length)===0;function Bn(){return u.jsx("div",{"data-role":"header",children:u.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function ve(){return u.jsxs(mb,{children:[u.jsx(gb,{asChild:!0,children:u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",children:u.jsx(Zv,{className:"size-3.5"})})}),u.jsxs(Mh,{align:"end",children:[u.jsx(hf,{children:"Options"}),u.jsx(bb,{}),u.jsx(um,{checked:s,onCheckedChange:i,children:"Token Usage"}),u.jsx(um,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),u.jsx(um,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}const xe=u.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[u.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Bn(),z&&u.jsx(le,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:z,children:(T==null?void 0:T.name)||"Default Profile"}),u.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[b&&ve(),a&&u.jsx(le,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground/70 hover:text-foreground",onClick:qt,children:"Copy Conversation"}),y&&u.jsx(Lu,{text:JSON.stringify(B,null,2),className:"h-7 p-2"}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:re,children:g?u.jsx(wL,{className:"size-4"}):u.jsx(P_,{className:"size-4"})}),(v||Sm)&&u.jsx(Lc,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:Qt,children:u.jsx(Pi,{className:"size-4"})}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),G(),Ve()},children:u.jsx(jL,{className:"size-4"})}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:()=>{t(!1)},children:u.jsx(Mn,{className:"size-4"})})]})]}),u.jsxs(nd,{"data-role":"dashboard-assistant-scroll-area",ref:We,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:Me,children:[u.jsxs("div",{className:"space-y-3 pb-4",children:[be&&u.jsx("div",{className:"flex justify-center py-2",children:u.jsxs(le,{variant:"outline",size:"sm",onClick:it,className:"text-xs",children:["Load ",Math.min(5,De-ue.length)," ","more messages (",De-ue.length," ","hidden)"]})}),u.jsx(CX,{showTools:a,showSystemMessage:c,messages:ue,onAddToDashboard:se,onQuickReply:on,disableQuickReplies:P}),!ke&&u.jsx(SX,{status:Y,errorMessage:U})]}),u.jsx(Qa,{orientation:"horizontal"})]}),!xn&&u.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:u.jsxs(le,{onClick:()=>{ge({force:!0}),Be()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[u.jsx(Co,{className:"h-4 w-4"}),zn&&ie>0&&u.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:ie>9?"9+":ie})]})}),u.jsxs("div",{className:"space-y-3",children:[!T&&bt&&u.jsx(EX,{onClick:Ze,placeholders:aKe}),u.jsx("div",{children:bt&&T&&u.jsx(IQ,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:Et})}),u.jsx(oJ,{assistantType:"dashboard",className:"mb-3"}),u.jsx(dD,{ref:x,setInput:ce,stop:q,input:J,handleInputChange:te,handleSubmit:fe=>{ye(),oe(fe),ge({force:!0})},isLoading:P,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),u.jsx(lD,{incomingSelectedEntities:(H==null?void 0:H.selectedEntities)||[],open:f,onOpenChange:h,dataSource:$||uh,fallbackDataSource:uh,dialogMode:"aiContext"})]});return g&&o?En.createPortal(u.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:u.jsx("div",{className:"flex h-full w-full",children:xe})}),o):xe}function cKe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:o}=nn(),s=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),l=ee(d=>d.isDashboardEditing),c=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||c)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Ue.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&&m.id){m.id=br();const g=m.activeCardId;m.cards.forEach(y=>{const b=y.id;y.id=br(),b===g&&(m.activeCardId=y.id,y.title=`${y.title} (Copy)`)}),r(a,m),o(m.id)}}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,o,a,l,c,t])}function cJ(){var T;const{showAssistant:e}=qe(),{preferences:t}=L1(),n=((T=t==null?void 0:t.cardDisplay)==null?void 0:T.mode)==="print",r=N.useRef(null),o=N.useRef(null),[s,i]=N.useState(!1),a=su(z=>z.setFullscreen),l=su(z=>z.setPanelOpen),c=su(z=>z.setContainer),d=_6("dashboard"),f=j6(),h=R6("dashboard"),p=d.isOpen,m=f==="dashboard",g=ee(z=>z.isVisualEditing),y=ee(z=>z.themeStyle),b=ee(z=>{var L;return(L=z.dashboard)==null?void 0:L.sheets}),x=ee(z=>z.isDashboardEditing),v=ee(z=>z.selectedSheetId),{setSelectedSheetId:w,setSheetTitle:S,addSheet:E,setSheets:C}=nn();cKe(o);const{setActiveAssistantType:_}=ow();N.useEffect(()=>{p?_("dashboard"):f==="dashboard"&&a(null)},[p,_,f,a]);function j(z){var L,P;z?((L=r.current)==null||L.resize(40),l("dashboard",!0),_("dashboard")):(l("dashboard",!1),a(null),(P=r.current)==null||P.resize(0),_(null))}function R(){const z={id:br(),title:"New Sheet"};E(z),w(z.id)}function D(z){z<1?(l("dashboard",!1),a(null),_(null)):(p||l("dashboard",!0),_("dashboard"))}function M(){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 I=(z,L)=>{z.dataTransfer.setData("tabIndex",L.toString())},O=z=>{z.preventDefault()},A=(z,L)=>{const P=z.dataTransfer.getData("tabIndex");if(P===L.toString())return;const B=Array.from(b||[]),[W]=B.splice(parseInt(P),1);B.splice(L,0,W),C(B)};function F(){var z,L;if(b&&b.length>1||x)return u.jsxs(Ds,{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:[b==null?void 0:b.map((P,B)=>u.jsxs(Fn,{draggable:!0,onDragStart:W=>I(W,B),onDragOver:O,onDrop:W=>A(W,B),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>w(P.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:P.id,children:[u.jsx(lg,{enabled:x&&P.id===v,text:P.title,onSave:W=>S(P.id,W),children:P.title},P.id),x&&v===P.id&&b.length>1&&u.jsx(Mn,{className:"ml-1 size-3",onClick:()=>i(!0)})]},P.id)),x&&u.jsx("div",{style:{borderRadius:(L=(z=y==null?void 0:y.chart)==null?void 0:z.options)==null?void 0:L.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:R,children:u.jsx(ks,{className:"size-3"})})]})}function V(){return u.jsx("div",{ref:o,style:{},className:"grow",children:b==null?void 0:b.map(z=>u.jsx(xr,{style:{backgroundColor:M()},className:Z("mt-0",{}),value:z.id,children:u.jsx(J$e,{sheet:z})},z.id))})}function H(){var z;return u.jsxs(fi,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:L=>{w(L)},value:v||((z=b==null?void 0:b[0])==null?void 0:z.id),children:[F(),u.jsx(nd,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:V()}),u.jsx(D3e,{open:s,setOpen:i})]})}const $=N.useCallback(z=>{c("dashboard",z)},[c]);return b?u.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[u.jsxs(nK,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[u.jsx(Pk,{children:H()}),e===!0&&u.jsxs(u.Fragment,{children:[u.jsx(P3e,{open:p,onTabClick:j,withHandle:!0}),u.jsx(Pk,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:D,defaultSize:p?40:0,ref:r,children:u.jsx("div",{className:"grow overflow-y-auto",children:u.jsx(lKe,{open:p,setOpen:j,isFullscreen:m,onFullscreenChange:z=>a(z?"dashboard":null),fullscreenContainer:h})})})]})]}),u.jsx("div",{ref:$,className:Z("absolute inset-0",!m&&"pointer-events-none")}),e===!0&&!n&&!p&&!g&&u.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:u.jsx(le,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>j(!0),title:"Open Assistant",children:u.jsx(O_,{className:"h-5 w-5"})})})]}):null}function uJ({children:e}){return u.jsx(ci,{style:{height:"100%",width:"100%"},children:u.jsx(yne,{defaultTheme:"system",storageKey:"vite-ui-theme",children:u.jsx(rd,{delayDuration:0,children:e})})})}function dJ({children:e,preferences:t}){const{currentUser:n}=na(),r=N.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return u.jsx(MZ.Provider,{value:r,children:u.jsx(mP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function fJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return u.jsx(sd,{FallbackComponent:MM,children:u.jsx(U3,{dashboardProps:e,children:u.jsx(uJ,{children:u.jsx(dJ,{preferences:t,children:u.jsx("main",{className:"flex h-full flex-col",children:u.jsx(I6,{...e,type:"dashboard",children:u.jsx(cJ,{})})})})})})})}const uKe=e=>{const{currentContext:t,currentMode:n,selectedUsers:r,usersToRemove:o,usersToUpdate:s,selectedGroups:i=[],groupsToRemove:a=[],groupsToUpdate:l=[],selectedTenant:c,orgWideRole:d,allTenantsRole:f,tenantWideRole:h}=e;if(!t||!n)return null;switch(t){case"org-tab":if(n==="allOrgUsers")return{context:"org-tab",mode:"allOrgUsers",orgWideRole:d};if(n==="specificOrgUsers")return{context:"org-tab",mode:"specificOrgUsers",selectedUsers:r,usersToRemove:o,usersToUpdate:s};break;case"tenant-tab":if(n==="allTenants")return{context:"tenant-tab",mode:"allTenants",allTenantsRole:f};if(n==="allTenantUsers")return c?{context:"tenant-tab",mode:"allTenantUsers",tenantId:c,tenantWideRole:h}:null;if(n==="specificTenantUsers")return c?{context:"tenant-tab",mode:"specificTenantUsers",tenantId:c,selectedUsers:r,usersToRemove:o,usersToUpdate:s}:null;break;case"tenant-dialog":if(n==="allTenantUsers")return{context:"tenant-dialog",mode:"allTenantUsers",tenantWideRole:h};if(n==="specificTenantUsers")return{context:"tenant-dialog",mode:"specificTenantUsers",selectedUsers:r,usersToRemove:o,usersToUpdate:s};break;case"group-share":if(n==="specificGroups")return{context:"group-share",mode:"specificGroups",selectedGroups:i,groupsToRemove:a,groupsToUpdate:l};break}return null},hJ=e=>{var t,n,r;switch(e.context){case"org-tab":return e.mode==="specificOrgUsers"?e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0:!0;case"tenant-tab":if(e.mode==="allTenantUsers"||e.mode==="specificTenantUsers"){if(!e.tenantId)return!1;if(e.mode==="specificTenantUsers")return e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0}return!0;case"tenant-dialog":return e.mode==="specificTenantUsers"?e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0:!0;case"group-share":return e.mode==="specificGroups"?(((t=e.selectedGroups)==null?void 0:t.length)??0)>0||(((n=e.groupsToRemove)==null?void 0:n.length)??0)>0||(((r=e.groupsToUpdate)==null?void 0:r.length)??0)>0:!0}return!1};function pJ(e){var b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,r=Ae(x=>x.selectedConnectionId),o=Ae(x=>x.selectedDatabaseName),s=Ae(x=>x.selectedDatamodelId),i=Ae(x=>x.selectedSchemaName),a=Ae(x=>x.selectedTableName),{selectedConnection:l}=ra(),c=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=bn({queryKey:["columns",r,o,s,i,a],queryFn:()=>qn(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:s||"",database_name:o,schema_name:i,table_name:a}),enabled:g(c)});function g(x){return n!=null&&n.accessToken?!!(r&&o&&o!=="NA"&&i&&a||r&&(x==="S3"||x==="API")||s&&s):!1}return{columns:(b=d==null?void 0:d.columns)==null?void 0:b.map(x=>({...x,data_type:x.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:p,refetchColumns:m}}function dKe(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}const T$={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},Gr=ea()(Dg(e=>({...T$,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(o=>o.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const o=r.selectedUsers.find(s=>s.id===t);o&&(o.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(o=>o.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const o=r.selectedGroups.find(s=>s.id===t);o&&(o.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(o=>o.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>hJ(t),resetShareState:()=>{e(t=>{Object.assign(t,T$)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),mJ=()=>Gr(e=>e.searchQuery),fKe=()=>Gr(e=>e.selectedUsers),hKe=()=>Gr(e=>e.usersToRemove),pKe=()=>Gr(e=>e.usersToUpdate),mKe=()=>Gr(e=>e.selectedTenant),gKe=()=>Gr(e=>e.selectedTab),bKe=()=>Gr(e=>e.currentContext),yKe=()=>Gr(e=>e.currentMode),xKe=()=>Gr(e=>e.orgWideRole),vKe=()=>Gr(e=>e.allTenantsRole),wKe=()=>Gr(e=>e.tenantWideRole),SKe=()=>Gr(e=>e.groupWideRole),CKe=()=>Gr(e=>e.selectedGroups),EKe=()=>Gr(e=>e.groupsToRemove),NKe=()=>Gr(e=>e.groupsToUpdate),gJ=()=>Gr(e=>e.actions),kKe=()=>{const e=mJ(),t=dKe(e,300),n=gJ();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function _Ke(e,t=[]){let n=[];function r(s,i){const a=k.createContext(i),l=n.length;n=[...n,i];const c=f=>{var b;const{scope:h,children:p,...m}=f,g=((b=h==null?void 0:h[e])==null?void 0:b[l])||a,y=k.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=k.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>k.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return k.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,jKe(o,...t)]}function jKe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function RKe(e){const t=k.useRef(e);return k.useEffect(()=>{t.current=e}),k.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}var r_=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},MKe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],fD=MKe.reduce((e,t)=>{const n=ei(`Primitive.${t}`),r=k.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function PKe(){return oZe.useSyncExternalStore(DKe,()=>!0,()=>!1)}function DKe(){return()=>{}}var hD="Avatar",[TKe,WQe]=_Ke(hD),[AKe,bJ]=TKe(hD),yJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,s]=k.useState("idle");return u.jsx(AKe,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:s,children:u.jsx(fD.span,{...r,ref:t})})});yJ.displayName=hD;var xJ="AvatarImage",vJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...s}=e,i=bJ(xJ,n),a=IKe(r,s),l=RKe(c=>{o(c),i.onImageLoadingStatusChange(c)});return r_(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?u.jsx(fD.img,{...s,ref:t,src:r}):null});vJ.displayName=xJ;var wJ="AvatarFallback",SJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,s=bJ(wJ,n),[i,a]=k.useState(r===void 0);return k.useEffect(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),i&&s.imageLoadingStatus!=="loaded"?u.jsx(fD.span,{...o,ref:t}):null});SJ.displayName=wJ;function A$(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function IKe(e,{referrerPolicy:t,crossOrigin:n}){const r=PKe(),o=k.useRef(null),s=r?(o.current||(o.current=new window.Image),o.current):null,[i,a]=k.useState(()=>A$(s,e));return r_(()=>{a(A$(s,e))},[s,e]),r_(()=>{const l=f=>()=>{a(f)};if(!s)return;const c=l("loaded"),d=l("error");return s.addEventListener("load",c),s.addEventListener("error",d),t&&(s.referrerPolicy=t),typeof n=="string"&&(s.crossOrigin=n),()=>{s.removeEventListener("load",c),s.removeEventListener("error",d)}},[s,n,t]),i}var CJ=yJ,EJ=vJ,NJ=SJ;const kJ=k.forwardRef(({className:e,...t},n)=>u.jsx(CJ,{ref:n,className:Z("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));kJ.displayName=CJ.displayName;const OKe=k.forwardRef(({className:e,...t},n)=>u.jsx(EJ,{ref:n,className:Z("aspect-square h-full w-full",e),...t}));OKe.displayName=EJ.displayName;const _J=k.forwardRef(({className:e,...t},n)=>u.jsx(NJ,{ref:n,className:Z("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));_J.displayName=NJ.displayName;function jJ(e,t){var Ze,Et,on,qt,Qt;const{tokenProps:n}=qe(),r=Jo(),o=qe().authToken||e,s=Ae(ye=>ye.selectedConnectionId),i=Ae(ye=>ye.card),{queryKey:a}=cue(i),l=Ae(ye=>ye.selectedDatamodelId),c=Ae(ye=>ye.isDevMode),d=Ae(ye=>ye.selectedDatabaseName),f=Ae(ye=>ye.selectedSchemaName),h=Ae(ye=>ye.selectedTableName),p=Ae(ye=>ye.actions.setSelectedConnectionId),m=Ae(ye=>ye.actions.setSelectedDatamodelId),g=Ae(ye=>ye.actions.setSelectedDatabaseName),y=Ae(ye=>ye.actions.setSelectedSchemaName),b=Ae(ye=>ye.actions.setSelectedTableName);Ae(ye=>ye.actions.setCardSql);const{setQueryConfig:x}=ko();function v(ye){return s&&d&&f&&d!=="NA"?!0:s&&ye==="API"?!1:!!(s&&ye==="S3")}function w(ye){return s&&ye?!(ye==="API"||ye==="S3"):!1}const{refetchConnections:S,connectionsData:E,isConnectionsLoading:C,isConnectionsError:_,selectedConnection:j}=ra(e),{refetch:R,data:D,isLoading:M,isError:I}=bn({queryKey:["models",s],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:!!(o!=null&&o.accessToken)&&!!s}),O=j==null?void 0:j.type,A=(j==null?void 0:j.type)==="API"||(j==null?void 0:j.type)==="S3",{data:F,isLoading:V,isFetching:H,isError:$,refetch:T}=bn({queryKey:["databases",s],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:w(O)}),{data:z,isLoading:L,isFetching:P,isError:B,refetch:W}=bn({queryKey:["schemas",s,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d}),enabled:!!s&&!!d&&!A&&d!=="NA"}),{data:Y,isLoading:q,isFetching:U,isError:G,refetch:X}=bn({queryKey:["tables",s,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d,schema_name:f}),enabled:v(O)}),{columns:re,isColumnsLoading:J,isColumnsFetching:ce,isColumnsError:te,refetchColumns:se}=pJ(e);N.useEffect(()=>{(O==="S3"||O==="API")&&(g(""),y(""),m(""),O==="API"&&b("api"))},[O,b,g,y,m]);const oe=(j==null?void 0:j.type)==="API"?(Ze=j==null?void 0:j.type)==null?void 0:Ze.toLowerCase():h||"",ke=A?"":f||"";function ue(ye){b(ye),x(void 0),c||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function be(ye){y(ye),b("")}function De(ye){g(ye==="none"?"":ye),y(""),b(""),ye!=="none"&&ye!==""&&m("")}function it(ye){p(ye)}function Ve(ye){m(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}F&&((Et=F==null?void 0:F.databases)==null?void 0:Et.length)>0,z&&((on=z==null?void 0:z.schemas)==null?void 0:on.length)>0;const We=E==null?void 0:E.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),xn=(qt=D==null?void 0:D.datamodels)==null?void 0:qt.map(ye=>({id:ye.id,name:ye.name})),zn=F==null?void 0:F.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),ie=z==null?void 0:z.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),ge=Y==null?void 0:Y.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),Me=(Qt=D==null?void 0:D.datamodels.find(ye=>ye.id===l))==null?void 0:Qt.name,Be=g3({schemaName:ke,tableName:oe,modelName:Me,connectionType:O,databaseName:d||""});return{connectionItems:We,selectedConnectionId:s,selectedConnection:j,isConnectionsLoading:C,isConnectionsError:_,modelItems:xn,selectedDatamodelId:l,selectedDatamodelName:Me,isModelsLoading:M,isModelsError:I,selectedDatabaseName:d,databaseItems:zn,isDatabasesLoadingOrFetching:V||H,isDatabaseError:$,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:L||P,isSchemaError:B,tableItems:ge,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:G,columns:re,isColumnsLoadingOrFetching:J||ce,isColumnsError:te,isNonDbConnection:A,connectionType:O,tableName:oe,formattedTableName:Be,schemaName:ke,refetchConnections:S,refetchModels:R,refetchDatabases:T,refetchSchemas:W,refetchTables:X,refetchColumns:se,handleConnectionChange:it,handleDatamodelChange:Ve,handleDatabaseChange:De,handleSchemaChange:be,handleTableChange:ue}}function FKe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function I$(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function O$(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?I$(Object(n),!0).forEach(function(r){FKe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):I$(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $Ke(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s<r.length;s++)o=r[s],!(t.indexOf(o)>=0)&&(n[o]=e[o]);return n}function LKe(e,t){if(e==null)return{};var n=$Ke(e,t),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o<s.length;o++)r=s[o],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function zKe(e,t){return BKe(e)||VKe(e,t)||HKe(e,t)||UKe()}function BKe(e){if(Array.isArray(e))return e}function VKe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,o=!1,s=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){o=!0,s=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(o)throw s}}return n}}function HKe(e,t){if(e){if(typeof e=="string")return F$(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 F$(e,t)}}function F$(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 UKe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
985
|
+
`)}})}});var _Ye=vGe(()=>xQ(Sr([An({type:tt("text-start"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("text-delta"),id:Pe(),delta:Pe(),providerMetadata:Qn.optional()}),An({type:tt("text-end"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("error"),errorText:Pe()}),An({type:tt("tool-input-start"),toolCallId:Pe(),toolName:Pe(),providerExecuted:fr().optional(),dynamic:fr().optional()}),An({type:tt("tool-input-delta"),toolCallId:Pe(),inputTextDelta:Pe()}),An({type:tt("tool-input-available"),toolCallId:Pe(),toolName:Pe(),input:Lo(),providerExecuted:fr().optional(),providerMetadata:Qn.optional(),dynamic:fr().optional()}),An({type:tt("tool-input-error"),toolCallId:Pe(),toolName:Pe(),input:Lo(),providerExecuted:fr().optional(),providerMetadata:Qn.optional(),dynamic:fr().optional(),errorText:Pe()}),An({type:tt("tool-output-available"),toolCallId:Pe(),output:Lo(),providerExecuted:fr().optional(),dynamic:fr().optional(),preliminary:fr().optional()}),An({type:tt("tool-output-error"),toolCallId:Pe(),errorText:Pe(),providerExecuted:fr().optional(),dynamic:fr().optional()}),An({type:tt("reasoning-start"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("reasoning-delta"),id:Pe(),delta:Pe(),providerMetadata:Qn.optional()}),An({type:tt("reasoning-end"),id:Pe(),providerMetadata:Qn.optional()}),An({type:tt("source-url"),sourceId:Pe(),url:Pe(),title:Pe().optional(),providerMetadata:Qn.optional()}),An({type:tt("source-document"),sourceId:Pe(),mediaType:Pe(),title:Pe(),filename:Pe().optional(),providerMetadata:Qn.optional()}),An({type:tt("file"),url:Pe(),mediaType:Pe(),providerMetadata:Qn.optional()}),An({type:pQ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Pe().optional(),data:Lo(),transient:fr().optional()}),An({type:tt("start-step")}),An({type:tt("finish-step")}),An({type:tt("start"),messageId:Pe().optional(),messageMetadata:Lo().optional()}),An({type:tt("finish"),messageMetadata:Lo().optional()}),An({type:tt("abort")}),An({type:tt("message-metadata"),messageMetadata:Lo()})])));function jYe(e){return e.type.startsWith("data-")}function _Q(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 o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?n[r]=_Q(s,o):n[r]=o}return n}function RYe(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,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=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){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":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){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(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,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"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,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 jQ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Av({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Av({text:RYe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function H0(e){return e.type.startsWith("tool-")}function MYe(e){return e.type==="dynamic-tool"}function k$(e){return H0(e)||MYe(e)}function _$(e){return e.type.split("-").slice(1).join("-")}function PYe({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 DYe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:c,write:d})=>{var f,h,p,m;function g(w){const E=c.message.parts.filter(H0).find(C=>C.toolCallId===w);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(w){const E=c.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===w);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function b(w){var S;const E=c.message.parts.find(j=>H0(j)&&j.toolCallId===w.toolCallId),C=w,_=E;E!=null?(E.state=w.state,_.input=C.input,_.output=C.output,_.errorText=C.errorText,_.rawInput=C.rawInput,_.preliminary=C.preliminary,_.providerExecuted=(S=C.providerExecuted)!=null?S:E.providerExecuted,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function x(w){var S;const E=c.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===w.toolCallId),C=w,_=E;E!=null?(E.state=w.state,_.toolName=w.toolName,_.input=C.input,_.output=C.output,_.errorText=C.errorText,_.rawInput=(S=C.rawInput)!=null?S:_.rawInput,_.preliminary=C.preliminary,C.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:C.input,output:C.output,errorText:C.errorText,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}async function v(w){if(w!=null){const S=c.message.metadata!=null?_Q(c.message.metadata,w):w;t!=null&&await w$({value:S,schema:t}),c.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=w,c.message.parts.push(w),d();break}case"text-delta":{const w=c.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=c.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete c.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=w,c.message.parts.push(w),d();break}case"reasoning-delta":{const w=c.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=c.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete c.activeReasoningParts[a.id],d();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{c.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=c.message.parts.filter(H0);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=c.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await jQ(w.text);w.dynamic?x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):b({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):b({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=y(a.toolCallId);x({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:_$(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=y(a.toolCallId);x({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:_$(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{a.messageId!=null&&(c.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":{o==null||o(new Error(a.errorText));break}default:if(jYe(a)){(n==null?void 0:n[a.type])!=null&&await w$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?c.message.parts.find(E=>w.type===E.type&&w.id===E.id):void 0;S!=null?S.data=w.data:c.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function TYe({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()}}zb({prefix:"aitxt",size:24});zb({prefix:"aiobj",size:24});var AYe=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()})}};zb({prefix:"aiobj",size:24});var IYe={};bYe(IYe,{object:()=>FYe,text:()=>OYe});var OYe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),FYe=({schema:e})=>{const t=mYe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await jQ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Av({text:n});if(!o.success)throw new E$({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await oD({value:o.value,schema:t});if(!s.success)throw new E$({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},$Ye=Zd({name:Pe(),version:Pe()}),iD=Zd({_meta:or(Lt({}).loose())}),Cg=iD,LYe=Lt({method:Pe(),params:or(iD)}),zYe=Zd({experimental:or(Lt({}).loose()),logging:or(Lt({}).loose()),prompts:or(Zd({listChanged:or(fr())})),resources:or(Zd({subscribe:or(fr()),listChanged:or(fr())})),tools:or(Zd({listChanged:or(fr())}))});Cg.extend({protocolVersion:Pe(),capabilities:zYe,serverInfo:$Ye,instructions:or(Pe())});var BYe=Cg.extend({nextCursor:or(Pe())}),VYe=Lt({name:Pe(),description:or(Pe()),inputSchema:Lt({type:tt("object"),properties:or(Lt({}).loose())}).loose()}).loose();BYe.extend({tools:mc(VYe)});var HYe=Lt({type:tt("text"),text:Pe()}).loose(),UYe=Lt({type:tt("image"),data:lQ(),mimeType:Pe()}).loose(),RQ=Lt({uri:Pe(),mimeType:or(Pe())}).loose(),WYe=RQ.extend({text:Pe()}),qYe=RQ.extend({blob:lQ()}),GYe=Lt({type:tt("resource"),resource:Sr([WYe,qYe])}).loose();Cg.extend({content:mc(Sr([HYe,UYe,GYe])),isError:fr().default(!1).optional()}).or(Cg.extend({toolResult:Lo()}));var eS="2.0",YYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()])}).merge(LYe).strict(),ZYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()]),result:Cg}).strict(),KYe=Lt({jsonrpc:tt(eS),id:Sr([Pe(),wg().int()]),error:Lt({code:wg().int(),message:Pe(),data:or(Lo())})}).strict(),XYe=Lt({jsonrpc:tt(eS)}).merge(Lt({method:Pe(),params:or(iD)})).strict();Sr([YYe,XYe,ZYe,KYe]);async function QYe(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,o=await new Promise((s,i)=>{const a=new FileReader;a.onload=l=>{var c;s((c=l.target)==null?void 0:c.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:o}}))}var JYe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:s,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=s,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,o,s,i;const a=await Pd(this.body),l=await Pd(this.headers),c=await Pd(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:c,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=(o=d==null?void 0:d.credentials)!=null?o:c,y=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"POST",headers:v$({"Content-Type":"application/json",...h},`ai-sdk/${N$}`,x$()),body:JSON.stringify(p),credentials:m,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,o,s;const i=await Pd(this.body),a=await Pd(this.headers),l=await Pd(this.credentials),c=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=c==null?void 0:c.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(c==null?void 0:c.headers)!==void 0?c.headers:{...a,...e.headers},h=(r=c==null?void 0:c.credentials)!=null?r:l,m=await((o=this.fetch)!=null?o:globalThis.fetch)(d,{method:"GET",headers:v$(f,`ai-sdk/${N$}`,x$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((s=await m.text())!=null?s:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},aD=class extends JYe{constructor(e={}){super(e)}processResponseStream(e){return CGe({stream:e,schema:_Ye}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},eZe=class{constructor({generateId:e=dGe,id:t=e(),transport:n=new aD,messageMetadataSchema:r,dataPartSchemas:o,state:s,onError:i,onToolCall:a,onFinish:l,onData:c,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new AYe,this.sendMessage=async(f,h)=>{var p,m,g,y;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let b;if("text"in f||"files"in f?b={parts:[...Array.isArray(f.files)?f.files:await QYe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:b=f,f.messageId!=null){const x=this.state.messages.findIndex(v=>v.id===f.messageId);if(x===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[x].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,x+1),this.state.replaceMessage(x,{...b,id:f.messageId,role:(m=b.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...b,id:(g=b.id)!=null?g:this.generateId(),role:(y=b.role)!=null?y:"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 y,b;const x=this.state.messages,v=x[x.length-1];this.state.replaceMessage(x.length-1,{...v,parts:v.parts.map(w=>k$(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=>k$(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((y=this.sendAutomaticallyWhen)!=null&&y.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(b=this.lastMessage)==null?void 0:b.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=o,this.state=s,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=c,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:o}){var s,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let c=!1,d=!1,f=!1;try{const h={state:PYe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{c=!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:o});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var y;this.setStatus({status:"streaming"}),h.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await TYe({stream:DYe({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(c||h.name==="AbortError")return c=!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{(s=this.onFinish)==null||s.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,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 tZe(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(...s){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,s)):n=setTimeout(()=>{r=Date.now(),e.apply(this,s)},l)}}var nZe=tZe;const rZe=Hu(nZe);var oZe=l_(),MQ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},wn=(e,t,n)=>(MQ(e,t,"read from private field"),n?n.call(e):t.get(e)),xi=(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)},yl=(e,t,n,r)=>(MQ(e,t,"write to private field"),t.set(e,n),n);function sZe(e,t){return t!=null?rZe(e,t):e}var os,U0,W0,Ip,Op,Fp,$d,Xk,Qk,iZe=class{constructor(e=[]){xi(this,os,void 0),xi(this,U0,"ready"),xi(this,W0,void 0),xi(this,Ip,new Set),xi(this,Op,new Set),xi(this,Fp,new Set),this.pushMessage=t=>{yl(this,os,wn(this,os).concat(t)),wn(this,$d).call(this)},this.popMessage=()=>{yl(this,os,wn(this,os).slice(0,-1)),wn(this,$d).call(this)},this.replaceMessage=(t,n)=>{yl(this,os,[...wn(this,os).slice(0,t),this.snapshot(n),...wn(this,os).slice(t+1)]),wn(this,$d).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?sZe(t,n):t;return wn(this,Ip).add(r),()=>{wn(this,Ip).delete(r)}},this["~registerStatusCallback"]=t=>(wn(this,Op).add(t),()=>{wn(this,Op).delete(t)}),this["~registerErrorCallback"]=t=>(wn(this,Fp).add(t),()=>{wn(this,Fp).delete(t)}),xi(this,$d,()=>{wn(this,Ip).forEach(t=>t())}),xi(this,Xk,()=>{wn(this,Op).forEach(t=>t())}),xi(this,Qk,()=>{wn(this,Fp).forEach(t=>t())}),yl(this,os,e)}get status(){return wn(this,U0)}set status(e){yl(this,U0,e),wn(this,Xk).call(this)}get error(){return wn(this,W0)}set error(e){yl(this,W0,e),wn(this,Qk).call(this)}get messages(){return wn(this,os)}set messages(e){yl(this,os,[...e]),wn(this,$d).call(this)}};os=new WeakMap;U0=new WeakMap;W0=new WeakMap;Ip=new WeakMap;Op=new WeakMap;Fp=new WeakMap;$d=new WeakMap;Xk=new WeakMap;Qk=new WeakMap;var Ld,j$=class extends eZe{constructor({messages:e,...t}){const n=new iZe(e);super({...t,state:n}),xi(this,Ld,void 0),this["~registerMessagesCallback"]=(r,o)=>wn(this,Ld)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>wn(this,Ld)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>wn(this,Ld)["~registerErrorCallback"](r),yl(this,Ld,n)}};Ld=new WeakMap;function PQ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new j$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new j$(n));const s="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,s]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),c=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:c,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function aZe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function lZe(e){return e.filter((n,r,o)=>r===o.findIndex(s=>s.tableName===n.tableName&&s.datamodelName===n.datamodelName))}function cZe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function uZe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function DQ(e){return e.map(r=>{const o=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:o,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:o,tableReferenceFormat:uZe(o)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function TQ(e){var n,r;if(!e)return"";let t="";try{const o=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=o==null?void 0:o.error)==null?void 0:n.lastError)==null?void 0:r.message)||(o==null?void 0:o.error)||e.message}catch{t=e.message}return t}function dZe(){const{authToken:e,tokenProps:t}=qe(),n=ee(g=>g.dashboard.aiScopeTables),{sendMessage:r,messages:o,setMessages:s,regenerate:i,status:a,addToolResult:l,error:c,stop:d,clearError:f}=PQ({transport:new aD({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const g=di.getState();return{assistantId:"dashboard-assistant",aiContext:g.currentAIContext,reasoningEffort:g.reasoningEffort,showReasoning:g.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:g,body:y})=>({body:{...y,messages:P6(g)}})}),onToolCall:h,onFinish({isAbort:g,isDisconnect:y,isError:b}){console.log(g?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":b?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(g){var y;if(g.name==="AbortError"||(y=g.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",g)}});async function h({toolCall:g}){g.toolName==="getCurrentTableScope"&&l({tool:g.toolName,toolCallId:g.toolCallId,output:{tables:DQ(n||[])}})}const p=!["ready","error"].includes(a),m=TQ(c);return{sendMessage:r,regenerate:i,isLoading:p,messages:o,setMessages:s,status:a,stop:d,errorMessage:m,clearError:f}}const Lc=N.forwardRef(({children:e,className:t,tooltip:n,onClick:r,openDelay:o=300,buttonProps:s,...i},a)=>u.jsx(rd,{children:u.jsxs(si,{delayDuration:o,children:[u.jsx(ii,{asChild:!0,children:u.jsx(le,{ref:a,size:"sm",variant:"ghost",onClick:r,...i,...s,className:Z(`${ef}`,t),children:e})}),n&&u.jsx(Xi,{side:"bottom",sideOffset:10,children:n})]})}));Lc.displayName="IconButton";function AQ(){const{authToken:e,tokenProps:t}=qe(),n=dne(e==null?void 0:e.accessToken);function r(){if(!n||!(e!=null&&e.accessToken))return!1}const{data:o,isLoading:s,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:o==null?void 0:o.assistantProfile,isLoading:s,isFetching:i,isError:a}}function IQ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:u.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[u.jsxs("div",{className:"mb-3 flex items-center",children:[u.jsx(lL,{className:"mr-2 h-4 w-4 text-muted-foreground"}),u.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),u.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>u.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}const fZe=e=>{switch(e){case"table":return u.jsx(Qv,{className:"h-4 w-4"});case"view":return u.jsx(fh,{className:"h-4 w-4"});case"model":return u.jsx(R_,{className:"h-4 w-4"});case"file":return u.jsx(Zo,{className:"h-4 w-4"});case"dataset":return u.jsx(ou,{className:"h-4 w-4"});case"upload":return u.jsx(Jv,{className:"h-4 w-4"});case"url":return u.jsx(M_,{className:"h-4 w-4"});default:return u.jsx(Xv,{className:"h-4 w-4"})}},p0=e=>e.label||(e==null?void 0:e.name),R$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function hZe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:o,selectedEntities:s,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:c}){const[d,f]=N.useState(""),[h,p]=N.useState(""),m=o.filter(w=>{if(!d)return!0;const S=p0(w).toLowerCase(),E=R$(w).toLowerCase(),C=d.toLowerCase();return S.includes(C)||E.includes(C)});N.useEffect(()=>{e||(f(""),p(""))},[e]),N.useEffect(()=>{m.length>0&&!h&&p(p0(m[0]))},[m,h]);const g=()=>{if(!h)return;const w=m.find(S=>p0(S)===h);w&&(s.some(E=>"id"in w&&"id"in E?w.id===E.id:w.name===E.name&&w.connectionId===E.connectionId)||t(w),i(w),r())},y=w=>{(w.key==="Tab"||w.key==="Enter")&&(w.preventDefault(),g())};if(!e)return null;const b=w=>s.some(S=>"id"in w&&"id"in S?w.id===S.id:w.name===S.name&&w.connectionId===S.connectionId),x=s.length===o.length,v=s.length>0;return u.jsx(u.Fragment,{children:u.jsxs(Lw,{shouldFilter:!1,value:h,onValueChange:p,onKeyDown:y,children:[u.jsx(zw,{placeholder:"Search entities...",value:d,onValueChange:f,className:"border-0",autoFocus:!0}),u.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-xs",children:[u.jsxs(W_,{children:[s.length," ",s.length===1?"entity":"entities"," selected",x&&" (all)"]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:w=>{w.preventDefault(),w.stopPropagation(),a==null||a()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},disabled:x,className:"flex items-center gap-1 text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",title:x?"All entities already selected":"Select all entities",children:[u.jsx(xre,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"All"})]}),v&&u.jsxs("button",{onClick:w=>{w.preventDefault(),w.stopPropagation(),l==null||l()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},className:"flex items-center gap-1 text-red-600 hover:text-red-800",title:"Remove all selected entities",children:[u.jsx(vre,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Clear"})]})]})]}),u.jsxs(Bw,{className:"min-h-60",children:[u.jsx(Vw,{children:u.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[u.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),u.jsxs(le,{onClick:w=>{w.preventDefault(),w.stopPropagation(),c==null||c()},onMouseDown:w=>{w.preventDefault(),w.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[u.jsx(ks,{className:"h-4 w-4"}),"Add Datasets"]})]})}),u.jsx(Hw,{children:m.map((w,S)=>{const E=b(w),C="id"in w?w.id:`${w.connectionId}-${w.name}`,_=p0(w);return u.jsxs(Uw,{value:_,onSelect:()=>{E?n==null||n(w):t(w)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},className:Z("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[u.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:fZe(w.type)}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate font-medium",children:_}),u.jsx("div",{className:"truncate text-xs text-muted-foreground",children:R$(w)})]}),E&&u.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:u.jsx(Lr,{className:"h-3 w-3 text-background"})})]},C)})})]})]})})}const M$=e=>{switch(e){case"table":return u.jsx(Qv,{className:"h-3 w-3"});case"view":return u.jsx(fh,{className:"h-3 w-3"});case"model":return u.jsx(R_,{className:"h-3 w-3"});case"file":return u.jsx(Zo,{className:"h-3 w-3"});case"dataset":return u.jsx(ou,{className:"h-3 w-3"});case"upload":return u.jsx(Jv,{className:"h-3 w-3"});case"url":return u.jsx(M_,{className:"h-3 w-3"});default:return u.jsx(Xv,{className:"h-3 w-3"})}},Jk=e=>e.name||e.name,pZe=e=>{const t=Jk(e),n="description"in e?e.description:"",r=e.database||"",o=e.schema||"";return u.jsxs("div",{className:"space-y-1",children:[u.jsx("div",{className:"font-medium",children:t}),n&&u.jsx("div",{className:"text-sm text-muted-foreground",children:n}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,o&&` • Schema: ${o}`]})]})};function mZe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[o,s]=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):[],c=l.length>0;return u.jsx(rd,{children:u.jsx("div",{className:"space-y-2",children:i&&u.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 u.jsxs(si,{children:[u.jsx(ii,{asChild:!0,children:u.jsxs(Mt,{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:[M$(d.type),u.jsx("span",{className:"max-w-24 truncate text-xs",children:Jk(d)}),u.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:u.jsx(Mn,{className:"h-3 w-3"})})]})}),u.jsx(Xi,{side:"top",className:"max-w-xs",children:pZe(d)})]},h)}),c&&u.jsxs(si,{open:o,onOpenChange:s,children:[u.jsx(ii,{asChild:!0,children:u.jsxs(Mt,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>s(!0),children:[u.jsx(dL,{className:"h-3 w-3"}),u.jsxs("span",{className:"text-xs",children:[l.length," more"]}),u.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:u.jsx(Mn,{className:"h-3 w-3"})})]})}),u.jsx(Xi,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),u.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return u.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:M$(d.type)}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate text-sm font-medium",children:Jk(d)}),u.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&s(!1)},children:u.jsx(Mn,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function OQ(e){return e.type==="dataset"&&e.label||e.name}function gZe(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 bZe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:u.jsxs("div",{className:"mb-4 space-y-2",children:[u.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),u.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:u.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>u.jsxs(Mt,{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:[u.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),OQ(n),u.jsx("button",{onClick:o=>{o.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:u.jsx(Mn,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQ(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;Ae(l=>l.selectedConnectionId),Ae(l=>{var c,d;return(d=(c=l==null?void 0:l.card)==null?void 0:c.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:o,data:s,isLoading:i,isError:a}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:o,error:a,semanticDomainsData:s,semanticDomains:(s==null?void 0:s.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function yZe(e,t){const{tokenProps:n}=qe(),r=ee(c=>c.authToken)||t,{refetch:o,isPending:s,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:s,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:o}}function xZe(e){var g,y;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=ra(e),o=Ae(b=>{var x,v;return(v=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:v.connectionId}),s=r==null?void 0:r.find(b=>b.id===o),i=s==null?void 0:s.type,a=s==null?void 0:s.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function c(b){return o&&b?!(b==="API"||b==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["databases",o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:o}),enabled:c(i)}),m=(y=d==null?void 0:d.databases)==null?void 0:y.map(b=>({id:b.database_name,name:b.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function vZe(e){var g;const{tokenProps:t}=qe(),n=ee(y=>y.authToken)||e,{connections:r}=ra(e),o=Ae(y=>{var b,x;return(x=(b=y==null?void 0:y.card)==null?void 0:b.dataSource)==null?void 0:x.connectionId}),s=Ae(y=>{var b,x,v;return(v=(x=(b=y==null?void 0:y.card)==null?void 0:b.dataSource)==null?void 0:x.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(y=>y.id===o),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function c(){return!(!o||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!s||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["schemas",o,s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:o,database_name:s}),enabled:c()}),m=d==null?void 0:d.schemas.map(y=>({id:y.schema_name,name:y.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function $Q(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=ra(e),o=Ae(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),s=r.find(h=>h.id===o);function i(){return!(!(n!=null&&n.accessToken)||!o)}const{data:a,isPending:l,error:c,refetch:d}=bn({queryKey:["dataModels",o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:o}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:o,dialect:h.dialect,connectionType:s==null?void 0:s.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:c,dataModels:f||[],refetch:d}}function wZe(){var S,E,C;const e=Ae(_=>_.card.dataSource);Ae(_=>_.actions.updateDirectSource);const t=Ae(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:o,error:s}=ra(),{databases:i,isPending:a,error:l,label:c}=xZe(),{schemas:d,isPending:f,error:h,label:p}=vZe(),{error:m}=$Q(),g=o==null?void 0:o.capabilities.path.includes("schema"),y=o==null?void 0:o.capabilities.path.includes("database"),b=c==null?void 0:c.toLowerCase(),x=p==null?void 0:p.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var R;if(!((R=e==null?void 0:e.dbSelection)!=null&&R.database))return;const j=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...j,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return u.jsxs(u.Fragment,{children:[(s||l||h||m)&&u.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[u.jsx("div",{className:"flex items-center",children:u.jsxs("div",{className:"text-sm text-red-800",children:[u.jsx("strong",{children:"Error loading data:"}),u.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[s&&u.jsxs("li",{children:["Connections: ",s]}),l&&u.jsxs("li",{children:[c,": ",l.message]}),h&&u.jsxs("li",{children:[p,": ",h.message]}),m&&u.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),u.jsx(le,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),u.jsxs("div",{className:"space-y-4",children:[y&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:c}),u.jsxs(Dt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[u.jsx(jt,{className:"w-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[a&&u.jsx(Ns,{className:"h-4 w-4 animate-spin"}),u.jsx($t,{placeholder:l?`Error loading ${b}`:a?`Loading ${b}...`:`Select ${b}...`})]})}),u.jsx(Rt,{children:i.map(_=>u.jsx(Se,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((E=e==null?void 0:e.dbSelection)==null?void 0:E.database)&&g&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:p}),u.jsxs(Dt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.schema)||"",onValueChange:w,disabled:f,children:[u.jsx(jt,{className:"w-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[f&&u.jsx(Ns,{className:"h-4 w-4 animate-spin"}),u.jsx($t,{placeholder:h?`Error loading ${x}`:f?`Loading ${x}...`:`Select ${x}...`})]})}),u.jsx(Rt,{children:d.map(_=>u.jsx(Se,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function SZe(){const e=Ae(l=>l.card.dataSource),t=Ae(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),o=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const c=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,...c]})},s=l=>{if(!e)return;const c=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:c})},i=l=>{if(l===0)return"0 Bytes";const c=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(c));return Number.parseFloat((l/Math.pow(c,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),u.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),o(l.dataTransfer.files)},children:[u.jsx(Jv,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),u.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),u.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>o(l.target.files),accept:".csv,.json,.xlsx,.xls"}),u.jsx(le,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),u.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>u.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(Zo,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),u.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>s(l.id),children:u.jsx(Mn,{className:"h-3 w-3"})})]},l.id))})]})]})}function CZe(){const e=Ae(f=>f.card.dataSource),t=Ae(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[o,s]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!o.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:o.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),s(""),a("api")},c=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 u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),u.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),u.jsx(wr,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),u.jsx(wr,{placeholder:"https://api.example.com/data",value:o,onChange:f=>s(f.target.value),className:"h-8 text-sm"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),u.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:[u.jsx("option",{value:"api",children:"API Endpoint"}),u.jsx("option",{value:"csv",children:"CSV File"}),u.jsx("option",{value:"json",children:"JSON File"})]})]}),u.jsxs(le,{onClick:l,disabled:!n.trim()||!o.trim(),size:"sm",className:"w-full",children:[u.jsx(ks,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&u.jsxs("div",{className:"space-y-2",children:[u.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>u.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(Xv,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),u.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>c(f.id),children:u.jsx(Mn,{className:"h-3 w-3"})})]},f.id))})]})]})}function EZe(e,t){var x,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:o}=ra(t),s=Ae(w=>{var S,E;return(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.connectionId}),i=Ae(w=>{var S,E,C;return(C=(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.dbSelection)==null?void 0:C.database}),a=Ae(w=>{var S,E,C;return(C=(E=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:E.dbSelection)==null?void 0:C.schema}),l=o==null?void 0:o.find(w=>w.id===s),c=l==null?void 0:l.capabilities,d=((x=c==null?void 0:c.labels)==null?void 0:x.schema)||"Schema";function f(){return s?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||c!=null&&c.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:y}=bn({queryKey:[e,s,i,a],queryFn:()=>qn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:s,database_name:i,schema_name:a}),enabled:f()}),b=(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:b||[],refetch:y,label:d}}function Iv({title:e,message:t}){return u.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:u.jsxs("div",{className:"flex items-start gap-4",children:[u.jsx(If,{className:"h-6 w-6 flex-shrink-0"}),u.jsxs("div",{className:"flex-1",children:[u.jsx("h4",{className:"text-base font-semibold",children:e}),t&&u.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function NZe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:o,isPending:s}=ra(),[i,a]=N.useState(""),[l,c]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ko(),{entities:m,isLoading:g,error:y}=EZe("table"),{dataModels:b,isPending:x,error:v}=$Q(),w=R=>{const D=o.find(I=>I.id===R);if(!D)return;const M=D.type==="upload"?"upload":D.type==="url"?"url":"database";h({...e,connectionId:R,connectionType:D.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),p(R)},S=R=>{var O,A;const D=n||[],M=D.some(F=>F.name===R.name&&F.type===R.type);let I;if(M)I=D.filter(F=>!(F.name===R.name&&F.type===R.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:R.type,dbObjectType:R.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:R.name,dialect:R.dialect};I=[...D,F]}t==null||t(I)},E=R=>{const D=n||[],M=D.some(O=>O.type==="model"&&O.name===R.name);let I;M?I=D.filter(O=>!(O.type==="model"&&O.name===R.name)):I=[...D,R],t==null||t(I)},C=m.filter(R=>R.name.toLowerCase().includes(i.toLowerCase())),_=b.filter(R=>R.name.toLowerCase().includes(l.toLowerCase())),j=N.useCallback(()=>{if(!t)return;const R=n||[];let D=[...R];if(d==="tables"){const I=C.filter(O=>!R.some(A=>A.name===O.name&&A.type==="table")).map(O=>{var A,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:O.name,dialect:O.dialect}});D=[...R,...I]}else if(d==="datamodels"){const M=_.filter(I=>!R.some(O=>O.name===I.name&&O.type==="model"));D=[...R,...M]}t(D)},[d,C,_,n,e,t]);return N.useEffect(()=>{r&&r(j)},[r,j]),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),u.jsxs(Dt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:s,children:[u.jsx(jt,{className:"w-full",children:u.jsx($t,{placeholder:s?"Loading connections...":"Select connection..."})}),u.jsx(Rt,{children:o.map(R=>u.jsx(Se,{className:"hover:bg-muted",value:R.id,children:u.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[u.jsx(ou,{className:"h-4 w-4 flex-shrink-0"}),u.jsx("span",{className:"truncate",children:R.name}),u.jsx(Mt,{variant:"secondary",className:"flex-shrink-0 text-xs",children:R.type})]})},R.id))})]})]}),(e==null?void 0:e.connectionId)&&u.jsxs(u.Fragment,{children:[e.connectionType==="upload"&&u.jsx(SZe,{}),e.connectionType==="url"&&u.jsx(CZe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&u.jsxs(u.Fragment,{children:[u.jsx(wZe,{}),u.jsx("div",{className:"space-y-4",children:u.jsx("div",{className:"space-y-2",children:u.jsxs(fi,{defaultValue:"tables",value:d,onValueChange:R=>f(R),className:"w-full",children:[u.jsxs(Ds,{className:"grid w-full grid-cols-2",children:[u.jsx(Fn,{value:"tables",children:"Tables & Views"}),u.jsx(Fn,{value:"datamodels",children:"Data Models"})]}),u.jsxs(xr,{value:"tables",className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search tables and views...",value:i,onChange:R=>a(R.target.value),className:"h-8 text-sm",disabled:g}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?u.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):y?u.jsx(Iv,{title:"Error loading tables",message:y.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):C.length===0?u.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):C.map(R=>{const D=n.some(M=>M.name===R.name&&M.type==="table");return u.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(R),children:[u.jsx(hn,{id:`table-${R.name}`,checked:D,onCheckedChange:()=>S(R),onClick:M=>M.stopPropagation(),disabled:g}),u.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[R.name,R.dbObjectType==="view"&&u.jsx(Mt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"})]})]},R.name)})})]}),u.jsxs(xr,{value:"datamodels",className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search data models...",value:l,onChange:R=>c(R.target.value),className:"h-8 text-sm",disabled:x}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:x?u.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?u.jsx(Iv,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?u.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(R=>{const D=n.some(M=>M.name===R.name&&M.type==="model");return u.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>E(R),children:[u.jsx(hn,{id:`dataModel-${R.name}`,checked:D,onCheckedChange:()=>E(R),onClick:M=>M.stopPropagation(),disabled:x}),u.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[u.jsx(de,{className:"cursor-pointer",children:R.name}),u.jsx("span",{className:"text-xs text-muted-foreground",children:R.description})]})]},R.name)})})]})]})})})]})]})]})}function kZe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:o=[],isRestricted:s=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,c]=N.useState(""),d=N.useCallback(E=>{const C={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:E};t({...C})},[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}=FQ(),m=s?f.filter(E=>o.includes(E.id)):f,{datasets:g,isPending:y,error:b}=yZe(e==null?void 0:e.semanticDomainId),x=E=>{const C=r||[],_=C.some(R=>R.id===E.id&&R.type==="dataset");let j;if(_)j=C.filter(R=>!(R.id===E.id&&R.type==="dataset"));else{const R={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};j=[...C,R]}n==null||n(j)},v=g.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const E=r||[],_=v.filter(R=>!E.some(D=>D.id===R.id&&D.type==="dataset")).map(R=>({id:R.id,datasetType:R.type,name:R.name||R.table,label:R.label,domainId:R.domainId,description:R.description,database:R.database,schema:R.schema,type:"dataset",connectionId:R.connectionId,connectionType:R.connectionType,dialect:R.dialect,datamodelId:R.datamodelId,sql:R.sql})),j=[...E,..._];n(j)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),u.jsxs(Dt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||s&&!!i,children:[u.jsx(jt,{className:"w-full",children:u.jsx($t,{placeholder:h?"Loading semantic domains...":s&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(E=>E.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),u.jsx(Rt,{children:m.map(E=>u.jsx(Se,{className:"hover:bg-muted",value:E.id,children:u.jsxs("div",{className:"flex flex-col items-start",children:[u.jsx("span",{className:"font-medium",children:E.label}),u.jsx("span",{className:"text-xs",children:E.description})]})},E.id))})]}),p&&u.jsx(Iv,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(Nr,{placeholder:"Search datasets...",value:l,onChange:E=>c(E.target.value),className:"h-8 text-sm",disabled:y}),u.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?u.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):b?u.jsx(Iv,{title:"Error loading datasets",message:b.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?u.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(E=>{const C=r.some(_=>_.id===E.id&&_.type==="dataset");return u.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>x(E),children:[u.jsx(hn,{id:`dataset-${E.id}`,checked:C,onCheckedChange:()=>x(E),onClick:_=>_.stopPropagation(),disabled:y}),u.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[u.jsx(de,{className:"cursor-pointer font-medium",children:E.label||E.name}),u.jsx("span",{className:"text-xs text-gray-500",children:E.description})]})]},E.label||E.name)})})]})]})]})}function lD({open:e,onOpenChange:t,dataSource:n,fallbackDataSource:r,dialogMode:o,incomingSelectedEntities:s}){const{tokenProps:i}=qe(),{allowedSemanticDomains:a}=i,[l,c]=N.useState([]),{updateDataSource:d}=ko(),f=ee(M=>M.isVisualEditing),h=ee(M=>M.dashboard.aiContext),{setAiContext:p}=nn(),m=N.useRef(null),[g,y]=N.useState(!1);FQ();const b=a&&a.length>0,x=!b,v=b&&a.length===1?a[0]:void 0,w=N.useCallback(M=>{d({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:M,selectedEntities:(n==null?void 0:n.selectedEntities)||[]})},[n,d]),S=N.useCallback(M=>{d({...n,...M})},[n,d]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&w("semanticDomain")},[b,n.mode,w]),N.useEffect(()=>{v&&!n.semanticDomainId&&S({semanticDomainId:v})},[v,n.semanticDomainId,S]),N.useEffect(()=>{e?c(s||[]):(m.current=null,y(!1))},[e,n==null?void 0:n.selectedEntities,o,d,s,n]);const E=M=>{const I=l.filter(O=>!(O.name===M.name&&O.type===M.type));c(I)},C=()=>{c([]),o==="aiContext"&&(p({...h,selectedEntities:[]}),t(!1)),o==="dataSource"&&(d({...r,...n,selectedEntities:[]}),t(!1))},_=N.useCallback(M=>{c(M)},[]),j=N.useCallback(()=>{m.current&&m.current()},[]),R=N.useCallback(M=>{m.current=M,y(!0)},[]);function D(){var M,I;if(o==="aiContext")f&&d(n),p({...h,selectedEntities:l}),t(!1);else if(o==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=l==null?void 0:l[0])==null?void 0:M.connectionId,A=(I=l==null?void 0:l[0])==null?void 0:I.connectionType;d({...n,connectionId:O,connectionType:A,selectedEntities:l})}else d({...n,selectedEntities:l});t(!1)}}return u.jsx(Ms,{open:e,onOpenChange:t,children:u.jsx(es,{className:"flex max-w-2xl flex-col",children:u.jsxs("div",{children:[u.jsxs(ts,{className:"flex-shrink-0",children:[u.jsx(ns,{children:o==="aiContext"?"Data Context":"Select Data Source"}),u.jsx(ui,{children:o==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),u.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:u.jsxs("div",{className:"space-y-4",children:[x&&u.jsx("div",{className:"space-y-2",children:u.jsx(fi,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:w,className:"w-full",children:u.jsxs(Ds,{className:"grid w-full grid-cols-2",children:[u.jsx(Fn,{value:"database",children:"Direct Source"}),u.jsx(Fn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&u.jsx(kZe,{dataSource:n,onDataSourceUpdate:S,selectedEntities:l,onSelectionChange:_,allowedDomainIds:a||[],isRestricted:b,autoSelectedDomainId:v,onRegisterSelectAll:R}),(n==null?void 0:n.mode)==="database"&&x&&u.jsx(NZe,{dataSource:n,onDataSourceUpdate:S,selectedEntities:l,onSelectionChange:_,onRegisterSelectAll:R})]})}),u.jsx(bZe,{selectedEntities:l,onDeselectEntity:E}),u.jsx(Ps,{className:"flex-shrink-0",children:u.jsx("div",{className:"flex w-full justify-between",children:u.jsxs("div",{className:"flex grow justify-end gap-2",children:[u.jsx(le,{variant:"outline",onClick:j,disabled:!g,children:"Select All"}),u.jsx(le,{variant:"outline",onClick:C,disabled:l.length===0,children:"Clear All"}),u.jsx(le,{variant:"outline",onClick:()=>t(!1),children:"Close"}),u.jsx(le,{onClick:D,disabled:l.length===0,children:"Add"})]})})})]})})})}function _Ze({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const o=N.useRef(null),s=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const c=Ca-n;if(l.length>c){Ue.error(`You can only attach ${Ca} files per message. You have ${c} slot(s) remaining.`);return}const{valid:d,errors:f}=gX(l);if(f.forEach(({file:h,error:p})=>{Ue.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>VP(p)));e(h)}catch(h){console.error("Failed to process files:",h),Ue.error("Failed to process one or more files")}o.current&&(o.current.value="")},i=()=>{var a;(a=o.current)==null||a.click()};return u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:o,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:s,className:"hidden",disabled:t||n>=Ca}),u.jsx(le,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ca,title:n>=Ca?`Maximum ${Ca} files allowed`:"Attach files",children:u.jsx(T_,{className:"h-4 w-4 text-muted-foreground"})})]})}function jZe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:o}){const[s,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)},[]),c=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=Ca-r;if(h.length>p){Ue.error(`You can only attach ${Ca} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=gX(h);if(g.forEach(({file:y,error:b})=>{Ue.error(`${y.name}: ${b}`)}),m.length>0)try{const y=await Promise.all(m.map(b=>VP(b)));t(y),Ue.success(`${y.length} file(s) attached successfully`)}catch(y){console.error("Failed to process files:",y),Ue.error("Failed to process one or more files")}},[n,r,t]);return u.jsxs("div",{className:Z("relative",o),onDragEnter:a,onDragLeave:l,onDragOver:c,onDrop:d,children:[e,s&&!n&&u.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:u.jsxs("div",{className:"flex flex-col items-center gap-2",children:[u.jsx(Jv,{className:"h-8 w-8 text-primary"}),u.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),u.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ca-r," slot(s) available"]})]})})]})}const cD=k.forwardRef(({className:e,...t},n)=>u.jsx(Ww,{className:Z("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(h7,{className:Z("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));cD.displayName=Ww.displayName;function LQ(e,[t,n]){return Math.min(n,Math.max(t,e))}function Kd(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function P$(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function RZe(...e){return t=>{let n=!1;const r=e.map(o=>{const s=P$(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():P$(e[o],null)}}}}function nc(...e){return k.useCallback(RZe(...e),e)}function zQ(e,t=[]){let n=[];function r(s,i){const a=k.createContext(i),l=n.length;n=[...n,i];const c=f=>{var b;const{scope:h,children:p,...m}=f,g=((b=h==null?void 0:h[e])==null?void 0:b[l])||a,y=k.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=k.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>k.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return k.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,MZe(o,...t)]}function MZe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var BQ=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},PZe=k[" useInsertionEffect ".trim().toString()]||BQ;function DZe({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=TZe({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=k.useRef(e!==void 0);k.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=k.useCallback(d=>{var f;if(a){const h=AZe(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function TZe({defaultProp:e,onChange:t}){const[n,r]=k.useState(e),o=k.useRef(n),s=k.useRef(t);return PZe(()=>{s.current=t},[t]),k.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function AZe(e){return typeof e=="function"}var IZe=k.createContext(void 0);function OZe(e){const t=k.useContext(IZe);return e||t||"ltr"}function FZe(e){const t=k.useRef({value:e,previous:e});return k.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function $Ze(e){const[t,n]=k.useState(void 0);return BQ(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var LZe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Bb=LZe.reduce((e,t)=>{const n=ei(`Primitive.${t}`),r=k.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function zZe(e){const t=e+"CollectionProvider",[n,r]=zQ(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:b}=g,x=N.useRef(null),v=N.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:v,collectionRef:x,children:b})};i.displayName=t;const a=e+"CollectionSlot",l=ei(a),c=N.forwardRef((g,y)=>{const{scope:b,children:x}=g,v=s(a,b),w=nc(y,v.collectionRef);return u.jsx(l,{ref:w,children:x})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=ei(d),p=N.forwardRef((g,y)=>{const{scope:b,children:x,...v}=g,w=N.useRef(null),S=nc(y,w),E=s(d,b);return N.useEffect(()=>(E.itemMap.set(w,{ref:w,...v}),()=>void E.itemMap.delete(w))),u.jsx(h,{[f]:"",ref:S,children:x})});p.displayName=d;function m(g){const y=s(e+"CollectionConsumer",g);return N.useCallback(()=>{const x=y.collectionRef.current;if(!x)return[];const v=Array.from(x.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((E,C)=>v.indexOf(E.ref.current)-v.indexOf(C.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var VQ=["PageUp","PageDown"],HQ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],UQ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Vh="Slider",[e_,BZe,VZe]=zZe(Vh),[WQ,UQe]=zQ(Vh,[VZe]),[HZe,tS]=WQ(Vh),qQ=k.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:m,...g}=e,y=k.useRef(new Set),b=k.useRef(0),v=i==="horizontal"?UZe:WZe,[w=[],S]=DZe({prop:d,defaultProp:c,onChange:D=>{var I;(I=[...y.current][b.current])==null||I.focus(),f(D)}}),E=k.useRef(w);function C(D){const M=KZe(w,D);R(D,M)}function _(D){R(D,b.current)}function j(){const D=E.current[b.current];w[b.current]!==D&&h(w)}function R(D,M,{commit:I}={commit:!1}){const O=eKe(s),A=tKe(Math.round((D-r)/s)*s+r,O),F=LQ(A,[r,o]);S((V=[])=>{const H=YZe(V,F,M);if(JZe(H,l*s)){b.current=H.indexOf(F);const $=String(H)!==String(V);return $&&I&&h(H),$?H:V}else return V})}return u.jsx(HZe,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:b,thumbs:y.current,values:w,orientation:i,form:m,children:u.jsx(e_.Provider,{scope:e.__scopeSlider,children:u.jsx(e_.Slot,{scope:e.__scopeSlider,children:u.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Kd(g.onPointerDown,()=>{a||(E.current=w)}),min:r,max:o,inverted:p,onSlideStart:a?void 0:C,onSlideMove:a?void 0:_,onSlideEnd:a?void 0:j,onHomeKeyDown:()=>!a&&R(r,0,{commit:!0}),onEndKeyDown:()=>!a&&R(o,w.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:M})=>{if(!a){const A=VQ.includes(D.key)||D.shiftKey&&HQ.includes(D.key)?10:1,F=b.current,V=w[F],H=s*A*M;R(V+H,F,{commit:!0})}}})})})})});qQ.displayName=Vh;var[GQ,YQ]=WQ(Vh,{startEdge:"left",endEdge:"right",size:"width",direction:1}),UZe=k.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...d}=e,[f,h]=k.useState(null),p=nc(t,v=>h(v)),m=k.useRef(void 0),g=OZe(o),y=g==="ltr",b=y&&!s||!y&&s;function x(v){const w=m.current||f.getBoundingClientRect(),S=[0,w.width],C=uD(S,b?[n,r]:[r,n]);return m.current=w,C(v-w.left)}return u.jsx(GQ,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:u.jsx(ZQ,{dir:g,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const w=x(v.clientX);i==null||i(w)},onSlideMove:v=>{const w=x(v.clientX);a==null||a(w)},onSlideEnd:()=>{m.current=void 0,l==null||l()},onStepKeyDown:v=>{const S=UQ[b?"from-left":"from-right"].includes(v.key);c==null||c({event:v,direction:S?-1:1})}})})}),WZe=k.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=e,d=k.useRef(null),f=nc(t,d),h=k.useRef(void 0),p=!o;function m(g){const y=h.current||d.current.getBoundingClientRect(),b=[0,y.height],v=uD(b,p?[r,n]:[n,r]);return h.current=y,v(g-y.top)}return u.jsx(GQ,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:u.jsx(ZQ,{"data-orientation":"vertical",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const y=m(g.clientY);s==null||s(y)},onSlideMove:g=>{const y=m(g.clientY);i==null||i(y)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=UQ[p?"from-bottom":"from-top"].includes(g.key);l==null||l({event:g,direction:b?-1:1})}})})}),ZQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=e,d=tS(Vh,n);return u.jsx(Bb.span,{...c,ref:t,onKeyDown:Kd(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):VQ.concat(HQ).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:Kd(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Kd(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:Kd(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),KQ="SliderTrack",XQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=tS(KQ,n);return u.jsx(Bb.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});XQ.displayName=KQ;var t_="SliderRange",QQ=k.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=tS(t_,n),s=YQ(t_,n),i=k.useRef(null),a=nc(t,i),l=o.values.length,c=o.values.map(h=>tJ(h,o.min,o.max)),d=l>1?Math.min(...c):0,f=100-Math.max(...c);return u.jsx(Bb.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});QQ.displayName=t_;var n_="SliderThumb",JQ=k.forwardRef((e,t)=>{const n=BZe(e.__scopeSlider),[r,o]=k.useState(null),s=nc(t,a=>o(a)),i=k.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return u.jsx(qZe,{...e,ref:s,index:i})}),qZe=k.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=tS(n_,n),a=YQ(n_,n),[l,c]=k.useState(null),d=nc(t,x=>c(x)),f=l?i.form||!!l.closest("form"):!0,h=$Ze(l),p=i.values[r],m=p===void 0?0:tJ(p,i.min,i.max),g=ZZe(r,i.values.length),y=h==null?void 0:h[a.size],b=y?XZe(y,m,a.direction):0;return k.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),u.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${m}% + ${b}px)`},children:[u.jsx(e_.ItemSlot,{scope:e.__scopeSlider,children:u.jsx(Bb.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:Kd(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&u.jsx(eJ,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});JQ.displayName=n_;var GZe="RadioBubbleInput",eJ=k.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=k.useRef(null),s=nc(o,r),i=FZe(t);return k.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Bb.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});eJ.displayName=GZe;function YZe(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function tJ(e,t,n){const s=100/(n-t)*(e-t);return LQ(s,[0,100])}function ZZe(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function KZe(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function XZe(e,t,n){const r=e/2,s=uD([0,50],[0,r]);return(r-s(t)*n)*n}function QZe(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function JZe(e,t){if(t>0){const n=QZe(e);return Math.min(...n)>=t}return!0}function uD(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function eKe(e){return(String(e).split(".")[1]||"").length}function tKe(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var nJ=qQ,nKe=XQ,rKe=QQ,oKe=JQ;const rJ=k.forwardRef(({className:e,...t},n)=>u.jsxs(nJ,{ref:n,className:Z("relative flex w-full touch-none select-none items-center",e),...t,children:[u.jsx(nKe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:u.jsx(rKe,{className:"absolute h-full bg-primary"})}),u.jsx(oKe,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));rJ.displayName=nJ.displayName;const pp=["low","medium","high"],D$={low:"Low",medium:"Medium",high:"High"},sKe={low:"bg-green-100 text-green-700 dark:bg-green-950 dark:text-green-300",medium:"bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",high:"bg-orange-100 text-orange-700 dark:bg-orange-950 dark:text-orange-300"};function iKe({value:e,onValueChange:t}){const n=l=>pp.indexOf(l),r=l=>pp[l],[o,s]=N.useState([n(e)]);N.useEffect(()=>{const l=pp.indexOf(e);s([l])},[e]);const i=l=>{s(l),t(r(l[0]))},a=pp[o[0]];return u.jsxs("div",{className:"w-full space-y-3",children:[u.jsxs("div",{className:"flex justify-between items-center",children:[u.jsx("span",{className:"text-sm font-medium",children:"Reasoning Effort"}),u.jsx("span",{className:`text-xs px-2 py-0.5 rounded-md font-medium ${sKe[a]}`,children:D$[a]})]}),u.jsx(rJ,{className:"[&_[role=slider]]:focus:outline-none [&_[role=slider]]:focus:ring-0 [&_[role=slider]]:focus:ring-offset-0 [&_[role=slider]]:focus-visible:outline-none [&_[role=slider]]:focus-visible:ring-0 [&_[role=slider]]:focus-visible:ring-offset-0",value:o,min:0,max:2,step:1,onValueChange:i}),u.jsx("div",{className:"flex justify-between text-xs text-muted-foreground px-1",children:pp.map(l=>u.jsx("span",{children:D$[l]},l))})]})}const dD=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:o,stop:s,onFocus:i,status:a,assistantType:l},c)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),y=N.useRef(null),b=$g(),x=Uie(),v=Hie(),{setCurrentAIContext:w,updateSelectedEntities:S,setReasoningEffort:E,setShowReasoning:C}=ow(),{queueMessage:_}=gh(),{addFileAttachment:j,removeFileAttachment:R,clearFileAttachments:D,getFileAttachments:M}=Y_(),I=G_(l),O=Ae(U=>U.card.dataSource),A=ee(U=>{var G;return(G=U.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{c&&"current"in c&&(c.current=y.current)},[c]);const F=N.useCallback(()=>{const U=y.current;if(U){if(!e||e.length===0){U.style.height="10px";return}U.style.height="auto";const G=Math.min(Math.max(U.scrollHeight,10),200);U.style.height=`${G}px`}},[e]);N.useEffect(()=>{F()},[F]),N.useEffect(()=>{const U=setTimeout(()=>{F()},0);return()=>clearTimeout(U)},[F]);const V=()=>{const U=e.trim();!U&&I.length===0||(a!=="ready"?(_(l,U,I),t(""),D(l)):r({preventDefault:()=>{}}))},H=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),V()),U.key==="@"&&f(!0)},$=N.useCallback(U=>{const G=OVe(U.nativeEvent);G.length>0&&(U.preventDefault(),G.forEach(async X=>{const re=await VP(X);j(l,re)}))},[j,l]),T=N.useCallback(U=>{U.forEach(G=>{j(l,G)})},[j,l]),z=N.useCallback(U=>{U.forEach(G=>{j(l,G)})},[j,l]),L=N.useCallback(U=>{R(l,U)},[R,l]),P=U=>{if(b.selectedEntities.some(X=>X.id&&X.id===U.id||X.name===U.name)){const X=b.selectedEntities.filter(re=>!(re.id&&re.id===U.id||re.name===U.name));w({selectedEntities:X})}else{const X=[...b.selectedEntities,U];w({selectedEntities:X})}},B=U=>{P(U)},W=U=>{var re;if(!b.selectedEntities.some(J=>J.id&&J.id===U.id||J.name===U.name)){const J=[...b.selectedEntities,U];w({selectedEntities:J})}const X="label"in U?U.label:U.name;t(e+`@${X} `),f(!1),(re=y.current)==null||re.focus()},Y=U=>{const G=b.selectedEntities.filter(J=>!(J.id&&J.id===U.id||J.name===U.name));w({selectedEntities:G});const re=`@${"label"in U?U.label:U.name}`;e.includes(re)&&t(e.replace(re,"").trim())},q=U=>{const G=new Set(U.map(J=>J.id||J.name)),X=b.selectedEntities.filter(J=>!G.has(J.id||J.name));w({selectedEntities:X});let re=e;U.forEach(J=>{const te=`@${"label"in J?J.label:J.name}`;re=re.replace(te,"").trim()}),t(re)};return u.jsxs(jZe,{onFilesDropped:T,currentFileCount:I.length,disabled:o,className:"space-y-4",children:[u.jsx(mZe,{entities:b.selectedEntities,availableEntities:A||[],onRemoveEntity:Y,onRemoveEntities:q}),I.length>0&&u.jsx(FVe,{files:I,onRemove:L,showRemove:!o,className:"mb-2"}),u.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[u.jsx("textarea",{ref:y,value:e,onChange:n,onKeyDown:H,onPaste:$,onFocus:()=>{F(),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"}}),u.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs(bs,{open:d,onOpenChange:f,children:[u.jsx(ys,{asChild:!0,children:u.jsx(le,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:u.jsx(ore,{className:"h-4 w-4 text-muted-foreground"})})}),u.jsx(xs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:U=>U.preventDefault(),children:u.jsx(hZe,{isOpen:!0,onSelect:P,onDeselect:B,onClose:()=>{var U;f(!1),(U=y.current)==null||U.focus()},availableEntities:A||[],selectedEntities:b.selectedEntities,onTabComplete:W,onSelectAll:()=>{A&&w({selectedEntities:A})},onRemoveAll:()=>{w({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),u.jsx(_Ze,{onFilesSelected:z,disabled:o,currentFileCount:I.length}),u.jsxs(bs,{open:m,onOpenChange:g,children:[u.jsx(ys,{asChild:!0,children:u.jsx(le,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Reasoning settings",children:u.jsx(sx,{className:"h-4 w-4 text-muted-foreground"})})}),u.jsx(xs,{className:"w-72",align:"start",side:"top",sideOffset:8,children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(iKe,{value:v,onValueChange:U=>{E(U)}}),u.jsxs("div",{className:"flex items-center space-x-2",children:[u.jsx(cD,{id:"show-reasoning",checked:x,onCheckedChange:C}),u.jsx(de,{htmlFor:"show-reasoning",className:"font-normal",children:"Show reasoning"})]})]})})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[o&&u.jsx(le,{className:"rounded-full",size:"sm",onClick:s,children:u.jsx(bre,{className:"size-3.5 bg-background"})}),!o&&u.jsx(le,{disabled:!e.trim()&&I.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:V,title:a!=="ready"?"Message will be queued":void 0,children:u.jsx(_L,{className:"size-4"})})]})]})]}),u.jsx(lD,{incomingSelectedEntities:b.selectedEntities,open:h,onOpenChange:p,dataSource:O||uh,fallbackDataSource:uh,dialogMode:"aiContext"})]})});dD.displayName="ChatInputWithContext";function oJ({assistantType:e,className:t}){const n=T6(e),{removeFromQueue:r}=gh();return n.length===0?null:u.jsxs("div",{className:Z("space-y-2",t),children:[u.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[u.jsx(Ga,{className:"h-3 w-3"}),u.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),u.jsx("div",{className:"space-y-2",children:n.map(o=>u.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:u.jsxs("div",{className:"flex items-start justify-between gap-2",children:[u.jsx("div",{className:"flex-1 space-y-1",children:u.jsx("p",{className:"break-words text-foreground/70",children:o.text})}),u.jsx(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,o.id),title:"Remove from queue",children:u.jsx(Mn,{className:"h-3 w-3"})})]})},o.id))})]})}function sJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const o=T6(e),{dequeueMessage:s}=gh();N.useEffect(()=>{if(t!=="ready"||n||!(o&&o.length>0))return;const a=s(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,o,s,r,e])}function iJ(e,t={}){const{threshold:n=50,delay:r=0,dependencies:o=[],forceScrollOnStream:s=!0}=t,i=N.useRef(null),[a,l]=N.useState(!0),[c,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(),y=N.useRef(e.length),b=N.useRef(!1),x=N.useRef(!1),v=N.useRef(0),w=N.useRef(0),S=N.useRef(),E=N.useCallback(()=>{const R=i.current;if(!R)return!0;const{scrollTop:D,scrollHeight:M,clientHeight:I}=R;return M-D-I<=n},[n]),C=N.useCallback((R={})=>{const D=i.current;if(!D)return;const{force:M=!1,instant:I=!1}=R;if(!a&&!M)return;const A=Date.now()-w.current;if(!M&&!I&&A<10)return;g.current&&clearTimeout(g.current),S.current&&clearTimeout(S.current);const F=()=>{x.current=!0,w.current=Date.now(),requestAnimationFrame(()=>{D&&(D.scrollTop=D.scrollHeight,d(!0),h(!1),m(0),setTimeout(()=>{x.current=!1},20))})};!I&&r>0?S.current=setTimeout(F,r):F()},[a,r]),_=N.useCallback(()=>{const R=i.current;if(!R||x.current)return;const D=R.scrollTop,M=Math.abs(D-v.current);v.current=D,M>5&&(b.current=!0);const I=E();d(I),I?(l(!0),h(!1),m(0),b.current=!1):b.current&&l(!1),b.current&&setTimeout(()=>{b.current=!1},200)},[E]),j=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{let R=!1;if(s&&e.length>0){const I=e[e.length-1];(I==null?void 0:I.role)==="assistant"&&(R=!0,b.current=!1)}if((a||R)&&!b.current){const I=e.length>50&&!R;C({instant:I})}const D=e.length!==y.current,M=e.length>y.current;D&&(y.current=e.length,!a&&!R&&M&&(h(!0),m(I=>I+1)))},5),()=>{S.current&&clearTimeout(S.current)}),[e,o,C,a,s]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>()=>{g.current&&clearTimeout(g.current),S.current&&clearTimeout(S.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:c,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:_,resetNewMessageCount:j}}function aJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:o=10}=t,[s,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=s)return e;const h=Math.max(0,e.length-s);return e.slice(h)},[e,s]),l=e.length>s,c=s>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+o,n))},[o,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{c&&e.length>s&&s<n&&i(Math.min(e.length,n))},[e.length,s,c,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:c}}function lJ(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 o=r,s=o.state;return{hasActiveTools:!0,activeToolText:bX(o.type,s),toolType:o.type}}}return{hasActiveTools:!1}}const aKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function lKe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=N.useState(!1),[a,l]=N.useState(Sm),[c,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:y,isConsoleMode:b}=L1(),x=N.useRef(null);ee(fe=>fe.dashboard.aiScopeTables);const v=ee(fe=>fe.isDashboardEditing),w=ee(fe=>fe.selectedSheetId),{setDataSource:S}=ko(),{addFrame:E,setSelectedFrameId:C,setIsDashboardEditing:_}=nn(),j=$g(),{setCurrentAIContext:R,updateSelectedEntities:D,setReasoningEffort:M,setShowReasoning:I}=ow(),{clearQueue:O}=gh(),{clearFileAttachments:A,getFileAttachments:F}=Y_(),V=G_("dashboard"),H=ee(fe=>fe.dashboard.aiContext),$=Ae(fe=>fe.card.dataSource),{assistantProfile:T}=AQ(),z=ee(fe=>fe.handleOpenAssistantProfile),{sendMessage:L,isLoading:P,messages:B,setMessages:W,status:Y,stop:q,errorMessage:U,clearError:G}=dZe(),X=N.useCallback(fe=>{r==null||r(fe),n===void 0&&m(fe)},[n,r]),re=N.useCallback(()=>{X(!g)},[g,X]);N.useEffect(()=>{if(!g)return;function fe(we){we.key==="Escape"&&X(!1)}return window.addEventListener("keydown",fe),()=>{window.removeEventListener("keydown",fe)}},[g,X]);const[J,ce]=N.useState(""),te=fe=>{ce(fe.target.value)};function se({sql:fe,data:we,cardTitle:Re,connectionId:Oe,cardType:Ie,python:$e,cardConfig:Ye,dataSource:et}){if(console.log("handleAddNewFrame",{sql:fe,data:we,cardTitle:Re,connectionId:Oe,cardType:Ie,python:$e,cardConfig:Ye,dataSource:et}),!w)return;const Ot={id:br(),title:Re||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ie==="horizontalBar"?"y":"x"}},type:Ie,sql:fe,python:$e,dataSource:et,config:Ye,connectionId:Oe},vt={id:br(),cards:[Ot],activeCardId:Ot.id};_(!0),E(w,vt,"end"),C(vt.id)}const oe=fe=>{fe.preventDefault();const we=J.trim();if(!we&&V.length===0)return;const Re=[];we&&Re.push({type:"text",text:we}),V.forEach(Oe=>{Oe.data&&Re.push({type:"file",mediaType:Oe.type,filename:Oe.name,url:`data:${Oe.type};base64,${Oe.data}`})}),L({role:"user",parts:Re}),ce(""),A("dashboard"),ge({force:!0})};N.useEffect(()=>{var fe;e&&((fe=x.current)==null||fe.focus())},[e]),sJ({assistantType:"dashboard",status:Y,isLoading:P,sendMessage:L});const{hasActiveTools:ke}=lJ(B),{visibleMessages:ue,hasMoreMessages:be,totalMessageCount:De,loadMoreMessages:it,resetMessageWindow:Ve}=aJ(B,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:We,isAtBottom:xn,hasNewMessages:zn,newMessageCount:ie,scrollToBottom:ge,handleScroll:Me,resetNewMessageCount:Be}=iJ(ue,{threshold:50,delay:0,dependencies:[Y,B.length]});function Ze(fe){ye();const we={role:"user",parts:[{type:"text",text:fe.title+" "+fe.subtitle}]};L(we)}function Et(fe){ye(),L({role:"user",parts:[{type:"text",text:fe}]})}function on(fe){ye(),L({role:"user",parts:[{type:"text",text:fe}]}),ge({force:!0})}const qt=N.useCallback(async()=>{const fe=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(fe),Ue.success("Conversation copied")}catch(we){console.error("Failed to copy conversation",we),Ue.error("Unable to copy conversation")}},[B]);function Qt(){var Re;const fe=(Re=H==null?void 0:H.selectedEntities)==null?void 0:Re[0],we={connectionId:(fe==null?void 0:fe.connectionId)||"",connectionType:(fe==null?void 0:fe.connectionType)||"",mode:(fe==null?void 0:fe.type)==="dataset"?"semanticDomain":"database",dbSelection:{database:(fe==null?void 0:fe.database)||"",schema:(fe==null?void 0:fe.schema)||"",entityType:(fe==null?void 0:fe.type)||"table"},selectedEntities:(H==null?void 0:H.selectedEntities)||[]};S(we),h(!0)}function ye(){j.selectedEntities.length===0&&R({selectedEntities:(H==null?void 0:H.selectedEntities)||[]})}const bt=(J==null?void 0:J.length)===0&&(B==null?void 0:B.filter(fe=>fe.role==="user").length)===0;function Bn(){return u.jsx("div",{"data-role":"header",children:u.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function ve(){return u.jsxs(mb,{children:[u.jsx(gb,{asChild:!0,children:u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:u.jsx(Zv,{className:"size-3.5"})})}),u.jsxs(Mh,{align:"end",children:[u.jsx(hf,{children:"Options"}),u.jsx(bb,{}),u.jsx(um,{checked:s,onCheckedChange:i,children:"Token Usage"}),u.jsx(um,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),u.jsx(um,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}const xe=u.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[u.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Bn(),z&&u.jsx(le,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:z,children:(T==null?void 0:T.name)||"Default Profile"}),u.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[b&&ve(),a&&u.jsx(le,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:qt,children:"Copy Conversation"}),y&&u.jsx(Lu,{text:JSON.stringify(B,null,2),className:"h-7 p-2"}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:re,children:g?u.jsx(wL,{className:"size-4"}):u.jsx(P_,{className:"size-4"})}),(v||Sm)&&u.jsx(Lc,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Qt,children:u.jsx(Pi,{className:"size-4"})}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),G(),Ve()},children:u.jsx(jL,{className:"size-4"})}),u.jsx(Lc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:u.jsx(Mn,{className:"size-4"})})]})]}),u.jsxs(nd,{"data-role":"dashboard-assistant-scroll-area",ref:We,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:Me,children:[u.jsxs("div",{className:"space-y-3 pb-4",children:[be&&u.jsx("div",{className:"flex justify-center py-2",children:u.jsxs(le,{variant:"outline",size:"sm",onClick:it,className:"text-xs",children:["Load ",Math.min(5,De-ue.length)," ","more messages (",De-ue.length," ","hidden)"]})}),u.jsx(CX,{showTools:a,showSystemMessage:c,messages:ue,onAddToDashboard:se,onQuickReply:on,disableQuickReplies:P}),!ke&&u.jsx(SX,{status:Y,errorMessage:U})]}),u.jsx(Qa,{orientation:"horizontal"})]}),!xn&&u.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:u.jsxs(le,{onClick:()=>{ge({force:!0}),Be()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[u.jsx(Co,{className:"h-4 w-4"}),zn&&ie>0&&u.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:ie>9?"9+":ie})]})}),u.jsxs("div",{className:"space-y-3",children:[!T&&bt&&u.jsx(EX,{onClick:Ze,placeholders:aKe}),u.jsx("div",{children:bt&&T&&u.jsx(IQ,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:Et})}),u.jsx(oJ,{assistantType:"dashboard",className:"mb-3"}),u.jsx(dD,{ref:x,setInput:ce,stop:q,input:J,handleInputChange:te,handleSubmit:fe=>{ye(),oe(fe),ge({force:!0})},isLoading:P,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),u.jsx(lD,{incomingSelectedEntities:(H==null?void 0:H.selectedEntities)||[],open:f,onOpenChange:h,dataSource:$||uh,fallbackDataSource:uh,dialogMode:"aiContext"})]});return g&&o?En.createPortal(u.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:u.jsx("div",{className:"flex h-full w-full",children:xe})}),o):xe}function cKe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:o}=nn(),s=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),l=ee(d=>d.isDashboardEditing),c=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||c)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Ue.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&&m.id){m.id=br();const g=m.activeCardId;m.cards.forEach(y=>{const b=y.id;y.id=br(),b===g&&(m.activeCardId=y.id,y.title=`${y.title} (Copy)`)}),r(a,m),o(m.id)}}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,o,a,l,c,t])}function cJ(){var T;const{showAssistant:e}=qe(),{preferences:t}=L1(),n=((T=t==null?void 0:t.cardDisplay)==null?void 0:T.mode)==="print",r=N.useRef(null),o=N.useRef(null),[s,i]=N.useState(!1),a=su(z=>z.setFullscreen),l=su(z=>z.setPanelOpen),c=su(z=>z.setContainer),d=_6("dashboard"),f=j6(),h=R6("dashboard"),p=d.isOpen,m=f==="dashboard",g=ee(z=>z.isVisualEditing),y=ee(z=>z.themeStyle),b=ee(z=>{var L;return(L=z.dashboard)==null?void 0:L.sheets}),x=ee(z=>z.isDashboardEditing),v=ee(z=>z.selectedSheetId),{setSelectedSheetId:w,setSheetTitle:S,addSheet:E,setSheets:C}=nn();cKe(o);const{setActiveAssistantType:_}=ow();N.useEffect(()=>{p?_("dashboard"):f==="dashboard"&&a(null)},[p,_,f,a]);function j(z){var L,P;z?((L=r.current)==null||L.resize(40),l("dashboard",!0),_("dashboard")):(l("dashboard",!1),a(null),(P=r.current)==null||P.resize(0),_(null))}function R(){const z={id:br(),title:"New Sheet"};E(z),w(z.id)}function D(z){z<1?(l("dashboard",!1),a(null),_(null)):(p||l("dashboard",!0),_("dashboard"))}function M(){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 I=(z,L)=>{z.dataTransfer.setData("tabIndex",L.toString())},O=z=>{z.preventDefault()},A=(z,L)=>{const P=z.dataTransfer.getData("tabIndex");if(P===L.toString())return;const B=Array.from(b||[]),[W]=B.splice(parseInt(P),1);B.splice(L,0,W),C(B)};function F(){var z,L;if(b&&b.length>1||x)return u.jsxs(Ds,{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:[b==null?void 0:b.map((P,B)=>u.jsxs(Fn,{draggable:!0,onDragStart:W=>I(W,B),onDragOver:O,onDrop:W=>A(W,B),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>w(P.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:P.id,children:[u.jsx(lg,{enabled:x&&P.id===v,text:P.title,onSave:W=>S(P.id,W),children:P.title},P.id),x&&v===P.id&&b.length>1&&u.jsx(Mn,{className:"ml-1 size-3",onClick:()=>i(!0)})]},P.id)),x&&u.jsx("div",{style:{borderRadius:(L=(z=y==null?void 0:y.chart)==null?void 0:z.options)==null?void 0:L.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:R,children:u.jsx(ks,{className:"size-3"})})]})}function V(){return u.jsx("div",{ref:o,style:{},className:"grow",children:b==null?void 0:b.map(z=>u.jsx(xr,{style:{backgroundColor:M()},className:Z("mt-0",{}),value:z.id,children:u.jsx(J$e,{sheet:z})},z.id))})}function H(){var z;return u.jsxs(fi,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:L=>{w(L)},value:v||((z=b==null?void 0:b[0])==null?void 0:z.id),children:[F(),u.jsx(nd,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:V()}),u.jsx(D3e,{open:s,setOpen:i})]})}const $=N.useCallback(z=>{c("dashboard",z)},[c]);return b?u.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[u.jsxs(nK,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[u.jsx(Pk,{children:H()}),e===!0&&u.jsxs(u.Fragment,{children:[u.jsx(P3e,{open:p,onTabClick:j,withHandle:!0}),u.jsx(Pk,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:D,defaultSize:p?40:0,ref:r,children:u.jsx("div",{className:"grow overflow-y-auto",children:u.jsx(lKe,{open:p,setOpen:j,isFullscreen:m,onFullscreenChange:z=>a(z?"dashboard":null),fullscreenContainer:h})})})]})]}),u.jsx("div",{ref:$,className:Z("absolute inset-0",!m&&"pointer-events-none")}),e===!0&&!n&&!p&&!g&&u.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:u.jsx(le,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>j(!0),title:"Open Assistant",children:u.jsx(O_,{className:"h-5 w-5"})})})]}):null}function uJ({children:e}){return u.jsx(ci,{style:{height:"100%",width:"100%"},children:u.jsx(yne,{defaultTheme:"system",storageKey:"vite-ui-theme",children:u.jsx(rd,{delayDuration:0,children:e})})})}function dJ({children:e,preferences:t}){const{currentUser:n}=na(),r=N.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return u.jsx(MZ.Provider,{value:r,children:u.jsx(mP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function fJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return u.jsx(sd,{FallbackComponent:MM,children:u.jsx(U3,{dashboardProps:e,children:u.jsx(uJ,{children:u.jsx(dJ,{preferences:t,children:u.jsx("main",{className:"flex h-full flex-col",children:u.jsx(I6,{...e,type:"dashboard",children:u.jsx(cJ,{})})})})})})})}const uKe=e=>{const{currentContext:t,currentMode:n,selectedUsers:r,usersToRemove:o,usersToUpdate:s,selectedGroups:i=[],groupsToRemove:a=[],groupsToUpdate:l=[],selectedTenant:c,orgWideRole:d,allTenantsRole:f,tenantWideRole:h}=e;if(!t||!n)return null;switch(t){case"org-tab":if(n==="allOrgUsers")return{context:"org-tab",mode:"allOrgUsers",orgWideRole:d};if(n==="specificOrgUsers")return{context:"org-tab",mode:"specificOrgUsers",selectedUsers:r,usersToRemove:o,usersToUpdate:s};break;case"tenant-tab":if(n==="allTenants")return{context:"tenant-tab",mode:"allTenants",allTenantsRole:f};if(n==="allTenantUsers")return c?{context:"tenant-tab",mode:"allTenantUsers",tenantId:c,tenantWideRole:h}:null;if(n==="specificTenantUsers")return c?{context:"tenant-tab",mode:"specificTenantUsers",tenantId:c,selectedUsers:r,usersToRemove:o,usersToUpdate:s}:null;break;case"tenant-dialog":if(n==="allTenantUsers")return{context:"tenant-dialog",mode:"allTenantUsers",tenantWideRole:h};if(n==="specificTenantUsers")return{context:"tenant-dialog",mode:"specificTenantUsers",selectedUsers:r,usersToRemove:o,usersToUpdate:s};break;case"group-share":if(n==="specificGroups")return{context:"group-share",mode:"specificGroups",selectedGroups:i,groupsToRemove:a,groupsToUpdate:l};break}return null},hJ=e=>{var t,n,r;switch(e.context){case"org-tab":return e.mode==="specificOrgUsers"?e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0:!0;case"tenant-tab":if(e.mode==="allTenantUsers"||e.mode==="specificTenantUsers"){if(!e.tenantId)return!1;if(e.mode==="specificTenantUsers")return e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0}return!0;case"tenant-dialog":return e.mode==="specificTenantUsers"?e.selectedUsers.length>0||e.usersToRemove.length>0||e.usersToUpdate.length>0:!0;case"group-share":return e.mode==="specificGroups"?(((t=e.selectedGroups)==null?void 0:t.length)??0)>0||(((n=e.groupsToRemove)==null?void 0:n.length)??0)>0||(((r=e.groupsToUpdate)==null?void 0:r.length)??0)>0:!0}return!1};function pJ(e){var b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,r=Ae(x=>x.selectedConnectionId),o=Ae(x=>x.selectedDatabaseName),s=Ae(x=>x.selectedDatamodelId),i=Ae(x=>x.selectedSchemaName),a=Ae(x=>x.selectedTableName),{selectedConnection:l}=ra(),c=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=bn({queryKey:["columns",r,o,s,i,a],queryFn:()=>qn(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:s||"",database_name:o,schema_name:i,table_name:a}),enabled:g(c)});function g(x){return n!=null&&n.accessToken?!!(r&&o&&o!=="NA"&&i&&a||r&&(x==="S3"||x==="API")||s&&s):!1}return{columns:(b=d==null?void 0:d.columns)==null?void 0:b.map(x=>({...x,data_type:x.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:p,refetchColumns:m}}function dKe(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}const T$={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},Gr=ea()(Dg(e=>({...T$,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(o=>o.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const o=r.selectedUsers.find(s=>s.id===t);o&&(o.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(o=>o.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const o=r.selectedGroups.find(s=>s.id===t);o&&(o.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(o=>o.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>hJ(t),resetShareState:()=>{e(t=>{Object.assign(t,T$)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),mJ=()=>Gr(e=>e.searchQuery),fKe=()=>Gr(e=>e.selectedUsers),hKe=()=>Gr(e=>e.usersToRemove),pKe=()=>Gr(e=>e.usersToUpdate),mKe=()=>Gr(e=>e.selectedTenant),gKe=()=>Gr(e=>e.selectedTab),bKe=()=>Gr(e=>e.currentContext),yKe=()=>Gr(e=>e.currentMode),xKe=()=>Gr(e=>e.orgWideRole),vKe=()=>Gr(e=>e.allTenantsRole),wKe=()=>Gr(e=>e.tenantWideRole),SKe=()=>Gr(e=>e.groupWideRole),CKe=()=>Gr(e=>e.selectedGroups),EKe=()=>Gr(e=>e.groupsToRemove),NKe=()=>Gr(e=>e.groupsToUpdate),gJ=()=>Gr(e=>e.actions),kKe=()=>{const e=mJ(),t=dKe(e,300),n=gJ();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function _Ke(e,t=[]){let n=[];function r(s,i){const a=k.createContext(i),l=n.length;n=[...n,i];const c=f=>{var b;const{scope:h,children:p,...m}=f,g=((b=h==null?void 0:h[e])==null?void 0:b[l])||a,y=k.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=k.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>k.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return k.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,jKe(o,...t)]}function jKe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function RKe(e){const t=k.useRef(e);return k.useEffect(()=>{t.current=e}),k.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}var r_=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},MKe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],fD=MKe.reduce((e,t)=>{const n=ei(`Primitive.${t}`),r=k.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function PKe(){return oZe.useSyncExternalStore(DKe,()=>!0,()=>!1)}function DKe(){return()=>{}}var hD="Avatar",[TKe,WQe]=_Ke(hD),[AKe,bJ]=TKe(hD),yJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,s]=k.useState("idle");return u.jsx(AKe,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:s,children:u.jsx(fD.span,{...r,ref:t})})});yJ.displayName=hD;var xJ="AvatarImage",vJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...s}=e,i=bJ(xJ,n),a=IKe(r,s),l=RKe(c=>{o(c),i.onImageLoadingStatusChange(c)});return r_(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?u.jsx(fD.img,{...s,ref:t,src:r}):null});vJ.displayName=xJ;var wJ="AvatarFallback",SJ=k.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,s=bJ(wJ,n),[i,a]=k.useState(r===void 0);return k.useEffect(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),i&&s.imageLoadingStatus!=="loaded"?u.jsx(fD.span,{...o,ref:t}):null});SJ.displayName=wJ;function A$(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function IKe(e,{referrerPolicy:t,crossOrigin:n}){const r=PKe(),o=k.useRef(null),s=r?(o.current||(o.current=new window.Image),o.current):null,[i,a]=k.useState(()=>A$(s,e));return r_(()=>{a(A$(s,e))},[s,e]),r_(()=>{const l=f=>()=>{a(f)};if(!s)return;const c=l("loaded"),d=l("error");return s.addEventListener("load",c),s.addEventListener("error",d),t&&(s.referrerPolicy=t),typeof n=="string"&&(s.crossOrigin=n),()=>{s.removeEventListener("load",c),s.removeEventListener("error",d)}},[s,n,t]),i}var CJ=yJ,EJ=vJ,NJ=SJ;const kJ=k.forwardRef(({className:e,...t},n)=>u.jsx(CJ,{ref:n,className:Z("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));kJ.displayName=CJ.displayName;const OKe=k.forwardRef(({className:e,...t},n)=>u.jsx(EJ,{ref:n,className:Z("aspect-square h-full w-full",e),...t}));OKe.displayName=EJ.displayName;const _J=k.forwardRef(({className:e,...t},n)=>u.jsx(NJ,{ref:n,className:Z("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));_J.displayName=NJ.displayName;function jJ(e,t){var Ze,Et,on,qt,Qt;const{tokenProps:n}=qe(),r=Jo(),o=qe().authToken||e,s=Ae(ye=>ye.selectedConnectionId),i=Ae(ye=>ye.card),{queryKey:a}=cue(i),l=Ae(ye=>ye.selectedDatamodelId),c=Ae(ye=>ye.isDevMode),d=Ae(ye=>ye.selectedDatabaseName),f=Ae(ye=>ye.selectedSchemaName),h=Ae(ye=>ye.selectedTableName),p=Ae(ye=>ye.actions.setSelectedConnectionId),m=Ae(ye=>ye.actions.setSelectedDatamodelId),g=Ae(ye=>ye.actions.setSelectedDatabaseName),y=Ae(ye=>ye.actions.setSelectedSchemaName),b=Ae(ye=>ye.actions.setSelectedTableName);Ae(ye=>ye.actions.setCardSql);const{setQueryConfig:x}=ko();function v(ye){return s&&d&&f&&d!=="NA"?!0:s&&ye==="API"?!1:!!(s&&ye==="S3")}function w(ye){return s&&ye?!(ye==="API"||ye==="S3"):!1}const{refetchConnections:S,connectionsData:E,isConnectionsLoading:C,isConnectionsError:_,selectedConnection:j}=ra(e),{refetch:R,data:D,isLoading:M,isError:I}=bn({queryKey:["models",s],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:!!(o!=null&&o.accessToken)&&!!s}),O=j==null?void 0:j.type,A=(j==null?void 0:j.type)==="API"||(j==null?void 0:j.type)==="S3",{data:F,isLoading:V,isFetching:H,isError:$,refetch:T}=bn({queryKey:["databases",s],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:w(O)}),{data:z,isLoading:L,isFetching:P,isError:B,refetch:W}=bn({queryKey:["schemas",s,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d}),enabled:!!s&&!!d&&!A&&d!=="NA"}),{data:Y,isLoading:q,isFetching:U,isError:G,refetch:X}=bn({queryKey:["tables",s,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d,schema_name:f}),enabled:v(O)}),{columns:re,isColumnsLoading:J,isColumnsFetching:ce,isColumnsError:te,refetchColumns:se}=pJ(e);N.useEffect(()=>{(O==="S3"||O==="API")&&(g(""),y(""),m(""),O==="API"&&b("api"))},[O,b,g,y,m]);const oe=(j==null?void 0:j.type)==="API"?(Ze=j==null?void 0:j.type)==null?void 0:Ze.toLowerCase():h||"",ke=A?"":f||"";function ue(ye){b(ye),x(void 0),c||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function be(ye){y(ye),b("")}function De(ye){g(ye==="none"?"":ye),y(""),b(""),ye!=="none"&&ye!==""&&m("")}function it(ye){p(ye)}function Ve(ye){m(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}F&&((Et=F==null?void 0:F.databases)==null?void 0:Et.length)>0,z&&((on=z==null?void 0:z.schemas)==null?void 0:on.length)>0;const We=E==null?void 0:E.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),xn=(qt=D==null?void 0:D.datamodels)==null?void 0:qt.map(ye=>({id:ye.id,name:ye.name})),zn=F==null?void 0:F.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),ie=z==null?void 0:z.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),ge=Y==null?void 0:Y.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),Me=(Qt=D==null?void 0:D.datamodels.find(ye=>ye.id===l))==null?void 0:Qt.name,Be=g3({schemaName:ke,tableName:oe,modelName:Me,connectionType:O,databaseName:d||""});return{connectionItems:We,selectedConnectionId:s,selectedConnection:j,isConnectionsLoading:C,isConnectionsError:_,modelItems:xn,selectedDatamodelId:l,selectedDatamodelName:Me,isModelsLoading:M,isModelsError:I,selectedDatabaseName:d,databaseItems:zn,isDatabasesLoadingOrFetching:V||H,isDatabaseError:$,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:L||P,isSchemaError:B,tableItems:ge,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:G,columns:re,isColumnsLoadingOrFetching:J||ce,isColumnsError:te,isNonDbConnection:A,connectionType:O,tableName:oe,formattedTableName:Be,schemaName:ke,refetchConnections:S,refetchModels:R,refetchDatabases:T,refetchSchemas:W,refetchTables:X,refetchColumns:se,handleConnectionChange:it,handleDatamodelChange:Ve,handleDatabaseChange:De,handleSchemaChange:be,handleTableChange:ue}}function FKe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function I$(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function O$(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?I$(Object(n),!0).forEach(function(r){FKe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):I$(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $Ke(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s<r.length;s++)o=r[s],!(t.indexOf(o)>=0)&&(n[o]=e[o]);return n}function LKe(e,t){if(e==null)return{};var n=$Ke(e,t),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o<s.length;o++)r=s[o],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function zKe(e,t){return BKe(e)||VKe(e,t)||HKe(e,t)||UKe()}function BKe(e){if(Array.isArray(e))return e}function VKe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,o=!1,s=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){o=!0,s=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(o)throw s}}return n}}function HKe(e,t){if(e){if(typeof e=="string")return F$(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 F$(e,t)}}function F$(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 UKe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
986
986
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function WKe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $$(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function L$(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$$(Object(n),!0).forEach(function(r){WKe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$$(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function qKe(){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(o,s){return s(o)},r)}}function $p(e){return function t(){for(var n=this,r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return o.length>=e.length?e.apply(this,o):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(o,a))}}}function Ov(e){return{}.toString.call(e).includes("Object")}function GKe(e){return!Object.keys(e).length}function Eg(e){return typeof e=="function"}function YKe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ZKe(e,t){return Ov(t)||Vl("changeType"),Object.keys(t).some(function(n){return!YKe(e,n)})&&Vl("changeField"),t}function KKe(e){Eg(e)||Vl("selectorType")}function XKe(e){Eg(e)||Ov(e)||Vl("handlerType"),Ov(e)&&Object.values(e).some(function(t){return!Eg(t)})&&Vl("handlersType")}function QKe(e){e||Vl("initialIsRequired"),Ov(e)||Vl("initialType"),GKe(e)&&Vl("initialContent")}function JKe(e,t){throw new Error(e[t]||e.default)}var eXe={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"},Vl=$p(JKe)(eXe),m0={changes:ZKe,selector:KKe,handler:XKe,initial:QKe};function tXe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};m0.initial(e),m0.handler(t);var n={current:e},r=$p(oXe)(n,t),o=$p(rXe)(n),s=$p(m0.changes)(e),i=$p(nXe)(n);function a(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return m0.selector(c),c(n.current)}function l(c){qKe(r,o,s,i)(c)}return[a,l]}function nXe(e,t){return Eg(t)?t(e.current):t}function rXe(e,t){return e.current=L$(L$({},e.current),t),t}function oXe(e,t,n){return Eg(t)?t(e.current):Object.keys(n).forEach(function(r){var o;return(o=t[r])===null||o===void 0?void 0:o.call(t,e.current[r])}),n}var sXe={create:tXe},iXe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function aXe(e){return function t(){for(var n=this,r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return o.length>=e.length?e.apply(this,o):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(o,a))}}}function lXe(e){return{}.toString.call(e).includes("Object")}function cXe(e){return e||z$("configIsRequired"),lXe(e)||z$("configType"),e.urls?(uXe(),{paths:{vs:e.urls.monacoBase}}):e}function uXe(){console.warn(RJ.deprecation)}function dXe(e,t){throw new Error(e[t]||e.default)}var RJ={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!
|
|
987
987
|
You are using deprecated way of configuration.
|
|
988
988
|
|