@cuadra-ai/uikit 0.1.17 → 0.1.19

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.
@@ -1,40 +1,40 @@
1
- (function(U,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):(U=typeof globalThis!="undefined"?globalThis:U||self,p(U.CuadraUIKit={},U.React,U.React,U.ReactDOM,U.ReactDOM))})(this,(function(U,p,y,ae,Oe){"use strict";var Dx=Object.defineProperty,Ox=Object.defineProperties;var Fx=Object.getOwnPropertyDescriptors;var an=Object.getOwnPropertySymbols;var su=Object.prototype.hasOwnProperty,au=Object.prototype.propertyIsEnumerable;var Ri=(U,p)=>(p=Symbol[U])?p:Symbol.for("Symbol."+U),ou=U=>{throw TypeError(U)},lu=Math.pow,ji=(U,p,y)=>p in U?Dx(U,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):U[p]=y,m=(U,p)=>{for(var y in p||(p={}))su.call(p,y)&&ji(U,y,p[y]);if(an)for(var y of an(p))au.call(p,y)&&ji(U,y,p[y]);return U},E=(U,p)=>Ox(U,Fx(p));var H=(U,p)=>{var y={};for(var ae in U)su.call(U,ae)&&p.indexOf(ae)<0&&(y[ae]=U[ae]);if(U!=null&&an)for(var ae of an(U))p.indexOf(ae)<0&&au.call(U,ae)&&(y[ae]=U[ae]);return y};var T=(U,p,y)=>ji(U,typeof p!="symbol"?p+"":p,y),uu=(U,p,y)=>p.has(U)||ou("Cannot "+y);var De=(U,p,y)=>(uu(U,p,"read from private field"),y?y.call(U):p.get(U)),jt=(U,p,y)=>p.has(U)?ou("Cannot add the same private member more than once"):p instanceof WeakSet?p.add(U):p.set(U,y),Ut=(U,p,y,ae)=>(uu(U,p,"write to private field"),ae?ae.call(U,y):p.set(U,y),y);var P=(U,p,y)=>new Promise((ae,Oe)=>{var Se=me=>{try{J(y.next(me))}catch(Pe){Oe(Pe)}},Fe=me=>{try{J(y.throw(me))}catch(Pe){Oe(Pe)}},J=me=>me.done?ae(me.value):Promise.resolve(me.value).then(Se,Fe);J((y=y.apply(U,p)).next())}),it=function(U,p){this[0]=U,this[1]=p},wr=(U,p,y)=>{var ae=(Fe,J,me,Pe)=>{try{var $t=y[Fe](J),Ht=(J=$t.value)instanceof it,un=$t.done;Promise.resolve(Ht?J[0]:J).then(Ge=>Ht?ae(Fe==="return"?Fe:"next",J[1]?{done:Ge.done,value:Ge.value}:Ge,me,Pe):me({value:Ge,done:un})).catch(Ge=>ae("throw",Ge,me,Pe))}catch(Ge){Pe(Ge)}},Oe=Fe=>Se[Fe]=J=>new Promise((me,Pe)=>ae(Fe,J,me,Pe)),Se={};return y=y.apply(U,p),Se[Ri("asyncIterator")]=()=>Se,Oe("next"),Oe("throw"),Oe("return"),Se};var xt=(U,p,y)=>(p=U[Ri("asyncIterator")])?p.call(U):(U=U[Ri("iterator")](),p={},y=(ae,Oe)=>(Oe=U[ae])&&(p[ae]=Se=>new Promise((Fe,J,me)=>(Se=Oe.call(U,Se),me=Se.done,Promise.resolve(Se.value).then(Pe=>Fe({value:Pe,done:me}),J)))),y("next"),y("return"),p);var We,yt,ze,Kl,fr,Xl,pr,mr,gr,Ql,Zl;var Se=typeof document!="undefined"?document.currentScript:null;function Fe(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const J=Fe(y);const me=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Pe=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),$t=e=>{const t=Pe(e);return t.charAt(0).toUpperCase()+t.slice(1)},Ht=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),un=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Ge={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const du=y.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:s,iconNode:a}=d,o=H(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(E(m({ref:l},Ge),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:Ht("lucide",i)}),!s&&!un(o)&&{"aria-hidden":"true"}),o),[...a.map(([c,f])=>y.createElement(c,f)),...Array.isArray(s)?s:[s]])});const Qe=(e,t)=>{const r=y.forwardRef((a,s)=>{var o=a,{className:n}=o,i=H(o,["className"]);return y.createElement(du,m({ref:s,iconNode:t,className:Ht(`lucide-${me($t(e))}`,`lucide-${e}`,n)},i))});return r.displayName=$t(e),r};const hu=Qe("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const fu=Qe("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const pu=Qe("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const mu=Qe("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const gu=Qe("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const yu=Qe("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const $i=Qe("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const bu=Qe("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const wu=Qe("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);var xu=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var i,s;return((i=n.priority)!=null?i:0)-((s=r.priority)!=null?s:0)}).reduce((r,n)=>{var i;if(n.system&&(r.system?r.system+=`
1
+ (function($,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):($=typeof globalThis!="undefined"?globalThis:$||self,p($.CuadraUIKit={},$.React,$.React,$.ReactDOM,$.ReactDOM))})(this,(function($,p,y,ue,Ne){"use strict";var Qx=Object.defineProperty,Zx=Object.defineProperties;var ev=Object.getOwnPropertyDescriptors;var yn=Object.getOwnPropertySymbols;var vu=Object.prototype.hasOwnProperty,Su=Object.prototype.propertyIsEnumerable;var Xa=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),ku=$=>{throw TypeError($)},_u=Math.pow,Qa=($,p,y)=>p in $?Qx($,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):$[p]=y,m=($,p)=>{for(var y in p||(p={}))vu.call(p,y)&&Qa($,y,p[y]);if(yn)for(var y of yn(p))Su.call(p,y)&&Qa($,y,p[y]);return $},E=($,p)=>Zx($,ev(p));var H=($,p)=>{var y={};for(var ue in $)vu.call($,ue)&&p.indexOf(ue)<0&&(y[ue]=$[ue]);if($!=null&&yn)for(var ue of yn($))p.indexOf(ue)<0&&Su.call($,ue)&&(y[ue]=$[ue]);return y};var C=($,p,y)=>Qa($,typeof p!="symbol"?p+"":p,y),Tu=($,p,y)=>p.has($)||ku("Cannot "+y);var Be=($,p,y)=>(Tu($,p,"read from private field"),y?y.call($):p.get($)),Kt=($,p,y)=>p.has($)?ku("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,y),Gt=($,p,y,ue)=>(Tu($,p,"write to private field"),ue?ue.call($,y):p.set($,y),y);var P=($,p,y)=>new Promise((ue,Ne)=>{var Se=ge=>{try{K(y.next(ge))}catch(Le){Ne(Le)}},ze=ge=>{try{K(y.throw(ge))}catch(Le){Ne(Le)}},K=ge=>ge.done?ue(ge.value):Promise.resolve(ge.value).then(Se,ze);K((y=y.apply($,p)).next())}),lt=function($,p){this[0]=$,this[1]=p},Pr=($,p,y)=>{var ue=(ze,K,ge,Le)=>{try{var Yt=y[ze](K),Xt=(K=Yt.value)instanceof lt,xn=Yt.done;Promise.resolve(Xt?K[0]:K).then(Xe=>Xt?ue(ze==="return"?ze:"next",K[1]?{done:Xe.done,value:Xe.value}:Xe,ge,Le):ge({value:Xe,done:xn})).catch(Xe=>ue("throw",Xe,ge,Le))}catch(Xe){Le(Xe)}},Ne=ze=>Se[ze]=K=>new Promise((ge,Le)=>ue(ze,K,ge,Le)),Se={};return y=y.apply($,p),Se[Xa("asyncIterator")]=()=>Se,Ne("next"),Ne("throw"),Ne("return"),Se};var Mt=($,p,y)=>(p=$[Xa("asyncIterator")])?p.call($):($=$[Xa("iterator")](),p={},y=(ue,Ne)=>(Ne=$[ue])&&(p[ue]=Se=>new Promise((ze,K,ge)=>(Se=Ne.call($,Se),ge=Se.done,Promise.resolve(Se.value).then(Le=>ze({value:Le,done:ge}),K)))),y("next"),y("return"),p);var Ge,Tt,Ue,gu,vr,yu,Sr,kr,_r,bu,wu;var Se=typeof document!="undefined"?document.currentScript:null;function ze(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const K=ze(y);const ge=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Le=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),Yt=e=>{const t=Le(e);return t.charAt(0).toUpperCase()+t.slice(1)},Xt=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),xn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Xe={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Iu=y.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:s}=d,o=H(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(E(m({ref:l},Xe),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:Xt("lucide",a)}),!i&&!xn(o)&&{"aria-hidden":"true"}),o),[...s.map(([c,f])=>y.createElement(c,f)),...Array.isArray(i)?i:[i]])});const Re=(e,t)=>{const r=y.forwardRef((s,i)=>{var o=s,{className:n}=o,a=H(o,["className"]);return y.createElement(Iu,m({ref:i,iconNode:t,className:Xt(`lucide-${ge(Yt(e))}`,`lucide-${e}`,n)},a))});return r.displayName=Yt(e),r};const Eu=Re("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Au=Re("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const ei=Re("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Pu=Re("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const Mu=Re("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const Nu=Re("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const ti=Re("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const Lu=Re("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);const Du=Re("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const ri=Re("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);const Ou=Re("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const vn=Re("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Fu=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,i;return((a=n.priority)!=null?a:0)-((i=r.priority)!=null?i:0)}).reduce((r,n)=>{var a;if(n.system&&(r.system?r.system+=`
2
2
 
3
- ${n.system}`:r.system=n.system),n.tools)for(const[s,a]of Object.entries(n.tools)){const o=(i=r.tools)==null?void 0:i[s];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${s}, but it already exists.`);r.tools||(r.tools={}),r.tools[s]=a}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),cn=class{constructor(){T(this,"_providers",new Set);T(this,"_subscribers",new Set)}getModelContext(){return xu(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},dn=class{constructor(){T(this,"_contextProvider",new cn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},qt=class{constructor(){T(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},vu=e=>e.status.type==="complete",Hi=class extends qt{constructor(){super(...arguments);T(this,"isEditing",!0);T(this,"_attachments",[]);T(this,"_text","");T(this,"_role","user");T(this,"_runConfig",{});T(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(s=>P(this,null,function*(){return vu(s)?s:yield t.send(s)}))):[],n=this.text;this._emptyTextAndAttachments();const i={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(i),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},i=r.add({file:t});if(Symbol.asyncIterator in i)try{for(var s=xt(i),a,o,l;a=!(o=yield s.next()).done;a=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{a&&(o=s.return)&&(yield o.call(s))}finally{if(l)throw l[0]}}else n(yield i);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(s=>s.id===t);if(n===-1)throw new Error("Attachment not found");const i=this._attachments[n];yield r.remove(i),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const i=this._eventSubscribers.get(t);i&&i.delete(r)}}},qi=class extends Hi{constructor(t){super();T(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let Vi=(e,t=21)=>(r=t)=>{let n="",i=r|0;for(;i--;)n+=e[Math.random()*e.length|0];return n};var ut=Vi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Su="__optimistic__",ku=()=>`${Su}${ut()}`,Vt=Symbol("autoStatus"),_u=Object.freeze(Object.assign({type:"running"},{[Vt]:!0})),Tu=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[Vt]:!0})),Cu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[Vt]:!0})),Iu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[Vt]:!0})),Wi=(e,t,r,n,i)=>e&&i?Object.assign({type:"incomplete",reason:"error",error:i},{[Vt]:!0}):e&&t?_u:r?Iu:n?Cu:Tu;function xr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ct={exports:{}},Ji;function Eu(){if(Ji)return ct.exports;Ji=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(c==="ignore"&&f==="ignore")return d;if(c!=="ignore"&&f!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&f==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return i(d,{protoAction:c,constructorAction:f,safe:u&&u.safe})}function i(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const f=c;c=[];for(const h of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"constructor")&&h.constructor!==null&&typeof h.constructor=="object"&&Object.prototype.hasOwnProperty.call(h.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.constructor}for(const g in h){const S=h[g];S&&typeof S=="object"&&c.push(S)}}}return o}function s(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function a(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return ct.exports=s,ct.exports.default=s,ct.exports.parse=s,ct.exports.safeParse=a,ct.exports.scan=i,ct.exports}var Au=Eu();const hn=xr(Au);function Pu(e){const t=["ROOT"];let r=-1,n=null;const i=[];let s;function a(){s!==void 0&&(i.push(JSON.parse(`"${s}"`)),s=void 0)}function o(c,f,h){switch(c){case'"':{r=f,t.pop(),t.push(h),t.push("INSIDE_STRING"),a();break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(h),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(h),t.push("INSIDE_NUMBER"),a();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(h),t.push("INSIDE_NUMBER"),a();break}case"{":{r=f,t.pop(),t.push(h),t.push("INSIDE_OBJECT_START"),a();break}case"[":{r=f,t.pop(),t.push(h),t.push("INSIDE_ARRAY_START"),a();break}}}function l(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop(),s=i.pop();break}}}function u(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{r=f,t.pop(),s=i.pop();break}}}for(let c=0;c<e.length;c++){const f=e[c];switch(t[t.length-1]){case"ROOT":o(f,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}case"}":{r=c,t.pop(),s=i.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),s+=f;break}default:{s+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(f,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,c);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=c,s=i.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=c,t.pop(),s=i.pop();break}default:{r=c,s="0",o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{r=c,t.pop(),s=i.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(s+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"}":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"]":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c);break}default:{t.pop(),s=i.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';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":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?d+="true".slice(h.length):"false".startsWith(h)?d+="false".slice(h.length):"null".startsWith(h)&&(d+="null".slice(h.length))}}return[d,i]}var vr=Symbol("aui.parse-partial-json-object.meta"),Mu=e=>e==null?void 0:e[vr],Sr=e=>{if(e.length===0)return{[vr]:{state:"partial",partialPath:[]}};try{const t=hn.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[vr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=Pu(e),i=hn.parse(r);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[vr]={state:"partial",partialPath:n},i}catch(r){return}}},Gi=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...i]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[s,...a]=t.partialPath;if(n!==s)return"complete";const o=e[n];return Gi(o,{state:"partial",partialPath:a},i)},vt=(e,t)=>{const r=Mu(e);if(!r)throw new Error("unable to determine object state");return Gi(e,r,t.map(String))};function Lu(){return wr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new it(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function fn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=Lu),e}var pn={toResponse(e,t){var r;return new Response(pn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return pn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},mn=function(){let e,t;const r=new Promise((n,i)=>{e=n,t=i});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},Nu=()=>{const e=[];let t=!1,r,n;const i=a=>{a.promise||(a.promise=a.reader.read().then(({done:o,value:l})=>{a.promise=void 0,o?(e.splice(e.indexOf(a),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(a){r=a},pull(){return n=mn(),e.forEach(a=>{i(a)}),n.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(a){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:a.getReader()};e.push(o),i(o)},enqueue(a){this.addStream(new ReadableStream({start(o){o.enqueue(a),o.close()}}))}}},Yi=class{constructor(e){T(this,"_controller");T(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},Ki=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Yi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Yi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),Xi=()=>{let e;return[Ki({start(r){e=r}}),e]},Qi=class{constructor(e){T(this,"_isClosed",!1);T(this,"_mergeTask");T(this,"_argsTextController");this._controller=e;const t=Ki({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},Du=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Qi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Qi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),Ou=()=>{let e;return[Du({start(r){e=r}}),e]},Zi=class{constructor(){T(this,"value",-1)}up(){return++this.value}},Fu=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...i]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(E(m({},t),{path:i}))}})}});var Bu=class extends TransformStream{constructor(e){const t=new Zi,r=new Map;super({transform(n,i){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[s,...a]=n.path;if(s===void 0){i.enqueue(n);return}const o=r.get(s);if(o===void 0)throw new Error("Path not found");i.enqueue(E(m({},n),{path:[o,...a]}))}})}},es=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},ts=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const i=e[n];r.enqueue(E(m({},t),{meta:i}));return}r.enqueue(t)}})}},rs=Vi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),zu=class cu{constructor(t){T(this,"_state");T(this,"_parentId");this._state=t||{merger:Nu(),contentCounter:new Zi}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new Fu(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new Bu(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=Xi();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=Xi();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,i=(o=r.toolCallId)!=null?o:rs(),[s,a]=Ou();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:i},this._parentId&&{parentId:this._parentId}),s),r.argsText!==void 0&&(a.argsText.append(r.argsText),a.argsText.close()),r.args!==void 0&&(a.argsText.append(JSON.stringify(r.args)),a.argsText.close()),r.response!==void 0&&a.setResponse(r.response),a}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new cu(this._state);return r._parentId=t,r}close(){var t,r,n,i;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(i=(n=this._state).closeSubscriber)==null||i.call(n)}};function Ru(e){const t=new zu;return P(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function ns(){const{resolve:e,promise:t}=mn();let r;return[Ru(i=>(r=i,r.__internal_subscribeToClose(e),t)),r]}var ju=class extends TransformStream{constructor(e,t,r){const[n,i]=ns();let s;super({start(o){var l;return s=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,i)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,i)},flush(){return P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,i),i.close(),yield s})}},t,r)}},Wt=(e,t,r)=>{var f,h,g,S,w,b,C;const{role:n,id:i,createdAt:s,attachments:a,status:o,metadata:l}=e,u={id:i!=null?i:t,createdAt:s!=null?s:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=B=>{var I=B,{image:_}=I,F=H(I,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},F),{image:_}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(a!=null&&a.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return E(m({},u),{role:n,content:d.map(_=>{var I,z,j,$,k;const F=_.type;switch(F){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return c(_);case"data":return _;case"tool-call":{const B=_,{parentId:N,messages:M}=B,V=H(B,["parentId","messages"]),R=m(m(E(m({},V),{toolCallId:(I=_.toolCallId)!=null?I:`tool-${ut()}`}),N!==void 0&&{parentId:N}),M!==void 0&&{messages:M});return _.args?E(m({},R),{args:_.args,argsText:(z=_.argsText)!=null?z:JSON.stringify(_.args)}):E(m({},R),{args:($=Sr((j=_.argsText)!=null?j:""))!=null?$:{},argsText:(k=_.argsText)!=null?k:""})}default:{const N=F;throw new Error(`Unsupported assistant message part type: ${N}`)}}}).filter(_=>!!_),status:o!=null?o:r,metadata:m({unstable_state:(f=l==null?void 0:l.unstable_state)!=null?f:null,unstable_annotations:(h=l==null?void 0:l.unstable_annotations)!=null?h:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(S=l==null?void 0:l.custom)!=null?S:{},steps:(w=l==null?void 0:l.steps)!=null?w:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:d.map(_=>{const F=_.type;switch(F){case"text":case"image":case"audio":case"file":return _;default:{const B=F;throw new Error(`Unsupported user message part type: ${B}`)}}}),attachments:a!=null?a:[],metadata:{custom:(b=l==null?void 0:l.custom)!=null?b:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:d,metadata:{custom:(C=l==null?void 0:l.custom)!=null?C:{}}});default:{const _=n;throw new Error(`Unknown message role: ${_}`)}}},gn={fromArray:e=>{const t=e.map(r=>Wt(r,ut(),Wi(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},kr=e=>e.next?kr(e.next):"current"in e?e:null,Uu=class{constructor(e){T(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},is=class{constructor(){T(this,"messages",new Map);T(this,"head",null);T(this,"root",{children:[],next:null});T(this,"_messages",new Uu(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var s;const n=(s=t.prev)!=null?s:this.root,i=e!=null?e:this.root;if(!(r==="relink"&&n===i)){if(r!=="link"&&(n.children=n.children.filter(a=>a!==t.current.id),n.next===t)){const a=n.children.at(-1),o=a?this.messages.get(a):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");i.children=[...i.children,t.current.id],(kr(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;const a=e?e.level+1:0;this.updateLevels(t,a)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let i=t;i;i=i.prev)r[i.level]=i.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const i={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,i),this.performOp(n,i,"link"),this.head===n&&(this.head=i),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=ku();while(this.messages.has(r));return this.addOrUpdateMessage(e,Wt(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const i of r.children){const s=this.messages.get(i);if(!s)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,s,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=kr(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=kr(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const i of n.children){const s=this.messages.get(i);s&&(r(s),this.messages.delete(i))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,i;const e=[];for(const[,s]of this.messages)e.push({message:s.current,parentId:(r=(t=s.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(i=(n=this.head)==null?void 0:n.current.id)!=null?i:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:i,parentId:s}of t)this.addOrUpdateMessage(s,i);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},_r=class{constructor(){T(this,"_subscriptions",new Set);T(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},Ue=Symbol("skip-update"),yn=class extends _r{constructor(t){super();T(this,"_previousStateDirty",!0);T(this,"_previousState");T(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Ue&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},Tr=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const i=this._core.getState(),s=i.isMain,a=i.id;r===s&&n===a||(r=s,n=a,!(e==="switched-to"&&!s)&&(e==="switched-away"&&s||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function $u(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],i=t[r];if(!Object.is(n,i))return!1}return!0}var $e=class extends _r{constructor(t){super();T(this,"_previousState");T(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Ue)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Ue||$u(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Cr=Symbol("innerMessage"),Ir=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
3
+ ${n.system}`:r.system=n.system),n.tools)for(const[i,s]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[i];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);r.tools||(r.tools={}),r.tools[i]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),Sn=class{constructor(){C(this,"_providers",new Set);C(this,"_subscribers",new Set)}getModelContext(){return Fu(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},kn=class{constructor(){C(this,"_contextProvider",new Sn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},Qt=class{constructor(){C(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},Bu=e=>e.status.type==="complete",ni=class extends Qt{constructor(){super(...arguments);C(this,"isEditing",!0);C(this,"_attachments",[]);C(this,"_text","");C(this,"_role","user");C(this,"_runConfig",{});C(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(i=>P(this,null,function*(){return Bu(i)?i:yield t.send(i)}))):[],n=this.text;this._emptyTextAndAttachments();const a={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(a),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},a=r.add({file:t});if(Symbol.asyncIterator in a)try{for(var i=Mt(a),s,o,l;s=!(o=yield i.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=i.return)&&(yield o.call(i))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(i=>i.id===t);if(n===-1)throw new Error("Attachment not found");const a=this._attachments[n];yield r.remove(a),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const a=this._eventSubscribers.get(t);a&&a.delete(r)}}},ai=class extends ni{constructor(t){super();C(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let ii=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var gt=ii("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),zu="__optimistic__",Ru=()=>`${zu}${gt()}`,Zt=Symbol("autoStatus"),ju=Object.freeze(Object.assign({type:"running"},{[Zt]:!0})),Uu=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[Zt]:!0})),$u=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[Zt]:!0})),Hu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[Zt]:!0})),si=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[Zt]:!0}):e&&t?ju:r?Hu:n?$u:Uu;function Mr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yt={exports:{}},oi;function qu(){if(oi)return yt.exports;oi=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(c==="ignore"&&f==="ignore")return d;if(c!=="ignore"&&f!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&f==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return a(d,{protoAction:c,constructorAction:f,safe:u&&u.safe})}function a(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const f=c;c=[];for(const h of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"constructor")&&h.constructor!==null&&typeof h.constructor=="object"&&Object.prototype.hasOwnProperty.call(h.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.constructor}for(const g in h){const S=h[g];S&&typeof S=="object"&&c.push(S)}}}return o}function i(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function s(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return yt.exports=i,yt.exports.default=i,yt.exports.parse=i,yt.exports.safeParse=s,yt.exports.scan=a,yt.exports}var Vu=qu();const _n=Mr(Vu);function Wu(e){const t=["ROOT"];let r=-1,n=null;const a=[];let i;function s(){i!==void 0&&(a.push(JSON.parse(`"${i}"`)),i=void 0)}function o(c,f,h){switch(c){case'"':{r=f,t.pop(),t.push(h),t.push("INSIDE_STRING"),s();break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(h),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(h),t.push("INSIDE_NUMBER"),s();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(h),t.push("INSIDE_NUMBER"),s();break}case"{":{r=f,t.pop(),t.push(h),t.push("INSIDE_OBJECT_START"),s();break}case"[":{r=f,t.pop(),t.push(h),t.push("INSIDE_ARRAY_START"),s();break}}}function l(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop(),i=a.pop();break}}}function u(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=f,t.pop(),i=a.pop();break}}}for(let c=0;c<e.length;c++){const f=e[c];switch(t[t.length-1]){case"ROOT":o(f,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}case"}":{r=c,t.pop(),i=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),i+=f;break}default:{i+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(f,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,c);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=c,i=a.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c,i="0",o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"}":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"]":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c);break}default:{t.pop(),i=a.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';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":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?d+="true".slice(h.length):"false".startsWith(h)?d+="false".slice(h.length):"null".startsWith(h)&&(d+="null".slice(h.length))}}return[d,a]}var Nr=Symbol("aui.parse-partial-json-object.meta"),Ju=e=>e==null?void 0:e[Nr],Lr=e=>{if(e.length===0)return{[Nr]:{state:"partial",partialPath:[]}};try{const t=_n.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Nr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=Wu(e),a=_n.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Nr]={state:"partial",partialPath:n},a}catch(r){return}}},li=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...a]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[i,...s]=t.partialPath;if(n!==i)return"complete";const o=e[n];return li(o,{state:"partial",partialPath:s},a)},Nt=(e,t)=>{const r=Ju(e);if(!r)throw new Error("unable to determine object state");return li(e,r,t.map(String))};function Ku(){return Pr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new lt(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function Tn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=Ku),e}var Cn={toResponse(e,t){var r;return new Response(Cn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return Cn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},In=function(){let e,t;const r=new Promise((n,a)=>{e=n,t=a});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},Gu=()=>{const e=[];let t=!1,r,n;const a=s=>{s.promise||(s.promise=s.reader.read().then(({done:o,value:l})=>{s.promise=void 0,o?(e.splice(e.indexOf(s),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(s){r=s},pull(){return n=In(),e.forEach(s=>{a(s)}),n.promise},cancel(){e.forEach(s=>{s.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(s){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:s.getReader()};e.push(o),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},ui=class{constructor(e){C(this,"_controller");C(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},ci=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new ui(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new ui(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),di=()=>{let e;return[ci({start(r){e=r}}),e]},hi=class{constructor(e){C(this,"_isClosed",!1);C(this,"_mergeTask");C(this,"_argsTextController");this._controller=e;const t=ci({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},Yu=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new hi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new hi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),Xu=()=>{let e;return[Yu({start(r){e=r}}),e]},fi=class{constructor(){C(this,"value",-1)}up(){return++this.value}},Qu=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...a]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(E(m({},t),{path:a}))}})}});var Zu=class extends TransformStream{constructor(e){const t=new fi,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...s]=n.path;if(i===void 0){a.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");a.enqueue(E(m({},n),{path:[o,...s]}))}})}},pi=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},mi=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const a=e[n];r.enqueue(E(m({},t),{meta:a}));return}r.enqueue(t)}})}},gi=ii("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),ec=class Cu{constructor(t){C(this,"_state");C(this,"_parentId");this._state=t||{merger:Gu(),contentCounter:new fi}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new Qu(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new Zu(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=di();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=di();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,a=(o=r.toolCallId)!=null?o:gi(),[i,s]=Xu();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),i),r.argsText!==void 0&&(s.argsText.append(r.argsText),s.argsText.close()),r.args!==void 0&&(s.argsText.append(JSON.stringify(r.args)),s.argsText.close()),r.response!==void 0&&s.setResponse(r.response),s}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new Cu(this._state);return r._parentId=t,r}close(){var t,r,n,a;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(a=(n=this._state).closeSubscriber)==null||a.call(n)}};function tc(e){const t=new ec;return P(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function yi(){const{resolve:e,promise:t}=In();let r;return[tc(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var rc=class extends TransformStream{constructor(e,t,r){const[n,a]=yi();let i;super({start(o){var l;return i=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,a)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,a)},flush(){return P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield i})}},t,r)}},er=(e,t,r)=>{var f,h,g,S,w,b,T;const{role:n,id:a,createdAt:i,attachments:s,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:i!=null?i:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=z=>{var I=z,{image:_}=I,F=H(I,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},F),{image:_}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(s!=null&&s.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return E(m({},u),{role:n,content:d.map(_=>{var I,U,j,R,k;const F=_.type;switch(F){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return c(_);case"data":return _;case"tool-call":{const z=_,{parentId:D,messages:M}=z,W=H(z,["parentId","messages"]),B=m(m(E(m({},W),{toolCallId:(I=_.toolCallId)!=null?I:`tool-${gt()}`}),D!==void 0&&{parentId:D}),M!==void 0&&{messages:M});return _.args?E(m({},B),{args:_.args,argsText:(U=_.argsText)!=null?U:JSON.stringify(_.args)}):E(m({},B),{args:(R=Lr((j=_.argsText)!=null?j:""))!=null?R:{},argsText:(k=_.argsText)!=null?k:""})}default:{const D=F;throw new Error(`Unsupported assistant message part type: ${D}`)}}}).filter(_=>!!_),status:o!=null?o:r,metadata:m({unstable_state:(f=l==null?void 0:l.unstable_state)!=null?f:null,unstable_annotations:(h=l==null?void 0:l.unstable_annotations)!=null?h:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(S=l==null?void 0:l.custom)!=null?S:{},steps:(w=l==null?void 0:l.steps)!=null?w:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:d.map(_=>{const F=_.type;switch(F){case"text":case"image":case"audio":case"file":return _;default:{const z=F;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:s!=null?s:[],metadata:{custom:(b=l==null?void 0:l.custom)!=null?b:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:d,metadata:{custom:(T=l==null?void 0:l.custom)!=null?T:{}}});default:{const _=n;throw new Error(`Unknown message role: ${_}`)}}},En={fromArray:e=>{const t=e.map(r=>er(r,gt(),si(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Dr=e=>e.next?Dr(e.next):"current"in e?e:null,nc=class{constructor(e){C(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},bi=class{constructor(){C(this,"messages",new Map);C(this,"head",null);C(this,"root",{children:[],next:null});C(this,"_messages",new nc(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var i;const n=(i=t.prev)!=null?i:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){if(r!=="link"&&(n.children=n.children.filter(s=>s!==t.current.id),n.next===t)){const s=n.children.at(-1),o=s?this.messages.get(s):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");a.children=[...a.children,t.current.id],(Dr(t)===this.head||a.next===null)&&(a.next=t),t.prev=e;const s=e?e.level+1:0;this.updateLevels(t,s)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let a=t;a;a=a.prev)r[a.level]=a.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const a={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,a),this.performOp(n,a,"link"),this.head===n&&(this.head=a),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=Ru();while(this.messages.has(r));return this.addOrUpdateMessage(e,er(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const a of r.children){const i=this.messages.get(a);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Dr(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=Dr(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const a of n.children){const i=this.messages.get(a);i&&(r(i),this.messages.delete(a))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,a;const e=[];for(const[,i]of this.messages)e.push({message:i.current,parentId:(r=(t=i.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(a=(n=this.head)==null?void 0:n.current.id)!=null?a:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:a,parentId:i}of t)this.addOrUpdateMessage(i,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Or=class{constructor(){C(this,"_subscriptions",new Set);C(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},qe=Symbol("skip-update"),An=class extends Or{constructor(t){super();C(this,"_previousStateDirty",!0);C(this,"_previousState");C(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==qe&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},Fr=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const a=this._core.getState(),i=a.isMain,s=a.id;r===i&&n===s||(r=i,n=s,!(e==="switched-to"&&!i)&&(e==="switched-away"&&i||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function ac(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],a=t[r];if(!Object.is(n,a))return!1}return!0}var Ve=class extends Or{constructor(t){super();C(this,"_previousState");C(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===qe)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===qe||ac(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Br=Symbol("innerMessage"),zr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
4
4
 
5
- `),ss=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},as=class extends ss{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},Hu=class extends as{get source(){return"thread-composer"}},qu=class extends as{get source(){return"edit-composer"}},Vu=class extends ss{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},os=class extends _r{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var a;const s=this.config.binding.getState();s!==t&&(t=s,r==null||r(),r=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,e))},i=this.outerSubscribe(n);return()=>{i==null||i(),r==null||r()}}},ls=Object.freeze([]),us=Object.freeze({}),Wu=e=>{var t,r,n,i,s,a,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(i=e==null?void 0:e.attachments)!=null?i:ls,text:(s=e==null?void 0:e.text)!=null?s:"",role:(a=e==null?void 0:e.role)!=null?a:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:us,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Ju=e=>{var t,r,n,i,s,a,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",attachments:(a=e==null?void 0:e.attachments)!=null?a:ls,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:us,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},cs=class{constructor(e){T(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new os({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Gu=class extends cs{constructor(t){const r=new yn({path:t.path,getState:()=>Wu(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});T(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new Hu(new $e({path:E(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"thread-composer"}):Ue},subscribe:r=>this._core.subscribe(r)}),this._core)}},Yu=class extends cs{constructor(t,r){const n=new yn({path:t.path,getState:()=>Ju(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>n.subscribe(i)});T(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new qu(new $e({path:E(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"edit-composer"}):Ue},subscribe:r=>this._core.subscribe(r)}),this._core)}},Ku=class on{constructor(t=null){T(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>on.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return on.updatePath(t,r.path,()=>r.value);case"append-text":return on.updatePath(t,r.path,i=>{if(typeof i!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return i+r.value});default:{const i=n;throw new Error(`Invalid operation type: ${i}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[i,...s]=r;if(Array.isArray(t)){const o=Number(i);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],s,n),l}const a=m({},t);return a[i]=this.updatePath(a[i],s,n),a}},Xu=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Er=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],i=r(e.parts[n]);return E(m({},e),{parts:[...e.parts.slice(0,n),i,...e.parts.slice(n+1)],get content(){return this.parts}})},Qu=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},Zu=(e,t)=>Er(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),ec=(e,t)=>Er(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),tc=(e,t)=>Er(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const i=r.argsText+t.textDelta,s=(n=Sr(i))!=null?n:r.args;return E(m({},r),{argsText:i,args:s})}else throw new Error("text-delta received but part is neither text nor tool-call")}),rc=(e,t)=>Er(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),ds=(e,t)=>{var n,i;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((i=e.status)==null?void 0:i.reason)==="error")return e;const r=nc(t);return E(m({},e),{status:r})},nc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},ic=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),sc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),ac=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),oc=(e,t)=>{var i;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((i=r[n])==null?void 0:i.state)==="started"?r[n]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:rs(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},lc=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),uc=(e,t)=>{const r=new Ku(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},cc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},dc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:Xu(),i;const s=t?cc(()=>{i==null||i.enqueue(n)}):()=>{i==null||i.enqueue(n)};super({start(a){i=a},transform(a){const o=a.type;switch(o){case"part-start":n=Qu(n,a);break;case"tool-call-args-text-finish":n=Zu(n,a);break;case"part-finish":n=ec(n,a);break;case"text-delta":n=tc(n,a);break;case"result":n=rc(n,a);break;case"message-finish":n=ds(n,a);break;case"annotations":n=ic(n,a);break;case"data":n=sc(n,a);break;case"step-start":n=ac(n,a);break;case"step-finish":n=oc(n,a);break;case"error":n=lc(n,a),r==null||r(a.error);break;case"update-state":n=uc(n,a);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}s()},flush(a){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=ds(n,{finishReason:d?"tool-calls":"unknown"}),a.enqueue(n)}}})}},hc=class extends es{constructor(){super(e=>{const t=new ju({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},fc=class ln{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new ln(t.pipeThrough(new dc))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=xt(this),n,i,s;n=!(i=yield r.next()).done;n=!1){const a=i.value;t=a}}catch(i){s=[i]}finally{try{n&&(i=r.return)&&(yield i.call(r))}finally{if(s)throw s[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return P(this,null,function*(){const{done:n,value:i}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:i}})}}}tee(){const[t,r]=this.readable.tee();return[new ln(t),new ln(r)]}},hs=Symbol.for("aui.tool-response"),st=class Ui{constructor(t){T(this,"artifact");T(this,"result");T(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[hs](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&hs in t}static toResponse(t){return t instanceof Ui?t:new Ui({result:t===void 0?"<no result>":t})}};function pc(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function Jt(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var mc=class{constructor(e,t,r){T(this,"resolve");T(this,"reject");T(this,"disposed",!1);T(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(vt(e,this.fieldPath)==="complete"){const t=Jt(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},fs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=Jt(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),vt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},ps=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=Jt(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}vt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},ms=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=Jt(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];vt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}vt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},gc=class{constructor(e){T(this,"argTextDeltas");T(this,"handles",new Set);T(this,"args",Sr(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const i=Sr(e);if(i!==void 0){this.args=i;for(const s of this.handles)s.update(i)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new mc(t,r,e);if(this.args&&vt(this.args,e)==="complete"){const i=Jt(this.args,e);if(i!==void 0){t(i);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const i=new fs(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof fs){n.dispose(),this.handles.delete(n);break}}});return fn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const i=new ps(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof ps){n.dispose(),this.handles.delete(n);break}}});return fn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const i=new ms(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof ms){n.dispose(),this.handles.delete(n);break}}});return fn(r)}},yc=class{constructor(e){this.promise=e}get(){return this.promise}},bc=class{constructor(){T(this,"args");T(this,"response");T(this,"writable");T(this,"resolve");T(this,"argsText","");T(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new gc(e.readable);const{promise:t,resolve:r}=mn();this.resolve=r,this.response=new yc(t)}appendArgsTextDelta(e){return P(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},wc=class extends es{constructor(e){const t=new Map,r=new Map;super(n=>{const i=new TransformStream({transform(a,o){switch((a.type!=="part-finish"||a.meta.type!=="tool-call")&&o.enqueue(a),a.type){case"part-start":if(a.part.type==="tool-call"){const u=new bc;r.set(a.part.toolCallId,u),e.streamCall({reader:u,toolCallId:a.part.toolCallId,toolName:a.part.toolName})}break;case"text-delta":{if(a.meta.type==="tool-call"){const u=a.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(a.textDelta)}break}case"result":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new st({result:a.result,artifact:a.artifact,isError:a.isError}));break}case"tool-call-args-text-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=a.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let f=!1;const h=pc(()=>{var w;let g;try{g=hn.parse(c.argsText)}catch(b){throw new Error(`Function parameter parsing failed. ${JSON.stringify(b.message)}`)}const S=e.execute({toolCallId:u,toolName:d,args:g});return S!==void 0&&(f=!0,(w=e.onExecutionStart)==null||w.call(e,u,d)),S},g=>{var w;if(f&&((w=e.onExecutionEnd)==null||w.call(e,u,d)),g===void 0)return;const S=new st({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(S),o.enqueue(m({type:"result",path:a.path},S))},g=>{var w;f&&((w=e.onExecutionEnd)==null||w.call(e,u,d));const S=new st({result:String(g),isError:!0});c.setResponse(S),o.enqueue(m({type:"result",path:a.path},S))});h&&t.set(u,h);break}case"part-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(a)}):o.enqueue(a)}}},flush(){return P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new ts).pipeThrough(i)})}},xc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function vc(e,t,r,n){const i=e==null?void 0:e[r.toolName];return!i||!i.execute?void 0:(a=>P(null,null,function*(){var d;if(t.aborted)return new st({result:"Tool execution was cancelled.",isError:!0});let o=a;if(xc(i.parameters)){let c=i.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=i.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new st({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=P(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return st.toResponse(c)});return Promise.race([u,l])}))(i.execute)}function Sc(e,t,r,n,i){var s,a;(a=(s=e==null?void 0:e[n.toolName])==null?void 0:s.streamCall)==null||a.call(s,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>i(n.toolCallId,o)})}function kc(e,t,r,n){const i=typeof e=="function"?e:()=>e,s=typeof t=="function"?t:()=>t;return new wc({execute:a=>vc(i(),s(),a,r),streamCall:l=>{var u=l,{reader:a}=u,o=H(u,["reader"]);return Sc(i(),s(),a,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var gs=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,i=t.toolCallId,s=st.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:i,result:s.result,artifact:s.artifact,isError:s.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Ar=class extends _r{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var a;const s=this.binding.getState();s!==t&&(t=s,r==null||r(),r=(a=this.binding.getState())==null?void 0:a.subscribe(e),e())},i=this.outerSubscribe(n);return()=>{i==null||i(),r==null||r()}}},Pr=Object.freeze({type:"complete"}),_c=(e,t,r)=>{if(e.role!=="assistant")return Pr;if(r.type==="tool-call")return r.result?Pr:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Pr:n?e.status:Pr},ys=(e,t)=>{const r=e.content[t];if(!r)return Ue;const n=_c(e,t,r);return Object.freeze(E(m({},r),{[Cr]:r[Cr],status:n}))},Tc=class{constructor(e,t){T(this,"composer");T(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new Yu(new Ar({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:i=n.runConfig}=e,s=this._core.getState();if(s.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:s.parentId,sourceId:s.id,runConfig:i})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const i=this._threadBinding.getState().getBranches(r.id);let s=t;if(e==="previous"?s=i[r.branchNumber-2]:e==="next"&&(s=i[r.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return Ir(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new gs(new $e({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>ys(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new gs(new $e({path:E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?Ue:ys(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new Vu(new $e({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?E(m({},r),{source:"message"}):Ue},subscribe:t=>this._core.subscribe(t)}))}},Cc=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},Ic=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},Ec=(e,t)=>{var r,n,i,s,a,o,l,u,d,c,f;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(i=t.createdAt)!=null?i:new Date,parentId:(o=(a=t.parentId)!=null?a:(s=e.at(-1))==null?void 0:s.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},Ac=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},bs=class{constructor(e,t){T(this,"_threadBinding");T(this,"composer");T(this,"_eventSubscriptionSubjects",new Map);const r=new $e({path:e.path,getState:()=>Ac(e.getState(),t.getState()),subscribe:n=>{const i=e.subscribe(n),s=t.subscribe(n);return()=>{i(),s()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new Gu(new Ar({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(Ec(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(Ic(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Cc(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,i;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(i=(n=t[e-1])==null?void 0:n.id)!=null?i:null,index:e}})}getMessageById(e){return this._getMessageRuntime(E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new Tc(new $e({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:i}=(d=t())!=null?d:{},{messages:s,speech:a}=this._threadBinding.getState();if(!r||n===void 0||i===void 0)return Ue;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[Cr]:r[Cr],index:i,isLast:((c=s.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(a==null?void 0:a.messageId)===r.id?a:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new os({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Pc=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Mr=(e,t)=>{if(t===void 0)return Ue;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:Ue},Mc=class{constructor(e,t=bs){T(this,"_getState");T(this,"_mainThreadListItemRuntime");T(this,"main");this._core=e,this._runtimeFactory=t;const r=new yn({path:{},getState:()=>Pc(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Tr(new $e({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Mr(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new Ar({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new Ar({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new Tr(new $e({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Mr(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Tr(new $e({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Mr(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Tr(new $e({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Mr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Lc=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",Nc=class{constructor(e){T(this,"accept","*");T(this,"uploadedUrls",new Map);this.cloud=e}add(t){return wr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=Lc(e.type);let i={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield i;try{const{signedUrl:s,publicUrl:a}=yield new it(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new it(fetch(s,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,a),i=E(m({},i),{status:{type:"requires-action",reason:"composer-send"}}),yield i}catch(s){i=E(m({},i),{status:{type:"incomplete",reason:"error"}}),yield i}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],E(m({},e),{status:{type:"complete"},content:r})})}},bn=y.createContext(null),wn=({adapters:e,children:t})=>{const r=y.useContext(bn);return p.jsx(bn.Provider,{value:m(m({},r),e),children:t})},Dc=()=>y.useContext(bn),Oc=class extends Hi{constructor(t,r,{parentId:n,message:i}){var s;super();T(this,"_nonTextParts");T(this,"_previousText");T(this,"_parentId");T(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=i.id,this._previousText=Ir(i),this.setText(this._previousText),this.setRole(i.role),this.setAttachments((s=i.attachments)!=null?s:[]),this._nonTextParts=i.content.filter(a=>a.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return P(this,null,function*(){Ir(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},Fc=class{constructor(e){T(this,"_subscriptions",new Set);T(this,"_isInitialized",!1);T(this,"repository",new is);T(this,"composer",new qi(this));T(this,"_editComposers",new Map);T(this,"_stopSpeaking");T(this,"speech");T(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new Oc(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var s;const r=(s=this.adapters)==null?void 0:s.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:i}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const a=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(i,a)}this._notifySubscribers()}speak(e){var s,a;const t=(s=this.adapters)==null?void 0:s.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(a=this._stopSpeaking)==null||a.call(this);const n=t.speak(Ir(r)),i=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),i(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(gn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,i,s;if(e==="model-context-update")return(s=(i=(n=this._contextProvider).subscribe)==null?void 0:i.call(n,t))!=null?s:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},Bc=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function zc({state:e,getTools:t,onResult:r,setToolStatuses:n}){const i=y.useRef({}),s=y.useRef(new Map),a=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[h,g]=ns(),S=kc(t,()=>{var w,b;return(b=(w=a.current)==null?void 0:w.signal)!=null?b:new AbortController().signal},(w,b)=>new Promise((C,_)=>{const F=s.current.get(w);F&&F.reject(new Error("Human input request was superseded by a new request")),s.current.set(w,{resolve:C,reject:_}),n(B=>E(m({},B),{[w]:{type:"interrupt",payload:{type:"human",payload:b}}}))}),{onExecutionStart:w=>{o.current++,n(b=>E(m({},b),{[w]:{type:"executing"}}))},onExecutionEnd:w=>{o.current--,n(b=>{const C=m({},b);return delete C[w],C}),o.current===0&&(l.current.forEach(b=>b()),l.current=[])}});return h.pipeThrough(S).pipeThrough(new ts).pipeTo(new WritableStream({write(w){var b;if(w.type==="result"){if((b=i.current[w.meta.toolCallId])!=null&&b.hasResult)return;r(m({type:"add-tool-result",toolCallId:w.meta.toolCallId,toolName:w.meta.toolName,result:w.result,isError:w.isError},w.artifact&&{artifact:w.artifact}))}}})),g}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const h=g=>{g.forEach(S=>{S.content.forEach(w=>{if(w.type==="tool-call"){if(c.current)d.current.add(w.toolCallId);else{if(d.current.has(w.toolCallId))return;let b=i.current[w.toolCallId];if(b||(b={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:w.toolName,toolCallId:w.toolCallId})},i.current[w.toolCallId]=b),w.argsText!==b.argsText)if(b.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:b.argsText,next:w.argsText});else{if(!w.argsText.startsWith(b.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${w.argsText} does not start with ${b.argsText}`);const C=w.argsText.slice(b.argsText.length);b.controller.argsText.append(C);const _=Bc(w.argsText);_&&b.controller.argsText.close(),i.current[w.toolCallId]={argsText:w.argsText,hasResult:b.hasResult,argsComplete:_,controller:b.controller}}w.result!==void 0&&!b.hasResult&&(b.controller.setResponse(new st({result:w.result,artifact:w.artifact,isError:w.isError})),b.controller.close(),i.current[w.toolCallId]={hasResult:!0,argsComplete:!0,argsText:b.argsText,controller:b.controller})}w.messages&&h(w.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u,r]);const f=()=>(s.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),s.current.clear(),a.current.abort(),a.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),c.current=!0},abort:f,resume:(h,g)=>{const S=s.current.get(h);if(S)s.current.delete(h),n(w=>E(m({},w),{[h]:{type:"executing"}})),S.resolve(g);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var Rc=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function jc(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,i=t.cells[n];if(i.type!=="effect")throw new Error("Cannot find effect cell");let s=!0;if(i.deps!==void 0&&r.deps!==void 0&&(s=i.deps.length!==r.deps.length||i.deps.some((a,o)=>!Object.is(a,r.deps[o]))),s){if(i.mounted){if(typeof i.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{i.mounted&&i.cleanup&&i.cleanup()}finally{i.mounted=!1}}try{const a=r.effect();if(a!==void 0&&typeof a!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof a}`);i.mounted=!0,i.cleanup=typeof a=="function"?a:void 0,i.deps=r.deps}catch(a){throw a}}})}function Uc(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(i){t==null&&(t=i)}finally{n.mounted=!1}}if(t!=null)throw t}var Gt=null;function $c(e,t){e.currentIndex=0;const r=Gt;Gt=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{Gt=r}}function xn(){if(!Gt)throw new Error("No resource fiber available");return Gt}function ws(e,t){const r=e[xs];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var xs=Symbol("fnSymbol");function Lr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function St(e){e.isMounted=!1,Uc(e)}function Yt(e,t){const r={commitTasks:[],props:t,state:void 0};return $c(e,()=>{e.renderContext=r;try{r.state=ws(e.resource,t)}finally{e.renderContext=void 0}}),r}function kt(e,t){e.isMounted=!0,e.isNeverMounted=!1,jc(t,e)}var Hc=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,vs=Hc?y.useEffect:y.useLayoutEffect;function vn(e){const[,t]=y.useState({}),r=y.useMemo(()=>Lr(e.type,()=>t({})),[e.type,t]),n=Yt(r,e.props);return vs(()=>()=>St(r),[]),vs(()=>{kt(r,n)}),n.state}var _t=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},dt=(e,t,r)=>t===e,Tt,Sn=()=>{if(Tt)return Tt;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Tt=e(),Tt;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Tt=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,Tt=r,r},qc=(We=class{static register(t){var o,l;const r=Sn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,i={api:t,logs:[]},s=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>We.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),We.notifyListeners(n))}),a=(l=t.subscribe)==null?void 0:l.call(t,()=>{We.notifyListeners(n)});return r.apis.set(n,i),We.notifyListeners(n),()=>{const u=Sn();u.apis.get(n)&&(s==null||s(),a==null||a(),u.apis.delete(n),We.notifyListeners(n))}}static notifyListeners(t){Sn().listeners.forEach(n=>n(t))}},T(We,"MAX_EVENT_LOGS_PER_API",200),We);function oe(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[xs]=e,t}var Vc=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function Wc(e){const t=xn(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const s={type:"state",value:typeof e=="function"?e():e,set:a=>{const o=s.value,l=typeof a=="function"?a(o):a;Object.is(o,l)||(s.value=l,Vc(t))}};t.cells[r]=s}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function Ye(e){const t=Wc(e);return[t.value,t.set]}function Jc(){const e=xn(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function ke(e,t){const r=xn(),n=Jc();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Ct(e){const[t]=Ye(()=>({current:e}));return t}var Gc=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},ee=(e,t)=>{const r=Ct();return r.current||(r.current={value:e(),deps:t}),Gc(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Nr(e,t){const[r,n]=Ye({}),i=ee(()=>Lr(e.type,()=>n({})),[e.type]),s=t?ee(()=>e.props,t):e.props,a=ee(()=>Yt(i,s),[i,s,r]);return ke(()=>()=>St(i),[i]),ke(()=>{kt(i,a)},[i,a]),a.state}function He(e){return ws(e.type,e.props)}function Ss(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=Ye({}),i=ee(()=>new Map(e.map(o=>[o.key,o])),[e]),[s]=Ye(()=>new Map),a=ee(()=>{const o=new Map,l=new Set;return i.forEach((u,d)=>{l.add(d);let c=s.get(d);(!c||c.resource!==u.type)&&(c&&St(c),c=Lr(u.type,()=>n({})),s.set(d,c));const f=Yt(c,u.props);o.set(d,f)}),s.forEach((u,d)=>{l.has(d)||(St(u),s.delete(d))}),o},[i,r]);return ke(()=>{a.forEach((o,l)=>{const u=s.get(l);u&&kt(u,o)})},[a,s]),ke(()=>()=>{s.forEach(o=>{St(o)}),s.clear()},[s]),ee(()=>e.map(o=>{var l;return(l=a.get(o.key))==null?void 0:l.state}),[e,a])}var kn=[],_n=!1;function Yc(){_n=!1;const e=kn;kn=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function Kc(e){kn.push(e),_n||(_n=!0,queueMicrotask(Yc))}var Xc=(yt=class{constructor(t){T(this,"_isDirty",!1);T(this,"_hasScheduledTask",!1);T(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,Kc(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>yt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},T(yt,"MAX_FLUSH_DEPTH",50),yt),Qc=oe(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[i,s]=Ye(e.props),a=He({type:e.type,props:i}),o=Ct(new Set).current,l=Ct(a);return ke(()=>{a!==l.current&&(l.current=a,o.forEach(d=>d()))}),ee(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),s(()=>d)},flushSync:r,dispose:n}),[])}),Zc=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,kt(s,a))},onFlushSync:()=>{i.flushSync()},onDispose:()=>St(s)},i=new Xc(()=>{a=Yt(s,n),r&&kt(s,a)}),s=Lr(Qc,()=>i.markDirty());let a=Yt(s,n);return r&&kt(s,a),a.state},Kt=Symbol("tap.Context"),ks=e=>({[Kt]:e}),_s=(e,t,r)=>{const n=e[Kt];e[Kt]=t;try{return r()}finally{e[Kt]=n}},Ts=e=>e[Kt];const Cs=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const f=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(h=>h(t,f))}},i=()=>t,o={setState:n,getState:i,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,i,o);return o},ed=(e=>e?Cs(e):Cs),td=e=>e;function rd(e,t=td){const r=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(r),r}const Is=e=>{const t=ed(e),r=n=>rd(t,n);return Object.assign(r,t),r},It=(e=>e?Is(e):Is);function Es(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function As(...e){return t=>{let r=!1;const n=e.map(i=>{const s=Es(i,t);return!r&&typeof s=="function"&&(r=!0),s});if(r)return()=>{for(let i=0;i<n.length;i++){const s=n[i];typeof s=="function"?s():Es(e[i],null)}}}}function Dr(...e){return J.useCallback(As(...e),e)}var Ps=oe(e=>{const t=ee(()=>Zc(e,!0),[e.type]);return ke(()=>{t.updateInput(e.props)}),t}),nd=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},qe=(e,t)=>{const r=Ct(e);ke(()=>{r.current=e});const n=ee(()=>new Proxy({},new nd(()=>r.current)),[]),i=t==null?void 0:t.key,s=e.getState();return ee(()=>({key:i,state:s,api:n}),[s,i])},Et=oe(e=>{const t=Ct(e.get);return ke(()=>{t.current=e.get}),ee(()=>be({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),id=oe(e=>{const t=Nr(e.scopeElement);return ee(()=>[e.fieldName,t],[e.fieldName,t])}),sd=oe(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,i=H(o,["on","subscribe","flushSync"]),s=Ct({on:t,subscribe:r,flushSync:n});ke(()=>{s.current={on:t,subscribe:r,flushSync:n}});const a=Ss(Object.entries(i).map(([l,u])=>id({fieldName:l,scopeElement:u},{key:l})));return ee(()=>{const l=Object.fromEntries(a),{on:u,subscribe:d,flushSync:c}=s.current;return u&&(l.on=(f,h)=>u(f,h)),d&&(l.subscribe=f=>d(f)),c&&(l.flushSync=()=>c()),l},[...a])}),Ms=ks(null),ad=(e,t)=>_s(Ms,e,t),Ls=()=>{const e=Ts(Ms);if(!e)throw new Error("Model context is not available in this context");return e},od=oe(({toolkit:e})=>{const[t,r]=Ye(()=>({tools:{}})),n=Ls();ke(()=>{if(!e)return;const s=[];for(const[l,u]of Object.entries(e))u.render&&s.push(i(l,u.render));const a=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=H(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:a})};return s.push(n.register(o)),()=>{s.forEach(l=>l())}},[e,n]);const i=(s,a)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[s]:[...(l=o.tools[s])!=null?l:[],a]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[s]:(u=(l=o.tools[s])==null?void 0:l.filter(d=>d!==a))!=null?u:[]})})})});return qe({getState:()=>t,setToolUI:i})}),ld=oe(()=>ee(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const i=t.get(r);return i.add(n),()=>{i.delete(n),i.size===0&&t.delete(r)}},emit:(r,n)=>{const i=t.get(r),s=t.get("*");!i&&!s||queueMicrotask(()=>{if(i)for(const a of i)a(n);if(s)for(const a of s)a({event:r,payload:n})})}}},[])),Ns=ks(null),ud=(e,t)=>_s(Ns,e,t),Tn=()=>{const e=Ts(Ns);if(!e)throw new Error("Events context is not available");return e},cd=oe(()=>{const[e]=Ye(()=>({})),t=new cn;return qe({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),dd=oe(({threads:e,modelContext:t,tools:r})=>{const n=He(ld()),{threads:i,tools:s,modelContext:a}=ud(n,()=>{const l=Nr(t!=null?t:cd(),[t]);return ad(l.api,()=>({modelContext:l,tools:Nr(r!=null?r:od({}),[r]),threads:Nr(e,[e])}))}),o=ee(()=>({threads:i.state,tools:s.state,modelContext:a.state}),[i.state,s.state,a.state]);return qe({getState:()=>o,threads:i.api,tools:s.api,modelContext:a.api,on:n.on})}),hd=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:be({source:"root",query:{},get:()=>e.getState().api.threads}),tools:be({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:be({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:be({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:be({source:"threads",query:{type:"main"},get:()=>t()}),composer:be({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:i,scope:s}=_t(r);if(s==="*")return e.getState().api.on(i,n);if(dt("thread",s)||dt("thread-list-item",s)||dt("composer",s))return e.getState().api.on(i,a=>{a.threadId===t().getState().id&&n(a)});throw new Error(`Event scope is not available in this component: ${s}`)},subscribe:e.subscribe,flushSync:e.flushSync}},fd=e=>{const t=Or(),r=vn(Ps(dd(e))),n=y.useMemo(()=>hd(r),[r]);return y.useMemo(()=>Os(t,n),[t,n])},be=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},at=()=>()=>{},Ds=y.createContext({threads:be({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:be({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:be({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:be({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:be({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:be({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:be({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:be({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:be({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:at,flushSync:at,on:e=>{const{scope:t}=_t(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Or=()=>y.useContext(Ds),Xt=e=>{const t=Or(),r=vn(sd(e));return y.useMemo(()=>Os(t,r),[t,r])},pd=e=>fd(e);function ue(e){return e?pd(e):Or()}var md=(e,t)=>e===at?t:t===at?e:(...r)=>{e(...r),t(...r)},gd=(e,t)=>e===at?t:t===at?e:(...r)=>{const n=e(...r),i=t(...r);return()=>{n(),i()}},Os=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:gd(e.subscribe,r!=null?r:at),flushSync:md(e.flushSync,n!=null?n:at)})},At=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return qc.register(e)},[e,r]),p.jsx(Ds.Provider,{value:e,children:t})),Fs=(Kl=class{constructor(e){jt(this,ze);Ut(this,ze,e)}get threads(){return De(this,ze).threads().getState()}get tools(){return De(this,ze).tools().getState()}get threadListItem(){return De(this,ze).threadListItem().getState()}get thread(){return De(this,ze).thread().getState()}get composer(){return De(this,ze).composer().getState()}get message(){return De(this,ze).message().getState()}get part(){return De(this,ze).part().getState()}get attachment(){return De(this,ze).attachment().getState()}},ze=new WeakMap,Kl),ie=e=>{const t=ue(),r=y.useMemo(()=>new Fs(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof Fs)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},Cn=(e,t)=>{const r=ue(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:i,event:s}=_t(e);y.useEffect(()=>r.on({scope:i,event:s},a=>n.current(a)),[r,i,s])};function yd(e,t){function r(n){const i=y.useContext(e);if(!(n!=null&&n.optional)&&!i)throw new Error(`This component must be used within ${t}.`);return i}return r}function Bs(e,t){function r(i){const s=e(i);return s?s[t]:null}function n(i){let s=!1,a;typeof i=="function"?a=i:i&&typeof i=="object"&&(s=!!i.optional,a=i.selector);const o=r({optional:s});return o?a?o(a):o():null}return{[t]:n,[`${t}Store`]:r}}var zs=y.createContext(null),bd=yd(zs,"ThreadPrimitive.Viewport"),{useThreadViewport:Fr,useThreadViewportStore:In}=Bs(bd,"useThreadViewport"),wd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function xd(e,t=vd){wd(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var vd=e=>e;function Rs(e){function t(r){let n=!1,i;typeof r=="function"?i=r:r&&(n=!!r.optional,i=r.selector);const s=e({optional:n});return s?xd(s,i):null}return t}function js(e){const t=ue(),r=ie(()=>{var n,i,s;return t.thread.source&&(s=(i=(n=t.thread()).__internal_getRuntime)==null?void 0:i.call(n))!=null?s:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var Sd=Rs(js);function kd(e){const t=ue(),r=ie(()=>{var n,i,s;return t.threadListItem.source&&(s=(i=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:i.call(n))!=null?s:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var Us=Rs(kd),ht=e=>{const[,t]=Ye(e.getState);return ke(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},_d=oe(({runtime:e})=>{const t=ht(e),r=Tn();return ke(()=>{const n=[],i=["switched-to","switched-away"];for(const s of i){const a=e.unstable_on(s,()=>{r.emit(`thread-list-item.${s}`,{threadId:e.getState().id})});n.push(a)}return()=>{for(const s of n)s()}},[e,r]),qe({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),Qt=e=>{const t=Ss(e);return{state:t.map(r=>r.state),api:r=>{var i,s;const n="index"in r?(i=t[r.index])==null?void 0:i.api:(s=t.find(a=>a.key===r.key))==null?void 0:s.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},$s=oe(({runtime:e})=>{const t=ht(e);return qe({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Td=oe(({runtime:e,index:t})=>{const r=ee(()=>e.getAttachmentByIndex(t),[e,t]);return He($s({runtime:r}))}),Hs=oe(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=ht(r),i=Tn();ke(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{i.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,i,e,t]);const s=Qt(n.attachments.map((l,u)=>Td({runtime:r,index:u},{key:u}))),a=ee(()=>{var l;return{text:n.text,role:n.role,attachments:s.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,s.state]);return qe({getState:()=>a,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?s.api({key:l.id}):s.api(l),__internal_getRuntime:()=>r})}),Cd=oe(({runtime:e})=>{const t=ht(e);return qe({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),Id=oe(({runtime:e,index:t})=>{const r=ee(()=>e.getAttachmentByIndex(t),[e,t]);return He($s({runtime:r}))}),Ed=oe(({runtime:e,index:t})=>{const r=ee(()=>e.getMessagePartByIndex(t),[e,t]);return He(Cd({runtime:r}))}),Ad=oe(({runtime:e,threadIdRef:t})=>{var f,h;const r=ht(e),[n,i]=Ye(!1),[s,a]=Ye(!1),o=ee(()=>({get current(){return e.getState().id}}),[e]),l=He(Hs({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=Qt(r.content.map((g,S)=>Ed({runtime:e,index:S},{key:S}))),d=Qt((h=(f=r.attachments)==null?void 0:f.map((g,S)=>Id({runtime:e,index:S},{key:S})))!=null?h:[]),c=ee(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:s}),[r,u.state,l.state,n,s]);return qe({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:i,setIsHovering:a,__internal_getRuntime:()=>e},{key:r.id})}),Pd=oe(({runtime:e,id:t,threadIdRef:r})=>{const n=ee(()=>e.getMessageById(t),[e,t]);return He(Ad({runtime:n,threadIdRef:r}))}),Md=oe(({runtime:e})=>{const t=ht(e),r=Tn();ke(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var f;const c=((f=e.getState())==null?void 0:f.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=ee(()=>({get current(){return e.getState().threadId}}),[e]),i=He(Hs({runtime:e.composer,threadIdRef:n})),s=Qt(t.messages.map(o=>Pd({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),a=ee(()=>({isEmpty:s.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:i.state,messages:s.state}),[t,s,i.state]);return qe({getState:()=>a,composer:i.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?s.api({key:o.id}):s.api(o),__internal_getRuntime:()=>e})}),Ld=oe(({runtime:e,id:t})=>{const r=ee(()=>e.getItemById(t),[e,t]);return He(_d({runtime:r}))}),Nd=oe(({runtime:e,__internal_assistantRuntime:t})=>{const r=ht(e),n=He(Md({runtime:e.main})),i=Qt(Object.keys(r.threadItems).map(a=>Ld({runtime:e,id:a},{key:a}))),s=ee(()=>{var a;return{mainThreadId:r.mainThreadId,newThreadId:(a=r.newThread)!=null?a:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:i.state,main:n.state}},[r,i.state,n.state]);return qe({getState:()=>s,thread:()=>n.api,item:a=>{if(a==="main")return i.api({key:s.mainThreadId});if("id"in a)return i.api({key:a.id});const{index:o,archived:l=!1}=a,u=l?s.archivedThreadIds[o]:s.threadIds[o];return i.api({key:u})},switchToThread:a=>{e.switchToThread(a)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),Dd=oe(e=>{const t=Ls();return ke(()=>e.registerModelContextProvider(t),[e,t]),He(Nd({runtime:e.threads,__internal_assistantRuntime:e}))}),En=e=>{const t=new Map,r=()=>{let n=0;for(const i of t.values())n+=i;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:i=>{t.get(n)!==i&&(t.set(n,i),r())},unregister:()=>{t.delete(n),r()}}}}},Od=(e={})=>{const t=new Set,r=En(a=>{s.setState({height:E(m({},s.getState().height),{viewport:a})})}),n=En(a=>{s.setState({height:E(m({},s.getState().height),{inset:a})})}),i=En(a=>{s.setState({height:E(m({},s.getState().height),{userMessage:a})})}),s=It(()=>{var a;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(a=e.turnAnchor)!=null?a:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:i.register}});return s},Zt=e=>e,Fd=e=>{const t=In({optional:!0}),[r]=y.useState(()=>Od(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),y.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&Zt(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var s;const n={turnAnchor:(s=e.turnAnchor)!=null?s:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&Zt(r).setState(n)},[r,e.turnAnchor]),r},qs=({children:e,options:t={}})=>{const r=Fd(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(zs.Provider,{value:n,children:e})},Bd=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},zd=({children:e,runtime:t})=>{const r=ue({threads:Dd(t)}),n=Bd(t);return p.jsxs(At,{api:r,children:[n&&p.jsx(n,{}),p.jsx(qs,{children:e})]})},Vs=y.memo(zd),Rd=({index:e,archived:t,children:r})=>{const n=ue(),i=Xt({threadListItem:Et({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(s,a){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=_t(s);return dt("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&a(d)}):n.on(s,a)}});return p.jsx(At,{api:i,children:r})},jd=({id:e,children:t})=>{const r=ue(),n=Xt({threadListItem:Et({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(i,s){const a=()=>r.threads().item({id:e}),{event:o,scope:l}=_t(i);return dt("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===a().getState().id&&s(u)}):r.on(i,s)}});return p.jsx(At,{api:n,children:t})},Ud=({index:e,children:t})=>{const r=ue(),n=Xt({message:Et({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:Et({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(i,s){const a=()=>r.thread().message({index:e}),{event:o,scope:l}=_t(i);return!dt("composer",l)&&!dt("message",l)?r.on(i,s):r.on({scope:"thread",event:o},u=>{u.messageId===a().getState().id&&s(u)})}});return p.jsx(At,{api:n,children:t})},$d=({index:e,children:t})=>{const r=ue(),n=Xt({part:Et({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(At,{api:n,children:t})},Hd=oe(({text:e,isRunning:t})=>{const r=ee(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return qe({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),qd=({text:e,isRunning:t=!1,children:r})=>{const n=vn(Ps(Hd({text:e,isRunning:t}))),i=Xt({part:Et({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(At,{api:i,children:r})},Ws=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result||!t.includes(i.toolName))},An=class extends Error{constructor(t,r){super(r);T(this,"name","AbortError");T(this,"detach");this.detach=t}},Vd=class extends Fc{constructor(t,r){super(t);T(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});T(this,"abortController",null);T(this,"isDisabled",!1);T(this,"_isLoading",!1);T(this,"_suggestions",[]);T(this,"_suggestionsController",null);T(this,"_options");T(this,"_lastRunConfig",{});T(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var a,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((a=t.adapters)==null?void 0:a.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const i=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==i&&(this.capabilities.attachments=i,r=!0);const s=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==s&&(this.capabilities.feedback=s,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(i=>{var a,o;if(!i)return;this.repository.import(i),this._notifySubscribers();const s=(o=(a=this.adapters.history)==null?void 0:a.resume)==null?void 0:o.bind(this.adapters.history);i.unstable_resume&&s&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},s)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var i,s,a;this.ensureInitialized();const r=Wt(t,ut(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(i=this._options.adapters.history)==null||i.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((s=t.startRun)!=null?s:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(a=t.runConfig)!=null?a:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var i=n,{stream:t}=i,r=H(i,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(i,s){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:ut(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(Ws(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const w=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in w)try{for(var f=xt(w),h,g,S;h=!(g=yield f.next()).done;h=!1){const b=g.value;if(l.aborted)break;this._suggestions=b,this._notifySubscribers()}}catch(g){S=[g]}finally{try{h&&(g=f.return)&&(yield g.call(f))}finally{if(S)throw S[0]}}else{const b=yield w;if(l.aborted)return;this._suggestions=b,this._notifySubscribers()}}})}performRoundtrip(t,r,n,i){return P(this,null,function*(){var g,S,w,b,C,_,F,B,I,N;const s=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const a=r.content,o=(S=r.metadata)==null?void 0:S.unstable_annotations,l=(w=r.metadata)==null?void 0:w.unstable_data,u=(b=r.metadata)==null?void 0:b.steps,d=(C=r.metadata)==null?void 0:C.custom,c=M=>{var fe,x,ye,Ie,v,ve;const V=(fe=M.metadata)==null?void 0:fe.steps,R=V?[...u!=null?u:[],...V]:void 0,D=(x=M.metadata)==null?void 0:x.unstable_annotations,Q=(ye=M.metadata)==null?void 0:ye.unstable_data,se=D?[...o!=null?o:[],...D]:void 0,ge=Q?[...l!=null?l:[],...Q]:void 0;r=m(E(m(m({},r),M.content?{content:[...a,...(Ie=M.content)!=null?Ie:[]]}:void 0),{status:(v=M.status)!=null?v:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),se?{unstable_annotations:se}:void 0),ge?{unstable_data:ge}:void 0),R?{steps:R}:void 0),(ve=M.metadata)!=null&&ve.custom?{custom:m(m({},d!=null?d:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(_=this._options.maxSteps)!=null?_:2;if(((I=(B=(F=r.metadata)==null?void 0:F.steps)==null?void 0:B.length)!=null?I:0)>=f)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const M=this.getModelContext();i=i!=null?i:this.adapters.chatModel.run.bind(this.adapters.chatModel);const V=this.abortController.signal,R=i({messages:s,runConfig:this._lastRunConfig,abortSignal:V,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in R)try{for(var z=xt(R),j,$,k;j=!($=yield z.next()).done;j=!1){const D=$.value;if(V.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(D)}}catch($){k=[$]}finally{try{j&&($=z.return)&&(yield $.call(z))}finally{if(k)throw k[0]}}else c(yield R);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof An)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(N=this._options.adapters.history)==null?void 0:N.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new An(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new An(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:i,artifact:s}){const a=this.repository.getMessage(t),{parentId:o}=a;let{message:l}=a;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(f=>f.type!=="tool-call"||f.toolCallId!==r?f:(d=!0,f.result||(u=!0),E(m({},f),{result:n,artifact:s,isError:i})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&Ws(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},Js=Object.freeze([]),Pn="__DEFAULT_ID__",Wd=Object.freeze({[Pn]:{id:Pn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),Jd=class extends qt{constructor(t){super();T(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw Js}get archivedThreadIds(){throw Js}get mainThreadId(){return Pn}get threadData(){return Wd}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return P(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},Gd=class extends dn{constructor(t,r){super();T(this,"threads");T(this,"Provider");T(this,"_options");this._options=t,this.threads=new Jd(()=>new Vd(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(gn.fromArray(r))}},Gs=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const i=atob(n),a=JSON.parse(i).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},Ys=(Xl=class{constructor(e){T(this,"strategy","jwt");T(this,"cachedToken",null);T(this,"tokenExpiry",null);jt(this,fr);Ut(this,fr,e)}getAuthHeaders(){return P(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield De(this,fr).call(this);return t?(this.cachedToken=t,this.tokenExpiry=Gs(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=Gs(n)}},fr=new WeakMap,Xl),Yd=(Ql=class{constructor(e,t,r){T(this,"strategy","api-key");jt(this,pr);jt(this,mr);jt(this,gr);Ut(this,pr,e),Ut(this,mr,t),Ut(this,gr,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${De(this,pr)}`,"Aui-User-Id":De(this,mr),"Aui-Workspace-Id":De(this,gr)}})}readAuthHeaders(){}},pr=new WeakMap,mr=new WeakMap,gr=new WeakMap,Ql),Br="aui:refresh_token",Kd=class{constructor(e){T(this,"strategy","anon");T(this,"baseUrl");T(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new Ys(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Br),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:f}=d;return f&&localStorage.setItem(Br,JSON.stringify(f)),c}}else localStorage.removeItem(Br);const i=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!i.ok)return null;const s=yield i.json(),{access_token:a,refresh_token:o}=s;return!a||!o?null:(localStorage.setItem(Br,JSON.stringify(o)),a)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Xd=class extends Error{constructor(e){super(e),this.name="APIError"}},Qd=class{constructor(e){T(this,"_auth");T(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new Ys(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new Yd(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new Kd(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const i=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),s=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?s.set(u,"true"):s.set(u,d.toString()));const a=new URL(`${this._baseUrl}/v1${e}`);a.search=s.toString();const o=yield fetch(a,{method:(l=t.method)!=null?l:"GET",headers:i,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new Xd(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Zd=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},eh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return pn.fromResponse(t,new hc)})}},th=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},rh=class{constructor(e){T(this,"messages");this.cloud=e,this.messages=new th(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},nh=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},ih=class{constructor(e){T(this,"threads");T(this,"auth");T(this,"runs");T(this,"files");const t=new Qd(e);this.threads=new rh(t),this.auth={tokens:new Zd(t)},this.runs=new eh(t),this.files=new nh(t)}};function Mn(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>Mn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Mn(n,t+1)):!1}var sh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return Mn(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const i=n;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},ah=e=>{const t=e.content,r=Wt(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Ln=new WeakMap,oh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},lh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Ln.has(this.store.threadListItem())||Ln.set(this.store.threadListItem(),{}),Ln.get(this.store.threadListItem())}withFormat(e){return new oh(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var s;const{remoteId:n}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:"aui/v0",content:sh(t)}).then(({message_id:a})=>(this._getIdForLocalId[t.id]=a,a));return this._getIdForLocalId[t.id]=i,i.then(()=>{})})}load(){return P(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(ah).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var a;const{remoteId:i}=yield this.store.threadListItem().initialize(),s=this.cloudRef.current.threads.messages.create(i,{parent_id:e?(a=yield this._getIdForLocalId[e])!=null?a:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=s,s.then(()=>{})})}_loadWithFormat(e,t){return P(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(i=>i.format===e).map(i=>t({id:i.id,parent_id:i.parent_id,format:i.format,content:i.content})).reverse()}})}},uh=e=>{const t=ue(),[r]=y.useState(()=>new lh(e,t));return r},Ks=typeof process!="undefined"&&((Zl=process==null?void 0:process.env)==null?void 0:Zl.NEXT_PUBLIC_ASSISTANT_BASE_URL),Nn=Ks?new ih({baseUrl:Ks,anonymous:!0}):void 0,ch=e=>{var i;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:a}){var c;const o=uh({get current(){var f;return(f=t.current.cloud)!=null?f:Nn}}),l=(c=t.current.cloud)!=null?c:Nn,u=y.useMemo(()=>new Nc(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(wn,{adapters:d,children:a})},[]),n=(i=e.cloud)!=null?i:Nn;return n?{list:()=>P(null,null,function*(){const{threads:s}=yield n.threads.list();return{threads:s.map(a=>{var o;return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}})}}),initialize:()=>P(null,null,function*(){var u,d;const a=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=a?a.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(s,a)=>P(null,null,function*(){return n.threads.update(s,{title:a})}),archive:s=>P(null,null,function*(){return n.threads.update(s,{is_archived:!0})}),unarchive:s=>P(null,null,function*(){return n.threads.update(s,{is_archived:!1})}),delete:s=>P(null,null,function*(){var a;return yield(a=e.delete)==null?void 0:a.call(e,s),n.threads.delete(s)}),generateTitle:(s,a)=>P(null,null,function*(){return n.runs.stream({thread_id:s,assistant_id:"system/thread_title",messages:a})}),fetch:s=>P(null,null,function*(){var o;const a=yield n.threads.get(s);return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}}),unstable_Provider:r}:new Rc},dh=(e,n)=>{var i=n,{initialMessages:t}=i,r=H(i,["initialMessages"]);var u;const d=(u=Dc())!=null?u:{},{modelContext:s}=d,a=H(d,["modelContext"]),o=y.useMemo(()=>E(m({},r),{adapters:E(m(m({},a),r.adapters),{chatModel:e})}),[e,r,a]),[l]=y.useState(()=>new Gd(o,t));return y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),y.useEffect(()=>{if(s)return l.registerModelContextProvider(s)},[s,l]),y.useMemo(()=>new Dn(l),[l])},Xs=(e,n={})=>{var i=n,{cloud:t}=i,r=H(i,["cloud"]);const s=ch({cloud:t});return ra({runtimeHook:function(){return dh(e,r)},adapter:s,allowNesting:!0})},Dn=class{constructor(e){T(this,"threads");T(this,"_thread");this._core=e,this.threads=new Mc(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(gn.fromArray(e!=null?e:[]))}},hh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:i,unstable_humanToolNames:s}=o,a=H(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:i,unstable_humanToolNames:s},otherOptions:a}};function ft(e){const t=J.useRef(e);return J.useEffect(()=>{t.current=e}),J.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var Qs=y.createContext(null),fh=e=>({useSmoothStatus:It(()=>e)}),ph=({children:e})=>{const t=Zs({optional:!0}),r=ue(),[n]=y.useState(()=>fh(r.part().getState().status));return t?e:p.jsx(Qs.Provider,{value:n,children:e})},mh=e=>{const t=y.forwardRef((r,n)=>p.jsx(ph,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function Zs(e){const t=y.useContext(Qs);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:gh,useSmoothStatusStore:yh}=Bs(Zs,"useSmoothStatus"),bh=class{constructor(e,t){T(this,"animationFrameId",null);T(this,"lastUpdateTime",Date.now());T(this,"targetText","");T(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,i=Math.min(5,250/n);let s=0;for(;r>=i&&s<n;)s++,r-=i;s!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},On=Object.freeze({type:"running"}),ea=(e,t=!1)=>{const{text:r}=e,n=ie(({message:d})=>d.id),i=y.useRef(n),[s,a]=y.useState(r),o=yh({optional:!0}),l=ft(d=>{if(a(d),o){const c=s!==d||e.status.type==="running"?On:e.status;Zt(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(s!==r||e.status.type==="running")?On:e.status;Zt(o).setState(d,!0)}},[o,t,r,s,e.status]);const[u]=y.useState(new bh(r,l));return y.useEffect(()=>{if(!t){u.stop();return}if(i.current!==n||!r.startsWith(u.targetText)){i.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:s,status:r===s?e.status:On}:e,[t,s,e,r])};const wh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Dn,BaseAssistantRuntimeCore:dn,CompositeContextProvider:cn,DefaultThreadComposerRuntimeCore:qi,MessageRepository:is,ThreadRuntimeImpl:bs,fromThreadMessageLike:Wt,generateId:ut,getAutoStatus:Wi,splitLocalRuntimeOptions:hh,useSmooth:ea,useSmoothStatus:gh,useToolInvocations:zc,withSmoothContextProvider:mh},Symbol.toStringTag,{value:"Module"}));var xh=class extends qt{constructor(t){super();T(this,"useRuntimeHook");T(this,"instances",new Map);T(this,"useAliveThreadsKeysChanged",It(()=>({})));T(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),i=n.thread.__internal_threadBinding,s=y.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=i.getState(),this._notifySubscribers()},[t,i]),a=y.useRef(!1);a.current||s(),y.useEffect(()=>(a.current=!0,s(),i.outerSubscribe(s)),[i,s]);const o=ue();return y.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});T(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(jd,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));T(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=It(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const i=()=>{const a=this.instances.get(t);if(!a)s(),n(new Error("Thread was deleted before runtime was started"));else if(a.runtime)s(),r(a.runtime);else return},s=this.subscribe(i);i()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},ce=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),vh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ce},append(){throw ce},startRun(){throw ce},resumeRun(){throw ce},cancelRun(){throw ce},addToolResult(){throw ce},resumeToolCall(){throw ce},speak(){throw ce},stopSpeaking(){throw ce},submitFeedback(){throw ce},getModelContext(){return{}},unstable_loadExternalState(){throw ce},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw ce})},removeAttachment(){return P(this,null,function*(){throw ce})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ce},role:"user",setRole(){throw ce},runConfig:{},setRunConfig(){throw ce},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw ce},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ce},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw ce},export(){return{messages:[]}},reset(){throw ce},unstable_on(){return()=>{}}},ta=(e,t,r)=>r.reduce((n,i)=>{var s;return(s=i==null?void 0:i(n,t))!=null?s:n},e),Sh=class extends qt{constructor(t){super();T(this,"_pendingTransforms",[]);T(this,"_baseValue");T(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>ta(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const i=yield r;return this._baseValue=ta(this._baseValue,i,[t.optimistic,t.then]),i}finally{const i=this._pendingTransforms.indexOf(n);i>-1&&this._pendingTransforms.splice(i,1),this._updateState()}})}};function Wx(e){return e}var zr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Rr=(e,t,r)=>{const n=zr(e,t);if(!n)return e;const{id:i,remoteId:s,status:a}=n;if(a===r)return e;const o=m({},e);switch(a){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==i);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==i);break;default:{const l=a;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[i,...o.threadIds];break;case"archived":o.archivedThreadIds=[i,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==i)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==i&&l!==s));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[i]:E(m({},n),{status:r})})),o},kh=class extends qt{constructor(t,r){super();T(this,"_options");T(this,"_hookManager");T(this,"_loadThreadsPromise");T(this,"_mainThreadId");T(this,"_state",new Sh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));T(this,"useProvider");T(this,"initialize",t=>P(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>Rr(r,t,"regular"),loading:(r,n)=>{const i=t;return E(m({},r),{threadData:E(m({},r.threadData),{[i]:E(m({},r.threadData[i]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:i})=>{const s=zr(r,t);if(!s)return r;const a=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:a}),threadData:E(m({},r.threadData),{[a]:E(m({},s),{initializeTask:Promise.resolve({remoteId:n,externalId:i}),remoteId:n,externalId:i})})})}})}));T(this,"generateTitle",t=>P(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,i=this._hookManager.getThreadRuntimeCore(r.id);if(!i)return;const s=i.messages,a=yield this._options.adapter.generateTitle(n,s),o=fc.fromAssistantStream(a);try{for(var u=xt(o),d,c,f;d=!(c=yield u.next()).done;d=!1){const h=c.value;const g=(l=h.parts.filter(w=>w.type==="text")[0])==null?void 0:l.text,S=this._state.baseValue;this._state.update(E(m({},S),{threadData:E(m({},S.threadData),{[r.id]:E(m({},r),{title:g})})}))}}catch(c){f=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(f)throw f[0]}}}));T(this,"useBoundIds",It(()=>[]));T(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(s=>[...s,t],!0),()=>{this.useBoundIds.setState(s=>s.filter(a=>a!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),i={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(wn,{adapters:i,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new xh(t.runtimeHook),this.useProvider=It(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:y.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],i=[],s={},a={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":i.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;s[o.remoteId]=l,a[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return E(m({},t),{threadIds:n,archivedThreadIds:i,threadIdMap:m(m({},t.threadIdMap),s),threadData:m(m({},t.threadData),a)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||vh}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return zr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const i=yield this._options.adapter.fetch(t),s=this._state.value,a=i.remoteId,o=E(m({},s.threadData),{[a]:{id:a,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title}}),l=E(m({},s.threadIdMap),{[i.remoteId]:a}),u=i.status==="regular"?[...s.threadIds,i.remoteId]:s.threadIds,d=i.status==="archived"?[...s.archivedThreadIds,i.remoteId]:s.archivedThreadIds;this._state.update(E(m({},s),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return P(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${ut()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){const{remoteId:i}=yield n.initializeTask;return this._options.adapter.rename(i,r)}),optimistic:i=>{const s=zr(i,t);return s?E(m({},i),{threadData:E(m({},i.threadData),{[s.id]:E(m({},s),{title:r})})}):i}})}_ensureThreadIsNotMain(t){return P(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Rr(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>Rr(n,r.id,"regular")})}delete(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Rr(n,r.id,"deleted")})})}detach(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},_h=class extends dn{constructor(t){super();T(this,"threads");this.threads=new kh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Th=e=>{const[t]=y.useState(()=>new _h(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Dn(t),[t])},ra=e=>{if(Or().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return Th(e)},Ch=Symbol.for("react.lazy"),jr=J[" use ".trim().toString()];function Ih(e){return typeof e=="object"&&e!==null&&"then"in e}function na(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Ch&&"_payload"in e&&Ih(e._payload)}function ia(e){const t=Eh(e),r=J.forwardRef((n,i)=>{let u=n,{children:s}=u,a=H(u,["children"]);na(s)&&typeof jr=="function"&&(s=jr(s._payload));const o=J.Children.toArray(s),l=o.find(Ph);if(l){const d=l.props.children,c=o.map(f=>f===l?J.Children.count(d)>1?J.Children.only(null):J.isValidElement(d)?d.props.children:null:f);return p.jsx(t,E(m({},a),{ref:i,children:J.isValidElement(d)?J.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},a),{ref:i,children:s}))});return r.displayName=`${e}.Slot`,r}var sa=ia("Slot");function Eh(e){const t=J.forwardRef((r,n)=>{let a=r,{children:i}=a,s=H(a,["children"]);if(na(i)&&typeof jr=="function"&&(i=jr(i._payload)),J.isValidElement(i)){const o=Lh(i),l=Mh(s,i.props);return i.type!==J.Fragment&&(l.ref=n?As(n,o):o),J.cloneElement(i,l)}return J.Children.count(i)>1?J.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Ah=Symbol("radix.slottable");function Ph(e){return J.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ah}function Mh(e,t){const r=m({},t);for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(r[n]=i):n==="style"?r[n]=m(m({},i),s):n==="className"&&(r[n]=[i,s].filter(Boolean).join(" "))}return m(m({},e),r)}function Lh(e){var n,i;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Nh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ze=Nh.reduce((e,t)=>{const r=ia(`Primitive.${t}`),n=J.forwardRef((i,s)=>{const u=i,{asChild:a}=u,o=H(u,["asChild"]),l=a?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:s}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function Pt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(e==null||e(i),r===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}var Fn=(e,t,r=[])=>{const n=y.forwardRef((i,s)=>{var u;const a={},o={};Object.keys(i).forEach(d=>{r.includes(d)?a[d]=i[d]:o[d]=i[d]});const l=(u=t(a))!=null?u:void 0;return p.jsx(Ze.button,E(m({type:"button"},o),{ref:s,disabled:o.disabled||!l,onClick:Pt(o.onClick,l)}))});return n.displayName=e,n};function Dh(e,t=globalThis==null?void 0:globalThis.document){const r=ft(e);J.useEffect(()=>{const n=i=>{i.key==="Escape"&&r(i)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var er=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},aa=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const i=e(),s=()=>{const o=t?t(n):n.offsetHeight;i.setHeight(o)},a=new ResizeObserver(s);return a.observe(n),s(),()=>{a.disconnect(),i.unregister()}},[e,t]);return er(r)},oa=y.createContext(!1),la=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),i=r[2];if(i==="px")return n;if(i==="em"){const s=parseFloat(getComputedStyle(t).fontSize)||16;return n*s}if(i==="rem"){const s=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*s}return 0},ua=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=ie(({message:l})=>l.isLast&&l.index>=2),i=In({optional:!0}),s=y.useContext(oa),a=y.useCallback(l=>{if(!i||s)return;const u=()=>{const d=i.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:f,userMessage:h}=d.height,g=la(t,l),S=la(r,l),w=h<=g?h:S,b=Math.max(0,c-f-w);l.style.minHeight=`${b}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),i.subscribe(u)},[i,n,s,t,r]),o=er(a);return p.jsx(oa.Provider,{value:!0,children:p.jsx(sa,{ref:o,children:e})})};ua.displayName="ThreadPrimitive.ViewportSlack";var Oh=()=>{const e=ue(),t=ie(()=>e.message()),r=y.useCallback(n=>{const i=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",i),n.addEventListener("mouseleave",s),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",i),n.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]);return er(r)},Fh=()=>{const e=Fr(i=>i.turnAnchor),t=Fr(i=>i.registerUserMessageHeight),r=ie(({thread:i,message:s})=>{var a;return e==="top"&&s.role==="user"&&s.index===i.messages.length-2&&((a=i.messages.at(-1))==null?void 0:a.role)==="assistant"}),n=y.useCallback(i=>i.offsetHeight,[]);return aa(r?t:null,n)},Bn=y.forwardRef((e,t)=>{const r=Oh(),n=Fh(),i=Dr(t,r,n);return p.jsx(ua,{children:p.jsx(Ze.div,E(m({},e),{ref:i}))})});Bn.displayName="MessagePrimitive.Root";var ca=()=>ie(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),da=y.forwardRef((i,n)=>{var s=i,{smooth:e=!0,component:t="span"}=s,r=H(s,["smooth","component"]);const{text:a,status:o}=ea(ca(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:a}))});da.displayName="MessagePartPrimitive.Text";var Bh=()=>ie(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),ha=y.forwardRef((e,t)=>{const{image:r}=Bh();return p.jsx(Ze.img,E(m({src:r},e),{ref:t}))});ha.displayName="MessagePartPrimitive.Image";var fa=({children:e})=>ie(({part:r})=>r.status.type==="running")?e:null;fa.displayName="MessagePartPrimitive.InProgress";const pa=e=>Symbol.iterator in e,ma=e=>"entries"in e,ga=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[i,s]of r)if(!n.has(i)||!Object.is(s,n.get(i)))return!1;return!0},zh=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let i=r.next(),s=n.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=r.next(),s=n.next()}return!!i.done&&!!s.done};function Rh(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:pa(e)&&pa(t)?ma(e)&&ma(t)?ga(e,t):zh(e,t):ga({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function jh(e){const t=y.useRef(void 0);return r=>{const n=e(r);return Rh(t.current,n)?t.current:t.current=n}}var ya=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},Uh=e=>{const t=[],r=ya("toolGroup"),n=ya("reasoningGroup");for(let i=0;i<e.length;i++){const s=e[i];s==="tool-call"?(n.endGroup(i-1,t),r.startGroup(i)):s==="reasoning"?(r.endGroup(i-1,t),n.startGroup(i)):(r.endGroup(i-1,t),n.endGroup(i-1,t),t.push({type:"single",index:i}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},$h=()=>{const e=ie(jh(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:Uh(e),[e])},Hh=r=>{var n=r,{Fallback:e}=n,t=H(n,["Fallback"]);const i=ie(({tools:s})=>{var o,l;const a=(o=s.tools[t.toolName])!=null?o:e;return Array.isArray(a)?(l=a[0])!=null?l:e:a});return i?p.jsx(i,m({},t)):null},et={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(da,{}),p.jsx(fa,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(ha,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},qh=({components:{Text:e=et.Text,Reasoning:t=et.Reasoning,Image:r=et.Image,Source:n=et.Source,File:i=et.File,Unstable_Audio:s=et.Unstable_Audio,tools:a={}}={}})=>{var d,c,f;const o=ue(),l=ie(({part:h})=>h),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in a)return p.jsx(a.Override,E(m({},l),{addResult:h,resume:g}));const S=(c=(d=a.by_name)==null?void 0:d[l.toolName])!=null?c:a.Fallback;return p.jsx(Hh,E(m({},l),{Fallback:S,addResult:h,resume:g}))}if(((f=l.status)==null?void 0:f.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(i,m({},l));case"audio":return p.jsx(s,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},Ur=y.memo(({index:e,components:t})=>p.jsx($d,{index:e,children:p.jsx(qh,{components:t})}),(e,t)=>{var r,n,i,s,a,o,l,u,d,c,f,h,g,S,w,b,C,_;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((i=e.components)==null?void 0:i.Reasoning)===((s=t.components)==null?void 0:s.Reasoning)&&((a=e.components)==null?void 0:a.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((f=e.components)==null?void 0:f.Unstable_Audio)===((h=t.components)==null?void 0:h.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((S=t.components)==null?void 0:S.tools)&&((w=e.components)==null?void 0:w.ToolGroup)===((b=t.components)==null?void 0:b.ToolGroup)&&((C=e.components)==null?void 0:C.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});Ur.displayName="MessagePrimitive.PartByIndex";var Vh=({status:e,component:t})=>p.jsx(qd,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),Wh=Object.freeze({type:"complete"}),Jh=({components:e})=>{var r;const t=ie(n=>{var i;return(i=n.message.status)!=null?i:Wh});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(Vh,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:et.Text})},Gh=y.memo(Jh,(e,t)=>{var r,n,i,s;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((i=e.components)==null?void 0:i.Text)===((s=t.components)==null?void 0:s.Text)}),zn=({components:e})=>{const t=ie(({message:i})=>i.parts.length),r=$h(),n=y.useMemo(()=>t===0?p.jsx(Gh,{components:e}):r.map(i=>{var s,a;if(i.type==="single")return p.jsx(Ur,{index:i.index,components:e},i.index);if(i.type==="toolGroup"){const o=(s=e==null?void 0:e.ToolGroup)!=null?s:et.ToolGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(Ur,{index:i.startIndex+u,components:e},u))},`tool-${i.startIndex}`)}else{const o=(a=e==null?void 0:e.ReasoningGroup)!=null?a:et.ReasoningGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(Ur,{index:i.startIndex+u,components:e},u))},`reasoning-${i.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};zn.displayName="MessagePrimitive.Parts";var ba=()=>{const e=ue(),t=ie(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Yh=Fn("ComposerPrimitive.Send",ba),wa=y.forwardRef((n,r)=>{var i=n,{onSubmit:e}=i,t=H(i,["onSubmit"]);const s=ba(),a=o=>{o.preventDefault(),s&&s()};return p.jsx(Ze.form,E(m({},t),{ref:r,onSubmit:Pt(e,a)}))});wa.displayName="ComposerPrimitive.Root";function Rn(){return Rn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Rn.apply(null,arguments)}function Kh(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Xh=y.useLayoutEffect,Qh=function(t){var r=y.useRef(t);return Xh(function(){r.current=t}),r},xa=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Zh=function(t,r){var n=y.useRef();return y.useCallback(function(i){t.current=i,n.current&&xa(n.current,null),n.current=r,r&&xa(r,i)},[r])},va={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},ef=function(t){Object.keys(va).forEach(function(r){t.style.setProperty(r,va[r],"important")})},Sa=ef,_e=null,ka=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function tf(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),_e||(_e=document.createElement("textarea"),_e.setAttribute("tabindex","-1"),_e.setAttribute("aria-hidden","true"),Sa(_e)),_e.parentNode===null&&document.body.appendChild(_e);var i=e.paddingSize,s=e.borderSize,a=e.sizingStyle,o=a.boxSizing;Object.keys(a).forEach(function(f){var h=f;_e.style[h]=a[h]}),Sa(_e),_e.value=t;var l=ka(_e,e);_e.value=t,l=ka(_e,e),_e.value="x";var u=_e.scrollHeight-i,d=u*r;o==="border-box"&&(d=d+i+s),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+i+s),l=Math.min(c,l),[l,u]}var _a=function(){},rf=function(t,r){return t.reduce(function(n,i){return n[i]=r[i],n},{})},nf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],sf=!!document.documentElement.currentStyle,af=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=rf(nf,r),i=n.boxSizing;if(i==="")return null;sf&&i==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var s=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),a=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:s,borderSize:a}},of=af;function jn(e,t,r){var n=Qh(r);J.useLayoutEffect(function(){var i=function(a){return n.current(a)};if(e)return e.addEventListener(t,i),function(){return e.removeEventListener(t,i)}},[])}var lf=function(t,r){jn(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},uf=function(t){jn(window,"resize",t)},cf=function(t){jn(document.fonts,"loadingdone",t)},df=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],hf=function(t,r){var n=t.cacheMeasurements,i=t.maxRows,s=t.minRows,a=t.onChange,o=a===void 0?_a:a,l=t.onHeightChange,u=l===void 0?_a:l,d=Kh(t,df),c=d.value!==void 0,f=J.useRef(null),h=Zh(f,r),g=J.useRef(0),S=J.useRef(),w=function(){var _=f.current,F=n&&S.current?S.current:of(_);if(F){S.current=F;var B=tf(F,_.value||_.placeholder||"x",s,i),I=B[0],z=B[1];g.current!==I&&(g.current=I,_.style.setProperty("height",I+"px","important"),u(I,{rowHeight:z}))}},b=function(_){c||w(),o(_)};return J.useLayoutEffect(w),lf(f,function(){if(!c){var C=f.current.value;requestAnimationFrame(function(){var _=f.current;_&&C!==_.value&&w()})}}),uf(w),cf(w),J.createElement("textarea",Rn({},d,{onChange:b,ref:h}))},ff=J.forwardRef(hf),Ta=e=>{const t=ft(e),r=Fr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},Ca=y.forwardRef((g,h)=>{var S=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:i,onPaste:s,submitOnEnter:a=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=S,f=H(S,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const w=ue(),b=ie(({composer:k})=>k.isEditing?k.text:""),C=t?sa:ff,_=ie(({thread:k})=>k.isDisabled)||r,F=y.useRef(null),B=Dr(h,F);Dh(k=>{var M;if(!o||!((M=F.current)!=null&&M.contains(k.target)))return;const N=w.composer();N.getState().canCancel&&(N.cancel(),k.preventDefault())});const I=k=>{var N,M;_||!a||k.nativeEvent.isComposing||k.key==="Enter"&&k.shiftKey===!1&&(w.thread().getState().isRunning||(k.preventDefault(),(M=(N=F.current)==null?void 0:N.closest("form"))==null||M.requestSubmit()))},z=k=>P(null,null,function*(){var V;if(!c)return;const N=w.thread().getState().capabilities,M=Array.from(((V=k.clipboardData)==null?void 0:V.files)||[]);if(N.attachments&&M.length>0)try{k.preventDefault(),yield Promise.all(M.map(R=>w.composer().addAttachment(R)))}catch(R){console.error("Error adding attachment:",R)}}),j=e&&!_,$=y.useCallback(()=>{const k=F.current;!k||!j||(k.focus({preventScroll:!0}),k.setSelectionRange(k.value.length,k.value.length))},[j]);return y.useEffect(()=>$(),[$]),Ta(()=>{w.composer().getState().type==="thread"&&u&&$()}),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!l))return w.on("thread.run-start",$)},[l,$,w]),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!d))return w.on("thread-list-item.switched-to",$)},[d,$,w]),p.jsx(C,E(m({name:"input",value:b},f),{ref:B,disabled:_,onChange:Pt(n,k=>{w.composer().getState().isEditing&&(w.composer().setText(k.target.value),w.flushSync())}),onKeyDown:Pt(i,I),onPaste:Pt(s,z)}))});Ca.displayName="ComposerPrimitive.Input";var Ia=y.forwardRef((e,t)=>p.jsx(Ze.div,E(m({},e),{ref:t})));Ia.displayName="ThreadPrimitive.Root";var Ea=({children:e})=>ie(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;Ea.displayName="ThreadPrimitive.Empty";var pf=e=>ie(({thread:t})=>!(e.empty===!0&&!t.isEmpty||e.empty===!1&&t.isEmpty||e.running===!0&&!t.isRunning||e.running===!1&&t.isRunning||e.disabled===!0&&!t.isDisabled||e.disabled===!1&&t.isDisabled)),Aa=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return pf(t)?e:null};Aa.displayName="ThreadPrimitive.If";var mf=e=>{const t=ft(e),r=y.useCallback(n=>{const i=new ResizeObserver(()=>{t()}),s=new MutationObserver(()=>{t()});return i.observe(n),s.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{i.disconnect(),s.disconnect()}},[t]);return er(r)},gf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const i=y.useRef(null),s=In();e===void 0&&(e=s.getState().turnAnchor!=="top");const a=y.useRef(0),o=y.useRef(null),l=y.useCallback(h=>{const g=i.current;g&&(o.current=h,g.scrollTo({top:g.scrollHeight,behavior:h}))},[]),u=()=>{const h=i.current;if(!h)return;const g=s.getState().isAtBottom,S=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!S&&a.current<h.scrollTop||(S&&(o.current=null),(S||o.current===null)&&S!==g&&Zt(s).setState({isAtBottom:S})),a.current=h.scrollTop},d=mf(()=>{const h=o.current;h?l(h):e&&s.getState().isAtBottom&&l("instant"),u()}),c=er(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return Ta(({behavior:h})=>{l(h)}),Cn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Cn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Cn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Dr(d,c,i)},yf=()=>{const e=Fr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return aa(e,t)},Pa=y.forwardRef((o,a)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:i}=l,s=H(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=gf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=yf(),c=Dr(a,u,d);return p.jsx(Ze.div,E(m({},s),{ref:c,children:i}))});Pa.displayName="ThreadPrimitive.ViewportScrollable";var Ma=y.forwardRef((n,r)=>{var i=n,{turnAnchor:e}=i,t=H(i,["turnAnchor"]);return p.jsx(qs,{options:{turnAnchor:e},children:p.jsx(Pa,E(m({},t),{ref:r}))})});Ma.displayName="ThreadPrimitive.Viewport";var La=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,bf=()=>null,wf=(e,t,r)=>{var n,i,s,a,o,l,u,d,c,f,h,g;switch(t){case"user":return r?(s=(i=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?i:e.UserMessage)!=null?s:e.Message:(a=e.UserMessage)!=null?a:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(h=(f=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(g=e.SystemMessage)!=null?g:bf;default:const S=t;throw new Error(`Unknown message role: ${S}`)}},xf=({components:e})=>{const t=ie(({message:i})=>i.role),r=ie(({message:i})=>i.composer.isEditing),n=wf(e,t,r);return p.jsx(n,{})},Na=y.memo(({index:e,components:t})=>p.jsx(Ud,{index:e,children:p.jsx(xf,{components:t})}),(e,t)=>e.index===t.index&&La(e.components,t.components));Na.displayName="ThreadPrimitive.MessageByIndex";var Da=({components:e})=>{const t=ie(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,i)=>p.jsx(Na,{index:i,components:e},i)),[t,e])};Da.displayName="ThreadPrimitive.Messages";var vf=y.memo(Da,(e,t)=>La(e.components,t.components)),Oa=y.forwardRef((i,n)=>{var s=i,{onClick:e,disabled:t}=s,r=H(s,["onClick","disabled"]);const a=ie(({threads:l})=>l.newThreadId===l.mainThreadId),o=ue();return p.jsx(Ze.button,E(m(m({type:"button"},a?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:Pt(e,()=>{o.threads().switchToNewThread()})}))});Oa.displayName="ThreadListPrimitive.New";var Fa=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(Rd,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);Fa.displayName="ThreadListPrimitive.ItemByIndex";var Ba=({archived:e=!1,components:t})=>{const r=ie(({threads:i})=>e?i.archivedThreadIds.length:i.threadIds.length);return y.useMemo(()=>Array.from({length:r},(i,s)=>p.jsx(Fa,{index:s,archived:e,components:t},s)),[r,e,t])};Ba.displayName="ThreadListPrimitive.Items";var za=y.forwardRef((e,t)=>p.jsx(Ze.div,E(m({},e),{ref:t})));za.displayName="ThreadListPrimitive.Root";var Ra=y.forwardRef((e,t)=>{const r=ie(({threads:n,threadListItem:i})=>n.mainThreadId===i.id);return p.jsx(Ze.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});Ra.displayName="ThreadListItemPrimitive.Root";var Sf=()=>{const e=ue();return y.useCallback(()=>{e.threadListItem().delete()},[e])},kf=Fn("ThreadListItemPrimitive.Delete",Sf),_f=()=>{const e=ue();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},Tf=Fn("ThreadListItemPrimitive.Trigger",_f);class ja{constructor(t,r,n=!1){T(this,"baseUrl");T(this,"sessionToken",null);T(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return P(this,null,function*(){const n=this.getUrl("/v1/chats"),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const a=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:s,body:JSON.stringify(a),signal:r});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return P(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r,{method:"GET",headers:n});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}listChats(t){return P(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}generateIdempotencyKey(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch(n){}const t=n=>Array.from({length:n},()=>Math.floor(Math.random()*16).toString(16)).join(""),r=()=>{const n=["8","9","a","b"];return n[Math.floor(Math.random()*n.length)]};return`${t(8)}-${t(4)}-4${t(3)}-${r()}${t(3)}-${t(12)}`}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,i=this.getUrl(n),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(f){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return P(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),i=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"DELETE",headers:a});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}listModels(t){return P(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}getModel(t){return P(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r,{method:"GET",headers:n});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}}function Cf(e,t){return wr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let i="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:s,value:a}=yield new it(r.read());if(s)break;i+=n.decode(a,{stream:!0});const o=i.split(`
5
+ `),wi=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},xi=class extends wi{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},ic=class extends xi{get source(){return"thread-composer"}},sc=class extends xi{get source(){return"edit-composer"}},oc=class extends wi{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},vi=class extends Or{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var s;const i=this.config.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Si=Object.freeze([]),ki=Object.freeze({}),lc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(a=e==null?void 0:e.attachments)!=null?a:Si,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:ki,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},uc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(a=e==null?void 0:e.text)!=null?a:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:Si,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:ki,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},_i=class{constructor(e){C(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new vi({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},cc=class extends _i{constructor(t){const r=new An({path:t.path,getState:()=>lc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});C(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new ic(new Ve({path:E(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"thread-composer"}):qe},subscribe:r=>this._core.subscribe(r)}),this._core)}},dc=class extends _i{constructor(t,r){const n=new An({path:t.path,getState:()=>uc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});C(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new sc(new Ve({path:E(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"edit-composer"}):qe},subscribe:r=>this._core.subscribe(r)}),this._core)}},hc=class bn{constructor(t=null){C(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>bn.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return bn.updatePath(t,r.path,()=>r.value);case"append-text":return bn.updatePath(t,r.path,a=>{if(typeof a!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return a+r.value});default:{const a=n;throw new Error(`Invalid operation type: ${a}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[a,...i]=r;if(Array.isArray(t)){const o=Number(a);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],i,n),l}const s=m({},t);return s[a]=this.updatePath(s[a],i,n),s}},fc=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Rr=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],a=r(e.parts[n]);return E(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},pc=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},mc=(e,t)=>Rr(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),gc=(e,t)=>Rr(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),yc=(e,t)=>Rr(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,i=(n=Lr(a))!=null?n:r.args;return E(m({},r),{argsText:a,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),bc=(e,t)=>Rr(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Ti=(e,t)=>{var n,a;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((a=e.status)==null?void 0:a.reason)==="error")return e;const r=wc(t);return E(m({},e),{status:r})},wc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},xc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),vc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Sc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),kc=(e,t)=>{var a;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((a=r[n])==null?void 0:a.state)==="started"?r[n]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:gi(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},_c=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Tc=(e,t)=>{const r=new hc(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},Cc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Ic=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:fc(),a;const i=t?Cc(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(s){a=s},transform(s){const o=s.type;switch(o){case"part-start":n=pc(n,s);break;case"tool-call-args-text-finish":n=mc(n,s);break;case"part-finish":n=gc(n,s);break;case"text-delta":n=yc(n,s);break;case"result":n=bc(n,s);break;case"message-finish":n=Ti(n,s);break;case"annotations":n=xc(n,s);break;case"data":n=vc(n,s);break;case"step-start":n=Sc(n,s);break;case"step-finish":n=kc(n,s);break;case"error":n=_c(n,s),r==null||r(s.error);break;case"update-state":n=Tc(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}i()},flush(s){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=Ti(n,{finishReason:d?"tool-calls":"unknown"}),s.enqueue(n)}}})}},Ec=class extends pi{constructor(){super(e=>{const t=new rc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Ac=class wn{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new wn(t.pipeThrough(new Ic))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=Mt(this),n,a,i;n=!(a=yield r.next()).done;n=!1){const s=a.value;t=s}}catch(a){i=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(i)throw i[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return P(this,null,function*(){const{done:n,value:a}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:a}})}}}tee(){const[t,r]=this.readable.tee();return[new wn(t),new wn(r)]}},Ci=Symbol.for("aui.tool-response"),ut=class Za{constructor(t){C(this,"artifact");C(this,"result");C(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[Ci](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Ci in t}static toResponse(t){return t instanceof Za?t:new Za({result:t===void 0?"<no result>":t})}};function Pc(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function tr(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var Mc=class{constructor(e,t,r){C(this,"resolve");C(this,"reject");C(this,"disposed",!1);C(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(Nt(e,this.fieldPath)==="complete"){const t=tr(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Ii=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=tr(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Ei=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=tr(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Ai=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=tr(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];Nt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Nc=class{constructor(e){C(this,"argTextDeltas");C(this,"handles",new Set);C(this,"args",Lr(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const a=Lr(e);if(a!==void 0){this.args=a;for(const i of this.handles)i.update(a)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new Mc(t,r,e);if(this.args&&Nt(this.args,e)==="complete"){const a=tr(this.args,e);if(a!==void 0){t(a);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Ii(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Ii){n.dispose(),this.handles.delete(n);break}}});return Tn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Ei(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Ei){n.dispose(),this.handles.delete(n);break}}});return Tn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Ai(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Ai){n.dispose(),this.handles.delete(n);break}}});return Tn(r)}},Lc=class{constructor(e){this.promise=e}get(){return this.promise}},Dc=class{constructor(){C(this,"args");C(this,"response");C(this,"writable");C(this,"resolve");C(this,"argsText","");C(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Nc(e.readable);const{promise:t,resolve:r}=In();this.resolve=r,this.response=new Lc(t)}appendArgsTextDelta(e){return P(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Oc=class extends pi{constructor(e){const t=new Map,r=new Map;super(n=>{const a=new TransformStream({transform(s,o){switch((s.type!=="part-finish"||s.meta.type!=="tool-call")&&o.enqueue(s),s.type){case"part-start":if(s.part.type==="tool-call"){const u=new Dc;r.set(s.part.toolCallId,u),e.streamCall({reader:u,toolCallId:s.part.toolCallId,toolName:s.part.toolName})}break;case"text-delta":{if(s.meta.type==="tool-call"){const u=s.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new ut({result:s.result,artifact:s.artifact,isError:s.isError}));break}case"tool-call-args-text-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=s.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let f=!1;const h=Pc(()=>{var w;let g;try{g=_n.parse(c.argsText)}catch(b){throw new Error(`Function parameter parsing failed. ${JSON.stringify(b.message)}`)}const S=e.execute({toolCallId:u,toolName:d,args:g});return S!==void 0&&(f=!0,(w=e.onExecutionStart)==null||w.call(e,u,d)),S},g=>{var w;if(f&&((w=e.onExecutionEnd)==null||w.call(e,u,d)),g===void 0)return;const S=new ut({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(S),o.enqueue(m({type:"result",path:s.path},S))},g=>{var w;f&&((w=e.onExecutionEnd)==null||w.call(e,u,d));const S=new ut({result:String(g),isError:!0});c.setResponse(S),o.enqueue(m({type:"result",path:s.path},S))});h&&t.set(u,h);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(s)}):o.enqueue(s)}}},flush(){return P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new mi).pipeThrough(a)})}},Fc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function Bc(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(s=>P(null,null,function*(){var d;if(t.aborted)return new ut({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Fc(a.parameters)){let c=a.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=a.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new ut({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=P(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return ut.toResponse(c)});return Promise.race([u,l])}))(a.execute)}function zc(e,t,r,n,a){var i,s;(s=(i=e==null?void 0:e[n.toolName])==null?void 0:i.streamCall)==null||s.call(i,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function Rc(e,t,r,n){const a=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new Oc({execute:s=>Bc(a(),i(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=H(u,["reader"]);return zc(a(),i(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Pi=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,a=t.toolCallId,i=ut.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},jr=class extends Or{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var s;const i=this.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Ur=Object.freeze({type:"complete"}),jc=(e,t,r)=>{if(e.role!=="assistant")return Ur;if(r.type==="tool-call")return r.result?Ur:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Ur:n?e.status:Ur},Mi=(e,t)=>{const r=e.content[t];if(!r)return qe;const n=jc(e,t,r);return Object.freeze(E(m({},r),{[Br]:r[Br],status:n}))},Uc=class{constructor(e,t){C(this,"composer");C(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new dc(new jr({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:a=n.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:a})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const a=this._threadBinding.getState().getBranches(r.id);let i=t;if(e==="previous"?i=a[r.branchNumber-2]:e==="next"&&(i=a[r.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return zr(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new Pi(new Ve({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>Mi(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Pi(new Ve({path:E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?qe:Mi(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new oc(new Ve({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?E(m({},r),{source:"message"}):qe},subscribe:t=>this._core.subscribe(t)}))}},$c=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},Hc=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},qc=(e,t)=>{var r,n,a,i,s,o,l,u,d,c,f;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(a=t.createdAt)!=null?a:new Date,parentId:(o=(s=t.parentId)!=null?s:(i=e.at(-1))==null?void 0:i.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},Vc=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},Ni=class{constructor(e,t){C(this,"_threadBinding");C(this,"composer");C(this,"_eventSubscriptionSubjects",new Map);const r=new Ve({path:e.path,getState:()=>Vc(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),i=t.subscribe(n);return()=>{a(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new cc(new jr({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(qc(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(Hc(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun($c(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,a;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(a=(n=t[e-1])==null?void 0:n.id)!=null?a:null,index:e}})}getMessageById(e){return this._getMessageRuntime(E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new Uc(new Ve({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:a}=(d=t())!=null?d:{},{messages:i,speech:s}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return qe;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[Br]:r[Br],index:a,isLast:((c=i.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(s==null?void 0:s.messageId)===r.id?s:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new vi({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Wc=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),$r=(e,t)=>{if(t===void 0)return qe;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:qe},Jc=class{constructor(e,t=Ni){C(this,"_getState");C(this,"_mainThreadListItemRuntime");C(this,"main");this._core=e,this._runtimeFactory=t;const r=new An({path:{},getState:()=>Wc(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Fr(new Ve({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>$r(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new jr({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new jr({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new Fr(new Ve({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>$r(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Fr(new Ve({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>$r(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Fr(new Ve({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>$r(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Kc=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",Gc=class{constructor(e){C(this,"accept","*");C(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Pr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=Kc(e.type);let a={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield a;try{const{signedUrl:i,publicUrl:s}=yield new lt(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new lt(fetch(i,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),a=E(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(i){a=E(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],E(m({},e),{status:{type:"complete"},content:r})})}},Pn=y.createContext(null),Mn=({adapters:e,children:t})=>{const r=y.useContext(Pn);return p.jsx(Pn.Provider,{value:m(m({},r),e),children:t})},Yc=()=>y.useContext(Pn),Xc=class extends ni{constructor(t,r,{parentId:n,message:a}){var i;super();C(this,"_nonTextParts");C(this,"_previousText");C(this,"_parentId");C(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=zr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((i=a.attachments)!=null?i:[]),this._nonTextParts=a.content.filter(s=>s.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return P(this,null,function*(){zr(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},Qc=class{constructor(e){C(this,"_subscriptions",new Set);C(this,"_isInitialized",!1);C(this,"repository",new bi);C(this,"composer",new ai(this));C(this,"_editComposers",new Map);C(this,"_stopSpeaking");C(this,"speech");C(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new Xc(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var i;const r=(i=this.adapters)==null?void 0:i.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:a}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const s=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,s)}this._notifySubscribers()}speak(e){var i,s;const t=(i=this.adapters)==null?void 0:i.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(s=this._stopSpeaking)==null||s.call(this);const n=t.speak(zr(r)),a=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),a(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(En.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,i;if(e==="model-context-update")return(i=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?i:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},Zc=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function ed({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=y.useRef({}),i=y.useRef(new Map),s=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[h,g]=yi(),S=Rc(t,()=>{var w,b;return(b=(w=s.current)==null?void 0:w.signal)!=null?b:new AbortController().signal},(w,b)=>new Promise((T,_)=>{const F=i.current.get(w);F&&F.reject(new Error("Human input request was superseded by a new request")),i.current.set(w,{resolve:T,reject:_}),n(z=>E(m({},z),{[w]:{type:"interrupt",payload:{type:"human",payload:b}}}))}),{onExecutionStart:w=>{o.current++,n(b=>E(m({},b),{[w]:{type:"executing"}}))},onExecutionEnd:w=>{o.current--,n(b=>{const T=m({},b);return delete T[w],T}),o.current===0&&(l.current.forEach(b=>b()),l.current=[])}});return h.pipeThrough(S).pipeThrough(new mi).pipeTo(new WritableStream({write(w){var b;if(w.type==="result"){if((b=a.current[w.meta.toolCallId])!=null&&b.hasResult)return;r(m({type:"add-tool-result",toolCallId:w.meta.toolCallId,toolName:w.meta.toolName,result:w.result,isError:w.isError},w.artifact&&{artifact:w.artifact}))}}})),g}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const h=g=>{g.forEach(S=>{S.content.forEach(w=>{if(w.type==="tool-call"){if(c.current)d.current.add(w.toolCallId);else{if(d.current.has(w.toolCallId))return;let b=a.current[w.toolCallId];if(b||(b={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:w.toolName,toolCallId:w.toolCallId})},a.current[w.toolCallId]=b),w.argsText!==b.argsText)if(b.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:b.argsText,next:w.argsText});else{if(!w.argsText.startsWith(b.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${w.argsText} does not start with ${b.argsText}`);const T=w.argsText.slice(b.argsText.length);b.controller.argsText.append(T);const _=Zc(w.argsText);_&&b.controller.argsText.close(),a.current[w.toolCallId]={argsText:w.argsText,hasResult:b.hasResult,argsComplete:_,controller:b.controller}}w.result!==void 0&&!b.hasResult&&(b.controller.setResponse(new ut({result:w.result,artifact:w.artifact,isError:w.isError})),b.controller.close(),a.current[w.toolCallId]={hasResult:!0,argsComplete:!0,argsText:b.argsText,controller:b.controller})}w.messages&&h(w.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u,r]);const f=()=>(i.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),i.current.clear(),s.current.abort(),s.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),c.current=!0},abort:f,resume:(h,g)=>{const S=i.current.get(h);if(S)i.current.delete(h),n(w=>E(m({},w),{[h]:{type:"executing"}})),S.resolve(g);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var td=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function rd(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,a=t.cells[n];if(a.type!=="effect")throw new Error("Cannot find effect cell");let i=!0;if(a.deps!==void 0&&r.deps!==void 0&&(i=a.deps.length!==r.deps.length||a.deps.some((s,o)=>!Object.is(s,r.deps[o]))),i){if(a.mounted){if(typeof a.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{a.mounted&&a.cleanup&&a.cleanup()}finally{a.mounted=!1}}try{const s=r.effect();if(s!==void 0&&typeof s!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof s}`);a.mounted=!0,a.cleanup=typeof s=="function"?s:void 0,a.deps=r.deps}catch(s){throw s}}})}function nd(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(a){t==null&&(t=a)}finally{n.mounted=!1}}if(t!=null)throw t}var rr=null;function ad(e,t){e.currentIndex=0;const r=rr;rr=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{rr=r}}function Nn(){if(!rr)throw new Error("No resource fiber available");return rr}function Li(e,t){const r=e[Di];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var Di=Symbol("fnSymbol");function Hr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Lt(e){e.isMounted=!1,nd(e)}function nr(e,t){const r={commitTasks:[],props:t,state:void 0};return ad(e,()=>{e.renderContext=r;try{r.state=Li(e.resource,t)}finally{e.renderContext=void 0}}),r}function Dt(e,t){e.isMounted=!0,e.isNeverMounted=!1,rd(t,e)}var id=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,Oi=id?y.useEffect:y.useLayoutEffect;function Ln(e){const[,t]=y.useState({}),r=y.useMemo(()=>Hr(e.type,()=>t({})),[e.type,t]),n=nr(r,e.props);return Oi(()=>()=>Lt(r),[]),Oi(()=>{Dt(r,n)}),n.state}var Ot=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},bt=(e,t,r)=>t===e,Ft,Dn=()=>{if(Ft)return Ft;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Ft=e(),Ft;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Ft=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,Ft=r,r},sd=(Ge=class{static register(t){var o,l;const r=Dn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},i=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>Ge.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),Ge.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{Ge.notifyListeners(n)});return r.apis.set(n,a),Ge.notifyListeners(n),()=>{const u=Dn();u.apis.get(n)&&(i==null||i(),s==null||s(),u.apis.delete(n),Ge.notifyListeners(n))}}static notifyListeners(t){Dn().listeners.forEach(n=>n(t))}},C(Ge,"MAX_EVENT_LOGS_PER_API",200),Ge);function ce(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[Di]=e,t}var od=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function ld(e){const t=Nn(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const i={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=i.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(i.value=l,od(t))}};t.cells[r]=i}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function Qe(e){const t=ld(e);return[t.value,t.set]}function ud(){const e=Nn(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function ke(e,t){const r=Nn(),n=ud();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Bt(e){const[t]=Qe(()=>({current:e}));return t}var cd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},re=(e,t)=>{const r=Bt();return r.current||(r.current={value:e(),deps:t}),cd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function qr(e,t){const[r,n]=Qe({}),a=re(()=>Hr(e.type,()=>n({})),[e.type]),i=t?re(()=>e.props,t):e.props,s=re(()=>nr(a,i),[a,i,r]);return ke(()=>()=>Lt(a),[a]),ke(()=>{Dt(a,s)},[a,s]),s.state}function We(e){return Li(e.type,e.props)}function Fi(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=Qe({}),a=re(()=>new Map(e.map(o=>[o.key,o])),[e]),[i]=Qe(()=>new Map),s=re(()=>{const o=new Map,l=new Set;return a.forEach((u,d)=>{l.add(d);let c=i.get(d);(!c||c.resource!==u.type)&&(c&&Lt(c),c=Hr(u.type,()=>n({})),i.set(d,c));const f=nr(c,u.props);o.set(d,f)}),i.forEach((u,d)=>{l.has(d)||(Lt(u),i.delete(d))}),o},[a,r]);return ke(()=>{s.forEach((o,l)=>{const u=i.get(l);u&&Dt(u,o)})},[s,i]),ke(()=>()=>{i.forEach(o=>{Lt(o)}),i.clear()},[i]),re(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var On=[],Fn=!1;function dd(){Fn=!1;const e=On;On=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function hd(e){On.push(e),Fn||(Fn=!0,queueMicrotask(dd))}var fd=(Tt=class{constructor(t){C(this,"_isDirty",!1);C(this,"_hasScheduledTask",!1);C(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,hd(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Tt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},C(Tt,"MAX_FLUSH_DEPTH",50),Tt),pd=ce(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,i]=Qe(e.props),s=We({type:e.type,props:a}),o=Bt(new Set).current,l=Bt(s);return ke(()=>{s!==l.current&&(l.current=s,o.forEach(d=>d()))}),re(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),i(()=>d)},flushSync:r,dispose:n}),[])}),md=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Dt(i,s))},onFlushSync:()=>{a.flushSync()},onDispose:()=>Lt(i)},a=new fd(()=>{s=nr(i,n),r&&Dt(i,s)}),i=Hr(pd,()=>a.markDirty());let s=nr(i,n);return r&&Dt(i,s),s.state},ar=Symbol("tap.Context"),Bi=e=>({[ar]:e}),zi=(e,t,r)=>{const n=e[ar];e[ar]=t;try{return r()}finally{e[ar]=n}},Ri=e=>e[ar];const ji=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const f=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(h=>h(t,f))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,a,o);return o},gd=(e=>e?ji(e):ji),yd=e=>e;function bd(e,t=yd){const r=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(r),r}const Ui=e=>{const t=gd(e),r=n=>bd(t,n);return Object.assign(r,t),r},zt=(e=>e?Ui(e):Ui);function $i(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Hi(...e){return t=>{let r=!1;const n=e.map(a=>{const i=$i(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a<n.length;a++){const i=n[a];typeof i=="function"?i():$i(e[a],null)}}}}function Vr(...e){return K.useCallback(Hi(...e),e)}var qi=ce(e=>{const t=re(()=>md(e,!0),[e.type]);return ke(()=>{t.updateInput(e.props)}),t}),wd=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},Je=(e,t)=>{const r=Bt(e);ke(()=>{r.current=e});const n=re(()=>new Proxy({},new wd(()=>r.current)),[]),a=t==null?void 0:t.key,i=e.getState();return re(()=>({key:a,state:i,api:n}),[i,a])},ct=ce(e=>{const t=Bt(e.get);return ke(()=>{t.current=e.get}),re(()=>be({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),xd=ce(e=>{const t=qr(e.scopeElement);return re(()=>[e.fieldName,t],[e.fieldName,t])}),vd=ce(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=H(o,["on","subscribe","flushSync"]),i=Bt({on:t,subscribe:r,flushSync:n});ke(()=>{i.current={on:t,subscribe:r,flushSync:n}});const s=Fi(Object.entries(a).map(([l,u])=>xd({fieldName:l,scopeElement:u},{key:l})));return re(()=>{const l=Object.fromEntries(s),{on:u,subscribe:d,flushSync:c}=i.current;return u&&(l.on=(f,h)=>u(f,h)),d&&(l.subscribe=f=>d(f)),c&&(l.flushSync=()=>c()),l},[...s])}),Vi=Bi(null),Sd=(e,t)=>zi(Vi,e,t),Wi=()=>{const e=Ri(Vi);if(!e)throw new Error("Model context is not available in this context");return e},kd=ce(({toolkit:e})=>{const[t,r]=Qe(()=>({tools:{}})),n=Wi();ke(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(a(l,u.render));const s=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=H(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:s})};return i.push(n.register(o)),()=>{i.forEach(l=>l())}},[e,n]);const a=(i,s)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(d=>d!==s))!=null?u:[]})})})});return Je({getState:()=>t,setToolUI:a})}),_d=ce(()=>re(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const a=t.get(r);return a.add(n),()=>{a.delete(n),a.size===0&&t.delete(r)}},emit:(r,n)=>{const a=t.get(r),i=t.get("*");!a&&!i||queueMicrotask(()=>{if(a)for(const s of a)s(n);if(i)for(const s of i)s({event:r,payload:n})})}}},[])),Ji=Bi(null),Td=(e,t)=>zi(Ji,e,t),Bn=()=>{const e=Ri(Ji);if(!e)throw new Error("Events context is not available");return e},Cd=ce(()=>{const[e]=Qe(()=>({})),t=new Sn;return Je({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),Id=ce(({threads:e,modelContext:t,tools:r})=>{const n=We(_d()),{threads:a,tools:i,modelContext:s}=Td(n,()=>{const l=qr(t!=null?t:Cd(),[t]);return Sd(l.api,()=>({modelContext:l,tools:qr(r!=null?r:kd({}),[r]),threads:qr(e,[e])}))}),o=re(()=>({threads:a.state,tools:i.state,modelContext:s.state}),[a.state,i.state,s.state]);return Je({getState:()=>o,threads:a.api,tools:i.api,modelContext:s.api,on:n.on})}),Ed=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:be({source:"root",query:{},get:()=>e.getState().api.threads}),tools:be({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:be({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:be({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:be({source:"threads",query:{type:"main"},get:()=>t()}),composer:be({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:i}=Ot(r);if(i==="*")return e.getState().api.on(a,n);if(bt("thread",i)||bt("thread-list-item",i)||bt("composer",i))return e.getState().api.on(a,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${i}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Ad=e=>{const t=Wr(),r=Ln(qi(Id(e))),n=y.useMemo(()=>Ed(r),[r]);return y.useMemo(()=>Gi(t,n),[t,n])},be=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},dt=()=>()=>{},Ki=y.createContext({threads:be({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:be({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:be({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:be({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:be({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:be({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:be({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:be({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:be({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:dt,flushSync:dt,on:e=>{const{scope:t}=Ot(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Wr=()=>y.useContext(Ki),wt=e=>{const t=Wr(),r=Ln(vd(e));return y.useMemo(()=>Gi(t,r),[t,r])},Pd=e=>Ad(e);function le(e){return e?Pd(e):Wr()}var Md=(e,t)=>e===dt?t:t===dt?e:(...r)=>{e(...r),t(...r)},Nd=(e,t)=>e===dt?t:t===dt?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},Gi=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:Nd(e.subscribe,r!=null?r:dt),flushSync:Md(e.flushSync,n!=null?n:dt)})},ht=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return sd.register(e)},[e,r]),p.jsx(Ki.Provider,{value:e,children:t})),Yi=(gu=class{constructor(e){Kt(this,Ue);Gt(this,Ue,e)}get threads(){return Be(this,Ue).threads().getState()}get tools(){return Be(this,Ue).tools().getState()}get threadListItem(){return Be(this,Ue).threadListItem().getState()}get thread(){return Be(this,Ue).thread().getState()}get composer(){return Be(this,Ue).composer().getState()}get message(){return Be(this,Ue).message().getState()}get part(){return Be(this,Ue).part().getState()}get attachment(){return Be(this,Ue).attachment().getState()}},Ue=new WeakMap,gu),ee=e=>{const t=le(),r=y.useMemo(()=>new Yi(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof Yi)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},zn=(e,t)=>{const r=le(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:a,event:i}=Ot(e);y.useEffect(()=>r.on({scope:a,event:i},s=>n.current(s)),[r,a,i])};function Ld(e,t){function r(n){const a=y.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function Xi(e,t){function r(a){const i=e(a);return i?i[t]:null}function n(a){let i=!1,s;typeof a=="function"?s=a:a&&typeof a=="object"&&(i=!!a.optional,s=a.selector);const o=r({optional:i});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var Qi=y.createContext(null),Dd=Ld(Qi,"ThreadPrimitive.Viewport"),{useThreadViewport:Jr,useThreadViewportStore:Rn}=Xi(Dd,"useThreadViewport"),Od=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Fd(e,t=Bd){Od(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var Bd=e=>e;function Zi(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const i=e({optional:n});return i?Fd(i,a):null}return t}function es(e){const t=le(),r=ee(()=>{var n,a,i;return t.thread.source&&(i=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var zd=Zi(es);function Rd(e){const t=le(),r=ee(()=>{var n,a,i;return t.threadListItem.source&&(i=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var ts=Zi(Rd),xt=e=>{const[,t]=Qe(e.getState);return ke(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},jd=ce(({runtime:e})=>{const t=xt(e),r=Bn();return ke(()=>{const n=[],a=["switched-to","switched-away"];for(const i of a){const s=e.unstable_on(i,()=>{r.emit(`thread-list-item.${i}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const i of n)i()}},[e,r]),Je({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),ir=e=>{const t=Fi(e);return{state:t.map(r=>r.state),api:r=>{var a,i;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(i=t.find(s=>s.key===r.key))==null?void 0:i.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},rs=ce(({runtime:e})=>{const t=xt(e);return Je({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Ud=ce(({runtime:e,index:t})=>{const r=re(()=>e.getAttachmentByIndex(t),[e,t]);return We(rs({runtime:r}))}),ns=ce(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=xt(r),a=Bn();ke(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{a.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,a,e,t]);const i=ir(n.attachments.map((l,u)=>Ud({runtime:r,index:u},{key:u}))),s=re(()=>{var l;return{text:n.text,role:n.role,attachments:i.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,i.state]);return Je({getState:()=>s,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?i.api({key:l.id}):i.api(l),__internal_getRuntime:()=>r})}),$d=ce(({runtime:e})=>{const t=xt(e);return Je({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),Hd=ce(({runtime:e,index:t})=>{const r=re(()=>e.getAttachmentByIndex(t),[e,t]);return We(rs({runtime:r}))}),qd=ce(({runtime:e,index:t})=>{const r=re(()=>e.getMessagePartByIndex(t),[e,t]);return We($d({runtime:r}))}),Vd=ce(({runtime:e,threadIdRef:t})=>{var f,h;const r=xt(e),[n,a]=Qe(!1),[i,s]=Qe(!1),o=re(()=>({get current(){return e.getState().id}}),[e]),l=We(ns({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=ir(r.content.map((g,S)=>qd({runtime:e,index:S},{key:S}))),d=ir((h=(f=r.attachments)==null?void 0:f.map((g,S)=>Hd({runtime:e,index:S},{key:S})))!=null?h:[]),c=re(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:i}),[r,u.state,l.state,n,i]);return Je({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:a,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),Wd=ce(({runtime:e,id:t,threadIdRef:r})=>{const n=re(()=>e.getMessageById(t),[e,t]);return We(Vd({runtime:n,threadIdRef:r}))}),Jd=ce(({runtime:e})=>{const t=xt(e),r=Bn();ke(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var f;const c=((f=e.getState())==null?void 0:f.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=re(()=>({get current(){return e.getState().threadId}}),[e]),a=We(ns({runtime:e.composer,threadIdRef:n})),i=ir(t.messages.map(o=>Wd({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=re(()=>({isEmpty:i.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:a.state,messages:i.state}),[t,i,a.state]);return Je({getState:()=>s,composer:a.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.api({key:o.id}):i.api(o),__internal_getRuntime:()=>e})}),Kd=ce(({runtime:e,id:t})=>{const r=re(()=>e.getItemById(t),[e,t]);return We(jd({runtime:r}))}),Gd=ce(({runtime:e,__internal_assistantRuntime:t})=>{const r=xt(e),n=We(Jd({runtime:e.main})),a=ir(Object.keys(r.threadItems).map(s=>Kd({runtime:e,id:s},{key:s}))),i=re(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return Je({getState:()=>i,thread:()=>n.api,item:s=>{if(s==="main")return a.api({key:i.mainThreadId});if("id"in s)return a.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?i.archivedThreadIds[o]:i.threadIds[o];return a.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),Yd=ce(e=>{const t=Wi();return ke(()=>e.registerModelContextProvider(t),[e,t]),We(Gd({runtime:e.threads,__internal_assistantRuntime:e}))}),jn=e=>{const t=new Map,r=()=>{let n=0;for(const a of t.values())n+=a;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:a=>{t.get(n)!==a&&(t.set(n,a),r())},unregister:()=>{t.delete(n),r()}}}}},Xd=(e={})=>{const t=new Set,r=jn(s=>{i.setState({height:E(m({},i.getState().height),{viewport:s})})}),n=jn(s=>{i.setState({height:E(m({},i.getState().height),{inset:s})})}),a=jn(s=>{i.setState({height:E(m({},i.getState().height),{userMessage:s})})}),i=zt(()=>{var s;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(s=e.turnAnchor)!=null?s:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:a.register}});return i},sr=e=>e,Qd=e=>{const t=Rn({optional:!0}),[r]=y.useState(()=>Xd(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),y.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&sr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var i;const n={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&sr(r).setState(n)},[r,e.turnAnchor]),r},as=({children:e,options:t={}})=>{const r=Qd(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(Qi.Provider,{value:n,children:e})},Zd=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},eh=({children:e,runtime:t})=>{const r=le({threads:Yd(t)}),n=Zd(t);return p.jsxs(ht,{api:r,children:[n&&p.jsx(n,{}),p.jsx(as,{children:e})]})},is=y.memo(eh),th=({index:e,archived:t,children:r})=>{const n=le(),a=wt({threadListItem:ct({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(i,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=Ot(i);return bt("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&s(d)}):n.on(i,s)}});return p.jsx(ht,{api:a,children:r})},rh=({id:e,children:t})=>{const r=le(),n=wt({threadListItem:ct({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,i){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=Ot(a);return bt("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&i(u)}):r.on(a,i)}});return p.jsx(ht,{api:n,children:t})},nh=({index:e,children:t})=>{const r=le(),n=wt({message:ct({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:ct({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,i){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=Ot(a);return!bt("composer",l)&&!bt("message",l)?r.on(a,i):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&i(u)})}});return p.jsx(ht,{api:n,children:t})},ah=({index:e,children:t})=>{const r=le(),n=wt({part:ct({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(ht,{api:n,children:t})},ih=({index:e,children:t})=>{const r=le(),n=wt({attachment:ct({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(ht,{api:n,children:t})},sh=({index:e,children:t})=>{const r=le(),n=wt({attachment:ct({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(ht,{api:n,children:t})},oh=ce(({text:e,isRunning:t})=>{const r=re(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return Je({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),lh=({text:e,isRunning:t=!1,children:r})=>{const n=Ln(qi(oh({text:e,isRunning:t}))),a=wt({part:ct({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(ht,{api:a,children:r})},ss=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result||!t.includes(a.toolName))},Un=class extends Error{constructor(t,r){super(r);C(this,"name","AbortError");C(this,"detach");this.detach=t}},uh=class extends Qc{constructor(t,r){super(t);C(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});C(this,"abortController",null);C(this,"isDisabled",!1);C(this,"_isLoading",!1);C(this,"_suggestions",[]);C(this,"_suggestionsController",null);C(this,"_options");C(this,"_lastRunConfig",{});C(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var s,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((s=t.adapters)==null?void 0:s.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const i=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==i&&(this.capabilities.feedback=i,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(a=>{var s,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const i=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&i&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},i)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var a,i,s;this.ensureInitialized();const r=er(t,gt(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(a=this._options.adapters.history)==null||a.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((i=t.startRun)!=null?i:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(s=t.runConfig)!=null?s:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var a=n,{stream:t}=a,r=H(a,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(a,i){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:gt(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(ss(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const w=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in w)try{for(var f=Mt(w),h,g,S;h=!(g=yield f.next()).done;h=!1){const b=g.value;if(l.aborted)break;this._suggestions=b,this._notifySubscribers()}}catch(g){S=[g]}finally{try{h&&(g=f.return)&&(yield g.call(f))}finally{if(S)throw S[0]}}else{const b=yield w;if(l.aborted)return;this._suggestions=b,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return P(this,null,function*(){var g,S,w,b,T,_,F,z,I,D;const i=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const s=r.content,o=(S=r.metadata)==null?void 0:S.unstable_annotations,l=(w=r.metadata)==null?void 0:w.unstable_data,u=(b=r.metadata)==null?void 0:b.steps,d=(T=r.metadata)==null?void 0:T.custom,c=M=>{var Ie,x,ve,Pe,v,me;const W=(Ie=M.metadata)==null?void 0:Ie.steps,B=W?[...u!=null?u:[],...W]:void 0,O=(x=M.metadata)==null?void 0:x.unstable_annotations,X=(ve=M.metadata)==null?void 0:ve.unstable_data,ae=O?[...o!=null?o:[],...O]:void 0,ye=X?[...l!=null?l:[],...X]:void 0;r=m(E(m(m({},r),M.content?{content:[...s,...(Pe=M.content)!=null?Pe:[]]}:void 0),{status:(v=M.status)!=null?v:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),ae?{unstable_annotations:ae}:void 0),ye?{unstable_data:ye}:void 0),B?{steps:B}:void 0),(me=M.metadata)!=null&&me.custom?{custom:m(m({},d!=null?d:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(_=this._options.maxSteps)!=null?_:2;if(((I=(z=(F=r.metadata)==null?void 0:F.steps)==null?void 0:z.length)!=null?I:0)>=f)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const M=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const W=this.abortController.signal,B=a({messages:i,runConfig:this._lastRunConfig,abortSignal:W,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in B)try{for(var U=Mt(B),j,R,k;j=!(R=yield U.next()).done;j=!1){const O=R.value;if(W.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(O)}}catch(R){k=[R]}finally{try{j&&(R=U.return)&&(yield R.call(U))}finally{if(k)throw k[0]}}else c(yield B);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof Un)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(D=this._options.adapters.history)==null?void 0:D.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new Un(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new Un(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:i}){const s=this.repository.getMessage(t),{parentId:o}=s;let{message:l}=s;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(f=>f.type!=="tool-call"||f.toolCallId!==r?f:(d=!0,f.result||(u=!0),E(m({},f),{result:n,artifact:i,isError:a})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&ss(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},os=Object.freeze([]),$n="__DEFAULT_ID__",ch=Object.freeze({[$n]:{id:$n,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),dh=class extends Qt{constructor(t){super();C(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw os}get archivedThreadIds(){throw os}get mainThreadId(){return $n}get threadData(){return ch}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return P(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},hh=class extends kn{constructor(t,r){super();C(this,"threads");C(this,"Provider");C(this,"_options");this._options=t,this.threads=new dh(()=>new uh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(En.fromArray(r))}},ls=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const a=atob(n),s=JSON.parse(a).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},us=(yu=class{constructor(e){C(this,"strategy","jwt");C(this,"cachedToken",null);C(this,"tokenExpiry",null);Kt(this,vr);Gt(this,vr,e)}getAuthHeaders(){return P(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield Be(this,vr).call(this);return t?(this.cachedToken=t,this.tokenExpiry=ls(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=ls(n)}},vr=new WeakMap,yu),fh=(bu=class{constructor(e,t,r){C(this,"strategy","api-key");Kt(this,Sr);Kt(this,kr);Kt(this,_r);Gt(this,Sr,e),Gt(this,kr,t),Gt(this,_r,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${Be(this,Sr)}`,"Aui-User-Id":Be(this,kr),"Aui-Workspace-Id":Be(this,_r)}})}readAuthHeaders(){}},Sr=new WeakMap,kr=new WeakMap,_r=new WeakMap,bu),Kr="aui:refresh_token",ph=class{constructor(e){C(this,"strategy","anon");C(this,"baseUrl");C(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new us(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Kr),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:f}=d;return f&&localStorage.setItem(Kr,JSON.stringify(f)),c}}else localStorage.removeItem(Kr);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const i=yield a.json(),{access_token:s,refresh_token:o}=i;return!s||!o?null:(localStorage.setItem(Kr,JSON.stringify(o)),s)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},mh=class extends Error{constructor(e){super(e),this.name="APIError"}},gh=class{constructor(e){C(this,"_auth");C(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new us(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new fh(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new ph(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),i=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?i.set(u,"true"):i.set(u,d.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=i.toString();const o=yield fetch(s,{method:(l=t.method)!=null?l:"GET",headers:a,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new mh(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},yh=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},bh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Cn.fromResponse(t,new Ec)})}},wh=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},xh=class{constructor(e){C(this,"messages");this.cloud=e,this.messages=new wh(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},vh=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Sh=class{constructor(e){C(this,"threads");C(this,"auth");C(this,"runs");C(this,"files");const t=new gh(e);this.threads=new xh(t),this.auth={tokens:new yh(t)},this.runs=new bh(t),this.files=new vh(t)}};function Hn(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>Hn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Hn(n,t+1)):!1}var kh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return Hn(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const a=n;throw new Error(`Message part type not supported by aui/v0: ${a}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},_h=e=>{const t=e.content,r=er(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},qn=new WeakMap,Th=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Ch=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return qn.has(this.store.threadListItem())||qn.set(this.store.threadListItem(),{}),qn.get(this.store.threadListItem())}withFormat(e){return new Th(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var i;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:"aui/v0",content:kh(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return P(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(_h).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var s;const{remoteId:a}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(a,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=i,i.then(()=>{})})}_loadWithFormat(e,t){return P(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(a=>a.format===e).map(a=>t({id:a.id,parent_id:a.parent_id,format:a.format,content:a.content})).reverse()}})}},Ih=e=>{const t=le(),[r]=y.useState(()=>new Ch(e,t));return r},cs=typeof process!="undefined"&&((wu=process==null?void 0:process.env)==null?void 0:wu.NEXT_PUBLIC_ASSISTANT_BASE_URL),Vn=cs?new Sh({baseUrl:cs,anonymous:!0}):void 0,Eh=e=>{var a;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:s}){var c;const o=Ih({get current(){var f;return(f=t.current.cloud)!=null?f:Vn}}),l=(c=t.current.cloud)!=null?c:Vn,u=y.useMemo(()=>new Gc(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Mn,{adapters:d,children:s})},[]),n=(a=e.cloud)!=null?a:Vn;return n?{list:()=>P(null,null,function*(){const{threads:i}=yield n.threads.list();return{threads:i.map(s=>{var o;return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}})}}),initialize:()=>P(null,null,function*(){var u,d;const s=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=s?s.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(i,s)=>P(null,null,function*(){return n.threads.update(i,{title:s})}),archive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,i),n.threads.delete(i)}),generateTitle:(i,s)=>P(null,null,function*(){return n.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:s})}),fetch:i=>P(null,null,function*(){var o;const s=yield n.threads.get(i);return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}}),unstable_Provider:r}:new td},Ah=(e,n)=>{var a=n,{initialMessages:t}=a,r=H(a,["initialMessages"]);var u;const d=(u=Yc())!=null?u:{},{modelContext:i}=d,s=H(d,["modelContext"]),o=y.useMemo(()=>E(m({},r),{adapters:E(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=y.useState(()=>new hh(o,t));return y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),y.useEffect(()=>{if(i)return l.registerModelContextProvider(i)},[i,l]),y.useMemo(()=>new Wn(l),[l])},ds=(e,n={})=>{var a=n,{cloud:t}=a,r=H(a,["cloud"]);const i=Eh({cloud:t});return gs({runtimeHook:function(){return Ah(e,r)},adapter:i,allowNesting:!0})},Wn=class{constructor(e){C(this,"threads");C(this,"_thread");this._core=e,this.threads=new Jc(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(En.fromArray(e!=null?e:[]))}},Ph=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i}=o,s=H(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i},otherOptions:s}};function vt(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var hs=y.createContext(null),Mh=e=>({useSmoothStatus:zt(()=>e)}),Nh=({children:e})=>{const t=fs({optional:!0}),r=le(),[n]=y.useState(()=>Mh(r.part().getState().status));return t?e:p.jsx(hs.Provider,{value:n,children:e})},Lh=e=>{const t=y.forwardRef((r,n)=>p.jsx(Nh,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function fs(e){const t=y.useContext(hs);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Dh,useSmoothStatusStore:Oh}=Xi(fs,"useSmoothStatus"),Fh=class{constructor(e,t){C(this,"animationFrameId",null);C(this,"lastUpdateTime",Date.now());C(this,"targetText","");C(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,a=Math.min(5,250/n);let i=0;for(;r>=a&&i<n;)i++,r-=a;i!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},Jn=Object.freeze({type:"running"}),ps=(e,t=!1)=>{const{text:r}=e,n=ee(({message:d})=>d.id),a=y.useRef(n),[i,s]=y.useState(r),o=Oh({optional:!0}),l=vt(d=>{if(s(d),o){const c=i!==d||e.status.type==="running"?Jn:e.status;sr(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(i!==r||e.status.type==="running")?Jn:e.status;sr(o).setState(d,!0)}},[o,t,r,i,e.status]);const[u]=y.useState(new Fh(r,l));return y.useEffect(()=>{if(!t){u.stop();return}if(a.current!==n||!r.startsWith(u.targetText)){a.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:i,status:r===i?e.status:Jn}:e,[t,i,e,r])};const Bh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Wn,BaseAssistantRuntimeCore:kn,CompositeContextProvider:Sn,DefaultThreadComposerRuntimeCore:ai,MessageRepository:bi,ThreadRuntimeImpl:Ni,fromThreadMessageLike:er,generateId:gt,getAutoStatus:si,splitLocalRuntimeOptions:Ph,useSmooth:ps,useSmoothStatus:Dh,useToolInvocations:ed,withSmoothContextProvider:Lh},Symbol.toStringTag,{value:"Module"}));var zh=class extends Qt{constructor(t){super();C(this,"useRuntimeHook");C(this,"instances",new Map);C(this,"useAliveThreadsKeysChanged",zt(()=>({})));C(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,i=y.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=a.getState(),this._notifySubscribers()},[t,a]),s=y.useRef(!1);s.current||i(),y.useEffect(()=>(s.current=!0,i(),a.outerSubscribe(i)),[a,i]);const o=le();return y.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});C(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(rh,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));C(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=zt(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const s=this.instances.get(t);if(!s)i(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)i(),r(s.runtime);else return},i=this.subscribe(a);a()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},de=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Rh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw de},append(){throw de},startRun(){throw de},resumeRun(){throw de},cancelRun(){throw de},addToolResult(){throw de},resumeToolCall(){throw de},speak(){throw de},stopSpeaking(){throw de},submitFeedback(){throw de},getModelContext(){return{}},unstable_loadExternalState(){throw de},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw de})},removeAttachment(){return P(this,null,function*(){throw de})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw de},role:"user",setRole(){throw de},runConfig:{},setRunConfig(){throw de},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw de},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw de},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw de},export(){return{messages:[]}},reset(){throw de},unstable_on(){return()=>{}}},ms=(e,t,r)=>r.reduce((n,a)=>{var i;return(i=a==null?void 0:a(n,t))!=null?i:n},e),jh=class extends Qt{constructor(t){super();C(this,"_pendingTransforms",[]);C(this,"_baseValue");C(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>ms(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=ms(this._baseValue,a,[t.optimistic,t.then]),a}finally{const a=this._pendingTransforms.indexOf(n);a>-1&&this._pendingTransforms.splice(a,1),this._updateState()}})}};function fv(e){return e}var Gr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Yr=(e,t,r)=>{const n=Gr(e,t);if(!n)return e;const{id:a,remoteId:i,status:s}=n;if(s===r)return e;const o=m({},e);switch(s){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=s;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[a,...o.threadIds];break;case"archived":o.archivedThreadIds=[a,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==a)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==a&&l!==i));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[a]:E(m({},n),{status:r})})),o},Uh=class extends Qt{constructor(t,r){super();C(this,"_options");C(this,"_hookManager");C(this,"_loadThreadsPromise");C(this,"_mainThreadId");C(this,"_state",new jh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));C(this,"useProvider");C(this,"initialize",t=>P(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>Yr(r,t,"regular"),loading:(r,n)=>{const a=t;return E(m({},r),{threadData:E(m({},r.threadData),{[a]:E(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const i=Gr(r,t);if(!i)return r;const s=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:s}),threadData:E(m({},r.threadData),{[s]:E(m({},i),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));C(this,"generateTitle",t=>P(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,a=this._hookManager.getThreadRuntimeCore(r.id);if(!a)return;const i=a.messages,s=yield this._options.adapter.generateTitle(n,i),o=Ac.fromAssistantStream(s);try{for(var u=Mt(o),d,c,f;d=!(c=yield u.next()).done;d=!1){const h=c.value;const g=(l=h.parts.filter(w=>w.type==="text")[0])==null?void 0:l.text,S=this._state.baseValue;this._state.update(E(m({},S),{threadData:E(m({},S.threadData),{[r.id]:E(m({},r),{title:g})})}))}}catch(c){f=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(f)throw f[0]}}}));C(this,"useBoundIds",zt(()=>[]));C(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(Mn,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new zh(t.runtimeHook),this.useProvider=zt(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:y.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],i={},s={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":a.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;i[o.remoteId]=l,s[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return E(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),i),threadData:m(m({},t.threadData),s)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||Rh}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return Gr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),i=this._state.value,s=a.remoteId,o=E(m({},i.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=E(m({},i.threadIdMap),{[a.remoteId]:s}),u=a.status==="regular"?[...i.threadIds,a.remoteId]:i.threadIds,d=a.status==="archived"?[...i.archivedThreadIds,a.remoteId]:i.archivedThreadIds;this._state.update(E(m({},i),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return P(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${gt()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const i=Gr(a,t);return i?E(m({},a),{threadData:E(m({},a.threadData),{[i.id]:E(m({},i),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return P(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Yr(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>Yr(n,r.id,"regular")})}delete(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Yr(n,r.id,"deleted")})})}detach(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},$h=class extends kn{constructor(t){super();C(this,"threads");this.threads=new Uh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Hh=e=>{const[t]=y.useState(()=>new $h(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Wn(t),[t])},gs=e=>{if(Wr().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return Hh(e)},qh=Symbol.for("react.lazy"),Xr=K[" use ".trim().toString()];function Vh(e){return typeof e=="object"&&e!==null&&"then"in e}function ys(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===qh&&"_payload"in e&&Vh(e._payload)}function bs(e){const t=Wh(e),r=K.forwardRef((n,a)=>{let u=n,{children:i}=u,s=H(u,["children"]);ys(i)&&typeof Xr=="function"&&(i=Xr(i._payload));const o=K.Children.toArray(i),l=o.find(Kh);if(l){const d=l.props.children,c=o.map(f=>f===l?K.Children.count(d)>1?K.Children.only(null):K.isValidElement(d)?d.props.children:null:f);return p.jsx(t,E(m({},s),{ref:a,children:K.isValidElement(d)?K.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},s),{ref:a,children:i}))});return r.displayName=`${e}.Slot`,r}var ws=bs("Slot");function Wh(e){const t=K.forwardRef((r,n)=>{let s=r,{children:a}=s,i=H(s,["children"]);if(ys(a)&&typeof Xr=="function"&&(a=Xr(a._payload)),K.isValidElement(a)){const o=Yh(a),l=Gh(i,a.props);return a.type!==K.Fragment&&(l.ref=n?Hi(n,o):o),K.cloneElement(a,l)}return K.Children.count(a)>1?K.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Jh=Symbol("radix.slottable");function Kh(e){return K.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Jh}function Gh(e,t){const r=m({},t);for(const n in t){const a=e[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const l=i(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),i):n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return m(m({},e),r)}function Yh(e){var n,a;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Xh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rt=Xh.reduce((e,t)=>{const r=bs(`Primitive.${t}`),n=K.forwardRef((a,i)=>{const u=a,{asChild:s}=u,o=H(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function Rt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(e==null||e(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}var or=(e,t,r=[])=>{const n=y.forwardRef((a,i)=>{var u;const s={},o={};Object.keys(a).forEach(d=>{r.includes(d)?s[d]=a[d]:o[d]=a[d]});const l=(u=t(s))!=null?u:void 0;return p.jsx(rt.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:Rt(o.onClick,l)}))});return n.displayName=e,n};function Qh(e,t=globalThis==null?void 0:globalThis.document){const r=vt(e);K.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var Zh=()=>{const e=le();return y.useCallback(()=>{e.attachment().remove()},[e])},ef=or("AttachmentPrimitive.Remove",Zh),lr=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},xs=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const a=e(),i=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},s=new ResizeObserver(i);return s.observe(n),i(),()=>{s.disconnect(),a.unregister()}},[e,t]);return lr(r)},vs=y.createContext(!1),Ss=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),a=r[2];if(a==="px")return n;if(a==="em"){const i=parseFloat(getComputedStyle(t).fontSize)||16;return n*i}if(a==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*i}return 0},ks=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=ee(({message:l})=>l.isLast&&l.index>=2),a=Rn({optional:!0}),i=y.useContext(vs),s=y.useCallback(l=>{if(!a||i)return;const u=()=>{const d=a.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:f,userMessage:h}=d.height,g=Ss(t,l),S=Ss(r,l),w=h<=g?h:S,b=Math.max(0,c-f-w);l.style.minHeight=`${b}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),a.subscribe(u)},[a,n,i,t,r]),o=lr(s);return p.jsx(vs.Provider,{value:!0,children:p.jsx(ws,{ref:o,children:e})})};ks.displayName="ThreadPrimitive.ViewportSlack";var tf=()=>{const e=le(),t=ee(()=>e.message()),r=y.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",i),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return lr(r)},rf=()=>{const e=Jr(a=>a.turnAnchor),t=Jr(a=>a.registerUserMessageHeight),r=ee(({thread:a,message:i})=>{var s;return e==="top"&&i.role==="user"&&i.index===a.messages.length-2&&((s=a.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=y.useCallback(a=>a.offsetHeight,[]);return xs(r?t:null,n)},Kn=y.forwardRef((e,t)=>{const r=tf(),n=rf(),a=Vr(t,r,n);return p.jsx(ks,{children:p.jsx(rt.div,E(m({},e),{ref:a}))})});Kn.displayName="MessagePrimitive.Root";var _s=()=>ee(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),Ts=y.forwardRef((a,n)=>{var i=a,{smooth:e=!0,component:t="span"}=i,r=H(i,["smooth","component"]);const{text:s,status:o}=ps(_s(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:s}))});Ts.displayName="MessagePartPrimitive.Text";var nf=()=>ee(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Cs=y.forwardRef((e,t)=>{const{image:r}=nf();return p.jsx(rt.img,E(m({src:r},e),{ref:t}))});Cs.displayName="MessagePartPrimitive.Image";var Is=({children:e})=>ee(({part:r})=>r.status.type==="running")?e:null;Is.displayName="MessagePartPrimitive.InProgress";const Es=e=>Symbol.iterator in e,As=e=>"entries"in e,Ps=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[a,i]of r)if(!n.has(a)||!Object.is(i,n.get(a)))return!1;return!0},af=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),i=n.next();for(;!a.done&&!i.done;){if(!Object.is(a.value,i.value))return!1;a=r.next(),i=n.next()}return!!a.done&&!!i.done};function sf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Es(e)&&Es(t)?As(e)&&As(t)?Ps(e,t):af(e,t):Ps({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function of(e){const t=y.useRef(void 0);return r=>{const n=e(r);return sf(t.current,n)?t.current:t.current=n}}var Ms=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},lf=e=>{const t=[],r=Ms("toolGroup"),n=Ms("reasoningGroup");for(let a=0;a<e.length;a++){const i=e[a];i==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):i==="reasoning"?(r.endGroup(a-1,t),n.startGroup(a)):(r.endGroup(a-1,t),n.endGroup(a-1,t),t.push({type:"single",index:a}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},uf=()=>{const e=ee(of(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:lf(e),[e])},cf=r=>{var n=r,{Fallback:e}=n,t=H(n,["Fallback"]);const a=ee(({tools:i})=>{var o,l;const s=(o=i.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return a?p.jsx(a,m({},t)):null},nt={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Ts,{}),p.jsx(Is,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Cs,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},df=({components:{Text:e=nt.Text,Reasoning:t=nt.Reasoning,Image:r=nt.Image,Source:n=nt.Source,File:a=nt.File,Unstable_Audio:i=nt.Unstable_Audio,tools:s={}}={}})=>{var d,c,f;const o=le(),l=ee(({part:h})=>h),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in s)return p.jsx(s.Override,E(m({},l),{addResult:h,resume:g}));const S=(c=(d=s.by_name)==null?void 0:d[l.toolName])!=null?c:s.Fallback;return p.jsx(cf,E(m({},l),{Fallback:S,addResult:h,resume:g}))}if(((f=l.status)==null?void 0:f.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(a,m({},l));case"audio":return p.jsx(i,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},Qr=y.memo(({index:e,components:t})=>p.jsx(ah,{index:e,children:p.jsx(df,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u,d,c,f,h,g,S,w,b,T,_;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((a=e.components)==null?void 0:a.Reasoning)===((i=t.components)==null?void 0:i.Reasoning)&&((s=e.components)==null?void 0:s.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((f=e.components)==null?void 0:f.Unstable_Audio)===((h=t.components)==null?void 0:h.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((S=t.components)==null?void 0:S.tools)&&((w=e.components)==null?void 0:w.ToolGroup)===((b=t.components)==null?void 0:b.ToolGroup)&&((T=e.components)==null?void 0:T.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});Qr.displayName="MessagePrimitive.PartByIndex";var hf=({status:e,component:t})=>p.jsx(lh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),ff=Object.freeze({type:"complete"}),pf=({components:e})=>{var r;const t=ee(n=>{var a;return(a=n.message.status)!=null?a:ff});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(hf,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:nt.Text})},mf=y.memo(pf,(e,t)=>{var r,n,a,i;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((a=e.components)==null?void 0:a.Text)===((i=t.components)==null?void 0:i.Text)}),Gn=({components:e})=>{const t=ee(({message:a})=>a.parts.length),r=uf(),n=y.useMemo(()=>t===0?p.jsx(mf,{components:e}):r.map(a=>{var i,s;if(a.type==="single")return p.jsx(Qr,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(i=e==null?void 0:e.ToolGroup)!=null?i:nt.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Qr,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:nt.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Qr,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};Gn.displayName="MessagePrimitive.Parts";var gf=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},yf=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=gf(e,t);return r?p.jsx(r,{}):null},Ns=y.memo(({index:e,components:t})=>p.jsx(ih,{index:e,children:p.jsx(yf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});Ns.displayName="MessagePrimitive.AttachmentByIndex";var Ls=({components:e})=>{const t=ee(({message:n})=>n.role!=="user"?0:n.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Ns,{index:a,components:e},a)),[t,e])};Ls.displayName="MessagePrimitive.Attachments";var Ds=()=>{const e=le(),t=ee(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},bf=or("ComposerPrimitive.Send",Ds),Os=y.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=H(a,["onSubmit"]);const i=Ds(),s=o=>{o.preventDefault(),i&&i()};return p.jsx(rt.form,E(m({},t),{ref:r,onSubmit:Rt(e,s)}))});Os.displayName="ComposerPrimitive.Root";function Yn(){return Yn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Yn.apply(null,arguments)}function wf(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var xf=y.useLayoutEffect,vf=function(t){var r=y.useRef(t);return xf(function(){r.current=t}),r},Fs=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Sf=function(t,r){var n=y.useRef();return y.useCallback(function(a){t.current=a,n.current&&Fs(n.current,null),n.current=r,r&&Fs(r,a)},[r])},Bs={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},kf=function(t){Object.keys(Bs).forEach(function(r){t.style.setProperty(r,Bs[r],"important")})},zs=kf,_e=null,Rs=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function _f(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),_e||(_e=document.createElement("textarea"),_e.setAttribute("tabindex","-1"),_e.setAttribute("aria-hidden","true"),zs(_e)),_e.parentNode===null&&document.body.appendChild(_e);var a=e.paddingSize,i=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(f){var h=f;_e.style[h]=s[h]}),zs(_e),_e.value=t;var l=Rs(_e,e);_e.value=t,l=Rs(_e,e),_e.value="x";var u=_e.scrollHeight-a,d=u*r;o==="border-box"&&(d=d+a+i),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+a+i),l=Math.min(c,l),[l,u]}var js=function(){},Tf=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},Cf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],If=!!document.documentElement.currentStyle,Ef=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=Tf(Cf,r),a=n.boxSizing;if(a==="")return null;If&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:s}},Af=Ef;function Xn(e,t,r){var n=vf(r);K.useLayoutEffect(function(){var a=function(s){return n.current(s)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var Pf=function(t,r){Xn(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Mf=function(t){Xn(window,"resize",t)},Nf=function(t){Xn(document.fonts,"loadingdone",t)},Lf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Df=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,i=t.minRows,s=t.onChange,o=s===void 0?js:s,l=t.onHeightChange,u=l===void 0?js:l,d=wf(t,Lf),c=d.value!==void 0,f=K.useRef(null),h=Sf(f,r),g=K.useRef(0),S=K.useRef(),w=function(){var _=f.current,F=n&&S.current?S.current:Af(_);if(F){S.current=F;var z=_f(F,_.value||_.placeholder||"x",i,a),I=z[0],U=z[1];g.current!==I&&(g.current=I,_.style.setProperty("height",I+"px","important"),u(I,{rowHeight:U}))}},b=function(_){c||w(),o(_)};return K.useLayoutEffect(w),Pf(f,function(){if(!c){var T=f.current.value;requestAnimationFrame(function(){var _=f.current;_&&T!==_.value&&w()})}}),Mf(w),Nf(w),K.createElement("textarea",Yn({},d,{onChange:b,ref:h}))},Of=K.forwardRef(Df),Us=e=>{const t=vt(e),r=Jr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},$s=y.forwardRef((g,h)=>{var S=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:i,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=S,f=H(S,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const w=le(),b=ee(({composer:k})=>k.isEditing?k.text:""),T=t?ws:Of,_=ee(({thread:k})=>k.isDisabled)||r,F=y.useRef(null),z=Vr(h,F);Qh(k=>{var M;if(!o||!((M=F.current)!=null&&M.contains(k.target)))return;const D=w.composer();D.getState().canCancel&&(D.cancel(),k.preventDefault())});const I=k=>{var D,M;_||!s||k.nativeEvent.isComposing||k.key==="Enter"&&k.shiftKey===!1&&(w.thread().getState().isRunning||(k.preventDefault(),(M=(D=F.current)==null?void 0:D.closest("form"))==null||M.requestSubmit()))},U=k=>P(null,null,function*(){var W;if(!c)return;const D=w.thread().getState().capabilities,M=Array.from(((W=k.clipboardData)==null?void 0:W.files)||[]);if(D.attachments&&M.length>0)try{k.preventDefault(),yield Promise.all(M.map(B=>w.composer().addAttachment(B)))}catch(B){console.error("Error adding attachment:",B)}}),j=e&&!_,R=y.useCallback(()=>{const k=F.current;!k||!j||(k.focus({preventScroll:!0}),k.setSelectionRange(k.value.length,k.value.length))},[j]);return y.useEffect(()=>R(),[R]),Us(()=>{w.composer().getState().type==="thread"&&u&&R()}),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!l))return w.on("thread.run-start",R)},[l,R,w]),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!d))return w.on("thread-list-item.switched-to",R)},[d,R,w]),p.jsx(T,E(m({name:"input",value:b},f),{ref:z,disabled:_,onChange:Rt(n,k=>{w.composer().getState().isEditing&&(w.composer().setText(k.target.value),w.flushSync())}),onKeyDown:Rt(a,I),onPaste:Rt(i,U)}))});$s.displayName="ComposerPrimitive.Input";var Ff=({multiple:e=!0}={})=>{const t=ee(({composer:a})=>!a.isEditing),r=le(),n=y.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const i=r.composer().getState().attachmentAccept;i!=="*"&&(a.accept=i),document.body.appendChild(a),a.onchange=s=>{const o=s.target.files;if(o){for(const l of o)r.composer().addAttachment(l);document.body.removeChild(a)}},a.oncancel=()=>{(!a.files||a.files.length===0)&&document.body.removeChild(a)},a.click()},[r,e]);return t?null:n},Bf=or("ComposerPrimitive.AddAttachment",Ff,["multiple"]),zf=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Rf=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=zf(e,t);return r?p.jsx(r,{}):null},Hs=y.memo(({index:e,components:t})=>p.jsx(sh,{index:e,children:p.jsx(Rf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});Hs.displayName="ComposerPrimitive.AttachmentByIndex";var qs=({components:e})=>{const t=ee(n=>n.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Hs,{index:a,components:e},a)),[t,e])};qs.displayName="ComposerPrimitive.Attachments";var Vs=y.forwardRef((e,t)=>p.jsx(rt.div,E(m({},e),{ref:t})));Vs.displayName="ThreadPrimitive.Root";var Ws=({children:e})=>ee(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;Ws.displayName="ThreadPrimitive.Empty";var jf=e=>ee(({thread:t})=>!(e.empty===!0&&!t.isEmpty||e.empty===!1&&t.isEmpty||e.running===!0&&!t.isRunning||e.running===!1&&t.isRunning||e.disabled===!0&&!t.isDisabled||e.disabled===!1&&t.isDisabled)),Js=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return jf(t)?e:null};Js.displayName="ThreadPrimitive.If";var Uf=e=>{const t=vt(e),r=y.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),i=new MutationObserver(()=>{t()});return a.observe(n),i.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),i.disconnect()}},[t]);return lr(r)},$f=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=y.useRef(null),i=Rn();e===void 0&&(e=i.getState().turnAnchor!=="top");const s=y.useRef(0),o=y.useRef(null),l=y.useCallback(h=>{const g=a.current;g&&(o.current=h,g.scrollTo({top:g.scrollHeight,behavior:h}))},[]),u=()=>{const h=a.current;if(!h)return;const g=i.getState().isAtBottom,S=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!S&&s.current<h.scrollTop||(S&&(o.current=null),(S||o.current===null)&&S!==g&&sr(i).setState({isAtBottom:S})),s.current=h.scrollTop},d=Uf(()=>{const h=o.current;h?l(h):e&&i.getState().isAtBottom&&l("instant"),u()}),c=lr(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return Us(({behavior:h})=>{l(h)}),zn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),zn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),zn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Vr(d,c,a)},Hf=()=>{const e=Jr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return xs(e,t)},Ks=y.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,i=H(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=$f({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=Hf(),c=Vr(s,u,d);return p.jsx(rt.div,E(m({},i),{ref:c,children:a}))});Ks.displayName="ThreadPrimitive.ViewportScrollable";var Gs=y.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=H(a,["turnAnchor"]);return p.jsx(as,{options:{turnAnchor:e},children:p.jsx(Ks,E(m({},t),{ref:r}))})});Gs.displayName="ThreadPrimitive.Viewport";var Ys=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,qf=()=>null,Vf=(e,t,r)=>{var n,a,i,s,o,l,u,d,c,f,h,g;switch(t){case"user":return r?(i=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?i:e.Message:(s=e.UserMessage)!=null?s:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(h=(f=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(g=e.SystemMessage)!=null?g:qf;default:const S=t;throw new Error(`Unknown message role: ${S}`)}},Wf=({components:e})=>{const t=ee(({message:a})=>a.role),r=ee(({message:a})=>a.composer.isEditing),n=Vf(e,t,r);return p.jsx(n,{})},Xs=y.memo(({index:e,components:t})=>p.jsx(nh,{index:e,children:p.jsx(Wf,{components:t})}),(e,t)=>e.index===t.index&&Ys(e.components,t.components));Xs.displayName="ThreadPrimitive.MessageByIndex";var Qs=({components:e})=>{const t=ee(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(Xs,{index:a,components:e},a)),[t,e])};Qs.displayName="ThreadPrimitive.Messages";var Jf=y.memo(Qs,(e,t)=>Ys(e.components,t.components)),Zs=y.forwardRef((a,n)=>{var i=a,{onClick:e,disabled:t}=i,r=H(i,["onClick","disabled"]);const s=ee(({threads:l})=>l.newThreadId===l.mainThreadId),o=le();return p.jsx(rt.button,E(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:Rt(e,()=>{o.threads().switchToNewThread()})}))});Zs.displayName="ThreadListPrimitive.New";var eo=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(th,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);eo.displayName="ThreadListPrimitive.ItemByIndex";var to=({archived:e=!1,components:t})=>{const r=ee(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return y.useMemo(()=>Array.from({length:r},(a,i)=>p.jsx(eo,{index:i,archived:e,components:t},i)),[r,e,t])};to.displayName="ThreadListPrimitive.Items";var ro=y.forwardRef((e,t)=>p.jsx(rt.div,E(m({},e),{ref:t})));ro.displayName="ThreadListPrimitive.Root";var no=y.forwardRef((e,t)=>{const r=ee(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(rt.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});no.displayName="ThreadListItemPrimitive.Root";var Kf=()=>{const e=le();return y.useCallback(()=>{e.threadListItem().delete()},[e])},Gf=or("ThreadListItemPrimitive.Delete",Kf),Yf=()=>{const e=le();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},Xf=or("ThreadListItemPrimitive.Trigger",Yf);class ao{constructor(t,r,n=!1){C(this,"baseUrl");C(this,"sessionToken",null);C(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return P(this,null,function*(){const n=this.getUrl("/v1/chats"),i={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(s),signal:r});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return P(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return P(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch(n){}const t=n=>Array.from({length:n},()=>Math.floor(Math.random()*16).toString(16)).join(""),r=()=>{const n=["8","9","a","b"];return n[Math.floor(Math.random()*n.length)]};return`${t(8)}-${t(4)}-4${t(3)}-${r()}${t(3)}-${t(12)}`}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(f){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return P(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),a=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.toString(),{method:"DELETE",headers:s});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}listModels(t){return P(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return P(this,null,function*(){const a=this.getUrl("/v1/files"),i=this.generateIdempotencyKey(),s=new FormData;s.append("file",t),r&&s.append("resource_type",r),n&&s.append("resource_id",n);const o={"Idempotency-Key":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{method:"POST",headers:o,body:s});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function Qf(e,t){return Pr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:i,value:s}=yield new lt(r.read());if(i)break;a+=n.decode(s,{stream:!0});const o=a.split(`
6
6
 
7
- `);i=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function If(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function Ef(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}function Ua(e,t){const{modelId:r,systemPrompt:n,ephemeral:i,onChatCreated:s,onUserMessage:a,onThreadIdUpdate:o}=t;return{run(u){return wr(this,null,function*(){const{messages:d,abortSignal:c,context:f}=u,h=f==null?void 0:f.threadId;a==null||a();const S={messages:If(d),chatId:null,systemPrompt:n,ephemeral:i,stream:!0};r&&r.trim()!==""&&(S.modelId=r);const w=yield new it(e.createOrContinueChat(S,c));let b="",C;try{for(var _=xt(Cf(w,c)),F,B,I;F=!(B=yield new it(_.next())).done;F=!1){const z=B.value;if(c!=null&&c.aborted)throw new Error("Request aborted");const j=z.id;j&&!C&&(C=j,s==null||s(j),h&&o&&o(h,j));const $=z.delta;if($!=null&&(b+=$),z.type==="message"||z.content){const N=z.content||"";b+=N}if(z.message&&(b+=z.message.content||""),z.tool_calls,z.finished){b&&(yield{content:[{type:"text",text:b}]});break}b&&(yield{content:[{type:"text",text:b}]})}}catch(B){I=[B]}finally{try{F&&(B=_.return)&&(yield new it(B.call(_)))}finally{if(I)throw I[0]}}b&&(yield{content:[{type:"text",text:b}]})})}}}const $a=new Map;function Af(e,t){return{list(){return P(this,null,function*(){const n=[];let s,a=0;do{const l=yield e.listChats({limit:50,cursor:s}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),s=l.nextCursor||void 0,a++}while(s&&a<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return P(this,null,function*(){return{remoteId:$a.get(n)||n,externalId:void 0}})},rename(n,i){return P(this,null,function*(){yield e.updateChat(n,{title:i})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){yield e.deleteChat(n)})},generateTitle(n,i){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(this,null,function*(){try{const i=yield e.getChat(n);return{status:"regular",remoteId:i.id||n,title:i.title||"Chat",createdAt:i.createdAt?new Date(i.createdAt):new Date,updatedAt:i.updatedAt?new Date(i.updatedAt):new Date}}catch(i){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,i){$a.set(n,i),t==null||t(n,i)},unstable_Provider:({children:n})=>{const i=Us(),s=i==null?void 0:i.remoteId,a=y.useMemo(()=>({load(){return P(this,null,function*(){if(!s)return{messages:[]};try{const u=yield e.getChat(s);return!u.messages||u.messages.length===0?{messages:[]}:{messages:u.messages.map(c=>Ef(c))}}catch(u){return console.error("Failed to load messages for thread:",s,u),{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[s,e]),o=y.useMemo(()=>({history:a}),[a]);return p.jsx(wn,{adapters:o,children:n})}}}function Pf({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:i="multiChat",modelId:s,onModelChange:a,ephemeral:o=!1,systemPrompt:l,initialThreadId:u,onError:d,onChatCreated:c,onUserMessage:f,onThreadIdUpdate:h,onChatsLoaded:g}){const S=y.useMemo(()=>new ja(t,r||void 0,n),[t,r,n]),[w,b]=y.useState(s||null);y.useEffect(()=>{s&&b(s)},[s]);const C=y.useCallback(B=>{c==null||c(B)},[c]),_=y.useCallback((B,I)=>{h==null||h(B,I)},[h]),F=y.useMemo(()=>Ua(S,{modelId:w||void 0,systemPrompt:l,ephemeral:o,onChatCreated:C,onUserMessage:f}),[S,w,l,o,C,f]);return i==="singleChat"?p.jsx(Mf,{modelAdapter:F,children:e}):p.jsx(Lf,{client:S,modelAdapterOptions:{modelId:w||void 0,systemPrompt:l,ephemeral:o,onChatCreated:C,onUserMessage:f},initialThreadId:u,onChatsLoaded:g,onThreadIdUpdate:_,onError:d,children:e})}function Mf({modelAdapter:e,children:t}){const r=Xs(e);return p.jsx(Vs,{runtime:r,children:t})}function Lf({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:i,onError:s,children:a}){const o=y.useMemo(()=>Af(e,(h,g)=>{i==null||i(h,g)}),[e,i]),l=y.useCallback((h,g)=>{o.updateRemoteId&&o.updateRemoteId(h,g),i==null||i(h,g)},[o,i]),u=y.useMemo(()=>E(m({},o),{list(){return P(this,null,function*(){const g=yield o.list();return n==null||n(),g})}}),[o,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=u,window.__cuadraThreadListRuntime=null},[u]);const d=y.useMemo(()=>Ua(e,E(m({},t),{onThreadIdUpdate:l})),[e,t,l]),c=y.useCallback(()=>Xs(d),[d]),f=ra({adapter:u,runtimeHook:c});return y.useEffect(()=>{window.__cuadraThreadListRuntime=f},[f]),p.jsx(Vs,{runtime:f,children:a})}function Jx(){}function Gx(){}function Nf(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const Df=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Of=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Ff={};function Ha(e,t){return(Ff.jsx?Of:Df).test(e)}const Bf=/[ \t\n\f\r]/g;function zf(e){return typeof e=="object"?e.type==="text"?qa(e.value):!1:qa(e)}function qa(e){return e.replace(Bf,"")===""}class tr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}tr.prototype.normal={},tr.prototype.property={},tr.prototype.space=void 0;function Va(e,t){const r={},n={};for(const i of e)Object.assign(r,i.property),Object.assign(n,i.normal);return new tr(r,n,t)}function Un(e){return e.toLowerCase()}class Ee{constructor(t,r){this.attribute=r,this.property=t}}Ee.prototype.attribute="",Ee.prototype.booleanish=!1,Ee.prototype.boolean=!1,Ee.prototype.commaOrSpaceSeparated=!1,Ee.prototype.commaSeparated=!1,Ee.prototype.defined=!1,Ee.prototype.mustUseProperty=!1,Ee.prototype.number=!1,Ee.prototype.overloadedBoolean=!1,Ee.prototype.property="",Ee.prototype.spaceSeparated=!1,Ee.prototype.space=void 0;let Rf=0;const G=pt(),de=pt(),$n=pt(),L=pt(),ne=pt(),Mt=pt(),Me=pt();function pt(){return lu(2,++Rf)}const Hn=Object.freeze(Object.defineProperty({__proto__:null,boolean:G,booleanish:de,commaOrSpaceSeparated:Me,commaSeparated:Mt,number:L,overloadedBoolean:$n,spaceSeparated:ne},Symbol.toStringTag,{value:"Module"})),qn=Object.keys(Hn);class Vn extends Ee{constructor(t,r,n,i){let s=-1;if(super(t,r),Wa(this,"space",i),typeof n=="number")for(;++s<qn.length;){const a=qn[s];Wa(this,qn[s],(n&Hn[a])===Hn[a])}}}Vn.prototype.defined=!0;function Wa(e,t,r){r&&(e[t]=r)}function Lt(e){const t={},r={};for(const[n,i]of Object.entries(e.properties)){const s=new Vn(n,e.transform(e.attributes||{},n),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(s.mustUseProperty=!0),t[n]=s,r[Un(n)]=n,r[Un(s.attribute)]=n}return new tr(t,r,e.space)}const Ja=Lt({properties:{ariaActiveDescendant:null,ariaAtomic:de,ariaAutoComplete:null,ariaBusy:de,ariaChecked:de,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:ne,ariaCurrent:null,ariaDescribedBy:ne,ariaDetails:null,ariaDisabled:de,ariaDropEffect:ne,ariaErrorMessage:null,ariaExpanded:de,ariaFlowTo:ne,ariaGrabbed:de,ariaHasPopup:null,ariaHidden:de,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ne,ariaLevel:L,ariaLive:null,ariaModal:de,ariaMultiLine:de,ariaMultiSelectable:de,ariaOrientation:null,ariaOwns:ne,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:de,ariaReadOnly:de,ariaRelevant:null,ariaRequired:de,ariaRoleDescription:ne,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:de,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Ga(e,t){return t in e?e[t]:t}function Ya(e,t){return Ga(e,t.toLowerCase())}const jf=Lt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Mt,acceptCharset:ne,accessKey:ne,action:null,allow:null,allowFullScreen:G,allowPaymentRequest:G,allowUserMedia:G,alt:null,as:null,async:G,autoCapitalize:null,autoComplete:ne,autoFocus:G,autoPlay:G,blocking:ne,capture:null,charSet:null,checked:G,cite:null,className:ne,cols:L,colSpan:null,content:null,contentEditable:de,controls:G,controlsList:ne,coords:L|Mt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:G,defer:G,dir:null,dirName:null,disabled:G,download:$n,draggable:de,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:G,formTarget:null,headers:ne,height:L,hidden:$n,high:L,href:null,hrefLang:null,htmlFor:ne,httpEquiv:ne,id:null,imageSizes:null,imageSrcSet:null,inert:G,inputMode:null,integrity:null,is:null,isMap:G,itemId:null,itemProp:ne,itemRef:ne,itemScope:G,itemType:ne,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:G,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:G,muted:G,name:null,nonce:null,noModule:G,noValidate:G,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:G,optimum:L,pattern:null,ping:ne,placeholder:null,playsInline:G,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:G,referrerPolicy:null,rel:ne,required:G,reversed:G,rows:L,rowSpan:L,sandbox:ne,scope:null,scoped:G,seamless:G,selected:G,shadowRootClonable:G,shadowRootDelegatesFocus:G,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:de,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:G,useMap:null,value:de,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ne,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:G,declare:G,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:G,noHref:G,noShade:G,noWrap:G,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:de,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:G,disableRemotePlayback:G,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:Ya}),Uf=Lt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Me,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:ne,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:G,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Mt,g2:Mt,glyphName:Mt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:Me,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ne,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Me,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Me,rev:Me,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Me,requiredFeatures:Me,requiredFonts:Me,requiredFormats:Me,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:Me,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Me,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Me,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Ga}),Ka=Lt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Xa=Lt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ya}),Qa=Lt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),$f={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Hf=/[A-Z]/g,Za=/-[a-z]/g,qf=/^data[-\w.:]+$/i;function Vf(e,t){const r=Un(t);let n=t,i=Ee;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&qf.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Za,Jf);n="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Za.test(s)){let a=s.replace(Hf,Wf);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=Vn}return new i(n,t)}function Wf(e){return"-"+e.toLowerCase()}function Jf(e){return e.charAt(1).toUpperCase()}const Gf=Va([Ja,jf,Ka,Xa,Qa],"html"),Wn=Va([Ja,Uf,Ka,Xa,Qa],"svg");function Yf(e){return e.join(" ").trim()}var Nt={},Jn,eo;function Kf(){if(eo)return Jn;eo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
- `,u="/",d="*",c="",f="comment",h="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var C=1,_=1;function F(R){var D=R.match(t);D&&(C+=D.length);var Q=R.lastIndexOf(l);_=~Q?R.length-Q:_+R.length}function B(){var R={line:C,column:_};return function(D){return D.position=new I(R),$(),D}}function I(R){this.start=R,this.end={line:C,column:_},this.source=b.source}I.prototype.content=w;function z(R){var D=new Error(b.source+":"+C+":"+_+": "+R);if(D.reason=R,D.filename=b.source,D.line=C,D.column=_,D.source=w,!b.silent)throw D}function j(R){var D=R.exec(w);if(D){var Q=D[0];return F(Q),w=w.slice(Q.length),D}}function $(){j(r)}function k(R){var D;for(R=R||[];D=N();)D!==!1&&R.push(D);return R}function N(){var R=B();if(!(u!=w.charAt(0)||d!=w.charAt(1))){for(var D=2;c!=w.charAt(D)&&(d!=w.charAt(D)||u!=w.charAt(D+1));)++D;if(D+=2,c===w.charAt(D-1))return z("End of comment missing");var Q=w.slice(2,D-2);return _+=2,F(Q),w=w.slice(D),_+=2,R({type:f,comment:Q})}}function M(){var R=B(),D=j(n);if(D){if(N(),!j(i))return z("property missing ':'");var Q=j(s),se=R({type:h,property:S(D[0].replace(e,c)),value:Q?S(Q[0].replace(e,c)):c});return j(a),se}}function V(){var R=[];k(R);for(var D;D=M();)D!==!1&&(R.push(D),k(R));return R}return $(),V()}function S(w){return w?w.replace(o,c):c}return Jn=g,Jn}var to;function Xf(){if(to)return Nt;to=1;var e=Nt&&Nt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.default=r;const t=e(Kf());function r(n,i){let s=null;if(!n||typeof n!="string")return s;const a=(0,t.default)(n),o=typeof i=="function";return a.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?i(u,d,l):d&&(s=s||{},s[u]=d)}),s}return Nt}var rr={},ro;function Qf(){if(ro)return rr;ro=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,s=function(u){return!u||r.test(u)||e.test(u)},a=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),s(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(i,o):u=u.replace(n,o),u.replace(t,a))};return rr.camelCase=l,rr}var nr,no;function Zf(){if(no)return nr;no=1;var e=nr&&nr.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(Xf()),r=Qf();function n(i,s){var a={};return!i||typeof i!="string"||(0,t.default)(i,function(o,l){o&&l&&(a[(0,r.camelCase)(o,s)]=l)}),a}return n.default=n,nr=n,nr}var ep=Zf();const tp=xr(ep),io=so("end"),Gn=so("start");function so(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function rp(e){const t=Gn(e),r=io(e);if(t&&r)return{start:t,end:r}}function ir(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ao(e.position):"start"in e||"end"in e?ao(e):"line"in e||"column"in e?Yn(e):""}function Yn(e){return oo(e&&e.line)+":"+oo(e&&e.column)}function ao(e){return Yn(e&&e.start)+"-"+Yn(e&&e.end)}function oo(e){return e&&typeof e=="number"?e:1}class we extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let i="",s={},a=!1;if(r&&("line"in r&&"column"in r?s={place:r}:"start"in r&&"end"in r?s={place:r}:"type"in r?s={ancestors:[r],place:r.position}:s=m({},r)),typeof t=="string"?i=t:!s.cause&&t&&(a=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?s.ruleId=n:(s.source=n.slice(0,l),s.ruleId=n.slice(l+1))}if(!s.place&&s.ancestors&&s.ancestors){const l=s.ancestors[s.ancestors.length-1];l&&(s.place=l.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=ir(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=a&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}we.prototype.file="",we.prototype.name="",we.prototype.reason="",we.prototype.message="",we.prototype.stack="",we.prototype.column=void 0,we.prototype.line=void 0,we.prototype.ancestors=void 0,we.prototype.cause=void 0,we.prototype.fatal=void 0,we.prototype.place=void 0,we.prototype.ruleId=void 0,we.prototype.source=void 0;const Kn={}.hasOwnProperty,np=new Map,ip=/[A-Z]/g,sp=new Set(["table","tbody","thead","tfoot","tr"]),ap=new Set(["td","th"]),lo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function op(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=mp(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=pp(r,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Wn:Gf,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=uo(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function uo(e,t,r){if(t.type==="element")return lp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return up(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return dp(e,t,r);if(t.type==="mdxjsEsm")return cp(e,t);if(t.type==="root")return hp(e,t,r);if(t.type==="text")return fp(e,t)}function lp(e,t,r){const n=e.schema;let i=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(i=Wn,e.schema=i),e.ancestors.push(t);const s=ho(e,t.tagName,!1),a=gp(e,t);let o=Qn(e,t);return sp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!zf(l):!0})),co(e,a,s,t),Xn(a,o),e.ancestors.pop(),e.schema=n,e.create(t,s,a,r)}function up(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}sr(e,t.position)}function cp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);sr(e,t.position)}function dp(e,t,r){const n=e.schema;let i=n;t.name==="svg"&&n.space==="html"&&(i=Wn,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:ho(e,t.name,!0),a=yp(e,t),o=Qn(e,t);return co(e,a,s,t),Xn(a,o),e.ancestors.pop(),e.schema=n,e.create(t,s,a,r)}function hp(e,t,r){const n={};return Xn(n,Qn(e,t)),e.create(t,e.Fragment,n,r)}function fp(e,t){return t.value}function co(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function Xn(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function pp(e,t,r){return n;function n(i,s,a,o){const u=Array.isArray(a.children)?r:t;return o?u(s,a,o):u(s,a)}}function mp(e,t){return r;function r(n,i,s,a){const o=Array.isArray(s.children),l=Gn(n);return t(i,s,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function gp(e,t){const r={};let n,i;for(i in t.properties)if(i!=="children"&&Kn.call(t.properties,i)){const s=bp(e,i,t.properties[i]);if(s){const[a,o]=s;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&ap.has(t.tagName)?n=o:r[a]=o}}if(n){const s=r.style||(r.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function yp(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const s=n.data.estree.body[0];s.type;const a=s.expression;a.type;const o=a.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else sr(e,t.position);else{const i=n.name;let s;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else sr(e,t.position);else s=n.value===null?!0:n.value;r[i]=s}return r}function Qn(e,t){const r=[];let n=-1;const i=e.passKeys?new Map:np;for(;++n<t.children.length;){const s=t.children[n];let a;if(e.passKeys){const l=s.type==="element"?s.tagName:s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement"?s.name:void 0;if(l){const u=i.get(l)||0;a=l+"-"+u,i.set(l,u+1)}}const o=uo(e,s,a);o!==void 0&&r.push(o)}return r}function bp(e,t,r){const n=Vf(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?Nf(r):Yf(r)),n.property==="style"){let i=typeof r=="object"?r:wp(e,String(r));return e.stylePropertyNameCase==="css"&&(i=xp(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&n.space?$f[n.property]||n.property:n.attribute,r]}}function wp(e,t){try{return tp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,i=new we("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=lo+"#cannot-parse-style-attribute",i}}function ho(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let s=-1,a;for(;++s<i.length;){const o=Ha(i[s])?{type:"Identifier",name:i[s]}:{type:"Literal",value:i[s]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(s&&o.type==="Literal"),optional:!1}:o}n=a}else n=Ha(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const i=n.value;return Kn.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(n);sr(e)}function sr(e,t){const r=new we("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=lo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function xp(e){const t={};let r;for(r in e)Kn.call(e,r)&&(t[vp(r)]=e[r]);return t}function vp(e){let t=e.replace(ip,Sp);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Sp(e){return"-"+e.toLowerCase()}const Zn={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},kp={};function ei(e,t){const r=kp,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return fo(e,n,i)}function fo(e,t,r){if(_p(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return po(e.children,t,r)}return Array.isArray(e)?po(e,t,r):""}function po(e,t,r){const n=[];let i=-1;for(;++i<e.length;)n[i]=fo(e[i],t,r);return n.join("")}function _p(e){return!!(e&&typeof e=="object")}const mo=document.createElement("i");function ti(e){const t="&"+e+";";mo.innerHTML=t;const r=mo.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Le(e,t,r,n){const i=e.length;let s=0,a;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,r=r>0?r:0,n.length<1e4)a=Array.from(n),a.unshift(t,r),e.splice(...a);else for(r&&e.splice(t,r);s<n.length;)a=n.slice(s,s+1e4),a.unshift(t,0),e.splice(...a),s+=1e4,t+=1e4}function Be(e,t){return e.length>0?(Le(e,e.length,0,t),e):t}const go={}.hasOwnProperty;function yo(e){const t={};let r=-1;for(;++r<e.length;)Tp(t,e[r]);return t}function Tp(e,t){let r;for(r in t){const i=(go.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r];let a;if(s)for(a in s){go.call(i,a)||(i[a]=[]);const o=s[a];Cp(i[a],Array.isArray(o)?o:o?[o]:[])}}}function Cp(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);Le(e,0,0,n)}function bo(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Ve(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Te=ot(/[A-Za-z]/),xe=ot(/[\dA-Za-z]/),Ip=ot(/[#-'*+\--9=?A-Z^-~]/);function $r(e){return e!==null&&(e<32||e===127)}const ri=ot(/\d/),Ep=ot(/[\dA-Fa-f]/),Ap=ot(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function te(e){return e!==null&&(e<0||e===32)}function Y(e){return e===-2||e===-1||e===32}const Hr=ot(new RegExp("\\p{P}|\\p{S}","u")),mt=ot(/\s/);function ot(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Dt(e){const t=[];let r=-1,n=0,i=0;for(;++r<e.length;){const s=e.charCodeAt(r);let a="";if(s===37&&xe(e.charCodeAt(r+1))&&xe(e.charCodeAt(r+2)))i=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(a=String.fromCharCode(s));else if(s>55295&&s<57344){const o=e.charCodeAt(r+1);s<56320&&o>56319&&o<57344?(a=String.fromCharCode(s,o),i=1):a="�"}else a=String.fromCharCode(s);a&&(t.push(e.slice(n,r),encodeURIComponent(a)),n=r+i+1,a=""),i&&(r+=i,i=0)}return t.join("")+e.slice(n)}function X(e,t,r,n){const i=n?n-1:Number.POSITIVE_INFINITY;let s=0;return a;function a(l){return Y(l)?(e.enter(r),o(l)):t(l)}function o(l){return Y(l)&&s++<i?(e.consume(l),o):(e.exit(r),t(l))}}const Pp={tokenize:Mp};function Mp(e){const t=e.attempt(this.parser.constructs.contentInitial,n,i);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),X(e,t,"linePrefix")}function i(o){return e.enter("paragraph"),s(o)}function s(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return q(o)?(e.consume(o),e.exit("chunkText"),s):(e.consume(o),a)}}const Lp={tokenize:Np},wo={tokenize:Dp};function Np(e){const t=this,r=[];let n=0,i,s,a;return o;function o(_){if(n<r.length){const F=r[n];return t.containerState=F[1],e.attempt(F[0].continuation,l,u)(_)}return u(_)}function l(_){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&C();const F=t.events.length;let B=F,I;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){I=t.events[B][1].end;break}b(n);let z=F;for(;z<t.events.length;)t.events[z][1].end=m({},I),z++;return Le(t.events,B+1,0,t.events.slice(F)),t.events.length=z,u(_)}return o(_)}function u(_){if(n===r.length){if(!i)return f(_);if(i.currentConstruct&&i.currentConstruct.concrete)return g(_);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(wo,d,c)(_)}function d(_){return i&&C(),b(n),f(_)}function c(_){return t.parser.lazy[t.now().line]=n!==r.length,a=t.now().offset,g(_)}function f(_){return t.containerState={},e.attempt(wo,h,g)(_)}function h(_){return n++,r.push([t.currentConstruct,t.containerState]),f(_)}function g(_){if(_===null){i&&C(),b(0),e.consume(_);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:s}),S(_)}function S(_){if(_===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(_);return}return q(_)?(e.consume(_),w(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(_),S)}function w(_,F){const B=t.sliceStream(_);if(F&&B.push(null),_.previous=s,s&&(s.next=_),s=_,i.defineSkip(_.start),i.write(B),t.parser.lazy[_.start.line]){let I=i.events.length;for(;I--;)if(i.events[I][1].start.offset<a&&(!i.events[I][1].end||i.events[I][1].end.offset>a))return;const z=t.events.length;let j=z,$,k;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){if($){k=t.events[j][1].end;break}$=!0}for(b(n),I=z;I<t.events.length;)t.events[I][1].end=m({},k),I++;Le(t.events,j+1,0,t.events.slice(z)),t.events.length=I}}function b(_){let F=r.length;for(;F-- >_;){const B=r[F];t.containerState=B[1],B[0].exit.call(t,e)}r.length=_}function C(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Dp(e,t,r){return X(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ot(e){if(e===null||te(e)||mt(e))return 1;if(Hr(e))return 2}function qr(e,t,r){const n=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!n.includes(s)&&(t=s(t,r),n.push(s))}return t}const ni={name:"attention",resolveAll:Op,tokenize:Fp};function Op(e,t){let r=-1,n,i,s,a,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),f=m({},e[r][1].start);xo(c,-l),xo(f,l),a={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:f},s={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},i={type:l>1?"strong":"emphasis",start:m({},a.start),end:m({},o.end)},e[n][1].end=m({},a.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Be(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Be(u,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",s,t]]),u=Be(u,qr(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Be(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Be(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,Le(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function Fp(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=Ot(n);let s;return a;function a(l){return s=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===s)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Ot(l),c=!d||d===2&&i||r.includes(l),f=!i||i===2&&d||r.includes(n);return u._open=!!(s===42?c:c&&(i||!f)),u._close=!!(s===42?f:f&&(d||!c)),t(l)}}function xo(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Bp={name:"autolink",tokenize:zp};function zp(e,t,r){let n=0;return i;function i(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(h){return Te(h)?(e.consume(h),a):h===64?r(h):u(h)}function a(h){return h===43||h===45||h===46||xe(h)?(n=1,o(h)):u(h)}function o(h){return h===58?(e.consume(h),n=0,l):(h===43||h===45||h===46||xe(h))&&n++<32?(e.consume(h),o):(n=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||$r(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):Ip(h)?(e.consume(h),u):r(h)}function d(h){return xe(h)?c(h):r(h)}function c(h){return h===46?(e.consume(h),n=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):f(h)}function f(h){if((h===45||xe(h))&&n++<63){const g=h===45?f:c;return e.consume(h),g}return r(h)}}const ar={partial:!0,tokenize:Rp};function Rp(e,t,r){return n;function n(s){return Y(s)?X(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||q(s)?t(s):r(s)}}const vo={continuation:{tokenize:Up},exit:$p,name:"blockQuote",tokenize:jp};function jp(e,t,r){const n=this;return i;function i(a){if(a===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),s}return r(a)}function s(a){return Y(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function Up(e,t,r){const n=this;return i;function i(a){return Y(a)?X(e,s,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):s(a)}function s(a){return e.attempt(vo,t,r)(a)}}function $p(e){e.exit("blockQuote")}const So={name:"characterEscape",tokenize:Hp};function Hp(e,t,r){return n;function n(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),i}function i(s){return Ap(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(s)}}const ko={name:"characterReference",tokenize:qp};function qp(e,t,r){const n=this;let i=0,s,a;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),s=31,a=xe,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,a=Ep,d):(e.enter("characterReferenceValue"),s=7,a=ri,d(c))}function d(c){if(c===59&&i){const f=e.exit("characterReferenceValue");return a===xe&&!ti(n.sliceSerialize(f))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(c)&&i++<s?(e.consume(c),d):r(c)}}const _o={partial:!0,tokenize:Wp},To={concrete:!0,name:"codeFenced",tokenize:Vp};function Vp(e,t,r){const n=this,i={partial:!0,tokenize:B};let s=0,a=0,o;return l;function l(I){return u(I)}function u(I){const z=n.events[n.events.length-1];return s=z&&z[1].type==="linePrefix"?z[2].sliceSerialize(z[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(I)}function d(I){return I===o?(a++,e.consume(I),d):a<3?r(I):(e.exit("codeFencedFenceSequence"),Y(I)?X(e,c,"whitespace")(I):c(I))}function c(I){return I===null||q(I)?(e.exit("codeFencedFence"),n.interrupt?t(I):e.check(_o,S,F)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(I))}function f(I){return I===null||q(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(I)):Y(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),X(e,h,"whitespace")(I)):I===96&&I===o?r(I):(e.consume(I),f)}function h(I){return I===null||q(I)?c(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(I))}function g(I){return I===null||q(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(I)):I===96&&I===o?r(I):(e.consume(I),g)}function S(I){return e.attempt(i,F,w)(I)}function w(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),b}function b(I){return s>0&&Y(I)?X(e,C,"linePrefix",s+1)(I):C(I)}function C(I){return I===null||q(I)?e.check(_o,S,F)(I):(e.enter("codeFlowValue"),_(I))}function _(I){return I===null||q(I)?(e.exit("codeFlowValue"),C(I)):(e.consume(I),_)}function F(I){return e.exit("codeFenced"),t(I)}function B(I,z,j){let $=0;return k;function k(D){return I.enter("lineEnding"),I.consume(D),I.exit("lineEnding"),N}function N(D){return I.enter("codeFencedFence"),Y(D)?X(I,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):M(D)}function M(D){return D===o?(I.enter("codeFencedFenceSequence"),V(D)):j(D)}function V(D){return D===o?($++,I.consume(D),V):$>=a?(I.exit("codeFencedFenceSequence"),Y(D)?X(I,R,"whitespace")(D):R(D)):j(D)}function R(D){return D===null||q(D)?(I.exit("codeFencedFence"),z(D)):j(D)}}}function Wp(e,t,r){const n=this;return i;function i(a){return a===null?r(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s)}function s(a){return n.parser.lazy[n.now().line]?r(a):t(a)}}const ii={name:"codeIndented",tokenize:Gp},Jp={partial:!0,tokenize:Yp};function Gp(e,t,r){const n=this;return i;function i(u){return e.enter("codeIndented"),X(e,s,"linePrefix",5)(u)}function s(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):r(u)}function a(u){return u===null?l(u):q(u)?e.attempt(Jp,a,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||q(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Yp(e,t,r){const n=this;return i;function i(a){return n.parser.lazy[n.now().line]?r(a):q(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):X(e,s,"linePrefix",5)(a)}function s(a){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):q(a)?i(a):r(a)}}const Kp={name:"codeText",previous:Qp,resolve:Xp,tokenize:Zp};function Xp(e){let t=e.length-4,r=3,n,i;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)i===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(i=n):(n===t||e[n][1].type==="lineEnding")&&(e[i][1].type="codeTextData",n!==i+2&&(e[i][1].end=e[n-1][1].end,e.splice(i+2,n-i-2),t-=n-i-2,n=i+2),i=void 0);return e}function Qp(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Zp(e,t,r){let n=0,i,s;return a;function a(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(s=e.enter("codeTextSequence"),i=0,d(c)):q(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||q(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),i++,d):i===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(s.type="codeTextData",u(c))}}class em{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const i=r||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&or(this.left,n),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),or(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),or(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);or(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);or(this.left,r.reverse())}}}function or(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function Co(e){const t={};let r=-1,n,i,s,a,o,l,u;const d=new em(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,s=0,s<l.length&&l[s][1].type==="lineEndingBlank"&&(s+=2),s<l.length&&l[s][1].type==="content"))for(;++s<l.length&&l[s][1].type!=="content";)l[s][1].type==="chunkText"&&(l[s][1]._isInFirstContentOfListItem=!0,s++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,tm(d,r)),r=t[r],u=!0);else if(n[1]._container){for(s=r,i=void 0;s--;)if(a=d.get(s),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(d.get(i)[1].type="lineEndingBlank"),a[1].type="lineEnding",i=s);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;i&&(n[1].end=m({},d.get(i)[1].start),o=d.slice(i,r),o.unshift(n),d.splice(i,r-i+1,o))}}return Le(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function tm(e,t){const r=e.get(t)[1],n=e.get(t)[2];let i=t-1;const s=[];let a=r._tokenizer;a||(a=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,l=[],u={};let d,c,f=-1,h=r,g=0,S=0;const w=[S];for(;h;){for(;e.get(++i)[1]!==h;);s.push(i),h._tokenizer||(d=n.sliceStream(h),h.next||d.push(null),c&&a.defineSkip(h.start),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),c=h,h=h.next}for(h=r;++f<o.length;)o[f][0]==="exit"&&o[f-1][0]==="enter"&&o[f][1].type===o[f-1][1].type&&o[f][1].start.line!==o[f][1].end.line&&(S=f+1,w.push(S),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(a.events=[],h?(h._tokenizer=void 0,h.previous=void 0):w.pop(),f=w.length;f--;){const b=o.slice(w[f],w[f+1]),C=s.pop();l.push([C,C+b.length-1]),e.splice(C,2,b)}for(l.reverse(),f=-1;++f<l.length;)u[g+l[f][0]]=g+l[f][1],g+=l[f][1]-l[f][0]-1;return u}const rm={resolve:im,tokenize:sm},nm={partial:!0,tokenize:am};function im(e){return Co(e),e}function sm(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),i(o)}function i(o){return o===null?s(o):q(o)?e.check(nm,a,s)(o):(e.consume(o),i)}function s(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function am(e,t,r){const n=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),X(e,s,"linePrefix")}function s(a){if(a===null||q(a))return r(a);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(n.parser.constructs.flow,r,t)(a)}}function Io(e,t,r,n,i,s,a,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(b){return b===60?(e.enter(n),e.enter(i),e.enter(s),e.consume(b),e.exit(s),f):b===null||b===32||b===41||$r(b)?r(b):(e.enter(n),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),S(b))}function f(b){return b===62?(e.enter(s),e.consume(b),e.exit(s),e.exit(i),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(o),f(b)):b===null||b===60||q(b)?r(b):(e.consume(b),b===92?g:h)}function g(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function S(b){return!d&&(b===null||b===41||te(b))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(n),t(b)):d<u&&b===40?(e.consume(b),d++,S):b===41?(e.consume(b),d--,S):b===null||b===32||b===40||$r(b)?r(b):(e.consume(b),b===92?w:S)}function w(b){return b===40||b===41||b===92?(e.consume(b),S):S(b)}}function Eo(e,t,r,n,i,s){const a=this;let o=0,l;return u;function u(h){return e.enter(n),e.enter(i),e.consume(h),e.exit(i),e.enter(s),d}function d(h){return o>999||h===null||h===91||h===93&&!l||h===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?r(h):h===93?(e.exit(s),e.enter(i),e.consume(h),e.exit(i),e.exit(n),t):q(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===null||h===91||h===93||q(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!Y(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function Ao(e,t,r,n,i,s){let a;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(i),e.consume(f),e.exit(i),a=f===40?41:f,l):r(f)}function l(f){return f===a?(e.enter(i),e.consume(f),e.exit(i),e.exit(n),t):(e.enter(s),u(f))}function u(f){return f===a?(e.exit(s),l(a)):f===null?r(f):q(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),X(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===a||f===null||q(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?c:d)}function c(f){return f===a||f===92?(e.consume(f),d):d(f)}}function lr(e,t){let r;return n;function n(i){return q(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),r=!0,n):Y(i)?X(e,n,r?"linePrefix":"lineSuffix")(i):t(i)}}const om={name:"definition",tokenize:um},lm={partial:!0,tokenize:cm};function um(e,t,r){const n=this;let i;return s;function s(h){return e.enter("definition"),a(h)}function a(h){return Eo.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return i=Ve(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):r(h)}function l(h){return te(h)?lr(e,u)(h):u(h)}function u(h){return Io(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(lm,c,c)(h)}function c(h){return Y(h)?X(e,f,"whitespace")(h):f(h)}function f(h){return h===null||q(h)?(e.exit("definition"),n.parser.defined.push(i),t(h)):r(h)}}function cm(e,t,r){return n;function n(o){return te(o)?lr(e,i)(o):r(o)}function i(o){return Ao(e,s,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return Y(o)?X(e,a,"whitespace")(o):a(o)}function a(o){return o===null||q(o)?t(o):r(o)}}const dm={name:"hardBreakEscape",tokenize:hm};function hm(e,t,r){return n;function n(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return q(s)?(e.exit("hardBreakEscape"),t(s)):r(s)}}const fm={name:"headingAtx",resolve:pm,tokenize:mm};function pm(e,t){let r=e.length-2,n=3,i,s;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},s={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},Le(e,n,r-n+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function mm(e,t,r){let n=0;return i;function i(d){return e.enter("atxHeading"),s(d)}function s(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&n++<6?(e.consume(d),a):d===null||te(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||q(d)?(e.exit("atxHeading"),t(d)):Y(d)?X(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||te(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const gm=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Po=["pre","script","style","textarea"],ym={concrete:!0,name:"htmlFlow",resolveTo:xm,tokenize:vm},bm={partial:!0,tokenize:km},wm={partial:!0,tokenize:Sm};function xm(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function vm(e,t,r){const n=this;let i,s,a,o,l;return u;function u(v){return d(v)}function d(v){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(v),c}function c(v){return v===33?(e.consume(v),f):v===47?(e.consume(v),s=!0,S):v===63?(e.consume(v),i=3,n.interrupt?t:x):Te(v)?(e.consume(v),a=String.fromCharCode(v),w):r(v)}function f(v){return v===45?(e.consume(v),i=2,h):v===91?(e.consume(v),i=5,o=0,g):Te(v)?(e.consume(v),i=4,n.interrupt?t:x):r(v)}function h(v){return v===45?(e.consume(v),n.interrupt?t:x):r(v)}function g(v){const ve="CDATA[";return v===ve.charCodeAt(o++)?(e.consume(v),o===ve.length?n.interrupt?t:M:g):r(v)}function S(v){return Te(v)?(e.consume(v),a=String.fromCharCode(v),w):r(v)}function w(v){if(v===null||v===47||v===62||te(v)){const ve=v===47,Re=a.toLowerCase();return!ve&&!s&&Po.includes(Re)?(i=1,n.interrupt?t(v):M(v)):gm.includes(a.toLowerCase())?(i=6,ve?(e.consume(v),b):n.interrupt?t(v):M(v)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(v):s?C(v):_(v))}return v===45||xe(v)?(e.consume(v),a+=String.fromCharCode(v),w):r(v)}function b(v){return v===62?(e.consume(v),n.interrupt?t:M):r(v)}function C(v){return Y(v)?(e.consume(v),C):k(v)}function _(v){return v===47?(e.consume(v),k):v===58||v===95||Te(v)?(e.consume(v),F):Y(v)?(e.consume(v),_):k(v)}function F(v){return v===45||v===46||v===58||v===95||xe(v)?(e.consume(v),F):B(v)}function B(v){return v===61?(e.consume(v),I):Y(v)?(e.consume(v),B):_(v)}function I(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),l=v,z):Y(v)?(e.consume(v),I):j(v)}function z(v){return v===l?(e.consume(v),l=null,$):v===null||q(v)?r(v):(e.consume(v),z)}function j(v){return v===null||v===34||v===39||v===47||v===60||v===61||v===62||v===96||te(v)?B(v):(e.consume(v),j)}function $(v){return v===47||v===62||Y(v)?_(v):r(v)}function k(v){return v===62?(e.consume(v),N):r(v)}function N(v){return v===null||q(v)?M(v):Y(v)?(e.consume(v),N):r(v)}function M(v){return v===45&&i===2?(e.consume(v),Q):v===60&&i===1?(e.consume(v),se):v===62&&i===4?(e.consume(v),ye):v===63&&i===3?(e.consume(v),x):v===93&&i===5?(e.consume(v),fe):q(v)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(bm,Ie,V)(v)):v===null||q(v)?(e.exit("htmlFlowData"),V(v)):(e.consume(v),M)}function V(v){return e.check(wm,R,Ie)(v)}function R(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),D}function D(v){return v===null||q(v)?V(v):(e.enter("htmlFlowData"),M(v))}function Q(v){return v===45?(e.consume(v),x):M(v)}function se(v){return v===47?(e.consume(v),a="",ge):M(v)}function ge(v){if(v===62){const ve=a.toLowerCase();return Po.includes(ve)?(e.consume(v),ye):M(v)}return Te(v)&&a.length<8?(e.consume(v),a+=String.fromCharCode(v),ge):M(v)}function fe(v){return v===93?(e.consume(v),x):M(v)}function x(v){return v===62?(e.consume(v),ye):v===45&&i===2?(e.consume(v),x):M(v)}function ye(v){return v===null||q(v)?(e.exit("htmlFlowData"),Ie(v)):(e.consume(v),ye)}function Ie(v){return e.exit("htmlFlow"),t(v)}}function Sm(e,t,r){const n=this;return i;function i(a){return q(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):r(a)}function s(a){return n.parser.lazy[n.now().line]?r(a):t(a)}}function km(e,t,r){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(ar,t,r)}}const _m={name:"htmlText",tokenize:Tm};function Tm(e,t,r){const n=this;let i,s,a;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),B):x===63?(e.consume(x),_):Te(x)?(e.consume(x),j):r(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),s=0,g):Te(x)?(e.consume(x),C):r(x)}function d(x){return x===45?(e.consume(x),h):r(x)}function c(x){return x===null?r(x):x===45?(e.consume(x),f):q(x)?(a=c,se(x)):(e.consume(x),c)}function f(x){return x===45?(e.consume(x),h):c(x)}function h(x){return x===62?Q(x):x===45?f(x):c(x)}function g(x){const ye="CDATA[";return x===ye.charCodeAt(s++)?(e.consume(x),s===ye.length?S:g):r(x)}function S(x){return x===null?r(x):x===93?(e.consume(x),w):q(x)?(a=S,se(x)):(e.consume(x),S)}function w(x){return x===93?(e.consume(x),b):S(x)}function b(x){return x===62?Q(x):x===93?(e.consume(x),b):S(x)}function C(x){return x===null||x===62?Q(x):q(x)?(a=C,se(x)):(e.consume(x),C)}function _(x){return x===null?r(x):x===63?(e.consume(x),F):q(x)?(a=_,se(x)):(e.consume(x),_)}function F(x){return x===62?Q(x):_(x)}function B(x){return Te(x)?(e.consume(x),I):r(x)}function I(x){return x===45||xe(x)?(e.consume(x),I):z(x)}function z(x){return q(x)?(a=z,se(x)):Y(x)?(e.consume(x),z):Q(x)}function j(x){return x===45||xe(x)?(e.consume(x),j):x===47||x===62||te(x)?$(x):r(x)}function $(x){return x===47?(e.consume(x),Q):x===58||x===95||Te(x)?(e.consume(x),k):q(x)?(a=$,se(x)):Y(x)?(e.consume(x),$):Q(x)}function k(x){return x===45||x===46||x===58||x===95||xe(x)?(e.consume(x),k):N(x)}function N(x){return x===61?(e.consume(x),M):q(x)?(a=N,se(x)):Y(x)?(e.consume(x),N):$(x)}function M(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(e.consume(x),i=x,V):q(x)?(a=M,se(x)):Y(x)?(e.consume(x),M):(e.consume(x),R)}function V(x){return x===i?(e.consume(x),i=void 0,D):x===null?r(x):q(x)?(a=V,se(x)):(e.consume(x),V)}function R(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||te(x)?$(x):(e.consume(x),R)}function D(x){return x===47||x===62||te(x)?$(x):r(x)}function Q(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):r(x)}function se(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),ge}function ge(x){return Y(x)?X(e,fe,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):fe(x)}function fe(x){return e.enter("htmlTextData"),a(x)}}const si={name:"labelEnd",resolveAll:Am,resolveTo:Pm,tokenize:Mm},Cm={tokenize:Lm},Im={tokenize:Nm},Em={tokenize:Dm};function Am(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const i=n.type==="labelImage"?4:2;n.type="data",t+=i}}return e.length!==r.length&&Le(e,0,e.length,r),e}function Pm(e,t){let r=e.length,n=0,i,s,a,o;for(;r--;)if(i=e[r][1],s){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(a){if(e[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(s=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(a=r);const l={type:e[s][1].type==="labelLink"?"link":"image",start:m({},e[s][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[s][1].start),end:m({},e[a][1].end)},d={type:"labelText",start:m({},e[s+n+2][1].end),end:m({},e[a-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Be(o,e.slice(s+1,s+n+3)),o=Be(o,[["enter",d,t]]),o=Be(o,qr(t.parser.constructs.insideSpan.null,e.slice(s+n+4,a-3),t)),o=Be(o,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),o=Be(o,e.slice(a+1)),o=Be(o,[["exit",l,t]]),Le(e,s,e.length,o),e}function Mm(e,t,r){const n=this;let i=n.events.length,s,a;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){s=n.events[i][1];break}return o;function o(f){return s?s._inactive?c(f):(a=n.parser.defined.includes(Ve(n.sliceSerialize({start:s.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):r(f)}function l(f){return f===40?e.attempt(Cm,d,a?d:c)(f):f===91?e.attempt(Im,d,a?u:c)(f):a?d(f):c(f)}function u(f){return e.attempt(Em,d,c)(f)}function d(f){return t(f)}function c(f){return s._balanced=!0,r(f)}}function Lm(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),i}function i(c){return te(c)?lr(e,s)(c):s(c)}function s(c){return c===41?d(c):Io(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function a(c){return te(c)?lr(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?Ao(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return te(c)?lr(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function Nm(e,t,r){const n=this;return i;function i(o){return Eo.call(n,e,s,a,"reference","referenceMarker","referenceString")(o)}function s(o){return n.parser.defined.includes(Ve(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function a(o){return r(o)}}function Dm(e,t,r){return n;function n(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),i}function i(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):r(s)}}const Om={name:"labelStartImage",resolveAll:si.resolveAll,tokenize:Fm};function Fm(e,t,r){const n=this;return i;function i(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),s}function s(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):r(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Bm={name:"labelStartLink",resolveAll:si.resolveAll,tokenize:zm};function zm(e,t,r){const n=this;return i;function i(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),s}function s(a){return a===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(a):t(a)}}const ai={name:"lineEnding",tokenize:Rm};function Rm(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),X(e,t,"linePrefix")}}const Vr={name:"thematicBreak",tokenize:jm};function jm(e,t,r){let n=0,i;return s;function s(u){return e.enter("thematicBreak"),a(u)}function a(u){return i=u,o(u)}function o(u){return u===i?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||q(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===i?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),Y(u)?X(e,o,"whitespace")(u):o(u))}}const Ae={continuation:{tokenize:qm},exit:Wm,name:"list",tokenize:Hm},Um={partial:!0,tokenize:Jm},$m={partial:!0,tokenize:Vm};function Hm(e,t,r){const n=this,i=n.events[n.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(h){const g=n.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||h===n.containerState.marker:ri(h)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(Vr,r,u)(h):u(h);if(!n.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return r(h)}function l(h){return ri(h)&&++a<10?(e.consume(h),l):(!n.interrupt||a<2)&&(n.containerState.marker?h===n.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):r(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||h,e.check(ar,n.interrupt?r:d,e.attempt(Um,f,c))}function d(h){return n.containerState.initialBlankLine=!0,s++,f(h)}function c(h){return Y(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=s+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function qm(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(ar,i,s);function i(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,X(e,t,"listItemIndent",n.containerState.size+1)(o)}function s(o){return n.containerState.furtherBlankLines||!Y(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,a(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt($m,t,a)(o))}function a(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,X(e,e.attempt(Ae,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Vm(e,t,r){const n=this;return X(e,i,"listItemIndent",n.containerState.size+1);function i(s){const a=n.events[n.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===n.containerState.size?t(s):r(s)}}function Wm(e){e.exit(this.containerState.type)}function Jm(e,t,r){const n=this;return X(e,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const a=n.events[n.events.length-1];return!Y(s)&&a&&a[1].type==="listItemPrefixWhitespace"?t(s):r(s)}}const Mo={name:"setextUnderline",resolveTo:Gm,tokenize:Ym};function Gm(e,t){let r=e.length,n,i,s;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(i=r)}else e[r][1].type==="content"&&e.splice(r,1),!s&&e[r][1].type==="definition"&&(s=r);const a={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",a,t]),e.splice(s+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[s][1].end)):e[n][1]=a,e.push(["exit",a,t]),e}function Ym(e,t,r){const n=this;let i;return s;function s(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),i=u,a(u)):r(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),Y(u)?X(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||q(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const Km={tokenize:Xm};function Xm(e){const t=this,r=e.attempt(ar,n,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(rm,i)),"linePrefix")));return r;function n(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Qm={resolveAll:No()},Zm=Lo("string"),eg=Lo("text");function Lo(e){return{resolveAll:No(e==="text"?tg:void 0),tokenize:t};function t(r){const n=this,i=this.parser.constructs[e],s=r.attempt(i,a,o);return a;function a(d){return u(d)?s(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),s(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=i[d];let f=-1;if(c)for(;++f<c.length;){const h=c[f];if(!h.previous||h.previous.call(n,n.previous))return!0}return!1}}}function No(e){return t;function t(r,n){let i=-1,s;for(;++i<=r.length;)s===void 0?r[i]&&r[i][1].type==="data"&&(s=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==s+2&&(r[s][1].end=r[i-1][1].end,r.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(r,n):r}}function tg(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],i=t.sliceStream(n);let s=i.length,a=-1,o=0,l;for(;s--;){const u=i[s];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)l=!0,o++;else if(u!==-1){s++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?a:n.start._bufferIndex+a,_index:n.start._index+s,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const rg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:om},disable:{null:[]},document:{42:Ae,43:Ae,45:Ae,48:Ae,49:Ae,50:Ae,51:Ae,52:Ae,53:Ae,54:Ae,55:Ae,56:Ae,57:Ae,62:vo},flow:{35:fm,42:Vr,45:[Mo,Vr],60:ym,61:Mo,95:Vr,96:To,126:To},flowInitial:{[-2]:ii,[-1]:ii,32:ii},insideSpan:{null:[ni,Qm]},string:{38:ko,92:So},text:{[-5]:ai,[-4]:ai,[-3]:ai,33:Om,38:ko,42:ni,60:[Bp,_m],91:Bm,92:[dm,So],93:si,95:ni,96:Kp}},Symbol.toStringTag,{value:"Module"}));function ng(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const i={},s=[];let a=[],o=[];const l={attempt:z(B),check:z(I),consume:C,enter:_,exit:F,interrupt:z(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:S,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&s.push(t),u;function c(N){return a=Be(a,N),w(),a[a.length-1]!==null?[]:(j(t,0),u.events=qr(s,u.events,u),u.events)}function f(N,M){return sg(h(N),M)}function h(N){return ig(a,N)}function g(){const{_bufferIndex:N,_index:M,line:V,column:R,offset:D}=n;return{_bufferIndex:N,_index:M,line:V,column:R,offset:D}}function S(N){i[N.line]=N.column,k()}function w(){let N;for(;n._index<a.length;){const M=a[n._index];if(typeof M=="string")for(N=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===N&&n._bufferIndex<M.length;)b(M.charCodeAt(n._bufferIndex));else b(M)}}function b(N){d=d(N)}function C(N){q(N)?(n.line++,n.column=1,n.offset+=N===-3?2:1,k()):N!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===a[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=N}function _(N,M){const V=M||{};return V.type=N,V.start=g(),u.events.push(["enter",V,u]),o.push(V),V}function F(N){const M=o.pop();return M.end=g(),u.events.push(["exit",M,u]),M}function B(N,M){j(N,M.from)}function I(N,M){M.restore()}function z(N,M){return V;function V(R,D,Q){let se,ge,fe,x;return Array.isArray(R)?Ie(R):"tokenize"in R?Ie([R]):ye(R);function ye(le){return zt;function zt(Z){const je=Z!==null&&le[Z],pe=Z!==null&&le.null,bt=[...Array.isArray(je)?je:je?[je]:[],...Array.isArray(pe)?pe:pe?[pe]:[]];return Ie(bt)(Z)}}function Ie(le){return se=le,ge=0,le.length===0?Q:v(le[ge])}function v(le){return zt;function zt(Z){return x=$(),fe=le,le.partial||(u.currentConstruct=le),le.name&&u.parser.constructs.disable.null.includes(le.name)?Re():le.tokenize.call(M?Object.assign(Object.create(u),M):u,l,ve,Re)(Z)}}function ve(le){return N(fe,x),D}function Re(le){return x.restore(),++ge<se.length?v(se[ge]):Q}}}function j(N,M){N.resolveAll&&!s.includes(N)&&s.push(N),N.resolve&&Le(u.events,M,u.events.length-M,N.resolve(u.events.slice(M),u)),N.resolveTo&&(u.events=N.resolveTo(u.events,u))}function $(){const N=g(),M=u.previous,V=u.currentConstruct,R=u.events.length,D=Array.from(o);return{from:R,restore:Q};function Q(){n=N,u.previous=M,u.currentConstruct=V,u.events.length=R,o=D,k()}}function k(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function ig(e,t){const r=t.start._index,n=t.start._bufferIndex,i=t.end._index,s=t.end._bufferIndex;let a;if(r===i)a=[e[r].slice(n,s)];else{if(a=e.slice(r,i),n>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(n):a.shift()}s>0&&a.push(e[i].slice(0,s))}return a}function sg(e,t){let r=-1;const n=[];let i;for(;++r<e.length;){const s=e[r];let a;if(typeof s=="string")a=s;else switch(s){case-5:{a="\r";break}case-4:{a=`
9
- `;break}case-3:{a=`\r
10
- `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&i)continue;a=" ";break}default:a=String.fromCharCode(s)}i=s===-2,n.push(a)}return n.join("")}function ag(e){const n={constructs:yo([rg,...(e||{}).extensions||[]]),content:i(Pp),defined:[],document:i(Lp),flow:i(Km),lazy:{},string:i(Zm),text:i(eg)};return n;function i(s){return a;function a(o){return ng(n,s,o)}}}function og(e){for(;!Co(e););return e}const Do=/[\0\t\n\r]/g;function lg(){let e=1,t="",r=!0,n;return i;function i(s,a,o){const l=[];let u,d,c,f,h;for(s=t+(typeof s=="string"?s.toString():new TextDecoder(a||void 0).decode(s)),c=0,t="",r&&(s.charCodeAt(0)===65279&&c++,r=void 0);c<s.length;){if(Do.lastIndex=c,u=Do.exec(s),f=u&&u.index!==void 0?u.index:s.length,h=s.charCodeAt(f),!u){t=s.slice(c);break}if(h===10&&c===f&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<f&&(l.push(s.slice(c,f)),e+=f-c),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=f+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const ug=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function cg(e){return e.replace(ug,dg)}function dg(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const i=r.charCodeAt(1),s=i===120||i===88;return bo(r.slice(s?2:1),s?16:10)}return ti(r)||e}const Oo={}.hasOwnProperty;function hg(e,t,r){return typeof t!="string"&&(r=t,t=void 0),fg(r)(og(ag(r).document().write(lg()(e,t,!0))))}function fg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(nu),autolinkProtocol:$,autolinkEmail:$,atxHeading:s(eu),blockQuote:s(pe),characterEscape:$,characterReference:$,codeFenced:s(bt),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:s(bt,a),codeText:s(nn,a),codeTextData:$,data:$,codeFlowValue:$,definition:s(sn),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:s(Ix),hardBreakEscape:s(tu),hardBreakTrailing:s(tu),htmlFlow:s(ru,a),htmlFlowData:$,htmlText:s(ru,a),htmlTextData:$,image:s(Ex),label:a,link:s(nu),listItem:s(Ax),listItemValue:f,listOrdered:s(iu,c),listUnordered:s(iu),paragraph:s(Px),reference:v,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:s(eu),strong:s(Mx),thematicBreak:s(Nx)},exit:{atxHeading:l(),atxHeadingSequence:B,autolink:l(),autolinkEmail:je,autolinkProtocol:Z,blockQuote:l(),characterEscapeValue:k,characterReferenceMarkerHexadecimal:Re,characterReferenceMarkerNumeric:Re,characterReferenceValue:le,characterReference:zt,codeFenced:l(w),codeFencedFence:S,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:k,codeIndented:l(b),codeText:l(D),codeTextData:k,data:k,definition:l(),definitionDestinationString:F,definitionLabelString:C,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(V),htmlFlowData:k,htmlText:l(R),htmlTextData:k,image:l(se),label:fe,labelText:ge,lineEnding:N,link:l(Q),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:ve,resourceDestinationString:x,resourceTitleString:ye,resource:Ie,setextHeading:l(j),setextHeadingLineSequence:z,setextHeadingText:I,strong:l(),thematicBreak:l()}};Fo(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let O={type:"root",children:[]};const W={stack:[O],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:d,data:r},K=[];let re=-1;for(;++re<A.length;)if(A[re][1].type==="listOrdered"||A[re][1].type==="listUnordered")if(A[re][0]==="enter")K.push(re);else{const Je=K.pop();re=i(A,Je,re)}for(re=-1;++re<A.length;){const Je=t[A[re][0]];Oo.call(Je,A[re][1].type)&&Je[A[re][1].type].call(Object.assign({sliceSerialize:A[re][2].sliceSerialize},W),A[re][1])}if(W.tokenStack.length>0){const Je=W.tokenStack[W.tokenStack.length-1];(Je[1]||Bo).call(W,void 0,Je[0])}for(O.position={start:lt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:lt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},re=-1;++re<t.transforms.length;)O=t.transforms[re](O)||O;return O}function i(A,O,W){let K=O-1,re=-1,Je=!1,wt,rt,yr,br;for(;++K<=W;){const Ne=A[K];switch(Ne[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ne[0]==="enter"?re++:re--,br=void 0;break}case"lineEndingBlank":{Ne[0]==="enter"&&(wt&&!br&&!re&&!yr&&(yr=K),br=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:br=void 0}if(!re&&Ne[0]==="enter"&&Ne[1].type==="listItemPrefix"||re===-1&&Ne[0]==="exit"&&(Ne[1].type==="listUnordered"||Ne[1].type==="listOrdered")){if(wt){let Rt=K;for(rt=void 0;Rt--;){const nt=A[Rt];if(nt[1].type==="lineEnding"||nt[1].type==="lineEndingBlank"){if(nt[0]==="exit")continue;rt&&(A[rt][1].type="lineEndingBlank",Je=!0),nt[1].type="lineEnding",rt=Rt}else if(!(nt[1].type==="linePrefix"||nt[1].type==="blockQuotePrefix"||nt[1].type==="blockQuotePrefixWhitespace"||nt[1].type==="blockQuoteMarker"||nt[1].type==="listItemIndent"))break}yr&&(!rt||yr<rt)&&(wt._spread=!0),wt.end=Object.assign({},rt?A[rt][1].start:Ne[1].end),A.splice(rt||K,0,["exit",wt,Ne[2]]),K++,W++}if(Ne[1].type==="listItemPrefix"){const Rt={type:"listItem",_spread:!1,start:Object.assign({},Ne[1].start),end:void 0};wt=Rt,A.splice(K,0,["enter",Rt,Ne[2]]),K++,W++,yr=void 0,br=!0}}}return A[O][1]._spread=Je,W}function s(A,O){return W;function W(K){o.call(this,A(K),K),O&&O.call(this,K)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(A,O,W){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([O,W||void 0]),A.position={start:lt(O.start),end:void 0}}function l(A){return O;function O(W){A&&A.call(this,W),u.call(this,W)}}function u(A,O){const W=this.stack.pop(),K=this.tokenStack.pop();if(K)K[0].type!==A.type&&(O?O.call(this,A,K[0]):(K[1]||Bo).call(this,A,K[0]));else throw new Error("Cannot close `"+A.type+"` ("+ir({start:A.start,end:A.end})+"): it’s not open");W.position.end=lt(A.end)}function d(){return ei(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const O=this.stack[this.stack.length-2];O.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),O=this.stack[this.stack.length-1];O.lang=A}function g(){const A=this.resume(),O=this.stack[this.stack.length-1];O.meta=A}function S(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/(\r?\n|\r)$/g,"")}function C(A){const O=this.resume(),W=this.stack[this.stack.length-1];W.label=O,W.identifier=Ve(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function F(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function B(A){const O=this.stack[this.stack.length-1];if(!O.depth){const W=this.sliceSerialize(A).length;O.depth=W}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function z(A){const O=this.stack[this.stack.length-1];O.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function j(){this.data.setextHeadingSlurpLineEnding=void 0}function $(A){const W=this.stack[this.stack.length-1].children;let K=W[W.length-1];(!K||K.type!=="text")&&(K=Lx(),K.position={start:lt(A.start),end:void 0},W.push(K)),this.stack.push(K)}function k(A){const O=this.stack.pop();O.value+=this.sliceSerialize(A),O.position.end=lt(A.end)}function N(A){const O=this.stack[this.stack.length-1];if(this.data.atHardBreak){const W=O.children[O.children.length-1];W.position.end=lt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(O.type)&&($.call(this,A),k.call(this,A))}function M(){this.data.atHardBreak=!0}function V(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function R(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function D(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function Q(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function se(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ge(A){const O=this.sliceSerialize(A),W=this.stack[this.stack.length-2];W.label=cg(O),W.identifier=Ve(O).toLowerCase()}function fe(){const A=this.stack[this.stack.length-1],O=this.resume(),W=this.stack[this.stack.length-1];if(this.data.inReference=!0,W.type==="link"){const K=A.children;W.children=K}else W.alt=O}function x(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function ye(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function Ie(){this.data.inReference=void 0}function v(){this.data.referenceType="collapsed"}function ve(A){const O=this.resume(),W=this.stack[this.stack.length-1];W.label=O,W.identifier=Ve(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Re(A){this.data.characterReferenceType=A.type}function le(A){const O=this.sliceSerialize(A),W=this.data.characterReferenceType;let K;W?(K=bo(O,W==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):K=ti(O);const re=this.stack[this.stack.length-1];re.value+=K}function zt(A){const O=this.stack.pop();O.position.end=lt(A.end)}function Z(A){k.call(this,A);const O=this.stack[this.stack.length-1];O.url=this.sliceSerialize(A)}function je(A){k.call(this,A);const O=this.stack[this.stack.length-1];O.url="mailto:"+this.sliceSerialize(A)}function pe(){return{type:"blockquote",children:[]}}function bt(){return{type:"code",lang:null,meta:null,value:""}}function nn(){return{type:"inlineCode",value:""}}function sn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Ix(){return{type:"emphasis",children:[]}}function eu(){return{type:"heading",depth:0,children:[]}}function tu(){return{type:"break"}}function ru(){return{type:"html",value:""}}function Ex(){return{type:"image",title:null,url:"",alt:null}}function nu(){return{type:"link",title:null,url:"",children:[]}}function iu(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function Ax(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Px(){return{type:"paragraph",children:[]}}function Mx(){return{type:"strong",children:[]}}function Lx(){return{type:"text",value:""}}function Nx(){return{type:"thematicBreak"}}}function lt(e){return{line:e.line,column:e.column,offset:e.offset}}function Fo(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?Fo(e,n):pg(e,n)}}function pg(e,t){let r;for(r in t)if(Oo.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function Bo(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+ir({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+ir({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+ir({start:t.start,end:t.end})+") is still open")}function mg(e){const t=this;t.parser=r;function r(n){return hg(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function gg(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function yg(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
- `}]}function bg(e,t){const r=t.value?t.value+`
12
- `:"",n={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(n.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function wg(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function xg(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function vg(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),i=Dt(n.toLowerCase()),s=e.footnoteOrder.indexOf(n);let a,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),a=e.footnoteOrder.length):a=s+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+i,id:r+"fnref-"+i+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function Sg(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function kg(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function zo(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&a.type==="text"?a.value+=n:i.push({type:"text",value:n}),i}function _g(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return zo(e,t);const i={src:Dt(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(i.title=n.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function Tg(e,t){const r={src:Dt(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function Cg(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function Ig(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return zo(e,t);const i={href:Dt(n.url||"")};n.title!==null&&n.title!==void 0&&(i.title=n.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function Eg(e,t){const r={href:Dt(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ag(e,t,r){const n=e.all(t),i=r?Pg(r):Ro(t),s={},a=[];if(typeof t.checked=="boolean"){const d=n[0];let c;d&&d.type==="element"&&d.tagName==="p"?c=d:(c={type:"element",tagName:"p",properties:{},children:[]},n.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(i||o!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
13
- `}),d.type==="element"&&d.tagName==="p"&&!i?a.push(...d.children):a.push(d)}const l=n[n.length-1];l&&(i||l.type!=="element"||l.tagName!=="p")&&a.push({type:"text",value:`
14
- `});const u={type:"element",tagName:"li",properties:s,children:a};return e.patch(t,u),e.applyData(t,u)}function Pg(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=Ro(r[n])}return t}function Ro(e){const t=e.spread;return t==null?e.children.length>1:t}function Mg(e,t){const r={},n=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++i<n.length;){const a=n[i];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const s={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,s),e.applyData(t,s)}function Lg(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Ng(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function Dg(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Og(e,t){const r=e.all(t),n=r.shift(),i=[];if(n){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],a),i.push(a)}if(r.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=Gn(t.children[1]),l=io(t.children[t.children.length-1]);o&&l&&(a.position={start:o,end:l}),i.push(a)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function Fg(e,t,r){const n=r?r.children:void 0,s=(n?n.indexOf(t):1)===0?"th":"td",a=r&&r.type==="table"?r.align:void 0,o=a?a.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],f={},h=a?a[l]:void 0;h&&(f.align=h);let g={type:"element",tagName:s,properties:f,children:[]};c&&(g.children=e.all(c),e.patch(c,g),g=e.applyData(c,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Bg(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const jo=9,Uo=32;function zg(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),i=0;const s=[];for(;n;)s.push($o(t.slice(i,n.index),i>0,!0),n[0]),i=n.index+n[0].length,n=r.exec(t);return s.push($o(t.slice(i),i>0,!1)),s.join("")}function $o(e,t,r){let n=0,i=e.length;if(t){let s=e.codePointAt(n);for(;s===jo||s===Uo;)n++,s=e.codePointAt(n)}if(r){let s=e.codePointAt(i-1);for(;s===jo||s===Uo;)i--,s=e.codePointAt(i-1)}return i>n?e.slice(n,i):""}function Rg(e,t){const r={type:"text",value:zg(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function jg(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const Ug={blockquote:gg,break:yg,code:bg,delete:wg,emphasis:xg,footnoteReference:vg,heading:Sg,html:kg,imageReference:_g,image:Tg,inlineCode:Cg,linkReference:Ig,link:Eg,listItem:Ag,list:Mg,paragraph:Lg,root:Ng,strong:Dg,table:Og,tableCell:Bg,tableRow:Fg,text:Rg,thematicBreak:jg,toml:Wr,yaml:Wr,definition:Wr,footnoteDefinition:Wr};function Wr(){}const Ho=-1,Jr=0,ur=1,Gr=2,oi=3,li=4,ui=5,ci=6,qo=7,Vo=8,Wo=typeof self=="object"?self:globalThis,$g=(e,t)=>{const r=(i,s)=>(e.set(s,i),i),n=i=>{if(e.has(i))return e.get(i);const[s,a]=t[i];switch(s){case Jr:case Ho:return r(a,i);case ur:{const o=r([],i);for(const l of a)o.push(n(l));return o}case Gr:{const o=r({},i);for(const[l,u]of a)o[n(l)]=n(u);return o}case oi:return r(new Date(a),i);case li:{const{source:o,flags:l}=a;return r(new RegExp(o,l),i)}case ui:{const o=r(new Map,i);for(const[l,u]of a)o.set(n(l),n(u));return o}case ci:{const o=r(new Set,i);for(const l of a)o.add(n(l));return o}case qo:{const{name:o,message:l}=a;return r(new Wo[o](l),i)}case Vo:return r(BigInt(a),i);case"BigInt":return r(Object(BigInt(a)),i);case"ArrayBuffer":return r(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return r(new DataView(o),a)}}return r(new Wo[s](a),i)};return n},Jo=e=>$g(new Map,e)(0),Ft="",{toString:Hg}={},{keys:qg}=Object,cr=e=>{const t=typeof e;if(t!=="object"||!e)return[Jr,t];const r=Hg.call(e).slice(8,-1);switch(r){case"Array":return[ur,Ft];case"Object":return[Gr,Ft];case"Date":return[oi,Ft];case"RegExp":return[li,Ft];case"Map":return[ui,Ft];case"Set":return[ci,Ft];case"DataView":return[ur,r]}return r.includes("Array")?[ur,r]:r.includes("Error")?[qo,r]:[Gr,r]},Yr=([e,t])=>e===Jr&&(t==="function"||t==="symbol"),Vg=(e,t,r,n)=>{const i=(a,o)=>{const l=n.push(a)-1;return r.set(o,l),l},s=a=>{if(r.has(a))return r.get(a);let[o,l]=cr(a);switch(o){case Jr:{let d=a;switch(l){case"bigint":o=Vo,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return i([Ho],a)}return i([o,d],a)}case ur:{if(l){let f=a;return l==="DataView"?f=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(a)),i([l,[...f]],a)}const d=[],c=i([o,d],a);for(const f of a)d.push(s(f));return c}case Gr:{if(l)switch(l){case"BigInt":return i([l,a.toString()],a);case"Boolean":case"Number":case"String":return i([l,a.valueOf()],a)}if(t&&"toJSON"in a)return s(a.toJSON());const d=[],c=i([o,d],a);for(const f of qg(a))(e||!Yr(cr(a[f])))&&d.push([s(f),s(a[f])]);return c}case oi:return i([o,a.toISOString()],a);case li:{const{source:d,flags:c}=a;return i([o,{source:d,flags:c}],a)}case ui:{const d=[],c=i([o,d],a);for(const[f,h]of a)(e||!(Yr(cr(f))||Yr(cr(h))))&&d.push([s(f),s(h)]);return c}case ci:{const d=[],c=i([o,d],a);for(const f of a)(e||!Yr(cr(f)))&&d.push(s(f));return c}}const{message:u}=a;return i([o,{name:l,message:u}],a)};return s},Go=(e,{json:t,lossy:r}={})=>{const n=[];return Vg(!(t||r),!!t,new Map,n)(e),n},Kr=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Jo(Go(e,t)):structuredClone(e):(e,t)=>Jo(Go(e,t));function Wg(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function Jg(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Gg(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||Wg,n=e.options.footnoteBackLabel||Jg,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const d=e.all(u),c=String(u.identifier).toUpperCase(),f=Dt(c.toLowerCase());let h=0;const g=[],S=e.footnoteCounts.get(c);for(;S!==void 0&&++h<=S;){g.length>0&&g.push({type:"text",value:" "});let C=typeof r=="string"?r:r(l,h);typeof C=="string"&&(C={type:"text",value:C}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,h),className:["data-footnote-backref"]},children:Array.isArray(C)?C:[C]})}const w=d[d.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const C=w.children[w.children.length-1];C&&C.type==="text"?C.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else d.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(d,!0)};e.patch(u,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:E(m({},Kr(a)),{id:"footnote-label"}),children:[{type:"text",value:i}]},{type:"text",value:`
7
+ `);a=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function Zf(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(a=>a.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function ep(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}function io(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,onChatCreated:i,onUserMessage:s,onThreadIdUpdate:o}=t;return{run(u){return Pr(this,null,function*(){const{messages:d,abortSignal:c,context:f}=u,h=f==null?void 0:f.threadId;s==null||s();const S={messages:Zf(d),chatId:null,systemPrompt:n,ephemeral:a,stream:!0};r&&r.trim()!==""&&(S.modelId=r);const w=yield new lt(e.createOrContinueChat(S,c));let b="",T;try{for(var _=Mt(Qf(w,c)),F,z,I;F=!(z=yield new lt(_.next())).done;F=!1){const U=z.value;if(c!=null&&c.aborted)throw new Error("Request aborted");const j=U.id;j&&!T&&(T=j,i==null||i(j),h&&o&&o(h,j));const R=U.delta;if(R!=null&&(b+=R),U.type==="message"||U.content){const D=U.content||"";b+=D}if(U.message&&(b+=U.message.content||""),U.tool_calls,U.finished){b&&(yield{content:[{type:"text",text:b}]});break}b&&(yield{content:[{type:"text",text:b}]})}}catch(z){I=[z]}finally{try{F&&(z=_.return)&&(yield new lt(z.call(_)))}finally{if(I)throw I[0]}}b&&(yield{content:[{type:"text",text:b}]})})}}}const so=new Map;function tp(e,t){return{list(){return P(this,null,function*(){const n=[];let i,s=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),i=l.nextCursor||void 0,s++}while(i&&s<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return P(this,null,function*(){return{remoteId:so.get(n)||n,externalId:void 0}})},rename(n,a){return P(this,null,function*(){yield e.updateChat(n,{title:a})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){yield e.deleteChat(n)})},generateTitle(n,a){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(this,null,function*(){try{const a=yield e.getChat(n);return{status:"regular",remoteId:a.id||n,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch(a){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,a){so.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=ts(),i=a==null?void 0:a.remoteId,s=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const u=yield e.getChat(i);return!u.messages||u.messages.length===0?{messages:[]}:{messages:u.messages.map(c=>ep(c))}}catch(u){return console.error("Failed to load messages for thread:",i,u),{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[i,e]),o=y.useMemo(()=>({history:s}),[s]);return p.jsx(Mn,{adapters:o,children:n})}}}function oo(){return{accept:".pdf,.docx,.txt,.md,.csv,.json,image/*",add(r){return P(this,arguments,function*({file:t}){let n="file";return t.type.startsWith("image/")?n="image":(t.type.includes("pdf")||t.type.includes("document")||t.type.includes("text")||t.name.endsWith(".pdf")||t.name.endsWith(".docx")||t.name.endsWith(".txt")||t.name.endsWith(".md")||t.name.endsWith(".csv")||t.name.endsWith(".json"))&&(n="document"),{id:`${t.name}-${Date.now()}`,type:n,name:t.name,contentType:t.type,file:t,status:{type:"requires-action",reason:"composer-send"}}})},remove(){return P(this,null,function*(){})},send(t){return P(this,null,function*(){if(t.type==="image"&&t.file){const r=yield new Promise((n,a)=>{const i=new FileReader;i.onload=()=>n(i.result),i.onerror=a,i.readAsDataURL(t.file)});return E(m({},t),{status:{type:"complete"},content:[{type:"image",image:r}]})}return E(m({},t),{status:{type:"complete"},content:[]})})}}}function rp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:i,onModelChange:s,ephemeral:o=!1,systemPrompt:l,initialThreadId:u,onError:d,onChatCreated:c,onUserMessage:f,onThreadIdUpdate:h,onChatsLoaded:g,enableAttachments:S=!1}){const w=y.useMemo(()=>new ao(t,r||void 0,n),[t,r,n]),[b,T]=y.useState(i||null);y.useEffect(()=>{i&&T(i)},[i]);const _=y.useCallback(I=>{c==null||c(I)},[c]),F=y.useCallback((I,U)=>{h==null||h(I,U)},[h]),z=y.useMemo(()=>io(w,{modelId:b||void 0,systemPrompt:l,ephemeral:o,onChatCreated:_,onUserMessage:f}),[w,b,l,o,_,f]);return a==="singleChat"?p.jsx(np,{modelAdapter:z,enableAttachments:S,children:e}):p.jsx(ap,{client:w,modelAdapterOptions:{modelId:b||void 0,systemPrompt:l,ephemeral:o,onChatCreated:_,onUserMessage:f},initialThreadId:u,onChatsLoaded:g,onThreadIdUpdate:F,onError:d,enableAttachments:S,children:e})}function np({modelAdapter:e,enableAttachments:t,children:r}){const n=y.useMemo(()=>t?oo():void 0,[t]),a=ds(e,{adapters:m({},n&&{attachments:n})});return p.jsx(is,{runtime:a,children:r})}function ap({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:i,enableAttachments:s,children:o}){const l=y.useMemo(()=>tp(e,(S,w)=>{a==null||a(S,w)}),[e,a]),u=y.useCallback((S,w)=>{l.updateRemoteId&&l.updateRemoteId(S,w),a==null||a(S,w)},[l,a]),d=y.useMemo(()=>E(m({},l),{list(){return P(this,null,function*(){const w=yield l.list();return n==null||n(),w})}}),[l,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const c=y.useMemo(()=>io(e,E(m({},t),{onThreadIdUpdate:u})),[e,t,u]),f=y.useMemo(()=>s?oo():void 0,[s]),h=y.useCallback(()=>ds(c,{adapters:m({},f&&{attachments:f})}),[c,f]),g=gs({adapter:d,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),p.jsx(is,{runtime:g,children:o})}function pv(){}function mv(){}function ip(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const sp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,op=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,lp={};function lo(e,t){return(lp.jsx?op:sp).test(e)}const up=/[ \t\n\f\r]/g;function cp(e){return typeof e=="object"?e.type==="text"?uo(e.value):!1:uo(e)}function uo(e){return e.replace(up,"")===""}class ur{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}ur.prototype.normal={},ur.prototype.property={},ur.prototype.space=void 0;function co(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new ur(r,n,t)}function Qn(e){return e.toLowerCase()}class Ee{constructor(t,r){this.attribute=r,this.property=t}}Ee.prototype.attribute="",Ee.prototype.booleanish=!1,Ee.prototype.boolean=!1,Ee.prototype.commaOrSpaceSeparated=!1,Ee.prototype.commaSeparated=!1,Ee.prototype.defined=!1,Ee.prototype.mustUseProperty=!1,Ee.prototype.number=!1,Ee.prototype.overloadedBoolean=!1,Ee.prototype.property="",Ee.prototype.spaceSeparated=!1,Ee.prototype.space=void 0;let dp=0;const G=St(),he=St(),Zn=St(),N=St(),se=St(),jt=St(),De=St();function St(){return _u(2,++dp)}const ea=Object.freeze(Object.defineProperty({__proto__:null,boolean:G,booleanish:he,commaOrSpaceSeparated:De,commaSeparated:jt,number:N,overloadedBoolean:Zn,spaceSeparated:se},Symbol.toStringTag,{value:"Module"})),ta=Object.keys(ea);class ra extends Ee{constructor(t,r,n,a){let i=-1;if(super(t,r),ho(this,"space",a),typeof n=="number")for(;++i<ta.length;){const s=ta[i];ho(this,ta[i],(n&ea[s])===ea[s])}}}ra.prototype.defined=!0;function ho(e,t,r){r&&(e[t]=r)}function Ut(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const i=new ra(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[Qn(n)]=n,r[Qn(i.attribute)]=n}return new ur(t,r,e.space)}const fo=Ut({properties:{ariaActiveDescendant:null,ariaAtomic:he,ariaAutoComplete:null,ariaBusy:he,ariaChecked:he,ariaColCount:N,ariaColIndex:N,ariaColSpan:N,ariaControls:se,ariaCurrent:null,ariaDescribedBy:se,ariaDetails:null,ariaDisabled:he,ariaDropEffect:se,ariaErrorMessage:null,ariaExpanded:he,ariaFlowTo:se,ariaGrabbed:he,ariaHasPopup:null,ariaHidden:he,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:se,ariaLevel:N,ariaLive:null,ariaModal:he,ariaMultiLine:he,ariaMultiSelectable:he,ariaOrientation:null,ariaOwns:se,ariaPlaceholder:null,ariaPosInSet:N,ariaPressed:he,ariaReadOnly:he,ariaRelevant:null,ariaRequired:he,ariaRoleDescription:se,ariaRowCount:N,ariaRowIndex:N,ariaRowSpan:N,ariaSelected:he,ariaSetSize:N,ariaSort:null,ariaValueMax:N,ariaValueMin:N,ariaValueNow:N,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function po(e,t){return t in e?e[t]:t}function mo(e,t){return po(e,t.toLowerCase())}const hp=Ut({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:jt,acceptCharset:se,accessKey:se,action:null,allow:null,allowFullScreen:G,allowPaymentRequest:G,allowUserMedia:G,alt:null,as:null,async:G,autoCapitalize:null,autoComplete:se,autoFocus:G,autoPlay:G,blocking:se,capture:null,charSet:null,checked:G,cite:null,className:se,cols:N,colSpan:null,content:null,contentEditable:he,controls:G,controlsList:se,coords:N|jt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:G,defer:G,dir:null,dirName:null,disabled:G,download:Zn,draggable:he,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:G,formTarget:null,headers:se,height:N,hidden:Zn,high:N,href:null,hrefLang:null,htmlFor:se,httpEquiv:se,id:null,imageSizes:null,imageSrcSet:null,inert:G,inputMode:null,integrity:null,is:null,isMap:G,itemId:null,itemProp:se,itemRef:se,itemScope:G,itemType:se,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:G,low:N,manifest:null,max:null,maxLength:N,media:null,method:null,min:null,minLength:N,multiple:G,muted:G,name:null,nonce:null,noModule:G,noValidate:G,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:G,optimum:N,pattern:null,ping:se,placeholder:null,playsInline:G,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:G,referrerPolicy:null,rel:se,required:G,reversed:G,rows:N,rowSpan:N,sandbox:se,scope:null,scoped:G,seamless:G,selected:G,shadowRootClonable:G,shadowRootDelegatesFocus:G,shadowRootMode:null,shape:null,size:N,sizes:null,slot:null,span:N,spellCheck:he,src:null,srcDoc:null,srcLang:null,srcSet:null,start:N,step:null,style:null,tabIndex:N,target:null,title:null,translate:null,type:null,typeMustMatch:G,useMap:null,value:he,width:N,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:se,axis:null,background:null,bgColor:null,border:N,borderColor:null,bottomMargin:N,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:G,declare:G,event:null,face:null,frame:null,frameBorder:null,hSpace:N,leftMargin:N,link:null,longDesc:null,lowSrc:null,marginHeight:N,marginWidth:N,noResize:G,noHref:G,noShade:G,noWrap:G,object:null,profile:null,prompt:null,rev:null,rightMargin:N,rules:null,scheme:null,scrolling:he,standby:null,summary:null,text:null,topMargin:N,valueType:null,version:null,vAlign:null,vLink:null,vSpace:N,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:G,disableRemotePlayback:G,prefix:null,property:null,results:N,security:null,unselectable:null},space:"html",transform:mo}),fp=Ut({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:De,accentHeight:N,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:N,amplitude:N,arabicForm:null,ascent:N,attributeName:null,attributeType:null,azimuth:N,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:N,by:null,calcMode:null,capHeight:N,className:se,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:N,diffuseConstant:N,direction:null,display:null,dur:null,divisor:N,dominantBaseline:null,download:G,dx:null,dy:null,edgeMode:null,editable:null,elevation:N,enableBackground:null,end:null,event:null,exponent:N,externalResourcesRequired:null,fill:null,fillOpacity:N,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:jt,g2:jt,glyphName:jt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:N,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:N,horizOriginX:N,horizOriginY:N,id:null,ideographic:N,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:N,k:N,k1:N,k2:N,k3:N,k4:N,kernelMatrix:De,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:N,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:N,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:N,overlineThickness:N,paintOrder:null,panose1:null,path:null,pathLength:N,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:se,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:N,pointsAtY:N,pointsAtZ:N,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:De,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:De,rev:De,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:De,requiredFeatures:De,requiredFonts:De,requiredFormats:De,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:N,specularExponent:N,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:N,strikethroughThickness:N,string:null,stroke:null,strokeDashArray:De,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:N,strokeOpacity:N,strokeWidth:null,style:null,surfaceScale:N,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:De,tabIndex:N,tableValues:null,target:null,targetX:N,targetY:N,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:De,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:N,underlineThickness:N,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:N,values:null,vAlphabetic:N,vMathematical:N,vectorEffect:null,vHanging:N,vIdeographic:N,version:null,vertAdvY:N,vertOriginX:N,vertOriginY:N,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:N,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:po}),go=Ut({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),yo=Ut({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:mo}),bo=Ut({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),pp={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},mp=/[A-Z]/g,wo=/-[a-z]/g,gp=/^data[-\w.:]+$/i;function yp(e,t){const r=Qn(t);let n=t,a=Ee;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&gp.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(wo,wp);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!wo.test(i)){let s=i.replace(mp,bp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}a=ra}return new a(n,t)}function bp(e){return"-"+e.toLowerCase()}function wp(e){return e.charAt(1).toUpperCase()}const xp=co([fo,hp,go,yo,bo],"html"),na=co([fo,fp,go,yo,bo],"svg");function vp(e){return e.join(" ").trim()}var $t={},aa,xo;function Sp(){if(xo)return aa;xo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
+ `,u="/",d="*",c="",f="comment",h="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var T=1,_=1;function F(B){var O=B.match(t);O&&(T+=O.length);var X=B.lastIndexOf(l);_=~X?B.length-X:_+B.length}function z(){var B={line:T,column:_};return function(O){return O.position=new I(B),R(),O}}function I(B){this.start=B,this.end={line:T,column:_},this.source=b.source}I.prototype.content=w;function U(B){var O=new Error(b.source+":"+T+":"+_+": "+B);if(O.reason=B,O.filename=b.source,O.line=T,O.column=_,O.source=w,!b.silent)throw O}function j(B){var O=B.exec(w);if(O){var X=O[0];return F(X),w=w.slice(X.length),O}}function R(){j(r)}function k(B){var O;for(B=B||[];O=D();)O!==!1&&B.push(O);return B}function D(){var B=z();if(!(u!=w.charAt(0)||d!=w.charAt(1))){for(var O=2;c!=w.charAt(O)&&(d!=w.charAt(O)||u!=w.charAt(O+1));)++O;if(O+=2,c===w.charAt(O-1))return U("End of comment missing");var X=w.slice(2,O-2);return _+=2,F(X),w=w.slice(O),_+=2,B({type:f,comment:X})}}function M(){var B=z(),O=j(n);if(O){if(D(),!j(a))return U("property missing ':'");var X=j(i),ae=B({type:h,property:S(O[0].replace(e,c)),value:X?S(X[0].replace(e,c)):c});return j(s),ae}}function W(){var B=[];k(B);for(var O;O=M();)O!==!1&&(B.push(O),k(B));return B}return R(),W()}function S(w){return w?w.replace(o,c):c}return aa=g,aa}var vo;function kp(){if(vo)return $t;vo=1;var e=$t&&$t.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty($t,"__esModule",{value:!0}),$t.default=r;const t=e(Sp());function r(n,a){let i=null;if(!n||typeof n!="string")return i;const s=(0,t.default)(n),o=typeof a=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?a(u,d,l):d&&(i=i||{},i[u]=d)}),i}return $t}var cr={},So;function _p(){if(So)return cr;So=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(u){return!u||r.test(u)||e.test(u)},s=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,s))};return cr.camelCase=l,cr}var dr,ko;function Tp(){if(ko)return dr;ko=1;var e=dr&&dr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(kp()),r=_p();function n(a,i){var s={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(s[(0,r.camelCase)(o,i)]=l)}),s}return n.default=n,dr=n,dr}var Cp=Tp();const Ip=Mr(Cp),_o=To("end"),ia=To("start");function To(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function Ep(e){const t=ia(e),r=_o(e);if(t&&r)return{start:t,end:r}}function hr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Co(e.position):"start"in e||"end"in e?Co(e):"line"in e||"column"in e?sa(e):""}function sa(e){return Io(e&&e.line)+":"+Io(e&&e.column)}function Co(e){return sa(e&&e.start)+"-"+sa(e&&e.end)}function Io(e){return e&&typeof e=="number"?e:1}class we extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},s=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i=m({},r)),typeof t=="string"?a=t:!i.cause&&t&&(s=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=hr(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=s&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}we.prototype.file="",we.prototype.name="",we.prototype.reason="",we.prototype.message="",we.prototype.stack="",we.prototype.column=void 0,we.prototype.line=void 0,we.prototype.ancestors=void 0,we.prototype.cause=void 0,we.prototype.fatal=void 0,we.prototype.place=void 0,we.prototype.ruleId=void 0,we.prototype.source=void 0;const oa={}.hasOwnProperty,Ap=new Map,Pp=/[A-Z]/g,Mp=new Set(["table","tbody","thead","tfoot","tr"]),Np=new Set(["td","th"]),Eo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Lp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=Up(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=jp(r,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?na:xp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Ao(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function Ao(e,t,r){if(t.type==="element")return Dp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Op(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Bp(e,t,r);if(t.type==="mdxjsEsm")return Fp(e,t);if(t.type==="root")return zp(e,t,r);if(t.type==="text")return Rp(e,t)}function Dp(e,t,r){const n=e.schema;let a=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=na,e.schema=a),e.ancestors.push(t);const i=Mo(e,t.tagName,!1),s=$p(e,t);let o=ua(e,t);return Mp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!cp(l):!0})),Po(e,s,i,t),la(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Op(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}fr(e,t.position)}function Fp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);fr(e,t.position)}function Bp(e,t,r){const n=e.schema;let a=n;t.name==="svg"&&n.space==="html"&&(a=na,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:Mo(e,t.name,!0),s=Hp(e,t),o=ua(e,t);return Po(e,s,i,t),la(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function zp(e,t,r){const n={};return la(n,ua(e,t)),e.create(t,e.Fragment,n,r)}function Rp(e,t){return t.value}function Po(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function la(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function jp(e,t,r){return n;function n(a,i,s,o){const u=Array.isArray(s.children)?r:t;return o?u(i,s,o):u(i,s)}}function Up(e,t){return r;function r(n,a,i,s){const o=Array.isArray(i.children),l=ia(n);return t(a,i,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function $p(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&oa.call(t.properties,a)){const i=qp(e,a,t.properties[a]);if(i){const[s,o]=i;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&Np.has(t.tagName)?n=o:r[s]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function Hp(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const s=i.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else fr(e,t.position);else{const a=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else fr(e,t.position);else i=n.value===null?!0:n.value;r[a]=i}return r}function ua(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Ap;for(;++n<t.children.length;){const i=t.children[n];let s;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;s=l+"-"+u,a.set(l,u+1)}}const o=Ao(e,i,s);o!==void 0&&r.push(o)}return r}function qp(e,t,r){const n=yp(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?ip(r):vp(r)),n.property==="style"){let a=typeof r=="object"?r:Vp(e,String(r));return e.stylePropertyNameCase==="css"&&(a=Wp(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?pp[n.property]||n.property:n.attribute,r]}}function Vp(e,t){try{return Ip(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new we("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=Eo+"#cannot-parse-style-attribute",a}}function Mo(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,s;for(;++i<a.length;){const o=lo(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=s}else n=lo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const a=n.value;return oa.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);fr(e)}function fr(e,t){const r=new we("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Eo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function Wp(e){const t={};let r;for(r in e)oa.call(e,r)&&(t[Jp(r)]=e[r]);return t}function Jp(e){let t=e.replace(Pp,Kp);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Kp(e){return"-"+e.toLowerCase()}const ca={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},Gp={};function da(e,t){const r=Gp,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return No(e,n,a)}function No(e,t,r){if(Yp(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Lo(e.children,t,r)}return Array.isArray(e)?Lo(e,t,r):""}function Lo(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=No(e[a],t,r);return n.join("")}function Yp(e){return!!(e&&typeof e=="object")}const Do=document.createElement("i");function ha(e){const t="&"+e+";";Do.innerHTML=t;const r=Do.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Oe(e,t,r,n){const a=e.length;let i=0,s;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(t,r),e.splice(...s);else for(r&&e.splice(t,r);i<n.length;)s=n.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function je(e,t){return e.length>0?(Oe(e,e.length,0,t),e):t}const Oo={}.hasOwnProperty;function Fo(e){const t={};let r=-1;for(;++r<e.length;)Xp(t,e[r]);return t}function Xp(e,t){let r;for(r in t){const a=(Oo.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let s;if(i)for(s in i){Oo.call(a,s)||(a[s]=[]);const o=i[s];Qp(a[s],Array.isArray(o)?o:o?[o]:[])}}}function Qp(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);Oe(e,0,0,n)}function Bo(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Ke(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Te=ft(/[A-Za-z]/),xe=ft(/[\dA-Za-z]/),Zp=ft(/[#-'*+\--9=?A-Z^-~]/);function Zr(e){return e!==null&&(e<32||e===127)}const fa=ft(/\d/),em=ft(/[\dA-Fa-f]/),tm=ft(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function ne(e){return e!==null&&(e<0||e===32)}function Y(e){return e===-2||e===-1||e===32}const en=ft(new RegExp("\\p{P}|\\p{S}","u")),kt=ft(/\s/);function ft(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Ht(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const i=e.charCodeAt(r);let s="";if(i===37&&xe(e.charCodeAt(r+1))&&xe(e.charCodeAt(r+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(s=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(s=String.fromCharCode(i,o),a=1):s="�"}else s=String.fromCharCode(i);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+a+1,s=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function Z(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return s;function s(l){return Y(l)?(e.enter(r),o(l)):t(l)}function o(l){return Y(l)&&i++<a?(e.consume(l),o):(e.exit(r),t(l))}}const rm={tokenize:nm};function nm(e){const t=e.attempt(this.parser.constructs.contentInitial,n,a);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),Z(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),i(o)}function i(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(o)}function s(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return q(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),s)}}const am={tokenize:im},zo={tokenize:sm};function im(e){const t=this,r=[];let n=0,a,i,s;return o;function o(_){if(n<r.length){const F=r[n];return t.containerState=F[1],e.attempt(F[0].continuation,l,u)(_)}return u(_)}function l(_){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&T();const F=t.events.length;let z=F,I;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){I=t.events[z][1].end;break}b(n);let U=F;for(;U<t.events.length;)t.events[U][1].end=m({},I),U++;return Oe(t.events,z+1,0,t.events.slice(F)),t.events.length=U,u(_)}return o(_)}function u(_){if(n===r.length){if(!a)return f(_);if(a.currentConstruct&&a.currentConstruct.concrete)return g(_);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(zo,d,c)(_)}function d(_){return a&&T(),b(n),f(_)}function c(_){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,g(_)}function f(_){return t.containerState={},e.attempt(zo,h,g)(_)}function h(_){return n++,r.push([t.currentConstruct,t.containerState]),f(_)}function g(_){if(_===null){a&&T(),b(0),e.consume(_);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),S(_)}function S(_){if(_===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(_);return}return q(_)?(e.consume(_),w(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(_),S)}function w(_,F){const z=t.sliceStream(_);if(F&&z.push(null),_.previous=i,i&&(i.next=_),i=_,a.defineSkip(_.start),a.write(z),t.parser.lazy[_.start.line]){let I=a.events.length;for(;I--;)if(a.events[I][1].start.offset<s&&(!a.events[I][1].end||a.events[I][1].end.offset>s))return;const U=t.events.length;let j=U,R,k;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){if(R){k=t.events[j][1].end;break}R=!0}for(b(n),I=U;I<t.events.length;)t.events[I][1].end=m({},k),I++;Oe(t.events,j+1,0,t.events.slice(U)),t.events.length=I}}function b(_){let F=r.length;for(;F-- >_;){const z=r[F];t.containerState=z[1],z[0].exit.call(t,e)}r.length=_}function T(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function sm(e,t,r){return Z(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function qt(e){if(e===null||ne(e)||kt(e))return 1;if(en(e))return 2}function tn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const pa={name:"attention",resolveAll:om,tokenize:lm};function om(e,t){let r=-1,n,a,i,s,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),f=m({},e[r][1].start);Ro(c,-l),Ro(f,l),s={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:f},i={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},a={type:l>1?"strong":"emphasis",start:m({},s.start),end:m({},o.end)},e[n][1].end=m({},s.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=je(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=je(u,[["enter",a,t],["enter",s,t],["exit",s,t],["enter",i,t]]),u=je(u,tn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=je(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=je(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,Oe(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function lm(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=qt(n);let i;return s;function s(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),d=qt(l),c=!d||d===2&&a||r.includes(l),f=!a||a===2&&d||r.includes(n);return u._open=!!(i===42?c:c&&(a||!f)),u._close=!!(i===42?f:f&&(d||!c)),t(l)}}function Ro(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const um={name:"autolink",tokenize:cm};function cm(e,t,r){let n=0;return a;function a(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(h){return Te(h)?(e.consume(h),s):h===64?r(h):u(h)}function s(h){return h===43||h===45||h===46||xe(h)?(n=1,o(h)):u(h)}function o(h){return h===58?(e.consume(h),n=0,l):(h===43||h===45||h===46||xe(h))&&n++<32?(e.consume(h),o):(n=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||Zr(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):Zp(h)?(e.consume(h),u):r(h)}function d(h){return xe(h)?c(h):r(h)}function c(h){return h===46?(e.consume(h),n=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):f(h)}function f(h){if((h===45||xe(h))&&n++<63){const g=h===45?f:c;return e.consume(h),g}return r(h)}}const pr={partial:!0,tokenize:dm};function dm(e,t,r){return n;function n(i){return Y(i)?Z(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||q(i)?t(i):r(i)}}const jo={continuation:{tokenize:fm},exit:pm,name:"blockQuote",tokenize:hm};function hm(e,t,r){const n=this;return a;function a(s){if(s===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(s),e.exit("blockQuoteMarker"),i}return r(s)}function i(s){return Y(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function fm(e,t,r){const n=this;return a;function a(s){return Y(s)?Z(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):i(s)}function i(s){return e.attempt(jo,t,r)(s)}}function pm(e){e.exit("blockQuote")}const Uo={name:"characterEscape",tokenize:mm};function mm(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return tm(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const $o={name:"characterReference",tokenize:gm};function gm(e,t,r){const n=this;let a=0,i,s;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,s=xe,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=em,d):(e.enter("characterReferenceValue"),i=7,s=fa,d(c))}function d(c){if(c===59&&a){const f=e.exit("characterReferenceValue");return s===xe&&!ha(n.sliceSerialize(f))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(c)&&a++<i?(e.consume(c),d):r(c)}}const Ho={partial:!0,tokenize:bm},qo={concrete:!0,name:"codeFenced",tokenize:ym};function ym(e,t,r){const n=this,a={partial:!0,tokenize:z};let i=0,s=0,o;return l;function l(I){return u(I)}function u(I){const U=n.events[n.events.length-1];return i=U&&U[1].type==="linePrefix"?U[2].sliceSerialize(U[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(I)}function d(I){return I===o?(s++,e.consume(I),d):s<3?r(I):(e.exit("codeFencedFenceSequence"),Y(I)?Z(e,c,"whitespace")(I):c(I))}function c(I){return I===null||q(I)?(e.exit("codeFencedFence"),n.interrupt?t(I):e.check(Ho,S,F)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(I))}function f(I){return I===null||q(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(I)):Y(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Z(e,h,"whitespace")(I)):I===96&&I===o?r(I):(e.consume(I),f)}function h(I){return I===null||q(I)?c(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(I))}function g(I){return I===null||q(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(I)):I===96&&I===o?r(I):(e.consume(I),g)}function S(I){return e.attempt(a,F,w)(I)}function w(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),b}function b(I){return i>0&&Y(I)?Z(e,T,"linePrefix",i+1)(I):T(I)}function T(I){return I===null||q(I)?e.check(Ho,S,F)(I):(e.enter("codeFlowValue"),_(I))}function _(I){return I===null||q(I)?(e.exit("codeFlowValue"),T(I)):(e.consume(I),_)}function F(I){return e.exit("codeFenced"),t(I)}function z(I,U,j){let R=0;return k;function k(O){return I.enter("lineEnding"),I.consume(O),I.exit("lineEnding"),D}function D(O){return I.enter("codeFencedFence"),Y(O)?Z(I,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):M(O)}function M(O){return O===o?(I.enter("codeFencedFenceSequence"),W(O)):j(O)}function W(O){return O===o?(R++,I.consume(O),W):R>=s?(I.exit("codeFencedFenceSequence"),Y(O)?Z(I,B,"whitespace")(O):B(O)):j(O)}function B(O){return O===null||q(O)?(I.exit("codeFencedFence"),U(O)):j(O)}}}function bm(e,t,r){const n=this;return a;function a(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const ma={name:"codeIndented",tokenize:xm},wm={partial:!0,tokenize:vm};function xm(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),Z(e,i,"linePrefix",5)(u)}function i(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(u):r(u)}function s(u){return u===null?l(u):q(u)?e.attempt(wm,s,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||q(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function vm(e,t,r){const n=this;return a;function a(s){return n.parser.lazy[n.now().line]?r(s):q(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):Z(e,i,"linePrefix",5)(s)}function i(s){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):q(s)?a(s):r(s)}}const Sm={name:"codeText",previous:_m,resolve:km,tokenize:Tm};function km(e){let t=e.length-4,r=3,n,a;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)a===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(a=n):(n===t||e[n][1].type==="lineEnding")&&(e[a][1].type="codeTextData",n!==a+2&&(e[a][1].end=e[n-1][1].end,e.splice(a+2,n-a-2),t-=n-a-2,n=a+2),a=void 0);return e}function _m(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Tm(e,t,r){let n=0,a,i;return s;function s(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(i=e.enter("codeTextSequence"),a=0,d(c)):q(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||q(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),a++,d):a===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(i.type="codeTextData",u(c))}}class Cm{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const a=r||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&mr(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),mr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),mr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);mr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);mr(this.left,r.reverse())}}}function mr(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function Vo(e){const t={};let r=-1,n,a,i,s,o,l,u;const d=new Cm(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Im(d,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,a=void 0;i--;)if(s=d.get(i),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),s[1].type="lineEnding",a=i);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;a&&(n[1].end=m({},d.get(a)[1].start),o=d.slice(a,r),o.unshift(n),d.splice(a,r-a+1,o))}}return Oe(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Im(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const i=[];let s=r._tokenizer;s||(s=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const o=s.events,l=[],u={};let d,c,f=-1,h=r,g=0,S=0;const w=[S];for(;h;){for(;e.get(++a)[1]!==h;);i.push(a),h._tokenizer||(d=n.sliceStream(h),h.next||d.push(null),c&&s.defineSkip(h.start),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(d),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),c=h,h=h.next}for(h=r;++f<o.length;)o[f][0]==="exit"&&o[f-1][0]==="enter"&&o[f][1].type===o[f-1][1].type&&o[f][1].start.line!==o[f][1].end.line&&(S=f+1,w.push(S),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(s.events=[],h?(h._tokenizer=void 0,h.previous=void 0):w.pop(),f=w.length;f--;){const b=o.slice(w[f],w[f+1]),T=i.pop();l.push([T,T+b.length-1]),e.splice(T,2,b)}for(l.reverse(),f=-1;++f<l.length;)u[g+l[f][0]]=g+l[f][1],g+=l[f][1]-l[f][0]-1;return u}const Em={resolve:Pm,tokenize:Mm},Am={partial:!0,tokenize:Nm};function Pm(e){return Vo(e),e}function Mm(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),a(o)}function a(o){return o===null?i(o):q(o)?e.check(Am,s,i)(o):(e.consume(o),a)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function s(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,a}}function Nm(e,t,r){const n=this;return a;function a(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Z(e,i,"linePrefix")}function i(s){if(s===null||q(s))return r(s);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):e.interrupt(n.parser.constructs.flow,r,t)(s)}}function Wo(e,t,r,n,a,i,s,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(b){return b===60?(e.enter(n),e.enter(a),e.enter(i),e.consume(b),e.exit(i),f):b===null||b===32||b===41||Zr(b)?r(b):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),S(b))}function f(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(o),f(b)):b===null||b===60||q(b)?r(b):(e.consume(b),b===92?g:h)}function g(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function S(b){return!d&&(b===null||b===41||ne(b))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(b)):d<u&&b===40?(e.consume(b),d++,S):b===41?(e.consume(b),d--,S):b===null||b===32||b===40||Zr(b)?r(b):(e.consume(b),b===92?w:S)}function w(b){return b===40||b===41||b===92?(e.consume(b),S):S(b)}}function Jo(e,t,r,n,a,i){const s=this;let o=0,l;return u;function u(h){return e.enter(n),e.enter(a),e.consume(h),e.exit(a),e.enter(i),d}function d(h){return o>999||h===null||h===91||h===93&&!l||h===94&&!o&&"_hiddenFootnoteSupport"in s.parser.constructs?r(h):h===93?(e.exit(i),e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):q(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===null||h===91||h===93||q(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!Y(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function Ko(e,t,r,n,a,i){let s;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(a),e.consume(f),e.exit(a),s=f===40?41:f,l):r(f)}function l(f){return f===s?(e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):(e.enter(i),u(f))}function u(f){return f===s?(e.exit(i),l(s)):f===null?r(f):q(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Z(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===s||f===null||q(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?c:d)}function c(f){return f===s||f===92?(e.consume(f),d):d(f)}}function gr(e,t){let r;return n;function n(a){return q(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):Y(a)?Z(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const Lm={name:"definition",tokenize:Om},Dm={partial:!0,tokenize:Fm};function Om(e,t,r){const n=this;let a;return i;function i(h){return e.enter("definition"),s(h)}function s(h){return Jo.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return a=Ke(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):r(h)}function l(h){return ne(h)?gr(e,u)(h):u(h)}function u(h){return Wo(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(Dm,c,c)(h)}function c(h){return Y(h)?Z(e,f,"whitespace")(h):f(h)}function f(h){return h===null||q(h)?(e.exit("definition"),n.parser.defined.push(a),t(h)):r(h)}}function Fm(e,t,r){return n;function n(o){return ne(o)?gr(e,a)(o):r(o)}function a(o){return Ko(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return Y(o)?Z(e,s,"whitespace")(o):s(o)}function s(o){return o===null||q(o)?t(o):r(o)}}const Bm={name:"hardBreakEscape",tokenize:zm};function zm(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return q(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const Rm={name:"headingAtx",resolve:jm,tokenize:Um};function jm(e,t){let r=e.length-2,n=3,a,i;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(a={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},Oe(e,n,r-n+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function Um(e,t,r){let n=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),s(d)}function s(d){return d===35&&n++<6?(e.consume(d),s):d===null||ne(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||q(d)?(e.exit("atxHeading"),t(d)):Y(d)?Z(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||ne(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const $m=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Go=["pre","script","style","textarea"],Hm={concrete:!0,name:"htmlFlow",resolveTo:Wm,tokenize:Jm},qm={partial:!0,tokenize:Gm},Vm={partial:!0,tokenize:Km};function Wm(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Jm(e,t,r){const n=this;let a,i,s,o,l;return u;function u(v){return d(v)}function d(v){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(v),c}function c(v){return v===33?(e.consume(v),f):v===47?(e.consume(v),i=!0,S):v===63?(e.consume(v),a=3,n.interrupt?t:x):Te(v)?(e.consume(v),s=String.fromCharCode(v),w):r(v)}function f(v){return v===45?(e.consume(v),a=2,h):v===91?(e.consume(v),a=5,o=0,g):Te(v)?(e.consume(v),a=4,n.interrupt?t:x):r(v)}function h(v){return v===45?(e.consume(v),n.interrupt?t:x):r(v)}function g(v){const me="CDATA[";return v===me.charCodeAt(o++)?(e.consume(v),o===me.length?n.interrupt?t:M:g):r(v)}function S(v){return Te(v)?(e.consume(v),s=String.fromCharCode(v),w):r(v)}function w(v){if(v===null||v===47||v===62||ne(v)){const me=v===47,tt=s.toLowerCase();return!me&&!i&&Go.includes(tt)?(a=1,n.interrupt?t(v):M(v)):$m.includes(s.toLowerCase())?(a=6,me?(e.consume(v),b):n.interrupt?t(v):M(v)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(v):i?T(v):_(v))}return v===45||xe(v)?(e.consume(v),s+=String.fromCharCode(v),w):r(v)}function b(v){return v===62?(e.consume(v),n.interrupt?t:M):r(v)}function T(v){return Y(v)?(e.consume(v),T):k(v)}function _(v){return v===47?(e.consume(v),k):v===58||v===95||Te(v)?(e.consume(v),F):Y(v)?(e.consume(v),_):k(v)}function F(v){return v===45||v===46||v===58||v===95||xe(v)?(e.consume(v),F):z(v)}function z(v){return v===61?(e.consume(v),I):Y(v)?(e.consume(v),z):_(v)}function I(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),l=v,U):Y(v)?(e.consume(v),I):j(v)}function U(v){return v===l?(e.consume(v),l=null,R):v===null||q(v)?r(v):(e.consume(v),U)}function j(v){return v===null||v===34||v===39||v===47||v===60||v===61||v===62||v===96||ne(v)?z(v):(e.consume(v),j)}function R(v){return v===47||v===62||Y(v)?_(v):r(v)}function k(v){return v===62?(e.consume(v),D):r(v)}function D(v){return v===null||q(v)?M(v):Y(v)?(e.consume(v),D):r(v)}function M(v){return v===45&&a===2?(e.consume(v),X):v===60&&a===1?(e.consume(v),ae):v===62&&a===4?(e.consume(v),ve):v===63&&a===3?(e.consume(v),x):v===93&&a===5?(e.consume(v),Ie):q(v)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(qm,Pe,W)(v)):v===null||q(v)?(e.exit("htmlFlowData"),W(v)):(e.consume(v),M)}function W(v){return e.check(Vm,B,Pe)(v)}function B(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),O}function O(v){return v===null||q(v)?W(v):(e.enter("htmlFlowData"),M(v))}function X(v){return v===45?(e.consume(v),x):M(v)}function ae(v){return v===47?(e.consume(v),s="",ye):M(v)}function ye(v){if(v===62){const me=s.toLowerCase();return Go.includes(me)?(e.consume(v),ve):M(v)}return Te(v)&&s.length<8?(e.consume(v),s+=String.fromCharCode(v),ye):M(v)}function Ie(v){return v===93?(e.consume(v),x):M(v)}function x(v){return v===62?(e.consume(v),ve):v===45&&a===2?(e.consume(v),x):M(v)}function ve(v){return v===null||q(v)?(e.exit("htmlFlowData"),Pe(v)):(e.consume(v),ve)}function Pe(v){return e.exit("htmlFlow"),t(v)}}function Km(e,t,r){const n=this;return a;function a(s){return q(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):r(s)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function Gm(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(pr,t,r)}}const Ym={name:"htmlText",tokenize:Xm};function Xm(e,t,r){const n=this;let a,i,s;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),z):x===63?(e.consume(x),_):Te(x)?(e.consume(x),j):r(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):Te(x)?(e.consume(x),T):r(x)}function d(x){return x===45?(e.consume(x),h):r(x)}function c(x){return x===null?r(x):x===45?(e.consume(x),f):q(x)?(s=c,ae(x)):(e.consume(x),c)}function f(x){return x===45?(e.consume(x),h):c(x)}function h(x){return x===62?X(x):x===45?f(x):c(x)}function g(x){const ve="CDATA[";return x===ve.charCodeAt(i++)?(e.consume(x),i===ve.length?S:g):r(x)}function S(x){return x===null?r(x):x===93?(e.consume(x),w):q(x)?(s=S,ae(x)):(e.consume(x),S)}function w(x){return x===93?(e.consume(x),b):S(x)}function b(x){return x===62?X(x):x===93?(e.consume(x),b):S(x)}function T(x){return x===null||x===62?X(x):q(x)?(s=T,ae(x)):(e.consume(x),T)}function _(x){return x===null?r(x):x===63?(e.consume(x),F):q(x)?(s=_,ae(x)):(e.consume(x),_)}function F(x){return x===62?X(x):_(x)}function z(x){return Te(x)?(e.consume(x),I):r(x)}function I(x){return x===45||xe(x)?(e.consume(x),I):U(x)}function U(x){return q(x)?(s=U,ae(x)):Y(x)?(e.consume(x),U):X(x)}function j(x){return x===45||xe(x)?(e.consume(x),j):x===47||x===62||ne(x)?R(x):r(x)}function R(x){return x===47?(e.consume(x),X):x===58||x===95||Te(x)?(e.consume(x),k):q(x)?(s=R,ae(x)):Y(x)?(e.consume(x),R):X(x)}function k(x){return x===45||x===46||x===58||x===95||xe(x)?(e.consume(x),k):D(x)}function D(x){return x===61?(e.consume(x),M):q(x)?(s=D,ae(x)):Y(x)?(e.consume(x),D):R(x)}function M(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(e.consume(x),a=x,W):q(x)?(s=M,ae(x)):Y(x)?(e.consume(x),M):(e.consume(x),B)}function W(x){return x===a?(e.consume(x),a=void 0,O):x===null?r(x):q(x)?(s=W,ae(x)):(e.consume(x),W)}function B(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||ne(x)?R(x):(e.consume(x),B)}function O(x){return x===47||x===62||ne(x)?R(x):r(x)}function X(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):r(x)}function ae(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),ye}function ye(x){return Y(x)?Z(e,Ie,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):Ie(x)}function Ie(x){return e.enter("htmlTextData"),s(x)}}const ga={name:"labelEnd",resolveAll:tg,resolveTo:rg,tokenize:ng},Qm={tokenize:ag},Zm={tokenize:ig},eg={tokenize:sg};function tg(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const a=n.type==="labelImage"?4:2;n.type="data",t+=a}}return e.length!==r.length&&Oe(e,0,e.length,r),e}function rg(e,t){let r=e.length,n=0,a,i,s,o;for(;r--;)if(a=e[r][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(s=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[s][1].end)},d={type:"labelText",start:m({},e[i+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=je(o,e.slice(i+1,i+n+3)),o=je(o,[["enter",d,t]]),o=je(o,tn(t.parser.constructs.insideSpan.null,e.slice(i+n+4,s-3),t)),o=je(o,[["exit",d,t],e[s-2],e[s-1],["exit",u,t]]),o=je(o,e.slice(s+1)),o=je(o,[["exit",l,t]]),Oe(e,i,e.length,o),e}function ng(e,t,r){const n=this;let a=n.events.length,i,s;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return o;function o(f){return i?i._inactive?c(f):(s=n.parser.defined.includes(Ke(n.sliceSerialize({start:i.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):r(f)}function l(f){return f===40?e.attempt(Qm,d,s?d:c)(f):f===91?e.attempt(Zm,d,s?u:c)(f):s?d(f):c(f)}function u(f){return e.attempt(eg,d,c)(f)}function d(f){return t(f)}function c(f){return i._balanced=!0,r(f)}}function ag(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),a}function a(c){return ne(c)?gr(e,i)(c):i(c)}function i(c){return c===41?d(c):Wo(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function s(c){return ne(c)?gr(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?Ko(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return ne(c)?gr(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function ig(e,t,r){const n=this;return a;function a(o){return Jo.call(n,e,i,s,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(Ke(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function sg(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const og={name:"labelStartImage",resolveAll:ga.resolveAll,tokenize:lg};function lg(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),s):r(o)}function s(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const ug={name:"labelStartLink",resolveAll:ga.resolveAll,tokenize:cg};function cg(e,t,r){const n=this;return a;function a(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),i}function i(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const ya={name:"lineEnding",tokenize:dg};function dg(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Z(e,t,"linePrefix")}}const rn={name:"thematicBreak",tokenize:hg};function hg(e,t,r){let n=0,a;return i;function i(u){return e.enter("thematicBreak"),s(u)}function s(u){return a=u,o(u)}function o(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||q(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===a?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),Y(u)?Z(e,o,"whitespace")(u):o(u))}}const Ae={continuation:{tokenize:gg},exit:bg,name:"list",tokenize:mg},fg={partial:!0,tokenize:wg},pg={partial:!0,tokenize:yg};function mg(e,t,r){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,s=0;return o;function o(h){const g=n.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||h===n.containerState.marker:fa(h)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(rn,r,u)(h):u(h);if(!n.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return r(h)}function l(h){return fa(h)&&++s<10?(e.consume(h),l):(!n.interrupt||s<2)&&(n.containerState.marker?h===n.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):r(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||h,e.check(pr,n.interrupt?r:d,e.attempt(fg,f,c))}function d(h){return n.containerState.initialBlankLine=!0,i++,f(h)}function c(h){return Y(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function gg(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(pr,a,i);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,Z(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!Y(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(pg,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,Z(e,e.attempt(Ae,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function yg(e,t,r){const n=this;return Z(e,a,"listItemIndent",n.containerState.size+1);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?t(i):r(i)}}function bg(e){e.exit(this.containerState.type)}function wg(e,t,r){const n=this;return Z(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const s=n.events[n.events.length-1];return!Y(i)&&s&&s[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const Yo={name:"setextUnderline",resolveTo:xg,tokenize:vg};function xg(e,t){let r=e.length,n,a,i;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(a=r)}else e[r][1].type==="content"&&e.splice(r,1),!i&&e[r][1].type==="definition"&&(i=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[i][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function vg(e,t,r){const n=this;let a;return i;function i(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),a=u,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),Y(u)?Z(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||q(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const Sg={tokenize:kg};function kg(e){const t=this,r=e.attempt(pr,n,e.attempt(this.parser.constructs.flowInitial,a,Z(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Em,a)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const _g={resolveAll:Qo()},Tg=Xo("string"),Cg=Xo("text");function Xo(e){return{resolveAll:Qo(e==="text"?Ig:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],i=r.attempt(a,s,o);return s;function s(d){return u(d)?i(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),i(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=a[d];let f=-1;if(c)for(;++f<c.length;){const h=c[f];if(!h.previous||h.previous.call(n,n.previous))return!0}return!1}}}function Qo(e){return t;function t(r,n){let a=-1,i;for(;++a<=r.length;)i===void 0?r[a]&&r[a][1].type==="data"&&(i=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==i+2&&(r[i][1].end=r[a-1][1].end,r.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(r,n):r}}function Ig(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],a=t.sliceStream(n);let i=a.length,s=-1,o=0,l;for(;i--;){const u=a[i];if(typeof u=="string"){for(s=u.length;u.charCodeAt(s-1)===32;)o++,s--;if(s)break;s=-1}else if(u===-2)l=!0,o++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?s:n.start._bufferIndex+s,_index:n.start._index+i,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const Eg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Lm},disable:{null:[]},document:{42:Ae,43:Ae,45:Ae,48:Ae,49:Ae,50:Ae,51:Ae,52:Ae,53:Ae,54:Ae,55:Ae,56:Ae,57:Ae,62:jo},flow:{35:Rm,42:rn,45:[Yo,rn],60:Hm,61:Yo,95:rn,96:qo,126:qo},flowInitial:{[-2]:ma,[-1]:ma,32:ma},insideSpan:{null:[pa,_g]},string:{38:$o,92:Uo},text:{[-5]:ya,[-4]:ya,[-3]:ya,33:og,38:$o,42:pa,60:[um,Ym],91:ug,92:[Bm,Uo],93:ga,95:pa,96:Sm}},Symbol.toStringTag,{value:"Module"}));function Ag(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const a={},i=[];let s=[],o=[];const l={attempt:U(z),check:U(I),consume:T,enter:_,exit:F,interrupt:U(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:S,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function c(D){return s=je(s,D),w(),s[s.length-1]!==null?[]:(j(t,0),u.events=tn(i,u.events,u),u.events)}function f(D,M){return Mg(h(D),M)}function h(D){return Pg(s,D)}function g(){const{_bufferIndex:D,_index:M,line:W,column:B,offset:O}=n;return{_bufferIndex:D,_index:M,line:W,column:B,offset:O}}function S(D){a[D.line]=D.column,k()}function w(){let D;for(;n._index<s.length;){const M=s[n._index];if(typeof M=="string")for(D=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===D&&n._bufferIndex<M.length;)b(M.charCodeAt(n._bufferIndex));else b(M)}}function b(D){d=d(D)}function T(D){q(D)?(n.line++,n.column=1,n.offset+=D===-3?2:1,k()):D!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=D}function _(D,M){const W=M||{};return W.type=D,W.start=g(),u.events.push(["enter",W,u]),o.push(W),W}function F(D){const M=o.pop();return M.end=g(),u.events.push(["exit",M,u]),M}function z(D,M){j(D,M.from)}function I(D,M){M.restore()}function U(D,M){return W;function W(B,O,X){let ae,ye,Ie,x;return Array.isArray(B)?Pe(B):"tokenize"in B?Pe([B]):ve(B);function ve(te){return Ct;function Ct(Me){const it=Me!==null&&te[Me],$e=Me!==null&&te.null,It=[...Array.isArray(it)?it:it?[it]:[],...Array.isArray($e)?$e:$e?[$e]:[]];return Pe(It)(Me)}}function Pe(te){return ae=te,ye=0,te.length===0?X:v(te[ye])}function v(te){return Ct;function Ct(Me){return x=R(),Ie=te,te.partial||(u.currentConstruct=te),te.name&&u.parser.constructs.disable.null.includes(te.name)?tt():te.tokenize.call(M?Object.assign(Object.create(u),M):u,l,me,tt)(Me)}}function me(te){return D(Ie,x),O}function tt(te){return x.restore(),++ye<ae.length?v(ae[ye]):X}}}function j(D,M){D.resolveAll&&!i.includes(D)&&i.push(D),D.resolve&&Oe(u.events,M,u.events.length-M,D.resolve(u.events.slice(M),u)),D.resolveTo&&(u.events=D.resolveTo(u.events,u))}function R(){const D=g(),M=u.previous,W=u.currentConstruct,B=u.events.length,O=Array.from(o);return{from:B,restore:X};function X(){n=D,u.previous=M,u.currentConstruct=W,u.events.length=B,o=O,k()}}function k(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function Pg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let s;if(r===a)s=[e[r].slice(n,i)];else{if(s=e.slice(r,a),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}i>0&&s.push(e[a].slice(0,i))}return s}function Mg(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const i=e[r];let s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`
9
+ `;break}case-3:{s=`\r
10
+ `;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&a)continue;s=" ";break}default:s=String.fromCharCode(i)}a=i===-2,n.push(s)}return n.join("")}function Ng(e){const n={constructs:Fo([Eg,...(e||{}).extensions||[]]),content:a(rm),defined:[],document:a(am),flow:a(Sg),lazy:{},string:a(Tg),text:a(Cg)};return n;function a(i){return s;function s(o){return Ag(n,i,o)}}}function Lg(e){for(;!Vo(e););return e}const Zo=/[\0\t\n\r]/g;function Dg(){let e=1,t="",r=!0,n;return a;function a(i,s,o){const l=[];let u,d,c,f,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(s||void 0).decode(i)),c=0,t="",r&&(i.charCodeAt(0)===65279&&c++,r=void 0);c<i.length;){if(Zo.lastIndex=c,u=Zo.exec(i),f=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(f),!u){t=i.slice(c);break}if(h===10&&c===f&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<f&&(l.push(i.slice(c,f)),e+=f-c),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=f+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Og=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Fg(e){return e.replace(Og,Bg)}function Bg(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),i=a===120||a===88;return Bo(r.slice(i?2:1),i?16:10)}return ha(r)||e}const el={}.hasOwnProperty;function zg(e,t,r){return typeof t!="string"&&(r=t,t=void 0),Rg(r)(Lg(Ng(r).document().write(Dg()(e,t,!0))))}function Rg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(gn),autolinkProtocol:R,autolinkEmail:R,atxHeading:i(He),blockQuote:i($e),characterEscape:R,characterReference:R,codeFenced:i(It),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:i(It,s),codeText:i(Ya,s),codeTextData:R,data:R,codeFlowValue:R,definition:i(mn),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:i(mt),hardBreakEscape:i(Tr),hardBreakTrailing:i(Tr),htmlFlow:i(Cr,s),htmlFlowData:R,htmlText:i(Cr,s),htmlTextData:R,image:i(Et),label:s,link:i(gn),listItem:i(Ir),listItemValue:f,listOrdered:i(At,c),listUnordered:i(At),paragraph:i(xu),reference:v,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:i(He),strong:i(J),thematicBreak:i(oe)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:it,autolinkProtocol:Me,blockQuote:l(),characterEscapeValue:k,characterReferenceMarkerHexadecimal:tt,characterReferenceMarkerNumeric:tt,characterReferenceValue:te,characterReference:Ct,codeFenced:l(w),codeFencedFence:S,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:k,codeIndented:l(b),codeText:l(O),codeTextData:k,data:k,definition:l(),definitionDestinationString:F,definitionLabelString:T,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(W),htmlFlowData:k,htmlText:l(B),htmlTextData:k,image:l(ae),label:Ie,labelText:ye,lineEnding:D,link:l(X),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:me,resourceDestinationString:x,resourceTitleString:ve,resource:Pe,setextHeading:l(j),setextHeadingLineSequence:U,setextHeadingText:I,strong:l(),thematicBreak:l()}};tl(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let L={type:"root",children:[]};const V={stack:[L],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:d,data:r},Q=[];let ie=-1;for(;++ie<A.length;)if(A[ie][1].type==="listOrdered"||A[ie][1].type==="listUnordered")if(A[ie][0]==="enter")Q.push(ie);else{const Ye=Q.pop();ie=a(A,Ye,ie)}for(ie=-1;++ie<A.length;){const Ye=t[A[ie][0]];el.call(Ye,A[ie][1].type)&&Ye[A[ie][1].type].call(Object.assign({sliceSerialize:A[ie][2].sliceSerialize},V),A[ie][1])}if(V.tokenStack.length>0){const Ye=V.tokenStack[V.tokenStack.length-1];(Ye[1]||rl).call(V,void 0,Ye[0])}for(L.position={start:pt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:pt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},ie=-1;++ie<t.transforms.length;)L=t.transforms[ie](L)||L;return L}function a(A,L,V){let Q=L-1,ie=-1,Ye=!1,Pt,st,Er,Ar;for(;++Q<=V;){const Fe=A[Q];switch(Fe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Fe[0]==="enter"?ie++:ie--,Ar=void 0;break}case"lineEndingBlank":{Fe[0]==="enter"&&(Pt&&!Ar&&!ie&&!Er&&(Er=Q),Ar=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ar=void 0}if(!ie&&Fe[0]==="enter"&&Fe[1].type==="listItemPrefix"||ie===-1&&Fe[0]==="exit"&&(Fe[1].type==="listUnordered"||Fe[1].type==="listOrdered")){if(Pt){let Jt=Q;for(st=void 0;Jt--;){const ot=A[Jt];if(ot[1].type==="lineEnding"||ot[1].type==="lineEndingBlank"){if(ot[0]==="exit")continue;st&&(A[st][1].type="lineEndingBlank",Ye=!0),ot[1].type="lineEnding",st=Jt}else if(!(ot[1].type==="linePrefix"||ot[1].type==="blockQuotePrefix"||ot[1].type==="blockQuotePrefixWhitespace"||ot[1].type==="blockQuoteMarker"||ot[1].type==="listItemIndent"))break}Er&&(!st||Er<st)&&(Pt._spread=!0),Pt.end=Object.assign({},st?A[st][1].start:Fe[1].end),A.splice(st||Q,0,["exit",Pt,Fe[2]]),Q++,V++}if(Fe[1].type==="listItemPrefix"){const Jt={type:"listItem",_spread:!1,start:Object.assign({},Fe[1].start),end:void 0};Pt=Jt,A.splice(Q,0,["enter",Jt,Fe[2]]),Q++,V++,Er=void 0,Ar=!0}}}return A[L][1]._spread=Ye,V}function i(A,L){return V;function V(Q){o.call(this,A(Q),Q),L&&L.call(this,Q)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,L,V){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([L,V||void 0]),A.position={start:pt(L.start),end:void 0}}function l(A){return L;function L(V){A&&A.call(this,V),u.call(this,V)}}function u(A,L){const V=this.stack.pop(),Q=this.tokenStack.pop();if(Q)Q[0].type!==A.type&&(L?L.call(this,A,Q[0]):(Q[1]||rl).call(this,A,Q[0]));else throw new Error("Cannot close `"+A.type+"` ("+hr({start:A.start,end:A.end})+"): it’s not open");V.position.end=pt(A.end)}function d(){return da(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const L=this.stack[this.stack.length-2];L.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),L=this.stack[this.stack.length-1];L.lang=A}function g(){const A=this.resume(),L=this.stack[this.stack.length-1];L.meta=A}function S(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const A=this.resume(),L=this.stack[this.stack.length-1];L.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const A=this.resume(),L=this.stack[this.stack.length-1];L.value=A.replace(/(\r?\n|\r)$/g,"")}function T(A){const L=this.resume(),V=this.stack[this.stack.length-1];V.label=L,V.identifier=Ke(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),L=this.stack[this.stack.length-1];L.title=A}function F(){const A=this.resume(),L=this.stack[this.stack.length-1];L.url=A}function z(A){const L=this.stack[this.stack.length-1];if(!L.depth){const V=this.sliceSerialize(A).length;L.depth=V}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function U(A){const L=this.stack[this.stack.length-1];L.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function j(){this.data.setextHeadingSlurpLineEnding=void 0}function R(A){const V=this.stack[this.stack.length-1].children;let Q=V[V.length-1];(!Q||Q.type!=="text")&&(Q=fe(),Q.position={start:pt(A.start),end:void 0},V.push(Q)),this.stack.push(Q)}function k(A){const L=this.stack.pop();L.value+=this.sliceSerialize(A),L.position.end=pt(A.end)}function D(A){const L=this.stack[this.stack.length-1];if(this.data.atHardBreak){const V=L.children[L.children.length-1];V.position.end=pt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(L.type)&&(R.call(this,A),k.call(this,A))}function M(){this.data.atHardBreak=!0}function W(){const A=this.resume(),L=this.stack[this.stack.length-1];L.value=A}function B(){const A=this.resume(),L=this.stack[this.stack.length-1];L.value=A}function O(){const A=this.resume(),L=this.stack[this.stack.length-1];L.value=A}function X(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=L,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ae(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=L,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ye(A){const L=this.sliceSerialize(A),V=this.stack[this.stack.length-2];V.label=Fg(L),V.identifier=Ke(L).toLowerCase()}function Ie(){const A=this.stack[this.stack.length-1],L=this.resume(),V=this.stack[this.stack.length-1];if(this.data.inReference=!0,V.type==="link"){const Q=A.children;V.children=Q}else V.alt=L}function x(){const A=this.resume(),L=this.stack[this.stack.length-1];L.url=A}function ve(){const A=this.resume(),L=this.stack[this.stack.length-1];L.title=A}function Pe(){this.data.inReference=void 0}function v(){this.data.referenceType="collapsed"}function me(A){const L=this.resume(),V=this.stack[this.stack.length-1];V.label=L,V.identifier=Ke(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function tt(A){this.data.characterReferenceType=A.type}function te(A){const L=this.sliceSerialize(A),V=this.data.characterReferenceType;let Q;V?(Q=Bo(L,V==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Q=ha(L);const ie=this.stack[this.stack.length-1];ie.value+=Q}function Ct(A){const L=this.stack.pop();L.position.end=pt(A.end)}function Me(A){k.call(this,A);const L=this.stack[this.stack.length-1];L.url=this.sliceSerialize(A)}function it(A){k.call(this,A);const L=this.stack[this.stack.length-1];L.url="mailto:"+this.sliceSerialize(A)}function $e(){return{type:"blockquote",children:[]}}function It(){return{type:"code",lang:null,meta:null,value:""}}function Ya(){return{type:"inlineCode",value:""}}function mn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function mt(){return{type:"emphasis",children:[]}}function He(){return{type:"heading",depth:0,children:[]}}function Tr(){return{type:"break"}}function Cr(){return{type:"html",value:""}}function Et(){return{type:"image",title:null,url:"",alt:null}}function gn(){return{type:"link",title:null,url:"",children:[]}}function At(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function Ir(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function xu(){return{type:"paragraph",children:[]}}function J(){return{type:"strong",children:[]}}function fe(){return{type:"text",value:""}}function oe(){return{type:"thematicBreak"}}}function pt(e){return{line:e.line,column:e.column,offset:e.offset}}function tl(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?tl(e,n):jg(e,n)}}function jg(e,t){let r;for(r in t)if(el.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function rl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+hr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+hr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+hr({start:t.start,end:t.end})+") is still open")}function Ug(e){const t=this;t.parser=r;function r(n){return zg(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function $g(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function Hg(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
+ `}]}function qg(e,t){const r=t.value?t.value+`
12
+ `:"",n={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(n.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function Vg(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Wg(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Jg(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=Ht(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),s=e.footnoteOrder.length):s=i+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+a,id:r+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function Kg(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Gg(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function nl(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const a=e.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const s=a[a.length-1];return s&&s.type==="text"?s.value+=n:a.push({type:"text",value:n}),a}function Yg(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return nl(e,t);const a={src:Ht(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function Xg(e,t){const r={src:Ht(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function Qg(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function Zg(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return nl(e,t);const a={href:Ht(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function ey(e,t){const r={href:Ht(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ty(e,t,r){const n=e.all(t),a=r?ry(r):al(t),i={},s=[];if(typeof t.checked=="boolean"){const d=n[0];let c;d&&d.type==="element"&&d.tagName==="p"?c=d:(c={type:"element",tagName:"p",properties:{},children:[]},n.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(a||o!==0||d.type!=="element"||d.tagName!=="p")&&s.push({type:"text",value:`
13
+ `}),d.type==="element"&&d.tagName==="p"&&!a?s.push(...d.children):s.push(d)}const l=n[n.length-1];l&&(a||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
14
+ `});const u={type:"element",tagName:"li",properties:i,children:s};return e.patch(t,u),e.applyData(t,u)}function ry(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=al(r[n])}return t}function al(e){const t=e.spread;return t==null?e.children.length>1:t}function ny(e,t){const r={},n=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++a<n.length;){const s=n[a];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function ay(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function iy(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function sy(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function oy(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],s),a.push(s)}if(r.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=ia(t.children[1]),l=_o(t.children[t.children.length-1]);o&&l&&(s.position={start:o,end:l}),a.push(s)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function ly(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,o=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],f={},h=s?s[l]:void 0;h&&(f.align=h);let g={type:"element",tagName:i,properties:f,children:[]};c&&(g.children=e.all(c),e.patch(c,g),g=e.applyData(c,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function uy(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const il=9,sl=32;function cy(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const i=[];for(;n;)i.push(ol(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return i.push(ol(t.slice(a),a>0,!1)),i.join("")}function ol(e,t,r){let n=0,a=e.length;if(t){let i=e.codePointAt(n);for(;i===il||i===sl;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(a-1);for(;i===il||i===sl;)a--,i=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function dy(e,t){const r={type:"text",value:cy(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function hy(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const fy={blockquote:$g,break:Hg,code:qg,delete:Vg,emphasis:Wg,footnoteReference:Jg,heading:Kg,html:Gg,imageReference:Yg,image:Xg,inlineCode:Qg,linkReference:Zg,link:ey,listItem:ty,list:ny,paragraph:ay,root:iy,strong:sy,table:oy,tableCell:uy,tableRow:ly,text:dy,thematicBreak:hy,toml:nn,yaml:nn,definition:nn,footnoteDefinition:nn};function nn(){}const ll=-1,an=0,yr=1,sn=2,ba=3,wa=4,xa=5,va=6,ul=7,cl=8,dl=typeof self=="object"?self:globalThis,py=(e,t)=>{const r=(a,i)=>(e.set(i,a),a),n=a=>{if(e.has(a))return e.get(a);const[i,s]=t[a];switch(i){case an:case ll:return r(s,a);case yr:{const o=r([],a);for(const l of s)o.push(n(l));return o}case sn:{const o=r({},a);for(const[l,u]of s)o[n(l)]=n(u);return o}case ba:return r(new Date(s),a);case wa:{const{source:o,flags:l}=s;return r(new RegExp(o,l),a)}case xa:{const o=r(new Map,a);for(const[l,u]of s)o.set(n(l),n(u));return o}case va:{const o=r(new Set,a);for(const l of s)o.add(n(l));return o}case ul:{const{name:o,message:l}=s;return r(new dl[o](l),a)}case cl:return r(BigInt(s),a);case"BigInt":return r(Object(BigInt(s)),a);case"ArrayBuffer":return r(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:o}=new Uint8Array(s);return r(new DataView(o),s)}}return r(new dl[i](s),a)};return n},hl=e=>py(new Map,e)(0),Vt="",{toString:my}={},{keys:gy}=Object,br=e=>{const t=typeof e;if(t!=="object"||!e)return[an,t];const r=my.call(e).slice(8,-1);switch(r){case"Array":return[yr,Vt];case"Object":return[sn,Vt];case"Date":return[ba,Vt];case"RegExp":return[wa,Vt];case"Map":return[xa,Vt];case"Set":return[va,Vt];case"DataView":return[yr,r]}return r.includes("Array")?[yr,r]:r.includes("Error")?[ul,r]:[sn,r]},on=([e,t])=>e===an&&(t==="function"||t==="symbol"),yy=(e,t,r,n)=>{const a=(s,o)=>{const l=n.push(s)-1;return r.set(o,l),l},i=s=>{if(r.has(s))return r.get(s);let[o,l]=br(s);switch(o){case an:{let d=s;switch(l){case"bigint":o=cl,d=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return a([ll],s)}return a([o,d],s)}case yr:{if(l){let f=s;return l==="DataView"?f=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(s)),a([l,[...f]],s)}const d=[],c=a([o,d],s);for(const f of s)d.push(i(f));return c}case sn:{if(l)switch(l){case"BigInt":return a([l,s.toString()],s);case"Boolean":case"Number":case"String":return a([l,s.valueOf()],s)}if(t&&"toJSON"in s)return i(s.toJSON());const d=[],c=a([o,d],s);for(const f of gy(s))(e||!on(br(s[f])))&&d.push([i(f),i(s[f])]);return c}case ba:return a([o,s.toISOString()],s);case wa:{const{source:d,flags:c}=s;return a([o,{source:d,flags:c}],s)}case xa:{const d=[],c=a([o,d],s);for(const[f,h]of s)(e||!(on(br(f))||on(br(h))))&&d.push([i(f),i(h)]);return c}case va:{const d=[],c=a([o,d],s);for(const f of s)(e||!on(br(f)))&&d.push(i(f));return c}}const{message:u}=s;return a([o,{name:l,message:u}],s)};return i},fl=(e,{json:t,lossy:r}={})=>{const n=[];return yy(!(t||r),!!t,new Map,n)(e),n},ln=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?hl(fl(e,t)):structuredClone(e):(e,t)=>hl(fl(e,t));function by(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function wy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function xy(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||by,n=e.options.footnoteBackLabel||wy,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",s=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const d=e.all(u),c=String(u.identifier).toUpperCase(),f=Ht(c.toLowerCase());let h=0;const g=[],S=e.footnoteCounts.get(c);for(;S!==void 0&&++h<=S;){g.length>0&&g.push({type:"text",value:" "});let T=typeof r=="string"?r:r(l,h);typeof T=="string"&&(T={type:"text",value:T}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,h),className:["data-footnote-backref"]},children:Array.isArray(T)?T:[T]})}const w=d[d.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const T=w.children[w.children.length-1];T&&T.type==="text"?T.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else d.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(d,!0)};e.patch(u,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:E(m({},ln(s)),{id:"footnote-label"}),children:[{type:"text",value:a}]},{type:"text",value:`
15
15
  `},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
16
- `}]}}const Xr=(function(e){if(e==null)return Qg;if(typeof e=="function")return Qr(e);if(typeof e=="object")return Array.isArray(e)?Yg(e):Kg(e);if(typeof e=="string")return Xg(e);throw new Error("Expected function, string, or object as test")});function Yg(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=Xr(e[r]);return Qr(n);function n(...i){let s=-1;for(;++s<t.length;)if(t[s].apply(this,i))return!0;return!1}}function Kg(e){const t=e;return Qr(r);function r(n){const i=n;let s;for(s in e)if(i[s]!==t[s])return!1;return!0}}function Xg(e){return Qr(t);function t(r){return r&&r.type===e}}function Qr(e){return t;function t(r,n,i){return!!(Zg(r)&&e.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function Qg(){return!0}function Zg(e){return e!==null&&typeof e=="object"&&"type"in e}function iv(e){return e}const Yo=[],ey=!0,di=!1,ty="skip";function Ko(e,t,r,n){let i;typeof t=="function"&&typeof r!="function"?(n=r,r=t):i=t;const s=Xr(i),a=n?-1:1;o(e,void 0,[])();function o(l,u,d){const c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){const h=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(l.type+(h?"<"+h+">":""))+")"})}return f;function f(){let h=Yo,g,S,w;if((!t||s(l,u,d[d.length-1]||void 0))&&(h=ry(r(l,d)),h[0]===di))return h;if("children"in l&&l.children){const b=l;if(b.children&&h[0]!==ty)for(S=(n?b.children.length:-1)+a,w=d.concat(b);S>-1&&S<b.children.length;){const C=b.children[S];if(g=o(C,S,w)(),g[0]===di)return g;S=typeof g[1]=="number"?g[1]:S+a}}return h}}}function ry(e){return Array.isArray(e)?e:typeof e=="number"?[ey,e]:e==null?Yo:[e]}function hi(e,t,r,n){let i,s,a;typeof t=="function"&&typeof r!="function"?(s=void 0,a=t,i=r):(s=t,a=r,i=n),Ko(e,s,o,i);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return a(l,c,d)}}const fi={}.hasOwnProperty,ny={};function iy(e,t){const r=t||ny,n=new Map,i=new Map,s=new Map,a=m(m({},Ug),r.handlers),o={all:u,applyData:ay,definitionById:n,footnoteById:i,footnoteCounts:s,footnoteOrder:[],handlers:a,one:l,options:r,patch:sy,wrap:ly};return hi(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const c=d.type==="definition"?n:i,f=String(d.identifier).toUpperCase();c.has(f)||c.set(f,d)}}),o;function l(d,c){const f=d.type,h=o.handlers[f];if(fi.call(o.handlers,f)&&h)return h(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(f)){if("children"in d){const S=d,{children:w}=S,b=H(S,["children"]),C=Kr(b);return C.children=o.all(d),C}return Kr(d)}return(o.options.unknownHandler||oy)(o,d,c)}function u(d){const c=[];if("children"in d){const f=d.children;let h=-1;for(;++h<f.length;){const g=o.one(f[h],d);if(g){if(h&&f[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Xo(g.value)),!Array.isArray(g)&&g.type==="element")){const S=g.children[0];S&&S.type==="text"&&(S.value=Xo(S.value))}Array.isArray(g)?c.push(...g):c.push(g)}}}return c}}function sy(e,t){e.position&&(t.position=rp(e))}function ay(e,t){let r=t;if(e&&e.data){const n=e.data.hName,i=e.data.hChildren,s=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const a="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:a}}r.type==="element"&&s&&Object.assign(r.properties,Kr(s)),"children"in r&&r.children&&i!==null&&i!==void 0&&(r.children=i)}return r}function oy(e,t){const r=t.data||{},n="value"in t&&!(fi.call(r,"hProperties")||fi.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ly(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
16
+ `}]}}const un=(function(e){if(e==null)return _y;if(typeof e=="function")return cn(e);if(typeof e=="object")return Array.isArray(e)?vy(e):Sy(e);if(typeof e=="string")return ky(e);throw new Error("Expected function, string, or object as test")});function vy(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=un(e[r]);return cn(n);function n(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function Sy(e){const t=e;return cn(r);function r(n){const a=n;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function ky(e){return cn(t);function t(r){return r&&r.type===e}}function cn(e){return t;function t(r,n,a){return!!(Ty(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function _y(){return!0}function Ty(e){return e!==null&&typeof e=="object"&&"type"in e}function Tv(e){return e}const pl=[],Cy=!0,Sa=!1,Iy="skip";function ml(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const i=un(a),s=n?-1:1;o(e,void 0,[])();function o(l,u,d){const c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){const h=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(l.type+(h?"<"+h+">":""))+")"})}return f;function f(){let h=pl,g,S,w;if((!t||i(l,u,d[d.length-1]||void 0))&&(h=Ey(r(l,d)),h[0]===Sa))return h;if("children"in l&&l.children){const b=l;if(b.children&&h[0]!==Iy)for(S=(n?b.children.length:-1)+s,w=d.concat(b);S>-1&&S<b.children.length;){const T=b.children[S];if(g=o(T,S,w)(),g[0]===Sa)return g;S=typeof g[1]=="number"?g[1]:S+s}}return h}}}function Ey(e){return Array.isArray(e)?e:typeof e=="number"?[Cy,e]:e==null?pl:[e]}function ka(e,t,r,n){let a,i,s;typeof t=="function"&&typeof r!="function"?(i=void 0,s=t,a=r):(i=t,s=r,a=n),ml(e,i,o,a);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return s(l,c,d)}}const _a={}.hasOwnProperty,Ay={};function Py(e,t){const r=t||Ay,n=new Map,a=new Map,i=new Map,s=m(m({},fy),r.handlers),o={all:u,applyData:Ny,definitionById:n,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:s,one:l,options:r,patch:My,wrap:Dy};return ka(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const c=d.type==="definition"?n:a,f=String(d.identifier).toUpperCase();c.has(f)||c.set(f,d)}}),o;function l(d,c){const f=d.type,h=o.handlers[f];if(_a.call(o.handlers,f)&&h)return h(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(f)){if("children"in d){const S=d,{children:w}=S,b=H(S,["children"]),T=ln(b);return T.children=o.all(d),T}return ln(d)}return(o.options.unknownHandler||Ly)(o,d,c)}function u(d){const c=[];if("children"in d){const f=d.children;let h=-1;for(;++h<f.length;){const g=o.one(f[h],d);if(g){if(h&&f[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=gl(g.value)),!Array.isArray(g)&&g.type==="element")){const S=g.children[0];S&&S.type==="text"&&(S.value=gl(S.value))}Array.isArray(g)?c.push(...g):c.push(g)}}}return c}}function My(e,t){e.position&&(t.position=Ep(e))}function Ny(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&i&&Object.assign(r.properties,ln(i)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function Ly(e,t){const r=t.data||{},n="value"in t&&!(_a.call(r,"hProperties")||_a.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Dy(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
17
17
  `});++n<e.length;)n&&r.push({type:"text",value:`
18
18
  `}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`
19
- `}),r}function Xo(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function Qo(e,t){const r=iy(e,t),n=r.one(e,void 0),i=Gg(r),s=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return i&&s.children.push({type:"text",value:`
20
- `},i),s}function uy(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const i=Qo(r,m({file:n},t));yield e.run(i,n)})}:function(r,n){return Qo(r,m({file:n},e||t))}}function Zo(e){if(e)throw e}var pi,el;function cy(){if(el)return pi;el=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var f;for(f in u);return typeof f=="undefined"||e.call(u,f)},a=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return pi=function l(){var u,d,c,f,h,g,S=arguments[0],w=1,b=arguments.length,C=!1;for(typeof S=="boolean"&&(C=S,S=arguments[1]||{},w=2),(S==null||typeof S!="object"&&typeof S!="function")&&(S={});w<b;++w)if(u=arguments[w],u!=null)for(d in u)c=o(S,d),f=o(u,d),S!==f&&(C&&f&&(s(f)||(h=i(f)))?(h?(h=!1,g=c&&i(c)?c:[]):g=c&&s(c)?c:{},a(S,{name:d,newValue:l(C,g,f)})):typeof f!="undefined"&&a(S,{name:d,newValue:f}));return S},pi}var dy=cy();const mi=xr(dy);function gi(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function hy(){const e=[],t={run:r,use:n};return t;function r(...i){let s=-1;const a=i.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...i);function o(l,...u){const d=e[++s];let c=-1;if(l){a(l);return}for(;++c<i.length;)(u[c]===null||u[c]===void 0)&&(u[c]=i[c]);i=u,d?fy(d,o)(...u):a(null,...u)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function fy(e,t){let r;return n;function n(...a){const o=e.length>a.length;let l;o&&a.push(i);try{l=e.apply(this,a)}catch(u){const d=u;if(o&&r)throw d;return i(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(s,i):l instanceof Error?i(l):s(l))}function i(a,...o){r||(r=!0,t(a,...o))}function s(a){i(null,a)}}const Ke={basename:py,dirname:my,extname:gy,join:yy,sep:"/"};function py(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');dr(e);let r=0,n=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){r=i+1;break}}else n<0&&(s=!0,n=i+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let a=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){r=i+1;break}}else a<0&&(s=!0,a=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(n=i):(o=-1,n=a));return r===n?n=a:n<0&&(n=e.length),e.slice(r,n)}function my(e){if(dr(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function gy(e){dr(e);let t=e.length,r=-1,n=0,i=-1,s=0,a;for(;t--;){const o=e.codePointAt(t);if(o===47){if(a){n=t+1;break}continue}r<0&&(a=!0,r=t+1),o===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||r<0||s===0||s===1&&i===r-1&&i===n+1?"":e.slice(i,r)}function yy(...e){let t=-1,r;for(;++t<e.length;)dr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":by(r)}function by(e){dr(e);const t=e.codePointAt(0)===47;let r=wy(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function wy(e,t){let r="",n=0,i=-1,s=0,a=-1,o,l;for(;++a<=e.length;){if(a<e.length)o=e.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(i===a-1||s===1))if(i!==a-1&&s===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),i=a,s=0;continue}}else if(r.length>0){r="",n=0,i=a,s=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(i+1,a):r=e.slice(i+1,a),n=a-i-1;i=a,s=0}else o===46&&s>-1?s++:s=-1}return r}function dr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const xy={cwd:vy};function vy(){return"/"}function yi(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Sy(e){if(typeof e=="string")e=new URL(e);else if(!yi(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return ky(e)}function ky(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const bi=["history","path","basename","stem","extname","dirname"];class tl{constructor(t){let r;t?yi(t)?r={path:t}:typeof t=="string"||_y(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":xy.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<bi.length;){const s=bi[n];s in r&&r[s]!==void 0&&r[s]!==null&&(this[s]=s==="history"?[...r[s]]:r[s])}let i;for(i in r)bi.includes(i)||(this[i]=r[i])}get basename(){return typeof this.path=="string"?Ke.basename(this.path):void 0}set basename(t){xi(t,"basename"),wi(t,"basename"),this.path=Ke.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Ke.dirname(this.path):void 0}set dirname(t){rl(this.basename,"dirname"),this.path=Ke.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Ke.extname(this.path):void 0}set extname(t){if(wi(t,"extname"),rl(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ke.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){yi(t)&&(t=Sy(t)),xi(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Ke.basename(this.path,this.extname):void 0}set stem(t){xi(t,"stem"),wi(t,"stem"),this.path=Ke.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const i=this.message(t,r,n);throw i.fatal=!0,i}info(t,r,n){const i=this.message(t,r,n);return i.fatal=void 0,i}message(t,r,n){const i=new we(t,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function wi(e,t){if(e&&e.includes(Ke.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Ke.sep+"`")}function xi(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function rl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function _y(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Ty=(function(e){const n=this.constructor.prototype,i=n[e],s=function(){return i.apply(s,arguments)};return Object.setPrototypeOf(s,n),s}),Cy={}.hasOwnProperty;class vi extends Ty{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=hy()}copy(){const t=new vi;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(mi(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(_i("data",this.frozen),this.namespace[t]=r,this):Cy.call(this.namespace,t)&&this.namespace[t]||void 0:t?(_i("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const i=r.call(t,...n);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=Zr(t),n=this.parser||this.Parser;return Si("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Si("process",this.parser||this.Parser),ki("process",this.compiler||this.Compiler),r?i(void 0,r):new Promise(i);function i(s,a){const o=Zr(t),l=n.parse(o);n.run(l,o,function(d,c,f){if(d||!c||!f)return u(d);const h=c,g=n.stringify(h,f);Ay(g)?f.value=g:f.result=g,u(d,f)});function u(d,c){d||!c?a(d):s?s(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),Si("processSync",this.parser||this.Parser),ki("processSync",this.compiler||this.Compiler),this.process(t,i),il("processSync","process",r),n;function i(s,a){r=!0,Zo(s),n=a}}run(t,r,n){nl(t),this.freeze();const i=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?s(void 0,n):new Promise(s);function s(a,o){const l=Zr(r);i.run(t,l,u);function u(d,c,f){const h=c||t;d?o(d):a?a(h):n(void 0,h,f)}}}runSync(t,r){let n=!1,i;return this.run(t,r,s),il("runSync","run",n),i;function s(a,o){Zo(a),i=o,n=!0}}stringify(t,r){this.freeze();const n=Zr(r),i=this.compiler||this.Compiler;return ki("stringify",i),nl(t),i(t,n)}use(t,...r){const n=this.attachers,i=this.namespace;if(_i("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(i.settings=mi(!0,i.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];s(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,f=-1;for(;++c<n.length;)if(n[c][0]===u){f=c;break}if(f===-1)n.push([u,...d]);else if(d.length>0){let[h,...g]=d;const S=n[f][1];gi(S)&&gi(h)&&(h=mi(!0,S,h)),n[f]=[u,h,...g]}}}}const Iy=new vi().freeze();function Si(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ki(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function _i(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function nl(e){if(!gi(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function il(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Zr(e){return Ey(e)?e:new tl(e)}function Ey(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Ay(e){return typeof e=="string"||Py(e)}function Py(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const My="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",sl=[],al={allowDangerousHtml:!0},Ly=/^(https?|ircs?|mailto|xmpp)$/i,Ny=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Dy(e){const t=Oy(e),r=Fy(e);return By(t.runSync(t.parse(r),r),e)}function Oy(e){const t=e.rehypePlugins||sl,r=e.remarkPlugins||sl,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),al):al;return Iy().use(mg).use(r).use(uy,n).use(t)}function Fy(e){const t=e.children||"",r=new tl;return typeof t=="string"&&(r.value=t),r}function By(e,t){const r=t.allowedElements,n=t.allowElement,i=t.components,s=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||zy;for(const d of Ny)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+My+d.id,void 0);return hi(e,u),op(e,{Fragment:p.Fragment,components:i,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,f){if(d.type==="raw"&&f&&typeof c=="number")return a?f.children.splice(c,1):f.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let h;for(h in Zn)if(Object.hasOwn(Zn,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],S=Zn[h];(S===null||S.includes(d.tagName))&&(d.properties[h]=l(String(g||""),h,d))}}if(d.type==="element"){let h=r?!r.includes(d.tagName):s?s.includes(d.tagName):!1;if(!h&&n&&typeof c=="number"&&(h=!n(d,c,f)),h&&f&&typeof c=="number")return o&&d.children?f.children.splice(c,1,...d.children):f.children.splice(c,1),c}}}function zy(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||r!==-1&&t>r||n!==-1&&t>n||Ly.test(e.slice(0,t))?e:""}var Ry=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),jy=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:i,data:s}=o;return H(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&Ry(e.children,t.children)},Ti=(e,t)=>jy(e.node,t.node),Uy=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,i=o=>{var l=o,{node:s}=l,a=H(l,["node"]);return p.jsx(n,m({},a))};return[t,y.memo(i,Ti)]})),Ci=y.createContext(null),ol=()=>y.useContext(Ci)!==null,$y=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return p.jsx(Ci.Provider,{value:t,children:e})},Hy=y.memo($y,Ti),qy=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("pre",m({},t))},Vy=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("code",m({},t))},Ii=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Wy=()=>null,Jy=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:i},language:s,code:a})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=s?n:Ii;return p.jsxs(p.Fragment,{children:[p.jsx(i,{node:e,language:s,code:a}),p.jsx(l,{node:e,components:o,language:s!=null?s:"unknown",code:a})]})},Ei={exports:{}};var ll;function Gy(){return ll||(ll=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=i(s,n(o)))}return s}function n(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return r.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)t.call(s,o)&&s[o]&&(a=i(a,o));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Ei)),Ei.exports}var Yy=Gy();const ul=xr(Yy);var cl=r=>{var n=r,{className:e}=n,t=H(n,["className"]);return a=>{var o=a,{className:i}=o,s=H(o,["className"]);return m(m({className:ul(e,i)},t),s)}},Ky=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:i},componentsByLanguage:s={},children:a}=u,o=H(u,["node","components","componentsByLanguage","children"]);var C,_,F,B,I,z;const d=y.useContext(Ci),c=cl(d),f=ft(j=>p.jsx(t,m({},c(j)))),h=cl(o),g=ft(j=>p.jsx(r,m({},h(j)))),S=(_=(C=/language-(\w+)/.exec(o.className||""))==null?void 0:C[1])!=null?_:"";if(typeof a!="string")return p.jsx(Ii,{node:e,components:{Pre:f,Code:g},code:a});const w=(B=(F=s[S])==null?void 0:F.SyntaxHighlighter)!=null?B:n,b=(z=(I=s[S])==null?void 0:I.CodeHeader)!=null?z:i;return p.jsx(Jy,{node:e,components:{Pre:f,Code:g,SyntaxHighlighter:w,CodeHeader:b},language:S||"unknown",code:a})},Xy=i=>{var s=i,{node:e,components:t,componentsByLanguage:r}=s,n=H(s,["node","components","componentsByLanguage"]);return ol()?p.jsx(Ky,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Qy=y.memo(Xy,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Ti(e,t)),{useSmooth:Zy,useSmoothStatus:eb,withSmoothContextProvider:tb}=wh,rb=s=>{var a=s,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=a,i=H(a,["components","componentsByLanguage","smooth","preprocess"]);const o=ca(),l=y.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Zy(l,r),{pre:d=qy,code:c=Vy,SyntaxHighlighter:f=Ii,CodeHeader:h=Wy}=e!=null?e:{},g=y.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:f,CodeHeader:h}),[d,c,f,h]),S=ft(b=>p.jsx(Qy,m({components:g,componentsByLanguage:t},b))),w=y.useMemo(()=>{const I=e!=null?e:{},{pre:b,code:C,SyntaxHighlighter:_,CodeHeader:F}=I,B=H(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},B),{pre:Hy,code:S})},[S,e]);return p.jsx(Dy,E(m({components:w},i),{children:u}))},dl=y.forwardRef((s,i)=>{var a=s,{className:e,containerProps:t,containerComponent:r="div"}=a,n=H(a,["className","containerProps","containerComponent"]);const o=eb();return p.jsx(r,E(m({"data-status":o.type},t),{className:ul(e,t==null?void 0:t.className),ref:i,children:p.jsx(rb,m({},n))}))});dl.displayName="MarkdownTextPrimitive";var nb=tb(dl);function hl(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(t);for(;i!==-1;)n++,i=r.indexOf(t,i+t.length);return n}function ib(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sb(e,t,r){const i=Xr((r||{}).ignore||[]),s=ab(t);let a=-1;for(;++a<s.length;)Ko(e,"text",o);function o(u,d){let c=-1,f;for(;++c<d.length;){const h=d[c],g=f?f.children:void 0;if(i(h,g?g.indexOf(h):void 0,f))return;f=h}if(f)return l(u,d)}function l(u,d){const c=d[d.length-1],f=s[a][0],h=s[a][1];let g=0;const w=c.children.indexOf(u);let b=!1,C=[];f.lastIndex=0;let _=f.exec(u.value);for(;_;){const F=_.index,B={index:_.index,input:_.input,stack:[...d,u]};let I=h(..._,B);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?f.lastIndex=F+1:(g!==F&&C.push({type:"text",value:u.value.slice(g,F)}),Array.isArray(I)?C.push(...I):I&&C.push(I),g=F+_[0].length,b=!0),!f.global)break;_=f.exec(u.value)}return b?(g<u.value.length&&C.push({type:"text",value:u.value.slice(g)}),c.children.splice(w,1,...C)):C=[u],w+C.length}}function ab(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const i=r[n];t.push([ob(i[0]),lb(i[1])])}return t}function ob(e){return typeof e=="string"?new RegExp(ib(e),"g"):e}function lb(e){return typeof e=="function"?e:function(){return e}}const Ai="phrasing",Pi=["autolink","link","image","label"];function ub(){return{transforms:[gb],enter:{literalAutolink:db,literalAutolinkEmail:Mi,literalAutolinkHttp:Mi,literalAutolinkWww:Mi},exit:{literalAutolink:mb,literalAutolinkEmail:pb,literalAutolinkHttp:hb,literalAutolinkWww:fb}}}function cb(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ai,notInConstruct:Pi},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ai,notInConstruct:Pi},{character:":",before:"[ps]",after:"\\/",inConstruct:Ai,notInConstruct:Pi}]}}function db(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Mi(e){this.config.enter.autolinkProtocol.call(this,e)}function hb(e){this.config.exit.autolinkProtocol.call(this,e)}function fb(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function pb(e){this.config.exit.autolinkEmail.call(this,e)}function mb(e){this.exit(e)}function gb(e){sb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,yb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),bb]],{ignore:["link","linkReference"]})}function yb(e,t,r,n,i){let s="";if(!fl(i)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!wb(r)))return!1;const a=xb(r+n);if(!a[0])return!1;const o={type:"link",title:null,url:s+t+a[0],children:[{type:"text",value:t+a[0]}]};return a[1]?[o,{type:"text",value:a[1]}]:o}function bb(e,t,r,n){return!fl(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function wb(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function xb(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const i=hl(e,"(");let s=hl(e,")");for(;n!==-1&&i>s;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),s++;return[e,r]}function fl(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||mt(r)||Hr(r))&&(!t||r!==47)}pl.peek=Ab;function vb(){this.buffer()}function Sb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function kb(){this.buffer()}function _b(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Tb(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ve(this.sliceSerialize(e)).toLowerCase(),r.label=t}function Cb(e){this.exit(e)}function Ib(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ve(this.sliceSerialize(e)).toLowerCase(),r.label=t}function Eb(e){this.exit(e)}function Ab(){return"["}function pl(e,t,r,n){const i=r.createTracker(n);let s=i.move("[^");const a=r.enter("footnoteReference"),o=r.enter("reference");return s+=i.move(r.safe(r.associationId(e),{after:"]",before:s})),o(),a(),s+=i.move("]"),s}function Pb(){return{enter:{gfmFootnoteCallString:vb,gfmFootnoteCall:Sb,gfmFootnoteDefinitionLabelString:kb,gfmFootnoteDefinition:_b},exit:{gfmFootnoteCallString:Tb,gfmFootnoteCall:Cb,gfmFootnoteDefinitionLabelString:Ib,gfmFootnoteDefinition:Eb}}}function Mb(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:pl},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,i,s,a){const o=s.createTracker(a);let l=o.move("[^");const u=s.enter("footnoteDefinition"),d=s.enter("label");return l+=o.move(s.safe(s.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
- `:" ")+s.indentLines(s.containerFlow(n,o.current()),t?ml:Lb))),u(),l}}function Lb(e,t,r){return t===0?e:ml(e,t,r)}function ml(e,t,r){return(r?"":" ")+e}const Nb=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];gl.peek=zb;function Db(){return{canContainEols:["delete"],enter:{strikethrough:Fb},exit:{strikethrough:Bb}}}function Ob(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Nb}],handlers:{delete:gl}}}function Fb(e){this.enter({type:"delete",children:[]},e)}function Bb(e){this.exit(e)}function gl(e,t,r,n){const i=r.createTracker(n),s=r.enter("strikethrough");let a=i.move("~~");return a+=r.containerPhrasing(e,E(m({},i.current()),{before:a,after:"~"})),a+=i.move("~~"),s(),a}function zb(){return"~"}function Rb(e){return e.length}function jb(e,t){const r=t||{},n=(r.align||[]).concat(),i=r.stringLength||Rb,s=[],a=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const S=[],w=[];let b=-1;for(e[d].length>u&&(u=e[d].length);++b<e[d].length;){const C=Ub(e[d][b]);if(r.alignDelimiters!==!1){const _=i(C);w[b]=_,(l[b]===void 0||_>l[b])&&(l[b]=_)}S.push(C)}a[d]=S,o[d]=w}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)s[c]=yl(n[c]);else{const S=yl(n);for(;++c<u;)s[c]=S}c=-1;const f=[],h=[];for(;++c<u;){const S=s[c];let w="",b="";S===99?(w=":",b=":"):S===108?w=":":S===114&&(b=":");let C=r.alignDelimiters===!1?1:Math.max(1,l[c]-w.length-b.length);const _=w+"-".repeat(C)+b;r.alignDelimiters!==!1&&(C=w.length+C+b.length,C>l[c]&&(l[c]=C),h[c]=C),f[c]=_}a.splice(1,0,f),o.splice(1,0,h),d=-1;const g=[];for(;++d<a.length;){const S=a[d],w=o[d];c=-1;const b=[];for(;++c<u;){const C=S[c]||"";let _="",F="";if(r.alignDelimiters!==!1){const B=l[c]-(w[c]||0),I=s[c];I===114?_=" ".repeat(B):I===99?B%2?(_=" ".repeat(B/2+.5),F=" ".repeat(B/2-.5)):(_=" ".repeat(B/2),F=_):F=" ".repeat(B)}r.delimiterStart!==!1&&!c&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&C==="")&&(r.delimiterStart!==!1||c)&&b.push(" "),r.alignDelimiters!==!1&&b.push(_),b.push(C),r.alignDelimiters!==!1&&b.push(F),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&b.push("|")}g.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
22
- `)}function Ub(e){return e==null?"":String(e)}function yl(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function $b(e,t,r,n){const i=r.enter("blockquote"),s=r.createTracker(n);s.move("> "),s.shift(2);const a=r.indentLines(r.containerFlow(e,s.current()),Hb);return i(),a}function Hb(e,t,r){return">"+(r?"":" ")+e}function qb(e,t){return bl(e,t.inConstruct,!0)&&!bl(e,t.notInConstruct,!1)}function bl(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function wl(e,t,r,n){let i=-1;for(;++i<r.unsafe.length;)if(r.unsafe[i].character===`
23
- `&&qb(r.stack,r.unsafe[i]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
- `}function Vb(e,t){const r=String(e);let n=r.indexOf(t),i=n,s=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===i?++s>a&&(a=s):s=1,i=n+t.length,n=r.indexOf(t,i);return a}function Wb(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Jb(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function Gb(e,t,r,n){const i=Jb(r),s=e.value||"",a=i==="`"?"GraveAccent":"Tilde";if(Wb(e,r)){const c=r.enter("codeIndented"),f=r.indentLines(s,Yb);return c(),f}const o=r.createTracker(n),l=i.repeat(Math.max(Vb(s,i)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${a}`);d+=o.move(r.safe(e.lang,m({before:d,after:" ",encode:["`"]},o.current()))),c()}if(e.lang&&e.meta){const c=r.enter(`codeFencedMeta${a}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
19
+ `}),r}function gl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function yl(e,t){const r=Py(e,t),n=r.one(e,void 0),a=xy(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&i.children.push({type:"text",value:`
20
+ `},a),i}function Oy(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const a=yl(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return yl(r,m({file:n},e||t))}}function bl(e){if(e)throw e}var Ta,wl;function Fy(){if(wl)return Ta;wl=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var f;for(f in u);return typeof f=="undefined"||e.call(u,f)},s=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return Ta=function l(){var u,d,c,f,h,g,S=arguments[0],w=1,b=arguments.length,T=!1;for(typeof S=="boolean"&&(T=S,S=arguments[1]||{},w=2),(S==null||typeof S!="object"&&typeof S!="function")&&(S={});w<b;++w)if(u=arguments[w],u!=null)for(d in u)c=o(S,d),f=o(u,d),S!==f&&(T&&f&&(i(f)||(h=a(f)))?(h?(h=!1,g=c&&a(c)?c:[]):g=c&&i(c)?c:{},s(S,{name:d,newValue:l(T,g,f)})):typeof f!="undefined"&&s(S,{name:d,newValue:f}));return S},Ta}var By=Fy();const Ca=Mr(By);function Ia(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function zy(){const e=[],t={run:r,use:n};return t;function r(...a){let i=-1;const s=a.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...a);function o(l,...u){const d=e[++i];let c=-1;if(l){s(l);return}for(;++c<a.length;)(u[c]===null||u[c]===void 0)&&(u[c]=a[c]);a=u,d?Ry(d,o)(...u):s(null,...u)}}function n(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function Ry(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(a);try{l=e.apply(this,s)}catch(u){const d=u;if(o&&r)throw d;return a(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,a):l instanceof Error?a(l):i(l))}function a(s,...o){r||(r=!0,t(s,...o))}function i(s){a(null,s)}}const Ze={basename:jy,dirname:Uy,extname:$y,join:Hy,sep:"/"};function jy(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');wr(e);let r=0,n=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else n<0&&(i=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else s<0&&(i=!0,s=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function Uy(e){if(wr(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function $y(e){wr(e);let t=e.length,r=-1,n=0,a=-1,i=0,s;for(;t--;){const o=e.codePointAt(t);if(o===47){if(s){n=t+1;break}continue}r<0&&(s=!0,r=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||r<0||i===0||i===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function Hy(...e){let t=-1,r;for(;++t<e.length;)wr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":qy(r)}function qy(e){wr(e);const t=e.codePointAt(0)===47;let r=Vy(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function Vy(e,t){let r="",n=0,a=-1,i=0,s=-1,o,l;for(;++s<=e.length;){if(s<e.length)o=e.codePointAt(s);else{if(o===47)break;o=47}if(o===47){if(!(a===s-1||i===1))if(a!==s-1&&i===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),a=s,i=0;continue}}else if(r.length>0){r="",n=0,a=s,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,s):r=e.slice(a+1,s),n=s-a-1;a=s,i=0}else o===46&&i>-1?i++:i=-1}return r}function wr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Wy={cwd:Jy};function Jy(){return"/"}function Ea(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Ky(e){if(typeof e=="string")e=new URL(e);else if(!Ea(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Gy(e)}function Gy(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Aa=["history","path","basename","stem","extname","dirname"];class xl{constructor(t){let r;t?Ea(t)?r={path:t}:typeof t=="string"||Yy(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":Wy.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<Aa.length;){const i=Aa[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let a;for(a in r)Aa.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?Ze.basename(this.path):void 0}set basename(t){Ma(t,"basename"),Pa(t,"basename"),this.path=Ze.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Ze.dirname(this.path):void 0}set dirname(t){vl(this.basename,"dirname"),this.path=Ze.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Ze.extname(this.path):void 0}set extname(t){if(Pa(t,"extname"),vl(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ze.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Ea(t)&&(t=Ky(t)),Ma(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Ze.basename(this.path,this.extname):void 0}set stem(t){Ma(t,"stem"),Pa(t,"stem"),this.path=Ze.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const a=this.message(t,r,n);throw a.fatal=!0,a}info(t,r,n){const a=this.message(t,r,n);return a.fatal=void 0,a}message(t,r,n){const a=new we(t,r,n);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Pa(e,t){if(e&&e.includes(Ze.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Ze.sep+"`")}function Ma(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function vl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function Yy(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Xy=(function(e){const n=this.constructor.prototype,a=n[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,n),i}),Qy={}.hasOwnProperty;class Na extends Xy{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=zy()}copy(){const t=new Na;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Ca(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Oa("data",this.frozen),this.namespace[t]=r,this):Qy.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Oa("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const a=r.call(t,...n);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=dn(t),n=this.parser||this.Parser;return La("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),La("process",this.parser||this.Parser),Da("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(i,s){const o=dn(t),l=n.parse(o);n.run(l,o,function(d,c,f){if(d||!c||!f)return u(d);const h=c,g=n.stringify(h,f);tb(g)?f.value=g:f.result=g,u(d,f)});function u(d,c){d||!c?s(d):i?i(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),La("processSync",this.parser||this.Parser),Da("processSync",this.compiler||this.Compiler),this.process(t,a),kl("processSync","process",r),n;function a(i,s){r=!0,bl(i),n=s}}run(t,r,n){Sl(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(s,o){const l=dn(r);a.run(t,l,u);function u(d,c,f){const h=c||t;d?o(d):s?s(h):n(void 0,h,f)}}}runSync(t,r){let n=!1,a;return this.run(t,r,i),kl("runSync","run",n),a;function i(s,o){bl(s),a=o,n=!0}}stringify(t,r){this.freeze();const n=dn(r),a=this.compiler||this.Compiler;return Da("stringify",a),Sl(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(Oa("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):s(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else s(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function s(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(a.settings=Ca(!0,a.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];i(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,f=-1;for(;++c<n.length;)if(n[c][0]===u){f=c;break}if(f===-1)n.push([u,...d]);else if(d.length>0){let[h,...g]=d;const S=n[f][1];Ia(S)&&Ia(h)&&(h=Ca(!0,S,h)),n[f]=[u,h,...g]}}}}const Zy=new Na().freeze();function La(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Da(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Oa(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Sl(e){if(!Ia(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function kl(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function dn(e){return eb(e)?e:new xl(e)}function eb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function tb(e){return typeof e=="string"||rb(e)}function rb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const nb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",_l=[],Tl={allowDangerousHtml:!0},ab=/^(https?|ircs?|mailto|xmpp)$/i,ib=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function sb(e){const t=ob(e),r=lb(e);return ub(t.runSync(t.parse(r),r),e)}function ob(e){const t=e.rehypePlugins||_l,r=e.remarkPlugins||_l,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Tl):Tl;return Zy().use(Ug).use(r).use(Oy,n).use(t)}function lb(e){const t=e.children||"",r=new xl;return typeof t=="string"&&(r.value=t),r}function ub(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,i=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||cb;for(const d of ib)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+nb+d.id,void 0);return ka(e,u),Lp(e,{Fragment:p.Fragment,components:a,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,f){if(d.type==="raw"&&f&&typeof c=="number")return s?f.children.splice(c,1):f.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let h;for(h in ca)if(Object.hasOwn(ca,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],S=ca[h];(S===null||S.includes(d.tagName))&&(d.properties[h]=l(String(g||""),h,d))}}if(d.type==="element"){let h=r?!r.includes(d.tagName):i?i.includes(d.tagName):!1;if(!h&&n&&typeof c=="number"&&(h=!n(d,c,f)),h&&f&&typeof c=="number")return o&&d.children?f.children.splice(c,1,...d.children):f.children.splice(c,1),c}}}function cb(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||r!==-1&&t>r||n!==-1&&t>n||ab.test(e.slice(0,t))?e:""}var db=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),hb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:i}=o;return H(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&db(e.children,t.children)},Fa=(e,t)=>hb(e.node,t.node),fb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,a=o=>{var l=o,{node:i}=l,s=H(l,["node"]);return p.jsx(n,m({},s))};return[t,y.memo(a,Fa)]})),Ba=y.createContext(null),Cl=()=>y.useContext(Ba)!==null,pb=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return p.jsx(Ba.Provider,{value:t,children:e})},mb=y.memo(pb,Fa),gb=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("pre",m({},t))},yb=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("code",m({},t))},za=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),bb=()=>null,wb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:i,code:s})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=i?n:za;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:i,code:s}),p.jsx(l,{node:e,components:o,language:i!=null?i:"unknown",code:s})]})},Ra={exports:{}};var Il;function xb(){return Il||(Il=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var i="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(i=a(i,n(o)))}return i}function n(i){if(typeof i=="string"||typeof i=="number")return i;if(typeof i!="object")return"";if(Array.isArray(i))return r.apply(null,i);if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]"))return i.toString();var s="";for(var o in i)t.call(i,o)&&i[o]&&(s=a(s,o));return s}function a(i,s){return s?i?i+" "+s:i+s:i}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Ra)),Ra.exports}var vb=xb();const El=Mr(vb);var Al=r=>{var n=r,{className:e}=n,t=H(n,["className"]);return s=>{var o=s,{className:a}=o,i=H(o,["className"]);return m(m({className:El(e,a)},t),i)}},Sb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:i={},children:s}=u,o=H(u,["node","components","componentsByLanguage","children"]);var T,_,F,z,I,U;const d=y.useContext(Ba),c=Al(d),f=vt(j=>p.jsx(t,m({},c(j)))),h=Al(o),g=vt(j=>p.jsx(r,m({},h(j)))),S=(_=(T=/language-(\w+)/.exec(o.className||""))==null?void 0:T[1])!=null?_:"";if(typeof s!="string")return p.jsx(za,{node:e,components:{Pre:f,Code:g},code:s});const w=(z=(F=i[S])==null?void 0:F.SyntaxHighlighter)!=null?z:n,b=(U=(I=i[S])==null?void 0:I.CodeHeader)!=null?U:a;return p.jsx(wb,{node:e,components:{Pre:f,Code:g,SyntaxHighlighter:w,CodeHeader:b},language:S||"unknown",code:s})},kb=a=>{var i=a,{node:e,components:t,componentsByLanguage:r}=i,n=H(i,["node","components","componentsByLanguage"]);return Cl()?p.jsx(Sb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},_b=y.memo(kb,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Fa(e,t)),{useSmooth:Tb,useSmoothStatus:Cb,withSmoothContextProvider:Ib}=Bh,Eb=i=>{var s=i,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,a=H(s,["components","componentsByLanguage","smooth","preprocess"]);const o=_s(),l=y.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Tb(l,r),{pre:d=gb,code:c=yb,SyntaxHighlighter:f=za,CodeHeader:h=bb}=e!=null?e:{},g=y.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:f,CodeHeader:h}),[d,c,f,h]),S=vt(b=>p.jsx(_b,m({components:g,componentsByLanguage:t},b))),w=y.useMemo(()=>{const I=e!=null?e:{},{pre:b,code:T,SyntaxHighlighter:_,CodeHeader:F}=I,z=H(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},z),{pre:mb,code:S})},[S,e]);return p.jsx(sb,E(m({components:w},a),{children:u}))},Pl=y.forwardRef((i,a)=>{var s=i,{className:e,containerProps:t,containerComponent:r="div"}=s,n=H(s,["className","containerProps","containerComponent"]);const o=Cb();return p.jsx(r,E(m({"data-status":o.type},t),{className:El(e,t==null?void 0:t.className),ref:a,children:p.jsx(Eb,m({},n))}))});Pl.displayName="MarkdownTextPrimitive";var Ab=Ib(Pl);function Ml(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,a=r.indexOf(t);for(;a!==-1;)n++,a=r.indexOf(t,a+t.length);return n}function Pb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Mb(e,t,r){const a=un((r||{}).ignore||[]),i=Nb(t);let s=-1;for(;++s<i.length;)ml(e,"text",o);function o(u,d){let c=-1,f;for(;++c<d.length;){const h=d[c],g=f?f.children:void 0;if(a(h,g?g.indexOf(h):void 0,f))return;f=h}if(f)return l(u,d)}function l(u,d){const c=d[d.length-1],f=i[s][0],h=i[s][1];let g=0;const w=c.children.indexOf(u);let b=!1,T=[];f.lastIndex=0;let _=f.exec(u.value);for(;_;){const F=_.index,z={index:_.index,input:_.input,stack:[...d,u]};let I=h(..._,z);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?f.lastIndex=F+1:(g!==F&&T.push({type:"text",value:u.value.slice(g,F)}),Array.isArray(I)?T.push(...I):I&&T.push(I),g=F+_[0].length,b=!0),!f.global)break;_=f.exec(u.value)}return b?(g<u.value.length&&T.push({type:"text",value:u.value.slice(g)}),c.children.splice(w,1,...T)):T=[u],w+T.length}}function Nb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const a=r[n];t.push([Lb(a[0]),Db(a[1])])}return t}function Lb(e){return typeof e=="string"?new RegExp(Pb(e),"g"):e}function Db(e){return typeof e=="function"?e:function(){return e}}const ja="phrasing",Ua=["autolink","link","image","label"];function Ob(){return{transforms:[$b],enter:{literalAutolink:Bb,literalAutolinkEmail:$a,literalAutolinkHttp:$a,literalAutolinkWww:$a},exit:{literalAutolink:Ub,literalAutolinkEmail:jb,literalAutolinkHttp:zb,literalAutolinkWww:Rb}}}function Fb(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:ja,notInConstruct:Ua},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:ja,notInConstruct:Ua},{character:":",before:"[ps]",after:"\\/",inConstruct:ja,notInConstruct:Ua}]}}function Bb(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function $a(e){this.config.enter.autolinkProtocol.call(this,e)}function zb(e){this.config.exit.autolinkProtocol.call(this,e)}function Rb(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function jb(e){this.config.exit.autolinkEmail.call(this,e)}function Ub(e){this.exit(e)}function $b(e){Mb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Hb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),qb]],{ignore:["link","linkReference"]})}function Hb(e,t,r,n,a){let i="";if(!Nl(a)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!Vb(r)))return!1;const s=Wb(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:i+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function qb(e,t,r,n){return!Nl(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function Vb(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Wb(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const a=Ml(e,"(");let i=Ml(e,")");for(;n!==-1&&a>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function Nl(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||kt(r)||en(r))&&(!t||r!==47)}Ll.peek=tw;function Jb(){this.buffer()}function Kb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Gb(){this.buffer()}function Yb(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Xb(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function Qb(e){this.exit(e)}function Zb(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function ew(e){this.exit(e)}function tw(){return"["}function Ll(e,t,r,n){const a=r.createTracker(n);let i=a.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return i+=a.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),s(),i+=a.move("]"),i}function rw(){return{enter:{gfmFootnoteCallString:Jb,gfmFootnoteCall:Kb,gfmFootnoteDefinitionLabelString:Gb,gfmFootnoteDefinition:Yb},exit:{gfmFootnoteCallString:Xb,gfmFootnoteCall:Qb,gfmFootnoteDefinitionLabelString:Zb,gfmFootnoteDefinition:ew}}}function nw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Ll},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,i,s){const o=i.createTracker(s);let l=o.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
+ `:" ")+i.indentLines(i.containerFlow(n,o.current()),t?Dl:aw))),u(),l}}function aw(e,t,r){return t===0?e:Dl(e,t,r)}function Dl(e,t,r){return(r?"":" ")+e}const iw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ol.peek=cw;function sw(){return{canContainEols:["delete"],enter:{strikethrough:lw},exit:{strikethrough:uw}}}function ow(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:iw}],handlers:{delete:Ol}}}function lw(e){this.enter({type:"delete",children:[]},e)}function uw(e){this.exit(e)}function Ol(e,t,r,n){const a=r.createTracker(n),i=r.enter("strikethrough");let s=a.move("~~");return s+=r.containerPhrasing(e,E(m({},a.current()),{before:s,after:"~"})),s+=a.move("~~"),i(),s}function cw(){return"~"}function dw(e){return e.length}function hw(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||dw,i=[],s=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const S=[],w=[];let b=-1;for(e[d].length>u&&(u=e[d].length);++b<e[d].length;){const T=fw(e[d][b]);if(r.alignDelimiters!==!1){const _=a(T);w[b]=_,(l[b]===void 0||_>l[b])&&(l[b]=_)}S.push(T)}s[d]=S,o[d]=w}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)i[c]=Fl(n[c]);else{const S=Fl(n);for(;++c<u;)i[c]=S}c=-1;const f=[],h=[];for(;++c<u;){const S=i[c];let w="",b="";S===99?(w=":",b=":"):S===108?w=":":S===114&&(b=":");let T=r.alignDelimiters===!1?1:Math.max(1,l[c]-w.length-b.length);const _=w+"-".repeat(T)+b;r.alignDelimiters!==!1&&(T=w.length+T+b.length,T>l[c]&&(l[c]=T),h[c]=T),f[c]=_}s.splice(1,0,f),o.splice(1,0,h),d=-1;const g=[];for(;++d<s.length;){const S=s[d],w=o[d];c=-1;const b=[];for(;++c<u;){const T=S[c]||"";let _="",F="";if(r.alignDelimiters!==!1){const z=l[c]-(w[c]||0),I=i[c];I===114?_=" ".repeat(z):I===99?z%2?(_=" ".repeat(z/2+.5),F=" ".repeat(z/2-.5)):(_=" ".repeat(z/2),F=_):F=" ".repeat(z)}r.delimiterStart!==!1&&!c&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&T==="")&&(r.delimiterStart!==!1||c)&&b.push(" "),r.alignDelimiters!==!1&&b.push(_),b.push(T),r.alignDelimiters!==!1&&b.push(F),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&b.push("|")}g.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
22
+ `)}function fw(e){return e==null?"":String(e)}function Fl(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function pw(e,t,r,n){const a=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const s=r.indentLines(r.containerFlow(e,i.current()),mw);return a(),s}function mw(e,t,r){return">"+(r?"":" ")+e}function gw(e,t){return Bl(e,t.inConstruct,!0)&&!Bl(e,t.notInConstruct,!1)}function Bl(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function zl(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
23
+ `&&gw(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
+ `}function yw(e,t){const r=String(e);let n=r.indexOf(t),a=n,i=0,s=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++i>s&&(s=i):i=1,a=n+t.length,n=r.indexOf(t,a);return s}function bw(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function ww(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function xw(e,t,r,n){const a=ww(r),i=e.value||"",s=a==="`"?"GraveAccent":"Tilde";if(bw(e,r)){const c=r.enter("codeIndented"),f=r.indentLines(i,vw);return c(),f}const o=r.createTracker(n),l=a.repeat(Math.max(yw(i,a)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${s}`);d+=o.move(r.safe(e.lang,m({before:d,after:" ",encode:["`"]},o.current()))),c()}if(e.lang&&e.meta){const c=r.enter(`codeFencedMeta${s}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
25
25
  `,encode:["`"]},o.current()))),c()}return d+=o.move(`
26
- `),s&&(d+=o.move(s+`
27
- `)),d+=o.move(l),u(),d}function Yb(e,t,r){return(r?"":" ")+e}function Li(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function Kb(e,t,r,n){const i=Li(r),s=i==='"'?"Quote":"Apostrophe",a=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("[");return u+=l.move(r.safe(r.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":`
28
- `},l.current())))),o(),e.title&&(o=r.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(r.safe(e.title,m({before:u,after:i},l.current()))),u+=l.move(i),o()),a(),u}function Xb(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function hr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function en(e,t,r){const n=Ot(e),i=Ot(t);return n===void 0?i===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}xl.peek=Qb;function xl(e,t,r,n){const i=Xb(r),s=r.enter("emphasis"),a=r.createTracker(n),o=a.move(i);let l=a.move(r.containerPhrasing(e,m({after:i,before:o},a.current())));const u=l.charCodeAt(0),d=en(n.before.charCodeAt(n.before.length-1),u,i);d.inside&&(l=hr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=en(n.after.charCodeAt(0),c,i);f.inside&&(l=l.slice(0,-1)+hr(c));const h=a.move(i);return s(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function Qb(e,t,r){return r.options.emphasis||"*"}function Zb(e,t){let r=!1;return hi(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,di}),!!((!e.depth||e.depth<3)&&ei(e)&&(t.options.setext||r))}function ew(e,t,r,n){const i=Math.max(Math.min(6,e.depth||1),1),s=r.createTracker(n);if(Zb(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),f=r.containerPhrasing(e,E(m({},s.current()),{before:`
26
+ `),i&&(d+=o.move(i+`
27
+ `)),d+=o.move(l),u(),d}function vw(e,t,r){return(r?"":" ")+e}function Ha(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function Sw(e,t,r,n){const a=Ha(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("[");return u+=l.move(r.safe(r.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":`
28
+ `},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),s(),u}function kw(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function xr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function hn(e,t,r){const n=qt(e),a=qt(t);return n===void 0?a===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Rl.peek=_w;function Rl(e,t,r,n){const a=kw(r),i=r.enter("emphasis"),s=r.createTracker(n),o=s.move(a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=hn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=xr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=hn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+xr(c));const h=s.move(a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function _w(e,t,r){return r.options.emphasis||"*"}function Tw(e,t){let r=!1;return ka(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Sa}),!!((!e.depth||e.depth<3)&&da(e)&&(t.options.setext||r))}function Cw(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(Tw(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),f=r.containerPhrasing(e,E(m({},i.current()),{before:`
29
29
  `,after:`
30
30
  `}));return c(),d(),f+`
31
- `+(i===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
32
- `))+1))}const a="#".repeat(i),o=r.enter("headingAtx"),l=r.enter("phrasing");s.move(a+" ");let u=r.containerPhrasing(e,m({before:"# ",after:`
33
- `},s.current()));return/^[\t ]/.test(u)&&(u=hr(u.charCodeAt(0))+u.slice(1)),u=u?a+" "+u:a,r.options.closeAtx&&(u+=" "+a),l(),o(),u}vl.peek=tw;function vl(e){return e.value||""}function tw(){return"<"}Sl.peek=rw;function Sl(e,t,r,n){const i=Li(r),s=i==='"'?"Quote":"Apostrophe",a=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("![");return u+=l.move(r.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=r.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(r.safe(e.title,m({before:u,after:i},l.current()))),u+=l.move(i),o()),u+=l.move(")"),a(),u}function rw(){return"!"}kl.peek=nw;function kl(e,t,r,n){const i=e.referenceType,s=r.enter("imageReference");let a=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const u=r.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const d=r.stack;r.stack=[],a=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return a(),r.stack=d,s(),i==="full"||!u||u!==c?l+=o.move(c+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function nw(){return"!"}_l.peek=iw;function _l(e,t,r){let n=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(n);)i+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++s<r.unsafe.length;){const a=r.unsafe[s],o=r.compilePattern(a);let l;if(a.atBreak)for(;l=o.exec(n);){let u=l.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(l.index+1)}}return i+n+i}function iw(){return"`"}function Tl(e,t){const r=ei(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Cl.peek=sw;function Cl(e,t,r,n){const i=Li(r),s=i==='"'?"Quote":"Apostrophe",a=r.createTracker(n);let o,l;if(Tl(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=a.move("<");return c+=a.move(r.containerPhrasing(e,m({before:c,after:">"},a.current()))),c+=a.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=a.move("[");return u+=a.move(r.containerPhrasing(e,m({before:u,after:"]("},a.current()))),u+=a.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=a.move("<"),u+=a.move(r.safe(e.url,m({before:u,after:">"},a.current()))),u+=a.move(">")):(l=r.enter("destinationRaw"),u+=a.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},a.current())))),l(),e.title&&(l=r.enter(`title${s}`),u+=a.move(" "+i),u+=a.move(r.safe(e.title,m({before:u,after:i},a.current()))),u+=a.move(i),l()),u+=a.move(")"),o(),u}function sw(e,t,r){return Tl(e,r)?"<":"["}Il.peek=aw;function Il(e,t,r,n){const i=e.referenceType,s=r.enter("linkReference");let a=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const u=r.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const d=r.stack;r.stack=[],a=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return a(),r.stack=d,s(),i==="full"||!u||u!==c?l+=o.move(c+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function aw(){return"["}function Ni(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function ow(e){const t=Ni(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function lw(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function El(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function uw(e,t,r,n){const i=r.enter("list"),s=r.bulletCurrent;let a=e.ordered?lw(r):Ni(r);const o=e.ordered?a==="."?")":".":ow(r);let l=t&&r.bulletLastUsed?a===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),El(r)===a&&d){let c=-1;for(;++c<e.children.length;){const f=e.children[c];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(a=o),r.bulletCurrent=a;const u=r.containerFlow(e,n);return r.bulletLastUsed=a,r.bulletCurrent=s,i(),u}function cw(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function dw(e,t,r,n){const i=cw(r);let s=r.bulletCurrent||Ni(r);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let a=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(a=Math.ceil(a/4)*4);const o=r.createTracker(n);o.move(s+" ".repeat(a-s.length)),o.shift(a);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),d);return l(),u;function d(c,f,h){return f?(h?"":" ".repeat(a))+c:(h?s:s+" ".repeat(a-s.length))+c}}function hw(e,t,r,n){const i=r.enter("paragraph"),s=r.enter("phrasing"),a=r.containerPhrasing(e,n);return s(),i(),a}const fw=Xr(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function pw(e,t,r,n){return(e.children.some(function(a){return fw(a)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function mw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}Al.peek=gw;function Al(e,t,r,n){const i=mw(r),s=r.enter("strong"),a=r.createTracker(n),o=a.move(i+i);let l=a.move(r.containerPhrasing(e,m({after:i,before:o},a.current())));const u=l.charCodeAt(0),d=en(n.before.charCodeAt(n.before.length-1),u,i);d.inside&&(l=hr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=en(n.after.charCodeAt(0),c,i);f.inside&&(l=l.slice(0,-1)+hr(c));const h=a.move(i+i);return s(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function gw(e,t,r){return r.options.strong||"*"}function yw(e,t,r,n){return r.safe(e.value,n)}function bw(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function ww(e,t,r){const n=(El(r)+(r.options.ruleSpaces?" ":"")).repeat(bw(r));return r.options.ruleSpaces?n.slice(0,-1):n}const Pl={blockquote:$b,break:wl,code:Gb,definition:Kb,emphasis:xl,hardBreak:wl,heading:ew,html:vl,image:Sl,imageReference:kl,inlineCode:_l,link:Cl,linkReference:Il,list:uw,listItem:dw,paragraph:hw,root:pw,strong:Al,text:yw,thematicBreak:ww};function xw(){return{enter:{table:vw,tableData:Ml,tableHeader:Ml,tableRow:kw},exit:{codeText:_w,table:Sw,tableData:Di,tableHeader:Di,tableRow:Di}}}function vw(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function Sw(e){this.exit(e),this.data.inTable=void 0}function kw(e){this.enter({type:"tableRow",children:[]},e)}function Di(e){this.exit(e)}function Ml(e){this.enter({type:"tableCell",children:[]},e)}function _w(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Tw));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function Tw(e,t){return t==="|"?t:e}function Cw(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,i=t.stringLength,s=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
34
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:a,tableCell:l,tableRow:o}};function a(h,g,S,w){return u(d(h,S,w),h.align)}function o(h,g,S,w){const b=c(h,S,w),C=u([b]);return C.slice(0,C.indexOf(`
35
- `))}function l(h,g,S,w){const b=S.enter("tableCell"),C=S.enter("phrasing"),_=S.containerPhrasing(h,E(m({},w),{before:s,after:s}));return C(),b(),_}function u(h,g){return jb(h,{align:g,alignDelimiters:n,padding:r,stringLength:i})}function d(h,g,S){const w=h.children;let b=-1;const C=[],_=g.enter("table");for(;++b<w.length;)C[b]=c(w[b],g,S);return _(),C}function c(h,g,S){const w=h.children;let b=-1;const C=[],_=g.enter("tableRow");for(;++b<w.length;)C[b]=l(w[b],h,g,S);return _(),C}function f(h,g,S){let w=Pl.inlineCode(h,g,S);return S.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function Iw(){return{exit:{taskListCheckValueChecked:Ll,taskListCheckValueUnchecked:Ll,paragraph:Aw}}}function Ew(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Pw}}}function Ll(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function Aw(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const i=t.children;let s=-1,a;for(;++s<i.length;){const o=i[s];if(o.type==="paragraph"){a=o;break}}a===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function Pw(e,t,r,n){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);s&&o.move(a);let l=Pl.listItem(e,t,r,m(m({},n),o.current()));return s&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+a}}function Mw(){return[ub(),Pb(),Db(),xw(),Iw()]}function Lw(e){return{extensions:[cb(),Mb(e),Ob(),Cw(e),Ew()]}}const Nw={tokenize:Rw,partial:!0},Nl={tokenize:jw,partial:!0},Dl={tokenize:Uw,partial:!0},Ol={tokenize:$w,partial:!0},Dw={tokenize:Hw,partial:!0},Fl={name:"wwwAutolink",tokenize:Bw,previous:zl},Bl={name:"protocolAutolink",tokenize:zw,previous:Rl},tt={name:"emailAutolink",tokenize:Fw,previous:jl},Xe={};function Ow(){return{text:Xe}}let gt=48;for(;gt<123;)Xe[gt]=tt,gt++,gt===58?gt=65:gt===91&&(gt=97);Xe[43]=tt,Xe[45]=tt,Xe[46]=tt,Xe[95]=tt,Xe[72]=[tt,Bl],Xe[104]=[tt,Bl],Xe[87]=[tt,Fl],Xe[119]=[tt,Fl];function Fw(e,t,r){const n=this;let i,s;return a;function a(c){return!Oi(c)||!jl.call(n,n.previous)||Fi(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return Oi(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(Dw,d,u)(c):c===45||c===95||xe(c)?(s=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),i=!0,l}function d(c){return s&&i&&Te(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function Bw(e,t,r){const n=this;return i;function i(a){return a!==87&&a!==119||!zl.call(n,n.previous)||Fi(n.events)?r(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Nw,e.attempt(Nl,e.attempt(Dl,s),r),r)(a))}function s(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function zw(e,t,r){const n=this;let i="",s=!1;return a;function a(c){return(c===72||c===104)&&Rl.call(n,n.previous)&&!Fi(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Te(c)&&i.length<5)return i+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const f=i.toLowerCase();if(f==="http"||f==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),s?u:(s=!0,l)):r(c)}function u(c){return c===null||$r(c)||te(c)||mt(c)||Hr(c)?r(c):e.attempt(Nl,e.attempt(Dl,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function Rw(e,t,r){let n=0;return i;function i(a){return(a===87||a===119)&&n<3?(n++,e.consume(a),i):a===46&&n===3?(e.consume(a),s):r(a)}function s(a){return a===null?r(a):t(a)}}function jw(e,t,r){let n,i,s;return a;function a(u){return u===46||u===95?e.check(Ol,l,o)(u):u===null||te(u)||mt(u)||u!==45&&Hr(u)?l(u):(s=!0,e.consume(u),a)}function o(u){return u===95?n=!0:(i=n,n=void 0),e.consume(u),a}function l(u){return i||n||!s?r(u):t(u)}}function Uw(e,t){let r=0,n=0;return i;function i(a){return a===40?(r++,e.consume(a),i):a===41&&n<r?s(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(Ol,t,s)(a):a===null||te(a)||mt(a)?t(a):(e.consume(a),i)}function s(a){return a===41&&n++,e.consume(a),i}}function $w(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),s):o===93?(e.consume(o),i):o===60||o===null||te(o)||mt(o)?t(o):r(o)}function i(o){return o===null||o===40||o===91||te(o)||mt(o)?t(o):n(o)}function s(o){return Te(o)?a(o):r(o)}function a(o){return o===59?(e.consume(o),n):Te(o)?(e.consume(o),a):r(o)}}function Hw(e,t,r){return n;function n(s){return e.consume(s),i}function i(s){return xe(s)?r(s):t(s)}}function zl(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||te(e)}function Rl(e){return!Te(e)}function jl(e){return!(e===47||Oi(e))}function Oi(e){return e===43||e===45||e===46||e===95||xe(e)}function Fi(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const qw={tokenize:Qw,partial:!0};function Vw(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Yw,continuation:{tokenize:Kw},exit:Xw}},text:{91:{name:"gfmFootnoteCall",tokenize:Gw},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ww,resolveTo:Jw}}}}function Ww(e,t,r){const n=this;let i=n.events.length;const s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a;for(;i--;){const l=n.events[i][1];if(l.type==="labelImage"){a=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!a||!a._balanced)return r(l);const u=Ve(n.sliceSerialize({start:a.end,end:n.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function Jw(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",a,t],["exit",a,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function Gw(e,t,r){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s=0,a;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(s>999||c===93&&!a||c===null||c===91||te(c))return r(c);if(c===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return i.includes(Ve(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return te(c)||(a=!0),s++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),s++,u):u(c)}}function Yw(e,t,r){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s,a=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(a>999||g===93&&!o||g===null||g===91||te(g))return r(g);if(g===93){e.exit("chunkString");const S=e.exit("gfmFootnoteDefinitionLabelString");return s=Ve(n.sliceSerialize(S)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return te(g)||(o=!0),a++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),a++,d):d(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),i.includes(s)||i.push(s),X(e,h,"gfmFootnoteDefinitionWhitespace")):r(g)}function h(g){return t(g)}}function Kw(e,t,r){return e.check(ar,t,e.attempt(qw,t,r))}function Xw(e){e.exit("gfmFootnoteDefinition")}function Qw(e,t,r){const n=this;return X(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const a=n.events[n.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(s):r(s)}}function Zw(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:s,resolveAll:i};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function i(a,o){let l=-1;for(;++l<a.length;)if(a[l][0]==="enter"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._close){let u=l;for(;u--;)if(a[u][0]==="exit"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._open&&a[l][1].end.offset-a[l][1].start.offset===a[u][1].end.offset-a[u][1].start.offset){a[l][1].type="strikethroughSequence",a[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},a[u][1].start),end:Object.assign({},a[l][1].end)},c={type:"strikethroughText",start:Object.assign({},a[u][1].end),end:Object.assign({},a[l][1].start)},f=[["enter",d,o],["enter",a[u][1],o],["exit",a[u][1],o],["enter",c,o]],h=o.parser.constructs.insideSpan.null;h&&Le(f,f.length,0,qr(h,a.slice(u+1,l),o)),Le(f,f.length,0,[["exit",c,o],["enter",a[l][1],o],["exit",a[l][1],o],["exit",d,o]]),Le(a,u-1,l-u+3,f),l=u+f.length-2;break}}for(l=-1;++l<a.length;)a[l][1].type==="strikethroughSequenceTemporary"&&(a[l][1].type="data");return a}function s(a,o,l){const u=this.previous,d=this.events;let c=0;return f;function f(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(a.enter("strikethroughSequenceTemporary"),h(g))}function h(g){const S=Ot(u);if(g===126)return c>1?l(g):(a.consume(g),c++,h);if(c<2&&!r)return l(g);const w=a.exit("strikethroughSequenceTemporary"),b=Ot(g);return w._open=!b||b===2&&!!S,w._close=!S||S===2&&!!b,o(g)}}}class ex{constructor(){this.map=[]}add(t,r,n){tx(this,t,r,n)}consume(t){if(this.map.sort(function(s,a){return s[0]-a[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let i=n.pop();for(;i;){for(const s of i)t.push(s);i=n.pop()}this.map.length=0}}function tx(e,t,r,n){let i=0;if(!(r===0&&n.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=r,e.map[i][2].push(...n);return}i+=1}e.map.push([t,r,n])}}function rx(e,t){let r=!1;const n=[];for(;t<e.length;){const i=e[t];if(r){if(i[0]==="enter")i[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const s=n.length-1;n[s]=n[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function nx(){return{flow:{null:{name:"table",tokenize:ix,resolveAll:sx}}}}function ix(e,t,r){const n=this;let i=0,s=0,a;return o;function o(k){let N=n.events.length-1;for(;N>-1;){const R=n.events[N][1].type;if(R==="lineEnding"||R==="linePrefix")N--;else break}const M=N>-1?n.events[N][1].type:null,V=M==="tableHead"||M==="tableRow"?I:l;return V===I&&n.parser.lazy[n.now().line]?r(k):V(k)}function l(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(a=!0,s+=1),d(k)}function d(k){return k===null?r(k):q(k)?s>1?(s=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),h):r(k):Y(k)?X(e,d,"whitespace")(k):(s+=1,a&&(a=!1,i+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),a=!0,d):(e.enter("data"),c(k)))}function c(k){return k===null||k===124||te(k)?(e.exit("data"),d(k)):(e.consume(k),k===92?f:c)}function f(k){return k===92||k===124?(e.consume(k),c):c(k)}function h(k){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(k):(e.enter("tableDelimiterRow"),a=!1,Y(k)?X(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):g(k))}function g(k){return k===45||k===58?w(k):k===124?(a=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),S):B(k)}function S(k){return Y(k)?X(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(s+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),b):k===45?(s+=1,b(k)):k===null||q(k)?F(k):B(k)}function b(k){return k===45?(e.enter("tableDelimiterFiller"),C(k)):B(k)}function C(k){return k===45?(e.consume(k),C):k===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(k))}function _(k){return Y(k)?X(e,F,"whitespace")(k):F(k)}function F(k){return k===124?g(k):k===null||q(k)?!a||i!==s?B(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):B(k)}function B(k){return r(k)}function I(k){return e.enter("tableRow"),z(k)}function z(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),z):k===null||q(k)?(e.exit("tableRow"),t(k)):Y(k)?X(e,z,"whitespace")(k):(e.enter("data"),j(k))}function j(k){return k===null||k===124||te(k)?(e.exit("data"),z(k)):(e.consume(k),k===92?$:j)}function $(k){return k===92||k===124?(e.consume(k),j):j(k)}}function sx(e,t){let r=-1,n=!0,i=0,s=[0,0,0,0],a=[0,0,0,0],o=!1,l=0,u,d,c;const f=new ex;for(;++r<e.length;){const h=e[r],g=h[1];h[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(Ul(f,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,s=[0,0,0,0],a=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",d,t]])),i=g.type==="tableDelimiterRow"?2:d?3:1):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,a[2]===0&&(s[1]!==0&&(a[0]=a[1],c=tn(f,t,s,i,void 0,c),s=[0,0,0,0]),a[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(s[1]!==0&&(a[0]=a[1],c=tn(f,t,s,i,void 0,c)),s=a,a=[s[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,s[1]!==0?(a[0]=a[1],c=tn(f,t,s,i,r,c)):a[1]!==0&&(c=tn(f,t,a,i,r,c)),i=0):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(a[3]=r)}for(l!==0&&Ul(f,t,l,u,d),f.consume(t.events),r=-1;++r<t.events.length;){const h=t.events[r];h[0]==="enter"&&h[1].type==="table"&&(h[1]._align=rx(t.events,r))}return e}function tn(e,t,r,n,i,s){const a=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(s.end=Object.assign({},Bt(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));const l=Bt(t.events,r[1]);if(s={type:a,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",s,t]]),r[2]!==0){const u=Bt(t.events,r[2]),d=Bt(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const f=t.events[r[2]],h=t.events[r[3]];if(f[1].end=Object.assign({},h[1].end),f[1].type="chunkText",f[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,S=r[3]-r[2]-1;e.add(g,S,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return i!==void 0&&(s.end=Object.assign({},Bt(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function Ul(e,t,r,n,i){const s=[],a=Bt(t.events,r);i&&(i.end=Object.assign({},a),s.push(["exit",i,t])),n.end=Object.assign({},a),s.push(["exit",n,t]),e.add(r+1,0,s)}function Bt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const ax={name:"tasklistCheck",tokenize:lx};function ox(){return{text:{91:ax}}}function lx(e,t,r){const n=this;return i;function i(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),s)}function s(l){return te(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),a):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),a):r(l)}function a(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return q(l)?t(l):Y(l)?e.check({tokenize:ux},t,r)(l):r(l)}}function ux(e,t,r){return X(e,n,"whitespace");function n(i){return i===null?r(i):t(i)}}function cx(e){return yo([Ow(),Vw(),Zw(e),nx(),ox()])}const dx={};function hx(e){const t=this,r=e||dx,n=t.data(),i=n.micromarkExtensions||(n.micromarkExtensions=[]),s=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),a=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);i.push(cx(r)),s.push(Mw()),a.push(Lw(r))}function he(...e){return e.filter(Boolean).join(" ")}const fx=({content:e})=>p.jsx(nb,{remarkPlugins:[hx],className:"cuadra-aui-md",components:gx,children:e}),$l=y.memo(fx),px=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=mx(),i=()=>{!t||r||n(t)};return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx(gu,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(fu,{className:"cuadra-h-4 cuadra-w-4"})]})]})},mx=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},gx=Uy({h1:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h1",m({className:he("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h2",m({className:he("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h3",m({className:he("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h4",m({className:he("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h5",m({className:he("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h6",m({className:he("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("p",m({className:he("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("a",m({className:he("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("blockquote",m({className:he("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ul",m({className:he("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ol",m({className:he("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("hr",m({className:he("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("table",m({className:he("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("th",m({className:he("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("td",m({className:he("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("tr",m({className:he("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("sup",m({className:he("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("pre",m({className:he("cuadra-overflow-x-auto cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var i=n,{className:t}=i,r=H(i,["className"]);const s=ol();return p.jsx("code",m({className:he(!s&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:px}),Hl=["Sending question…","Understanding your need…","Scanning data…","Comparing results…","Composing answer…"];function yx({active:e}){const[t,r]=y.useState(0);return y.useEffect(()=>{if(!e){r(0);return}const n=window.setInterval(()=>{r(i=>i>=Hl.length-1?(window.clearInterval(n),i):i+1)},2500);return()=>window.clearInterval(n)},[e]),e?p.jsxs("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-font-brand",children:["Thinking… ",Hl[t]]}):null}function ql({welcomeTitle:e="Hi, how can I help you today?",welcomeSubtitle:t="Start exploring our platform and discover what you can build.",extraTopPadding:r,suggestions:n,inputPlaceholder:i="Type your message..."}={}){const s=js(),[a,o]=y.useState(!1),[l,u]=y.useState(null),[d,c]=y.useState(!1);return y.useEffect(()=>{var f,h;if(!s){o(!1);return}try{const g=s==null?void 0:s.store;if(!g){o(!1);return}const S=(f=g.subscribe)==null?void 0:f.call(g,b=>{const C=b==null?void 0:b.threadId,_=(b==null?void 0:b.messages)||[],F=(b==null?void 0:b.isLoadingHistory)||!1,B=_.length;C&&C!==l&&u(C),o(F&&B===0);const z=_.some(j=>j.role==="assistant"&&!!j.content&&(Array.isArray(j.content)?j.content.some($=>typeof $=="object"&&($!=null&&$.text)?$.text.trim().length>0:!1):typeof j.content=="string"?j.content.trim().length>0:!1));c(z)}),w=(h=g.getState)==null?void 0:h.call(g);if(w){const b=w==null?void 0:w.threadId,C=(w==null?void 0:w.messages)||[],_=(w==null?void 0:w.isLoadingHistory)||!1,F=C.length;b&&b!==l&&u(b),o(_&&F===0);const I=C.some(z=>z.role==="assistant"&&!!z.content&&(Array.isArray(z.content)?z.content.some(j=>typeof j=="object"&&(j!=null&&j.text)?j.text.trim().length>0:!1):typeof z.content=="string"?z.content.trim().length>0:!1));c(I)}return()=>{S&&S()}}catch(g){o(!1)}},[s,l]),p.jsxs(Ia,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(Ma,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:r?{paddingTop:r}:void 0,children:a?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:[p.jsx($i,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs(p.Fragment,{children:[p.jsx(Ea,{children:p.jsx(bx,{title:e,subtitle:t,suggestions:n})}),p.jsx(vf,{components:{UserMessage:wx,AssistantMessage:xx}}),p.jsx(Aa,{running:!0,children:!d&&p.jsx("div",{className:"cuadra-mt-2 cuadra-max-w-2xl",children:p.jsx(yx,{active:!0})})})]})}),p.jsx("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",children:p.jsxs(wa,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx(Ca,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:i,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none cuadra-pr-10 font-brand",style:{paddingRight:"2.5rem",fontSize:"1rem",borderWidth:"1px"}})}),p.jsx(Yh,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--primary)",color:"hsl(var(--primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(hu,{className:"cuadra-h-4 cuadra-w-4"})})})]})})]})}function bx({title:e,subtitle:t,suggestions:r}){const n=ue(),i=s=>P(null,null,function*(){try{n.composer().setText(s),yield new Promise(a=>setTimeout(a,10)),n.composer().send()}catch(a){}});return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((s,a)=>p.jsx("button",{type:"button",onClick:()=>i(s.prompt),className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0",style:{borderWidth:"1px"},children:s.prompt},`suggestion-${a}`))})]})})}function wx(){return p.jsx(Bn,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:p.jsx("div",{className:"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--muted)",color:"hsl(var(--foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(zn,{components:{Text:({text:e})=>p.jsx($l,{content:e||""})}})})})}function xx(){return p.jsx(Bn,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsx("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:p.jsx(zn,{components:{Text:({text:e})=>p.jsx($l,{content:e||""})}})})})}function vx({onThreadSelect:e}){var w,b;const t=Us(),r=Sd(C=>C.threadId),[n,i]=y.useState(null),s=(t==null?void 0:t.id)===r,a=n===(t==null?void 0:t.id),[o,l]=y.useState(!1),[u,d]=y.useState((t==null?void 0:t.title)||""),[c,f]=y.useState(!1),[h,g]=y.useState(!1),S=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{g(!0);const C=window.__cuadraThreadListAdapter;C&&typeof C.rename=="function"&&(yield C.rename(t.remoteId,u)),l(!1),f(!1)}catch(C){l(!1),f(!1)}finally{g(!1)}});return y.useEffect(()=>{t!=null&&t.title&&!o&&d(t.title)},[t==null?void 0:t.title,o]),t?p.jsx(Ra,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${s?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>i(t.id),onMouseLeave:()=>i(null),children:p.jsxs(Tf,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-w-full cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:[p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:C=>d(C.target.value),onKeyDown:C=>{C.key==="Enter"&&S(),C.key==="Escape"&&(l(!1),d(t.title||""))},disabled:h,autoFocus:!0,onClick:C=>C.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((w=t.title)==null?void 0:w.length)||0)>60?`${(b=t.title)==null?void 0:b.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})}),p.jsx("div",{className:"cuadra-ml-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(a||s||c)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:C=>{C.stopPropagation(),f(!c)},"aria-label":"Thread options",children:p.jsx(yu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),c&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>f(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:C=>{C.stopPropagation(),S()},disabled:h,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:C=>{C.stopPropagation(),l(!0),d(t.title||""),f(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(kf,{asChild:!0,children:p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:C=>{C.stopPropagation(),f(!1)},children:"Delete"})})]})})]})]})})]})}):null}function Vl({onThreadSelect:e}){return p.jsxs(za,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsx("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4",children:p.jsx("h3",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-text-nowrap font-brand",children:"Chat History"})}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin",children:[p.jsx(Oa,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(wu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(Ba,{components:{ThreadListItem:t=>p.jsx(vx,E(m({},t),{onThreadSelect:e}))}})]})]})}const Sx=`
31
+ `+(a===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
32
+ `))+1))}const s="#".repeat(a),o=r.enter("headingAtx"),l=r.enter("phrasing");i.move(s+" ");let u=r.containerPhrasing(e,m({before:"# ",after:`
33
+ `},i.current()));return/^[\t ]/.test(u)&&(u=xr(u.charCodeAt(0))+u.slice(1)),u=u?s+" "+u:s,r.options.closeAtx&&(u+=" "+s),l(),o(),u}jl.peek=Iw;function jl(e){return e.value||""}function Iw(){return"<"}Ul.peek=Ew;function Ul(e,t,r,n){const a=Ha(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("![");return u+=l.move(r.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),u+=l.move(")"),s(),u}function Ew(){return"!"}$l.peek=Aw;function $l(e,t,r,n){const a=e.referenceType,i=r.enter("imageReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const u=r.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Aw(){return"!"}Hl.peek=Pw;function Hl(e,t,r){let n=e.value||"",a="`",i=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(n);)a+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<r.unsafe.length;){const s=r.unsafe[i],o=r.compilePattern(s);let l;if(s.atBreak)for(;l=o.exec(n);){let u=l.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(l.index+1)}}return a+n+a}function Pw(){return"`"}function ql(e,t){const r=da(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Vl.peek=Mw;function Vl(e,t,r,n){const a=Ha(r),i=a==='"'?"Quote":"Apostrophe",s=r.createTracker(n);let o,l;if(ql(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=s.move("<");return c+=s.move(r.containerPhrasing(e,m({before:c,after:">"},s.current()))),c+=s.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=s.move("[");return u+=s.move(r.containerPhrasing(e,m({before:u,after:"]("},s.current()))),u+=s.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=s.move("<"),u+=s.move(r.safe(e.url,m({before:u,after:">"},s.current()))),u+=s.move(">")):(l=r.enter("destinationRaw"),u+=s.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},s.current())))),l(),e.title&&(l=r.enter(`title${i}`),u+=s.move(" "+a),u+=s.move(r.safe(e.title,m({before:u,after:a},s.current()))),u+=s.move(a),l()),u+=s.move(")"),o(),u}function Mw(e,t,r){return ql(e,r)?"<":"["}Wl.peek=Nw;function Wl(e,t,r,n){const a=e.referenceType,i=r.enter("linkReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const u=r.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Nw(){return"["}function qa(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Lw(e){const t=qa(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Dw(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function Jl(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Ow(e,t,r,n){const a=r.enter("list"),i=r.bulletCurrent;let s=e.ordered?Dw(r):qa(r);const o=e.ordered?s==="."?")":".":Lw(r);let l=t&&r.bulletLastUsed?s===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((s==="*"||s==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),Jl(r)===s&&d){let c=-1;for(;++c<e.children.length;){const f=e.children[c];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(s=o),r.bulletCurrent=s;const u=r.containerFlow(e,n);return r.bulletLastUsed=s,r.bulletCurrent=i,a(),u}function Fw(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function Bw(e,t,r,n){const a=Fw(r);let i=r.bulletCurrent||qa(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let s=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(s=Math.ceil(s/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(s-i.length)),o.shift(s);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),d);return l(),u;function d(c,f,h){return f?(h?"":" ".repeat(s))+c:(h?i:i+" ".repeat(s-i.length))+c}}function zw(e,t,r,n){const a=r.enter("paragraph"),i=r.enter("phrasing"),s=r.containerPhrasing(e,n);return i(),a(),s}const Rw=un(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function jw(e,t,r,n){return(e.children.some(function(s){return Rw(s)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function Uw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}Kl.peek=$w;function Kl(e,t,r,n){const a=Uw(r),i=r.enter("strong"),s=r.createTracker(n),o=s.move(a+a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=hn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=xr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=hn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+xr(c));const h=s.move(a+a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function $w(e,t,r){return r.options.strong||"*"}function Hw(e,t,r,n){return r.safe(e.value,n)}function qw(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function Vw(e,t,r){const n=(Jl(r)+(r.options.ruleSpaces?" ":"")).repeat(qw(r));return r.options.ruleSpaces?n.slice(0,-1):n}const Gl={blockquote:pw,break:zl,code:xw,definition:Sw,emphasis:Rl,hardBreak:zl,heading:Cw,html:jl,image:Ul,imageReference:$l,inlineCode:Hl,link:Vl,linkReference:Wl,list:Ow,listItem:Bw,paragraph:zw,root:jw,strong:Kl,text:Hw,thematicBreak:Vw};function Ww(){return{enter:{table:Jw,tableData:Yl,tableHeader:Yl,tableRow:Gw},exit:{codeText:Yw,table:Kw,tableData:Va,tableHeader:Va,tableRow:Va}}}function Jw(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function Kw(e){this.exit(e),this.data.inTable=void 0}function Gw(e){this.enter({type:"tableRow",children:[]},e)}function Va(e){this.exit(e)}function Yl(e){this.enter({type:"tableCell",children:[]},e)}function Yw(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Xw));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function Xw(e,t){return t==="|"?t:e}function Qw(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,i=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
34
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:s,tableCell:l,tableRow:o}};function s(h,g,S,w){return u(d(h,S,w),h.align)}function o(h,g,S,w){const b=c(h,S,w),T=u([b]);return T.slice(0,T.indexOf(`
35
+ `))}function l(h,g,S,w){const b=S.enter("tableCell"),T=S.enter("phrasing"),_=S.containerPhrasing(h,E(m({},w),{before:i,after:i}));return T(),b(),_}function u(h,g){return hw(h,{align:g,alignDelimiters:n,padding:r,stringLength:a})}function d(h,g,S){const w=h.children;let b=-1;const T=[],_=g.enter("table");for(;++b<w.length;)T[b]=c(w[b],g,S);return _(),T}function c(h,g,S){const w=h.children;let b=-1;const T=[],_=g.enter("tableRow");for(;++b<w.length;)T[b]=l(w[b],h,g,S);return _(),T}function f(h,g,S){let w=Gl.inlineCode(h,g,S);return S.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function Zw(){return{exit:{taskListCheckValueChecked:Xl,taskListCheckValueUnchecked:Xl,paragraph:tx}}}function ex(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:rx}}}function Xl(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function tx(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const a=t.children;let i=-1,s;for(;++i<a.length;){const o=a[i];if(o.type==="paragraph"){s=o;break}}s===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function rx(e,t,r,n){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(s);let l=Gl.listItem(e,t,r,m(m({},n),o.current()));return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+s}}function nx(){return[Ob(),rw(),sw(),Ww(),Zw()]}function ax(e){return{extensions:[Fb(),nw(e),ow(),Qw(e),ex()]}}const ix={tokenize:dx,partial:!0},Ql={tokenize:hx,partial:!0},Zl={tokenize:fx,partial:!0},eu={tokenize:px,partial:!0},sx={tokenize:mx,partial:!0},tu={name:"wwwAutolink",tokenize:ux,previous:nu},ru={name:"protocolAutolink",tokenize:cx,previous:au},at={name:"emailAutolink",tokenize:lx,previous:iu},et={};function ox(){return{text:et}}let _t=48;for(;_t<123;)et[_t]=at,_t++,_t===58?_t=65:_t===91&&(_t=97);et[43]=at,et[45]=at,et[46]=at,et[95]=at,et[72]=[at,ru],et[104]=[at,ru],et[87]=[at,tu],et[119]=[at,tu];function lx(e,t,r){const n=this;let a,i;return s;function s(c){return!Wa(c)||!iu.call(n,n.previous)||Ja(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return Wa(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(sx,d,u)(c):c===45||c===95||xe(c)?(i=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),a=!0,l}function d(c){return i&&a&&Te(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function ux(e,t,r){const n=this;return a;function a(s){return s!==87&&s!==119||!nu.call(n,n.previous)||Ja(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(ix,e.attempt(Ql,e.attempt(Zl,i),r),r)(s))}function i(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function cx(e,t,r){const n=this;let a="",i=!1;return s;function s(c){return(c===72||c===104)&&au.call(n,n.previous)&&!Ja(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Te(c)&&a.length<5)return a+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const f=a.toLowerCase();if(f==="http"||f==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),i?u:(i=!0,l)):r(c)}function u(c){return c===null||Zr(c)||ne(c)||kt(c)||en(c)?r(c):e.attempt(Ql,e.attempt(Zl,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function dx(e,t,r){let n=0;return a;function a(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),a):s===46&&n===3?(e.consume(s),i):r(s)}function i(s){return s===null?r(s):t(s)}}function hx(e,t,r){let n,a,i;return s;function s(u){return u===46||u===95?e.check(eu,l,o)(u):u===null||ne(u)||kt(u)||u!==45&&en(u)?l(u):(i=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),s}function l(u){return a||n||!i?r(u):t(u)}}function fx(e,t){let r=0,n=0;return a;function a(s){return s===40?(r++,e.consume(s),a):s===41&&n<r?i(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?e.check(eu,t,i)(s):s===null||ne(s)||kt(s)?t(s):(e.consume(s),a)}function i(s){return s===41&&n++,e.consume(s),a}}function px(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),i):o===93?(e.consume(o),a):o===60||o===null||ne(o)||kt(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||ne(o)||kt(o)?t(o):n(o)}function i(o){return Te(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Te(o)?(e.consume(o),s):r(o)}}function mx(e,t,r){return n;function n(i){return e.consume(i),a}function a(i){return xe(i)?r(i):t(i)}}function nu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ne(e)}function au(e){return!Te(e)}function iu(e){return!(e===47||Wa(e))}function Wa(e){return e===43||e===45||e===46||e===95||xe(e)}function Ja(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const gx={tokenize:_x,partial:!0};function yx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:vx,continuation:{tokenize:Sx},exit:kx}},text:{91:{name:"gfmFootnoteCall",tokenize:xx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:bx,resolveTo:wx}}}}function bx(e,t,r){const n=this;let a=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;a--;){const l=n.events[a][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!s||!s._balanced)return r(l);const u=Ke(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function wx(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function xx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,s;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(i>999||c===93&&!s||c===null||c===91||ne(c))return r(c);if(c===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return a.includes(Ke(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return ne(c)||(s=!0),i++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),i++,u):u(c)}}function vx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,s=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(s>999||g===93&&!o||g===null||g===91||ne(g))return r(g);if(g===93){e.exit("chunkString");const S=e.exit("gfmFootnoteDefinitionLabelString");return i=Ke(n.sliceSerialize(S)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return ne(g)||(o=!0),s++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),s++,d):d(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),a.includes(i)||a.push(i),Z(e,h,"gfmFootnoteDefinitionWhitespace")):r(g)}function h(g){return t(g)}}function Sx(e,t,r){return e.check(pr,t,e.attempt(gx,t,r))}function kx(e){e.exit("gfmFootnoteDefinition")}function _x(e,t,r){const n=this;return Z(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(i):r(i)}}function Tx(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(s,o){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},f=[["enter",d,o],["enter",s[u][1],o],["exit",s[u][1],o],["enter",c,o]],h=o.parser.constructs.insideSpan.null;h&&Oe(f,f.length,0,tn(h,s.slice(u+1,l),o)),Oe(f,f.length,0,[["exit",c,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",d,o]]),Oe(s,u-1,l-u+3,f),l=u+f.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function i(s,o,l){const u=this.previous,d=this.events;let c=0;return f;function f(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(s.enter("strikethroughSequenceTemporary"),h(g))}function h(g){const S=qt(u);if(g===126)return c>1?l(g):(s.consume(g),c++,h);if(c<2&&!r)return l(g);const w=s.exit("strikethroughSequenceTemporary"),b=qt(g);return w._open=!b||b===2&&!!S,w._close=!S||S===2&&!!b,o(g)}}}class Cx{constructor(){this.map=[]}add(t,r,n){Ix(this,t,r,n)}consume(t){if(this.map.sort(function(i,s){return i[0]-s[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let a=n.pop();for(;a;){for(const i of a)t.push(i);a=n.pop()}this.map.length=0}}function Ix(e,t,r,n){let a=0;if(!(r===0&&n.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=r,e.map[a][2].push(...n);return}a+=1}e.map.push([t,r,n])}}function Ex(e,t){let r=!1;const n=[];for(;t<e.length;){const a=e[t];if(r){if(a[0]==="enter")a[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function Ax(){return{flow:{null:{name:"table",tokenize:Px,resolveAll:Mx}}}}function Px(e,t,r){const n=this;let a=0,i=0,s;return o;function o(k){let D=n.events.length-1;for(;D>-1;){const B=n.events[D][1].type;if(B==="lineEnding"||B==="linePrefix")D--;else break}const M=D>-1?n.events[D][1].type:null,W=M==="tableHead"||M==="tableRow"?I:l;return W===I&&n.parser.lazy[n.now().line]?r(k):W(k)}function l(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(s=!0,i+=1),d(k)}function d(k){return k===null?r(k):q(k)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),h):r(k):Y(k)?Z(e,d,"whitespace")(k):(i+=1,s&&(s=!1,a+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),s=!0,d):(e.enter("data"),c(k)))}function c(k){return k===null||k===124||ne(k)?(e.exit("data"),d(k)):(e.consume(k),k===92?f:c)}function f(k){return k===92||k===124?(e.consume(k),c):c(k)}function h(k){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(k):(e.enter("tableDelimiterRow"),s=!1,Y(k)?Z(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):g(k))}function g(k){return k===45||k===58?w(k):k===124?(s=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),S):z(k)}function S(k){return Y(k)?Z(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(i+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),b):k===45?(i+=1,b(k)):k===null||q(k)?F(k):z(k)}function b(k){return k===45?(e.enter("tableDelimiterFiller"),T(k)):z(k)}function T(k){return k===45?(e.consume(k),T):k===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(k))}function _(k){return Y(k)?Z(e,F,"whitespace")(k):F(k)}function F(k){return k===124?g(k):k===null||q(k)?!s||a!==i?z(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):z(k)}function z(k){return r(k)}function I(k){return e.enter("tableRow"),U(k)}function U(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),U):k===null||q(k)?(e.exit("tableRow"),t(k)):Y(k)?Z(e,U,"whitespace")(k):(e.enter("data"),j(k))}function j(k){return k===null||k===124||ne(k)?(e.exit("data"),U(k)):(e.consume(k),k===92?R:j)}function R(k){return k===92||k===124?(e.consume(k),j):j(k)}}function Mx(e,t){let r=-1,n=!0,a=0,i=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,d,c;const f=new Cx;for(;++r<e.length;){const h=e[r],g=h[1];h[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(su(f,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,i=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",d,t]])),a=g.type==="tableDelimiterRow"?2:d?3:1):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(i[1]!==0&&(s[0]=s[1],c=fn(f,t,i,a,void 0,c),i=[0,0,0,0]),s[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(s[0]=s[1],c=fn(f,t,i,a,void 0,c)),i=s,s=[i[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,i[1]!==0?(s[0]=s[1],c=fn(f,t,i,a,r,c)):s[1]!==0&&(c=fn(f,t,s,a,r,c)),a=0):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&su(f,t,l,u,d),f.consume(t.events),r=-1;++r<t.events.length;){const h=t.events[r];h[0]==="enter"&&h[1].type==="table"&&(h[1]._align=Ex(t.events,r))}return e}function fn(e,t,r,n,a,i){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},Wt(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=Wt(t.events,r[1]);if(i={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=Wt(t.events,r[2]),d=Wt(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const f=t.events[r[2]],h=t.events[r[3]];if(f[1].end=Object.assign({},h[1].end),f[1].type="chunkText",f[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,S=r[3]-r[2]-1;e.add(g,S,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return a!==void 0&&(i.end=Object.assign({},Wt(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function su(e,t,r,n,a){const i=[],s=Wt(t.events,r);a&&(a.end=Object.assign({},s),i.push(["exit",a,t])),n.end=Object.assign({},s),i.push(["exit",n,t]),e.add(r+1,0,i)}function Wt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Nx={name:"tasklistCheck",tokenize:Dx};function Lx(){return{text:{91:Nx}}}function Dx(e,t,r){const n=this;return a;function a(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return ne(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),s):r(l)}function s(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return q(l)?t(l):Y(l)?e.check({tokenize:Ox},t,r)(l):r(l)}}function Ox(e,t,r){return Z(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function Fx(e){return Fo([ox(),yx(),Tx(e),Ax(),Lx()])}const Bx={};function zx(e){const t=this,r=e||Bx,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(Fx(r)),i.push(nx()),s.push(ax(r))}function pe(...e){return e.filter(Boolean).join(" ")}const Rx=({content:e})=>p.jsx(Ab,{remarkPlugins:[zx],className:"cuadra-aui-md",components:$x,children:e}),ou=y.memo(Rx),jx=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=Ux(),a=()=>{!t||r||n(t)};return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:a,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx(Mu,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(Au,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Ux=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},$x=fb({h1:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h1",m({className:pe("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h2",m({className:pe("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h3",m({className:pe("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h4",m({className:pe("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h5",m({className:pe("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h6",m({className:pe("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("p",m({className:pe("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("a",m({className:pe("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("blockquote",m({className:pe("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ul",m({className:pe("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ol",m({className:pe("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("hr",m({className:pe("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("table",m({className:pe("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("th",m({className:pe("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("td",m({className:pe("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("tr",m({className:pe("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("sup",m({className:pe("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("pre",m({className:pe("cuadra-overflow-x-auto cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var a=n,{className:t}=a,r=H(a,["className"]);const i=Cl();return p.jsx("code",m({className:pe(!i&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:jx}),lu=["Sending question…","Understanding your need…","Scanning data…","Comparing results…","Composing answer…"];function Hx({active:e}){const[t,r]=y.useState(0);return y.useEffect(()=>{if(!e){r(0);return}const n=window.setInterval(()=>{r(a=>a>=lu.length-1?(window.clearInterval(n),a):a+1)},2500);return()=>window.clearInterval(n)},[e]),e?p.jsxs("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-font-brand",children:["Thinking… ",lu[t]]}):null}function uu({welcomeTitle:e="Hi, how can I help you today?",welcomeSubtitle:t="Start exploring our platform and discover what you can build.",extraTopPadding:r,suggestions:n,inputPlaceholder:a="Type your message...",enableAttachments:i=!1}={}){const s=es(),[o,l]=y.useState(!1),[u,d]=y.useState(null),[c,f]=y.useState(!1);return y.useEffect(()=>{var h,g;if(!s){l(!1);return}try{const S=s==null?void 0:s.store;if(!S){l(!1);return}const w=(h=S.subscribe)==null?void 0:h.call(S,T=>{const _=T==null?void 0:T.threadId,F=(T==null?void 0:T.messages)||[],z=(T==null?void 0:T.isLoadingHistory)||!1,I=F.length;_&&_!==u&&d(_),l(z&&I===0);const j=F.some(R=>R.role==="assistant"&&!!R.content&&(Array.isArray(R.content)?R.content.some(k=>typeof k=="object"&&(k!=null&&k.text)?k.text.trim().length>0:!1):typeof R.content=="string"?R.content.trim().length>0:!1));f(j)}),b=(g=S.getState)==null?void 0:g.call(S);if(b){const T=b==null?void 0:b.threadId,_=(b==null?void 0:b.messages)||[],F=(b==null?void 0:b.isLoadingHistory)||!1,z=_.length;T&&T!==u&&d(T),l(F&&z===0);const U=_.some(j=>j.role==="assistant"&&!!j.content&&(Array.isArray(j.content)?j.content.some(R=>typeof R=="object"&&(R!=null&&R.text)?R.text.trim().length>0:!1):typeof j.content=="string"?j.content.trim().length>0:!1));f(U)}return()=>{w&&w()}}catch(S){l(!1)}},[s,u]),p.jsxs(Vs,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(Gs,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:r?{paddingTop:r}:void 0,children:o?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:[p.jsx(ti,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs(p.Fragment,{children:[p.jsx(Ws,{children:p.jsx(qx,{title:e,subtitle:t,suggestions:n})}),p.jsx(Jf,{components:{UserMessage:Vx,AssistantMessage:Wx}}),p.jsx(Js,{running:!0,children:!c&&p.jsx("div",{className:"cuadra-mt-2 cuadra-max-w-2xl",children:p.jsx(Hx,{active:!0})})})]})}),p.jsxs("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",children:[i&&p.jsx(qs,{components:{Attachment:()=>{const h=ee(({attachment:g})=>g);return h?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-2 cuadra-py-1 cuadra-rounded-md cuadra-bg-muted cuadra-border cuadra-border-border",children:[p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground font-brand",children:h.name||"Attachment"}),p.jsx(ef,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded hover:cuadra-bg-background cuadra-transition-colors","aria-label":"Remove attachment",children:p.jsx(vn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(Os,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx($s,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:a,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{paddingRight:i?"5rem":"3rem",fontSize:"1rem",borderWidth:"1px"}})}),i&&p.jsx(Bf,{multiple:!0,asChild:!0,children:p.jsx("button",{type:"button",className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-12 cuadra-size-8 cuadra-rounded-md hover:cuadra-bg-muted cuadra-transition-colors cuadra-flex cuadra-items-center cuadra-justify-center cuadra-border cuadra-border-border",style:{position:"absolute",bottom:"0.5rem",right:"3rem"},"aria-label":"Attach file",children:p.jsx(ri,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5})})}),p.jsx(bf,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(Eu,{className:"cuadra-h-4 cuadra-w-4"})})})]})]})]})}function qx({title:e,subtitle:t,suggestions:r}){const n=le(),a=i=>P(null,null,function*(){try{n.composer().setText(i),yield new Promise(s=>setTimeout(s,10)),n.composer().send()}catch(s){}});return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((i,s)=>p.jsx("button",{type:"button",onClick:()=>a(i.prompt),className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0",style:{borderWidth:"1px"},children:i.prompt},`suggestion-${s}`))})]})})}function Vx(){return p.jsxs(Kn,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:[p.jsx(Ls,{components:{Attachment:()=>{var i;const e=ee(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(i=e.content)==null?void 0:i.find(s=>s.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-col-start-2 cuadra-row-start-1 cuadra-mb-2 cuadra-max-w-[calc(42rem*0.8)]",children:t&&a?p.jsx("img",{src:a,alt:e.name||"Attachment",className:"cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{borderWidth:"1px"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted cuadra-px-3 cuadra-py-2",children:[p.jsx(ri,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),p.jsx("div",{className:"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--cuadra-muted)",color:"hsl(var(--cuadra-foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(Gn,{components:{Text:({text:e})=>p.jsx(ou,{content:e||""})}})})]})}function Wx(){return p.jsx(Kn,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsx("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:p.jsx(Gn,{components:{Text:({text:e})=>p.jsx(ou,{content:e||""})}})})})}const cu=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const s=localStorage.getItem("theme");return s||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,a]=y.useState(r);y.useEffect(()=>{t!=="system"&&a(t)},[t]),y.useEffect(()=>{const s=document.documentElement;s.classList.remove("light","dark"),s.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const i=()=>{t==="system"&&a(s=>s==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:i,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(Pu,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})};function Jx({onThreadSelect:e}){var w,b;const t=ts(),r=zd(T=>T.threadId),[n,a]=y.useState(null),i=(t==null?void 0:t.id)===r,s=n===(t==null?void 0:t.id),[o,l]=y.useState(!1),[u,d]=y.useState((t==null?void 0:t.title)||""),[c,f]=y.useState(!1),[h,g]=y.useState(!1),S=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{g(!0);const T=window.__cuadraThreadListAdapter;T&&typeof T.rename=="function"&&(yield T.rename(t.remoteId,u)),l(!1),f(!1)}catch(T){l(!1),f(!1)}finally{g(!1)}});return y.useEffect(()=>{t!=null&&t.title&&!o&&d(t.title)},[t==null?void 0:t.title,o]),t?p.jsx(no,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${i?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>a(t.id),onMouseLeave:()=>a(null),children:p.jsxs(Xf,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-w-full cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:[p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:T=>d(T.target.value),onKeyDown:T=>{T.key==="Enter"&&S(),T.key==="Escape"&&(l(!1),d(t.title||""))},disabled:h,autoFocus:!0,onClick:T=>T.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((w=t.title)==null?void 0:w.length)||0)>60?`${(b=t.title)==null?void 0:b.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})}),p.jsx("div",{className:"cuadra-ml-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(s||i||c)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:T=>{T.stopPropagation(),f(!c)},"aria-label":"Thread options",children:p.jsx(Nu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),c&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>f(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),S()},disabled:h,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),l(!0),d(t.title||""),f(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(Gf,{asChild:!0,children:p.jsx("button",{className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),f(!1)},children:"Delete"})})]})})]})]})})]})}):null}function du({onThreadSelect:e,showThemeToggle:t,theme:r,onLogout:n}){return p.jsxs(ro,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsx("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-end cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4",children:p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(vn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin",children:[p.jsx(Zs,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(Ou,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(to,{components:{ThreadListItem:a=>p.jsx(Jx,E(m({},a),{onThreadSelect:e}))}})]}),(t||n)&&p.jsxs("div",{className:"cuadra-border-t cuadra-border-border cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-4",children:[n&&p.jsx("button",{type:"button",onClick:n,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Logout",children:p.jsx(Lu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),t&&p.jsx(cu,{theme:r})]})]})}const Kx=`
36
36
  @keyframes rotate {
37
37
  100% { transform: rotate(1turn); }
38
38
  }
39
- `,Bi=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:i=4,style:s,contentStyle:a,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:Sx}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:i},s),children:[p.jsx("div",{className:"cuadra-absolute md:cuadra-rounded-xl",style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundImage:"conic-gradient(#F4633A, #FF7A4D, #FF8C5C, #F4633A, #FF7A4D, #FF8C5C)",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundImage:"linear-gradient(to right, #F4633A, #FF7A4D, #FF8C5C, #F4633A)",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},a),children:e})]})]}),kx=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const a=localStorage.getItem("theme");return a||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,i]=y.useState(r);y.useEffect(()=>{t!=="system"&&i(t)},[t]),y.useEffect(()=>{const a=document.documentElement;a.classList.remove("light","dark"),a.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const s=()=>{t==="system"&&i(a=>a==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:s,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(mu,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})},Wl=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:i,hideModelSelector:s=!1,showThemeToggle:a=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1})=>{const[d,c]=y.useState(!1),f=y.useRef(null);y.useEffect(()=>{const g=S=>{f.current&&!f.current.contains(S.target)&&c(!1)};return d&&document.addEventListener("mousedown",g),()=>{document.removeEventListener("mousedown",g)}},[d]);const h=t.find(g=>g.id===e);return p.jsxs("div",{className:"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden","aria-label":"Toggle thread list",children:p.jsx(bu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),a&&p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(kx,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!s&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),s?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs("div",{ref:f,className:"cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>c(!d),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:h?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(h==null?void 0:h.name)||"Select model"}),p.jsx(pu,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),d&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(g=>p.jsxs("button",{type:"button",onClick:()=>{i(g.id),c(!1)},className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===g.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===g.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:g.name})]},g.id))})})]})]})]})},_x=y.createContext(void 0),zi=({children:e,value:t})=>p.jsx(_x.Provider,{value:t,children:e});function Tx(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.type="text/css";const i=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:Se&&Se.tagName.toUpperCase()==="SCRIPT"&&Se.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let s=!1;for(const a of i)if(n.href=a,n.onload=()=>{s=!0},n.onerror=()=>{},document.head.appendChild(n),s)break},[])}const Jl=({config:e})=>{Tx();const{baseUrl:t,proxyUrl:r,sessionToken:n,mode:i="multiChat",modelMode:s="fixed",modelId:a,onModelChange:o,ephemeral:l=!1,systemPrompt:u,initialThreadId:d,welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g,inputPlaceholder:S,showThemeToggle:w=!0,theme:b="system",onError:C,onChatCreated:_,onUserMessage:F,onThreadIdUpdate:B}=e,[I,z]=y.useState(!1),j=r||t||"",$=!!r,k=y.useMemo(()=>new ja(j,n||void 0,$),[j,n,$]),[N,M]=y.useState(null),[V,R]=y.useState(!1),[D,Q]=y.useState(null),[se,ge]=y.useState(!1);y.useEffect(()=>{i==="multiChat"&&ge(!0)},[i]);const fe=y.useCallback(()=>P(null,null,function*(){if(s==="selector"){R(!0),Q(null);try{const Z=yield k.listModels();M(Z)}catch(Z){Q(Z instanceof Error?Z:new Error("Failed to load models"))}finally{R(!1)}}}),[k,s]);y.useEffect(()=>{s==="selector"&&fe()},[s,fe]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=fe),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[fe]);const[x,ye]=y.useState(s==="fixed"&&a||null),Ie=y.useRef(x),v=y.useCallback(Z=>{const je=Ie.current;ye(Z),Ie.current=Z,o==null||o(Z),je!==null&&je!==Z&&i==="multiChat"&&setTimeout(()=>{var bt,nn;const pe=window.__cuadraThreadListRuntime;if((bt=pe==null?void 0:pe.threads)!=null&&bt.switchToNewThread)try{pe.threads.switchToNewThread()}catch(sn){}else if((nn=pe==null?void 0:pe.threads)!=null&&nn.createThread)try{pe.threads.createThread()}catch(sn){}else if(pe!=null&&pe.switchToNewThread)try{pe.switchToNewThread()}catch(sn){}},100)},[o,i]);y.useEffect(()=>{if(s==="selector"&&(N!=null&&N.items)&&N.items.length>0&&!x){const Z=N.items[0];if(Z!=null&&Z.id){const je=Z.id;ye(je),o==null||o(je)}}},[s,N==null?void 0:N.items,x,o]);const ve=s==="fixed"?!!a:!!x,Re=y.useMemo(()=>((N==null?void 0:N.items)||[]).filter(Z=>(Z==null?void 0:Z.id)&&(Z==null?void 0:Z.displayName)).map(Z=>({id:Z.id,name:Z.displayName})),[N]),le=y.useMemo(()=>({currentModelId:x||"",models:Re,modelsLoading:V,modelsError:D,onModelChange:v,refetchModels:fe}),[x,Re,V,D,v,fe]);return s==="selector"&&V||i==="multiChat"&&se?p.jsx(zi,{value:le,children:p.jsx(Bi,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx($i,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):s==="selector"&&!ve&&D?p.jsx(zi,{value:le,children:p.jsx(Bi,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(zi,{value:le,children:p.jsx(Pf,{baseUrl:$?j:t||j,sessionToken:n,isProxyMode:$,mode:i,modelMode:s,modelId:x||a||void 0,onModelChange:v,ephemeral:l,systemPrompt:u,initialThreadId:d,onError:C,onChatCreated:_,onUserMessage:F,onThreadIdUpdate:B,onChatsLoaded:()=>{i==="multiChat"&&ge(!1)},children:p.jsx(Bi,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${e.containerClass||""}`,borderSizePx:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:i==="multiChat"?p.jsxs(p.Fragment,{children:[I&&typeof document!="undefined"&&Oe.createPortal(p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-40 md:cuadra-hidden",onClick:()=>z(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(Vl,{onThreadSelect:()=>z(!1)})}),I&&Oe.createPortal(p.jsx("div",{className:"cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 cuadra-translate-x-0",style:{borderRightWidth:"1px"},children:p.jsx(Vl,{onThreadSelect:()=>z(!1)})}),document.body)]}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[s==="selector"&&p.jsx(Wl,{currentModel:x||"",models:Re,modelsLoading:V,modelsError:D,onModelChange:v,showThemeToggle:w,theme:b,onMobileMenuClick:()=>z(!I),showMobileMenuButton:i==="multiChat"}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(ql,{welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g,inputPlaceholder:S})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[s==="selector"&&p.jsx(Wl,{currentModel:x||"",models:Re,modelsLoading:V,modelsError:D,onModelChange:v,showThemeToggle:w,theme:b}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(ql,{welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g})})]})})})})})})};class rn{constructor(){T(this,"config",null);T(this,"root",null);T(this,"container",null);T(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=E(m({},t),{containerId:r}),this.container=n,this.root=ae.createRoot(n),this.root.render(y.createElement(Gl,{config:this.config})),this.instances.set(r,this)}destroy(t){var i;const r=t||((i=this.config)==null?void 0:i.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var a;const n=r||((a=this.config)==null?void 0:a.containerId);if(!n)return;const i=this.instances.get(n);if(!(i!=null&&i.config))return;const s=m(m({},i.config),t);i.config=s,i.root&&i.container&&i.root.render(y.createElement(Gl,{config:s}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const Gl=({config:e})=>p.jsx(Jl,{config:e});let Ce=null;typeof window!="undefined"&&(Ce=new rn);const Yl={init:e=>(Ce||(Ce=new rn),Ce.init(e)),destroy:e=>Ce==null?void 0:Ce.destroy(e),updateConfig:(e,t)=>Ce==null?void 0:Ce.updateConfig(e,t),getInstance:e=>Ce==null?void 0:Ce.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=Yl;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&Cx(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function Cx(e){if(!e||!Ce)return;const t=rn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const i=rn.parseConfigFromAttributes(e,n);Object.assign(t,i)}(t.baseUrl||t.proxyUrl)&&Ce.init(t)}U.WidgetContent=Jl,U.default=Yl,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
39
+ `,Ka=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=4,style:i,contentStyle:s,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:Kx}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:a},i),children:[p.jsx("div",{className:"cuadra-absolute md:cuadra-rounded-xl",style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundImage:"conic-gradient(#F4633A, #FF7A4D, #FF8C5C, #F4633A, #FF7A4D, #FF8C5C)",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundImage:"linear-gradient(to right, #F4633A, #FF7A4D, #FF8C5C, #F4633A)",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},s),children:e})]})]}),hu=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:a,hideModelSelector:i=!1,showThemeToggle:s=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1})=>{const[d,c]=y.useState(!1),[f,h]=y.useState(!1),g=y.useRef(null);y.useEffect(()=>{const b=T=>{g.current&&!g.current.contains(T.target)&&c(!1)};return d&&document.addEventListener("mousedown",b),()=>{document.removeEventListener("mousedown",b)}},[d]);const S=t.find(b=>b.id===e),w=b=>{a(b),c(!1),h(!1)};return p.jsxs("div",{className:"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden","aria-label":"Toggle thread list",children:p.jsx(Du,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),s&&p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(cu,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!i&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),i?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:g,className:"cuadra-hidden md:cuadra-block cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>c(!d),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:S?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(S==null?void 0:S.name)||"Select model"}),p.jsx(ei,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),d&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>w(b.id),className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===b.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===b.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:b.name})]},b.id))})})]}),p.jsxs("button",{type:"button",onClick:()=>h(!0),disabled:r||t.length===0||!!n,className:"cuadra-flex md:cuadra-hidden cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:S?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(S==null?void 0:S.name)||"Select model"}),p.jsx(ei,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),f&&typeof document!="undefined"&&Ne.createPortal(p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-50 md:cuadra-hidden",onClick:()=>h(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col cuadra-bg-background md:cuadra-hidden",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-4",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>h(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(vn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-4",children:r?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading models..."})}):n?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):t.length===0?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"No models available"})}):p.jsx("div",{className:"cuadra-space-y-2",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>w(b.id),className:`cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-rounded-lg cuadra-border cuadra-px-4 cuadra-py-4 cuadra-text-left cuadra-transition-colors font-brand cuadra-bg-background cuadra-text-foreground cuadra-border-border hover:cuadra-bg-muted ${e===b.id?"cuadra-border-primary":""}`,children:[p.jsx("span",{className:"cuadra-text-base cuadra-font-normal",children:b.name}),e===b.id&&p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"none",viewBox:"0 0 20 20",className:"cuadra-text-primary",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z",clipRule:"evenodd"})})]},b.id))})})]})]}),document.body)]})]})]})},Gx=y.createContext(void 0),Ga=({children:e,value:t})=>p.jsx(Gx.Provider,{value:t,children:e});function Yx(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.type="text/css";const a=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:Se&&Se.tagName.toUpperCase()==="SCRIPT"&&Se.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let i=!1;for(const s of a)if(n.href=s,n.onload=()=>{i=!0},n.onerror=()=>{},document.head.appendChild(n),i)break},[])}const fu=({config:e})=>{Yx();const{baseUrl:t,proxyUrl:r,sessionToken:n,mode:a="multiChat",modelMode:i="fixed",modelId:s,onModelChange:o,ephemeral:l=!1,systemPrompt:u,initialThreadId:d,welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g,inputPlaceholder:S,showThemeToggle:w=!0,theme:b="system",onError:T,onChatCreated:_,onUserMessage:F,onThreadIdUpdate:z,onLogout:I,enableAttachments:U=!1}=e,[j,R]=y.useState(!1),[k,D]=y.useState(null),[M,W]=y.useState(null),[B,O]=y.useState(!1),X=y.useRef(null),ae=J=>{if(J<30)return!0;if(X.current){const fe=X.current.getBoundingClientRect();if(J-fe.left<30)return!0}return!1},ye=J=>{const oe=J.touches[0].clientX;(ae(oe)||j)&&(D(oe),W(oe),O(!0))},Ie=J=>{if(k===null||!B)return;const fe=J.touches[0];W(fe.clientX)},x=()=>{if(k===null||M===null){O(!1);return}const J=M-k,fe=50,oe=.3,L=Math.abs(J)/300;J>fe&&!j&&k!==null?ae(k)&&R(!0):((J<-fe||J<0&&L>oe)&&j||j&&J<-20&&L>oe)&&R(!1),D(null),W(null),O(!1)},ve=()=>{if(B&&k!==null&&M!==null){const J=M-k;if(j)return`translateX(${Math.min(0,J)}px)`;if(k!==null&&ae(k))return`translateX(${Math.min(0,-320+J)}px)`}return j?"translateX(0)":"translateX(-100%)"},Pe=()=>{if(!B||k===null||M===null)return j?.5:0;const fe=M-k;return j?Math.max(0,Math.min(1,(320+fe)/320))*.5:k!==null&&ae(k)?Math.max(0,Math.min(1,(fe+320)/320))*.5:0},v=r||t||"",me=!!r,tt=y.useMemo(()=>new ao(v,n||void 0,me),[v,n,me]),[te,Ct]=y.useState(null),[Me,it]=y.useState(!1),[$e,It]=y.useState(null),[Ya,mn]=y.useState(!1);y.useEffect(()=>{a==="multiChat"&&mn(!0)},[a]);const mt=y.useCallback(()=>P(null,null,function*(){if(i==="selector"){it(!0),It(null);try{const J=yield tt.listModels();Ct(J)}catch(J){It(J instanceof Error?J:new Error("Failed to load models"))}finally{it(!1)}}}),[tt,i]);y.useEffect(()=>{i==="selector"&&mt()},[i,mt]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=mt),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[mt]);const[He,Tr]=y.useState(i==="fixed"&&s||null),Cr=y.useRef(He),Et=y.useCallback(J=>{const fe=Cr.current;Tr(J),Cr.current=J,o==null||o(J),fe!==null&&fe!==J&&a==="multiChat"&&setTimeout(()=>{var A,L;const oe=window.__cuadraThreadListRuntime;if((A=oe==null?void 0:oe.threads)!=null&&A.switchToNewThread)try{oe.threads.switchToNewThread()}catch(V){}else if((L=oe==null?void 0:oe.threads)!=null&&L.createThread)try{oe.threads.createThread()}catch(V){}else if(oe!=null&&oe.switchToNewThread)try{oe.switchToNewThread()}catch(V){}},100)},[o,a]);y.useEffect(()=>{if(i==="selector"&&(te!=null&&te.items)&&te.items.length>0&&!He){const J=te.items[0];if(J!=null&&J.id){const fe=J.id;Tr(fe),o==null||o(fe)}}},[i,te==null?void 0:te.items,He,o]);const gn=i==="fixed"?!!s:!!He,At=y.useMemo(()=>((te==null?void 0:te.items)||[]).filter(J=>(J==null?void 0:J.id)&&(J==null?void 0:J.displayName)).map(J=>({id:J.id,name:J.displayName})),[te]),Ir=y.useMemo(()=>({currentModelId:He||"",models:At,modelsLoading:Me,modelsError:$e,onModelChange:Et,refetchModels:mt}),[He,At,Me,$e,Et,mt]);return i==="selector"&&Me||a==="multiChat"&&Ya?p.jsx(Ga,{value:Ir,children:p.jsx(Ka,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(ti,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):i==="selector"&&!gn&&$e?p.jsx(Ga,{value:Ir,children:p.jsx(Ka,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(Ga,{value:Ir,children:p.jsx(rp,{baseUrl:me?v:t||v,sessionToken:n,isProxyMode:me,mode:a,modelMode:i,modelId:He||s||void 0,onModelChange:Et,ephemeral:l,systemPrompt:u,initialThreadId:d,enableAttachments:U,onError:T,onChatCreated:_,onUserMessage:F,onThreadIdUpdate:z,onChatsLoaded:()=>{a==="multiChat"&&mn(!1)},children:p.jsx(Ka,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${e.containerClass||""}`,borderSizePx:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},onTouchStart:ye,onTouchMove:Ie,onTouchEnd:x,children:a==="multiChat"?p.jsxs(p.Fragment,{children:[typeof document!="undefined"&&Ne.createPortal(p.jsx("div",{className:`cuadra-fixed cuadra-inset-0 cuadra-bg-black cuadra-z-40 md:cuadra-hidden cuadra-transition-opacity cuadra-duration-300 ${j||B?"":"cuadra-pointer-events-none"}`,style:{opacity:Pe()},onClick:()=>R(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(du,{onThreadSelect:()=>R(!1),showThemeToggle:w,theme:b,onLogout:I})}),typeof document!="undefined"&&Ne.createPortal(p.jsx("div",{className:`cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 ${j||B?"":"cuadra-pointer-events-none"}`,style:{borderRightWidth:"1px",transform:ve(),transition:B?"none":"transform 0.3s ease-in-out"},onTouchStart:ye,onTouchMove:Ie,onTouchEnd:x,children:p.jsx(du,{onThreadSelect:()=>R(!1),showThemeToggle:w,theme:b,onLogout:I})}),document.body)]}),p.jsxs("div",{ref:X,className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[i==="selector"&&p.jsx(hu,{currentModel:He||"",models:At,modelsLoading:Me,modelsError:$e,onModelChange:Et,showThemeToggle:w,theme:b,onMobileMenuClick:()=>R(!j),showMobileMenuButton:a==="multiChat"}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(uu,{welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g,inputPlaceholder:S,enableAttachments:U})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[i==="selector"&&p.jsx(hu,{currentModel:He||"",models:At,modelsLoading:Me,modelsError:$e,onModelChange:Et,showThemeToggle:w,theme:b}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(uu,{welcomeTitle:c,welcomeSubtitle:f,extraTopPadding:h,suggestions:g,inputPlaceholder:S})})]})})})})})})};class pn{constructor(){C(this,"config",null);C(this,"root",null);C(this,"container",null);C(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=E(m({},t),{containerId:r}),this.container=n,this.root=ue.createRoot(n),this.root.render(y.createElement(pu,{config:this.config})),this.instances.set(r,this)}destroy(t){var a;const r=t||((a=this.config)==null?void 0:a.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const i=m(m({},a.config),t);a.config=i,a.root&&a.container&&a.root.render(y.createElement(pu,{config:i}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const pu=({config:e})=>p.jsx(fu,{config:e});let Ce=null;typeof window!="undefined"&&(Ce=new pn);const mu={init:e=>(Ce||(Ce=new pn),Ce.init(e)),destroy:e=>Ce==null?void 0:Ce.destroy(e),updateConfig:(e,t)=>Ce==null?void 0:Ce.updateConfig(e,t),getInstance:e=>Ce==null?void 0:Ce.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=mu;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&Xx(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function Xx(e){if(!e||!Ce)return;const t=pn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=pn.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&Ce.init(t)}$.WidgetContent=fu,$.default=mu,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
40
40
  //# sourceMappingURL=cuadra-uikit.umd.js.map