@meandr/chat-sdk 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -10
- package/dist/api.d.ts +4 -1
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +659 -421
- package/dist/index.js.map +3 -3
- package/dist/markdown.js +112 -112
- package/dist/markdown.js.map +3 -3
- package/dist/meandr-chat.js +9 -9
- package/dist/meandr-chat.js.map +3 -3
- package/dist/sse.d.ts +8 -8
- package/dist/token.d.ts +5 -5
- package/dist/types.d.ts +53 -1
- package/package.json +1 -1
package/dist/meandr-chat.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var MeandrChat=(()=>{var
|
|
2
|
-
`,this.
|
|
3
|
-
`+bt(s.ext===void 0||i?null:s.ext)}}catch{return null}}function bt(e){var t;if(Array.isArray(e))return"["+e.map(bt).join(",")+"]";if(e&&typeof e=="object"){let n=e;return"{"+Object.keys(n).sort().map(r=>JSON.stringify(r)+":"+bt(n[r])).join(",")+"}"}return(t=JSON.stringify(e))!=null?t:"null"}function xt(e){try{return new URL(e).origin}catch{return null}}var qe=["url","token","tokenUrl","getToken","fetch"],We=["conversation","message","delta","tool","done","error"],tt=["network","internal","rate_limited","overloaded","not_connected","token_failed"],Ve=1<<20,ze=100,ne=45e3,Xe=65*6e4,_t=6e4,re=12e4,et=[2e3,3e3,5e3,8e3,1e4],He=[1e3,2e3,4e3,8e3,15e3],Je=3e3,Ze=1e4,$e=6e5,Ge=20,oe=[1e3,2e3,4e3,8e3,15e3],se=15e3,Ke=3e3,St={status:"idle",anonymous:null,conversation:null,messages:[],outgoing:null,answer:null,answering:!1,waiting:null,stop:null,error:null};function ce(e){return new Tt(e)}var Tt=class{constructor(t){this.s=St;this.listeners=new Set;this.auth={kind:"cookie"};this.who=null;this.cookieless=!1;this.opening=null;this.session=new AbortController;this.conv=new AbortController;this.convVersion=0;this.wantNew=!1;this.sending=null;this.watcher=null;this.unsure=null;this.maxSeen=0;this.batching=!1;this.dirty=!1;this.dead=!1;this.getState=()=>this.s;this.subscribe=t=>{if(typeof t!="function")throw new TypeError("subscribe needs a function");return this.dead||this.listeners.add(t),this.call(t),()=>{this.listeners.delete(t)}};this.open=()=>{if(this.dead||this.s.status==="ready")return Promise.resolve(this.s);if(!this.opening){let t=this.doOpen();this.opening=t;let n=()=>{this.opening===t&&(this.opening=null)};t.then(n,n)}return this.opening};this.send=t=>{if(typeof t!="string")throw new TypeError("send needs the message's text");return this.doSend(t)};this.start=()=>this.doStart();this.newConversation=()=>{this.dead||(this.s.status!=="ready"&&(this.wantNew=!0),this.dropConversation(),this.set({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.way=kt(n.token);else if(this.way.kind==="token")throw new TypeError("this client was given token: pass reopen({ token }), null when nobody is signed in");if(this.dead)return Promise.resolve(this.s);let r=this.s.status==="idle";return this.forgetUser(),r?Promise.resolve(this.s):this.open()};this.signOut=async()=>{if(this.dead)return;let t=this.auth;this.way.kind==="token"&&(this.way={kind:"token",token:null}),this.forgetUser();let n=new AbortController,r=setTimeout(()=>n.abort(),Ke);try{let o=t.kind==="session"?t.token():null;D(await N(this.fetchFn,this.base,{method:"DELETE",path:"/session",bearer:o,signal:n.signal}))}catch{}finally{clearTimeout(r)}};this.destroy=()=>{this.dead||(this.dropSession(),this.dead=!0,this.listeners.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: your workspace's URL");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new TypeError("fetch must be a function");this.base=te(t.url),this.origin=xt(this.base),this.way=ee(t);let n=t.fetch;this.fetchFn=n?(r,o)=>n(r,o):(r,o)=>fetch(r,o)}set(t){this.s={...this.s,...t},this.batching?this.dirty=!0:this.emit()}emit(){if(!this.dead)for(let t of Array.from(this.listeners))this.call(t)}call(t){try{t(this.s)}catch(n){setTimeout(()=>{throw n})}}seen(t){for(let n of t)n.id>this.maxSeen&&(this.maxSeen=n.id)}current(t){return this.s.conversation!==null&&this.s.conversation.id===t}dropConversation(){this.conv.abort(),this.conv=new AbortController,this.convVersion++,this.sending=null,this.watcher=null,this.unsure=null}dropSession(){this.session.abort(),this.session=new AbortController,this.opening=null,this.dropConversation()}forgetUser(){this.dropSession(),this.auth={kind:"cookie"},this.who=null,this.wantNew=!1,this.maxSeen=0,this.s=St,this.emit()}userChanged(t){this.watcher&&this.watcher.abort(),this.watcher=null,this.convVersion++,this.unsure=null,this.wantNew=!1,this.maxSeen=0,this.s={...St,status:"ready"},this.show(t,this.convVersion,!1)}show(t,n,r){if(this.seen(t.messages),n!==this.convVersion){this.set({anonymous:t.anonymous});return}if(r){this.set({anonymous:t.anonymous,conversation:null,messages:[],answering:!1});return}let o=t.answering&&t.conversation!==null;this.set({anonymous:t.anonymous,conversation:t.conversation,messages:Ct(this.s.messages,t.messages),answering:o}),o&&t.conversation&&this.watch(t.conversation.id)}forget(t){this.current(t)&&this.set({conversation:null,messages:[],answer:null,answering:!1})}async doOpen(){let t=this.session,n=this.convVersion,r=Date.now();this.set({status:"opening",error:null});for(let o=0;;o++)try{let s=await this.establish(t.signal);if(t.signal.aborted)return this.s;let a=this.wantNew;return this.wantNew=!1,this.show(s,n,a),this.set({status:"ready",waiting:null}),this.s}catch(s){if(t.signal.aborted)return this.s;let a=z(s);if(tt.indexOf(a.code)<0||a.code==="token_failed")return this.set({status:"error",error:a,waiting:null}),this.s;let i=Ye(a,o,Date.now()-r);this.set({waiting:{code:a.code,until:Date.now()+i}});try{await V(i,t.signal)}catch{return this.s}}}async establish(t){let n=await Q(this.way,this.fetchFn,t,!1);if(typeof n!="string")return this.openWithout(n===null,t);try{return await this.openAs(n,t)}catch(o){if(!F(o,"token_expired")||!vt(this.way))throw o}let r=await Q(this.way,this.fetchFn,t,!0);return typeof r!="string"?this.openWithout(r===null,t):this.openAs(r,t)}async openAs(t,n){if(!this.mayCarry(t))throw ie(this.origin);let r=ae(t);if(this.cookieless){let s=await this.post({cookieless:!0},t,n);return this.auth={kind:"token",token:j(t)},this.who=r,s}let o=await this.post({},t,n);return o.started&&!await this.cookieKept(n)?(this.cookieless=!0,this.auth={kind:"token",token:j(t)}):this.auth={kind:"cookie"},this.who=r,o}async openWithout(t,n){let r=this.auth;if(r.kind==="session")try{let s=await this.post({},r.token(),n);return this.who="anonymous",s}catch(s){if(!F(s,"session_expired")&&!F(s,"unauthorized"))throw s}if(this.auth={kind:"cookie"},this.cookieless)return this.openCookieless(n);t&&await this.signedIn(n)&&await this.end(n);let o=await this.post({},null,n);if(t&&!o.anonymous)throw new g("protocol","The chat answered for a signed-in user on a page that says nobody is signed in.");return o.started&&!await this.cookieKept(n)?(this.cookieless=!0,this.openCookieless(n)):(this.who=o.anonymous?"anonymous":"cookie",o)}async openCookieless(t){let n=await this.post({cookieless:!0},null,t);if(!n.sessionToken)throw new g("protocol","The chat gave no session token.");return this.auth={kind:"session",token:j(n.sessionToken)},this.who="anonymous",n}async post(t,n,r){let o=await N(this.fetchFn,this.base,{method:"POST",path:"/session",body:t,bearer:n,signal:r});if(!o.ok)throw await P(o,r);let s=en(await G(o,r));return U(r),s}async cookieKept(t){let n=await N(this.fetchFn,this.base,{method:"GET",path:"/session",signal:t});if(n.ok||n.status===401)return D(n),U(t),n.ok;throw await P(n,t)}async signedIn(t){let n=await N(this.fetchFn,this.base,{method:"GET",path:"/session",signal:t});if(n.status===401||n.status===403)return D(n),n.status===403;if(!n.ok)throw await P(n,t);let r=await G(n,t);return!!r&&typeof r=="object"&&r.anonymous===!1}async end(t){let n=await N(this.fetchFn,this.base,{method:"DELETE",path:"/session",signal:t});if(!n.ok)throw await P(n,t);D(n)}mayCarry(t){if((typeof location=="object"&&location?location.origin:null)===this.origin)return!0;let r=At(t);return!!r&&r.aud.some(o=>xt(o)===this.origin)}bearer(){return this.auth.kind==="cookie"?null:this.auth.token()}async authed(t,n,r){for(let o=!1;;o=!0){let s=await N(this.fetchFn,this.base,{...t,bearer:this.bearer(),signal:n});if(s.status!==401||o)return s;let a=await P(s,n);if(!await this.recoverAuth(a,n,r))throw a}}async recoverAuth(t,n,r){if(this.auth.kind==="token"&&(t.code==="token_expired"||t.code==="unauthorized")){if(!vt(this.way))return!1;let s=await Q(this.way,this.fetchFn,n,t.code==="token_expired");if(typeof s=="string"&&ae(s)===this.who){if(!this.mayCarry(s))throw ie(this.origin);return this.auth={kind:"token",token:j(s)},!0}}else if(t.code!=="session_expired"&&t.code!=="unauthorized")return!1;let o=await this.reestablish(n);return this.set({anonymous:o.anonymous}),!0}async reestablish(t){U(t);let n=this.who,r=await this.establish(t);if(U(t),this.who!==n)throw this.userChanged(r),new g("session_expired","Someone else is signed in now.",{status:401});return this.seen(r.messages),r}async doSend(t){let n=Qe(t);if(this.dead)return{ok:!1,error:x()};if(n==="")return{ok:!1,error:new g("bad_request","The message is empty.")};if(this.sending||this.s.answering)return{ok:!1,error:nt()};let r={};this.sending=r;let o=this.conv,s=this.unsure&&this.unsure.text===n?this.unsure:null;this.unsure=null;let a=-1;this.set({outgoing:n,error:null,stop:null});try{if(this.s.status!=="ready"){let u=await this.open();if(o.signal.aborted||this.sending!==r)return{ok:!1,error:x()};if(u.status!=="ready")return this.failed(r,o,u.error||new g("unauthorized","The chat couldn't be opened."),-1);if(this.s.answering)return this.failed(r,o,nt(),-1)}a=this.convVersion,this.set({answering:!0,answer:{text:"",tools:[]}});let i=await this.deliver(n,o.signal,s);return{ok:!0,message:i.message,stop:i.stop}}catch(i){return this.failed(r,o,z(i),a)}finally{this.sending===r&&(this.sending=null)}}async doStart(){if(this.dead)return{ok:!1,error:x()};if(this.sending||this.s.answering)return{ok:!1,error:nt()};let t={};this.sending=t;let n=this.conv,r=-1;this.set({error:null,stop:null});try{if(this.s.status!=="ready"){let s=await this.open();if(n.signal.aborted||this.sending!==t)return{ok:!1,error:x()};if(s.status!=="ready")return this.failed(t,n,s.error||new g("unauthorized","The chat couldn't be opened."),-1);if(this.s.answering)return this.failed(t,n,nt(),-1)}r=this.convVersion,this.set({answering:!0,answer:{text:"",tools:[]}});let o=await this.begin(n.signal);return{ok:!0,message:o.message,stop:o.stop}}catch(o){return this.failed(t,n,z(o),r)}finally{this.sending===t&&(this.sending=null)}}async begin(t){let n={text:"",target:null,known:this.maxSeen},r=this.s.conversation===null?{method:"POST",path:"/start",body:{new:!0},stream:!0}:{method:"POST",path:"/start",stream:!0},o=Date.now()+_t,s=Date.now()+re;for(let a=0;;){let i=new AbortController,u=()=>i.abort();t.addEventListener("abort",u);try{let c;try{c=await this.authed(r,i.signal,null)}catch(k){if(t.aborted)throw x();let p=T(k)?X(k):null;if(p!==null&&Date.now()+p<=o){await this.pause(k.code,p,t);continue}throw k}if(c.ok)return await this.read(c,i,t,n);let f=await P(c,t),w=X(f);if(w!==null&&Date.now()+w<=o){await this.pause(f.code,w,t);continue}if(f.code==="busy"&&Date.now()<s){await this.pause("busy",et[Math.min(a++,et.length-1)],t);continue}throw f}finally{t.removeEventListener("abort",u)}}}failed(t,n,r,o){return this.sending===t&&!n.signal.aborted&&r.code!=="aborted"&&(o<0?this.set({error:r}):o===this.convVersion?this.set({answer:null,answering:!1,waiting:null,error:r}):this.set({answer:null,waiting:null,error:r})),{ok:!1,error:r}}async deliver(t,n,r){if(r){let u=await this.landedSoon(r,n,null);if(u!==null)return this.follow(u,r,n)}let o={text:t,target:this.s.conversation?this.s.conversation.id:null,known:this.maxSeen},s=o.target===null?"/conversations":"/conversations/"+encodeURIComponent(o.target)+"/messages",a=Date.now()+_t,i=Date.now()+re;for(let u=0;;){let c=new AbortController,f=()=>c.abort();n.addEventListener("abort",f);try{let w;try{w=await this.authed({method:"POST",path:s,body:{text:t},stream:!0},c.signal,o.target)}catch(y){if(n.aborted)throw x();if(F(y,"network"))return await this.ifLanded(y,o,n);let v=T(y)?X(y):null;if(v!==null&&Date.now()+v<=a){await this.pause(y.code,v,n);continue}throw y}if(w.ok)return await this.read(w,c,n,o);let k=await P(w,n);if(k.code==="internal")return await this.ifLanded(k,o,n);k.code==="not_found"&&o.target!==null&&this.forget(o.target);let p=X(k);if(p!==null&&Date.now()+p<=a){await this.pause(k.code,p,n);continue}if(k.code==="busy"&&Date.now()<i){await this.pause("busy",et[Math.min(u++,et.length-1)],n);continue}throw k}finally{n.removeEventListener("abort",f)}}}async pause(t,n,r){U(r),this.set({waiting:{code:t,until:Date.now()+n}});try{await V(n,r)}finally{r.aborted||this.set({waiting:null})}}async ifLanded(t,n,r){let o=await this.landedSoon(n,r,t);if(o===null)throw t;return this.follow(o,n,r)}async landedSoon(t,n,r){let o=this.convVersion,s=null;for(let a of He){await V(a,n);try{return await this.landed(t,n)}catch(i){if(n.aborted)throw x();if(s=z(i),this.convVersion!==o)throw s;if(s.code==="not_found")return null;if(tt.indexOf(s.code)<0)break}}throw this.unsure=t,s&&tt.indexOf(s.code)<0?s:r||s||new g("network","The chat couldn't be reached.")}async landed(t,n){let r=s=>s.role==="user"&&s.id>t.known&&s.text===t.text,o=null;if(t.target!==null){let s=await this.view(t.target,n);s.messages.some(r)&&(o=s)}else{let s=await this.latest(n);s.conversation&&s.messages.some(r)&&s.messages.every(a=>a.id>t.known)&&(o={conversation:s.conversation,messages:s.messages})}return U(n),o?(this.seen(o.messages),this.set({conversation:o.conversation,messages:Ct(this.s.messages,o.messages),outgoing:null}),o.conversation.id):null}async latest(t){if(this.auth.kind==="cookie"){let n=await N(this.fetchFn,this.base,{method:"GET",path:"/session",signal:t});if(n.ok){D(n);let r=await this.post({},null,t);if(!r.started)return r}else if(n.status===401)D(n);else throw await P(n,t);return this.reestablish(t)}try{return await this.post(this.auth.kind==="token"?{cookieless:!0}:{},this.bearer(),t)}catch(n){if(!F(n,"token_expired")&&!F(n,"session_expired")&&!F(n,"unauthorized"))throw n;return this.reestablish(t)}}async read(t,n,r,o){let s=o.target,a=!1,i=t.body?t.body.getReader():null;if(i){let u=new TextDecoder,c=new Y,f=()=>{i.cancel().catch(()=>{})};n.signal.addEventListener("abort",f,{once:!0}),n.signal.aborted&&f();let w=setTimeout(()=>n.abort(),ne),k=setTimeout(()=>n.abort(),Xe);try{for(;;){let{value:p,done:y}=await i.read();if(r.aborted)throw x();if(y)break;clearTimeout(w),w=setTimeout(()=>n.abort(),ne),this.batching=!0;try{for(let v of c.push(u.decode(p,{stream:!0}))){if(r.aborted)throw x();if(v.event==="message"&&a)continue;v.event==="message"&&(a=!0);let C=this.event(v.event,v.data);if(C)if("conversation"in C)s=C.conversation;else return C}}finally{this.batching=!1,this.dirty&&(this.dirty=!1,this.emit())}}}catch(p){if(r.aborted)throw x();if(T(p)&&p.code!=="protocol")throw p}finally{clearTimeout(w),clearTimeout(k),n.signal.removeEventListener("abort",f),f()}}if(r.aborted)throw x();return this.follow(s,{...o,target:s},r)}event(t,n){if(We.indexOf(t)<0)return null;let r;try{let o=JSON.parse(n);r=o&&typeof o=="object"?o:{}}catch{throw new g("protocol","The chat's stream couldn't be read.")}switch(t){case"conversation":{let o=Ot(r);return this.s.conversation&&this.s.conversation.id===o.id?this.set({conversation:o}):this.set({conversation:o,messages:[]}),{conversation:o.id}}case"message":{let o=rt(r);return this.seen([o]),this.set({messages:Et(this.s.messages,o),outgoing:null}),null}case"delta":{let o=this.s.answer||{text:"",tools:[]};return typeof r.text!="string"||r.text===""||o.text.length>=Ve||this.set({answer:{text:o.text+r.text,tools:o.tools}}),null}case"tool":{let o=this.s.answer||{text:"",tools:[]};if(typeof r.name!="string"||typeof r.status!="string")return null;let s=tn(o.tools,r.name,r.status);return s!==o.tools&&this.set({answer:{text:o.text,tools:s}}),null}case"done":{let o=rt(r.message),s=typeof r.stop=="string"?r.stop:null;return this.seen([o]),this.set({messages:Et(this.s.messages,o),outgoing:null,answer:null,answering:!1,waiting:null,stop:s}),{message:o,stop:s}}default:{let o=r.partial?rt(r.partial):null;o&&this.seen([o]),this.set({messages:o?Et(this.s.messages,o):this.s.messages,outgoing:null,answer:null,answering:!1});let s=typeof r.error=="string"&&r.error!==""?r.error:"unavailable";throw new g(s,typeof r.message=="string"?r.message:"The answer failed.",{status:200,partial:o})}}}async follow(t,n,r){let o=n.text==="";if(t===null&&o)throw new g("network","The answer was lost.");let s=t!==null?t:await this.landedSoon(n,r,null);if(s===null)throw this.unsure=n,new g("no_answer","The answer was lost.");let a=this.convVersion,i;try{i=await this.poll(s,r)}catch(c){throw!o&&!r.aborted&&!F(c,"not_found")&&a===this.convVersion&&(this.unsure={...n,target:s}),c}U(r),this.current(s)&&this.set({outgoing:null,answer:null,waiting:null});let u;if(o)u=i.messages.filter(c=>c.role==="assistant"&&c.id>n.known).pop();else{let c=i.messages.length-1;for(;c>=0&&!(i.messages[c].role==="user"&&i.messages[c].id>n.known&&i.messages[c].text===n.text);)c--;u=c>=0?i.messages.slice(c+1).find(f=>f.role==="assistant"):void 0}if(!u)throw new g("no_answer","The assistant didn't answer.");return{message:u,stop:null}}async view(t,n){let r=await this.authed({method:"GET",path:"/conversations/"+encodeURIComponent(t)},n,t);if(!r.ok)throw await P(r,n);return nn(await G(r,n))}async poll(t,n){let r=Date.now(),o=0;for(;;){let s=Date.now()-r;if(s>=$e)throw new g("timeout","The answer took too long.");await V(s<6e4?Je:Ze,n);let a;try{a=await this.view(t,n)}catch(i){if(n.aborted)throw x();let u=z(i);if(u.code==="not_found")this.forget(t);else if(tt.indexOf(u.code)>=0&&++o<Ge)continue;throw u}if(o=0,U(n),!a.answering)return this.current(t)&&(this.seen(a.messages),this.set({conversation:a.conversation,messages:Ct(this.s.messages,a.messages),answering:!1})),a}}watch(t){this.watcher&&this.watcher.abort();let n=new AbortController;this.watcher=n;let r=this.conv.signal,o=()=>n.abort();r.addEventListener("abort",o,{once:!0}),this.poll(t,n.signal).then(()=>{},()=>{!n.signal.aborted&&this.current(t)&&this.set({answering:!1})}).then(()=>{r.removeEventListener("abort",o),this.watcher===n&&(this.watcher=null)})}};function Ye(e,t,n){let r=X(e);return n<_t?r!=null?r:oe[Math.min(t,oe.length-1)]:Math.max(r!=null?r:0,se+Math.random()*se)}function X(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 nt(){return new g("busy","Still answering the previous message.")}function ie(e){return new g("token_failed","The token is for another chat: its aud must be "+e+".")}function U(e){if(e.aborted)throw x()}function F(e,t){return T(e)&&e.code===t}function z(e){return T(e)?e:new g("protocol",e instanceof Error?e.message:"Something went wrong.",{cause:e})}function ae(e){let t=At(e);return t?t.who:"token"}function Qe(e){let t="",n=0;for(let a=0;a<e.length;a++){let i=e.charCodeAt(a);i>=55296&&i<=56319&&a+1<e.length&&(e.charCodeAt(a+1)&64512)===56320?a++:(i&63488)===55296&&(t+=e.slice(n,a)+"\uFFFD",n=a+1)}let r=n===0?e:t+e.slice(n),o=0,s=r.length;for(;o<s&&le(r.charCodeAt(o));)o++;for(;s>o&&le(r.charCodeAt(s-1));)s--;return r.slice(o,s)}function le(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 Ct(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)?o:r})}function Et(e,t){return e.some(n=>n.id===t.id)?e.map(n=>n.id===t.id?t:n):e.concat(t)}function tn(e,t,n){if(n!=="started"){for(let r=e.length-1;r>=0;r--)if(e[r].name===t&&e[r].status==="started")return e.slice(0,r).concat({name:t,status:n},e.slice(r+1))}return e.length>=ze?e:e.concat({name:t,status:n})}function ot(e){return new g("protocol","The chat sent "+e+" the client can't read.")}function Ot(e){var n,r;let t=e;if(!t||typeof t!="object"||typeof t.id!="string")throw ot("a conversation");return{id:t.id,createdAt:String((n=t.created_at)!=null?n:""),updatedAt:String((r=t.updated_at)!=null?r:"")}}function rt(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 ot("a message");let n={id:t.id,role:t.role,text:t.text,createdAt:String((r=t.created_at)!=null?r:"")};return Array.isArray(t.tools)&&(n.tools=t.tools.filter(o=>typeof o=="string")),n}function ue(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&(t.role==="user"||t.role==="assistant")).map(rt):[]}function en(e){let t=e;if(!t||typeof t!="object")throw ot("a session");return{anonymous:t.anonymous===!0,started:t.started===!0,conversation:t.conversation?Ot(t.conversation):null,messages:ue(t.messages),answering:t.answering===!0,sessionToken:typeof t.session_token=="string"&&t.session_token!==""?t.session_token:null}}function nn(e){let t=e;if(!t||typeof t!="object")throw ot("a conversation");return{conversation:Ot(t.conversation),messages:ue(t.messages),answering:t.answering===!0}}var rn="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",he=/[\p{P}\p{S}]/u,Ut=/\s/,on=/^[A-Za-z0-9_+-]+$/,we=/[A-Za-z0-9]/,sn=/[0-9A-Fa-f]/,an=/[0-9]/;var me="\u2800\u3164\u115F\u1160\uFFA0",fe=new RegExp("[\\s\\p{Default_Ignorable_Code_Point}"+me+"]","u"),ln=new RegExp("[\\s\\p{Cc}\\p{Default_Ignorable_Code_Point}"+me+"]","gu"),Mt="\u200C",Pt="\u200D",de=new RegExp("[\uFE00-\uFE0F"+String.fromCodePoint(917760)+"-"+String.fromCodePoint(917999)+"]","u"),be=/^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])$/,cn=new RegExp("[\u202A-\u202E\u2066-\u2069]","g"),Ft={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Lt="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<Lt.length;e+=2)Ft[Lt[e]]=String.fromCharCode(parseInt(Lt[e+1],16));var I=0,jt=1,B=2,J=3,ke=4,gt=5;function zt(e){let t=String(e==null?"":e).replace(/\r\n?/g,`
|
|
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,`
|
|
4
4
|
`).split(`
|
|
5
|
-
`).map(
|
|
6
|
-
`),
|
|
7
|
-
`)})}}return{
|
|
8
|
-
`)
|
|
9
|
-
`);)t++;return t}function
|
|
10
|
-
`)break}if(e.charAt(t)!==">")return null;r=e.slice(a,t++)}else{let a=t,i=0;for(;t<n;t++){let
|
|
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&>(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);})();
|
|
11
11
|
//# sourceMappingURL=meandr-chat.js.map
|