@meandr/chat-sdk 0.0.2 → 0.0.3

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,11 +1,11 @@
1
- "use strict";var MeandrChat=(()=>{var bt=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var ze=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:!0})},We=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fe(t))!qe.call(e,o)&&o!==n&&bt(e,o,{get:()=>t[o],enumerable:!(r=Be(t,o))||r.enumerable});return e};var Xe=e=>We(bt({},"__esModule",{value:!0}),e);var Bn={};ze(Bn,{ChatError:()=>p,createChat:()=>be,isChatError:()=>T,parseMarkdown:()=>Zt,renderMarkdown:()=>Re});var Je=new Set(["busy","rate_limited","overloaded","not_connected","interrupted","timeout","unavailable","model_busy","no_answer","network","internal","token_failed"]),p=class extends Error{constructor(t,n,r={}){var o,s,a;super(n),this.name="ChatError",this.code=t,this.status=(o=r.status)!=null?o:0,this.retryAfter=(s=r.retryAfter)!=null?s:null,this.partial=(a=r.partial)!=null?a:null,r.cause!==void 0&&(this.cause=r.cause)}get retryable(){return Je.has(this.code)}};function T(e){return e instanceof p||!!e&&typeof e=="object"&&e.name==="ChatError"&&typeof e.code=="string"}var He=/^(localhost|127\.0\.0\.1|\[::1\])$/,H=3e4,ee=16<<20,Ge=18e4,re=32;function oe(e){let t;try{t=new URL(e)}catch{throw new TypeError("url must be an absolute URL")}if(t.protocol!=="https:"&&!(t.protocol==="http:"&&He.test(t.hostname)))throw new TypeError("url must be an https: URL");if(t.username||t.password)throw new TypeError("url must not carry credentials");return t.origin+t.pathname.replace(/\/+$/,"")+"/chat/v1"}function A(){return new p("aborted","Cut short by the page.")}function B(e,t,n,r){return new Promise((o,s)=>{if(t&&t.aborted)return s(A());let a=()=>{clearTimeout(c),t&&t.removeEventListener("abort",i)},i=()=>{a(),s(A())},c=setTimeout(()=>{a(),s(r())},n);t&&t.addEventListener("abort",i,{once:!0}),e.then(u=>{a(),o(u)},u=>{a(),s(u)})})}async function K(e,t,n,r,o=H){if(r&&r.aborted)throw A();let s=new AbortController,a=new Promise((i,c)=>{try{e(t,{...n,signal:s.signal}).then(i,c)}catch(u){c(u)}});try{return await B(a,r,o,se)}catch(i){throw s.abort(),a.then(U,()=>{}),T(i)?i:new p("network","Couldn't connect.")}}function D(e,t,n){let r={Accept:n.stream?"text/event-stream":"application/json"};n.body!==void 0&&(r["Content-Type"]=n.type||"application/json"),n.bearer&&(r.Authorization="Bearer "+n.bearer);let o={method:n.method,headers:r,credentials:"include",cache:"no-store",redirect:"error"};return n.body!==void 0&&(o.body=n.type?n.body:JSON.stringify(n.body)),n.type?n.progress&&typeof XMLHttpRequest=="function"?Ze(t+n.path,o,n.progress,n.signal):K(e,t+n.path,o,n.signal,H+n.body.size/re):K(e,t+n.path,o,n.signal)}function Ze(e,t,n,r){return new Promise((o,s)=>{if(r&&r.aborted)return s(A());let a=new XMLHttpRequest,i,c=m=>{clearTimeout(i),r&&r.removeEventListener("abort",u),m&&(a.abort(),s(m))},u=()=>c(A()),h=()=>{clearTimeout(i),i=setTimeout(()=>c(se()),H)};a.open(t.method,e),a.withCredentials=!0;let g=t.headers;for(let m in g)a.setRequestHeader(m,g[m]);a.upload.onprogress=m=>{h(),n(m.loaded)},a.onprogress=h,a.onerror=()=>c(new p("network","Couldn't connect.")),a.onload=()=>{c();try{o(new Response(a.responseText,{status:a.status,headers:{"Retry-After":a.getResponseHeader("Retry-After")||""}}))}catch{s(new p("protocol","The chat's answer couldn't be read.",{status:a.status}))}},r&&r.addEventListener("abort",u,{once:!0}),h(),a.send(t.body)})}function se(){return new p("network","No answer came in time.")}function U(e){e.body&&!e.body.locked&&e.body.cancel().catch(()=>{})}async function yt(e,t){let n=e.body;if(!n){let i;try{i=await B(e.arrayBuffer(),t,H,ne)}catch(c){throw T(c)?c:new p("network","The answer was cut short.")}if(i.byteLength>ee)throw new p("protocol","The chat's answer is too large.",{status:e.status});return[new Uint8Array(i)]}let r=n.getReader(),o=[],s=Date.now(),a=0;try{for(;;){let i;try{i=await B(r.read(),t,Math.max(0,Math.min(H,s+Ge+a/re-Date.now())),ne)}catch(c){throw T(c)?c:new p("network","The answer was cut short.")}if(i.done)return o;if(a+=i.value.length,a>ee)throw new p("protocol","The chat's answer is too large.",{status:e.status});o.push(i.value)}}catch(i){throw r.cancel().catch(()=>{}),i}}async function Q(e,t){let n=new TextDecoder,r="";for(let o of await yt(e,t))r+=n.decode(o,{stream:!0});r+=n.decode();try{return JSON.parse(r)}catch{throw new p("protocol","The chat's answer couldn't be read.",{status:e.status})}}function ne(){return new p("network","The answer stalled.")}function G(e,t){return Q(e,t)}async function M(e,t){let n="",r="";try{let o=await Q(e,t);o&&typeof o.error=="string"&&(n=o.error),o&&typeof o.message=="string"&&(r=o.message)}catch{if(t&&t.aborted)return A()}return n||(n=e.status===429?"rate_limited":e.status>=500?"internal":"protocol"),new p(n,r||"The chat refused the request ("+e.status+").",{status:e.status,retryAfter:$e(e)})}function $e(e){let t=e.headers.get("Retry-After");if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);return isNaN(r)?null:Math.max(0,Math.ceil((r-Date.now())/1e3))}function q(e,t){return new Promise((n,r)=>{if(t.aborted)return r(A());let o=()=>{clearTimeout(s),r(A())},s=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);t.addEventListener("abort",o,{once:!0})})}var tt=class extends Error{},et=class{constructor(t=4<<20){this.ut=t;this.q="";this.E="";this.Y="";this.T=!1;this.K=!1}push(t){let n=[],r=t;!this.T&&r.length>0&&(this.T=!0,r.charCodeAt(0)===65279&&(r=r.slice(1)));let o=0;this.K&&r.length>0&&(this.K=!1,r.charCodeAt(0)===10&&(o=1));for(let s=o;s<r.length;s++){let a=r.charCodeAt(s);a!==10&&a!==13||(this.Ft(this.q+r.slice(o,s),n),this.q="",a===13&&(s+1===r.length?this.K=!0:r.charCodeAt(s+1)===10&&s++),o=s+1)}if(this.q+=r.slice(o),this.q.length+this.E.length>this.ut)throw new tt("event too large");return n}Ft(t,n){if(t===""){this.E!==""&&n.push({event:this.Y||"message",data:this.E.slice(0,-1)}),this.E="",this.Y="";return}if(t.charCodeAt(0)===58)return;let r=t.indexOf(":"),o=r<0?t:t.slice(0,r),s=r<0?"":t.slice(r+1);if(s.charCodeAt(0)===32&&(s=s.slice(1)),o==="event")this.Y=s;else if(o==="data"&&(this.E+=s+`
2
- `,this.E.length>this.ut))throw new tt("event too large")}};var Ve=3e4;function z(e){return()=>e}function ie(e){for(let n of["token","tokenUrl","getToken"])if(n in e&&e[n]===void 0)throw new TypeError(n+" is undefined: omit it, or null for nobody");if([e.token,e.tokenUrl,e.getToken].filter(n=>n!==void 0).length>1)throw new TypeError("at most one of token, tokenUrl, getToken");if(e.token!==void 0)return At(e.token);if(e.tokenUrl!==void 0){if(typeof e.tokenUrl!="string"||e.tokenUrl==="")throw new TypeError("tokenUrl must be an address");return{a:"url",url:e.tokenUrl}}if(e.getToken!==void 0){if(typeof e.getToken!="function")throw new TypeError("getToken must be a function");return{a:"fn",fn:e.getToken}}return{a:"none"}}function At(e){if(e===null)return{a:"token",token:null};if(typeof e=="string"&&vt(e))return{a:"token",token:z(e)};throw new TypeError("token must be a token or null")}function vt(e){if(e==="")return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<33||n>126)return!1}return!0}function _t(e){return e.a==="url"||e.a==="fn"}async function nt(e,t,n,r){switch(e.a){case"none":return;case"token":return e.token?e.token():null;case"url":return Ye(e.url,t,n);case"fn":return Ke(e.fn,n,r)}}async function Ye(e,t,n){let r;try{r=await K(t,e,{method:"GET",headers:{Accept:"application/json"},credentials:"include",cache:"no-store"},n)}catch{throw n.aborted?A():new p("token_failed","The token couldn't be fetched.")}if(r.status===401||r.status===403)return null;if(!r.ok)throw new p("token_failed","tokenUrl answered "+r.status+".",{status:r.status});let o;try{o=await Q(r,n)}catch{throw n.aborted?A():new p("token_failed","tokenUrl didn't answer JSON.",{status:r.status})}let s=o&&typeof o=="object"?o.token:void 0;if(s===null||typeof s=="string"&&vt(s))return s;throw new p("token_failed",'tokenUrl must answer {"token": token or null}.',{status:r.status})}async function Ke(e,t,n){let r;try{let o=new Promise(s=>s(e({expired:n,signal:t})));r=await B(o,t,Ve,()=>new p("token_failed","getToken didn't answer in time."))}catch(o){throw t.aborted?A():T(o)&&o.code==="token_failed"?o:new p("token_failed","getToken failed.",{cause:o})}if(t.aborted)throw A();if(r===null||typeof r=="string"&&vt(r))return r;throw new p("token_failed","getToken must return a token or null.")}function St(e){let t=e.split(".");if(t.length!==3)return null;try{let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(n+"===".slice((n.length+3)%4)),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let s=JSON.parse(new TextDecoder().decode(o));if(!s||typeof s!="object"||typeof s.sub!="string")return null;let a=typeof s.aud=="string"?[s.aud]:Array.isArray(s.aud)?s.aud.filter(c=>typeof c=="string"):[],i=!!s.ext&&typeof s.ext=="object"&&!Array.isArray(s.ext)&&Object.keys(s.ext).length===0;return{aud:a,f:"user:"+s.sub+`
3
- `+kt(s.ext===void 0||i?null:s.ext)}}catch{return null}}function kt(e){var t;if(Array.isArray(e))return"["+e.map(kt).join(",")+"]";if(e&&typeof e=="object"){let n=e;return"{"+Object.keys(n).sort().map(r=>JSON.stringify(r)+":"+kt(n[r])).join(",")+"}"}return(t=JSON.stringify(e))!=null?t:"null"}function Ct(e){try{return new URL(e).origin}catch{return null}}var Qe=["url","token","tokenUrl","getToken","fetch","context"],tn=["conversation","message","delta","tool","done","error"],rt=["network","internal","rate_limited","overloaded","not_connected","token_failed"],en=1<<20,nn=100,ae=45e3,rn=65*6e4,it=6e4,le=12e4,ot=[2e3,3e3,5e3,8e3,1e4],on=[1e3,2e3,4e3,8e3,15e3],sn=3e3,an=1e4,ln=6e5,un=20,ue=[1e3,2e3,4e3,8e3,15e3],ce=15e3,cn=3e3,hn=10<<20,fn=/^image\/(png|jpeg|webp|gif)$/i,dn=5e3,xt={url:2048,title:512,timezone:64},Et={status:"idle",anonymous:null,conversation:null,messages:[],outgoing:null,answer:null,answering:!1,waiting:null,stop:null,error:null,files:null};function be(e){return new Mt(e)}var Mt=class{constructor(t){this.e=Et;this.z=new Set;this.u={a:"cookie"};this.f=null;this.W=!1;this.O=null;this.X=new AbortController;this.D=new AbortController;this.c=0;this.U=!1;this.h=null;this.b=null;this.A=null;this.P=0;this.ht=new Set;this.tt=!1;this.et=!1;this.g=!1;this.getState=()=>this.e;this.subscribe=t=>{if(typeof t!="function")throw new TypeError("subscribe needs a function");return this.g||this.z.add(t),this.ft(t),()=>{this.z.delete(t)}};this.open=()=>{if(this.g||this.e.status==="ready")return Promise.resolve(this.e);if(!this.O){let t=this.qt();this.O=t;let n=()=>{this.O===t&&(this.O=null)};t.then(n,n)}return this.O};this.send=(t,n)=>{if(typeof t!="string")throw new TypeError("send needs text");let r=Ot(n,["files"]).files;if(r!==void 0&&!Array.isArray(r))throw new TypeError("files must be an array");return this.zt(t,r?r.map(he):[])};this.attach=(t,n)=>{var i,c;if(!(t instanceof Blob))throw new TypeError("attach needs a Blob");let r=Ot(n,["name","onProgress","signal"]),o=r.onProgress;if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("name must be a string");if(o!==void 0&&typeof o!="function")throw new TypeError("onProgress must be a function");let s=t.size;if(s>hn)return Promise.resolve({ok:!1,error:new p("too_large","The file is too large.")});let a="/files?name="+encodeURIComponent(ye((c=(i=r.name)!=null?i:t.name)!=null?c:"")||"file");return this.dt(r.signal,async u=>{let h=this.Q;if(h===null)throw new p("attachments_off","This chat takes no files.");if(h&&s>h.maxBytes)throw new p("too_large","The file is too large.");let g={method:"POST",path:a,body:t,type:t.type||"application/octet-stream"},m=await this.pt(o?{...g,progress:w=>o(Math.min(w,s),s)}:g,u);return{ok:!0,file:ke(await G(m,u))}})};this.readFile=(t,n)=>{let r="/files/"+encodeURIComponent(he(t));return this.dt(Ot(n,["signal"]).signal,async o=>{let s=await this.pt({method:"GET",path:r},o),a=s.headers.get("Content-Type")||"";return{ok:!0,blob:new Blob(await yt(s,o),{type:fn.test(a)?a:"application/octet-stream"})}})};this.start=()=>this.Wt();this.newConversation=()=>{this.g||(this.e.status!=="ready"&&(this.U=!0),this.wt(),this.o({conversation:null,messages:[],outgoing:null,answer:null,answering:!1,waiting:null,stop:null,error:null}))};this.reopen=t=>{if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("reopen takes { token }");let n=t||{};for(let o of Object.keys(n))if(o!=="token")throw new TypeError("unknown option "+o);if("token"in n)this.w=At(n.token);else if(this.w.a==="token")throw new TypeError("reopen needs { token }, or { token: null }");if(this.g)return Promise.resolve(this.e);let r=this.e.status==="idle";return this.mt(),r?Promise.resolve(this.e):this.open()};this.signOut=async()=>{if(this.g)return;let t=this.u;this.w.a==="token"&&(this.w={a:"token",token:null}),this.mt();let n=new AbortController,r=setTimeout(()=>n.abort(),cn);try{let o=t.a==="session"?t.token():null;U(await D(this.d,this.m,{method:"DELETE",path:"/session",bearer:o,signal:n.signal}))}catch{}finally{clearTimeout(r)}};this.destroy=()=>{this.g||(this.bt(),this.g=!0,this.z.clear())};if(!t||typeof t!="object")throw new TypeError("createChat needs options");for(let r of Object.keys(t))if(Qe.indexOf(r)<0)throw new TypeError("unknown option "+r);if(typeof t.url!="string")throw new TypeError("url is required");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new TypeError("fetch must be a function");if(t.context!==void 0&&typeof t.context!="function")throw new TypeError("context must be a function");this.ct=t.context,this.m=oe(t.url),this.N=Ct(this.m),this.w=ie(t);let n=t.fetch;this.d=n?(r,o)=>n(r,o):(r,o)=>fetch(r,o)}o(t){this.e={...this.e,...t},this.tt?this.et=!0:this.nt()}nt(){if(!this.g)for(let t of Array.from(this.z))this.ft(t)}ft(t){try{t(this.e)}catch(n){setTimeout(()=>{throw n})}}_(t){for(let n of t)n.id>this.P&&(this.P=n.id)}J(t){return this.e.conversation!==null&&this.e.conversation.id===t}wt(){this.D.abort(),this.D=new AbortController,this.c++,this.h=null,this.b=null,this.A=null}bt(){this.X.abort(),this.X=new AbortController,this.O=null,this.wt()}mt(){this.bt(),this.u={a:"cookie"},this.f=null,this.U=!1,this.P=0,this.Q=this.v=void 0,this.e=Et,this.nt()}Xt(t){this.b&&this.b.abort(),this.b=null,this.c++,this.A=null,this.U=!1,this.P=0,this.e={...Et,status:"ready",files:this.e.files},this.yt(t,this.c,!1)}yt(t,n,r){if(this._(t.messages),n!==this.c){this.o({anonymous:t.anonymous});return}if(r){this.o({anonymous:t.anonymous,conversation:null,messages:[],answering:!1});return}let o=t.answering&&t.conversation!==null;this.o({anonymous:t.anonymous,conversation:t.conversation,messages:Pt(this.e.messages,t.messages),answering:o}),o&&t.conversation&&this.Jt(t.conversation.id)}kt(t){this.J(t)&&this.o({conversation:null,messages:[],answer:null,answering:!1})}async qt(){let t=this.X,n=this.c,r=Date.now();this.o({status:"opening",error:null});for(let o=0;;o++)try{let s=await this.At(t.signal);if(t.signal.aborted)return this.e;let a=this.U;return this.U=!1,this.yt(s,n,a),this.o({status:"ready",waiting:null}),this.e}catch(s){if(t.signal.aborted)return this.e;let a=F(s);if(rt.indexOf(a.code)<0||a.code==="token_failed")return this.o({status:"error",error:a,waiting:null}),this.e;let i=gn(a,o,Date.now()-r);this.o({waiting:{code:a.code,until:Date.now()+i}});try{await q(i,t.signal)}catch{return this.e}}}async At(t){let n=await nt(this.w,this.d,t,!1);if(typeof n!="string")return this.vt(n===null,t);try{return await this._t(n,t)}catch(o){if(!j(o,"token_expired")||!_t(this.w))throw o}let r=await nt(this.w,this.d,t,!0);return typeof r!="string"?this.vt(r===null,t):this._t(r,t)}async _t(t,n){if(!this.St(t))throw pe(this.N);let r=we(t);if(this.W){let s=await this.S({cookieless:!0},t,n);return this.u={a:"token",token:z(t)},this.f=r,s}let o=await this.S({},t,n);return o.T&&!await this.Ct(n)?(this.W=!0,this.u={a:"token",token:z(t)}):this.u={a:"cookie"},this.f=r,o}async vt(t,n){let r=this.u;if(r.a==="session")try{let s=await this.S({},r.token(),n);return this.f="anonymous",s}catch(s){if(!j(s,"session_expired")&&!j(s,"unauthorized"))throw s}if(this.u={a:"cookie"},this.W)return this.xt(n);t&&await this.Ht(n)&&await this.R(n);let o=await this.S({},null,n);if(t&&!o.anonymous)throw new p("protocol","Signed in, though the page says nobody is.");return o.T&&!await this.Ct(n)?(this.W=!0,this.xt(n)):(this.f=o.anonymous?"anonymous":"cookie",o)}async xt(t){let n=await this.S({cookieless:!0},null,t);if(!n.Et)throw new p("protocol","The chat gave no session token.");return this.u={a:"session",token:z(n.Et)},this.f="anonymous",n}async S(t,n,r){let o=await D(this.d,this.m,{method:"POST",path:"/session",body:t,bearer:n,signal:r});if(!o.ok)throw await M(o,r);let s=mn(await G(o,r));L(r),this.Q=s.files,this.v=s.v;let a=s.files||null;return JSON.stringify(a)!==JSON.stringify(this.e.files)&&this.o({files:a}),s}async Ct(t){let n=await D(this.d,this.m,{method:"GET",path:"/session",signal:t});if(n.ok||n.status===401)return U(n),L(t),n.ok;throw await M(n,t)}async Ht(t){let n=await D(this.d,this.m,{method:"GET",path:"/session",signal:t});if(n.status===401||n.status===403)return U(n),n.status===403;if(!n.ok)throw await M(n,t);let r=await G(n,t);return!!r&&typeof r=="object"&&r.anonymous===!1}async R(t){let n=await D(this.d,this.m,{method:"DELETE",path:"/session",signal:t});if(!n.ok)throw await M(n,t);U(n)}St(t){if((typeof location=="object"&&location?location.origin:null)===this.N)return!0;let r=St(t);return!!r&&r.aud.some(o=>Ct(o)===this.N)}Tt(){return this.u.a==="cookie"?null:this.u.token()}async H(t,n,r){for(let o=!1;;o=!0){let s=await D(this.d,this.m,{...t,bearer:this.Tt(),signal:n});if(s.status!==401||o)return s;let a=await M(s,n);if(!await this.Gt(a,n,r))throw a}}async Gt(t,n,r){if(this.u.a==="token"&&(t.code==="token_expired"||t.code==="unauthorized")){if(!_t(this.w))return!1;let s=await nt(this.w,this.d,n,t.code==="token_expired");if(typeof s=="string"&&we(s)===this.f){if(!this.St(s))throw pe(this.N);return this.u={a:"token",token:z(s)},!0}}else if(t.code!=="session_expired"&&t.code!=="unauthorized")return!1;let o=await this.rt(n);return this.o({anonymous:o.anonymous}),!0}async rt(t){L(t);let n=this.f,r=await this.At(t);if(L(t),this.f!==n)throw this.Xt(r),new p("session_expired","Someone else is signed in now.",{status:401});return this._(r.messages),r}async dt(t,n){if(this.g)return{ok:!1,error:A()};let r=new AbortController,o=()=>r.abort(),s=this.X.signal;s.addEventListener("abort",o),t&&t.addEventListener("abort",o),(s.aborted||t&&t.aborted)&&o();try{if(L(r.signal),this.e.status!=="ready"){let a=await new Promise((i,c)=>{r.signal.addEventListener("abort",()=>c(A())),this.open().then(i)});if(a.status!=="ready")throw a.error||Tt()}return await n(r.signal)}catch(a){return{ok:!1,error:r.signal.aborted?A():F(a)}}finally{s.removeEventListener("abort",o),t&&t.removeEventListener("abort",o)}}async pt(t,n){let r=Date.now()+it;for(;;){let o;try{let a=await this.H(t,n,null);if(a.ok)return a;o=await M(a,n)}catch(a){o=F(a)}let s=W(o);if(s===null||Date.now()+s>r)throw o;await q(s,n)}}async Ot(t){let n;try{n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}let r=n?{timezone:n}:{},o=this.ct;if(o&&this.v!==void 0){let a;try{a=await B(new Promise(i=>i(o())),t,dn,()=>new Error("timeout"))}catch(i){if(t.aborted)throw A();this.Pt("the option failed or took 5 s",i)}if(a!=null){let i=fe(r,a,this.v);if(typeof i!="string")return i;this.Pt(i)}}let s=fe(r,{},this.v);return typeof s=="string"?void 0:s}Pt(t,...n){this.ht.has(t)||(this.ht.add(t),console.warn("@meandr/chat-sdk: context left out: "+t,...n))}async zt(t,n){let r=pn(t);if(this.g)return{ok:!1,error:A()};if(r===""&&!n.length)return{ok:!1,error:new p("bad_request","The message is empty.")};if(this.h||this.e.answering)return{ok:!1,error:st()};let o={};this.h=o;let s=this.D,a=this.A,i=a&&a.text===r&&String(a.files)===String(n)?a:null;this.A=null;let c=-1;this.o({outgoing:r,error:null,stop:null});try{if(this.e.status!=="ready"){let g=await this.open();if(s.signal.aborted||this.h!==o)return{ok:!1,error:A()};if(g.status!=="ready")return this.M(o,s,g.error||Tt(),-1);if(this.e.answering)return this.M(o,s,st(),-1)}let u=await this.Ot(s.signal);c=this.c,this.o({answering:!0,answer:{text:"",tools:[]}});let h=await this.Zt(r,n,u,s.signal,i);return{ok:!0,message:h.message,stop:h.stop}}catch(u){return this.M(o,s,F(u),c)}finally{this.h===o&&(this.h=null)}}async Wt(){if(this.g)return{ok:!1,error:A()};if(this.h||this.e.answering)return{ok:!1,error:st()};let t={};this.h=t;let n=this.D,r=-1;this.o({error:null,stop:null});try{if(this.e.status!=="ready"){let a=await this.open();if(n.signal.aborted||this.h!==t)return{ok:!1,error:A()};if(a.status!=="ready")return this.M(t,n,a.error||Tt(),-1);if(this.e.answering)return this.M(t,n,st(),-1)}let o=await this.Ot(n.signal);r=this.c,this.o({answering:!0,answer:{text:"",tools:[]}});let s=await this.$t(n.signal,o);return{ok:!0,message:s.message,stop:s.stop}}catch(o){return this.M(t,n,F(o),r)}finally{this.h===t&&(this.h=null)}}async $t(t,n){let r={text:"",files:[],p:null,G:this.P},s={method:"POST",path:"/start",body:this.e.conversation===null?{new:!0,context:n}:{context:n},stream:!0},a=Date.now()+it,i=Date.now()+le;for(let c=0;;){let u=new AbortController,h=()=>u.abort();t.addEventListener("abort",h);try{let g;try{g=await this.H(s,u.signal,null)}catch(k){if(t.aborted)throw A();let v=T(k)?W(k):null;if(v!==null&&Date.now()+v<=a){await this.L(k.code,v,t);continue}throw k}if(g.ok)return await this.Rt(g,u,t,r);let m=await M(g,t),w=W(m);if(w!==null&&Date.now()+w<=a){await this.L(m.code,w,t);continue}if(m.code==="busy"&&Date.now()<i){await this.L("busy",ot[Math.min(c++,ot.length-1)],t);continue}throw m}finally{t.removeEventListener("abort",h)}}}M(t,n,r,o){return this.h===t&&!n.signal.aborted&&r.code!=="aborted"&&(o<0?this.o({error:r}):o===this.c?this.o({answer:null,answering:!1,waiting:null,error:r}):this.o({answer:null,waiting:null,error:r})),{ok:!1,error:r}}async Zt(t,n,r,o,s){if(s){let h=await this.ot(s,o,null);if(h!==null)return this.st(h,s,o)}let a={text:t,files:n,p:this.e.conversation?this.e.conversation.id:null,G:this.P},i=a.p===null?"/conversations":"/conversations/"+encodeURIComponent(a.p)+"/messages",c=Date.now()+it,u=Date.now()+le;for(let h=0;;){let g=new AbortController,m=()=>g.abort();o.addEventListener("abort",m);try{let w;try{w=await this.H({method:"POST",path:i,body:n.length?{text:t,files:n,context:r}:{text:t,context:r},stream:!0},g.signal,a.p)}catch(S){if(o.aborted)throw A();if(j(S,"network"))return await this.Mt(S,a,o);let P=T(S)?W(S):null;if(P!==null&&Date.now()+P<=c){await this.L(S.code,P,o);continue}throw S}if(w.ok)return await this.Rt(w,g,o,a);let k=await M(w,o);if(k.code==="internal")return await this.Mt(k,a,o);k.code==="not_found"&&a.p!==null&&this.kt(a.p);let v=W(k);if(v!==null&&Date.now()+v<=c){await this.L(k.code,v,o);continue}if(k.code==="busy"&&Date.now()<u){await this.L("busy",ot[Math.min(h++,ot.length-1)],o);continue}throw k}finally{o.removeEventListener("abort",m)}}}async L(t,n,r){L(r),this.o({waiting:{code:t,until:Date.now()+n}});try{await q(n,r)}finally{r.aborted||this.o({waiting:null})}}async Mt(t,n,r){let o=await this.ot(n,r,t);if(o===null)throw t;return this.st(o,n,r)}async ot(t,n,r){let o=this.c,s=null;for(let a of on){await q(a,n);try{return await this.Vt(t,n)}catch(i){if(n.aborted)throw A();if(s=F(i),this.c!==o)throw s;if(s.code==="not_found")return null;if(rt.indexOf(s.code)<0)break}}throw this.A=t,s&&rt.indexOf(s.code)<0?s:r||s||new p("network","The chat couldn't be reached.")}async Vt(t,n){let r=s=>ge(s,t),o=null;if(t.p!==null){let s=await this.Lt(t.p,n);s.messages.some(r)&&(o=s)}else{let s=await this.Yt(n);s.conversation&&s.messages.some(r)&&s.messages.every(a=>a.id>t.G)&&(o={conversation:s.conversation,messages:s.messages})}return L(n),o?(this._(o.messages),this.o({conversation:o.conversation,messages:Pt(this.e.messages,o.messages),outgoing:null}),o.conversation.id):null}async Yt(t){if(this.u.a==="cookie"){let n=await D(this.d,this.m,{method:"GET",path:"/session",signal:t});if(n.ok){U(n);let r=await this.S({},null,t);if(!r.T)return r}else if(n.status===401)U(n);else throw await M(n,t);return this.rt(t)}try{return await this.S(this.u.a==="token"?{cookieless:!0}:{},this.Tt(),t)}catch(n){if(!j(n,"token_expired")&&!j(n,"session_expired")&&!j(n,"unauthorized"))throw n;return this.rt(t)}}async Rt(t,n,r,o){let s=o.p,a=!1,i=t.body?t.body.getReader():null;if(i){let c=new TextDecoder,u=new et,h=()=>{i.cancel().catch(()=>{})};n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h();let g=setTimeout(()=>n.abort(),ae),m=setTimeout(()=>n.abort(),rn);try{for(;;){let{value:w,done:k}=await i.read();if(r.aborted)throw A();if(k)break;clearTimeout(g),g=setTimeout(()=>n.abort(),ae),this.tt=!0;try{for(let v of u.push(c.decode(w,{stream:!0}))){if(r.aborted)throw A();if(v.event==="message"&&a)continue;v.event==="message"&&(a=!0);let S=this.Kt(v.event,v.data);if(S)if("conversation"in S)s=S.conversation;else return S}}finally{this.tt=!1,this.et&&(this.et=!1,this.nt())}}}catch(w){if(r.aborted)throw A();if(T(w)&&w.code!=="protocol")throw w}finally{clearTimeout(g),clearTimeout(m),n.signal.removeEventListener("abort",h),h()}}if(r.aborted)throw A();return this.st(s,{...o,p:s},r)}Kt(t,n){if(tn.indexOf(t)<0)return null;let r;try{let o=JSON.parse(n);r=o&&typeof o=="object"?o:{}}catch{throw new p("protocol","The stream couldn't be read.")}switch(t){case"conversation":{let o=Lt(r);return this.e.conversation&&this.e.conversation.id===o.id?this.o({conversation:o}):this.o({conversation:o,messages:[]}),{conversation:o.id}}case"message":{let o=at(r);return this._([o]),this.o({messages:Rt(this.e.messages,o),outgoing:null}),null}case"delta":{let o=this.e.answer||{text:"",tools:[]};return typeof r.text!="string"||r.text===""||o.text.length>=en||this.o({answer:{text:o.text+r.text,tools:o.tools}}),null}case"tool":{let o=this.e.answer||{text:"",tools:[]};if(typeof r.name!="string"||typeof r.status!="string")return null;let s=wn(o.tools,r.name,r.status,typeof r.title=="string"?r.title:"");return s!==o.tools&&this.o({answer:{text:o.text,tools:s}}),null}case"done":{let o=at(r.message),s=typeof r.stop=="string"?r.stop:null;return this._([o]),this.o({messages:Rt(this.e.messages,o),outgoing:null,answer:null,answering:!1,waiting:null,stop:s}),{message:o,stop:s}}default:{let o=r.partial?at(r.partial):null;o&&this._([o]),this.o({messages:o?Rt(this.e.messages,o):this.e.messages,outgoing:null,answer:null,answering:!1});let s=typeof r.error=="string"&&r.error!==""?r.error:"unavailable";throw new p(s,typeof r.message=="string"?r.message:"The answer failed.",{status:200,partial:o})}}}async st(t,n,r){let o=n.text===""&&!n.files.length;if(t===null&&o)throw new p("network","The answer was lost.");let s=t!==null?t:await this.ot(n,r,null);if(s===null)throw this.A=n,new p("no_answer","The answer was lost.");let a=this.c,i;try{i=await this.It(s,r)}catch(u){throw!o&&!r.aborted&&!j(u,"not_found")&&a===this.c&&(this.A={...n,p:s}),u}L(r),this.J(s)&&this.o({outgoing:null,answer:null,waiting:null});let c;if(o)c=i.messages.filter(u=>u.role==="assistant"&&u.id>n.G).pop();else{let u=i.messages.length-1;for(;u>=0&&!ge(i.messages[u],n);)u--;c=u>=0?i.messages.slice(u+1).find(h=>h.role==="assistant"):void 0}if(!c)throw new p("no_answer","The assistant didn't answer.");return{message:c,stop:null}}async Lt(t,n){let r=await this.H({method:"GET",path:"/conversations/"+encodeURIComponent(t)},n,t);if(!r.ok)throw await M(r,n);return yn(await G(r,n))}async It(t,n){let r=Date.now(),o=0;for(;;){let s=Date.now()-r;if(s>=ln)throw new p("timeout","The answer took too long.");await q(s<6e4?sn:an,n);let a;try{a=await this.Lt(t,n)}catch(i){if(n.aborted)throw A();let c=F(i);if(c.code==="not_found")this.kt(t);else if(rt.indexOf(c.code)>=0&&++o<un)continue;throw c}if(o=0,L(n),!a.answering)return this.J(t)&&(this._(a.messages),this.o({conversation:a.conversation,messages:Pt(this.e.messages,a.messages),answering:!1})),a}}Jt(t){this.b&&this.b.abort();let n=new AbortController;this.b=n;let r=this.D.signal,o=()=>n.abort();r.addEventListener("abort",o,{once:!0}),this.It(t,n.signal).then(()=>{},()=>{!n.signal.aborted&&this.J(t)&&this.o({answering:!1})}).then(()=>{r.removeEventListener("abort",o),this.b===n&&(this.b=null)})}};function gn(e,t,n){let r=W(e);return n<it?r!=null?r:ue[Math.min(t,ue.length-1)]:Math.max(r!=null?r:0,ce+Math.random()*ce)}function W(e){return e.code!=="rate_limited"&&e.code!=="overloaded"&&e.code!=="not_connected"?null:(e.retryAfter===null?5:Math.min(Math.max(e.retryAfter,1),60))*1e3}function st(){return new p("busy","Still answering.")}function Tt(){return new p("unauthorized","The chat couldn't be opened.")}function Ot(e,t){if(e===void 0)return{};if(!e||typeof e!="object")throw new TypeError("options must be an object");for(let r of Object.keys(e))if(t.indexOf(r)<0)throw new TypeError("unknown option "+r);let n=e.signal;if(n!=null&&!(n instanceof AbortSignal))throw new TypeError("signal must be an AbortSignal");return e}function he(e){let t=typeof e=="string"?e:e&&e.id;if(typeof t!="string"||t==="")throw new TypeError("a file is a ChatFile or its id");return t}function fe(e,t,n){let r;try{t&&typeof t=="object"&&!Array.isArray(t)&&(r=JSON.stringify({...e,...t}))}catch{}if(!r||r[0]!=="{")return"no JSON object";let o=JSON.parse(r);for(let s in xt){let a=o[s];if(a!=null&&(typeof a!="string"||de(a)>xt[s]))return s+" must be a string of at most "+xt[s]+" bytes"}return n!==void 0&&de(r)>n?"over the chat's "+n+" bytes":r==="{}"?void 0:o}function de(e){return new TextEncoder().encode(e).length}function ge(e,t){return e.role!=="user"||e.id<=t.G?!1:t.files.length?!!e.files&&e.files.some(n=>n.id===t.files[0]):e.text===t.text}function pe(e){return new p("token_failed","The token's aud isn't "+e+".")}function L(e){if(e.aborted)throw A()}function j(e,t){return T(e)&&e.code===t}function F(e){return T(e)?e:new p("protocol",e instanceof Error?e.message:"Something went wrong.",{cause:e})}function we(e){let t=St(e);return t?t.f:"token"}function ye(e){let t="",n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?r++:(o&63488)===55296&&(t+=e.slice(n,r)+"\uFFFD",n=r+1)}return n===0?e:t+e.slice(n)}function pn(e){let t=ye(e),n=0,r=t.length;for(;n<r&&me(t.charCodeAt(n));)n++;for(;r>n&&me(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function me(e){return e>=9&&e<=13||e===32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288}function Pt(e,t){let n=new Map(e.map(r=>[r.id,r]));return t.map(r=>{let o=n.get(r.id);return o&&o.text===r.text&&o.role===r.role&&o.createdAt===r.createdAt&&String(o.tools)===String(r.tools)&&JSON.stringify(o.files)===JSON.stringify(r.files)?o:r})}function Rt(e,t){return e.some(n=>n.id===t.id)?e.map(n=>n.id===t.id?t:n):e.concat(t)}function wn(e,t,n,r){if(n!=="started"){for(let o=e.length-1;o>=0;o--)if(e[o].name===t&&e[o].status==="started")return e.slice(0,o).concat({name:t,status:n,title:r||e[o].title},e.slice(o+1))}return e.length>=nn?e:e.concat({name:t,status:n,title:r||t})}function Z(e){return new p("protocol","Unreadable "+e+" from the chat.")}function Lt(e){var n,r;let t=e;if(!t||typeof t!="object"||typeof t.id!="string")throw Z("conversation");return{id:t.id,createdAt:String((n=t.created_at)!=null?n:""),updatedAt:String((r=t.updated_at)!=null?r:"")}}function at(e){var r;let t=e;if(!t||typeof t!="object"||typeof t.id!="number"||typeof t.text!="string"||t.role!=="user"&&t.role!=="assistant")throw Z("message");let n={id:t.id,role:t.role,text:t.text,createdAt:String((r=t.created_at)!=null?r:"")};if(Array.isArray(t.tools)){let o=t.tools.filter(a=>typeof a=="string"),s=t.tool_titles&&typeof t.tool_titles=="object"?t.tool_titles:{};n.tools=o,n.toolTitles=Object.fromEntries(o.map(a=>{let i=s[a];return[a,typeof i=="string"&&i?i:a]}))}return Array.isArray(t.files)&&(n.files=t.files.filter(o=>o&&typeof o.id=="string").map(ke)),n}function ke(e){var r,o,s;let t=e;if(!t||typeof t!="object"||typeof t.id!="string")throw Z("file");let n=typeof t.size=="number"?t.size:0;return{id:t.id,name:String((r=t.name)!=null?r:""),type:String((o=t.type)!=null?o:""),size:n,createdAt:String((s=t.created_at)!=null?s:"")}}function Ae(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&(t.role==="user"||t.role==="assistant")).map(at):[]}function mn(e){let t=e;if(!t||typeof t!="object")throw Z("session");return{anonymous:t.anonymous===!0,T:t.started===!0,conversation:t.conversation?Lt(t.conversation):null,messages:Ae(t.messages),answering:t.answering===!0,Et:typeof t.session_token=="string"&&t.session_token!==""?t.session_token:null,files:bn(t.files),v:typeof t.context_max_bytes=="number"?t.context_max_bytes:void 0}}function bn(e){let t=e;if(t===null)return null;if(!(!t||typeof t!="object"||!Array.isArray(t.types)||typeof t.max_bytes!="number"||typeof t.per_message!="number"))return{types:t.types.filter(n=>typeof n=="string"),maxBytes:t.max_bytes,perMessage:t.per_message}}function yn(e){let t=e;if(!t||typeof t!="object")throw Z("conversation");return{conversation:Lt(t.conversation),messages:Ae(t.messages),answering:t.answering===!0}}var kn="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",ve=/[\p{P}\p{S}]/u,qt=/\s/,An=/^[A-Za-z0-9_+-]+$/,Ee=/[A-Za-z0-9]/,vn=/[0-9A-Fa-f]/,_n=/[0-9]/;var Te="\u2800\u3164\u115F\u1160\uFFA0",_e=new RegExp("[\\s\\p{Default_Ignorable_Code_Point}"+Te+"]","u"),Sn=new RegExp("[\\s\\p{Cc}\\p{Default_Ignorable_Code_Point}"+Te+"]","gu"),It="\u200C",Nt="\u200D",Se=new RegExp("[\uFE00-\uFE0F"+String.fromCodePoint(917760)+"-"+String.fromCodePoint(917999)+"]","u"),Oe=/^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])$/,Cn=new RegExp("[\u202A-\u202E\u2066-\u2069]","g"),zt={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Dt="nbsp a0 mdash 2014 ndash 2013 hellip 2026 copy a9 reg ae trade 2122 laquo ab raquo bb lsquo 2018 rsquo 2019 ldquo 201c rdquo 201d times d7 euro 20ac pound a3 yen a5 deg b0 middot b7 bull 2022".split(" ");for(let e=0;e<Dt.length;e+=2)zt[Dt[e]]=String.fromCharCode(parseInt(Dt[e+1],16));var N=0,Wt=1,X=2,V=3,Pe=4,mt=5;function Zt(e){let t=String(e==null?"":e).replace(/\r\n?/g,`
1
+ "use strict";var MeandrChat=(()=>{var vt=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Je=(n,t)=>{for(var e in t)vt(n,e,{get:t[e],enumerable:!0})},He=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of We(t))!Xe.call(n,o)&&o!==e&&vt(n,o,{get:()=>t[o],enumerable:!(r=ze(t,o))||r.enumerable});return n};var Ge=n=>He(vt({},"__esModule",{value:!0}),n);var qn={};Je(qn,{ChatError:()=>w,createChat:()=>ve,isChatError:()=>O,parseMarkdown:()=>Zt,renderMarkdown:()=>Ie});var Ze=new Set(["busy","rate_limited","overloaded","not_connected","interrupted","timeout","unavailable","model_busy","no_answer","network","internal","token_failed"]),w=class extends Error{constructor(t,e,r={}){var o,s,a;super(e),this.name="ChatError",this.code=t,this.status=(o=r.status)!=null?o:0,this.retryAfter=(s=r.retryAfter)!=null?s:null,this.partial=(a=r.partial)!=null?a:null,r.cause!==void 0&&(this.cause=r.cause)}get retryable(){return Ze.has(this.code)}};function O(n){return n instanceof w||!!n&&typeof n=="object"&&n.name==="ChatError"&&typeof n.code=="string"}var $e=/^(localhost|127\.0\.0\.1|\[::1\])$/,Z=3e4,ee=16<<20,Ve=18e4,re=32;function oe(n){let t;try{t=new URL(n)}catch{throw new TypeError("url must be an absolute URL")}if(t.protocol!=="https:"&&!(t.protocol==="http:"&&$e.test(t.hostname)))throw new TypeError("url must be an https: URL");if(t.username||t.password)throw new TypeError("url must not carry credentials");return t.origin+t.pathname.replace(/\/+$/,"")+"/chat/v1"}function k(){return new w("aborted","Cut short by the page.")}function F(n,t,e,r){return new Promise((o,s)=>{if(t&&t.aborted)return s(k());let a=()=>{clearTimeout(c),t&&t.removeEventListener("abort",i)},i=()=>{a(),s(k())},c=setTimeout(()=>{a(),s(r())},e);t&&t.addEventListener("abort",i,{once:!0}),n.then(l=>{a(),o(l)},l=>{a(),s(l)})})}async function nt(n,t,e,r,o=Z){if(r&&r.aborted)throw k();let s=new AbortController,a=new Promise((i,c)=>{try{n(t,{...e,signal:s.signal}).then(i,c)}catch(l){c(l)}});try{return await F(a,r,o,se)}catch(i){throw s.abort(),a.then(M,()=>{}),O(i)?i:new w("network","Couldn't connect.")}}function N(n,t,e){let r={Accept:e.stream?"text/event-stream":"application/json"};e.body!==void 0&&(r["Content-Type"]=e.type||"application/json"),e.bearer&&(r.Authorization="Bearer "+e.bearer);let o={method:e.method,headers:r,credentials:"include",cache:"no-store",redirect:"error"};return e.keepalive&&(o.keepalive=!0),e.body!==void 0&&(o.body=e.type?e.body:JSON.stringify(e.body)),e.type?e.progress&&typeof XMLHttpRequest=="function"?Ye(t+e.path,o,e.progress,e.signal):nt(n,t+e.path,o,e.signal,Z+e.body.size/re):nt(n,t+e.path,o,e.signal)}function Ye(n,t,e,r){return new Promise((o,s)=>{if(r&&r.aborted)return s(k());let a=new XMLHttpRequest,i,c=p=>{clearTimeout(i),r&&r.removeEventListener("abort",l),p&&(a.abort(),s(p))},l=()=>c(k()),h=()=>{clearTimeout(i),i=setTimeout(()=>c(se()),Z)};a.open(t.method,n),a.withCredentials=!0;let g=t.headers;for(let p in g)a.setRequestHeader(p,g[p]);a.upload.onprogress=p=>{h(),e(p.loaded)},a.onprogress=h,a.onerror=()=>c(new w("network","Couldn't connect.")),a.onload=()=>{c();try{o(new Response(a.responseText,{status:a.status,headers:{"Retry-After":a.getResponseHeader("Retry-After")||""}}))}catch{s(new w("protocol","The chat's answer couldn't be read.",{status:a.status}))}},r&&r.addEventListener("abort",l,{once:!0}),h(),a.send(t.body)})}function se(){return new w("network","No answer came in time.")}function M(n){n.body&&!n.body.locked&&n.body.cancel().catch(()=>{})}async function At(n,t){let e=n.body;if(!e){let i;try{i=await F(n.arrayBuffer(),t,Z,ne)}catch(c){throw O(c)?c:new w("network","The answer was cut short.")}if(i.byteLength>ee)throw new w("protocol","The chat's answer is too large.",{status:n.status});return[new Uint8Array(i)]}let r=e.getReader(),o=[],s=Date.now(),a=0;try{for(;;){let i;try{i=await F(r.read(),t,Math.max(0,Math.min(Z,s+Ve+a/re-Date.now())),ne)}catch(c){throw O(c)?c:new w("network","The answer was cut short.")}if(i.done)return o;if(a+=i.value.length,a>ee)throw new w("protocol","The chat's answer is too large.",{status:n.status});o.push(i.value)}}catch(i){throw r.cancel().catch(()=>{}),i}}async function rt(n,t){let e=new TextDecoder,r="";for(let o of await At(n,t))r+=e.decode(o,{stream:!0});r+=e.decode();try{return JSON.parse(r)}catch{throw new w("protocol","The chat's answer couldn't be read.",{status:n.status})}}function ne(){return new w("network","The answer stalled.")}function q(n,t){return rt(n,t)}async function L(n,t){let e="",r="";try{let o=await rt(n,t);o&&typeof o.error=="string"&&(e=o.error),o&&typeof o.message=="string"&&(r=o.message)}catch{if(t&&t.aborted)return k()}return e||(e=n.status===429?"rate_limited":n.status>=500?"internal":"protocol"),new w(e,r||"The chat refused the request ("+n.status+").",{status:n.status,retryAfter:Ke(n)})}function Ke(n){let t=n.headers.get("Retry-After");if(!t)return null;let e=t.trim();if(/^\d+$/.test(e))return Number(e);let r=Date.parse(e);return isNaN(r)?null:Math.max(0,Math.ceil((r-Date.now())/1e3))}function z(n,t){return new Promise((e,r)=>{if(t.aborted)return r(k());let o=()=>{clearTimeout(s),r(k())},s=setTimeout(()=>{t.removeEventListener("abort",o),e()},n);t.addEventListener("abort",o,{once:!0})})}var ot=class extends Error{},st=class{constructor(t=4<<20){this.St=t;this.Y="";this.I="";this.ut="";this.N=!1;this.ct=!1}push(t){let e=[],r=t;!this.N&&r.length>0&&(this.N=!0,r.charCodeAt(0)===65279&&(r=r.slice(1)));let o=0;this.ct&&r.length>0&&(this.ct=!1,r.charCodeAt(0)===10&&(o=1));for(let s=o;s<r.length;s++){let a=r.charCodeAt(s);a!==10&&a!==13||(this.re(this.Y+r.slice(o,s),e),this.Y="",a===13&&(s+1===r.length?this.ct=!0:r.charCodeAt(s+1)===10&&s++),o=s+1)}if(this.Y+=r.slice(o),this.Y.length+this.I.length>this.St)throw new ot("event too large");return e}re(t,e){if(t===""){this.I!==""&&e.push({event:this.ut||"message",data:this.I.slice(0,-1)}),this.I="",this.ut="";return}if(t.charCodeAt(0)===58)return;let r=t.indexOf(":"),o=r<0?t:t.slice(0,r),s=r<0?"":t.slice(r+1);if(s.charCodeAt(0)===32&&(s=s.slice(1)),o==="event")this.ut=s;else if(o==="data"&&(this.I+=s+`
2
+ `,this.I.length>this.St))throw new ot("event too large")}};var Qe=3e4;function W(n){return()=>n}function ie(n){for(let e of["token","tokenUrl","getToken"])if(e in n&&n[e]===void 0)throw new TypeError(e+" is undefined: omit it, or null for nobody");if([n.token,n.tokenUrl,n.getToken].filter(e=>e!==void 0).length>1)throw new TypeError("at most one of token, tokenUrl, getToken");if(n.token!==void 0)return Ct(n.token);if(n.tokenUrl!==void 0){if(typeof n.tokenUrl!="string"||n.tokenUrl==="")throw new TypeError("tokenUrl must be an address");return{a:"url",url:n.tokenUrl}}if(n.getToken!==void 0){if(typeof n.getToken!="function")throw new TypeError("getToken must be a function");return{a:"fn",fn:n.getToken}}return{a:"none"}}function Ct(n){if(n===null)return{a:"token",token:null};if(typeof n=="string"&&St(n))return{a:"token",token:W(n)};throw new TypeError("token must be a token or null")}function St(n){if(n==="")return!1;for(let t=0;t<n.length;t++){let e=n.charCodeAt(t);if(e<33||e>126)return!1}return!0}function xt(n){return n.a==="url"||n.a==="fn"}async function it(n,t,e,r){switch(n.a){case"none":return;case"token":return n.token?n.token():null;case"url":return tn(n.url,t,e);case"fn":return en(n.fn,e,r)}}async function tn(n,t,e){let r;try{r=await nt(t,n,{method:"GET",headers:{Accept:"application/json"},credentials:"include",cache:"no-store"},e)}catch{throw e.aborted?k():new w("token_failed","The token couldn't be fetched.")}if(r.status===401||r.status===403)return null;if(!r.ok)throw new w("token_failed","tokenUrl answered "+r.status+".",{status:r.status});let o;try{o=await rt(r,e)}catch{throw e.aborted?k():new w("token_failed","tokenUrl didn't answer JSON.",{status:r.status})}let s=o&&typeof o=="object"?o.token:void 0;if(s===null||typeof s=="string"&&St(s))return s;throw new w("token_failed",'tokenUrl must answer {"token": token or null}.',{status:r.status})}async function en(n,t,e){let r;try{let o=new Promise(s=>s(n({expired:e,signal:t})));r=await F(o,t,Qe,()=>new w("token_failed","getToken didn't answer in time."))}catch(o){throw t.aborted?k():O(o)&&o.code==="token_failed"?o:new w("token_failed","getToken failed.",{cause:o})}if(t.aborted)throw k();if(r===null||typeof r=="string"&&St(r))return r;throw new w("token_failed","getToken must return a token or null.")}function Et(n){let t=n.split(".");if(t.length!==3)return null;try{let e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(e+"===".slice((e.length+3)%4)),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);let s=JSON.parse(new TextDecoder().decode(o));if(!s||typeof s!="object"||typeof s.sub!="string")return null;let a=typeof s.aud=="string"?[s.aud]:Array.isArray(s.aud)?s.aud.filter(c=>typeof c=="string"):[],i=!!s.ext&&typeof s.ext=="object"&&!Array.isArray(s.ext)&&Object.keys(s.ext).length===0;return{aud:a,g:"user:"+s.sub+`
3
+ `+_t(s.ext===void 0||i?null:s.ext)}}catch{return null}}function _t(n){var t;if(Array.isArray(n))return"["+n.map(_t).join(",")+"]";if(n&&typeof n=="object"){let e=n;return"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+_t(e[r])).join(",")+"}"}return(t=JSON.stringify(n))!=null?t:"null"}function Tt(n){try{return new URL(n).origin}catch{return null}}var nn=["url","token","tokenUrl","getToken","fetch","context"],rn=["conversation","message","delta","tool","done","error"],$=["network","internal","rate_limited","overloaded","not_connected","token_failed"],on=1<<20,sn=100,ae=45e3,an=65*6e4,Y=6e4,le=12e4,at=[2e3,3e3,5e3,8e3,1e4],ln=[1e3,2e3,4e3,8e3,15e3],un=3e3,cn=1e4,hn=6e5,fn=20,ue=[1e3,2e3,4e3,8e3,15e3],ce=15e3,dn=3e3,gn=10<<20,pn=/^image\/(png|jpeg|webp|gif)$/i,wn=5e3,Ot={url:2048,title:512,timezone:64},Pt={status:"idle",anonymous:null,conversation:null,messages:[],hasOlder:!1,outgoing:null,answer:null,answering:!1,waiting:null,stop:null,error:null,files:null,conversationList:null};function ve(n){return new Mt(n)}var Mt=class{constructor(t){this.e=Pt;this.K=new Set;this.u={a:"cookie"};this.g=null;this.Q=!1;this.S=null;this.b=new AbortController;this.x=new AbortController;this.c=0;this.W=!1;this.X=!1;this.tt=0;this.J=null;this.f=null;this.y=null;this.H=null;this.E=null;this.D=0;this.Tt=new Set;this.ft=!1;this.dt=!1;this.p=!1;this.getState=()=>this.e;this.subscribe=t=>{if(typeof t!="function")throw new TypeError("subscribe needs a function");return this.p||this.K.add(t),this.Ot(t),()=>{this.K.delete(t)}};this.open=()=>{if(this.p||this.e.status==="ready")return Promise.resolve(this.e);if(!this.S){let t=this.oe();this.S=t;let e=()=>{this.S===t&&(this.S=null)};t.then(e,e)}return this.S};this.send=(t,e)=>{if(typeof t!="string")throw new TypeError("send needs text");let r=ut(e,["files"]).files;if(r!==void 0&&!Array.isArray(r))throw new TypeError("files must be an array");return this.se(t,r?r.map(V):[])};this.attach=(t,e)=>{var i,c;if(!(t instanceof Blob))throw new TypeError("attach needs a Blob");let r=ut(e,["name","onProgress","signal"]),o=r.onProgress;if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("name must be a string");if(o!==void 0&&typeof o!="function")throw new TypeError("onProgress must be a function");let s=t.size;if(s>gn)return Promise.resolve({ok:!1,error:new w("too_large","The file is too large.")});let a="/files?name="+encodeURIComponent(Ae((c=(i=r.name)!=null?i:t.name)!=null?c:"")||"file");return this.U(r.signal,async l=>{let h=this.ht;if(h===null)throw new w("attachments_off","This chat takes no files.");if(h&&s>h.maxBytes)throw new w("too_large","The file is too large.");let g={method:"POST",path:a,body:t,type:t.type||"application/octet-stream"},p=await this.G(o?{...g,progress:m=>o(Math.min(m,s),s)}:g,l);return{ok:!0,file:_e(await q(p,l))}})};this.readFile=(t,e)=>{let r="/files/"+encodeURIComponent(V(t));return this.U(ut(e,["signal"]).signal,async o=>{let s=await this.G({method:"GET",path:r},o),a=s.headers.get("Content-Type")||"";return{ok:!0,blob:new Blob(await At(s,o),{type:pn.test(a)?a:"application/octet-stream"})}})};this.start=()=>this.ie();this.endConversation=()=>{if(this.p)return Promise.resolve();let t=this.e.conversation,e=t?null:this.J,r=this.S;this.e.status!=="ready"&&(this.X=!0);let o=e&&new Promise(s=>e.O=s);return this.J=null,this.Pt(),t?this.pt(t.id):o||(r?r.then(s=>s.status==="ready"?this.xt:void 0):Promise.resolve())};this.newConversation=()=>{this.endConversation()};this.listConversations=t=>{let e=ut(t,["before","signal"]),r="/conversations"+(e.before===void 0?"":"?before="+encodeURIComponent(V(e.before)));return this.U(e.signal,async o=>{if(this.e.conversationList===!1)throw fe();let s=await q(await this.G({method:"GET",path:r},o),o);if(!s||!Array.isArray(s.conversations))throw J("list");return{ok:!0,conversations:s.conversations.map(a=>K(a,!0)),hasMore:s.has_more===!0}})};this.openConversation=t=>{let e=V(t);this.e.status!=="ready"&&(this.W=!0);let r=++this.tt,o=this.c;return this.U(this.x.signal,async s=>{let a=await this.Rt(e,s);if(r!==this.tt||o!==this.c)throw k();return this.wt(),this.v(a.messages),this.r({...this.et(a.conversation,a.messages,a.A),outgoing:null,answer:null,answering:a.answering,waiting:null,stop:null,error:null}),a.answering&&this.Lt(a.conversation.id),{ok:!0,conversation:a.conversation}})};this.deleteConversation=t=>{let e=V(t);return this.U(null,async r=>{if(this.e.conversationList===!1)throw fe();try{M(await this.G({method:"DELETE",path:"/conversations/"+encodeURIComponent(e)},r))}catch(o){if(!I(o,"not_found"))throw o}return this.P(e)&&this.Pt(),{ok:!0}})};this.loadOlder=()=>{let{conversation:t,messages:e,hasOlder:r}=this.e,o=e[0];if(!t||!o||!r)return Promise.resolve({ok:!0,messages:[]});let s=this.H;if(s&&s.ae===o)return s.Mt;let a=this.U(this.x.signal,async i=>{let c=await this.Rt(t.id,i,o.id),l=this.e.messages;if(l[0]!==o)throw k();let h=c.messages.filter(g=>g.id<o.id);return this.r({messages:h.concat(l),hasOlder:c.A&&h.length>0}),{ok:!0,messages:h}});return this.H={ae:o,Mt:a},a.then(()=>{this.H&&this.H.Mt===a&&(this.H=null)}),a};this.reopen=t=>{if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("reopen takes { token }");let e=t||{};for(let o of Object.keys(e))if(o!=="token")throw new TypeError("unknown option "+o);if("token"in e)this.m=Ct(e.token);else if(this.m.a==="token")throw new TypeError("reopen needs { token }, or { token: null }");if(this.p)return Promise.resolve(this.e);let r=this.e.status==="idle";return this.It(),r?Promise.resolve(this.e):this.open()};this.signOut=async()=>{if(this.p)return;let t=this.u;this.m.a==="token"&&(this.m={a:"token",token:null}),this.It();let e=new AbortController,r=setTimeout(()=>e.abort(),dn);try{let o=t.a==="session"?t.token():null;M(await N(this.h,this.w,{method:"DELETE",path:"/session",bearer:o,signal:e.signal}))}catch{}finally{clearTimeout(r)}};this.destroy=()=>{this.p||(this.Nt(),this.p=!0,this.K.clear())};if(!t||typeof t!="object")throw new TypeError("createChat needs options");for(let r of Object.keys(t))if(nn.indexOf(r)<0)throw new TypeError("unknown option "+r);if(typeof t.url!="string")throw new TypeError("url is required");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new TypeError("fetch must be a function");if(t.context!==void 0&&typeof t.context!="function")throw new TypeError("context must be a function");this.Et=t.context,this.w=oe(t.url),this.z=Tt(this.w),this.m=ie(t);let e=t.fetch;this.h=e?(r,o)=>e(r,o):(r,o)=>fetch(r,o)}r(t){this.e={...this.e,...t},this.ft?this.dt=!0:this.mt()}mt(){if(!this.p)for(let t of Array.from(this.K))this.Ot(t)}Ot(t){try{t(this.e)}catch(e){setTimeout(()=>{throw e})}}v(t){for(let e of t)e.id>this.D&&(this.D=e.id)}P(t){return this.e.conversation!==null&&this.e.conversation.id===t}wt(){this.x.abort(),this.x=new AbortController,this.c++,this.f=null,this.y=null,this.E=null}Pt(){this.wt(),this.r({conversation:null,messages:[],hasOlder:!1,outgoing:null,answer:null,answering:!1,waiting:null,stop:null,error:null})}_(t){t&&this.J===t&&(this.J=null)}nt(t){return!!t&&!!t.O&&!t.b.aborted}Nt(){this.b.abort(),this.b=new AbortController,this.S=null,this.wt()}It(){this.Nt(),this.u={a:"cookie"},this.g=null,this.W=this.X=!1,this.D=0,this.ht=this.T=void 0,this.e=Pt,this.mt()}le(t){this.y&&this.y.abort(),this.y=null,this.c++,this.E=null,this.W=this.X=!1,this.D=0;let e=this.e;this.e={...Pt,status:"ready",files:e.files,conversationList:e.conversationList},this.Dt(t,this.c,!1)}Dt(t,e,r){if(this.v(t.messages),e!==this.c){this.r({anonymous:t.anonymous});return}let o=t.conversation;if(r||!o){this.r({anonymous:t.anonymous,conversation:null,messages:[],hasOlder:!1,answering:!1});return}this.r({anonymous:t.anonymous,...this.et(o,t.messages,t.A),answering:t.answering}),t.answering&&this.Lt(o.id)}et(t,e,r){let o=this.e.messages,s=this.P(t.id)&&e.length?o.findIndex(i=>i.id===e[0].id):-1,a=bn(o,e);return s<0?{conversation:t,messages:a,hasOlder:r}:{conversation:t,messages:o.slice(0,s).concat(a)}}bt(t,e){return I(e,"not_found")&&this.P(t)&&this.r({conversation:null,messages:[],hasOlder:!1,answer:null,answering:!1}),e}async oe(){let t=this.b,e=this.c,r=Date.now();this.r({status:"opening",error:null});for(let o=0;;o++)try{let s=await this.Ut(t.signal);if(t.signal.aborted)return this.e;let a=this.X,i=a||this.W;return this.W=this.X=!1,this.Dt(s,e,i),this.r({status:"ready",waiting:null}),this.xt=a&&s.conversation?this.pt(s.conversation.id):void 0,this.e}catch(s){if(t.signal.aborted)return this.e;let a=B(s);if($.indexOf(a.code)<0||a.code==="token_failed")return this.r({status:"error",error:a,waiting:null}),this.e;let i=he(a,o,Date.now()-r);this.r({waiting:{code:a.code,until:Date.now()+i}});try{await z(i,t.signal)}catch{return this.e}}}async Ut(t){let e=await it(this.m,this.h,t,!1);if(typeof e!="string")return this.jt(e===null,t);try{return await this.Bt(e,t)}catch(o){if(!I(o,"token_expired")||!xt(this.m))throw o}let r=await it(this.m,this.h,t,!0);return typeof r!="string"?this.jt(r===null,t):this.Bt(r,t)}async Bt(t,e){if(!this.Ft(t))throw we(this.z);let r=be(t);if(this.Q){let s=await this.R({cookieless:!0},t,e);return this.u={a:"token",token:W(t)},this.g=r,s}let o=await this.R({},t,e);return o.N&&!await this.qt(e)?(this.Q=!0,this.u={a:"token",token:W(t)}):this.u={a:"cookie"},this.g=r,o}async jt(t,e){let r=this.u;if(r.a==="session")try{let s=await this.R({},r.token(),e);return this.g="anonymous",s}catch(s){if(!I(s,"session_expired")&&!I(s,"unauthorized"))throw s}if(this.u={a:"cookie"},this.Q)return this.zt(e);t&&await this.ue(e)&&await this.j(e);let o=await this.R({},null,e);if(t&&!o.anonymous)throw new w("protocol","Signed in, though the page says nobody is.");return o.N&&!await this.qt(e)?(this.Q=!0,this.zt(e)):(this.g=o.anonymous?"anonymous":"cookie",o)}async zt(t){let e=await this.R({cookieless:!0},null,t);if(!e.Wt)throw new w("protocol","The chat gave no session token.");return this.u={a:"session",token:W(e.Wt)},this.g="anonymous",e}async R(t,e,r){let o=await N(this.h,this.w,{method:"POST",path:"/session",body:t,bearer:e,signal:r});if(!o.ok)throw await L(o,r);let s=kn(await q(o,r));D(r),this.ht=s.files,this.T=s.T;let a=s.files||null;return JSON.stringify(a)!==JSON.stringify(this.e.files)&&this.r({files:a}),s.Xt!==this.e.conversationList&&this.r({conversationList:s.Xt}),s}async qt(t){let e=await N(this.h,this.w,{method:"GET",path:"/session",signal:t});if(e.ok||e.status===401)return M(e),D(t),e.ok;throw await L(e,t)}async ue(t){let e=await N(this.h,this.w,{method:"GET",path:"/session",signal:t});if(e.status===401||e.status===403)return M(e),e.status===403;if(!e.ok)throw await L(e,t);let r=await q(e,t);return!!r&&typeof r=="object"&&r.anonymous===!1}async j(t){let e=await N(this.h,this.w,{method:"DELETE",path:"/session",signal:t});if(!e.ok)throw await L(e,t);M(e)}Ft(t){if((typeof location=="object"&&location?location.origin:null)===this.z)return!0;let r=Et(t);return!!r&&r.aud.some(o=>Tt(o)===this.z)}yt(){return this.u.a==="cookie"?null:this.u.token()}async rt(t,e,r,o){for(let s=!1;;s=!0){o&&(this.J=o);let a=await N(this.h,this.w,{...t,bearer:this.yt(),signal:e});if(a.status!==401||s||o&&o.O)return a;this._(o);let i=await L(a,e);if(!await this.Jt(i,e,r))throw i}}async Jt(t,e,r){if(this.u.a==="token"&&(t.code==="token_expired"||t.code==="unauthorized")){if(!xt(this.m))return!1;let s=await it(this.m,this.h,e,t.code==="token_expired");if(typeof s=="string"&&be(s)===this.g){if(!this.Ft(s))throw we(this.z);return this.u={a:"token",token:W(s)},!0}}else if(t.code!=="session_expired"&&t.code!=="unauthorized")return!1;let o=await this.kt(e);return this.r({anonymous:o.anonymous}),!0}async kt(t){D(t);let e=this.g,r=await this.Ut(t);if(D(t),this.g!==e)throw this.le(r),new w("session_expired","Someone else is signed in now.",{status:401});return this.v(r.messages),r}async U(t,e){if(this.p)return{ok:!1,error:k()};let r=new AbortController,o=()=>r.abort(),s=this.b.signal;s.addEventListener("abort",o),t&&t.addEventListener("abort",o),(s.aborted||t&&t.aborted)&&o();try{if(D(r.signal),this.e.status!=="ready"){let a=await new Promise((i,c)=>{r.signal.addEventListener("abort",()=>c(k())),this.open().then(i)});if(a.status!=="ready")throw a.error||Rt()}return await e(r.signal)}catch(a){return{ok:!1,error:r.signal.aborted?k():B(a)}}finally{s.removeEventListener("abort",o),t&&t.removeEventListener("abort",o)}}async G(t,e){let r=Date.now()+Y;for(;;){let o;try{let a=await this.rt(t,e,null);if(a.ok)return a;o=await L(a,e)}catch(a){o=B(a)}let s=X(o);if(s===null||Date.now()+s>r)throw o;await z(s,e)}}async pt(t){let e=this.b.signal,r=Date.now()+Y,o="/conversations/"+encodeURIComponent(t)+"/end";for(let s=0,a=!1;;s++){let i;try{let l=await N(this.h,this.w,{method:"POST",path:o,bearer:this.yt(),keepalive:!0});if(l.ok||l.status===404)return M(l);if(i=await L(l),l.status===401&&!a&&!e.aborted&&(a=!0,await this.Jt(i,e,t)))continue}catch(l){i=B(l)}let c=$.indexOf(i.code)<0?null:he(i,s,0);if(c===null||Date.now()+c>r)return;try{await z(c,e)}catch{return}}}async Ht(t){let e;try{e=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}let r=e?{timezone:e}:{},o=this.Et;if(o&&this.T!==void 0){let a;try{a=await F(new Promise(i=>i(o())),t,wn,()=>new Error("timeout"))}catch(i){if(t.aborted)throw k();this.Gt("the option failed or took 5 s",i)}if(a!=null){let i=de(r,a,this.T);if(typeof i!="string")return i;this.Gt(i)}}let s=de(r,{},this.T);return typeof s=="string"?void 0:s}Gt(t,...e){this.Tt.has(t)||(this.Tt.add(t),console.warn("@meandr/chat-sdk: context left out: "+t,...e))}async se(t,e){let r=mn(t);if(this.p)return{ok:!1,error:k()};if(r===""&&!e.length)return{ok:!1,error:new w("bad_request","The message is empty.")};if(this.f||this.e.answering)return{ok:!1,error:lt()};let o={};this.f=o,this.tt++;let s=this.x,a=this.E,i=a&&a.text===r&&String(a.files)===String(e)?a:null;this.E=null;let c=-1;this.r({outgoing:r,error:null,stop:null});try{if(this.e.status!=="ready"){let g=await this.open();if(s.signal.aborted||this.f!==o)return{ok:!1,error:k()};if(g.status!=="ready")return this.B(o,s,g.error||Rt(),-1);if(this.e.answering)return this.B(o,s,lt(),-1)}let l=await this.Ht(s.signal);c=this.c,this.r({answering:!0,answer:{text:"",tools:[]}});let h=await me(this.ce(r,e,l,s.signal,i),s.signal);return{ok:!0,message:h.message,stop:h.stop}}catch(l){return this.B(o,s,B(l),c)}finally{this.f===o&&(this.f=null)}}async ie(){if(this.p)return{ok:!1,error:k()};if(this.f||this.e.answering)return{ok:!1,error:lt()};let t={};this.f=t,this.tt++;let e=this.x,r=-1;this.r({error:null,stop:null});try{if(this.e.status!=="ready"){let a=await this.open();if(e.signal.aborted||this.f!==t)return{ok:!1,error:k()};if(a.status!=="ready")return this.B(t,e,a.error||Rt(),-1);if(this.e.answering)return this.B(t,e,lt(),-1)}let o=await this.Ht(e.signal);r=this.c,this.r({answering:!0,answer:{text:"",tools:[]}});let s=await me(this.he(e.signal,o),e.signal);return{ok:!0,message:s.message,stop:s.stop}}catch(o){return this.B(t,e,B(o),r)}finally{this.f===t&&(this.f=null)}}async he(t,e){let r={text:"",files:[],d:null,ot:this.D},o=this.e.conversation===null,s={method:"POST",path:"/start",body:o?{new:!0,context:e}:{context:e},stream:!0},a=Date.now()+Y,i=Date.now()+le;for(let c=0;;){let l=new AbortController,h=o?{b:this.b.signal}:null,g=()=>{this.nt(h)||l.abort()};t.addEventListener("abort",g);try{let p;try{p=await this.rt(s,l.signal,null,h)}catch(A){if(this._(h),t.aborted)throw k();let _=O(A)?X(A):null;if(_!==null&&Date.now()+_<=a){await this.F(A.code,_,t);continue}throw A}if(p.ok)return await this.Zt(p,l,t,r,h);this._(h);let m=await L(p,t),v=X(m);if(v!==null&&Date.now()+v<=a){await this.F(m.code,v,t);continue}if(m.code==="busy"&&Date.now()<i){await this.F("busy",at[Math.min(c++,at.length-1)],t);continue}throw m}finally{t.removeEventListener("abort",g),this._(h),h&&h.O&&h.O()}}}B(t,e,r,o){return this.f===t&&!e.signal.aborted&&r.code!=="aborted"&&(o<0?this.r({error:r}):o===this.c?this.r({answer:null,answering:!1,waiting:null,error:r}):this.r({answer:null,waiting:null,error:r})),{ok:!1,error:r}}async ce(t,e,r,o,s){if(s){let h=await this.vt(s,o,null);if(h!==null)return this.At(h,s,o)}let a={text:t,files:e,d:this.e.conversation?this.e.conversation.id:null,ot:this.D},i=a.d===null?"/conversations":"/conversations/"+encodeURIComponent(a.d)+"/messages",c=Date.now()+Y,l=Date.now()+le;for(let h=0;;){let g=new AbortController,p=a.d===null?{b:this.b.signal}:null,m=()=>{this.nt(p)||g.abort()};o.addEventListener("abort",m);try{let v;try{v=await this.rt({method:"POST",path:i,body:e.length?{text:t,files:e,context:r}:{text:t,context:r},stream:!0},g.signal,a.d,p)}catch(S){if(this._(p),o.aborted)throw k();if(I(S,"network"))return await this.$t(S,a,o);let d=O(S)?X(S):null;if(d!==null&&Date.now()+d<=c){await this.F(S.code,d,o);continue}throw S}if(v.ok)return await this.Zt(v,g,o,a,p);this._(p);let A=await L(v,o);if(A.code==="internal")return await this.$t(A,a,o);a.d!==null&&this.bt(a.d,A);let _=X(A);if(_!==null&&Date.now()+_<=c){await this.F(A.code,_,o);continue}if(A.code==="busy"&&Date.now()<l){await this.F("busy",at[Math.min(h++,at.length-1)],o);continue}throw A}finally{o.removeEventListener("abort",m),this._(p),p&&p.O&&p.O()}}}async F(t,e,r){D(r),this.r({waiting:{code:t,until:Date.now()+e}});try{await z(e,r)}finally{r.aborted||this.r({waiting:null})}}async $t(t,e,r){let o=await this.vt(e,r,t);if(o===null)throw t;return this.At(o,e,r)}async vt(t,e,r){let o=this.c,s=null;for(let a of ln){await z(a,e);try{return await this.fe(t,e)}catch(i){if(e.aborted)throw k();if(s=B(i),this.c!==o)throw s;if(s.code==="not_found")return null;if($.indexOf(s.code)<0)break}}throw this.E=t,s&&$.indexOf(s.code)<0?s:r||s||new w("network","The chat couldn't be reached.")}async fe(t,e){let r=s=>pe(s,t),o=null;if(t.d!==null){let s=await this.Vt(t.d,e);s.messages.some(r)&&(o=s)}else{let s=await this.de(e);s.conversation&&s.messages.some(r)&&s.messages.every(a=>a.id>t.ot)&&(o={conversation:s.conversation,messages:s.messages,A:s.A})}return D(e),o?(this.v(o.messages),this.r({...this.et(o.conversation,o.messages,o.A),outgoing:null}),o.conversation.id):null}async de(t){if(this.u.a==="cookie"){let e=await N(this.h,this.w,{method:"GET",path:"/session",signal:t});if(e.ok){M(e);let r=await this.R({},null,t);if(!r.N)return r}else if(e.status===401)M(e);else throw await L(e,t);return this.kt(t)}try{return await this.R(this.u.a==="token"?{cookieless:!0}:{},this.yt(),t)}catch(e){if(!I(e,"token_expired")&&!I(e,"session_expired")&&!I(e,"unauthorized"))throw e;return this.kt(t)}}async Zt(t,e,r,o,s){let a=o.d,i=!1,c=t.body?t.body.getReader():null;if(c){let l=new TextDecoder,h=new st,g=()=>{c.cancel().catch(()=>{})};e.signal.addEventListener("abort",g,{once:!0}),e.signal.aborted&&g();let p=setTimeout(()=>e.abort(),ae),m=setTimeout(()=>e.abort(),an);try{for(;;){let{value:v,done:A}=await c.read();if(r.aborted&&!this.nt(s))throw k();if(A)break;clearTimeout(p),p=setTimeout(()=>e.abort(),ae),this.ft=!0;try{for(let _ of h.push(l.decode(v,{stream:!0}))){if(this.nt(s)){if(_.event!=="conversation")continue;throw s.O(this.pt(K(JSON.parse(_.data)).id)),k()}if(r.aborted)throw k();if(_.event==="message"&&i)continue;_.event==="message"&&(i=!0);let S=this.ge(_.event,_.data);if(S){if(!("conversation"in S))return S;a=S.conversation,this._(s)}}}finally{this.ft=!1,this.dt&&(this.dt=!1,this.mt())}}}catch(v){if(r.aborted)throw k();if(O(v)&&v.code!=="protocol")throw v}finally{clearTimeout(p),clearTimeout(m),e.signal.removeEventListener("abort",g),g()}}if(r.aborted)throw k();return this.At(a,{...o,d:a},r)}ge(t,e){if(rn.indexOf(t)<0)return null;let r;try{let o=JSON.parse(e);r=o&&typeof o=="object"?o:{}}catch{throw new w("protocol","The stream couldn't be read.")}switch(t){case"conversation":{let o=K(r);return this.r(this.P(o.id)?{conversation:o}:{conversation:o,messages:[],hasOlder:!1}),{conversation:o.id}}case"message":{let o=ct(r),s=this.e.conversation;return this.v([o]),this.r({messages:Lt(this.e.messages,o),outgoing:null}),s&&s.endedAt&&this.r({conversation:{...s,endedAt:null}}),null}case"delta":{let o=this.e.answer||{text:"",tools:[]};return typeof r.text!="string"||r.text===""||o.text.length>=on||this.r({answer:{text:o.text+r.text,tools:o.tools}}),null}case"tool":{let o=this.e.answer||{text:"",tools:[]};if(typeof r.name!="string"||typeof r.status!="string")return null;let s=yn(o.tools,r.name,r.status,typeof r.title=="string"?r.title:"");return s!==o.tools&&this.r({answer:{text:o.text,tools:s}}),null}case"done":{let o=ct(r.message),s=typeof r.stop=="string"?r.stop:null;return this.v([o]),this.r({messages:Lt(this.e.messages,o),outgoing:null,answer:null,answering:!1,waiting:null,stop:s}),{message:o,stop:s}}default:{let o=r.partial?ct(r.partial):null;o&&this.v([o]),this.r({messages:o?Lt(this.e.messages,o):this.e.messages,outgoing:null,answer:null,answering:!1});let s=typeof r.error=="string"&&r.error!==""?r.error:"unavailable";throw new w(s,typeof r.message=="string"?r.message:"The answer failed.",{status:200,partial:o})}}}async At(t,e,r){let o=e.text===""&&!e.files.length;if(t===null&&o)throw new w("network","The answer was lost.");let s=t!==null?t:await this.vt(e,r,null);if(s===null)throw this.E=e,new w("no_answer","The answer was lost.");let a=this.c,i;try{i=await this.Yt(s,r)}catch(l){throw!o&&!r.aborted&&!I(l,"not_found")&&a===this.c&&(this.E={...e,d:s}),l}D(r),this.P(s)&&this.r({outgoing:null,answer:null,waiting:null});let c;if(o)c=i.messages.filter(l=>l.role==="assistant"&&l.id>e.ot).pop();else{let l=i.messages.length-1;for(;l>=0&&!pe(i.messages[l],e);)l--;c=l>=0?i.messages.slice(l+1).find(h=>h.role==="assistant"):void 0}if(!c)throw new w("no_answer","The assistant didn't answer.");return{message:c,stop:null}}async Vt(t,e){let r=await this.rt({method:"GET",path:"/conversations/"+encodeURIComponent(t)},e,t);if(!r.ok)throw this.bt(t,await L(r,e));return ke(await q(r,e))}async Rt(t,e,r){let o="/conversations/"+encodeURIComponent(t)+(r?"?before="+r:"");try{return ke(await q(await this.G({method:"GET",path:o},e),e))}catch(s){throw this.bt(t,s)}}async Yt(t,e){let r=Date.now(),o=0;for(;;){let s=Date.now()-r;if(s>=hn)throw new w("timeout","The answer took too long.");await z(s<6e4?un:cn,e);let a;try{a=await this.Vt(t,e)}catch(i){if(e.aborted)throw k();let c=B(i);if($.indexOf(c.code)>=0&&++o<fn)continue;throw c}if(o=0,D(e),!a.answering)return this.P(t)&&(this.v(a.messages),this.r({...this.et(a.conversation,a.messages,a.A),answering:!1})),a}}Lt(t){this.y&&this.y.abort();let e=new AbortController;this.y=e;let r=this.x.signal,o=()=>e.abort();r.addEventListener("abort",o,{once:!0}),this.Yt(t,e.signal).then(()=>{},()=>{!e.signal.aborted&&this.P(t)&&this.r({answering:!1})}).then(()=>{r.removeEventListener("abort",o),this.y===e&&(this.y=null)})}};function he(n,t,e){let r=X(n);return e<Y?r!=null?r:ue[Math.min(t,ue.length-1)]:Math.max(r!=null?r:0,ce+Math.random()*ce)}function X(n){return n.code!=="rate_limited"&&n.code!=="overloaded"&&n.code!=="not_connected"?null:(n.retryAfter===null?5:Math.min(Math.max(n.retryAfter,1),60))*1e3}function lt(){return new w("busy","Still answering.")}function fe(){return new w("conversation_list_off","This chat lists no conversations.")}function Rt(){return new w("unauthorized","The chat couldn't be opened.")}function ut(n,t){if(n===void 0)return{};if(!n||typeof n!="object")throw new TypeError("options must be an object");for(let r of Object.keys(n))if(t.indexOf(r)<0)throw new TypeError("unknown option "+r);let e=n.signal;if(e!=null&&!(e instanceof AbortSignal))throw new TypeError("signal must be an AbortSignal");return n}function V(n){let t=typeof n=="string"?n:n&&n.id;if(typeof t!="string"||t==="")throw new TypeError("expected a ChatFile or Conversation, or its id");return t}function de(n,t,e){let r;try{t&&typeof t=="object"&&!Array.isArray(t)&&(r=JSON.stringify({...n,...t}))}catch{}if(!r||r[0]!=="{")return"no JSON object";let o=JSON.parse(r);for(let s in Ot){let a=o[s];if(a!=null&&(typeof a!="string"||ge(a)>Ot[s]))return s+" must be a string of at most "+Ot[s]+" bytes"}return e!==void 0&&ge(r)>e?"over the chat's "+e+" bytes":r==="{}"?void 0:o}function ge(n){return new TextEncoder().encode(n).length}function pe(n,t){return n.role!=="user"||n.id<=t.ot?!1:t.files.length?!!n.files&&n.files.some(e=>e.id===t.files[0]):n.text===t.text}function we(n){return new w("token_failed","The token's aud isn't "+n+".")}function D(n){if(n.aborted)throw k()}function me(n,t){return new Promise((e,r)=>{let o=()=>r(k());t.addEventListener("abort",o,{once:!0}),n.then(e,r).then(()=>t.removeEventListener("abort",o))})}function I(n,t){return O(n)&&n.code===t}function B(n){return O(n)?n:new w("protocol",n instanceof Error?n.message:"Something went wrong.",{cause:n})}function be(n){let t=Et(n);return t?t.g:"token"}function Ae(n){let t="",e=0;for(let r=0;r<n.length;r++){let o=n.charCodeAt(r);o>=55296&&o<=56319&&r+1<n.length&&(n.charCodeAt(r+1)&64512)===56320?r++:(o&63488)===55296&&(t+=n.slice(e,r)+"\uFFFD",e=r+1)}return e===0?n:t+n.slice(e)}function mn(n){let t=Ae(n),e=0,r=t.length;for(;e<r&&ye(t.charCodeAt(e));)e++;for(;r>e&&ye(t.charCodeAt(r-1));)r--;return t.slice(e,r)}function ye(n){return n>=9&&n<=13||n===32||n===133||n===160||n===5760||n>=8192&&n<=8202||n===8232||n===8233||n===8239||n===8287||n===12288}function bn(n,t){let e=new Map(n.map(r=>[r.id,r]));return t.map(r=>{let o=e.get(r.id);return o&&o.text===r.text&&o.role===r.role&&o.createdAt===r.createdAt&&String(o.tools)===String(r.tools)&&JSON.stringify(o.files)===JSON.stringify(r.files)?o:r})}function Lt(n,t){return n.some(e=>e.id===t.id)?n.map(e=>e.id===t.id?t:e):n.concat(t)}function yn(n,t,e,r){if(e!=="started"){for(let o=n.length-1;o>=0;o--)if(n[o].name===t&&n[o].status==="started")return n.slice(0,o).concat({name:t,status:e,title:r||n[o].title},n.slice(o+1))}return n.length>=sn?n:n.concat({name:t,status:e,title:r||t})}function J(n){return new w("protocol","Unreadable "+n+" from the chat.")}function K(n,t){var s,a,i;let e=n;if(!e||typeof e!="object"||typeof e.id!="string")throw J("conversation");let r=e.ended_at,o={id:e.id,createdAt:String((s=e.created_at)!=null?s:""),updatedAt:String((a=e.updated_at)!=null?a:""),endedAt:typeof r=="string"&&r?r:null};return t&&(o.title=String((i=e.title)!=null?i:"")),o}function ct(n){var r;let t=n;if(!t||typeof t!="object"||typeof t.id!="number"||typeof t.text!="string"||t.role!=="user"&&t.role!=="assistant")throw J("message");let e={id:t.id,role:t.role,text:t.text,createdAt:String((r=t.created_at)!=null?r:"")};if(Array.isArray(t.tools)){let o=t.tools.filter(a=>typeof a=="string"),s=t.tool_titles&&typeof t.tool_titles=="object"?t.tool_titles:{};e.tools=o,e.toolTitles=Object.fromEntries(o.map(a=>{let i=s[a];return[a,typeof i=="string"&&i?i:a]}))}return Array.isArray(t.files)&&(e.files=t.files.filter(o=>o&&typeof o.id=="string").map(_e)),e}function _e(n){var r,o,s;let t=n;if(!t||typeof t!="object"||typeof t.id!="string")throw J("file");let e=typeof t.size=="number"?t.size:0;return{id:t.id,name:String((r=t.name)!=null?r:""),type:String((o=t.type)!=null?o:""),size:e,createdAt:String((s=t.created_at)!=null?s:"")}}function Ce(n){return Array.isArray(n)?n.filter(t=>t&&typeof t=="object"&&(t.role==="user"||t.role==="assistant")).map(ct):[]}function kn(n){let t=n;if(!t||typeof t!="object")throw J("session");return{anonymous:t.anonymous===!0,N:t.started===!0,conversation:t.conversation?K(t.conversation):null,messages:Ce(t.messages),A:t.has_more===!0,answering:t.answering===!0,Wt:typeof t.session_token=="string"&&t.session_token!==""?t.session_token:null,files:vn(t.files),T:typeof t.context_max_bytes=="number"?t.context_max_bytes:void 0,Xt:t.conversation_list===!0}}function vn(n){let t=n;if(t===null)return null;if(!(!t||typeof t!="object"||!Array.isArray(t.types)||typeof t.max_bytes!="number"||typeof t.per_message!="number"))return{types:t.types.filter(e=>typeof e=="string"),maxBytes:t.max_bytes,perMessage:t.per_message}}function ke(n){let t=n;if(!t||typeof t!="object")throw J("conversation");return{conversation:K(t.conversation),messages:Ce(t.messages),A:t.has_more===!0,answering:t.answering===!0}}var An="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",Se=/[\p{P}\p{S}]/u,qt=/\s/,_n=/^[A-Za-z0-9_+-]+$/,Pe=/[A-Za-z0-9]/,Cn=/[0-9A-Fa-f]/,Sn=/[0-9]/;var Re="\u2800\u3164\u115F\u1160\uFFA0",xe=new RegExp("[\\s\\p{Default_Ignorable_Code_Point}"+Re+"]","u"),xn=new RegExp("[\\s\\p{Cc}\\p{Default_Ignorable_Code_Point}"+Re+"]","gu"),It="\u200C",Nt="\u200D",Ee=new RegExp("[\uFE00-\uFE0F"+String.fromCodePoint(917760)+"-"+String.fromCodePoint(917999)+"]","u"),Le=/^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])$/,En=new RegExp("[\u202A-\u202E\u2066-\u2069]","g"),zt={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Dt="nbsp a0 mdash 2014 ndash 2013 hellip 2026 copy a9 reg ae trade 2122 laquo ab raquo bb lsquo 2018 rsquo 2019 ldquo 201c rdquo 201d times d7 euro 20ac pound a3 yen a5 deg b0 middot b7 bull 2022".split(" ");for(let n=0;n<Dt.length;n+=2)zt[Dt[n]]=String.fromCharCode(parseInt(Dt[n+1],16));var j=0,Wt=1,H=2,tt=3,Me=4,kt=5;function Zt(n){let t=String(n==null?"":n).replace(/\r\n?/g,`
4
4
  `).split(`
5
- `).map(Me);return Gt(Xt(t,0).it,!1)}function Re(e,t=document){let n=t.createDocumentFragment();return je(Zt(e),n,t),n}function Xt(e,t){let n=[],r=t<8,o=e.length,s=!1,a=!1,i=0;for(;i<o;){let c=e[i];if(I(c)){a=n.length>0,i++;continue}a&&(s=!0),a=!1;let u,h,g,m;if(u=$t(c)){let w=[];for(i++;i<o&&!Le(e[i],u);i++)w.push(Ce(e[i],u.Qt));i++;let k=u.te.split(/\s/)[0];n.push({t:"pre",s:w.join(`
6
- `),Nt:An.test(k)?k:""})}else if(h=Ie(c))n.push({t:"h"+h.ee,s:h.Z}),i++;else if(Ne(c))n.push({t:"hr",s:""}),i++;else if(r&&Jt(c)!==null){let w=[],k=null;for(;i<o;){let v=Jt(e[i]);if(v===null&&(I(e[i])||k||I(w[w.length-1])||lt(e[i],r)))break;let S=v===null?e[i]:v;w.push(S),k=Ut(k,S),i++}n.push({t:"blockquote",s:"",ne:Xt(w,t+1).it})}else if(r&&(g=ct(c))){let w=g,k=[],v=g,S=!1;for(;;){let P=[v.Dt],d=Ut(null,v.Dt),l=-1;for(i++;i<o;i++){let _=e[i];if(I(_)){l<0&&(l=i);continue}if(xn(_)>=v.Ut){for(;l>=0&&l<i;l++)P.push("");l=-1;let y=Ce(_,v.Ut);P.push(y),d=Ut(d,y);continue}if(l>=0||d||I(P[P.length-1])||ct(_)||lt(_,r))break;P.push(_)}l>=0&&(i=l);let b=Xt(P,t+1);k.push(b.it),b.re&&(S=!0);let f=i;for(;f<o&&I(e[f]);)f++;let C=f<o?ct(e[f]):null;if(!C||C.$!==w.$||C.jt!==w.jt)break;f>i&&(S=!0),i=f,v=C}n.push({t:w.$?"ol":"ul",s:"",j:w.j,oe:!S,se:k})}else if(m=xe(e,i)){let w=[gt(c,64)];for(i+=2;i<o&&!I(e[i])&&!lt(e[i],r);i++)w.push(gt(e[i],64));n.push({t:"table",s:"",ie:w,ae:m.slice(0,64)})}else{let w=[c.trim()];for(i++;i<o&&!I(e[i])&&!lt(e[i],r)&&!xe(e,i);i++)w.push(e[i].trim());n.push({t:"p",s:w.join(`
7
- `)})}}return{it:n,re:s}}function I(e){if(e===void 0)return!0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==32&&n!==9)return!1}return!0}function xn(e){let t=0;for(;e.charCodeAt(t)===32;)t++;return t}function J(e){let t=0;for(;t<3&&e.charCodeAt(t)===32;)t++;return t}function Ce(e,t){let n=0;for(;n<t&&e.charCodeAt(n)===32;)n++;return e.slice(n)}function Me(e){let t=0,n=0,r=!1;for(;t<e.length;t++){let o=e.charCodeAt(t);if(o===9)n+=4-n%4,r=!0;else if(o===32)n++;else break}return r?" ".repeat(n)+e.slice(t):e}function $t(e){let t=J(e),n=e.charAt(t);if(n!=="`"&&n!=="~")return null;let r=t;for(;e.charAt(r)===n;)r++;let o=e.slice(r).trim();return r-t>=3&&!(n==="`"&&o.indexOf("`")>=0)?{ch:n,le:r-t,Qt:t,te:o}:null}function Le(e,t){let n=J(e),r=n;for(;e.charAt(r)===t.ch;)r++;return r-n>=t.le&&I(e.slice(r))}function Ut(e,t){return e?Le(t,e)?null:e:$t(t)}function Ie(e){let t=J(e),n=t;for(;n-t<7&&e.charAt(n)==="#";)n++;let r=n-t,o=e.charAt(n);if(r<1||r>6||o!==""&&o!==" "&&o!==" ")return null;let s=e.slice(n).trim(),a=s.length;for(;a>0&&s.charAt(a-1)==="#";)a--;return(a===0||s.charAt(a-1)===" "||s.charAt(a-1)===" ")&&(s=s.slice(0,a).trim()),{ee:r,Z:s}}function Ne(e){let t=J(e),n=e.charAt(t);if(n!=="-"&&n!=="*"&&n!=="_")return!1;let r=0;for(let o=t;o<e.length;o++){let s=e.charAt(o);if(s===n)r++;else if(s!==" "&&s!==" ")return!1}return r>=3}function Jt(e){let t=J(e);return e.charAt(t)!==">"?null:(t++,(e.charAt(t)===" "||e.charAt(t)===" ")&&t++,Me(e.slice(t)))}function ct(e){let t=J(e),n=1,r=e.charAt(t),o=r>="0"&&r<="9",s=r;if(o){let u=t;for(;u-t<9&&e.charAt(u)>="0"&&e.charAt(u)<="9";)u++;if(s=e.charAt(u),s!=="."&&s!==")")return null;n=parseInt(e.slice(t,u),10),t=u}else if(r!=="-"&&r!=="*"&&r!=="+")return null;t++;let a=t;for(;e.charAt(a)===" "||e.charAt(a)===" ";)a++;if(a===t&&a<e.length)return null;let i=a>=e.length,c=a-t>4;return{$:o,jt:s,j:n,Ut:i||c?t+1:a,Dt:i?"":e.slice(c?t+1:a),ue:i}}function lt(e,t){if($t(e)||Ie(e)||Ne(e))return!0;if(!t)return!1;if(Jt(e)!==null)return!0;let n=ct(e);return n!==null&&!n.ue&&(!n.$||n.j===1)}function gt(e,t){let n=e.trim(),r=[],o=n.charAt(0)==="|"?1:0,s=n.length,a="";if(s>o&&n.charAt(s-1)==="|"){let i=0;for(;n.charAt(s-2-i)==="\\";)i++;i%2===0&&s--}for(;o<s;o++){let i=n.charAt(o);if(i==="\\"&&o+1<s){let c=n.charAt(++o);a+=c==="|"?c:i+c}else i==="|"&&r.length<t-1?(r.push(a.trim()),a=""):a+=i}return r.push(a.trim()),r}function En(e){if(e.indexOf("|")<0||e.indexOf("-")<0)return null;let t=[];for(let n of gt(e,1/0)){if(!/^:?-+:?$/.test(n))return null;let r=n.charAt(0)===":",o=n.charAt(n.length-1)===":";t.push(r&&o?"center":o?"right":r?"left":"")}return t}function xe(e,t){let n=t+1<e.length?En(e[t+1]):null;return n&&e[t].indexOf("|")>=0&&gt(e[t],1/0).length===n.length?n:null}function O(e,t){return{k:e,s:t,C:"",y:"",I:null,i:null,r:null}}function jt(e,t){let n=O(X,"a");return n.C=e,n.I=t,n}function Vt(e){return e!==""&&kn.indexOf(e)>=0}function Tn(e){switch(e){case 10:case 33:case 38:case 42:case 60:case 72:case 91:case 92:case 93:case 95:case 96:case 104:case 126:return!0}return!1}function ht(e){let t=O(X,""),n=e.length,r=t,o=null,s=null,a=0,i=0,c=0,u=-1,h=d=>{r.r=d,d.i=r,r=d},g=d=>{r.k===N?r.s+=d:h(O(N,d))},m=d=>{d.i.r=d.r,d.r?d.r.i=d.i:r=d.i},w=d=>{d.l.s=d.l.s.slice(0,d.n),d.i&&(d.i.r=d.r),d.r?d.r.i=d.i:o=d.i},k=d=>{let l=d?d.id:-1,b={},f=o;if(!(!f||f.id<=l)){for(;f.i&&f.i.id>l;)f=f.i;for(;f;){if(!f.Bt){f=f.r;continue}let C=f.ch+(f.V?"1":"0")+f.B%3,_=Math.max(l,C in b?b[C]:-1),y=f.i;for(;y&&y.id>_&&!(y.ch===f.ch&&y.V&&On(y,f));)y=y.i;if(y&&y.id>_){let E=f.ch==="~"||f.n>1&&y.n>1?2:1;y.n-=E,f.n-=E;let R=O(X,f.ch==="~"?"del":E===2?"strong":"em");if(y.l.r!==f.l){let x=y.l.r,Y=f.l.i;x.i=null,Y.r=null,R.I=x}y.l.r=R,R.i=y.l,R.r=f.l,f.l.i=R;for(let x=y.r;x&&x!==f;x=x.r)x.l.s=x.l.s.slice(0,x.n);if(y.r=f,f.i=y,y.n||(m(y.l),w(y)),!f.n){m(f.l);let x=f.r;w(f),f=x}}else{b[C]=f.i?f.i.id:-1;let E=f.r;f.V||w(f),f=E}}for(;o&&o.id>l;)w(o)}},v=[],S=[],P=[];if(e.indexOf("`")>=0){for(let l=0;l<n;){if(e.charCodeAt(l)!==96){l++;continue}let b=l;for(;e.charCodeAt(b)===96;)b++;v.push(l),S.push(b-l),l=b}let d={};for(let l=v.length-1;l>=0;l--)P[l]=S[l]in d?d[S[l]]:-1,d[S[l]]=l}for(;i<n;){let d=e.charCodeAt(i);if(d===92){let l=e.charAt(i+1);if(l===`
8
- `)h(O(V,"")),i+=2;else if(Vt(l)){let b=i+2;if(l==="`")for(;e.charCodeAt(b)===96;)b++;g(e.slice(i+1,b)),i=b}else g("\\"),i++}else if(d===96){for(;c<v.length&&v[c]<i;)c++;if(v[c]!==i){g("`"),i++;continue}let l=S[c],b=P[c];if(b<0){g(e.slice(i,i+l)),i+=l;continue}let f=e.slice(i+l,v[b]).replace(/\n/g," ");f.length>1&&f.charAt(0)===" "&&f.charAt(f.length-1)===" "&&/[^ ]/.test(f)&&(f=f.slice(1,-1)),h(O(Pe,f)),i=v[b]+l}else if(d===42||d===95||d===126){let l=i+1;for(;e.charCodeAt(l)===d;)l++;let b=e.charAt(i-1),f=e.charAt(l),C=b===""||qt.test(b),_=f===""||qt.test(f),y=ve.test(b),E=ve.test(f),R=!_&&(!E||C||y),x=!C&&(!y||_||E),Y=d===95?R&&(!x||y):R,Kt=d===95?x&&(!R||E):x,Qt=O(Wt,e.slice(i,l));if(h(Qt),(Y||Kt)&&(d!==126||l-i===2)){let te={l:Qt,ch:e.charAt(i),n:l-i,B:l-i,V:Y,Bt:Kt,id:a++,i:o,r:null};o&&(o.r=te),o=te}i=l}else if(d===91||d===33&&e.charCodeAt(i+1)===91){let l=d===33,b=O(Wt,l?"![":"[");h(b),s={l:b,F:l,at:!0,x:!1,ce:o,i:s},i+=l?2:1}else if(d===93){let l=s,b=l&&l.at?Pn(e,i+1):null;if(l&&(s=l.i),!l||!b){l&&l.x&&s&&(s.x=!0),g("]"),i++;continue}k(l.ce);let f=l.l.r,C=pt(b.y);if(l.F||C){let _=!l.F&&f?f:O(N,l.F&&!(C&&l.x)?ft(f):"");if(C&&Dn(_),ft(_)||(_=O(N,C?dt(C):b.y)),_.i=null,l.l.r=null,r=l.l,C){let y=jt(C,_),E=l.l.i;if(y.y=Nn(ft(_),C),y.y){let R=O(mt,"["+y.y+"] ");E.r=R,R.i=E,E=R}E.r=y,y.i=E,r=y}else l.l.k=N,l.l.s=_.s}else m(l.l);if(!l.F)for(let _=s;_&&_.at;_=_.i)_.at=!1;s&&(l.F||C||l.x)&&(s.x=!0),i=b.R}else if(d===60){let l=Rn(e,i);if(!l){g("<"),i++;continue}l.C?(h(jt(l.C,O(N,dt(l.C)))),s&&(s.x=!0)):g(l.Z),i=l.R}else if(d===38){let l=De(e,i);l?(g(l[0]),i=l[1]):(g("&"),i++)}else if(d===10)for(h(O(V,"")),i++;e.charCodeAt(i)===32;)i++;else if((d===104||d===72)&&(u=Mn(e,i,s!==null))>i){let l=e.slice(i,u),b=pt(l);b?(h(jt(b,O(N,dt(b)))),s&&(s.x=!0)):g(l),i=u}else{let l=i+1;for(;l<n&&!Tn(e.charCodeAt(l));)l++;g(e.slice(i,l)),i=l}}return k(null),t.r}function On(e,t){return t.ch==="~"||!((e.Bt||t.V)&&(e.B+t.B)%3===0&&(e.B%3!==0||t.B%3!==0))}function ft(e){let t="",n=[];for(;;){if(!e){if(!n.length)return t;e=n.pop();continue}if(e.k===X){n.push(e.r),e=e.I;continue}e.k!==mt&&(t+=e.k===V?" ":e.s),e=e.r}}function Bt(e,t,n){for(;t<n&&(e.charAt(t)===" "||e.charAt(t)===" "||e.charAt(t)===`
9
- `);)t++;return t}function Pn(e,t){if(e.charAt(t)!=="(")return null;let n=Math.min(e.length,t+4096);t=Bt(e,t+1,n);let r;if(e.charAt(t)==="<"){let a=++t;for(;t<n;t++){let i=e.charAt(t);if(i==="\\")t++;else if(i===">"||i==="<"||i===`
10
- `)break}if(e.charAt(t)!==">")return null;r=e.slice(a,t++)}else{let a=t,i=0;for(;t<n;t++){let c=e.charCodeAt(t);if(c===92&&Vt(e.charAt(t+1)))t++;else{if(c<=32)break;if(c===40){if(++i>32)return null}else if(c===41){if(!i)break;i--}}}if(i||t>=n)return null;r=e.slice(a,t)}let o=t;t=Bt(e,t,n);let s=e.charAt(t);if(t>o&&(s==='"'||s==="'"||s==="(")){let a=s==="("?")":s;for(t++;t<n;t++){let i=e.charAt(t);if(i==="\\")t++;else{if(i===a)break;if(s==="("&&i==="(")return null}}if(t>=n)return null;t=Bt(e,t+1,n)}return e.charAt(t)!==")"?null:{y:Ln(r),R:t+1}}function Rn(e,t){let n=Math.min(e.length,t+2048),r=t+1;for(;r<n;){let s=e.charCodeAt(r);if(s<=32||s===60||s===62)break;r++}if(e.charAt(r)!==">"||r===t+1)return null;let o=e.slice(t+1,r);return/^[A-Za-z][A-Za-z0-9+.-]{1,31}:/.test(o)?{Z:o,C:pt(o),R:r+1}:/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/.test(o)?{Z:o,C:pt("mailto:"+o),R:r+1}:null}function Mn(e,t,n){let r=e.charAt(t-1);if(r!==""&&!qt.test(r)&&"*_~(".indexOf(r)<0||r==="("&&e.charAt(t-2)==="]")return-1;let o=e.slice(t,t+8).toLowerCase(),s=o.indexOf("https://")===0?t+8:o.indexOf("http://")===0?t+7:-1;if(s<0)return-1;let a=s,i=0,c=0;for(;a<e.length;a++){let u=e.charCodeAt(a);if(u<=32||u===60||u===160||n&&u===93)break;u===40?i++:u===41&&c++}for(;;){let u=e.charAt(a-1);if(`?!.,:*_~'"`.indexOf(u)>=0)a--;else if(u===")"&&c>i)a--,c--;else if(u===";"){let h=a-2;for(;h>s&&Ee.test(e.charAt(h));)h--;if(e.charAt(h)!=="&"||h===a-2)break;a=h}else break}return a>s?a:-1}function De(e,t){let n=t+1;if(e.charAt(n)==="#"){let o=e.charAt(n+1)==="x"||e.charAt(n+1)==="X",s=o?vn:_n,a=n+=o?2:1;for(;n-a<(o?6:7)&&s.test(e.charAt(n));)n++;if(n===a||e.charAt(n)!==";")return null;let i=parseInt(e.slice(a,n),o?16:10);return(!i||i>1114111||i>=55296&&i<=57343)&&(i=65533),[String.fromCodePoint(i),n+1]}for(;n-t<10&&Ee.test(e.charAt(n));)n++;let r=e.slice(t+1,n);return e.charAt(n)===";"&&Object.prototype.hasOwnProperty.call(zt,r)?[zt[r],n+1]:null}function Ln(e){if(e.indexOf("\\")<0&&e.indexOf("&")<0)return e;let t="";for(let n=0;n<e.length;n++){let r=e.charAt(n);if(r==="\\"&&Vt(e.charAt(n+1))){t+=e.charAt(++n);continue}let o=r==="&"?De(e,n):null;o?(t+=o[0],n=o[1]-1):t+=r}return t}function pt(e){let t;try{t=new URL(e)}catch{return null}return t.username||t.password?null:t.protocol==="mailto:"?Yt(t)?t.href:null:(t.protocol==="https:"||t.protocol==="http:")&&Oe.test(t.hostname)?t.href:null}function Yt(e){let t=e.pathname,n=t.lastIndexOf("@"),r=t.slice(n+1);if(n<1||/[/\\?#:]/.test(r))return null;let o,s;try{o=decodeURIComponent(t.slice(0,n)),s=new URL("http://"+r).hostname}catch{return null}return Oe.test(s)&&!/[@"()\s]/.test(o)?t.slice(0,n+1)+s+e.search:null}function dt(e){let t=new URL(e),n=t.protocol==="mailto:"?"mailto:"+(Yt(t)||t.pathname):t.protocol+"//"+t.host+In(t.pathname+t.search+t.hash);return Ht(n)>200?Ue(n,199)+"\u2026":n}function In(e){try{return decodeURI(e).replace(Sn,encodeURIComponent)}catch{return e}}function Ht(e){let t=0;for(let n=0;n<e.length;n+=e.codePointAt(n)>65535?2:1)t++;return t}function Ue(e,t){let n=0;for(;t>0&&n<e.length;t--)n+=e.codePointAt(n)>65535?2:1;return e.slice(0,n)}function Nn(e,t){let n=new URL(t);if(n.protocol==="mailto:"){let s=Yt(n)||n.pathname;return e===s?"":s}let r=Ft(e),o=n.hostname;return r===Ft(t)||r===Ft(dt(t))||r===o||r==="www."+o?"":o}function Dn(e){let t=[],n=[],r="";Un(e,u=>(u.k===V&&(u.k=N,u.s=" "),t.push(u),r+=u.s,!0));let o=0,s=0,a=!0,i=-1,c=!1;for(let u of t){let h="";for(let g=o+u.s.length;o<g;){let m=String.fromCodePoint(r.codePointAt(o));if(o+=m.length,!a&&(m===It||m===Nt)&&o>i){for(i=o;i<r.length;){let k=String.fromCodePoint(r.codePointAt(i));if(k!==It&&k!==Nt&&!Se.test(k))break;i+=k.length}c=i<r.length&&!_e.test(String.fromCodePoint(r.codePointAt(i)))}let w=_e.test(m)&&(a||(m===It||m===Nt?!c:!Se.test(m)));w&&a||(h+=w?" ":m,s++,a=w)}n.push(h)}for(let u=n.length-1;u>=0;u--)if(n[u]){n[u].charAt(n[u].length-1)===" "&&(n[u]=n[u].slice(0,-1),s--);break}if(s>120){let u=119,h=0;for(;Ht(n[h])<u;)u-=Ht(n[h++]);let g=Ue(n[h],u);for(g.charAt(g.length-1)===" "&&(g=g.slice(0,-1)),n[h]=g+"\u2026";++h<n.length;)n[h]=""}t.forEach((u,h)=>{u.s=n[h]})}function Un(e,t){let n=[];for(;;){if(!e){if(!n.length)return;e=n.pop();continue}if(e.k===X){n.push(e.r),e=e.I;continue}if(e.k!==mt&&!t(e))return;e=e.r}}function Ft(e){e=e.trim();let t=e.slice(0,8).toLowerCase();return e=t.indexOf("https://")===0?e.slice(8):t.indexOf("http://")===0?e.slice(7):e,e.charAt(e.length-1)==="/"?e.slice(0,-1):e}function Gt(e,t){let n=[];for(let r of e)switch(r.t){case"p":t?$(ht(r.s),n,0,!1):n.push({tag:"p",children:$(ht(r.s),[],0,!1)});break;case"pre":n.push(r.Nt?{tag:"pre",language:r.Nt,children:[wt(r.s)]}:{tag:"pre",children:[wt(r.s)]});break;case"blockquote":n.push({tag:"blockquote",children:Gt(r.ne||[],!1)});break;case"ul":case"ol":{let o=(r.se||[]).map(a=>({tag:"li",children:Gt(a,!!r.oe)})),s={tag:r.t,children:o};r.t==="ol"&&r.j!==1&&(s.start=r.j),n.push(s);break}case"table":n.push(jn(r.ie||[],r.ae||[]));break;case"hr":n.push({tag:"hr"});break;default:n.push({tag:r.t,children:$(ht(r.s),[],0,!1)})}return n}function jn(e,t){let n=[],r=e.length?e[0].length:0,o=[],s=0;for(let a of e)s+=2*a.length;for(let a=0;a<e.length;a++){a<2&&n.push({tag:a?"tbody":"thead",children:o=[]});let i=e[a].length,c=i;i<r&&(r-i<=s?(s-=r-i,c=r):s=0);let u=[];for(let h=0;h<c;h++){let g={tag:a?"td":"th",children:h<i?$(ht(e[a][h]),[],0,!1):[]},m=t[h];m&&(g.align=m),u.push(g)}o.push({tag:"tr",children:u})}return{tag:"table",children:n}}function $(e,t,n,r){let o="";for(;e;e=e.r)if(e.k===N||e.k===Wt)o+=e.s;else if(e.k===mt){if(r||n>=16)continue;ut(t,o),ut(t,e.s),o=""}else if(e.k===X&&(e.s==="a"&&r||n>=16))o+=ft(e.I);else if(ut(t,o),o="",e.k===V)t.push({tag:"br"});else if(e.k===Pe)t.push({tag:"code",children:[wt(e.s)]});else{let s={tag:e.s,children:$(e.I,[],n+1,r||e.s==="a")};e.s==="a"&&(s.href=e.C,e.y&&(s.dest=e.y)),t.push(s)}return ut(t,o),t}function ut(e,t){t=wt(t),t&&e.push(t)}function wt(e){return e.replace(Cn,"")}function je(e,t,n){for(let r of e){if(typeof r=="string"){t.appendChild(n.createTextNode(r));continue}let o=n.createElement(r.tag),s=o;r.tag==="pre"?(s=n.createElement("code"),r.language&&s.setAttribute("class","language-"+r.language),o.appendChild(s)):r.tag==="a"&&r.href?(o.setAttribute("href",r.href),o.setAttribute("target","_blank"),o.setAttribute("rel","noopener noreferrer")):r.tag==="ol"&&r.start!==void 0?o.setAttribute("start",String(r.start)):(r.tag==="th"||r.tag==="td")&&r.align&&(o.style.textAlign=r.align),r.children&&je(r.children,s,n),t.appendChild(o)}}return Xe(Bn);})();
5
+ `).map(Ne);return Gt(Xt(t,0)._t,!1)}function Ie(n,t=document){let e=t.createDocumentFragment();return qe(Zt(n),e,t),e}function Xt(n,t){let e=[],r=t<8,o=n.length,s=!1,a=!1,i=0;for(;i<o;){let c=n[i];if(U(c)){a=e.length>0,i++;continue}a&&(s=!0),a=!1;let l,h,g,p;if(l=$t(c)){let m=[];for(i++;i<o&&!De(n[i],l);i++)m.push(Te(n[i],l.pe));i++;let v=l.we.split(/\s/)[0];e.push({t:"pre",s:m.join(`
6
+ `),Kt:_n.test(v)?v:""})}else if(h=Ue(c))e.push({t:"h"+h.me,s:h.st}),i++;else if(je(c))e.push({t:"hr",s:""}),i++;else if(r&&Jt(c)!==null){let m=[],v=null;for(;i<o;){let A=Jt(n[i]);if(A===null&&(U(n[i])||v||U(m[m.length-1])||ht(n[i],r)))break;let _=A===null?n[i]:A;m.push(_),v=Ut(v,_),i++}e.push({t:"blockquote",s:"",be:Xt(m,t+1)._t})}else if(r&&(g=dt(c))){let m=g,v=[],A=g,_=!1;for(;;){let S=[A.Qt],d=Ut(null,A.Qt),u=-1;for(i++;i<o;i++){let C=n[i];if(U(C)){u<0&&(u=i);continue}if(Tn(C)>=A.te){for(;u>=0&&u<i;u++)S.push("");u=-1;let y=Te(C,A.te);S.push(y),d=Ut(d,y);continue}if(u>=0||d||U(S[S.length-1])||dt(C)||ht(C,r))break;S.push(C)}u>=0&&(i=u);let b=Xt(S,t+1);v.push(b._t),b.ye&&(_=!0);let f=i;for(;f<o&&U(n[f]);)f++;let x=f<o?dt(n[f]):null;if(!x||x.it!==m.it||x.ee!==m.ee)break;f>i&&(_=!0),i=f,A=x}e.push({t:m.it?"ol":"ul",s:"",Z:m.Z,ke:!_,ve:v})}else if(p=Oe(n,i)){let m=[mt(c,64)];for(i+=2;i<o&&!U(n[i])&&!ht(n[i],r);i++)m.push(mt(n[i],64));e.push({t:"table",s:"",Ae:m,_e:p.slice(0,64)})}else{let m=[c.trim()];for(i++;i<o&&!U(n[i])&&!ht(n[i],r)&&!Oe(n,i);i++)m.push(n[i].trim());e.push({t:"p",s:m.join(`
7
+ `)})}}return{_t:e,ye:s}}function U(n){if(n===void 0)return!0;for(let t=0;t<n.length;t++){let e=n.charCodeAt(t);if(e!==32&&e!==9)return!1}return!0}function Tn(n){let t=0;for(;n.charCodeAt(t)===32;)t++;return t}function G(n){let t=0;for(;t<3&&n.charCodeAt(t)===32;)t++;return t}function Te(n,t){let e=0;for(;e<t&&n.charCodeAt(e)===32;)e++;return n.slice(e)}function Ne(n){let t=0,e=0,r=!1;for(;t<n.length;t++){let o=n.charCodeAt(t);if(o===9)e+=4-e%4,r=!0;else if(o===32)e++;else break}return r?" ".repeat(e)+n.slice(t):n}function $t(n){let t=G(n),e=n.charAt(t);if(e!=="`"&&e!=="~")return null;let r=t;for(;n.charAt(r)===e;)r++;let o=n.slice(r).trim();return r-t>=3&&!(e==="`"&&o.indexOf("`")>=0)?{ch:e,Ce:r-t,pe:t,we:o}:null}function De(n,t){let e=G(n),r=e;for(;n.charAt(r)===t.ch;)r++;return r-e>=t.Ce&&U(n.slice(r))}function Ut(n,t){return n?De(t,n)?null:n:$t(t)}function Ue(n){let t=G(n),e=t;for(;e-t<7&&n.charAt(e)==="#";)e++;let r=e-t,o=n.charAt(e);if(r<1||r>6||o!==""&&o!==" "&&o!==" ")return null;let s=n.slice(e).trim(),a=s.length;for(;a>0&&s.charAt(a-1)==="#";)a--;return(a===0||s.charAt(a-1)===" "||s.charAt(a-1)===" ")&&(s=s.slice(0,a).trim()),{me:r,st:s}}function je(n){let t=G(n),e=n.charAt(t);if(e!=="-"&&e!=="*"&&e!=="_")return!1;let r=0;for(let o=t;o<n.length;o++){let s=n.charAt(o);if(s===e)r++;else if(s!==" "&&s!==" ")return!1}return r>=3}function Jt(n){let t=G(n);return n.charAt(t)!==">"?null:(t++,(n.charAt(t)===" "||n.charAt(t)===" ")&&t++,Ne(n.slice(t)))}function dt(n){let t=G(n),e=1,r=n.charAt(t),o=r>="0"&&r<="9",s=r;if(o){let l=t;for(;l-t<9&&n.charAt(l)>="0"&&n.charAt(l)<="9";)l++;if(s=n.charAt(l),s!=="."&&s!==")")return null;e=parseInt(n.slice(t,l),10),t=l}else if(r!=="-"&&r!=="*"&&r!=="+")return null;t++;let a=t;for(;n.charAt(a)===" "||n.charAt(a)===" ";)a++;if(a===t&&a<n.length)return null;let i=a>=n.length,c=a-t>4;return{it:o,ee:s,Z:e,te:i||c?t+1:a,Qt:i?"":n.slice(c?t+1:a),Se:i}}function ht(n,t){if($t(n)||Ue(n)||je(n))return!0;if(!t)return!1;if(Jt(n)!==null)return!0;let e=dt(n);return e!==null&&!e.Se&&(!e.it||e.Z===1)}function mt(n,t){let e=n.trim(),r=[],o=e.charAt(0)==="|"?1:0,s=e.length,a="";if(s>o&&e.charAt(s-1)==="|"){let i=0;for(;e.charAt(s-2-i)==="\\";)i++;i%2===0&&s--}for(;o<s;o++){let i=e.charAt(o);if(i==="\\"&&o+1<s){let c=e.charAt(++o);a+=c==="|"?c:i+c}else i==="|"&&r.length<t-1?(r.push(a.trim()),a=""):a+=i}return r.push(a.trim()),r}function On(n){if(n.indexOf("|")<0||n.indexOf("-")<0)return null;let t=[];for(let e of mt(n,1/0)){if(!/^:?-+:?$/.test(e))return null;let r=e.charAt(0)===":",o=e.charAt(e.length-1)===":";t.push(r&&o?"center":o?"right":r?"left":"")}return t}function Oe(n,t){let e=t+1<n.length?On(n[t+1]):null;return e&&n[t].indexOf("|")>=0&&mt(n[t],1/0).length===e.length?e:null}function P(n,t){return{k:n,s:t,L:"",C:"",q:null,i:null,o:null}}function jt(n,t){let e=P(H,"a");return e.L=n,e.q=t,e}function Vt(n){return n!==""&&An.indexOf(n)>=0}function Pn(n){switch(n){case 10:case 33:case 38:case 42:case 60:case 72:case 91:case 92:case 93:case 95:case 96:case 104:case 126:return!0}return!1}function gt(n){let t=P(H,""),e=n.length,r=t,o=null,s=null,a=0,i=0,c=0,l=-1,h=d=>{r.o=d,d.i=r,r=d},g=d=>{r.k===j?r.s+=d:h(P(j,d))},p=d=>{d.i.o=d.o,d.o?d.o.i=d.i:r=d.i},m=d=>{d.l.s=d.l.s.slice(0,d.n),d.i&&(d.i.o=d.o),d.o?d.o.i=d.i:o=d.i},v=d=>{let u=d?d.id:-1,b={},f=o;if(!(!f||f.id<=u)){for(;f.i&&f.i.id>u;)f=f.i;for(;f;){if(!f.ne){f=f.o;continue}let x=f.ch+(f.at?"1":"0")+f.$%3,C=Math.max(u,x in b?b[x]:-1),y=f.i;for(;y&&y.id>C&&!(y.ch===f.ch&&y.at&&Rn(y,f));)y=y.i;if(y&&y.id>C){let T=f.ch==="~"||f.n>1&&y.n>1?2:1;y.n-=T,f.n-=T;let R=P(H,f.ch==="~"?"del":T===2?"strong":"em");if(y.l.o!==f.l){let E=y.l.o,et=f.l.i;E.i=null,et.o=null,R.q=E}y.l.o=R,R.i=y.l,R.o=f.l,f.l.i=R;for(let E=y.o;E&&E!==f;E=E.o)E.l.s=E.l.s.slice(0,E.n);if(y.o=f,f.i=y,y.n||(p(y.l),m(y)),!f.n){p(f.l);let E=f.o;m(f),f=E}}else{b[x]=f.i?f.i.id:-1;let T=f.o;f.at||m(f),f=T}}for(;o&&o.id>u;)m(o)}},A=[],_=[],S=[];if(n.indexOf("`")>=0){for(let u=0;u<e;){if(n.charCodeAt(u)!==96){u++;continue}let b=u;for(;n.charCodeAt(b)===96;)b++;A.push(u),_.push(b-u),u=b}let d={};for(let u=A.length-1;u>=0;u--)S[u]=_[u]in d?d[_[u]]:-1,d[_[u]]=u}for(;i<e;){let d=n.charCodeAt(i);if(d===92){let u=n.charAt(i+1);if(u===`
8
+ `)h(P(tt,"")),i+=2;else if(Vt(u)){let b=i+2;if(u==="`")for(;n.charCodeAt(b)===96;)b++;g(n.slice(i+1,b)),i=b}else g("\\"),i++}else if(d===96){for(;c<A.length&&A[c]<i;)c++;if(A[c]!==i){g("`"),i++;continue}let u=_[c],b=S[c];if(b<0){g(n.slice(i,i+u)),i+=u;continue}let f=n.slice(i+u,A[b]).replace(/\n/g," ");f.length>1&&f.charAt(0)===" "&&f.charAt(f.length-1)===" "&&/[^ ]/.test(f)&&(f=f.slice(1,-1)),h(P(Me,f)),i=A[b]+u}else if(d===42||d===95||d===126){let u=i+1;for(;n.charCodeAt(u)===d;)u++;let b=n.charAt(i-1),f=n.charAt(u),x=b===""||qt.test(b),C=f===""||qt.test(f),y=Se.test(b),T=Se.test(f),R=!C&&(!T||x||y),E=!x&&(!y||C||T),et=d===95?R&&(!E||y):R,Kt=d===95?E&&(!R||T):E,Qt=P(Wt,n.slice(i,u));if(h(Qt),(et||Kt)&&(d!==126||u-i===2)){let te={l:Qt,ch:n.charAt(i),n:u-i,$:u-i,at:et,ne:Kt,id:a++,i:o,o:null};o&&(o.o=te),o=te}i=u}else if(d===91||d===33&&n.charCodeAt(i+1)===91){let u=d===33,b=P(Wt,u?"![":"[");h(b),s={l:b,V:u,Ct:!0,M:!1,xe:o,i:s},i+=u?2:1}else if(d===93){let u=s,b=u&&u.Ct?Ln(n,i+1):null;if(u&&(s=u.i),!u||!b){u&&u.M&&s&&(s.M=!0),g("]"),i++;continue}v(u.xe);let f=u.l.o,x=bt(b.C);if(u.V||x){let C=!u.V&&f?f:P(j,u.V&&!(x&&u.M)?pt(f):"");if(x&&jn(C),pt(C)||(C=P(j,x?wt(x):b.C)),C.i=null,u.l.o=null,r=u.l,x){let y=jt(x,C),T=u.l.i;if(y.C=Un(pt(C),x),y.C){let R=P(kt,"["+y.C+"] ");T.o=R,R.i=T,T=R}T.o=y,y.i=T,r=y}else u.l.k=j,u.l.s=C.s}else p(u.l);if(!u.V)for(let C=s;C&&C.Ct;C=C.i)C.Ct=!1;s&&(u.V||x||u.M)&&(s.M=!0),i=b.j}else if(d===60){let u=Mn(n,i);if(!u){g("<"),i++;continue}u.L?(h(jt(u.L,P(j,wt(u.L)))),s&&(s.M=!0)):g(u.st),i=u.j}else if(d===38){let u=Be(n,i);u?(g(u[0]),i=u[1]):(g("&"),i++)}else if(d===10)for(h(P(tt,"")),i++;n.charCodeAt(i)===32;)i++;else if((d===104||d===72)&&(l=In(n,i,s!==null))>i){let u=n.slice(i,l),b=bt(u);b?(h(jt(b,P(j,wt(b)))),s&&(s.M=!0)):g(u),i=l}else{let u=i+1;for(;u<e&&!Pn(n.charCodeAt(u));)u++;g(n.slice(i,u)),i=u}}return v(null),t.o}function Rn(n,t){return t.ch==="~"||!((n.ne||t.at)&&(n.$+t.$)%3===0&&(n.$%3!==0||t.$%3!==0))}function pt(n){let t="",e=[];for(;;){if(!n){if(!e.length)return t;n=e.pop();continue}if(n.k===H){e.push(n.o),n=n.q;continue}n.k!==kt&&(t+=n.k===tt?" ":n.s),n=n.o}}function Bt(n,t,e){for(;t<e&&(n.charAt(t)===" "||n.charAt(t)===" "||n.charAt(t)===`
9
+ `);)t++;return t}function Ln(n,t){if(n.charAt(t)!=="(")return null;let e=Math.min(n.length,t+4096);t=Bt(n,t+1,e);let r;if(n.charAt(t)==="<"){let a=++t;for(;t<e;t++){let i=n.charAt(t);if(i==="\\")t++;else if(i===">"||i==="<"||i===`
10
+ `)break}if(n.charAt(t)!==">")return null;r=n.slice(a,t++)}else{let a=t,i=0;for(;t<e;t++){let c=n.charCodeAt(t);if(c===92&&Vt(n.charAt(t+1)))t++;else{if(c<=32)break;if(c===40){if(++i>32)return null}else if(c===41){if(!i)break;i--}}}if(i||t>=e)return null;r=n.slice(a,t)}let o=t;t=Bt(n,t,e);let s=n.charAt(t);if(t>o&&(s==='"'||s==="'"||s==="(")){let a=s==="("?")":s;for(t++;t<e;t++){let i=n.charAt(t);if(i==="\\")t++;else{if(i===a)break;if(s==="("&&i==="(")return null}}if(t>=e)return null;t=Bt(n,t+1,e)}return n.charAt(t)!==")"?null:{C:Nn(r),j:t+1}}function Mn(n,t){let e=Math.min(n.length,t+2048),r=t+1;for(;r<e;){let s=n.charCodeAt(r);if(s<=32||s===60||s===62)break;r++}if(n.charAt(r)!==">"||r===t+1)return null;let o=n.slice(t+1,r);return/^[A-Za-z][A-Za-z0-9+.-]{1,31}:/.test(o)?{st:o,L:bt(o),j:r+1}:/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/.test(o)?{st:o,L:bt("mailto:"+o),j:r+1}:null}function In(n,t,e){let r=n.charAt(t-1);if(r!==""&&!qt.test(r)&&"*_~(".indexOf(r)<0||r==="("&&n.charAt(t-2)==="]")return-1;let o=n.slice(t,t+8).toLowerCase(),s=o.indexOf("https://")===0?t+8:o.indexOf("http://")===0?t+7:-1;if(s<0)return-1;let a=s,i=0,c=0;for(;a<n.length;a++){let l=n.charCodeAt(a);if(l<=32||l===60||l===160||e&&l===93)break;l===40?i++:l===41&&c++}for(;;){let l=n.charAt(a-1);if(`?!.,:*_~'"`.indexOf(l)>=0)a--;else if(l===")"&&c>i)a--,c--;else if(l===";"){let h=a-2;for(;h>s&&Pe.test(n.charAt(h));)h--;if(n.charAt(h)!=="&"||h===a-2)break;a=h}else break}return a>s?a:-1}function Be(n,t){let e=t+1;if(n.charAt(e)==="#"){let o=n.charAt(e+1)==="x"||n.charAt(e+1)==="X",s=o?Cn:Sn,a=e+=o?2:1;for(;e-a<(o?6:7)&&s.test(n.charAt(e));)e++;if(e===a||n.charAt(e)!==";")return null;let i=parseInt(n.slice(a,e),o?16:10);return(!i||i>1114111||i>=55296&&i<=57343)&&(i=65533),[String.fromCodePoint(i),e+1]}for(;e-t<10&&Pe.test(n.charAt(e));)e++;let r=n.slice(t+1,e);return n.charAt(e)===";"&&Object.prototype.hasOwnProperty.call(zt,r)?[zt[r],e+1]:null}function Nn(n){if(n.indexOf("\\")<0&&n.indexOf("&")<0)return n;let t="";for(let e=0;e<n.length;e++){let r=n.charAt(e);if(r==="\\"&&Vt(n.charAt(e+1))){t+=n.charAt(++e);continue}let o=r==="&"?Be(n,e):null;o?(t+=o[0],e=o[1]-1):t+=r}return t}function bt(n){let t;try{t=new URL(n)}catch{return null}return t.username||t.password?null:t.protocol==="mailto:"?Yt(t)?t.href:null:(t.protocol==="https:"||t.protocol==="http:")&&Le.test(t.hostname)?t.href:null}function Yt(n){let t=n.pathname,e=t.lastIndexOf("@"),r=t.slice(e+1);if(e<1||/[/\\?#:]/.test(r))return null;let o,s;try{o=decodeURIComponent(t.slice(0,e)),s=new URL("http://"+r).hostname}catch{return null}return Le.test(s)&&!/[@"()\s]/.test(o)?t.slice(0,e+1)+s+n.search:null}function wt(n){let t=new URL(n),e=t.protocol==="mailto:"?"mailto:"+(Yt(t)||t.pathname):t.protocol+"//"+t.host+Dn(t.pathname+t.search+t.hash);return Ht(e)>200?Fe(e,199)+"\u2026":e}function Dn(n){try{return decodeURI(n).replace(xn,encodeURIComponent)}catch{return n}}function Ht(n){let t=0;for(let e=0;e<n.length;e+=n.codePointAt(e)>65535?2:1)t++;return t}function Fe(n,t){let e=0;for(;t>0&&e<n.length;t--)e+=n.codePointAt(e)>65535?2:1;return n.slice(0,e)}function Un(n,t){let e=new URL(t);if(e.protocol==="mailto:"){let s=Yt(e)||e.pathname;return n===s?"":s}let r=Ft(n),o=e.hostname;return r===Ft(t)||r===Ft(wt(t))||r===o||r==="www."+o?"":o}function jn(n){let t=[],e=[],r="";Bn(n,l=>(l.k===tt&&(l.k=j,l.s=" "),t.push(l),r+=l.s,!0));let o=0,s=0,a=!0,i=-1,c=!1;for(let l of t){let h="";for(let g=o+l.s.length;o<g;){let p=String.fromCodePoint(r.codePointAt(o));if(o+=p.length,!a&&(p===It||p===Nt)&&o>i){for(i=o;i<r.length;){let v=String.fromCodePoint(r.codePointAt(i));if(v!==It&&v!==Nt&&!Ee.test(v))break;i+=v.length}c=i<r.length&&!xe.test(String.fromCodePoint(r.codePointAt(i)))}let m=xe.test(p)&&(a||(p===It||p===Nt?!c:!Ee.test(p)));m&&a||(h+=m?" ":p,s++,a=m)}e.push(h)}for(let l=e.length-1;l>=0;l--)if(e[l]){e[l].charAt(e[l].length-1)===" "&&(e[l]=e[l].slice(0,-1),s--);break}if(s>120){let l=119,h=0;for(;Ht(e[h])<l;)l-=Ht(e[h++]);let g=Fe(e[h],l);for(g.charAt(g.length-1)===" "&&(g=g.slice(0,-1)),e[h]=g+"\u2026";++h<e.length;)e[h]=""}t.forEach((l,h)=>{l.s=e[h]})}function Bn(n,t){let e=[];for(;;){if(!n){if(!e.length)return;n=e.pop();continue}if(n.k===H){e.push(n.o),n=n.q;continue}if(n.k!==kt&&!t(n))return;n=n.o}}function Ft(n){n=n.trim();let t=n.slice(0,8).toLowerCase();return n=t.indexOf("https://")===0?n.slice(8):t.indexOf("http://")===0?n.slice(7):n,n.charAt(n.length-1)==="/"?n.slice(0,-1):n}function Gt(n,t){let e=[];for(let r of n)switch(r.t){case"p":t?Q(gt(r.s),e,0,!1):e.push({tag:"p",children:Q(gt(r.s),[],0,!1)});break;case"pre":e.push(r.Kt?{tag:"pre",language:r.Kt,children:[yt(r.s)]}:{tag:"pre",children:[yt(r.s)]});break;case"blockquote":e.push({tag:"blockquote",children:Gt(r.be||[],!1)});break;case"ul":case"ol":{let o=(r.ve||[]).map(a=>({tag:"li",children:Gt(a,!!r.ke)})),s={tag:r.t,children:o};r.t==="ol"&&r.Z!==1&&(s.start=r.Z),e.push(s);break}case"table":e.push(Fn(r.Ae||[],r._e||[]));break;case"hr":e.push({tag:"hr"});break;default:e.push({tag:r.t,children:Q(gt(r.s),[],0,!1)})}return e}function Fn(n,t){let e=[],r=n.length?n[0].length:0,o=[],s=0;for(let a of n)s+=2*a.length;for(let a=0;a<n.length;a++){a<2&&e.push({tag:a?"tbody":"thead",children:o=[]});let i=n[a].length,c=i;i<r&&(r-i<=s?(s-=r-i,c=r):s=0);let l=[];for(let h=0;h<c;h++){let g={tag:a?"td":"th",children:h<i?Q(gt(n[a][h]),[],0,!1):[]},p=t[h];p&&(g.align=p),l.push(g)}o.push({tag:"tr",children:l})}return{tag:"table",children:e}}function Q(n,t,e,r){let o="";for(;n;n=n.o)if(n.k===j||n.k===Wt)o+=n.s;else if(n.k===kt){if(r||e>=16)continue;ft(t,o),ft(t,n.s),o=""}else if(n.k===H&&(n.s==="a"&&r||e>=16))o+=pt(n.q);else if(ft(t,o),o="",n.k===tt)t.push({tag:"br"});else if(n.k===Me)t.push({tag:"code",children:[yt(n.s)]});else{let s={tag:n.s,children:Q(n.q,[],e+1,r||n.s==="a")};n.s==="a"&&(s.href=n.L,n.C&&(s.dest=n.C)),t.push(s)}return ft(t,o),t}function ft(n,t){t=yt(t),t&&n.push(t)}function yt(n){return n.replace(En,"")}function qe(n,t,e){for(let r of n){if(typeof r=="string"){t.appendChild(e.createTextNode(r));continue}let o=e.createElement(r.tag),s=o;r.tag==="pre"?(s=e.createElement("code"),r.language&&s.setAttribute("class","language-"+r.language),o.appendChild(s)):r.tag==="a"&&r.href?(o.setAttribute("href",r.href),o.setAttribute("target","_blank"),o.setAttribute("rel","noopener noreferrer")):r.tag==="ol"&&r.start!==void 0?o.setAttribute("start",String(r.start)):(r.tag==="th"||r.tag==="td")&&r.align&&(o.style.textAlign=r.align),r.children&&qe(r.children,s,e),t.appendChild(o)}}return Ge(qn);})();
11
11
  //# sourceMappingURL=meandr-chat.js.map