@aikaara/chat-sdk 1.5.3 → 1.5.5

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.
@@ -5,7 +5,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
5
5
  `+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
6
6
  `+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Te=0;Te<z.length;Te++)Ae[Te]=oe(z,Te)?ie(z[Te],z):""}var Oe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Oe.length;tt++)et["$"+Oe[tt]]=Oe[tt]}for(var qe in z)oe(z,qe)&&(Ee&&String(Number(qe))===qe&&qe<z.length||D&&et["$"+qe]instanceof Symbol||(E.call(/[^\w$]/,qe)?Ae.push(ie(qe,z)+": "+ie(z[qe],z)):Ae.push(qe+": "+ie(z[qe],z))));if(typeof T=="function")for(var rt=0;rt<Oe.length;rt++)ae.call(z,Oe[rt])&&Ae.push("["+ie(Oe[rt])+"]: "+ie(z[Oe[rt]],z));return Ae}return Lr}function Rh(){if(ro)return jr;ro=!0;var s=Gt(),e=yh(),t=Mh(),r=cr(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),h=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},b=function(y,w){var m=p(y,w);return m&&m.value},d=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},g=function(y,w){return!!p(y,w)};return jr=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return i(y,x)}else if(n){if(w)return c(w,x)}else if(m)return b(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return h(w,x)}else if(m)return g(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),d(m,x,v))}};return _},jr}function Eo(){if(no)return Ur;no=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Ur={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Ur}function dl(){if(io)return Br;io=!0;var s=Eo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},i=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,_)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,_):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,_):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,O=[],P=0;P<I.length;++P){var j=I.charCodeAt(P);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===s.RFC1738&&(j===40||j===41)){O[O.length]=I.charAt(P);continue}if(j<128){O[O.length]=r[j];continue}if(j<2048){O[O.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){O[O.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}P+=1,j=65536+((j&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=O.join("")}return E},h=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return o(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},d=function(y,w){return[].concat(y,w)},g=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Br={arrayToObject:n,assign:a,combine:d,compact:h,decode:l,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},Br}function Lh(){if(oo)return Dr;oo=!0;var s=Rh(),e=dl(),t=Eo(),r=Object.prototype.hasOwnProperty,o={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,a=function(g,y){i.apply(g,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(g){return l.call(g)},skipNulls:!1,strictNullHandling:!1},h=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},b=function g(y,w,m,_,x,v,E,S,I,O,P,j,T,q,D,U,ae,Y){for(var V=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof O=="function"?V=O(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(h(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(O))te=O;else{var we=Object.keys(V);te=P?we.sort(P):we}var K=S?w.replace(/\./g,"%2E"):w,N=_&&n(V)&&V.length===1?K+"[]":K;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],G=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&G===null)){var J=j&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,F);var oe=s();oe.set(p,Y),a(be,g(G,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,j,T,q,D,U,ae,oe))}}return be},d=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],_=u.filter;(typeof g.filter=="function"||n(g.filter))&&(_=g.filter);var x;if(g.arrayFormat in o?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Dr=function(g,y){var w=g,m=d(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=s(),O=0;O<_.length;++O){var P=_[O];m.skipNulls&&w[P]===null||a(v,b(w[P],P,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},Dr}function Nh(){if(so)return Fr;so=!0;var s=dl(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:s.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(p){return p.replace(/&#(\d+);/g,function(b,d){return String.fromCharCode(parseInt(d,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,b){var d={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,w=g.split(b.delimiter,y),m=-1,_,x=b.charset;if(b.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===i&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=b.decoder(v,r.decoder,x,"key"),O=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,S),r.decoder,x,"key"),O=s.maybeMap(n(v.slice(S+1),b),function(j){return b.decoder(j,r.decoder,x,"value")})),O&&b.interpretNumericEntities&&x==="iso-8859-1"&&(O=o(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(d,I);P&&b.duplicates==="combine"?d[I]=s.combine(d[I],O):(!P||b.duplicates==="last")&&(d[I]=O)}return d},c=function(p,b,d,g){for(var y=g?b:n(b,d),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&d.parseArrays)m=d.allowEmptyArrays&&(y===""||d.strictNullHandling&&y===null)?[]:[].concat(y);else{m=d.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=d.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!d.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&d.parseArrays&&E<=d.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,d,g){if(p){var y=d.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=d.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!d.plainObjects&&e.call(Object.prototype,x)&&!d.allowPrototypes)return;v.push(x)}for(var E=0;d.depth>0&&(_=m.exec(y))!==null&&E<d.depth;){if(E+=1,!d.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!d.allowPrototypes)return;v.push(_[1])}if(_){if(d.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+d.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,b,d,g)}},h=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var b=typeof p.charset>"u"?r.charset:p.charset,d=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(d!=="combine"&&d!=="first"&&d!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:b,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||s.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:d,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Fr=function(p,b){var d=h(b);if(p===""||p===null||typeof p>"u")return d.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,d):p,y=d.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var _=w[m],x=u(_,g[_],d,typeof p=="string");y=s.merge(y,x,d)}return d.allowSparse===!0?y:s.compact(y)},Fr}function jh(){if(ao)return $r;ao=!0;var s=Lh(),e=Nh(),t=Eo();return $r={formats:t,parse:e,stringify:s},$r}function Uh(){if(lo)return xt;lo=!0;var s=kt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
7
  `," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=jh();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",P=v.split(O),j=/\\/g;P[0]=P[0].replace(j,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=o.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&d[D])&&(T=T.substr(2),this.slashes=!0)}if(!d[D]&&(ae||D&&!g[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var V=0;V<l.length;V++){var re=T.indexOf(l[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,be=Q.length;V<be;V++){var te=Q[V];if(te&&!te.match(h)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(h)){var ne=Q.slice(0,V),W=Q.slice(V+1),G=te.match(p);G&&(ne.push(G[1]),W.unshift(G[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!b[U])for(var V=0,be=a.length;V<be;V++){var oe=a[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),g[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",de=this.search||"";this.path=J+de}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",O=!1,P="";this.host?O=v+this.host:this.hostname&&(O=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(O+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(P=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||P&&"?"+P||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&O!==!1?(O="//"+(O||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+O+S+j+I};function _(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),O=0;O<I.length;O++){var P=I[O];S[P]=this[P]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var q=j[T];q!=="protocol"&&(S[q]=v[q])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!d[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||Q[0]==="")),F)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Q=be;else if(be.length)Q||(Q=[]),Q.pop(),Q=Q.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,W=Q.length;W>=0;W--)K=Q[W],K==="."?Q.splice(W,1):K===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},xt.parse=w,xt.resolve=_,xt.resolveObject=x,xt.format=m,xt.Url=e,xt}function fl(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Wr?Bh(s):Dh(s)}function Bh(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Al,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<Sl||r>El||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Dh(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function pl(s){let e=eo.resolve(s),t=s.charCodeAt(s.length-1);(t===xl||Wr&&t===kl)&&e[e.length-1]!==eo.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Il,"%25")),!Wr&&e.includes("\\")&&(e=e.replace(Tl,"%5C")),e.includes(`
8
- `)&&(e=e.replace(Cl,"%0A")),e.includes("\r")&&(e=e.replace(Ol,"%0D")),e.includes(" ")&&(e=e.replace(Pl,"%09")),r.pathname=e,r}var ml,Lr,to,Nr,jr,ro,Ur,no,Br,io,Dr,oo,Fr,so,$r,ao,xt,lo,ze,Fs,gl,bl,yl,vl,wl,_l,kl,xl,Sl,El,Wr,Al,Il,Tl,Cl,Ol,Pl,Fh=Je(()=>{le(),ue(),ce(),nh(),vh(),Ph(),ul(),ml=Object.freeze(Object.create(null)),Lr={},to=!1,Nr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,$r={},ao=!1,xt={},lo=!1,ze=Uh(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Fs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=pl,ze.fileURLToPath=fl,gl=ze.Url,bl=ze.format,yl=ze.resolve,vl=ze.resolveObject,wl=ze.parse,_l=ze.URL,kl=92,xl=47,Sl=97,El=122,Wr=Fs==="win32",Al=/\//g,Il=/%/g,Tl=/\\/g,Cl=/\n/g,Ol=/\r/g,Pl=/\t/g}),$h=pe((s,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Ao=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=jt(),t=($e(),Me(Fe));function r(n,i){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),pr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=($e(),Me(Fe)),r=e($h()),o=e(pt()),n=jt(),i=e(Qr()),a=Ao(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function d(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=d(w,m),I=P(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new a.BufferedDuplex(m,I,S),O?S.addEventListener("open",j):S.onopen=j),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=y}),Io={};zt(Io,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Ml,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ml,Rl=Je(()=>{le(),ue(),ce(),Ml={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),Ll=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),$s=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((Rl(),Me(Io))),r=e(pt()),o=e(Ll()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),Nl={};zt(Nl,{default:()=>jl});var jl,qh=Je(()=>{le(),ue(),ce(),jl={}}),qs=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(qh(),Me(Nl)),r=e((Rl(),Me(Io))),o=e(pt()),n=e(Ll()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let d=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:d})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=a(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};s.default=l}),Hs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i;function a(){let p=new t.Transform;return p._write=(b,d,g)=>{o.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{o.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let d=p.protocol==="wxs"?"wss":"ws",g=`${d}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${d}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let d=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);o=wx.connectSocket({url:g,protocols:[d]}),n=a(),i=new r.BufferedDuplex(b,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=h}),Ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(d,g,y)=>{o.sendSocketMessage({data:d.buffer,success(){y()},fail(){y(new Error)}})},b._flush=d=>{o.closeSocket({success(){d()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,d){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,d)),y}function h(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(b=>{if(typeof b.data=="string"){let d=e.Buffer.from(b.data,"base64");n.push(d)}else{let d=new FileReader;d.addEventListener("load",()=>{if(d.result instanceof ArrayBuffer){n.push(e.Buffer.from(d.result));return}n.push(e.Buffer.from(d.result,"utf-8"))}),d.readAsArrayBuffer(b.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(b=>{i.destroy(b)}))}var p=(b,d)=>{if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");let g=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";c(d);let y=u(d,b);return o=d.my,o.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(d,n,o),h(),i};s.default=p}),Hh=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Fh(),Me(hl))),o=e(_i()),n=e(Qr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,d]=p;h.username=b,h.password=d}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=pr().streamBuilder,a.wss=pr().streamBuilder,a.mqtt=$s().default,a.tcp=$s().default,a.ssl=qs().default,a.tls=a.ssl,a.mqtts=qs().default):(a.ws=pr().browserStreamBuilder,a.wss=pr().browserStreamBuilder,a.wx=Hs().default,a.wxs=Hs().default,a.ali=Ws().default,a.alis=Ws().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let d=new o.default(b,p);return d.on("error",()=>{}),d}function u(h,p,b=!0){return new Promise((d,g)=>{let y=c(h,p),w={connect:_=>{m(),d(y)},end:()=>{m(),d(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}s.default=c}),zs=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(b,d,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(d,g);(!w||("get"in w?!d.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return d[g]}}),Object.defineProperty(b,y,w)}:function(b,d,g,y){y===void 0&&(y=g),b[y]=d[g]}),t=s&&s.__setModuleDefault||(Object.create?function(b,d){Object.defineProperty(b,"default",{enumerable:!0,value:d})}:function(b,d){b.default=d}),r=s&&s.__importStar||(function(){var b=function(d){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(d)};return function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var y=b(d),w=0;w<y.length;w++)y[w]!=="default"&&e(g,d,y[w]);return t(g,d),g}})(),o=s&&s.__exportStar||function(b,d){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(d,g)&&e(d,b,g)},n=s&&s.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Xa());s.DefaultMessageIdProvider=a.default;var l=n(th());s.UniqueMessageIdProvider=l.default;var c=n(Na());s.Store=c.default;var u=r(Hh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ol());s.KeepaliveManager=h.default,s.Client=i.default,o(_i(),s),o(Kt(),s),o(La(),s);var p=Yr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Wh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(zs());s.default=n,o(zs(),s)});const zh=Wh();const Vh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},Kh=300,Gh={templateId:"7",type:"link",isDeepLink:!0},Yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ul{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Vh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=h=>{a||(a=!0,clearTimeout(u),h())},c=(h,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=zh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),a||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Gh,...this.config.fileTemplate??{},...Jh(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Kh){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:h,raw:o};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Yh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Jh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Bl(s,e){return(s.sender??"").toString()===e}function Dl(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function To(s){const e={raw:s},t=s.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Fl(s){const e=To(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Vs(s,e,t){const r=Dl(s,t),o=To(s),n=Fl(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Qh(s.status):"delivered",h={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(h.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:o}}function Qh(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class $l extends fo{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new ra(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new na,this.conversationManager=new oa(e.conversationId),this.usesAikaara()&&(this.connection=new ta(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Vs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(h){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",h)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Vs(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Bl(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ks={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Xh(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Zh(s,e,t){const r=Xh(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Ks[r]?Ks[r]:t}function rn(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ed(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function ql(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Zh(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=rn(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=ed(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const d=s.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):b,g=await fetch(d,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(rn(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:s.viewerTemplate?rn(s.viewerTemplate,i):b.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Co(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const td="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Hl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??td;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const rd="^[A-Z]{4}[0-9]{5}[A-Z]$",nd="^[A-Z]{4}0[A-Z0-9]{6}$",id={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:rd,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},od={id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},sd={id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},ad={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},ld={id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:nd,maxLength:11}]}],submitLabel:"Save"},cd=[id,ad,od,sd,ld];function ud(s,e){const t=s||{},r={userId:Yt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=co(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Pe(t.bizName)!==void 0||o>0;r.businessName=Pe(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Pe(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Pe(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Pe(t.bankAccountNumber),r.bankIfscCode=Pe(t.bankIfscCode),(Pe(t.bankAccountNumber)||Pe(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Pe(t.bankAccountNumber),bankIfscCode:Pe(t.bankIfscCode)}]);const a={description:Pe(t.immovableAssetDescription),flatNo:Pe(t.immovableAssetFlatNo),area:Pe(t.immovableAssetArea),pinCode:Pe(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=nn(t.hpDetails,hd);l.length&&(r.hpDetails=l);const c=nn(t.salaryDetails,dd);if(c.length){r.salaryIncome=c;const u=nn(t.salaryDetails,p=>({grossSalary:Ie(p.grossSalary),employerName:Pe(p.employerName)}));u.length&&(r.salary=u);const h=Wl(t.salaryDetails)[0]??{};r.hraAmount=Ie(h.hraReceived),r.leaveTravelAllowanceAmount=Ie(h.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(h.leaveEncashment),r.anyOtherAllowanceAmount=Ie(h.anyOtherAllowance),r.salaryIncomeFlag=!0}return zr(r)}function hd(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Pe(s.loanTakenFrom),bankOrInstituteName:Pe(s.lenderName),loanAccountNo:Pe(s.loanAccountNumber),loanSanctionDate:yd(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Pe(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:co(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Pe(s.housePropertyAddress),housePropertyPincode:Pe(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Pe(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:co(s.hasCoOwnedProperty),coOwnerName:Pe(s.coOwnerName),coOwnerPan:Pe(s.coOwnerPan),coOwnerShare:Pe(s.coOwnerShare),loanDetails:t?[e]:void 0}}function dd(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Pe(s.employerName),employerTan:Pe(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function fd(s,e){const t=[];for(const r of s){const o=Pe(r.employerName),n=Pe(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function pd(s,e){const t=Pe(s.aadhaarNumber),r=Pe(s.bankAccountNumber),o=Pe(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function md(s,e){return{userId:Yt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function gd(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function bd(s,e){const t=(o,n,i,a)=>{const l=Pe(s[o]),c=Pe(s[n]),u=Ie(s[i]),h=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&h===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:h??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Yt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Pe(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function co(s){return s===!0||s===!1?s:void 0}function yd(s){const e=Pe(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Wl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function nn(s,e){return Wl(s).map(t=>zr(e(t))).filter(t=>t!==void 0)}function zr(s){if(Array.isArray(s)){const e=s.map(zr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=zr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function vd(s){const e=s&&typeof s=="object"?s:{},t={},r=De(e.employers),o=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(h=>{const p=on(h.salary),b=on(h.perquisites),d=on(h.profitsInLieuOfSalaryType),g=p+b+d,y=_d(h.allowance);return{employerName:Re(h.employerName),employerTan:Re(h.employerTAN),basicSalary:p||void 0,grossSalary:g||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:wd(h,o,r)??Ne(h.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(h=>{const p=De(h.loanDetails),b=p.length?p[0]:void 0,d=Ne(h.grossAnnualRentReceived),g=p.length?p.reduce((x,v)=>x+(Ne(v.interest)??0),0):void 0,y=De(h.tenant),w=De(h.coOwners),m=y[0],_=w[0];return{typeOfHouseProperty:Re(h.propertyType),loanTakenFrom:Re(b?.loanTakenFrom),lenderName:Re(b?.bankOrInstituteName),loanAccountNumber:Re(b?.loanAccountNo),sanctionDate:Re(b?.loanSanctionDate),totalLoanAmount:Ne(b?.totalLoanAmount),outstandingAmount:Ne(b?.loanOutstandingAmount),homeLoanInterest:g,homeLoanPrinciple:void 0,housePropertyAddress:Re(h.address),housePropertyPincode:Re(h.pinCode),rentalIncome:d,nameOfTenant:Re(m?.name),propertyTax:Ne(h.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Re(_?.name),coOwnerPan:Re(_?.panNumber),coOwnerShare:Ne(_?.share)?.toString()}})),t.us80cAmount=Tt(De(e.deductionUS80CDetails).map(h=>Ne(h.amount))),t.us80dForSelfAndFamilyAmount=Tt(De(e.deductionUS80DDetails).map(h=>Ne(h.healthInsuranceAmount)));const i=De(e.incomes),a=h=>Tt(i.filter(p=>Re(p.incomeType)===h).map(p=>Ne(p.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Tt(De(e.dividendIncomes).map(h=>Ne(h.income)));const l=e.business;if(l){const h=De(l.presumptiveIncomes),p=g=>{const y=De(g.incomes),w=m=>Ne(y.find(_=>Re(_.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Re(g.businessType)?.toUpperCase().includes("PROFESSION")},b=g=>h.find(y=>p(y)===g),d=(g,y)=>{if(!g)return;const w=De(g.incomes),m=x=>Ne(w.find(v=>Re(v.incomeType)===x)?.receipts),_=m("BANK")||m("ANY_OTHER");t[y.name]=Re(g.businessType),t[y.nature]=Re(g.natureOfBusiness),t[y.bank]=_||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Tt(w.map(x=>Ne(x.presumptiveIncome)))||void 0};d(b(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),d(b(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=De(e.capitalGain).filter(h=>Re(h.assetType)?.toUpperCase()==="VDA").flatMap(h=>De(h.assetDetails));c.length&&(t.cryptoSellPrice=Tt(c.map(h=>Ne(h.sellValue))),t.cryptoPurchasePrice=Tt(c.map(h=>Ne(h.purchaseCost)))),t.agricultureIncome=Ne(e.agriculturalDetails?.income),t.aadhaarNumber=Re(e.aadharNumber);const u=De(e.bankDetails)[0];return u&&(t.bankAccountNumber=Re(u.accountNumber),t.bankIfscCode=Re(u.ifsCode)),zl(t)}function on(s){return De(s).reduce((e,t)=>e+(Ne(t.taxableAmount)??0),0)}function wd(s,e,t){if(!e.length)return;const r=Re(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Re(n.deductorTAN)?.trim().toUpperCase()===r)return Ne(n.totalTdsDeposited)}const o=Re(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Re(n.deductorName)?.trim().toLowerCase()===o)return Ne(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ne(e[0].totalTdsDeposited)}function _d(s){const e=De(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ne(i.exemptAmount)??Ne(i.allowanceAmount);switch(Re(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ne(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Tt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ne(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Re(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function zl(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?zl(o):o):e[t]=r);return e}function sn(){if(typeof window>"u")return null;const s=window,e=s.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=s.__aikaara_descriptor__??{},r=Cd(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=Od(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):Md(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Pd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Rd(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function kd(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return vd(Oo(await r.json().catch(()=>({}))))}async function xd(s,e){const t=await s.getToken(),r=s.userId,o={...ud(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Oo(await a.json().catch(()=>({})))}async function Sd(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function Ed(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Ad(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Id(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Td(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function ur(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Oo(await n.json().catch(()=>({})))}function Cd(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function Od(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function Pd(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function Md(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Oo(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Rd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class Ld{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new $l(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:cd,data:{}});const t=sn();if(!(!t||!t.baseUrl))try{const r=await kd(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=sn();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=fd(n,o);i&&await Sd(r,i)}else if(e==="bank-details"){const n=pd(t,o);n&&await Ed(r,n)}else if(e==="other-sources")await Ad(r,md(t,o));else if(e==="business-profession"){const n=bd(t,o);n&&await Id(r,n)}else if(e==="crypto-income"){const n=gd(t,o);n&&await Td(r,n)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=sn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await xd(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class Vl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||jc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Mo,position:this.getAttribute("position")||this._config.position||Nc,width:Number(this.getAttribute("width"))||this._config.width||Pc,height:Number(this.getAttribute("height"))||this._config.height||Mc,fontFamily:this._config.fontFamily||Lc,borderRadius:this._config.borderRadius??Rc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ro,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Uc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
8
+ `)&&(e=e.replace(Cl,"%0A")),e.includes("\r")&&(e=e.replace(Ol,"%0D")),e.includes(" ")&&(e=e.replace(Pl,"%09")),r.pathname=e,r}var ml,Lr,to,Nr,jr,ro,Ur,no,Br,io,Dr,oo,Fr,so,$r,ao,xt,lo,ze,Fs,gl,bl,yl,vl,wl,_l,kl,xl,Sl,El,Wr,Al,Il,Tl,Cl,Ol,Pl,Fh=Je(()=>{le(),ue(),ce(),nh(),vh(),Ph(),ul(),ml=Object.freeze(Object.create(null)),Lr={},to=!1,Nr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,$r={},ao=!1,xt={},lo=!1,ze=Uh(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Fs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=pl,ze.fileURLToPath=fl,gl=ze.Url,bl=ze.format,yl=ze.resolve,vl=ze.resolveObject,wl=ze.parse,_l=ze.URL,kl=92,xl=47,Sl=97,El=122,Wr=Fs==="win32",Al=/\//g,Il=/%/g,Tl=/\\/g,Cl=/\n/g,Ol=/\r/g,Pl=/\t/g}),$h=pe((s,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Ao=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=jt(),t=($e(),Me(Fe));function r(n,i){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),pr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=($e(),Me(Fe)),r=e($h()),o=e(pt()),n=jt(),i=e(Qr()),a=Ao(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function d(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=d(w,m),I=P(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new a.BufferedDuplex(m,I,S),O?S.addEventListener("open",j):S.onopen=j),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=y}),Io={};zt(Io,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Ml,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ml,Rl=Je(()=>{le(),ue(),ce(),Ml={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),Ll=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),$s=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((Rl(),Me(Io))),r=e(pt()),o=e(Ll()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),Nl={};zt(Nl,{default:()=>jl});var jl,qh=Je(()=>{le(),ue(),ce(),jl={}}),qs=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(qh(),Me(Nl)),r=e((Rl(),Me(Io))),o=e(pt()),n=e(Ll()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let d=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:d})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=a(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};s.default=l}),Hs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i;function a(){let p=new t.Transform;return p._write=(b,d,g)=>{o.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{o.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let d=p.protocol==="wxs"?"wss":"ws",g=`${d}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${d}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let d=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);o=wx.connectSocket({url:g,protocols:[d]}),n=a(),i=new r.BufferedDuplex(b,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=h}),Ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(d,g,y)=>{o.sendSocketMessage({data:d.buffer,success(){y()},fail(){y(new Error)}})},b._flush=d=>{o.closeSocket({success(){d()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,d){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,d)),y}function h(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(b=>{if(typeof b.data=="string"){let d=e.Buffer.from(b.data,"base64");n.push(d)}else{let d=new FileReader;d.addEventListener("load",()=>{if(d.result instanceof ArrayBuffer){n.push(e.Buffer.from(d.result));return}n.push(e.Buffer.from(d.result,"utf-8"))}),d.readAsArrayBuffer(b.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(b=>{i.destroy(b)}))}var p=(b,d)=>{if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");let g=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";c(d);let y=u(d,b);return o=d.my,o.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(d,n,o),h(),i};s.default=p}),Hh=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Fh(),Me(hl))),o=e(_i()),n=e(Qr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,d]=p;h.username=b,h.password=d}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=pr().streamBuilder,a.wss=pr().streamBuilder,a.mqtt=$s().default,a.tcp=$s().default,a.ssl=qs().default,a.tls=a.ssl,a.mqtts=qs().default):(a.ws=pr().browserStreamBuilder,a.wss=pr().browserStreamBuilder,a.wx=Hs().default,a.wxs=Hs().default,a.ali=Ws().default,a.alis=Ws().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let d=new o.default(b,p);return d.on("error",()=>{}),d}function u(h,p,b=!0){return new Promise((d,g)=>{let y=c(h,p),w={connect:_=>{m(),d(y)},end:()=>{m(),d(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}s.default=c}),zs=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(b,d,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(d,g);(!w||("get"in w?!d.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return d[g]}}),Object.defineProperty(b,y,w)}:function(b,d,g,y){y===void 0&&(y=g),b[y]=d[g]}),t=s&&s.__setModuleDefault||(Object.create?function(b,d){Object.defineProperty(b,"default",{enumerable:!0,value:d})}:function(b,d){b.default=d}),r=s&&s.__importStar||(function(){var b=function(d){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(d)};return function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var y=b(d),w=0;w<y.length;w++)y[w]!=="default"&&e(g,d,y[w]);return t(g,d),g}})(),o=s&&s.__exportStar||function(b,d){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(d,g)&&e(d,b,g)},n=s&&s.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Xa());s.DefaultMessageIdProvider=a.default;var l=n(th());s.UniqueMessageIdProvider=l.default;var c=n(Na());s.Store=c.default;var u=r(Hh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ol());s.KeepaliveManager=h.default,s.Client=i.default,o(_i(),s),o(Kt(),s),o(La(),s);var p=Yr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Wh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(zs());s.default=n,o(zs(),s)});const zh=Wh();const Vh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},Kh=300,Gh={templateId:"7",type:"link",isDeepLink:!0},Yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ul{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Vh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=h=>{a||(a=!0,clearTimeout(u),h())},c=(h,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=zh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),a||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Gh,...this.config.fileTemplate??{},...Jh(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Kh){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:h,raw:o};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Yh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Jh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Bl(s,e){return(s.sender??"").toString()===e}function Dl(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function To(s){const e={raw:s},t=s.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Fl(s){const e=To(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Vs(s,e,t){const r=Dl(s,t),o=To(s),n=Fl(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Qh(s.status):"delivered",h={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(h.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:o}}function Qh(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class $l extends fo{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new ra(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new na,this.conversationManager=new oa(e.conversationId),this.usesAikaara()&&(this.connection=new ta(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Vs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(h){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",h)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Vs(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Bl(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ks={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Xh(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Zh(s,e,t){const r=Xh(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Ks[r]?Ks[r]:t}function rn(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ed(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function ql(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Zh(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=rn(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=ed(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const d=s.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):b,g=await fetch(d,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(rn(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:s.viewerTemplate?rn(s.viewerTemplate,i):b.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Co(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const td="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Hl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??td;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const rd="^[A-Z]{4}[0-9]{5}[A-Z]$",nd="^[A-Z]{4}0[A-Z0-9]{6}$",id={id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name",required:!0},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account No.",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},od={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:rd,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},sd={id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},ad={id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},ld={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},cd={id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:nd,maxLength:11}]}],submitLabel:"Save"},ud=[od,ld,sd,ad,id,cd];function hd(s,e){const t=s||{},r={userId:Yt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=co(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Pe(t.bizName)!==void 0||o>0;r.businessName=Pe(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Pe(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Pe(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Pe(t.bankAccountNumber),r.bankIfscCode=Pe(t.bankIfscCode),(Pe(t.bankAccountNumber)||Pe(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Pe(t.bankAccountNumber),bankIfscCode:Pe(t.bankIfscCode)}]);const a={description:Pe(t.immovableAssetDescription),flatNo:Pe(t.immovableAssetFlatNo),area:Pe(t.immovableAssetArea),pinCode:Pe(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=nn(t.hpDetails,dd);l.length&&(r.hpDetails=l);const c=nn(t.salaryDetails,fd);if(c.length){r.salaryIncome=c;const u=nn(t.salaryDetails,p=>({grossSalary:Ie(p.grossSalary),employerName:Pe(p.employerName)}));u.length&&(r.salary=u);const h=Wl(t.salaryDetails)[0]??{};r.hraAmount=Ie(h.hraReceived),r.leaveTravelAllowanceAmount=Ie(h.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(h.leaveEncashment),r.anyOtherAllowanceAmount=Ie(h.anyOtherAllowance),r.salaryIncomeFlag=!0}return zr(r)}function dd(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Pe(s.loanTakenFrom),bankOrInstituteName:Pe(s.lenderName),loanAccountNo:Pe(s.loanAccountNumber),loanSanctionDate:vd(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Pe(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:co(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Pe(s.housePropertyAddress),housePropertyPincode:Pe(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Pe(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:co(s.hasCoOwnedProperty),coOwnerName:Pe(s.coOwnerName),coOwnerPan:Pe(s.coOwnerPan),coOwnerShare:Pe(s.coOwnerShare),loanDetails:t?[e]:void 0}}function fd(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Pe(s.employerName),employerTan:Pe(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function pd(s,e){const t=[];for(const r of s){const o=Pe(r.employerName),n=Pe(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function md(s,e){const t=Pe(s.aadhaarNumber),r=Pe(s.bankAccountNumber),o=Pe(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function gd(s,e){return{userId:Yt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function bd(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function yd(s,e){const t=(o,n,i,a)=>{const l=Pe(s[o]),c=Pe(s[n]),u=Ie(s[i]),h=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&h===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:h??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Yt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Pe(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function co(s){return s===!0||s===!1?s:void 0}function vd(s){const e=Pe(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Wl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function nn(s,e){return Wl(s).map(t=>zr(e(t))).filter(t=>t!==void 0)}function zr(s){if(Array.isArray(s)){const e=s.map(zr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=zr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function wd(s){const e=s&&typeof s=="object"?s:{},t={},r=De(e.employers),o=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(h=>{const p=on(h.salary),b=on(h.perquisites),d=on(h.profitsInLieuOfSalaryType),g=p+b+d,y=xd(h.allowance);return{employerName:Re(h.employerName),employerTan:Re(h.employerTAN),basicSalary:p||void 0,grossSalary:g||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:kd(h,o,r)??Ne(h.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(h=>{const p=De(h.loanDetails),b=p.length?p[0]:void 0,d=Ne(h.grossAnnualRentReceived),g=p.length?p.reduce((x,v)=>x+(Ne(v.interest)??0),0):void 0,y=De(h.tenant),w=De(h.coOwners),m=y[0],_=w[0];return{typeOfHouseProperty:Re(h.propertyType),loanTakenFrom:Re(b?.loanTakenFrom),lenderName:Re(b?.bankOrInstituteName),loanAccountNumber:Re(b?.loanAccountNo),sanctionDate:_d(b?.loanSanctionDate),totalLoanAmount:Ne(b?.totalLoanAmount),outstandingAmount:Ne(b?.loanOutstandingAmount),homeLoanInterest:g,homeLoanPrinciple:void 0,housePropertyAddress:Re(h.address),housePropertyPincode:Re(h.pinCode),rentalIncome:d,nameOfTenant:Re(m?.name),propertyTax:Ne(h.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Re(_?.name),coOwnerPan:Re(_?.panNumber),coOwnerShare:Ne(_?.share)?.toString()}})),t.us80cAmount=Tt(De(e.deductionUS80CDetails).map(h=>Ne(h.amount))),t.us80dForSelfAndFamilyAmount=Tt(De(e.deductionUS80DDetails).map(h=>Ne(h.healthInsuranceAmount)));const i=De(e.incomes),a=h=>Tt(i.filter(p=>Re(p.incomeType)===h).map(p=>Ne(p.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Tt(De(e.dividendIncomes).map(h=>Ne(h.income)));const l=e.business;if(l){const h=De(l.presumptiveIncomes),p=g=>{const y=De(g.incomes),w=m=>Ne(y.find(_=>Re(_.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Re(g.businessType)?.toUpperCase().includes("PROFESSION")},b=g=>h.find(y=>p(y)===g),d=(g,y)=>{if(!g)return;const w=De(g.incomes),m=x=>Ne(w.find(v=>Re(v.incomeType)===x)?.receipts),_=m("BANK")||m("ANY_OTHER");t[y.name]=Re(g.businessType),t[y.nature]=Re(g.natureOfBusiness),t[y.bank]=_||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Tt(w.map(x=>Ne(x.presumptiveIncome)))||void 0};d(b(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),d(b(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=De(e.capitalGain).filter(h=>Re(h.assetType)?.toUpperCase()==="VDA").flatMap(h=>De(h.assetDetails));c.length&&(t.cryptoSellPrice=Tt(c.map(h=>Ne(h.sellValue))),t.cryptoPurchasePrice=Tt(c.map(h=>Ne(h.purchaseCost)))),t.agricultureIncome=Ne(e.agriculturalDetails?.income),t.aadhaarNumber=Re(e.aadharNumber);const u=De(e.bankDetails)[0];return u&&(t.bankAccountNumber=Re(u.accountNumber),t.bankIfscCode=Re(u.ifsCode)),zl(t)}function _d(s){const e=Re(s);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function on(s){return De(s).reduce((e,t)=>e+(Ne(t.taxableAmount)??0),0)}function kd(s,e,t){if(!e.length)return;const r=Re(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Re(n.deductorTAN)?.trim().toUpperCase()===r)return Ne(n.totalTdsDeposited)}const o=Re(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Re(n.deductorName)?.trim().toLowerCase()===o)return Ne(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ne(e[0].totalTdsDeposited)}function xd(s){const e=De(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ne(i.exemptAmount)??Ne(i.allowanceAmount);switch(Re(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ne(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Tt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ne(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Re(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function zl(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?zl(o):o):e[t]=r);return e}function sn(){if(typeof window>"u")return null;const s=window,e=s.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=s.__aikaara_descriptor__??{},r=Pd(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=Md(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):Ld(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Rd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Nd(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Sd(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return wd(Oo(await r.json().catch(()=>({}))))}async function Ed(s,e){const t=await s.getToken(),r=s.userId,o={...hd(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Oo(await a.json().catch(()=>({})))}async function Ad(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function Id(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Td(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Cd(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Od(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function ur(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Oo(await n.json().catch(()=>({})))}function Pd(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function Md(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function Rd(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function Ld(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Oo(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Nd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class jd{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new $l(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:ud,data:{}});const t=sn();if(!(!t||!t.baseUrl))try{const r=await Sd(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=sn();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=pd(n,o);i&&await Ad(r,i)}else if(e==="bank-details"){const n=md(t,o);n&&await Id(r,n)}else if(e==="other-sources")await Td(r,gd(t,o));else if(e==="business-profession"){const n=yd(t,o);n&&await Cd(r,n)}else if(e==="crypto-income"){const n=bd(t,o);n&&await Od(r,n)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=sn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Ed(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class Vl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||jc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Mo,position:this.getAttribute("position")||this._config.position||Nc,width:Number(this.getAttribute("width"))||this._config.width||Pc,height:Number(this.getAttribute("height"))||this._config.height||Mc,fontFamily:this._config.fontFamily||Lc,borderRadius:this._config.borderRadius??Rc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ro,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Uc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
9
9
  `)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
10
10
  font-family: var(--aikaara-font);
11
11
  position: fixed;
@@ -119,7 +119,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
119
119
  ></aikaara-chat-input>
120
120
  <aikaara-error-banner></aikaara-error-banner>
121
121
  </div>
122
- `;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new Ld(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),o=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|o<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Kl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
122
+ `;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new jd(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),o=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|o<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Kl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
123
123
  <style>
124
124
  .bubble {
125
125
  width: var(--aikaara-bubble-size, 60px);
@@ -154,7 +154,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
154
154
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
155
155
  </svg>
156
156
  </button>
157
- `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const Nd=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Gl extends HTMLElement{shadow;actions=Nd;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const o=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:o,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),o=this.getAttribute("status")||"connected",n=o==="connected"?"#10b981":o==="connecting"||o==="reconnecting"?"#f59e0b":"#ef4444",i=this.actions.map(a=>`
157
+ `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const Ud=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Gl extends HTMLElement{shadow;actions=Ud;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const o=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:o,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),o=this.getAttribute("status")||"connected",n=o==="connected"?"#10b981":o==="connecting"||o==="reconnecting"?"#f59e0b":"#ef4444",i=this.actions.map(a=>`
158
158
  <button class="menu-item" type="button" data-action-id="${a.id}" data-action-label="${a.label}">
159
159
  <span class="menu-item-icon">${this.iconSvg(a.icon)}</span>
160
160
  <span class="menu-item-label">${a.label}</span>
@@ -314,7 +314,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
314
314
  </button>
315
315
  </div>
316
316
  </div>
317
- `}setStatus(e){this.setAttribute("status",e)}}const jd=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Ud=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Bd={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function Dd(s){return s.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Bd[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&amp;/gi,"&")}function qt(s){if(jd.test(s))return s;const e=Ud.test(s)?Dd(s):s;let t=Fd(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,o,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,o,n)=>{const i=/[.,!?;:]+$/.exec(n),a=i?i[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function Fd(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return s.replace(/[&<>"']/g,t=>e[t])}const $d=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),qd={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Ht(s){const e=document.createElement("template");return e.innerHTML=s,Yl(e.content),e.innerHTML}function Yl(s){const e=Array.from(s.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!$d.has(o)){const a=document.createTextNode(r.textContent||"");s.replaceChild(a,t);continue}const n=qd[o]||new Set,i=Array.from(r.attributes);for(const a of i)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}Yl(t)}}function Jl(s,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),i=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(s,"aikaara_popup",`width=${t},height=${r},left=${n},top=${i},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const h=u.data?.type;o&&typeof h=="string"&&!o.includes(h)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function Hd(s){const e=Date.now()-s.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const o=Math.round(r/60);if(o<24)return`${o} hr ago`;const n=Math.round(o/24);return n===1?"Yesterday":n<7?`${n} d ago`:s.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Ql extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(o=>r.includes(o)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(i=>i&&i.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(i=>Gs(r.href,i.match));r.target==="_self"&&!o||t.some(i=>{if(!i||!i.classList)return!1;const a=i.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
317
+ `}setStatus(e){this.setAttribute("status",e)}}const Bd=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Dd=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Fd={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function $d(s){return s.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Fd[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&amp;/gi,"&")}function qt(s){if(Bd.test(s))return s;const e=Dd.test(s)?$d(s):s;let t=qd(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,o,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,o,n)=>{const i=/[.,!?;:]+$/.exec(n),a=i?i[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function qd(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return s.replace(/[&<>"']/g,t=>e[t])}const Hd=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Wd={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Ht(s){const e=document.createElement("template");return e.innerHTML=s,Yl(e.content),e.innerHTML}function Yl(s){const e=Array.from(s.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!Hd.has(o)){const a=document.createTextNode(r.textContent||"");s.replaceChild(a,t);continue}const n=Wd[o]||new Set,i=Array.from(r.attributes);for(const a of i)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}Yl(t)}}function Jl(s,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),i=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(s,"aikaara_popup",`width=${t},height=${r},left=${n},top=${i},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const h=u.data?.type;o&&typeof h=="string"&&!o.includes(h)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function zd(s){const e=Date.now()-s.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const o=Math.round(r/60);if(o<24)return`${o} hr ago`;const n=Math.round(o/24);return n===1?"Yesterday":n<7?`${n} d ago`:s.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Ql extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(o=>r.includes(o)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(i=>i&&i.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(i=>Gs(r.href,i.match));r.target==="_self"&&!o||t.some(i=>{if(!i||!i.classList)return!1;const a=i.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
318
318
  <style>
319
319
  :host {
320
320
  display: flex;
@@ -475,7 +475,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
475
475
  }
476
476
  </style>
477
477
  <div class="message-list"></div>
478
- `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ht(qt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const a=Wd(i);if(i.message_id&&t.set(i.message_id,a),Object.keys(a).length>0)for(let l=o-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,h=t.get(u);(!h||Object.keys(h).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r){const i=n.externalId??n.id;t.has(i)||t.set(i,{})}}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ht(qt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const h=document.createElement("div");h.classList.add("message-wrap","system"),h.dataset.messageId=e.id,e.externalId&&(h.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),h.appendChild(p),this.container.appendChild(h);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const o=document.createElement("div");o.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:i?e.content&&(o.innerHTML=Ht(qt(e.content))):(o.innerHTML=Ht(qt(e.content||"")),e.status==="streaming"&&o.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type",e.template.contentType),e.template.templateId&&h.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&h.setAttribute("message-id",p),h.setPayload(e.template.payload),t!==void 0&&(h.dataset.consumed="true",Object.keys(t).length>0&&h.setConsumedValues?.(t)),this.templateLayout==="outside"?(h.classList.add("template-outside"),a=h):o.appendChild(h)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const h=document.createElement("div");h.classList.add("attachments");for(const p of e.attachments){const b=document.createElement("aikaara-template-renderer");b.setAttribute("content-type","300"),b.setAttribute("template-id","7");const d={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};b.setPayload(d,""),h.appendChild(b)}o.appendChild(h)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const h=document.createElement("div");if(h.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(h.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",h.appendChild(p)}r.appendChild(h)}r.childNodes.length>0&&this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return Hd(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(b=>Gs(e,b.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){Jl(e);return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const a=zd(e),l=Xl(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(c.authorization=`Bearer ${b}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(uo(r.fetch.body,a)));let p=null;try{const b=await fetch(l,h);b.ok&&(p=await b.json().catch(()=>null))}catch(b){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",b)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,b=>{const d=r.props??{setData:p};for(const[y,w]of Object.entries(d)){const m=b[y];typeof m=="function"&&m.call(b,w)}const g=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};b.addEventListener("aikaara-plan-select",g),b.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Wd(s){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function Gs(s,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(s)}function zd(s){try{const e=new URL(s),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function Xl(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function uo(s,e){if(typeof s=="string")return Xl(s,e);if(Array.isArray(s))return s.map(t=>uo(t,e));if(s&&typeof s=="object"){const t={};for(const[r,o]of Object.entries(s))t[r]=uo(o,e);return t}return s}class Zl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",o=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Ht(qt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
478
+ `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ht(qt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const a=Vd(i);if(i.message_id&&t.set(i.message_id,a),Object.keys(a).length>0)for(let l=o-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,h=t.get(u);(!h||Object.keys(h).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r){const i=n.externalId??n.id;t.has(i)||t.set(i,{})}}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ht(qt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const h=document.createElement("div");h.classList.add("message-wrap","system"),h.dataset.messageId=e.id,e.externalId&&(h.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),h.appendChild(p),this.container.appendChild(h);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const o=document.createElement("div");o.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:i?e.content&&(o.innerHTML=Ht(qt(e.content))):(o.innerHTML=Ht(qt(e.content||"")),e.status==="streaming"&&o.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type",e.template.contentType),e.template.templateId&&h.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&h.setAttribute("message-id",p),h.setPayload(e.template.payload),t!==void 0&&(h.dataset.consumed="true",Object.keys(t).length>0&&h.setConsumedValues?.(t)),this.templateLayout==="outside"?(h.classList.add("template-outside"),a=h):o.appendChild(h)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const h=document.createElement("div");h.classList.add("attachments");for(const p of e.attachments){const b=document.createElement("aikaara-template-renderer");b.setAttribute("content-type","300"),b.setAttribute("template-id","7");const d={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};b.setPayload(d,""),h.appendChild(b)}o.appendChild(h)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const h=document.createElement("div");if(h.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(h.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",h.appendChild(p)}r.appendChild(h)}r.childNodes.length>0&&this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return zd(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(b=>Gs(e,b.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){Jl(e);return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const a=Kd(e),l=Xl(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(c.authorization=`Bearer ${b}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(uo(r.fetch.body,a)));let p=null;try{const b=await fetch(l,h);b.ok&&(p=await b.json().catch(()=>null))}catch(b){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",b)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,b=>{const d=r.props??{setData:p};for(const[y,w]of Object.entries(d)){const m=b[y];typeof m=="function"&&m.call(b,w)}const g=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};b.addEventListener("aikaara-plan-select",g),b.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Vd(s){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function Gs(s,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(s)}function Kd(s){try{const e=new URL(s),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function Xl(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function uo(s,e){if(typeof s=="string")return Xl(s,e);if(Array.isArray(s))return s.map(t=>uo(t,e));if(s&&typeof s=="object"){const t={};for(const[r,o]of Object.entries(s))t[r]=uo(o,e);return t}return s}class Zl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",o=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Ht(qt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
479
479
  <style>
480
480
  :host { display: flex; flex-direction: column; }
481
481
  :host([role="user"]) { align-items: flex-end; }
@@ -553,8 +553,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
553
553
  </div>
554
554
  `:""}
555
555
  `;const h=this.shadow.querySelector("aikaara-template-renderer");h&&this.templatePayload!==null&&h.setPayload(this.templatePayload,a),h&&h.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Ys(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
- 📎 ${Vd(t.fileName)}
557
- </a>`).join("")}</div>`:""}}function Ys(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Vd(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class ec extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",o=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",a=t?`
556
+ 📎 ${Gd(t.fileName)}
557
+ </a>`).join("")}</div>`:""}}function Ys(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Gd(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class ec extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",o=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",a=t?`
558
558
  <button class="attach-btn" aria-label="Attach file" type="button">
559
559
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
560
560
  <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
@@ -743,7 +743,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
743
743
  <span class="message"></span>
744
744
  <button class="dismiss">Dismiss</button>
745
745
  </div>
746
- `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const an=new Map;function ic(s){const e=an.get(s);if(e)return e;const t=new Promise((r,o)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(s)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error(`Failed to load ${s}`)),{once:!0}));return}const i=document.createElement("script");i.src=s,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=s,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{an.delete(s),o(new Error(`Failed to load ${s}`))},{once:!0}),document.head.appendChild(i)});return an.set(s,t),t}function Kd(s,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${s}> not registered within ${e}ms`)),e);customElements.whenDefined(s).then(()=>{clearTimeout(o),t()})})}const Gd={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>require("./AikaaraPaymentLink-D_SZ081m.cjs")).then(({registerAikaaraPaymentLink:s})=>s())};function Yd(s){const e=`template:${s}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[s]}class oc extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const o=Xd(t.attributes.action);if(Object.keys(o).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(o))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const o=localStorage.getItem(`aikaara_form:${r}`);o&&(e=JSON.parse(o))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o,i=n.getName?.();i&&r[i]?.length&&n.setPreSelected?.(r[i])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
746
+ `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const an=new Map;function ic(s){const e=an.get(s);if(e)return e;const t=new Promise((r,o)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(s)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error(`Failed to load ${s}`)),{once:!0}));return}const i=document.createElement("script");i.src=s,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=s,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{an.delete(s),o(new Error(`Failed to load ${s}`))},{once:!0}),document.head.appendChild(i)});return an.set(s,t),t}function Yd(s,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${s}> not registered within ${e}ms`)),e);customElements.whenDefined(s).then(()=>{clearTimeout(o),t()})})}const Jd={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>require("./AikaaraPaymentLink-D_SZ081m.cjs")).then(({registerAikaaraPaymentLink:s})=>s())};function Qd(s){const e=`template:${s}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[s]}class oc extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const o=ef(t.attributes.action);if(Object.keys(o).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(o))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const o=localStorage.getItem(`aikaara_form:${r}`);o&&(e=JSON.parse(o))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o,i=n.getName?.();i&&r[i]?.length&&n.setPreSelected?.(r[i])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
747
747
  <style>
748
748
  :host { display: block; }
749
749
  ::slotted(*) { display: block; }
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
757
757
  }
758
758
  </style>
759
759
  <slot></slot>
760
- `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Yd(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Gd[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&ic(r.scriptUrl).then(()=>Kd(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof i[a]=="function")try{i[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:i.map(c=>{const u=typeof c.title=="string"?c.title:"",h=c.message;return{label:u||h,value:h}})}),this.appendChild(l);return}for(const l of i)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-CBAy6ItK.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Qd(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Jd=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Qd(s){const e={};for(const[t,r]of Object.entries(s))Jd.has(t)||(e[t]=r);return e}function Xd(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class sc extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
760
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Qd(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Jd[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&ic(r.scriptUrl).then(()=>Yd(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof i[a]=="function")try{i[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:i.map(c=>{const u=typeof c.title=="string"?c.title:"",h=c.message;return{label:u||h,value:h}})}),this.appendChild(l);return}for(const l of i)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-Cu9jSZv5.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Zd(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Xd=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Zd(s){const e={};for(const[t,r]of Object.entries(s))Xd.has(t)||(e[t]=r);return e}function ef(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class sc extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
761
761
  <style>
762
762
  :host {
763
763
  display: flex;
@@ -939,8 +939,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
939
939
  button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
940
940
  button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
941
941
  </style>
942
- <button type="button">${Zd(e)}</button>
943
- `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Zd(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class cc extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
942
+ <button type="button">${tf(e)}</button>
943
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function tf(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class cc extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
944
944
  <style>
945
945
  :host { all: initial; }
946
946
  .overlay {
@@ -1081,7 +1081,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1081
1081
  <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
1082
1082
  </div>
1083
1083
  </div>
1084
- `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const ef=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],tf=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class fc extends HTMLElement{shadow;data=null;columns=tf;features=ef;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
1084
+ `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const rf=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],nf=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class fc extends HTMLElement{shadow;data=null;columns=nf;features=rf;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
1085
1085
  <style>
1086
1086
  :host {
1087
1087
  display: block;
@@ -1163,7 +1163,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1163
1163
  <div class="modal-title">Correct Your ITR Details</div>
1164
1164
  <button class="icon-btn close-btn" type="button" aria-label="Close">${Qs}</button>
1165
1165
  `;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(i=>`
1166
- <button class="chip" type="button" data-section-id="${nf(i.id)}">
1166
+ <button class="chip" type="button" data-section-id="${sf(i.id)}">
1167
1167
  <span class="chip-icon">${i.icon??"📄"}</span>
1168
1168
  <span class="chip-label">${Xs(i.title)}</span>
1169
1169
  </button>`).join("");r.innerHTML=`
@@ -1180,7 +1180,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1180
1180
  `;const n=this.shadow.querySelector(".modal-footer");n.style.display="",n.innerHTML=`
1181
1181
  <button class="primary-btn" type="button" data-action="recalculate">Save &amp; Recalculate</button>
1182
1182
  `,this.bindCommon(),r.querySelectorAll(".chip").forEach(i=>{i.addEventListener("click",()=>{const a=i.dataset.sectionId;a&&this.openSection(a)})}),n.querySelector('[data-action="recalculate"]')?.addEventListener("click",()=>this.handleRecalculate())}renderForm(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-picker"),e.classList.add("view-form");const t=this.schemas.find(n=>n.id===this.activeSectionId),r=this.shadow.querySelector(".modal-header");r.innerHTML=`
1183
- <button class="icon-btn back-btn" type="button" aria-label="Back">${rf}</button>
1183
+ <button class="icon-btn back-btn" type="button" aria-label="Back">${of}</button>
1184
1184
  <div class="modal-title">${Xs(t?.title??"Edit")}</div>
1185
1185
  <button class="icon-btn close-btn" type="button" aria-label="Close">${Qs}</button>
1186
1186
  `;const o=this.shadow.querySelector(".modal-footer");o.style.display="none",o.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(o=>o.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(o=>{const n=o.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
@@ -1321,7 +1321,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1321
1321
  border-radius: 16px 16px 0 0;
1322
1322
  }
1323
1323
  }
1324
- `}}const Qs='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',rf='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';function nf(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Xs(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class mc extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const o=this.getEntries(),n={...o[e]||{}};n[t]=r,o[e]=n,this.isRepeatable()?this.value=o:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=i=>{if(!i)return null;const a=t[i.field];return"equals"in i?a===i.equals:Array.isArray(i.in)?i.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!this.fieldVisible(o,t)||o.type==="group")return;const n=t[o.id],i=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(i,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(i,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=o;Number.isNaN(a)?this.errors.set(i,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(i,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(i,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((o,n)=>this.renderEntry(o,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1324
+ `}}const Qs='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',of='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';function sf(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Xs(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class mc extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const o=this.getEntries(),n={...o[e]||{}};n[t]=r,o[e]=n,this.isRepeatable()?this.value=o:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=i=>{if(!i)return null;const a=t[i.field];return"equals"in i?a===i.equals:Array.isArray(i.in)?i.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!this.fieldVisible(o,t)||o.type==="group")return;const n=t[o.id],i=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(i,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(i,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=o;Number.isNaN(a)?this.errors.set(i,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(i,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(i,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((o,n)=>this.renderEntry(o,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1325
1325
  <style>${this.css()}</style>
1326
1326
  <div class="container">
1327
1327
  <div class="scroll">
@@ -1596,4 +1596,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1596
1596
  }
1597
1597
  .save-btn:hover { filter: brightness(1.07); }
1598
1598
  .save-btn:active { filter: brightness(0.95); }
1599
- `}}function wt(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ge(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gc(){const s=[["aikaara-chat-widget",Vl],["aikaara-chat-bubble",Kl],["aikaara-chat-header",Gl],["aikaara-message-list",Ql],["aikaara-message-bubble",Zl],["aikaara-chat-input",ec],["aikaara-typing-indicator",tc],["aikaara-streaming-message",rc],["aikaara-error-banner",nc],["aikaara-template-renderer",oc],["aikaara-system-pill",sc],["aikaara-option-list",ac],["aikaara-submit-action",lc],["aikaara-modal-action",cc],["aikaara-text-input",uc],["aikaara-chat",hc],["aikaara-link-modal",dc],["aikaara-compare-plans",fc],["aikaara-smart-edit-modal",pc],["aikaara-schema-form",mc]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}gc();function mr(s,e,t=""){if(!e)return t;const r=e.split(".");let o=s;for(const n of r)if(o&&typeof o=="object"&&n in o)o=o[n];else return t;return typeof o=="string"?o:t}function Zs(s){try{const e=s.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Wt(s){return typeof s=="function"?await s():s}class bc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Zs(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Wt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",o={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,i);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=mr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=mr(l,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",d=mr(l,this.descriptor.fullNamePath??"data.fullName"),g=mr(l,this.descriptor.userPath??"data.userId"),y=Zs(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:b,fullName:d,userId:g,expiresAt:y},this.cache}}async function yc(s){const e={};for(const t of s.spec){const r=await of(t,s.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function of(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return sf(t);case"localStorage":return gr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return gr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return gr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return gr(()=>document.querySelector(`meta[name="${af(t)}"]`)?.content??void 0);case"callback":{const r=e?.[s.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function sf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function gr(s){try{return s()}catch{return}}function af(s){return s.replace(/["\\]/g,"\\$&")}const lf=1800;class vc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await yc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??lf;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const cf=3e4,uf=2e3,hf=100;async function wc(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:s.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=df(r);if(!o)throw new Xe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=ff(r);if(!o)throw new Xe("hash",`#${r}= not present`);return{token:o,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",o=typeof t.key=="string"&&t.key?t.key:"token",n=yf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:cf;return{token:await bf({type:r,key:o,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const o=pf(r);if(!o)throw new Xe("cookie",`cookie "${r}" not set`);return{token:o,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",o=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!o)throw new Xe("storage","storage.key not configured");const i=mf(r,o,n);if(!i)throw new Xe("storage",`${r}Storage["${o}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:uf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:hf,i=await gf(r,o,n);if(!i)throw new Xe("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class _c{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await wc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function df(s){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===s)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function ff(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function pf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function mf(s,e,t){if(!(typeof window>"u"))try{const o=(s==="session"?window.sessionStorage:window.localStorage).getItem(e);if(o==null)return;if(!t)return o;let n;try{n=JSON.parse(o)}catch{return o}const i=kc(n,t);return typeof i=="string"?i:void 0}catch{return}}async function gf(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=kc(window,s);if(typeof o=="string"&&o.length>0)return o;if(typeof o=="function")try{const n=o();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function bf(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=i=>{if(s.origins.length>0&&!s.origins.includes(i.origin))return;const a=i.data;if(!a||typeof a!="object")return;const l=a;if(s.type&&l.type!==s.type)return;const c=l[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function yf(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function kc(s,e){if(!e)return s;const t=e.split(".").filter(Boolean);let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function vf(){const s=typeof crypto<"u"?crypto:null;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues){const e=new Uint8Array(16);s.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const wf="aikaara_chat:requestId";function Po(s,e,t){const r=`${wf}:${s}:${e}`;return t?`${r}:${t}`:r}function xc(s,e,t){try{return localStorage.getItem(Po(s,e,t))}catch{return null}}function _f(s,e,t,r){try{localStorage.setItem(Po(s,e,r),t)}catch{}}function kf(s,e,t){try{localStorage.removeItem(Po(s,e,t))}catch{}}async function ho(s,e,t="before-chat"){const r=s.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,h]of Object.entries(e.identity))typeof h=="string"&&(o[u]=h);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(h,p)=>p in o?o[p]:""),i=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(i);if(u&&typeof u=="object"){const h={};for(const[p,b]of Object.entries(u))h[p]=i(b);return h}return u},a=await Wt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const h=r[u],p=n(h.url),b=h.method??(h.body?"POST":"GET"),d={accept:"application/json",...h.headers??{}};if((h.authHeader??"session")==="session"){const x=h.authHeaderTemplate??"Bearer {token}";d.authorization=x.replace("{token}",a)}const g={method:b,headers:d};h.body&&(d["content-type"]="application/json",g.body=JSON.stringify(i(h.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,g);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Sf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${b} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${b} ${p} → ${y} ${w.slice(0,200)}`;if(h.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(h.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&h.capture&&h.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(h.capture.path)for(const E of h.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;h.capture.stripPrefix&&E.startsWith(h.capture.stripPrefix)&&(E=E.slice(h.capture.stripPrefix.length)),l[h.capture.as]=E,o[h.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${h.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function xf(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await ho(e,{sessionToken:s.sessionToken,userId:s.userId,projectId:s.projectId??"",slug:s.slug??"",identity:s.identity,serviceType:s.serviceType,userType:s.userType},"on-method-select")).captured:{}}function Sf(s,e){if(s===503||s===504||s===502)return!0;if(s===401||s===403)return e.trim().length===0;if(s===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Sc(s,e){const t=await fetch(s,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Ec(s,e){return s.replace("{projectId}",e).replace("{uuid}",vf().replace(/-/g,""))}function Ac(s){const e=s._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>ic(r)))}async function Ic(s){const e={...s.config??(s.configUrl?await Sc(s.configUrl,s.configHeaders):{}),...s.overrides??{}};Ac(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const o=r?.projectId??"",n=s.identity.userId,i=s.conversationScope||void 0,a=s.forceNewConversation?null:xc(n,o,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??a??Ec(l,o);(s.conversationId||!a||s.forceNewConversation)&&o&&_f(n,o,c,i);const u=await s.tokenProvider(),h=s.tokenProvider,p=s.historyTokenProvider??h,b=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:h}:void 0,d=s.uploadAdapter??(e.uploadEndpoint?Co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=s.historyAdapter??(e.historyApiBase?Hl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:s.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:s.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:b,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:d,historyAdapter:g,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),s.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Ef(s){if(typeof s!="string")return s;const e=document.querySelector(s);if(!e)throw new Error(`mountFromSlug: container "${s}" not found`);return e}async function Tc(s){const e=(s.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(s.slug)}`;let r=null;try{r=await Sc(t,s.configHeaders)}catch(I){if(!s.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${s.slug}" — using fallbackConfig.`,I)}const o={...s.fallbackConfig??{},...r??{},...s.overrides??{}};if(Ac(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,O]of Object.entries(o.templates)){const P=`template:${I}`;o.components[P]||!O?.scriptUrl||!O?.render||(o.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth},!o.auth)throw new Error(`mountFromSlug: widget_configs/${s.slug} descriptor must include "auth" block`);let i=null,a=s.user.id,l=s.user.name,c="",u=s.user.token,h=null;const p=await Wt(s.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&o.sso?.tokenSource){h=new _c({descriptor:{provider:o.sso.provider,flow:o.sso.flow,skipLogin:o.sso.skipLogin,autoRefresh:o.sso.autoRefresh,tokenSource:o.sso.tokenSource,tokenSourceConfig:o.sso.tokenSourceConfig,fallback:o.sso.fallback,map:o.sso.map},initToken:s.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!b&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;i=await new vc({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let d="",g="";if(o.preflight&&o.preflight.length){const I=await ho(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){d=I.captured.sessionToken;const O=d;u=()=>O}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const y=new bc(o.auth,u);if(d){const I=o.tiledesk?.projectId??"",O=I?xc(a,I):null,P=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?Ec(P,I):"");y.prime(d,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Wt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const _=h&&o.sso?.autoRefresh?async()=>{try{return await h.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Wt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?ql({...x,authHeader:v}):x&&x.mode==="direct"?Co({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Ic({container:Ef(s.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||g||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Wt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const O=o.preflight;return!O||!O.length?{}:O.some(j=>j.trigger==="on-method-select")?(await ho(O,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=hn;exports.AikaaraChat=hc;exports.AikaaraChatBubble=Kl;exports.AikaaraChatClient=$l;exports.AikaaraChatHeader=Gl;exports.AikaaraChatInput=ec;exports.AikaaraChatWidget=Vl;exports.AikaaraComparePlans=fc;exports.AikaaraErrorBanner=nc;exports.AikaaraLinkModal=dc;exports.AikaaraMessageBubble=Zl;exports.AikaaraMessageList=Ql;exports.AikaaraModalAction=cc;exports.AikaaraOptionList=ac;exports.AikaaraSchemaForm=mc;exports.AikaaraSmartEditModal=pc;exports.AikaaraStreamingMessage=rc;exports.AikaaraSubmitAction=lc;exports.AikaaraSystemPill=sc;exports.AikaaraTemplateRenderer=oc;exports.AikaaraTextInput=uc;exports.AikaaraTypingIndicator=tc;exports.ApiClient=ra;exports.ChannelSubscription=ea;exports.ConnectionManager=ta;exports.ConversationManager=oa;exports.EventEmitter=fo;exports.MessageStore=na;exports.SessionAuthAdapter=bc;exports.SsoExchangeAdapter=vc;exports.TiledeskTransport=Ul;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=_c;exports.clearPersistedConversationId=kf;exports.collectSsoCredentials=yc;exports.createFetchUploadAdapter=Co;exports.createPresigned3StepUploadAdapter=ql;exports.createTiledeskHistoryAdapter=Hl;exports.discoverToken=wc;exports.extractTiledeskFileEnvelope=Fl;exports.inferTiledeskRole=Dl;exports.isTiledeskSelfEcho=Bl;exports.mount=Ic;exports.mountFromSlug=Tc;exports.openInPopupWindow=Jl;exports.parseTiledeskTemplate=To;exports.registerComponents=gc;exports.runMethodSelectPreflight=xf;
1599
+ `}}function wt(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ge(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gc(){const s=[["aikaara-chat-widget",Vl],["aikaara-chat-bubble",Kl],["aikaara-chat-header",Gl],["aikaara-message-list",Ql],["aikaara-message-bubble",Zl],["aikaara-chat-input",ec],["aikaara-typing-indicator",tc],["aikaara-streaming-message",rc],["aikaara-error-banner",nc],["aikaara-template-renderer",oc],["aikaara-system-pill",sc],["aikaara-option-list",ac],["aikaara-submit-action",lc],["aikaara-modal-action",cc],["aikaara-text-input",uc],["aikaara-chat",hc],["aikaara-link-modal",dc],["aikaara-compare-plans",fc],["aikaara-smart-edit-modal",pc],["aikaara-schema-form",mc]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}gc();function mr(s,e,t=""){if(!e)return t;const r=e.split(".");let o=s;for(const n of r)if(o&&typeof o=="object"&&n in o)o=o[n];else return t;return typeof o=="string"?o:t}function Zs(s){try{const e=s.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Wt(s){return typeof s=="function"?await s():s}class bc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Zs(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Wt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",o={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,i);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=mr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=mr(l,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",d=mr(l,this.descriptor.fullNamePath??"data.fullName"),g=mr(l,this.descriptor.userPath??"data.userId"),y=Zs(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:b,fullName:d,userId:g,expiresAt:y},this.cache}}async function yc(s){const e={};for(const t of s.spec){const r=await af(t,s.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function af(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return lf(t);case"localStorage":return gr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return gr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return gr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return gr(()=>document.querySelector(`meta[name="${cf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[s.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function lf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function gr(s){try{return s()}catch{return}}function cf(s){return s.replace(/["\\]/g,"\\$&")}const uf=1800;class vc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await yc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??uf;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const hf=3e4,df=2e3,ff=100;async function wc(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:s.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=pf(r);if(!o)throw new Xe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=mf(r);if(!o)throw new Xe("hash",`#${r}= not present`);return{token:o,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",o=typeof t.key=="string"&&t.key?t.key:"token",n=wf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:hf;return{token:await vf({type:r,key:o,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const o=gf(r);if(!o)throw new Xe("cookie",`cookie "${r}" not set`);return{token:o,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",o=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!o)throw new Xe("storage","storage.key not configured");const i=bf(r,o,n);if(!i)throw new Xe("storage",`${r}Storage["${o}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:df,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:ff,i=await yf(r,o,n);if(!i)throw new Xe("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class _c{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await wc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function pf(s){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===s)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function mf(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function gf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function bf(s,e,t){if(!(typeof window>"u"))try{const o=(s==="session"?window.sessionStorage:window.localStorage).getItem(e);if(o==null)return;if(!t)return o;let n;try{n=JSON.parse(o)}catch{return o}const i=kc(n,t);return typeof i=="string"?i:void 0}catch{return}}async function yf(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=kc(window,s);if(typeof o=="string"&&o.length>0)return o;if(typeof o=="function")try{const n=o();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function vf(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=i=>{if(s.origins.length>0&&!s.origins.includes(i.origin))return;const a=i.data;if(!a||typeof a!="object")return;const l=a;if(s.type&&l.type!==s.type)return;const c=l[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function wf(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function kc(s,e){if(!e)return s;const t=e.split(".").filter(Boolean);let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function _f(){const s=typeof crypto<"u"?crypto:null;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues){const e=new Uint8Array(16);s.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const kf="aikaara_chat:requestId";function Po(s,e,t){const r=`${kf}:${s}:${e}`;return t?`${r}:${t}`:r}function xc(s,e,t){try{return localStorage.getItem(Po(s,e,t))}catch{return null}}function xf(s,e,t,r){try{localStorage.setItem(Po(s,e,r),t)}catch{}}function Sf(s,e,t){try{localStorage.removeItem(Po(s,e,t))}catch{}}async function ho(s,e,t="before-chat"){const r=s.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,h]of Object.entries(e.identity))typeof h=="string"&&(o[u]=h);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(h,p)=>p in o?o[p]:""),i=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(i);if(u&&typeof u=="object"){const h={};for(const[p,b]of Object.entries(u))h[p]=i(b);return h}return u},a=await Wt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const h=r[u],p=n(h.url),b=h.method??(h.body?"POST":"GET"),d={accept:"application/json",...h.headers??{}};if((h.authHeader??"session")==="session"){const x=h.authHeaderTemplate??"Bearer {token}";d.authorization=x.replace("{token}",a)}const g={method:b,headers:d};h.body&&(d["content-type"]="application/json",g.body=JSON.stringify(i(h.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,g);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Af(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${b} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${b} ${p} → ${y} ${w.slice(0,200)}`;if(h.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(h.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&h.capture&&h.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(h.capture.path)for(const E of h.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;h.capture.stripPrefix&&E.startsWith(h.capture.stripPrefix)&&(E=E.slice(h.capture.stripPrefix.length)),l[h.capture.as]=E,o[h.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${h.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Ef(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await ho(e,{sessionToken:s.sessionToken,userId:s.userId,projectId:s.projectId??"",slug:s.slug??"",identity:s.identity,serviceType:s.serviceType,userType:s.userType},"on-method-select")).captured:{}}function Af(s,e){if(s===503||s===504||s===502)return!0;if(s===401||s===403)return e.trim().length===0;if(s===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Sc(s,e){const t=await fetch(s,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Ec(s,e){return s.replace("{projectId}",e).replace("{uuid}",_f().replace(/-/g,""))}function Ac(s){const e=s._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>ic(r)))}async function Ic(s){const e={...s.config??(s.configUrl?await Sc(s.configUrl,s.configHeaders):{}),...s.overrides??{}};Ac(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const o=r?.projectId??"",n=s.identity.userId,i=s.conversationScope||void 0,a=s.forceNewConversation?null:xc(n,o,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??a??Ec(l,o);(s.conversationId||!a||s.forceNewConversation)&&o&&xf(n,o,c,i);const u=await s.tokenProvider(),h=s.tokenProvider,p=s.historyTokenProvider??h,b=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:h}:void 0,d=s.uploadAdapter??(e.uploadEndpoint?Co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=s.historyAdapter??(e.historyApiBase?Hl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:s.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:s.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:b,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:d,historyAdapter:g,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),s.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function If(s){if(typeof s!="string")return s;const e=document.querySelector(s);if(!e)throw new Error(`mountFromSlug: container "${s}" not found`);return e}async function Tc(s){const e=(s.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(s.slug)}`;let r=null;try{r=await Sc(t,s.configHeaders)}catch(I){if(!s.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${s.slug}" — using fallbackConfig.`,I)}const o={...s.fallbackConfig??{},...r??{},...s.overrides??{}};if(Ac(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,O]of Object.entries(o.templates)){const P=`template:${I}`;o.components[P]||!O?.scriptUrl||!O?.render||(o.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth},!o.auth)throw new Error(`mountFromSlug: widget_configs/${s.slug} descriptor must include "auth" block`);let i=null,a=s.user.id,l=s.user.name,c="",u=s.user.token,h=null;const p=await Wt(s.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&o.sso?.tokenSource){h=new _c({descriptor:{provider:o.sso.provider,flow:o.sso.flow,skipLogin:o.sso.skipLogin,autoRefresh:o.sso.autoRefresh,tokenSource:o.sso.tokenSource,tokenSourceConfig:o.sso.tokenSourceConfig,fallback:o.sso.fallback,map:o.sso.map},initToken:s.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!b&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;i=await new vc({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let d="",g="";if(o.preflight&&o.preflight.length){const I=await ho(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){d=I.captured.sessionToken;const O=d;u=()=>O}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const y=new bc(o.auth,u);if(d){const I=o.tiledesk?.projectId??"",O=I?xc(a,I):null,P=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?Ec(P,I):"");y.prime(d,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Wt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const _=h&&o.sso?.autoRefresh?async()=>{try{return await h.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Wt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?ql({...x,authHeader:v}):x&&x.mode==="direct"?Co({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Ic({container:If(s.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||g||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Wt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const O=o.preflight;return!O||!O.length?{}:O.some(j=>j.trigger==="on-method-select")?(await ho(O,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=hn;exports.AikaaraChat=hc;exports.AikaaraChatBubble=Kl;exports.AikaaraChatClient=$l;exports.AikaaraChatHeader=Gl;exports.AikaaraChatInput=ec;exports.AikaaraChatWidget=Vl;exports.AikaaraComparePlans=fc;exports.AikaaraErrorBanner=nc;exports.AikaaraLinkModal=dc;exports.AikaaraMessageBubble=Zl;exports.AikaaraMessageList=Ql;exports.AikaaraModalAction=cc;exports.AikaaraOptionList=ac;exports.AikaaraSchemaForm=mc;exports.AikaaraSmartEditModal=pc;exports.AikaaraStreamingMessage=rc;exports.AikaaraSubmitAction=lc;exports.AikaaraSystemPill=sc;exports.AikaaraTemplateRenderer=oc;exports.AikaaraTextInput=uc;exports.AikaaraTypingIndicator=tc;exports.ApiClient=ra;exports.ChannelSubscription=ea;exports.ConnectionManager=ta;exports.ConversationManager=oa;exports.EventEmitter=fo;exports.MessageStore=na;exports.SessionAuthAdapter=bc;exports.SsoExchangeAdapter=vc;exports.TiledeskTransport=Ul;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=_c;exports.clearPersistedConversationId=Sf;exports.collectSsoCredentials=yc;exports.createFetchUploadAdapter=Co;exports.createPresigned3StepUploadAdapter=ql;exports.createTiledeskHistoryAdapter=Hl;exports.discoverToken=wc;exports.extractTiledeskFileEnvelope=Fl;exports.inferTiledeskRole=Dl;exports.isTiledeskSelfEcho=Bl;exports.mount=Ic;exports.mountFromSlug=Tc;exports.openInPopupWindow=Jl;exports.parseTiledeskTemplate=To;exports.registerComponents=gc;exports.runMethodSelectPreflight=Ef;