@trailheadai/chat 0.2.1 → 0.2.2

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.
@@ -255,7 +255,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
255
255
 
256
256
  `)},flush(u){u.enqueue(`data: [DONE]
257
257
 
258
- `)}})}};var w6=SD(()=>bE(su([ra({type:at("text-start"),id:ve(),providerMetadata:za.optional()}),ra({type:at("text-delta"),id:ve(),delta:ve(),providerMetadata:za.optional()}),ra({type:at("text-end"),id:ve(),providerMetadata:za.optional()}),ra({type:at("error"),errorText:ve()}),ra({type:at("tool-input-start"),toolCallId:ve(),toolName:ve(),providerExecuted:xn().optional(),dynamic:xn().optional()}),ra({type:at("tool-input-delta"),toolCallId:ve(),inputTextDelta:ve()}),ra({type:at("tool-input-available"),toolCallId:ve(),toolName:ve(),input:Bi(),providerExecuted:xn().optional(),providerMetadata:za.optional(),dynamic:xn().optional()}),ra({type:at("tool-input-error"),toolCallId:ve(),toolName:ve(),input:Bi(),providerExecuted:xn().optional(),providerMetadata:za.optional(),dynamic:xn().optional(),errorText:ve()}),ra({type:at("tool-output-available"),toolCallId:ve(),output:Bi(),providerExecuted:xn().optional(),dynamic:xn().optional(),preliminary:xn().optional()}),ra({type:at("tool-output-error"),toolCallId:ve(),errorText:ve(),providerExecuted:xn().optional(),dynamic:xn().optional()}),ra({type:at("reasoning-start"),id:ve(),providerMetadata:za.optional()}),ra({type:at("reasoning-delta"),id:ve(),delta:ve(),providerMetadata:za.optional()}),ra({type:at("reasoning-end"),id:ve(),providerMetadata:za.optional()}),ra({type:at("source-url"),sourceId:ve(),url:ve(),title:ve().optional(),providerMetadata:za.optional()}),ra({type:at("source-document"),sourceId:ve(),mediaType:ve(),title:ve(),filename:ve().optional(),providerMetadata:za.optional()}),ra({type:at("file"),url:ve(),mediaType:ve(),providerMetadata:za.optional()}),ra({type:iE(u=>typeof u=="string"&&u.startsWith("data-"),{message:'Type must start with "data-"'}),id:ve().optional(),data:Bi(),transient:xn().optional()}),ra({type:at("start-step")}),ra({type:at("finish-step")}),ra({type:at("start"),messageId:ve().optional(),messageMetadata:Bi().optional()}),ra({type:at("finish"),finishReason:z1(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Bi().optional()}),ra({type:at("abort")}),ra({type:at("message-metadata"),messageMetadata:Bi()})])));function D6(u){return u.type.startsWith("data-")}function ME(u,c){if(u===void 0&&c===void 0)return;if(u===void 0)return c;if(c===void 0)return u;const d={...u};for(const h in c)if(Object.prototype.hasOwnProperty.call(c,h)){const g=c[h];if(g===void 0)continue;const b=h in u?u[h]:void 0,_=g!==null&&typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)&&!(g instanceof RegExp),z=b!=null&&typeof b=="object"&&!Array.isArray(b)&&!(b instanceof Date)&&!(b instanceof RegExp);_&&z?d[h]=ME(b,g):d[h]=g}return d}function M6(u){const c=["ROOT"];let d=-1,h=null;function g(w,O,j){switch(w){case'"':{d=O,c.pop(),c.push(j),c.push("INSIDE_STRING");break}case"f":case"t":case"n":{d=O,h=O,c.pop(),c.push(j),c.push("INSIDE_LITERAL");break}case"-":{c.pop(),c.push(j),c.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{d=O,c.pop(),c.push(j),c.push("INSIDE_NUMBER");break}case"{":{d=O,c.pop(),c.push(j),c.push("INSIDE_OBJECT_START");break}case"[":{d=O,c.pop(),c.push(j),c.push("INSIDE_ARRAY_START");break}}}function b(w,O){switch(w){case",":{c.pop(),c.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{d=O,c.pop();break}}}function _(w,O){switch(w){case",":{c.pop(),c.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{d=O,c.pop();break}}}for(let w=0;w<u.length;w++){const O=u[w];switch(c[c.length-1]){case"ROOT":g(O,w,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_KEY");break}case"}":{d=w,c.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{c.pop(),c.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{g(O,w,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{b(O,w);break}case"INSIDE_STRING":{switch(O){case'"':{c.pop(),d=w;break}case"\\":{c.push("INSIDE_STRING_ESCAPE");break}default:d=w}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{d=w,c.pop();break}default:{d=w,g(O,w,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{c.pop(),c.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{d=w,c.pop();break}default:{d=w;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{g(O,w,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{c.pop(),d=w;break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{d=w;break}case"e":case"E":case"-":case".":break;case",":{c.pop(),c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&b(O,w);break}case"}":{c.pop(),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&b(O,w);break}case"]":{c.pop(),c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w);break}default:{c.pop();break}}break}case"INSIDE_LITERAL":{const Y=u.substring(h,w+1);!"false".startsWith(Y)&&!"true".startsWith(Y)&&!"null".startsWith(Y)?(c.pop(),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?b(O,w):c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w)):d=w;break}}}let z=u.slice(0,d+1);for(let w=c.length-1;w>=0;w--)switch(c[w]){case"INSIDE_STRING":{z+='"';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":{z+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{z+="]";break}case"INSIDE_LITERAL":{const j=u.substring(h,u.length);"true".startsWith(j)?z+="true".slice(j.length):"false".startsWith(j)?z+="false".slice(j.length):"null".startsWith(j)&&(z+="null".slice(j.length))}}return z}async function xE(u){if(u===void 0)return{value:void 0,state:"undefined-input"};let c=await Cg({text:u});return c.success?{value:c.value,state:"successful-parse"}:(c=await Cg({text:M6(u)}),c.success?{value:c.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ug(u){return u.type.startsWith("tool-")}function x6(u){return u.type==="dynamic-tool"}function CE(u){return Ug(u)||x6(u)}function RE(u){return u.type.split("-").slice(1).join("-")}function C6({lastMessage:u,messageId:c}){return{message:u?.role==="assistant"?u:{id:c,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function R6({stream:u,messageMetadataSchema:c,dataPartSchemas:d,runUpdateMessageJob:h,onError:g,onToolCall:b,onData:_}){return u.pipeThrough(new TransformStream({async transform(z,w){await h(async({state:O,write:j})=>{var Y,ae,ne,ce;function re(F){const je=O.message.parts.filter(Ug).find(Te=>Te.toolCallId===F);if(je==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return je}function se(F){const je=O.message.parts.filter(Te=>Te.type==="dynamic-tool").find(Te=>Te.toolCallId===F);if(je==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return je}function ue(F){var Je;const je=O.message.parts.find(qe=>Ug(qe)&&qe.toolCallId===F.toolCallId),Te=F,ie=je;je!=null?(je.state=F.state,ie.input=Te.input,ie.output=Te.output,ie.errorText=Te.errorText,ie.rawInput=Te.rawInput,ie.preliminary=Te.preliminary,ie.providerExecuted=(Je=Te.providerExecuted)!=null?Je:je.providerExecuted,Te.providerMetadata!=null&&je.state==="input-available"&&(je.callProviderMetadata=Te.providerMetadata)):O.message.parts.push({type:`tool-${F.toolName}`,toolCallId:F.toolCallId,state:F.state,input:Te.input,output:Te.output,rawInput:Te.rawInput,errorText:Te.errorText,providerExecuted:Te.providerExecuted,preliminary:Te.preliminary,...Te.providerMetadata!=null?{callProviderMetadata:Te.providerMetadata}:{}})}function Ee(F){var Je,je;const Te=O.message.parts.find(de=>de.type==="dynamic-tool"&&de.toolCallId===F.toolCallId),ie=F,qe=Te;Te!=null?(Te.state=F.state,qe.toolName=F.toolName,qe.input=ie.input,qe.output=ie.output,qe.errorText=ie.errorText,qe.rawInput=(Je=ie.rawInput)!=null?Je:qe.rawInput,qe.preliminary=ie.preliminary,qe.providerExecuted=(je=ie.providerExecuted)!=null?je:Te.providerExecuted,ie.providerMetadata!=null&&Te.state==="input-available"&&(Te.callProviderMetadata=ie.providerMetadata)):O.message.parts.push({type:"dynamic-tool",toolName:F.toolName,toolCallId:F.toolCallId,state:F.state,input:ie.input,output:ie.output,errorText:ie.errorText,preliminary:ie.preliminary,providerExecuted:ie.providerExecuted,...ie.providerMetadata!=null?{callProviderMetadata:ie.providerMetadata}:{}})}async function ye(F){if(F!=null){const Je=O.message.metadata!=null?ME(O.message.metadata,F):F;c!=null&&await dE({value:Je,schema:c}),O.message.metadata=Je}}switch(z.type){case"text-start":{const F={type:"text",text:"",providerMetadata:z.providerMetadata,state:"streaming"};O.activeTextParts[z.id]=F,O.message.parts.push(F),j();break}case"text-delta":{const F=O.activeTextParts[z.id];F.text+=z.delta,F.providerMetadata=(Y=z.providerMetadata)!=null?Y:F.providerMetadata,j();break}case"text-end":{const F=O.activeTextParts[z.id];F.state="done",F.providerMetadata=(ae=z.providerMetadata)!=null?ae:F.providerMetadata,delete O.activeTextParts[z.id],j();break}case"reasoning-start":{const F={type:"reasoning",text:"",providerMetadata:z.providerMetadata,state:"streaming"};O.activeReasoningParts[z.id]=F,O.message.parts.push(F),j();break}case"reasoning-delta":{const F=O.activeReasoningParts[z.id];F.text+=z.delta,F.providerMetadata=(ne=z.providerMetadata)!=null?ne:F.providerMetadata,j();break}case"reasoning-end":{const F=O.activeReasoningParts[z.id];F.providerMetadata=(ce=z.providerMetadata)!=null?ce:F.providerMetadata,F.state="done",delete O.activeReasoningParts[z.id],j();break}case"file":{O.message.parts.push({type:"file",mediaType:z.mediaType,url:z.url}),j();break}case"source-url":{O.message.parts.push({type:"source-url",sourceId:z.sourceId,url:z.url,title:z.title,providerMetadata:z.providerMetadata}),j();break}case"source-document":{O.message.parts.push({type:"source-document",sourceId:z.sourceId,mediaType:z.mediaType,title:z.title,filename:z.filename,providerMetadata:z.providerMetadata}),j();break}case"tool-input-start":{const F=O.message.parts.filter(Ug);O.partialToolCalls[z.toolCallId]={text:"",toolName:z.toolName,index:F.length,dynamic:z.dynamic},z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-streaming",input:void 0,providerExecuted:z.providerExecuted}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-streaming",input:void 0,providerExecuted:z.providerExecuted}),j();break}case"tool-input-delta":{const F=O.partialToolCalls[z.toolCallId];F.text+=z.inputTextDelta;const{value:Je}=await xE(F.text);F.dynamic?Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"input-streaming",input:Je}):ue({toolCallId:z.toolCallId,toolName:F.toolName,state:"input-streaming",input:Je}),j();break}case"tool-input-available":{z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-available",input:z.input,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-available",input:z.input,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}),j(),b&&!z.providerExecuted&&await b({toolCall:z});break}case"tool-input-error":{z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"output-error",input:z.input,errorText:z.errorText,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"output-error",input:void 0,rawInput:z.input,errorText:z.errorText,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}),j();break}case"tool-output-available":{if(z.dynamic){const F=se(z.toolCallId);Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"output-available",input:F.input,output:z.output,preliminary:z.preliminary})}else{const F=re(z.toolCallId);ue({toolCallId:z.toolCallId,toolName:RE(F),state:"output-available",input:F.input,output:z.output,providerExecuted:z.providerExecuted,preliminary:z.preliminary})}j();break}case"tool-output-error":{if(z.dynamic){const F=se(z.toolCallId);Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"output-error",input:F.input,errorText:z.errorText,providerExecuted:z.providerExecuted})}else{const F=re(z.toolCallId);ue({toolCallId:z.toolCallId,toolName:RE(F),state:"output-error",input:F.input,rawInput:F.rawInput,errorText:z.errorText,providerExecuted:z.providerExecuted})}j();break}case"start-step":{O.message.parts.push({type:"step-start"});break}case"finish-step":{O.activeTextParts={},O.activeReasoningParts={};break}case"start":{z.messageId!=null&&(O.message.id=z.messageId),await ye(z.messageMetadata),(z.messageId!=null||z.messageMetadata!=null)&&j();break}case"finish":{z.finishReason!=null&&(O.finishReason=z.finishReason),await ye(z.messageMetadata),z.messageMetadata!=null&&j();break}case"message-metadata":{await ye(z.messageMetadata),z.messageMetadata!=null&&j();break}case"error":{g?.(new Error(z.errorText));break}default:if(D6(z)){d?.[z.type]!=null&&await dE({value:z.data,schema:d[z.type]});const F=z;if(F.transient){_?.(F);break}const Je=F.id!=null?O.message.parts.find(je=>F.type===je.type&&F.id===je.id):void 0;Je!=null?Je.data=F.data:O.message.parts.push(F),_?.(F),j()}}w.enqueue(z)})}}))}async function U6({stream:u,onError:c}){const d=u.getReader();try{for(;;){const{done:h}=await d.read();if(h)break}}catch(h){c?.(h)}finally{d.releaseLock()}}im({prefix:"aitxt",size:24}),im({prefix:"aiobj",size:24});var N6=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(u){return new Promise((c,d)=>{this.queue.push(async()=>{try{await u(),c()}catch(h){d(h)}}),this.processQueue()})}};im({prefix:"aiobj",size:24});var Z6={};g6(Z6,{object:()=>j6,text:()=>H6});var H6=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:u}){return{partial:u}},async parseOutput({text:u}){return u}}),j6=({schema:u})=>{const c=m6(u);return{type:"object",responseFormat:{type:"json",schema:c.jsonSchema},async parsePartial({text:d}){const h=await xE(d);switch(h.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:h.value};default:{const g=h.state;throw new Error(`Unsupported parse state: ${g}`)}}},async parseOutput({text:d},h){const g=await Cg({text:d});if(!g.success)throw new zE({message:"No object generated: could not parse the response.",cause:g.error,text:d,response:h.response,usage:h.usage,finishReason:h.finishReason});const b=await A1({value:g.value,schema:c});if(!b.success)throw new zE({message:"No object generated: response did not match schema.",cause:b.error,text:d,response:h.response,usage:h.usage,finishReason:h.finishReason});return b.value}}};async function B6(u){if(u==null)return[];if(!globalThis.FileList||!(u instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(u).map(async c=>{const{name:d,type:h}=c,g=await new Promise((b,_)=>{const z=new FileReader;z.onload=w=>{var O;b((O=w.target)==null?void 0:O.result)},z.onerror=w=>_(w),z.readAsDataURL(c)});return{type:"file",mediaType:h,filename:d,url:g}}))}var q6=class{constructor({api:u="/api/chat",credentials:c,headers:d,body:h,fetch:g,prepareSendMessagesRequest:b,prepareReconnectToStreamRequest:_}){this.api=u,this.credentials=c,this.headers=d,this.body=h,this.fetch=g,this.prepareSendMessagesRequest=b,this.prepareReconnectToStreamRequest=_}async sendMessages({abortSignal:u,...c}){var d,h,g,b,_;const z=await wd(this.body),w=await wd(this.headers),O=await wd(this.credentials),j={...Ds(w),...Ds(c.headers)},Y=await((d=this.prepareSendMessagesRequest)==null?void 0:d.call(this,{api:this.api,id:c.chatId,messages:c.messages,body:{...z,...c.body},headers:j,credentials:O,requestMetadata:c.metadata,trigger:c.trigger,messageId:c.messageId})),ae=(h=Y?.api)!=null?h:this.api,ne=Y?.headers!==void 0?Ds(Y.headers):j,ce=Y?.body!==void 0?Y.body:{...z,...c.body,id:c.chatId,messages:c.messages,trigger:c.trigger,messageId:c.messageId},re=(g=Y?.credentials)!=null?g:O,ue=await((b=this.fetch)!=null?b:globalThis.fetch)(ae,{method:"POST",headers:sE({"Content-Type":"application/json",...ne},`ai-sdk/${TE}`,rE()),body:JSON.stringify(ce),credentials:re,signal:u});if(!ue.ok)throw new Error((_=await ue.text())!=null?_:"Failed to fetch the chat response.");if(!ue.body)throw new Error("The response body is empty.");return this.processResponseStream(ue.body)}async reconnectToStream(u){var c,d,h,g,b;const _=await wd(this.body),z=await wd(this.headers),w=await wd(this.credentials),O={...Ds(z),...Ds(u.headers)},j=await((c=this.prepareReconnectToStreamRequest)==null?void 0:c.call(this,{api:this.api,id:u.chatId,body:{..._,...u.body},headers:O,credentials:w,requestMetadata:u.metadata})),Y=(d=j?.api)!=null?d:`${this.api}/${u.chatId}/stream`,ae=j?.headers!==void 0?Ds(j.headers):O,ne=(h=j?.credentials)!=null?h:w,re=await((g=this.fetch)!=null?g:globalThis.fetch)(Y,{method:"GET",headers:sE(ae,`ai-sdk/${TE}`,rE()),credentials:ne});if(re.status===204)return null;if(!re.ok)throw new Error((b=await re.text())!=null?b:"Failed to fetch the chat response.");if(!re.body)throw new Error("The response body is empty.");return this.processResponseStream(re.body)}},UE=class extends q6{constructor(u={}){super(u)}processResponseStream(u){return zD({stream:u,schema:w6}).pipeThrough(new TransformStream({async transform(c,d){if(!c.success)throw c.error;d.enqueue(c.value)}}))}},Y6=class{constructor({generateId:u=hD,id:c=u(),transport:d=new UE,messageMetadataSchema:h,dataPartSchemas:g,state:b,onError:_,onToolCall:z,onFinish:w,onData:O,sendAutomaticallyWhen:j}){this.activeResponse=void 0,this.jobExecutor=new N6,this.sendMessage=async(Y,ae)=>{var ne,ce,re,se;if(Y==null){await this.makeRequest({trigger:"submit-message",messageId:(ne=this.lastMessage)==null?void 0:ne.id,...ae});return}let ue;if("text"in Y||"files"in Y?ue={parts:[...Array.isArray(Y.files)?Y.files:await B6(Y.files),..."text"in Y&&Y.text!=null?[{type:"text",text:Y.text}]:[]]}:ue=Y,Y.messageId!=null){const Ee=this.state.messages.findIndex(ye=>ye.id===Y.messageId);if(Ee===-1)throw new Error(`message with id ${Y.messageId} not found`);if(this.state.messages[Ee].role!=="user")throw new Error(`message with id ${Y.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,Ee+1),this.state.replaceMessage(Ee,{...ue,id:Y.messageId,role:(ce=ue.role)!=null?ce:"user",metadata:Y.metadata})}else this.state.pushMessage({...ue,id:(re=ue.id)!=null?re:this.generateId(),role:(se=ue.role)!=null?se:"user",metadata:Y.metadata});await this.makeRequest({trigger:"submit-message",messageId:Y.messageId,...ae})},this.regenerate=async({messageId:Y,...ae}={})=>{const ne=Y==null?this.state.messages.length-1:this.state.messages.findIndex(ce=>ce.id===Y);if(ne===-1)throw new Error(`message ${Y} not found`);this.state.messages=this.state.messages.slice(0,this.messages[ne].role==="assistant"?ne:ne+1),await this.makeRequest({trigger:"regenerate-message",messageId:Y,...ae})},this.resumeStream=async(Y={})=>{await this.makeRequest({trigger:"resume-stream",...Y})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:Y="output-available",tool:ae,toolCallId:ne,output:ce,errorText:re})=>this.jobExecutor.run(async()=>{var se,ue;const Ee=this.state.messages,ye=Ee[Ee.length-1];this.state.replaceMessage(Ee.length-1,{...ye,parts:ye.parts.map(F=>CE(F)&&F.toolCallId===ne?{...F,state:Y,output:ce,errorText:re}:F)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(F=>CE(F)&&F.toolCallId===ne?{...F,state:Y,output:ce,errorText:re}:F)),this.status!=="streaming"&&this.status!=="submitted"&&((se=this.sendAutomaticallyWhen)!=null&&se.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(ue=this.lastMessage)==null?void 0:ue.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var Y;this.status!=="streaming"&&this.status!=="submitted"||(Y=this.activeResponse)!=null&&Y.abortController&&this.activeResponse.abortController.abort()},this.id=c,this.transport=d,this.generateId=u,this.messageMetadataSchema=h,this.dataPartSchemas=g,this.state=b,this.onError=_,this.onToolCall=z,this.onFinish=w,this.onData=O,this.sendAutomaticallyWhen=j}get status(){return this.state.status}setStatus({status:u,error:c}){this.status!==u&&(this.state.status=u,this.state.error=c)}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(u){this.state.messages=u}async makeRequest({trigger:u,metadata:c,headers:d,body:h,messageId:g}){var b,_,z,w;this.setStatus({status:"submitted",error:void 0});const O=this.lastMessage;let j=!1,Y=!1,ae=!1;try{const ne={state:C6({lastMessage:this.state.snapshot(O),messageId:this.generateId()}),abortController:new AbortController};ne.abortController.signal.addEventListener("abort",()=>{j=!0}),this.activeResponse=ne;let ce;if(u==="resume-stream"){const se=await this.transport.reconnectToStream({chatId:this.id,metadata:c,headers:d,body:h});if(se==null){this.setStatus({status:"ready"});return}ce=se}else ce=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:ne.abortController.signal,metadata:c,headers:d,body:h,trigger:u,messageId:g});const re=se=>this.jobExecutor.run(()=>se({state:ne.state,write:()=>{var ue;this.setStatus({status:"streaming"}),ne.state.message.id===((ue=this.lastMessage)==null?void 0:ue.id)?this.state.replaceMessage(this.state.messages.length-1,ne.state.message):this.state.pushMessage(ne.state.message)}}));await U6({stream:R6({stream:ce,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:re,onError:se=>{throw se}}),onError:se=>{throw se}}),this.setStatus({status:"ready"})}catch(ne){if(j||ne.name==="AbortError")return j=!0,this.setStatus({status:"ready"}),null;ae=!0,ne instanceof TypeError&&(ne.message.toLowerCase().includes("fetch")||ne.message.toLowerCase().includes("network"))&&(Y=!0),this.onError&&ne instanceof Error&&this.onError(ne),this.setStatus({status:"error",error:ne})}finally{try{(_=this.onFinish)==null||_.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:j,isDisconnect:Y,isError:ae,finishReason:(b=this.activeResponse)==null?void 0:b.state.finishReason})}catch(ne){console.error(ne)}this.activeResponse=void 0}(z=this.sendAutomaticallyWhen)!=null&&z.call(this,{messages:this.state.messages})&&!ae&&await this.makeRequest({trigger:"submit-message",messageId:(w=this.lastMessage)==null?void 0:w.id,metadata:c,headers:d,body:h})}},C1,NE;function L6(){if(NE)return C1;NE=1;function u(c,d){if(typeof c!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof c}\`.`);let h,g=0;return function(..._){clearTimeout(h);const z=Date.now(),w=z-g,O=d-w;O<=0?(g=z,c.apply(this,_)):h=setTimeout(()=>{g=Date.now(),c.apply(this,_)},O)}}return C1=u,C1}var V6=L6();const G6=fA(V6);var ZE=(u,c,d)=>{if(!c.has(u))throw TypeError("Cannot "+d)},Ft=(u,c,d)=>(ZE(u,c,"read from private field"),d?d.call(u):c.get(u)),qi=(u,c,d)=>{if(c.has(u))throw TypeError("Cannot add the same private member more than once");c instanceof WeakSet?c.add(u):c.set(u,d)},$c=(u,c,d,h)=>(ZE(u,c,"write to private field"),c.set(u,d),d);function X6(u,c){return c!=null?G6(u,c):u}var fu,Ng,Zg,cm,rm,sm,Dd,R1,U1,Q6=class{constructor(u=[]){qi(this,fu,void 0),qi(this,Ng,"ready"),qi(this,Zg,void 0),qi(this,cm,new Set),qi(this,rm,new Set),qi(this,sm,new Set),this.pushMessage=c=>{$c(this,fu,Ft(this,fu).concat(c)),Ft(this,Dd).call(this)},this.popMessage=()=>{$c(this,fu,Ft(this,fu).slice(0,-1)),Ft(this,Dd).call(this)},this.replaceMessage=(c,d)=>{$c(this,fu,[...Ft(this,fu).slice(0,c),this.snapshot(d),...Ft(this,fu).slice(c+1)]),Ft(this,Dd).call(this)},this.snapshot=c=>structuredClone(c),this["~registerMessagesCallback"]=(c,d)=>{const h=d?X6(c,d):c;return Ft(this,cm).add(h),()=>{Ft(this,cm).delete(h)}},this["~registerStatusCallback"]=c=>(Ft(this,rm).add(c),()=>{Ft(this,rm).delete(c)}),this["~registerErrorCallback"]=c=>(Ft(this,sm).add(c),()=>{Ft(this,sm).delete(c)}),qi(this,Dd,()=>{Ft(this,cm).forEach(c=>c())}),qi(this,R1,()=>{Ft(this,rm).forEach(c=>c())}),qi(this,U1,()=>{Ft(this,sm).forEach(c=>c())}),$c(this,fu,u)}get status(){return Ft(this,Ng)}set status(u){$c(this,Ng,u),Ft(this,R1).call(this)}get error(){return Ft(this,Zg)}set error(u){$c(this,Zg,u),Ft(this,U1).call(this)}get messages(){return Ft(this,fu)}set messages(u){$c(this,fu,[...u]),Ft(this,Dd).call(this)}};fu=new WeakMap,Ng=new WeakMap,Zg=new WeakMap,cm=new WeakMap,rm=new WeakMap,sm=new WeakMap,Dd=new WeakMap,R1=new WeakMap,U1=new WeakMap;var Md,HE=class extends Y6{constructor({messages:c,...d}){const h=new Q6(c);super({...d,state:h}),qi(this,Md,void 0),this["~registerMessagesCallback"]=(g,b)=>Ft(this,Md)["~registerMessagesCallback"](g,b),this["~registerStatusCallback"]=g=>Ft(this,Md)["~registerStatusCallback"](g),this["~registerErrorCallback"]=g=>Ft(this,Md)["~registerErrorCallback"](g),$c(this,Md,h)}};Md=new WeakMap;function J6({experimental_throttle:u,resume:c=!1,...d}={}){const h=Oe.useRef("chat"in d?d.chat:new HE(d));("chat"in d&&d.chat!==h.current||"id"in d&&h.current.id!==d.id)&&(h.current="chat"in d?d.chat:new HE(d));const b=Oe.useCallback(j=>h.current["~registerMessagesCallback"](j,u),[u,h.current.id]),_=Oe.useSyncExternalStore(b,()=>h.current.messages,()=>h.current.messages),z=Oe.useSyncExternalStore(h.current["~registerStatusCallback"],()=>h.current.status,()=>h.current.status),w=Oe.useSyncExternalStore(h.current["~registerErrorCallback"],()=>h.current.error,()=>h.current.error),O=Oe.useCallback(j=>{typeof j=="function"&&(j=j(h.current.messages)),h.current.messages=j},[h]);return Oe.useEffect(()=>{c&&h.current.resumeStream()},[c,h]),{id:h.current.id,messages:_,setMessages:O,sendMessage:h.current.sendMessage,regenerate:h.current.regenerate,clearError:h.current.clearError,stop:h.current.stop,error:w,resumeStream:h.current.resumeStream,status:z,addToolResult:h.current.addToolOutput,addToolOutput:h.current.addToolOutput}}const fn=[];for(let u=0;u<256;++u)fn.push((u+256).toString(16).slice(1));function $6(u,c=0){return(fn[u[c+0]]+fn[u[c+1]]+fn[u[c+2]]+fn[u[c+3]]+"-"+fn[u[c+4]]+fn[u[c+5]]+"-"+fn[u[c+6]]+fn[u[c+7]]+"-"+fn[u[c+8]]+fn[u[c+9]]+"-"+fn[u[c+10]]+fn[u[c+11]]+fn[u[c+12]]+fn[u[c+13]]+fn[u[c+14]]+fn[u[c+15]]).toLowerCase()}let N1;const k6=new Uint8Array(16);function K6(){if(!N1){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");N1=crypto.getRandomValues.bind(crypto)}return N1(k6)}const jE={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function I6(u,c,d){u=u||{};const h=u.random??u.rng?.()??K6();if(h.length<16)throw new Error("Random bytes length must be >= 16");return h[6]=h[6]&15|64,h[8]=h[8]&63|128,$6(h)}function F6(u,c,d){return jE.randomUUID&&!u?jE.randomUUID():I6(u)}console.log("TH_API_URL","https://trailhead-production.up.railway.app");const Z1="https://trailhead-production.up.railway.app",W6=Ea({role:z1(["user","assistant"]),content:ve()}),P6=Ea({sessionId:ve(),welcomeMessages:Jc(ve()).nullable().optional(),messages:Jc(W6).nullable().optional(),completed:xn().default(!1),name:ve(),color:ve(),imageUrl:ve().nullable(),formData:S1().nullable(),maxMessages:I_(),formFields:S1()}),BE=Ea({session:P6,token:ve()}),qE=Ea({success:xn(),message:ve(),data:S1().nullable()}),eM={session:null,token:null,isLoading:!0,isFetching:!1,error:null,refetch:async()=>{}},H1=Oe.createContext(eM);function tM({projectId:u,children:c}){const[d,h]=Oe.useState(!0),[g,b]=Oe.useState(!1),[_,z]=Oe.useState(null),[w,O]=Oe.useState(null),[j,Y]=Oe.useState(null),ae=Oe.useEffectEvent(async()=>{const re=new URL(`${Z1}/session/new?project_id=${u}`),se=await fetch(re.toString()),ue=await se.json();if(!se.ok)throw new Error(ue.error);const{success:Ee,data:ye}=BE.safeParse(ue);if(!Ee)throw console.error("Invalid session data: ",_),new Error("Invalid session data");return localStorage.setItem(`th__token_${ye.session.sessionId}`,ye.token??""),Y(ye.token??""),ye.session}),ne=Oe.useEffectEvent(async re=>{const se=new URL(`${Z1}/session`),ue=await fetch(se.toString(),{headers:{Authorization:`Bearer ${re}`}}),Ee=await ue.json();if(!ue.ok)throw new Error(Ee.error);const{success:ye,data:F}=BE.safeParse(Ee);if(!ye)throw console.error("Invalid session data: ",_),new Error("Invalid session data");return F}),ce=Oe.useCallback(async()=>{b(!0);try{const re=localStorage.getItem(`th__token_${u}`);let se=null;if(re)try{const{session:ue}=await ne(re);Y(re),se=ue}catch{console.warn("Failed to get session, creating new one"),se=await ae()}else se=await ae();O(se)}catch(re){console.error(re),z(re)}finally{h(!1),b(!1)}},[u]);return Oe.useEffect(()=>{ce()},[]),te.jsx(H1.Provider,{value:{session:w,token:j,isLoading:d,isFetching:g,error:_,refetch:ce},children:c})}function YE(){const u=Oe.useContext(H1);if(!u)throw new Error("useSession must be used within a SessionProvider");if(!u.session||!u.token)throw new Error("Session not found");return{session:u.session,token:u.token,refetch:u.refetch}}function aM(){const u=Oe.useContext(H1);if(!u)throw new Error("useMaybeSession must be used within a SessionProvider");return u}const LE=Oe.createContext(null);function nM(){const u=Oe.useContext(LE);if(!u)throw new Error("useChatContext must be used within a ChatProvider");return u}function VE({children:u}){const{token:c,session:{sessionId:d,messages:h}}=YE(),{messages:g,setMessages:b,sendMessage:_,status:z,error:w}=J6({transport:new UE({api:`${Z1}/chat`,body:{session_id:d},headers:c?{Authorization:`Bearer ${c}`}:void 0}),messages:h?.map(O=>({id:F6(),role:O.role,content:O.content,parts:[{type:"text",text:O.content}],metadata:{isLoading:!1}}))});return te.jsx(LE.Provider,{value:{messages:g,setMessages:b,sendMessage:_,status:z,error:w??null},children:u})}function lM(u){if(u.includes("email"))return"your@email.com";if(u.includes("website")||u.includes("portfolio")||u.includes("github")||u.includes("url")||u.includes("twitter")||u.includes("blog"))return"Share a link...";if(u.includes("looking for"))return"What you're looking for...";if(u.includes("great at"))return"Your key strengths...";if(u.includes("avoid"))return"What to avoid...";if(u.includes("location")||u.includes("based"))return"Your location..."}function GE(u){var c,d,h="";if(typeof u=="string"||typeof u=="number")h+=u;else if(typeof u=="object")if(Array.isArray(u)){var g=u.length;for(c=0;c<g;c++)u[c]&&(d=GE(u[c]))&&(h&&(h+=" "),h+=d)}else for(d in u)u[d]&&(h&&(h+=" "),h+=d);return h}function uM(){for(var u,c,d=0,h="",g=arguments.length;d<g;d++)(u=arguments[d])&&(c=GE(u))&&(h&&(h+=" "),h+=c);return h}function Ms(...u){return uM(u)}const XE=h2.forwardRef(({className:u,size:c="default",...d},h)=>{const g={sm:"h-8 px-3 text-xs",default:"h-9 px-4",icon:"h-9 w-9 rounded-lg"};return te.jsx("button",{className:Ms("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g[c],u),ref:h,...d})});XE.displayName="Button";const QE=h2.forwardRef(({className:u,...c},d)=>te.jsx("textarea",{className:Ms("w-full rounded-lg bg-gray-50 border border-gray-200 focus:border-gray-300 focus:ring-0 px-3 py-2 min-h-[38px] text-gray-900 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 leading-6",u),ref:d,...c}));QE.displayName="Textarea";function JE({className:u,...c}){return te.jsxs("svg",{className:Ms("size-4 animate-spin text-gray-400",u),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",role:"status","aria-label":"Loading",...c,children:[te.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),te.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function iM({message:u,className:c="h-full"}){return te.jsx("div",{className:`flex items-center justify-center ${c}`,children:te.jsxs("div",{className:"text-center",children:[te.jsx(JE,{className:"size-6 mx-auto mb-3"}),u&&te.jsx("p",{className:"text-gray-500",children:u})]})})}function oM({variant:u="narrow",speed:c=1,className:d,color:h="muted"}){const g=u==="wide"?48:24,b=24,z={light:"text-gray-300",muted:"text-gray-400",dark:"text-gray-700"}[h];return te.jsx("svg",{width:g,height:b,viewBox:`0 0 ${g} ${b}`,xmlns:"http://www.w3.org/2000/svg",className:Ms("inline-block",z,d),style:{overflow:"hidden"},"aria-label":"Loading",children:te.jsx("g",{children:te.jsx("path",{d:"M-16,12 Q-12,4 -8,12 Q-4,20 0,12 Q4,4 8,12 Q12,20 16,12 Q20,4 24,12 Q28,20 32,12 Q36,4 40,12 Q44,20 48,12 Q52,4 56,12 Q60,20 64,12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:te.jsx("animateTransform",{attributeName:"transform",type:"translate",from:"0 0",to:"16 0",dur:`${c}s`,repeatCount:"indefinite"})})})})}function cM(u){const c=u.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i)||u.match(/^#?([a-f\d])([a-f\d])([a-f\d])$/i);if(!c)return null;let[,d,h,g]=c;return d.length===1&&(d=d+d,h=h+h,g=g+g),[parseInt(d,16),parseInt(h,16),parseInt(g,16)]}function rM(u){const c=u.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);return c?[parseInt(c[1]),parseInt(c[2]),parseInt(c[3])]:null}function sM([u,c,d]){const[h,g,b]=[u,c,d].map(_=>(_=_/255,_<=.03928?_/12.92:Math.pow((_+.055)/1.055,2.4)));return .2126*h+.7152*g+.0722*b}function fM(u){const c=cM(u)||rM(u)||[255,255,255];return sM(c)>.2}function $E(u){return fM(u)?"#121212":"#fafafa"}function dM({onSend:u,disabled:c,placeholder:d="Type your message...",color:h}){const[g,b]=Oe.useState(""),_=Oe.useRef(null);Oe.useEffect(()=>{_.current&&(_.current.style.height="48px",g&&(_.current.style.height=`${Math.min(_.current.scrollHeight,200)}px`))},[g]),Oe.useEffect(()=>{!c&&_.current&&_.current.focus()},[c,g]);const z=j=>{j.preventDefault(),g.trim()&&!c&&(u(g.trim()),b(""))},w=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),z(j))},O=Oe.useMemo(()=>$E(h),[h]);return te.jsxs(te.Fragment,{children:[te.jsx("style",{children:`
258
+ `)}})}};var w6=SD(()=>bE(su([ra({type:at("text-start"),id:ve(),providerMetadata:za.optional()}),ra({type:at("text-delta"),id:ve(),delta:ve(),providerMetadata:za.optional()}),ra({type:at("text-end"),id:ve(),providerMetadata:za.optional()}),ra({type:at("error"),errorText:ve()}),ra({type:at("tool-input-start"),toolCallId:ve(),toolName:ve(),providerExecuted:xn().optional(),dynamic:xn().optional()}),ra({type:at("tool-input-delta"),toolCallId:ve(),inputTextDelta:ve()}),ra({type:at("tool-input-available"),toolCallId:ve(),toolName:ve(),input:Bi(),providerExecuted:xn().optional(),providerMetadata:za.optional(),dynamic:xn().optional()}),ra({type:at("tool-input-error"),toolCallId:ve(),toolName:ve(),input:Bi(),providerExecuted:xn().optional(),providerMetadata:za.optional(),dynamic:xn().optional(),errorText:ve()}),ra({type:at("tool-output-available"),toolCallId:ve(),output:Bi(),providerExecuted:xn().optional(),dynamic:xn().optional(),preliminary:xn().optional()}),ra({type:at("tool-output-error"),toolCallId:ve(),errorText:ve(),providerExecuted:xn().optional(),dynamic:xn().optional()}),ra({type:at("reasoning-start"),id:ve(),providerMetadata:za.optional()}),ra({type:at("reasoning-delta"),id:ve(),delta:ve(),providerMetadata:za.optional()}),ra({type:at("reasoning-end"),id:ve(),providerMetadata:za.optional()}),ra({type:at("source-url"),sourceId:ve(),url:ve(),title:ve().optional(),providerMetadata:za.optional()}),ra({type:at("source-document"),sourceId:ve(),mediaType:ve(),title:ve(),filename:ve().optional(),providerMetadata:za.optional()}),ra({type:at("file"),url:ve(),mediaType:ve(),providerMetadata:za.optional()}),ra({type:iE(u=>typeof u=="string"&&u.startsWith("data-"),{message:'Type must start with "data-"'}),id:ve().optional(),data:Bi(),transient:xn().optional()}),ra({type:at("start-step")}),ra({type:at("finish-step")}),ra({type:at("start"),messageId:ve().optional(),messageMetadata:Bi().optional()}),ra({type:at("finish"),finishReason:z1(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Bi().optional()}),ra({type:at("abort")}),ra({type:at("message-metadata"),messageMetadata:Bi()})])));function D6(u){return u.type.startsWith("data-")}function ME(u,c){if(u===void 0&&c===void 0)return;if(u===void 0)return c;if(c===void 0)return u;const d={...u};for(const h in c)if(Object.prototype.hasOwnProperty.call(c,h)){const g=c[h];if(g===void 0)continue;const b=h in u?u[h]:void 0,_=g!==null&&typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)&&!(g instanceof RegExp),z=b!=null&&typeof b=="object"&&!Array.isArray(b)&&!(b instanceof Date)&&!(b instanceof RegExp);_&&z?d[h]=ME(b,g):d[h]=g}return d}function M6(u){const c=["ROOT"];let d=-1,h=null;function g(w,O,j){switch(w){case'"':{d=O,c.pop(),c.push(j),c.push("INSIDE_STRING");break}case"f":case"t":case"n":{d=O,h=O,c.pop(),c.push(j),c.push("INSIDE_LITERAL");break}case"-":{c.pop(),c.push(j),c.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{d=O,c.pop(),c.push(j),c.push("INSIDE_NUMBER");break}case"{":{d=O,c.pop(),c.push(j),c.push("INSIDE_OBJECT_START");break}case"[":{d=O,c.pop(),c.push(j),c.push("INSIDE_ARRAY_START");break}}}function b(w,O){switch(w){case",":{c.pop(),c.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{d=O,c.pop();break}}}function _(w,O){switch(w){case",":{c.pop(),c.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{d=O,c.pop();break}}}for(let w=0;w<u.length;w++){const O=u[w];switch(c[c.length-1]){case"ROOT":g(O,w,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_KEY");break}case"}":{d=w,c.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{c.pop(),c.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{c.pop(),c.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{g(O,w,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{b(O,w);break}case"INSIDE_STRING":{switch(O){case'"':{c.pop(),d=w;break}case"\\":{c.push("INSIDE_STRING_ESCAPE");break}default:d=w}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{d=w,c.pop();break}default:{d=w,g(O,w,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{c.pop(),c.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{d=w,c.pop();break}default:{d=w;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{g(O,w,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{c.pop(),d=w;break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{d=w;break}case"e":case"E":case"-":case".":break;case",":{c.pop(),c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&b(O,w);break}case"}":{c.pop(),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&b(O,w);break}case"]":{c.pop(),c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w);break}default:{c.pop();break}}break}case"INSIDE_LITERAL":{const Y=u.substring(h,w+1);!"false".startsWith(Y)&&!"true".startsWith(Y)&&!"null".startsWith(Y)?(c.pop(),c[c.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?b(O,w):c[c.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&_(O,w)):d=w;break}}}let z=u.slice(0,d+1);for(let w=c.length-1;w>=0;w--)switch(c[w]){case"INSIDE_STRING":{z+='"';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":{z+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{z+="]";break}case"INSIDE_LITERAL":{const j=u.substring(h,u.length);"true".startsWith(j)?z+="true".slice(j.length):"false".startsWith(j)?z+="false".slice(j.length):"null".startsWith(j)&&(z+="null".slice(j.length))}}return z}async function xE(u){if(u===void 0)return{value:void 0,state:"undefined-input"};let c=await Cg({text:u});return c.success?{value:c.value,state:"successful-parse"}:(c=await Cg({text:M6(u)}),c.success?{value:c.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ug(u){return u.type.startsWith("tool-")}function x6(u){return u.type==="dynamic-tool"}function CE(u){return Ug(u)||x6(u)}function RE(u){return u.type.split("-").slice(1).join("-")}function C6({lastMessage:u,messageId:c}){return{message:u?.role==="assistant"?u:{id:c,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function R6({stream:u,messageMetadataSchema:c,dataPartSchemas:d,runUpdateMessageJob:h,onError:g,onToolCall:b,onData:_}){return u.pipeThrough(new TransformStream({async transform(z,w){await h(async({state:O,write:j})=>{var Y,ae,ne,ce;function re(F){const je=O.message.parts.filter(Ug).find(Te=>Te.toolCallId===F);if(je==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return je}function se(F){const je=O.message.parts.filter(Te=>Te.type==="dynamic-tool").find(Te=>Te.toolCallId===F);if(je==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return je}function ue(F){var Je;const je=O.message.parts.find(qe=>Ug(qe)&&qe.toolCallId===F.toolCallId),Te=F,ie=je;je!=null?(je.state=F.state,ie.input=Te.input,ie.output=Te.output,ie.errorText=Te.errorText,ie.rawInput=Te.rawInput,ie.preliminary=Te.preliminary,ie.providerExecuted=(Je=Te.providerExecuted)!=null?Je:je.providerExecuted,Te.providerMetadata!=null&&je.state==="input-available"&&(je.callProviderMetadata=Te.providerMetadata)):O.message.parts.push({type:`tool-${F.toolName}`,toolCallId:F.toolCallId,state:F.state,input:Te.input,output:Te.output,rawInput:Te.rawInput,errorText:Te.errorText,providerExecuted:Te.providerExecuted,preliminary:Te.preliminary,...Te.providerMetadata!=null?{callProviderMetadata:Te.providerMetadata}:{}})}function Ee(F){var Je,je;const Te=O.message.parts.find(de=>de.type==="dynamic-tool"&&de.toolCallId===F.toolCallId),ie=F,qe=Te;Te!=null?(Te.state=F.state,qe.toolName=F.toolName,qe.input=ie.input,qe.output=ie.output,qe.errorText=ie.errorText,qe.rawInput=(Je=ie.rawInput)!=null?Je:qe.rawInput,qe.preliminary=ie.preliminary,qe.providerExecuted=(je=ie.providerExecuted)!=null?je:Te.providerExecuted,ie.providerMetadata!=null&&Te.state==="input-available"&&(Te.callProviderMetadata=ie.providerMetadata)):O.message.parts.push({type:"dynamic-tool",toolName:F.toolName,toolCallId:F.toolCallId,state:F.state,input:ie.input,output:ie.output,errorText:ie.errorText,preliminary:ie.preliminary,providerExecuted:ie.providerExecuted,...ie.providerMetadata!=null?{callProviderMetadata:ie.providerMetadata}:{}})}async function ye(F){if(F!=null){const Je=O.message.metadata!=null?ME(O.message.metadata,F):F;c!=null&&await dE({value:Je,schema:c}),O.message.metadata=Je}}switch(z.type){case"text-start":{const F={type:"text",text:"",providerMetadata:z.providerMetadata,state:"streaming"};O.activeTextParts[z.id]=F,O.message.parts.push(F),j();break}case"text-delta":{const F=O.activeTextParts[z.id];F.text+=z.delta,F.providerMetadata=(Y=z.providerMetadata)!=null?Y:F.providerMetadata,j();break}case"text-end":{const F=O.activeTextParts[z.id];F.state="done",F.providerMetadata=(ae=z.providerMetadata)!=null?ae:F.providerMetadata,delete O.activeTextParts[z.id],j();break}case"reasoning-start":{const F={type:"reasoning",text:"",providerMetadata:z.providerMetadata,state:"streaming"};O.activeReasoningParts[z.id]=F,O.message.parts.push(F),j();break}case"reasoning-delta":{const F=O.activeReasoningParts[z.id];F.text+=z.delta,F.providerMetadata=(ne=z.providerMetadata)!=null?ne:F.providerMetadata,j();break}case"reasoning-end":{const F=O.activeReasoningParts[z.id];F.providerMetadata=(ce=z.providerMetadata)!=null?ce:F.providerMetadata,F.state="done",delete O.activeReasoningParts[z.id],j();break}case"file":{O.message.parts.push({type:"file",mediaType:z.mediaType,url:z.url}),j();break}case"source-url":{O.message.parts.push({type:"source-url",sourceId:z.sourceId,url:z.url,title:z.title,providerMetadata:z.providerMetadata}),j();break}case"source-document":{O.message.parts.push({type:"source-document",sourceId:z.sourceId,mediaType:z.mediaType,title:z.title,filename:z.filename,providerMetadata:z.providerMetadata}),j();break}case"tool-input-start":{const F=O.message.parts.filter(Ug);O.partialToolCalls[z.toolCallId]={text:"",toolName:z.toolName,index:F.length,dynamic:z.dynamic},z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-streaming",input:void 0,providerExecuted:z.providerExecuted}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-streaming",input:void 0,providerExecuted:z.providerExecuted}),j();break}case"tool-input-delta":{const F=O.partialToolCalls[z.toolCallId];F.text+=z.inputTextDelta;const{value:Je}=await xE(F.text);F.dynamic?Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"input-streaming",input:Je}):ue({toolCallId:z.toolCallId,toolName:F.toolName,state:"input-streaming",input:Je}),j();break}case"tool-input-available":{z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-available",input:z.input,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"input-available",input:z.input,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}),j(),b&&!z.providerExecuted&&await b({toolCall:z});break}case"tool-input-error":{z.dynamic?Ee({toolCallId:z.toolCallId,toolName:z.toolName,state:"output-error",input:z.input,errorText:z.errorText,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}):ue({toolCallId:z.toolCallId,toolName:z.toolName,state:"output-error",input:void 0,rawInput:z.input,errorText:z.errorText,providerExecuted:z.providerExecuted,providerMetadata:z.providerMetadata}),j();break}case"tool-output-available":{if(z.dynamic){const F=se(z.toolCallId);Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"output-available",input:F.input,output:z.output,preliminary:z.preliminary})}else{const F=re(z.toolCallId);ue({toolCallId:z.toolCallId,toolName:RE(F),state:"output-available",input:F.input,output:z.output,providerExecuted:z.providerExecuted,preliminary:z.preliminary})}j();break}case"tool-output-error":{if(z.dynamic){const F=se(z.toolCallId);Ee({toolCallId:z.toolCallId,toolName:F.toolName,state:"output-error",input:F.input,errorText:z.errorText,providerExecuted:z.providerExecuted})}else{const F=re(z.toolCallId);ue({toolCallId:z.toolCallId,toolName:RE(F),state:"output-error",input:F.input,rawInput:F.rawInput,errorText:z.errorText,providerExecuted:z.providerExecuted})}j();break}case"start-step":{O.message.parts.push({type:"step-start"});break}case"finish-step":{O.activeTextParts={},O.activeReasoningParts={};break}case"start":{z.messageId!=null&&(O.message.id=z.messageId),await ye(z.messageMetadata),(z.messageId!=null||z.messageMetadata!=null)&&j();break}case"finish":{z.finishReason!=null&&(O.finishReason=z.finishReason),await ye(z.messageMetadata),z.messageMetadata!=null&&j();break}case"message-metadata":{await ye(z.messageMetadata),z.messageMetadata!=null&&j();break}case"error":{g?.(new Error(z.errorText));break}default:if(D6(z)){d?.[z.type]!=null&&await dE({value:z.data,schema:d[z.type]});const F=z;if(F.transient){_?.(F);break}const Je=F.id!=null?O.message.parts.find(je=>F.type===je.type&&F.id===je.id):void 0;Je!=null?Je.data=F.data:O.message.parts.push(F),_?.(F),j()}}w.enqueue(z)})}}))}async function U6({stream:u,onError:c}){const d=u.getReader();try{for(;;){const{done:h}=await d.read();if(h)break}}catch(h){c?.(h)}finally{d.releaseLock()}}im({prefix:"aitxt",size:24}),im({prefix:"aiobj",size:24});var N6=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(u){return new Promise((c,d)=>{this.queue.push(async()=>{try{await u(),c()}catch(h){d(h)}}),this.processQueue()})}};im({prefix:"aiobj",size:24});var Z6={};g6(Z6,{object:()=>j6,text:()=>H6});var H6=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:u}){return{partial:u}},async parseOutput({text:u}){return u}}),j6=({schema:u})=>{const c=m6(u);return{type:"object",responseFormat:{type:"json",schema:c.jsonSchema},async parsePartial({text:d}){const h=await xE(d);switch(h.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:h.value};default:{const g=h.state;throw new Error(`Unsupported parse state: ${g}`)}}},async parseOutput({text:d},h){const g=await Cg({text:d});if(!g.success)throw new zE({message:"No object generated: could not parse the response.",cause:g.error,text:d,response:h.response,usage:h.usage,finishReason:h.finishReason});const b=await A1({value:g.value,schema:c});if(!b.success)throw new zE({message:"No object generated: response did not match schema.",cause:b.error,text:d,response:h.response,usage:h.usage,finishReason:h.finishReason});return b.value}}};async function B6(u){if(u==null)return[];if(!globalThis.FileList||!(u instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(u).map(async c=>{const{name:d,type:h}=c,g=await new Promise((b,_)=>{const z=new FileReader;z.onload=w=>{var O;b((O=w.target)==null?void 0:O.result)},z.onerror=w=>_(w),z.readAsDataURL(c)});return{type:"file",mediaType:h,filename:d,url:g}}))}var q6=class{constructor({api:u="/api/chat",credentials:c,headers:d,body:h,fetch:g,prepareSendMessagesRequest:b,prepareReconnectToStreamRequest:_}){this.api=u,this.credentials=c,this.headers=d,this.body=h,this.fetch=g,this.prepareSendMessagesRequest=b,this.prepareReconnectToStreamRequest=_}async sendMessages({abortSignal:u,...c}){var d,h,g,b,_;const z=await wd(this.body),w=await wd(this.headers),O=await wd(this.credentials),j={...Ds(w),...Ds(c.headers)},Y=await((d=this.prepareSendMessagesRequest)==null?void 0:d.call(this,{api:this.api,id:c.chatId,messages:c.messages,body:{...z,...c.body},headers:j,credentials:O,requestMetadata:c.metadata,trigger:c.trigger,messageId:c.messageId})),ae=(h=Y?.api)!=null?h:this.api,ne=Y?.headers!==void 0?Ds(Y.headers):j,ce=Y?.body!==void 0?Y.body:{...z,...c.body,id:c.chatId,messages:c.messages,trigger:c.trigger,messageId:c.messageId},re=(g=Y?.credentials)!=null?g:O,ue=await((b=this.fetch)!=null?b:globalThis.fetch)(ae,{method:"POST",headers:sE({"Content-Type":"application/json",...ne},`ai-sdk/${TE}`,rE()),body:JSON.stringify(ce),credentials:re,signal:u});if(!ue.ok)throw new Error((_=await ue.text())!=null?_:"Failed to fetch the chat response.");if(!ue.body)throw new Error("The response body is empty.");return this.processResponseStream(ue.body)}async reconnectToStream(u){var c,d,h,g,b;const _=await wd(this.body),z=await wd(this.headers),w=await wd(this.credentials),O={...Ds(z),...Ds(u.headers)},j=await((c=this.prepareReconnectToStreamRequest)==null?void 0:c.call(this,{api:this.api,id:u.chatId,body:{..._,...u.body},headers:O,credentials:w,requestMetadata:u.metadata})),Y=(d=j?.api)!=null?d:`${this.api}/${u.chatId}/stream`,ae=j?.headers!==void 0?Ds(j.headers):O,ne=(h=j?.credentials)!=null?h:w,re=await((g=this.fetch)!=null?g:globalThis.fetch)(Y,{method:"GET",headers:sE(ae,`ai-sdk/${TE}`,rE()),credentials:ne});if(re.status===204)return null;if(!re.ok)throw new Error((b=await re.text())!=null?b:"Failed to fetch the chat response.");if(!re.body)throw new Error("The response body is empty.");return this.processResponseStream(re.body)}},UE=class extends q6{constructor(u={}){super(u)}processResponseStream(u){return zD({stream:u,schema:w6}).pipeThrough(new TransformStream({async transform(c,d){if(!c.success)throw c.error;d.enqueue(c.value)}}))}},Y6=class{constructor({generateId:u=hD,id:c=u(),transport:d=new UE,messageMetadataSchema:h,dataPartSchemas:g,state:b,onError:_,onToolCall:z,onFinish:w,onData:O,sendAutomaticallyWhen:j}){this.activeResponse=void 0,this.jobExecutor=new N6,this.sendMessage=async(Y,ae)=>{var ne,ce,re,se;if(Y==null){await this.makeRequest({trigger:"submit-message",messageId:(ne=this.lastMessage)==null?void 0:ne.id,...ae});return}let ue;if("text"in Y||"files"in Y?ue={parts:[...Array.isArray(Y.files)?Y.files:await B6(Y.files),..."text"in Y&&Y.text!=null?[{type:"text",text:Y.text}]:[]]}:ue=Y,Y.messageId!=null){const Ee=this.state.messages.findIndex(ye=>ye.id===Y.messageId);if(Ee===-1)throw new Error(`message with id ${Y.messageId} not found`);if(this.state.messages[Ee].role!=="user")throw new Error(`message with id ${Y.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,Ee+1),this.state.replaceMessage(Ee,{...ue,id:Y.messageId,role:(ce=ue.role)!=null?ce:"user",metadata:Y.metadata})}else this.state.pushMessage({...ue,id:(re=ue.id)!=null?re:this.generateId(),role:(se=ue.role)!=null?se:"user",metadata:Y.metadata});await this.makeRequest({trigger:"submit-message",messageId:Y.messageId,...ae})},this.regenerate=async({messageId:Y,...ae}={})=>{const ne=Y==null?this.state.messages.length-1:this.state.messages.findIndex(ce=>ce.id===Y);if(ne===-1)throw new Error(`message ${Y} not found`);this.state.messages=this.state.messages.slice(0,this.messages[ne].role==="assistant"?ne:ne+1),await this.makeRequest({trigger:"regenerate-message",messageId:Y,...ae})},this.resumeStream=async(Y={})=>{await this.makeRequest({trigger:"resume-stream",...Y})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:Y="output-available",tool:ae,toolCallId:ne,output:ce,errorText:re})=>this.jobExecutor.run(async()=>{var se,ue;const Ee=this.state.messages,ye=Ee[Ee.length-1];this.state.replaceMessage(Ee.length-1,{...ye,parts:ye.parts.map(F=>CE(F)&&F.toolCallId===ne?{...F,state:Y,output:ce,errorText:re}:F)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(F=>CE(F)&&F.toolCallId===ne?{...F,state:Y,output:ce,errorText:re}:F)),this.status!=="streaming"&&this.status!=="submitted"&&((se=this.sendAutomaticallyWhen)!=null&&se.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(ue=this.lastMessage)==null?void 0:ue.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var Y;this.status!=="streaming"&&this.status!=="submitted"||(Y=this.activeResponse)!=null&&Y.abortController&&this.activeResponse.abortController.abort()},this.id=c,this.transport=d,this.generateId=u,this.messageMetadataSchema=h,this.dataPartSchemas=g,this.state=b,this.onError=_,this.onToolCall=z,this.onFinish=w,this.onData=O,this.sendAutomaticallyWhen=j}get status(){return this.state.status}setStatus({status:u,error:c}){this.status!==u&&(this.state.status=u,this.state.error=c)}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(u){this.state.messages=u}async makeRequest({trigger:u,metadata:c,headers:d,body:h,messageId:g}){var b,_,z,w;this.setStatus({status:"submitted",error:void 0});const O=this.lastMessage;let j=!1,Y=!1,ae=!1;try{const ne={state:C6({lastMessage:this.state.snapshot(O),messageId:this.generateId()}),abortController:new AbortController};ne.abortController.signal.addEventListener("abort",()=>{j=!0}),this.activeResponse=ne;let ce;if(u==="resume-stream"){const se=await this.transport.reconnectToStream({chatId:this.id,metadata:c,headers:d,body:h});if(se==null){this.setStatus({status:"ready"});return}ce=se}else ce=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:ne.abortController.signal,metadata:c,headers:d,body:h,trigger:u,messageId:g});const re=se=>this.jobExecutor.run(()=>se({state:ne.state,write:()=>{var ue;this.setStatus({status:"streaming"}),ne.state.message.id===((ue=this.lastMessage)==null?void 0:ue.id)?this.state.replaceMessage(this.state.messages.length-1,ne.state.message):this.state.pushMessage(ne.state.message)}}));await U6({stream:R6({stream:ce,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:re,onError:se=>{throw se}}),onError:se=>{throw se}}),this.setStatus({status:"ready"})}catch(ne){if(j||ne.name==="AbortError")return j=!0,this.setStatus({status:"ready"}),null;ae=!0,ne instanceof TypeError&&(ne.message.toLowerCase().includes("fetch")||ne.message.toLowerCase().includes("network"))&&(Y=!0),this.onError&&ne instanceof Error&&this.onError(ne),this.setStatus({status:"error",error:ne})}finally{try{(_=this.onFinish)==null||_.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:j,isDisconnect:Y,isError:ae,finishReason:(b=this.activeResponse)==null?void 0:b.state.finishReason})}catch(ne){console.error(ne)}this.activeResponse=void 0}(z=this.sendAutomaticallyWhen)!=null&&z.call(this,{messages:this.state.messages})&&!ae&&await this.makeRequest({trigger:"submit-message",messageId:(w=this.lastMessage)==null?void 0:w.id,metadata:c,headers:d,body:h})}},C1,NE;function L6(){if(NE)return C1;NE=1;function u(c,d){if(typeof c!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof c}\`.`);let h,g=0;return function(..._){clearTimeout(h);const z=Date.now(),w=z-g,O=d-w;O<=0?(g=z,c.apply(this,_)):h=setTimeout(()=>{g=Date.now(),c.apply(this,_)},O)}}return C1=u,C1}var V6=L6();const G6=fA(V6);var ZE=(u,c,d)=>{if(!c.has(u))throw TypeError("Cannot "+d)},Ft=(u,c,d)=>(ZE(u,c,"read from private field"),d?d.call(u):c.get(u)),qi=(u,c,d)=>{if(c.has(u))throw TypeError("Cannot add the same private member more than once");c instanceof WeakSet?c.add(u):c.set(u,d)},$c=(u,c,d,h)=>(ZE(u,c,"write to private field"),c.set(u,d),d);function X6(u,c){return c!=null?G6(u,c):u}var fu,Ng,Zg,cm,rm,sm,Dd,R1,U1,Q6=class{constructor(u=[]){qi(this,fu,void 0),qi(this,Ng,"ready"),qi(this,Zg,void 0),qi(this,cm,new Set),qi(this,rm,new Set),qi(this,sm,new Set),this.pushMessage=c=>{$c(this,fu,Ft(this,fu).concat(c)),Ft(this,Dd).call(this)},this.popMessage=()=>{$c(this,fu,Ft(this,fu).slice(0,-1)),Ft(this,Dd).call(this)},this.replaceMessage=(c,d)=>{$c(this,fu,[...Ft(this,fu).slice(0,c),this.snapshot(d),...Ft(this,fu).slice(c+1)]),Ft(this,Dd).call(this)},this.snapshot=c=>structuredClone(c),this["~registerMessagesCallback"]=(c,d)=>{const h=d?X6(c,d):c;return Ft(this,cm).add(h),()=>{Ft(this,cm).delete(h)}},this["~registerStatusCallback"]=c=>(Ft(this,rm).add(c),()=>{Ft(this,rm).delete(c)}),this["~registerErrorCallback"]=c=>(Ft(this,sm).add(c),()=>{Ft(this,sm).delete(c)}),qi(this,Dd,()=>{Ft(this,cm).forEach(c=>c())}),qi(this,R1,()=>{Ft(this,rm).forEach(c=>c())}),qi(this,U1,()=>{Ft(this,sm).forEach(c=>c())}),$c(this,fu,u)}get status(){return Ft(this,Ng)}set status(u){$c(this,Ng,u),Ft(this,R1).call(this)}get error(){return Ft(this,Zg)}set error(u){$c(this,Zg,u),Ft(this,U1).call(this)}get messages(){return Ft(this,fu)}set messages(u){$c(this,fu,[...u]),Ft(this,Dd).call(this)}};fu=new WeakMap,Ng=new WeakMap,Zg=new WeakMap,cm=new WeakMap,rm=new WeakMap,sm=new WeakMap,Dd=new WeakMap,R1=new WeakMap,U1=new WeakMap;var Md,HE=class extends Y6{constructor({messages:c,...d}){const h=new Q6(c);super({...d,state:h}),qi(this,Md,void 0),this["~registerMessagesCallback"]=(g,b)=>Ft(this,Md)["~registerMessagesCallback"](g,b),this["~registerStatusCallback"]=g=>Ft(this,Md)["~registerStatusCallback"](g),this["~registerErrorCallback"]=g=>Ft(this,Md)["~registerErrorCallback"](g),$c(this,Md,h)}};Md=new WeakMap;function J6({experimental_throttle:u,resume:c=!1,...d}={}){const h=Oe.useRef("chat"in d?d.chat:new HE(d));("chat"in d&&d.chat!==h.current||"id"in d&&h.current.id!==d.id)&&(h.current="chat"in d?d.chat:new HE(d));const b=Oe.useCallback(j=>h.current["~registerMessagesCallback"](j,u),[u,h.current.id]),_=Oe.useSyncExternalStore(b,()=>h.current.messages,()=>h.current.messages),z=Oe.useSyncExternalStore(h.current["~registerStatusCallback"],()=>h.current.status,()=>h.current.status),w=Oe.useSyncExternalStore(h.current["~registerErrorCallback"],()=>h.current.error,()=>h.current.error),O=Oe.useCallback(j=>{typeof j=="function"&&(j=j(h.current.messages)),h.current.messages=j},[h]);return Oe.useEffect(()=>{c&&h.current.resumeStream()},[c,h]),{id:h.current.id,messages:_,setMessages:O,sendMessage:h.current.sendMessage,regenerate:h.current.regenerate,clearError:h.current.clearError,stop:h.current.stop,error:w,resumeStream:h.current.resumeStream,status:z,addToolResult:h.current.addToolOutput,addToolOutput:h.current.addToolOutput}}const fn=[];for(let u=0;u<256;++u)fn.push((u+256).toString(16).slice(1));function $6(u,c=0){return(fn[u[c+0]]+fn[u[c+1]]+fn[u[c+2]]+fn[u[c+3]]+"-"+fn[u[c+4]]+fn[u[c+5]]+"-"+fn[u[c+6]]+fn[u[c+7]]+"-"+fn[u[c+8]]+fn[u[c+9]]+"-"+fn[u[c+10]]+fn[u[c+11]]+fn[u[c+12]]+fn[u[c+13]]+fn[u[c+14]]+fn[u[c+15]]).toLowerCase()}let N1;const k6=new Uint8Array(16);function K6(){if(!N1){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");N1=crypto.getRandomValues.bind(crypto)}return N1(k6)}const jE={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function I6(u,c,d){u=u||{};const h=u.random??u.rng?.()??K6();if(h.length<16)throw new Error("Random bytes length must be >= 16");return h[6]=h[6]&15|64,h[8]=h[8]&63|128,$6(h)}function F6(u,c,d){return jE.randomUUID&&!u?jE.randomUUID():I6(u)}const Z1="http://localhost:3000",W6=Ea({role:z1(["user","assistant"]),content:ve()}),P6=Ea({sessionId:ve(),welcomeMessages:Jc(ve()).nullable().optional(),messages:Jc(W6).nullable().optional(),completed:xn().default(!1),name:ve(),color:ve(),imageUrl:ve().nullable(),formData:S1().nullable(),maxMessages:I_(),formFields:S1()}),BE=Ea({session:P6,token:ve()}),qE=Ea({success:xn(),message:ve(),data:S1().nullable()}),eM={session:null,token:null,isLoading:!0,isFetching:!1,error:null,refetch:async()=>{}},H1=Oe.createContext(eM);function tM({projectId:u,children:c}){const[d,h]=Oe.useState(!0),[g,b]=Oe.useState(!1),[_,z]=Oe.useState(null),[w,O]=Oe.useState(null),[j,Y]=Oe.useState(null),ae=Oe.useEffectEvent(async()=>{const re=new URL(`${Z1}/session/new?project_id=${u}`),se=await fetch(re.toString()),ue=await se.json();if(!se.ok)throw new Error(ue.error);const{success:Ee,data:ye}=BE.safeParse(ue);if(!Ee)throw console.error("Invalid session data: ",_),new Error("Invalid session data");return localStorage.setItem(`th__token_${ye.session.sessionId}`,ye.token??""),Y(ye.token??""),ye.session}),ne=Oe.useEffectEvent(async re=>{const se=new URL(`${Z1}/session`),ue=await fetch(se.toString(),{headers:{Authorization:`Bearer ${re}`}}),Ee=await ue.json();if(!ue.ok)throw new Error(Ee.error);const{success:ye,data:F}=BE.safeParse(Ee);if(!ye)throw console.error("Invalid session data: ",_),new Error("Invalid session data");return F}),ce=Oe.useCallback(async()=>{b(!0);try{const re=localStorage.getItem(`th__token_${u}`);let se=null;if(re)try{const{session:ue}=await ne(re);Y(re),se=ue}catch{console.warn("Failed to get session, creating new one"),se=await ae()}else se=await ae();O(se)}catch(re){console.error(re),z(re)}finally{h(!1),b(!1)}},[u]);return Oe.useEffect(()=>{ce()},[]),te.jsx(H1.Provider,{value:{session:w,token:j,isLoading:d,isFetching:g,error:_,refetch:ce},children:c})}function YE(){const u=Oe.useContext(H1);if(!u)throw new Error("useSession must be used within a SessionProvider");if(!u.session||!u.token)throw new Error("Session not found");return{session:u.session,token:u.token,refetch:u.refetch}}function aM(){const u=Oe.useContext(H1);if(!u)throw new Error("useMaybeSession must be used within a SessionProvider");return u}const LE=Oe.createContext(null);function nM(){const u=Oe.useContext(LE);if(!u)throw new Error("useChatContext must be used within a ChatProvider");return u}function VE({children:u}){const{token:c,session:{sessionId:d,messages:h}}=YE(),{messages:g,setMessages:b,sendMessage:_,status:z,error:w}=J6({transport:new UE({api:`${Z1}/chat`,body:{session_id:d},headers:c?{Authorization:`Bearer ${c}`}:void 0}),messages:h?.map(O=>({id:F6(),role:O.role,content:O.content,parts:[{type:"text",text:O.content}],metadata:{isLoading:!1}}))});return te.jsx(LE.Provider,{value:{messages:g,setMessages:b,sendMessage:_,status:z,error:w??null},children:u})}function lM(u){if(u.includes("email"))return"your@email.com";if(u.includes("website")||u.includes("portfolio")||u.includes("github")||u.includes("url")||u.includes("twitter")||u.includes("blog"))return"Share a link...";if(u.includes("looking for"))return"What you're looking for...";if(u.includes("great at"))return"Your key strengths...";if(u.includes("avoid"))return"What to avoid...";if(u.includes("location")||u.includes("based"))return"Your location..."}function GE(u){var c,d,h="";if(typeof u=="string"||typeof u=="number")h+=u;else if(typeof u=="object")if(Array.isArray(u)){var g=u.length;for(c=0;c<g;c++)u[c]&&(d=GE(u[c]))&&(h&&(h+=" "),h+=d)}else for(d in u)u[d]&&(h&&(h+=" "),h+=d);return h}function uM(){for(var u,c,d=0,h="",g=arguments.length;d<g;d++)(u=arguments[d])&&(c=GE(u))&&(h&&(h+=" "),h+=c);return h}function Ms(...u){return uM(u)}const XE=h2.forwardRef(({className:u,size:c="default",...d},h)=>{const g={sm:"h-8 px-3 text-xs",default:"h-9 px-4",icon:"h-9 w-9 rounded-lg"};return te.jsx("button",{className:Ms("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g[c],u),ref:h,...d})});XE.displayName="Button";const QE=h2.forwardRef(({className:u,...c},d)=>te.jsx("textarea",{className:Ms("w-full rounded-lg bg-gray-50 border border-gray-200 focus:border-gray-300 focus:ring-0 px-3 py-2 min-h-[38px] text-gray-900 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 leading-6",u),ref:d,...c}));QE.displayName="Textarea";function JE({className:u,...c}){return te.jsxs("svg",{className:Ms("size-4 animate-spin text-gray-400",u),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",role:"status","aria-label":"Loading",...c,children:[te.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),te.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function iM({message:u,className:c="h-full"}){return te.jsx("div",{className:`flex items-center justify-center ${c}`,children:te.jsxs("div",{className:"text-center",children:[te.jsx(JE,{className:"size-6 mx-auto mb-3"}),u&&te.jsx("p",{className:"text-gray-500",children:u})]})})}function oM({variant:u="narrow",speed:c=1,className:d,color:h="muted"}){const g=u==="wide"?48:24,b=24,z={light:"text-gray-300",muted:"text-gray-400",dark:"text-gray-700"}[h];return te.jsx("svg",{width:g,height:b,viewBox:`0 0 ${g} ${b}`,xmlns:"http://www.w3.org/2000/svg",className:Ms("inline-block",z,d),style:{overflow:"hidden"},"aria-label":"Loading",children:te.jsx("g",{children:te.jsx("path",{d:"M-16,12 Q-12,4 -8,12 Q-4,20 0,12 Q4,4 8,12 Q12,20 16,12 Q20,4 24,12 Q28,20 32,12 Q36,4 40,12 Q44,20 48,12 Q52,4 56,12 Q60,20 64,12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:te.jsx("animateTransform",{attributeName:"transform",type:"translate",from:"0 0",to:"16 0",dur:`${c}s`,repeatCount:"indefinite"})})})})}function cM(u){const c=u.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i)||u.match(/^#?([a-f\d])([a-f\d])([a-f\d])$/i);if(!c)return null;let[,d,h,g]=c;return d.length===1&&(d=d+d,h=h+h,g=g+g),[parseInt(d,16),parseInt(h,16),parseInt(g,16)]}function rM(u){const c=u.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);return c?[parseInt(c[1]),parseInt(c[2]),parseInt(c[3])]:null}function sM([u,c,d]){const[h,g,b]=[u,c,d].map(_=>(_=_/255,_<=.03928?_/12.92:Math.pow((_+.055)/1.055,2.4)));return .2126*h+.7152*g+.0722*b}function fM(u){const c=cM(u)||rM(u)||[255,255,255];return sM(c)>.2}function $E(u){return fM(u)?"#121212":"#fafafa"}function dM({onSend:u,disabled:c,placeholder:d="Type your message...",color:h}){const[g,b]=Oe.useState(""),_=Oe.useRef(null);Oe.useEffect(()=>{_.current&&(_.current.style.height="48px",g&&(_.current.style.height=`${Math.min(_.current.scrollHeight,200)}px`))},[g]),Oe.useEffect(()=>{!c&&_.current&&_.current.focus()},[c,g]);const z=j=>{j.preventDefault(),g.trim()&&!c&&(u(g.trim()),b(""))},w=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),z(j))},O=Oe.useMemo(()=>$E(h),[h]);return te.jsxs(te.Fragment,{children:[te.jsx("style",{children:`
259
259
  @keyframes bounceIn {
260
260
  0% {
261
261
  opacity: 0;
@@ -335,4 +335,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
335
335
  animation: slideUp 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) both;
336
336
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
337
337
  }
338
- `}),te.jsxs("div",{className:"h-full flex flex-col pt-4",children:[te.jsx("div",{ref:je,className:"flex-1 overflow-y-auto",children:te.jsxs("div",{className:"max-w-xl mx-auto px-4 pt-8 pb-4",children:[w&&te.jsx("div",{className:"flex justify-center py-8",children:te.jsx("img",{src:w,alt:"Avatar",className:"h-8 logo-enter rounded-full"})}),te.jsx(yM,{messages:ce,isLoading:ye,color:h})]})}),Y&&te.jsx("div",{className:"shrink-0 bg-background ",children:te.jsx(dM,{onSend:Je,disabled:ye||!Y||O||ce.length>=z,placeholder:O?"Conversation ended.":ce.length>=z?"Max chat length reached.":Te,color:h})})]})]})}function KE({error:u,onRetry:c}){return te.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:te.jsxs("div",{className:"text-center",children:[te.jsx("div",{className:"w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4",children:te.jsx(vA,{className:"w-6 h-6 text-red-600"})}),te.jsx("p",{className:"text-red-600 font-medium mb-1",children:"Failed to load chat"}),te.jsx("p",{className:"text-gray-500 text-sm mb-4",children:u.message}),c&&te.jsx("button",{onClick:c,className:"px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500",children:"Try Again"})]})})}function IE(){return te.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:te.jsxs("div",{className:"text-center",children:[te.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:te.jsx(_2,{className:"w-6 h-6 text-gray-400"})}),te.jsx("p",{className:"text-gray-600 font-medium mb-1",children:"Chat unavailable"}),te.jsx("p",{className:"text-gray-500 text-sm",children:"Unable to start a session"})]})})}function FE({projectId:u,type:c="bubble",onFormUpdated:d,onReady:h,onSubmit:g,onError:b}){return te.jsx(tM,{projectId:u,children:te.jsx(gM,{projectId:u,type:c,onFormUpdated:d,onReady:h,onSubmit:g,onError:b})})}function gM({type:u="bubble",onFormUpdated:c,onReady:d,onSubmit:h,onError:g}){const{session:b,isLoading:_,error:z,refetch:w}=aM(),O=Oe.useRef(!1);Oe.useEffect(()=>{b&&d&&!O.current&&(d({sessionId:b.sessionId,completed:b.completed??!1,messages:b.messages??[],formData:b.formData??null}),O.current=!0)},[b]),Oe.useEffect(()=>{z&&(console.error("Error in TrailheadChat:",z),g?.(z))},[z]);const j={onFormUpdated:c,onSubmit:h,onError:g};return u==="bubble"?te.jsx(bM,{...j,isLoading:_,error:z,session:b,onRetry:w}):_?te.jsx(iM,{}):z?te.jsx(KE,{error:z,onRetry:w}):b?te.jsx(vM,{...j},"embedded"):te.jsx(IE,{})}function vM(u){return te.jsx(VE,{children:te.jsx(kE,{...u})})}function bM({isLoading:u,error:c,session:d,onRetry:h,...g}){const[b,_]=Oe.useState(!1);if(u)return null;const z=()=>c?te.jsx(KE,{error:c,onRetry:h}):d?te.jsx(VE,{children:te.jsx(kE,{...g})}):te.jsx(IE,{});return te.jsxs(te.Fragment,{children:[b&&te.jsx("div",{className:"absolute bottom-24 right-5 w-[400px] h-[600px] max-w-[calc(100vw-40px)] max-h-[calc(100vh-140px)] shadow-2xl bg-white rounded-xl z-9999 flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-300",children:z()}),te.jsx("button",{onClick:()=>_(!b),className:"absolute bottom-5 right-5 w-[60px] h-[60px] rounded-full border-none cursor-pointer flex items-center shadow-sm justify-center z-10000 transition-all hover:scale-105 animate-in fade-in zoom-in-50 animate-in fade-in slide-in-from-bottom-4 duration-300",style:{backgroundColor:d?.color??"#252525"},"aria-label":b?"Close chat":"Open chat",children:te.jsxs("div",{className:"relative w-7 h-7",children:[te.jsx(E2,{className:"w-7 h-7 text-white absolute inset-0 transition-all duration-300",style:{opacity:b?1:0,transform:b?"rotate(0deg) scale(1)":"rotate(-90deg) scale(0.5)",pointerEvents:b?"auto":"none"}}),te.jsx(_2,{className:"w-7 h-7 text-white absolute inset-0 transition-all duration-300",style:{opacity:b?0:1,transform:b?"rotate(90deg) scale(0.5)":"rotate(0deg) scale(1)",pointerEvents:b?"none":"auto"}})]})})]})}function WE(u,c){const d=document.getElementById(u);if(!d)throw new Error(`Element with id "${u}" not found`);const h=gA.createRoot(d);return h.render(te.jsx(Oe.StrictMode,{children:te.jsx(FE,{...c})})),{unmount:()=>h.unmount()}}if(typeof window<"u"){const u=document.currentScript;if(u){const c=u.getAttribute("data-project-id"),d=u.getAttribute("data-type")||"bubble",h=u.getAttribute("data-auto-init")!=="false";if(c&&h){const g=document.createElement("div");g.id="trailhead-widget-root",document.body.appendChild(g),WE("trailhead-widget-root",{projectId:c,type:d})}}}ji.TrailheadChat=FE,ji.initTrailheadWidget=WE,Object.defineProperty(ji,Symbol.toStringTag,{value:"Module"})}));
338
+ `}),te.jsxs("div",{className:"h-full flex flex-col pt-4",children:[te.jsx("div",{ref:je,className:"flex-1 overflow-y-auto",children:te.jsxs("div",{className:"max-w-xl mx-auto px-4 pt-8 pb-4",children:[w&&te.jsx("div",{className:"flex justify-center py-8",children:te.jsx("img",{src:w,alt:"Avatar",className:"h-8 logo-enter rounded-full"})}),te.jsx(yM,{messages:ce,isLoading:ye,color:h})]})}),Y&&te.jsx("div",{className:"shrink-0 bg-background ",children:te.jsx(dM,{onSend:Je,disabled:ye||!Y||O||ce.length>=z,placeholder:O?"Conversation ended.":ce.length>=z?"Max chat length reached.":Te,color:h})})]})]})}function KE({error:u,onRetry:c}){return te.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:te.jsxs("div",{className:"text-center",children:[te.jsx(vA,{className:"w-6 h-6 text-red-600"}),te.jsx("p",{className:"text-red-600 font-medium mb-1",children:"Failed to load chat"}),te.jsx("p",{className:"text-gray-500 text-sm mb-4",children:u.message}),c&&te.jsx("button",{onClick:c,className:"px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500",children:"Try Again"})]})})}function IE(){return te.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:te.jsxs("div",{className:"text-center",children:[te.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-4",children:te.jsx(_2,{className:"w-6 h-6 text-gray-400"})}),te.jsx("p",{className:"text-gray-600 font-medium mb-1",children:"Chat unavailable"}),te.jsx("p",{className:"text-gray-500 text-sm",children:"Unable to start a session"})]})})}function FE({projectId:u,type:c="bubble",onFormUpdated:d,onReady:h,onSubmit:g,onError:b}){return te.jsx(tM,{projectId:u,children:te.jsx(gM,{projectId:u,type:c,onFormUpdated:d,onReady:h,onSubmit:g,onError:b})})}function gM({type:u="bubble",onFormUpdated:c,onReady:d,onSubmit:h,onError:g}){const{session:b,isLoading:_,error:z,refetch:w}=aM(),O=Oe.useRef(!1);Oe.useEffect(()=>{b&&d&&!O.current&&(d({sessionId:b.sessionId,completed:b.completed??!1,messages:b.messages??[],formData:b.formData??null}),O.current=!0)},[b]),Oe.useEffect(()=>{z&&(console.error("Error in TrailheadChat:",z),g?.(z))},[z]);const j={onFormUpdated:c,onSubmit:h,onError:g};return u==="bubble"?te.jsx(bM,{...j,isLoading:_,error:z,session:b,onRetry:w}):_?te.jsx(iM,{}):z?te.jsx(KE,{error:z,onRetry:w}):b?te.jsx(vM,{...j},"embedded"):te.jsx(IE,{})}function vM(u){return te.jsx(VE,{children:te.jsx(kE,{...u})})}function bM({isLoading:u,error:c,session:d,onRetry:h,...g}){const[b,_]=Oe.useState(!1);if(u)return null;const z=()=>c?te.jsx(KE,{error:c,onRetry:h}):d?te.jsx(VE,{children:te.jsx(kE,{...g})}):te.jsx(IE,{});return te.jsxs(te.Fragment,{children:[b&&te.jsx("div",{className:"absolute bottom-24 right-5 w-[400px] h-[600px] max-w-[calc(100vw-40px)] max-h-[calc(100vh-140px)] shadow-2xl bg-white rounded-xl z-9999 flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-300",children:z()}),te.jsx("button",{onClick:()=>_(!b),className:"absolute bottom-5 right-5 w-[60px] h-[60px] rounded-full border-none cursor-pointer flex items-center shadow-sm justify-center z-10000 transition-all hover:scale-105 animate-in fade-in zoom-in-50 animate-in fade-in slide-in-from-bottom-4 duration-300",style:{backgroundColor:d?.color??"#252525"},"aria-label":b?"Close chat":"Open chat",children:te.jsxs("div",{className:"relative w-7 h-7",children:[te.jsx(E2,{className:"w-7 h-7 text-white absolute inset-0 transition-all duration-300",style:{opacity:b?1:0,transform:b?"rotate(0deg) scale(1)":"rotate(-90deg) scale(0.5)",pointerEvents:b?"auto":"none"}}),te.jsx(_2,{className:"w-7 h-7 text-white absolute inset-0 transition-all duration-300",style:{opacity:b?0:1,transform:b?"rotate(90deg) scale(0.5)":"rotate(0deg) scale(1)",pointerEvents:b?"none":"auto"}})]})})]})}function WE(u,c){const d=document.getElementById(u);if(!d)throw new Error(`Element with id "${u}" not found`);const h=gA.createRoot(d);return h.render(te.jsx(Oe.StrictMode,{children:te.jsx(FE,{...c})})),{unmount:()=>h.unmount()}}if(typeof window<"u"){const u=document.currentScript;if(u){const c=u.getAttribute("data-project-id"),d=u.getAttribute("data-type")||"bubble",h=u.getAttribute("data-auto-init")!=="false";if(c&&h){const g=document.createElement("div");g.id="trailhead-widget-root",document.body.appendChild(g),WE("trailhead-widget-root",{projectId:c,type:d})}}}ji.TrailheadChat=FE,ji.initTrailheadWidget=WE,Object.defineProperty(ji,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trailheadai/chat",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Embeddable React chat widget for lead qualification",
5
5
  "type": "module",
6
6
  "main": "./dist/widget.umd.js",