@aikaara/chat-sdk 1.1.14 → 1.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MountTenant-B06QBb_3.cjs → MountTenant-CBNuUhDN.cjs} +2 -2
- package/dist/{MountTenant-CfeFONXt.mjs → MountTenant-CvzatZXg.mjs} +3 -1
- package/dist/cdn/aikaara-chat.iife.js +2 -2
- package/dist/headless.cjs +1 -1
- package/dist/headless.d.ts +10 -0
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +10 -0
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.d.ts +10 -0
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -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 Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],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 He in z)oe(z,He)&&(Ee&&String(Number(He))===He&&He<z.length||D&&et["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Ae.push(ie(He,z)+": "+ie(z[He],z)):Ae.push(He+": "+ie(z[He],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 Pr}function ph(){if(Zi)return Rr;Zi=!0;var l=Bt(),e=Zu(),t=fh(),r=Qt(),i=l("%WeakMap%",!0),n=l("%Map%",!0),o=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),a=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(b,k){for(var m=b,w;(w=m.next)!==null;m=w)if(w.key===k)return m.next=w.next,w.next=b.next,b.next=w,w},y=function(b,k){var m=p(b,k);return m&&m.value},f=function(b,k,m){var w=p(b,k);w?w.value=m:b.next={key:k,next:b.next,value:m}},g=function(b,k){return!!p(b,k)};return Rr=function(){var b,k,m,w={assert:function(x){if(!w.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(b)return o(b,x)}else if(n){if(k)return c(k,x)}else if(m)return y(m,x)},has:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(b)return a(b,x)}else if(n){if(k)return h(k,x)}else if(m)return g(m,x);return!1},set:function(x,v){i&&x&&(typeof x=="object"||typeof x=="function")?(b||(b=new i),s(b,x,v)):n?(k||(k=new n),u(k,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return w},Rr}function Ji(){if(eo)return Lr;eo=!0;var l=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Lr={default:t.RFC3986,formatters:{RFC1738:function(r){return l.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Lr}function Ma(){if(to)return jr;to=!0;var l=Ji(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],k=0;k<256;++k)b.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return b})(),i=function(b){for(;b.length>1;){var k=b.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],x=0;x<m.length;++x)typeof m[x]<"u"&&w.push(m[x]);k.obj[k.prop]=w}}},n=function(b,k){for(var m=k&&k.plainObjects?Object.create(null):{},w=0;w<b.length;++w)typeof b[w]<"u"&&(m[w]=b[w]);return m},o=function b(k,m,w){if(!m)return k;if(typeof m!="object"){if(t(k))k.push(m);else if(k&&typeof k=="object")(w&&(w.plainObjects||w.allowPrototypes)||!e.call(Object.prototype,m))&&(k[m]=!0);else return[k,m];return k}if(!k||typeof k!="object")return[k].concat(m);var x=k;return t(k)&&!t(m)&&(x=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,E){if(e.call(k,E)){var S=k[E];S&&typeof S=="object"&&v&&typeof v=="object"?k[E]=b(S,v,w):k.push(v)}else k[E]=v}),k):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=b(v[E],S,w):v[E]=S,v},x)},s=function(b,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},b)},a=function(b,k,m){var w=b.replace(/\+/g," ");if(m==="iso-8859-1")return w.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(w)}catch{return w}},c=1024,u=function(b,k,m,w,x){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),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 N=I.charCodeAt(P);if(N===45||N===46||N===95||N===126||N>=48&&N<=57||N>=65&&N<=90||N>=97&&N<=122||x===l.RFC1738&&(N===40||N===41)){O[O.length]=I.charAt(P);continue}if(N<128){O[O.length]=r[N];continue}if(N<2048){O[O.length]=r[192|N>>6]+r[128|N&63];continue}if(N<55296||N>=57344){O[O.length]=r[224|N>>12]+r[128|N>>6&63]+r[128|N&63];continue}P+=1,N=65536+((N&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|N>>18]+r[128|N>>12&63]+r[128|N>>6&63]+r[128|N&63]}E+=O.join("")}return E},h=function(b){for(var k=[{obj:{o:b},prop:"o"}],m=[],w=0;w<k.length;++w)for(var x=k[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&&(k.push({obj:v,prop:I}),m.push(O))}return i(k),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,k){return[].concat(b,k)},g=function(b,k){if(t(b)){for(var m=[],w=0;w<b.length;w+=1)m.push(k(b[w]));return m}return k(b)};return jr={arrayToObject:n,assign:s,combine:f,compact:h,decode:a,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:o},jr}function mh(){if(ro)return Nr;ro=!0;var l=ph(),e=Ma(),t=Ji(),r=Object.prototype.hasOwnProperty,i={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,b){return g+"["+b+"]"},repeat:function(g){return g}},n=Array.isArray,o=Array.prototype.push,s=function(g,b){o.apply(g,n(b)?b:[b])},a=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 a.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={},y=function g(b,k,m,w,x,v,E,S,I,O,P,N,T,q,D,U,ae,Y){for(var V=b,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(b);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(k,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(k,u.encoder,ae,"key",q):k;V=""}if(h(V)||e.isBuffer(V)){if(I){var J=U?k:I(k,u.encoder,ae,"key",q);return[D(J)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(k)+"="+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 G=S?k.replace(/\./g,"%2E"):k,j=w&&n(V)&&V.length===1?G+"[]":G;if(x&&n(V)&&V.length===0)return j+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===null)){var Q=N&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(j,Q):j:j+(N?"."+Q:"["+Q+"]");Y.set(b,F);var oe=l();oe.set(p,Y),s(be,g(K,ge,m,w,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,N,T,q,D,U,ae,oe))}}return be},f=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 b=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 k=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");k=g.format}var m=t.formatters[k],w=u.filter;(typeof g.filter=="function"||n(g.filter))&&(w=g.filter);var x;if(g.arrayFormat in i?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:b,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:w,format:k,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 Nr=function(g,b){var k=g,m=f(b),w,x;typeof m.filter=="function"?(x=m.filter,k=x("",k)):n(m.filter)&&(x=m.filter,w=x);var v=[];if(typeof k!="object"||k===null)return"";var E=i[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=l(),O=0;O<w.length;++O){var P=w[O];m.skipNulls&&k[P]===null||s(v,y(k[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 N=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&"),N.length>0?T+N:""},Nr}function gh(){if(no)return Ur;no=!0;var l=Ma(),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:l.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},i=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},o="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",a=function(p,y){var f={__proto__:null},g=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,k=g.split(y.delimiter,b),m=-1,w,x=y.charset;if(y.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===s?x="utf-8":k[w]===o&&(x="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=y.decoder(v,r.decoder,x,"key"),O=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,S),r.decoder,x,"key"),O=l.maybeMap(n(v.slice(S+1),y),function(N){return y.decoder(N,r.decoder,x,"value")})),O&&y.interpretNumericEntities&&x==="iso-8859-1"&&(O=i(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(f,I);P&&y.duplicates==="combine"?f[I]=l.combine(f[I],O):(!P||y.duplicates==="last")&&(f[I]=O)}return f},c=function(p,y,f,g){for(var b=g?y:n(y,f),k=p.length-1;k>=0;--k){var m,w=p[k];if(w==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var x=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(E)&&w!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,y,f,g){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,w=f.depth>0&&k.exec(b),x=w?b.slice(0,w.index):b,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var E=0;f.depth>0&&(w=m.exec(b))!==null&&E<f.depth;){if(E+=1,!f.plainObjects&&e.call(Object.prototype,w[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(w[1])}if(w){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(w.index)+"]")}return c(v,y,f,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 y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="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:y,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"||l.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,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 Ur=function(p,y){var f=h(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?a(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],x=u(w,g[w],f,typeof p=="string");b=l.merge(b,x,f)}return f.allowSparse===!0?b:l.compact(b)},Ur}function bh(){if(io)return Br;io=!0;var l=mh(),e=gh(),t=Ji();return Br={formats:t,parse:e,stringify:l},Br}function yh(){if(oo)return _t;oo=!0;var l=vt;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]*$/,i=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
7
|
`," "],o=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(o),a=["%","/","?",";","#"].concat(s),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={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},b=bh();function k(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),N=/\\/g;P[0]=P[0].replace(N,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=i.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=b.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&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[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<a.length;V++){var re=T.indexOf(a[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 J=this.hostname.split(/\./),V=0,be=J.length;V<be;V++){var te=J[V];if(te&&!te.match(h)){for(var we="",G=0,j=te.length;G<j;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(h)){var ne=J.slice(0,V),W=J.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[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=l.toASCII(this.hostname));var Q=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+Q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[U])for(var V=0,be=s.length;V<be;V++){var oe=s[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=b.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 Q=this.pathname||"",de=this.search||"";this.path=Q+de}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=k(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=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var N=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),N&&N.charAt(0)!=="?"&&(N="?"+N),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),N=N.replace("#","%23"),E+O+S+N+I};function w(v,E){return k(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function x(v,E){return v?k(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 N=Object.keys(v),T=0;T<N.length;T++){var q=N[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&&!f[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,J=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&&(J[0]===""?J[0]=S.host:J.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]===""||J[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,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=J.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(!J.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var G=J.slice(-1)[0],j=(S.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=J.length;W>=0;W--)G=J[W],G==="."?J.splice(W,1):G===".."?(J.splice(W,1),ne++):ne&&(J.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),j&&J.join("/").substr(-1)!=="/"&&J.push("");var K=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=K?"":J.length?J.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&&J.length,Z&&!K&&J.unshift(""),J.length>0?S.pathname=J.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)},_t.parse=k,_t.resolve=w,_t.resolveObject=x,_t.format=m,_t.Url=e,_t}function Ra(l){if(typeof l=="string")l=new URL(l);else if(!(l instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(l.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Dr?vh(l):wh(l)}function vh(l){let e=l.hostname,t=l.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let i=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&i===102||t[r+1]==="5"&&i===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Ga,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,i=t[2];if(r<za||r>Va||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function wh(l){if(l.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=l.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 La(l){let e=Qi.resolve(l),t=l.charCodeAt(l.length-1);(t===Wa||Dr&&t===Ha)&&e[e.length-1]!==Qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Ka,"%25")),!Dr&&e.includes("\\")&&(e=e.replace(Ya,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(Qa,"%0A")),e.includes("\r")&&(e=e.replace(Ja,"%0D")),e.includes(" ")&&(e=e.replace(Xa,"%09")),r.pathname=e,r}var ja,Pr,Xi,Mr,Rr,Zi,Lr,eo,jr,to,Nr,ro,Ur,no,Br,io,_t,oo,qe,Na,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,Va,Dr,Ga,Ka,Ya,Qa,Ja,Xa,_h=Ve(()=>{le(),ue(),ce(),Bu(),eh(),dh(),Oa(),ja=Object.freeze(Object.create(null)),Pr={},Xi=!1,Mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Rr={},Zi=!1,Lr={},eo=!1,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,_t={},oo=!1,qe=yh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Na=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=La,qe.fileURLToPath=Ra,Ua=qe.Url,Ba=qe.format,Da=qe.resolve,Fa=qe.resolveObject,$a=qe.parse,qa=qe.URL,Ha=92,Wa=47,za=97,Va=122,Dr=Na==="win32",Ga=/\//g,Ka=/%/g,Ya=/\\/g,Qa=/\n/g,Ja=/\r/g,Xa=/\t/g}),kh=pe((l,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")}}),so=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.BufferedDuplex=void 0,l.writev=r;var e=It(),t=(De(),Me(Be));function r(n,o){let s=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?s[a]=t.Buffer.from(n[a].chunk,"utf8"):s[a]=n[a].chunk;this._write(t.Buffer.concat(s),"binary",o)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,s){super({objectMode:!0}),this.proxy=o,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,o,s){this.isSocketOpen?this.writeToProxy(n,o,s):this.writeQueue.push({chunk:n,encoding:o,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,s){this.proxy.write(n,o)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:s}=this.writeQueue.shift();this.writeToProxy(n,o,s)}}};l.BufferedDuplex=i}),Fr=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(l,"__esModule",{value:!0}),l.streamBuilder=l.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(kh()),i=e(ht()),n=It(),o=e(pr()),s=so(),a=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function h(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!o.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&c.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=h(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){a("createWebSocket"),a(`protocol: ${w.protocolId} ${w.protocolVersion}`);let x=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";a(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[x],w):v=new r.default(m,[x],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(x,[w],m):v=new WebSocket(x,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{a("streamBuilder");let w=h(m);w.hostname=w.hostname||w.host||"localhost";let x=u(w,k),v=y(k,x,w),E=r.default.createWebSocketStream(v,w.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};l.streamBuilder=g;var b=(k,m)=>{a("browserStreamBuilder");let w,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(k,m),I=P(m,U,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),O?S.addEventListener("open",N):S.onopen=N),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 N(){a("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){a("WebSocket onClose",Y),w.end(),w.destroy()}function q(Y){a("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,w.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 w};l.browserStreamBuilder=b}),ao={};Rt(ao,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Za,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 Za,el=Ve(()=>{le(),ue(),ce(),Za={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),tl=pe((l,e)=>{le(),ue(),ce(),e.exports={}}),rl=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(l,"__esModule",{value:!0});var t=e((el(),Me(ao))),r=e(ht()),i=e(tl()),n=(0,r.default)("mqttjs:tcp"),o=(s,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,i.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,h=a.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};l.default=o}),nl={};Rt(nl,{default:()=>il});var il,xh=Ve(()=>{le(),ue(),ce(),il={}}),ol=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(l,"__esModule",{value:!0});var t=(xh(),Me(nl)),r=e((el(),Me(ao))),i=e(ht()),n=e(tl()),o=(0,i.default)("mqttjs:tls");function s(c){let{host:u,port:h,socksProxy:p,...y}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(c)}var a=(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,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=s(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(y){u.rejectUnauthorized&&c.emit("error",y),h.end()}return h.on("error",p),h};l.default=a}),sl=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),i,n,o;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{i.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{i.close({success(){y()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){i.onOpen(()=>{o.socketReady()}),i.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),i.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),i.onError(p=>{let y=new Error(p.errMsg);o.destroy(y)})}var h=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";a(y);let g=c(y,p);i=wx.connectSocket({url:g,protocols:[f]}),n=s(),o=new r.BufferedDuplex(y,n,i),o._destroy=(k,m)=>{i.close({success(){m&&m(k)}})};let b=o.destroy;return o.destroy=(k,m)=>(o.destroy=b,setTimeout(()=>{i.close({fail(){o._destroy(k,m)}})},0),o),u(),o};l.default=h}),al=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),i,n,o,s=!1;function a(){let y=new t.Transform;return y._write=(f,g,b)=>{i.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{i.closeSocket({success(){f()}})},y}function c(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function h(){s||(s=!0,i.onSocketOpen(()=>{o.socketReady()}),i.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),i.onSocketClose(()=>{o.end(),o.destroy()}),i.onSocketError(y=>{o.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let b=u(f,y);return i=f.my,i.connectSocket({url:b,protocols:g}),n=a(),o=new r.BufferedDuplex(f,n,i),h(),o};l.default=p}),Sh=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(l,"__esModule",{value:!0}),l.connectAsync=u;var t=e(ht()),r=e((_h(),Me(Pa))),i=e(di()),n=e(pr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),s=null;function a(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;h.username=y,h.password=f}else h.username=h.auth}function c(h,p){if(o("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),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...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,a(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(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=Fr().streamBuilder,s.wss=Fr().streamBuilder,s.mqtt=rl().default,s.tcp=rl().default,s.ssl=ol().default,s.tls=s.ssl,s.mqtts=ol().default):(s.ws=Fr().browserStreamBuilder,s.wss=Fr().browserStreamBuilder,s.wx=sl().default,s.wxs=sl().default,s.ali=al().default,s.alis=al().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(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++),o("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new i.default(y,p);return f.on("error",()=>{}),f}function u(h,p,y=!0){return new Promise((f,g)=>{let b=c(h,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}l.default=c}),ll=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=l&&l.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=l&&l.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),i=l&&l.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=l&&l.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=l.KeepaliveManager=l.UniqueMessageIdProvider=l.DefaultMessageIdProvider=l.Store=l.MqttClient=l.connectAsync=l.connect=l.Client=void 0;var o=n(di());l.MqttClient=o.default;var s=n(ms());l.DefaultMessageIdProvider=s.default;var a=n(Nu());l.UniqueMessageIdProvider=a.default;var c=n(ls());l.Store=c.default;var u=r(Sh());l.connect=u.default,Object.defineProperty(l,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ks());l.KeepaliveManager=h.default,l.Client=o.default,i(di(),l),i(Ut(),l),i(as(),l);var p=dr();Object.defineProperty(l,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Eh=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(o,s,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(s,a);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[a]}}),Object.defineProperty(o,c,u)}:function(o,s,a,c){c===void 0&&(c=a),o[c]=s[a]}),t=l&&l.__setModuleDefault||(Object.create?function(o,s){Object.defineProperty(o,"default",{enumerable:!0,value:s})}:function(o,s){o.default=s}),r=l&&l.__importStar||(function(){var o=function(s){return o=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},o(s)};return function(s){if(s&&s.__esModule)return s;var a={};if(s!=null)for(var c=o(s),u=0;u<c.length;u++)c[u]!=="default"&&e(a,s,c[u]);return t(a,s),a}})(),i=l&&l.__exportStar||function(o,s){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(s,a)&&e(s,o,a)};Object.defineProperty(l,"__esModule",{value:!0});var n=r(ll());l.default=n,i(ll(),l)});const Ah=Eh();const Ih={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}/#"},Th=300,Ch={templateId:"7",type:"link",isDeepLink:!0},Oh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class cl{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={...Ih,...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,i={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&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,o)=>{let s=!1;const a=h=>{s||(s=!0,clearTimeout(u),h())},c=(h,p)=>{s||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),a(()=>o(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Ah.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),s||a(()=>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),!s){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),s||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",{}),s||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[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=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 i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...Ch,...this.config.fileTemplate??{},...Ph(t)},i={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??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Th){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,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 i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.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 i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:h,raw:i};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),s=o?.groups?.conversationId,a={topic:e,conversationId:s,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,a))}buildOutgoingEnvelope(e,t){const r={...Oh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={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:i,senderFullname:i,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:o}}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,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=o[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Ph(l){const e={};for(const[t,r]of Object.entries(l))r!==void 0&&(e[t]=r);return e}function ul(l,e){return(l.sender??"").toString()===e}function hl(l,e){const t=(l.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(l){const e={raw:l},t=l.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 l.text=="string"&&l.text.trim().startsWith("{"))try{const i=JSON.parse(l.text);typeof i.message=="string"&&(e.innerMessage=i.message);const n=i.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=l.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function dl(l){const e=lo(l);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 i=r[0],n=i.action,o=n&&typeof n.url=="string"?n.url:void 0,s=typeof i.description=="string"?i.description:void 0,a=l.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!o&&!s?null:{fileName:s,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function fl(l,e,t){const r=hl(l,t),i=lo(l),n=dl(l);let o="";i.innerMessage?o=i.innerMessage:typeof l.text=="string"&&(l.text.trim().startsWith("{")?i.contentType!=="300"&&(o=l.text):o=l.text);const s=typeof l.message_id=="string"?l.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=typeof l.timestamp=="number"?new Date(l.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof l.status=="number"?Mh(l.status):"delivered",h={id:s,externalId:s,conversationId:e,role:c,content:o,createdAt:a,status:u,metadata:{sender:l.sender,sender_fullname:l.sender_fullname??l.senderFullname,app_id:l.app_id,attributes:l.attributes}};return i.contentType&&(h.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:i}}function Mh(l){return l<0?"error":l>=250?"read":l>=150?"delivered":"sent"}class pl extends ir{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 Ao(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Io,this.conversationManager=new Mo(e.conversationId),this.usesAikaara()&&(this.connection=new Eo(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.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 cl({...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 i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),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),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(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(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const i=r.map(s=>fl(s,e,{userId:t}).message).sort((s,a)=>new Date(s.createdAt).getTime()-new Date(a.createdAt).getTime()),n=this.messageStore.messages,o=[...i,...n.filter(s=>!i.some(a=>a.externalId&&a.externalId===s.externalId))];if(this.messageStore.setMessages(o),this.config.onMessage)for(const s of i)try{this.config.onMessage(s)}catch(a){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",a)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);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 i=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:i.fileName,fileUrl:i.url,cloudFileId:i.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 i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,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=t.conversationId??this.conversationManager.conversationId;if(!r)return;const i=this.config.tiledeskIdentity?.userId??"",{message:n,template:o}=fl(e,r,{userId:i,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(ul(e,i)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:s,deduped:a}=this.messageStore.upsertRemoteMessage(n);if(a)this.emit("message:updated",s);else{this.emit("message:received",s),this.config.onMessage?.(s);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:s.role,hasAttachments:Array.isArray(s.attachments)&&s.attachments.length>0,templateId:s.template?.templateId,messageId:s.id,conversationId:s.conversationId}}))}catch{}}if(o.contentType){const c={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:o.contentType,templateId:o.templateId,payload:o.payload,innerMessage:o.innerMessage,raw:e};this.config.onTemplateMessage?.(c)}}handleTiledeskStatusUpdate(e){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{}}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||"",i=e.content||"";i?this.messageStore.updateStreaming(i):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,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.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}}}class Rh extends ir{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const ml={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 Lh(l){const e=l.lastIndexOf(".");return e<0||e===l.length-1?"":l.slice(e+1).toLowerCase()}function jh(l,e,t){const r=Lh(l.name||"");if(r&&e&&e[r])return e[r];const i=l.type;return i&&i.trim().length>0?i:r&&ml[r]?ml[r]:t}function co(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Nh(l,e){const t=e.split(".");let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function gl(l){const e=l.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=jh(t,l.contentTypeMap,l.contentTypeFallback??"application/octet-stream"),o={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},s=l.authHeader?await l.authHeader():void 0,a={accept:"application/json",...l.extraHeaders??{},...s?{authorization:s}:{}};let c=l.signEndpoint.includes("{")?l.signEndpoint:`${l.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const k=c.includes("?")?"&":"?";c=`${c}${k}contentType={contentType}`}const u=co(c,o),h=await fetch(u,{method:l.signMethod??"GET",headers:a});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),y=Nh(p,e);if(!y)throw new Error(`Sign response missing path "${e}"`);const f=l.s3HostRewrite?y.replace(/^https:\/\/[^/]+/i,l.s3HostRewrite):y,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const k=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${k.slice(0,200)}`)}if(l.registerEndpoint){const k=JSON.parse(co(JSON.stringify(l.registerBody??{}),o)),m=await fetch(l.registerEndpoint,{method:"POST",headers:{...a,"content-type":"application/json"},body:JSON.stringify(k)});if(!m.ok){const w=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${w.slice(0,200)}`)}}return{url:l.viewerTemplate?co(l.viewerTemplate,o):y.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function uo(l){return{async upload(e,t){const r=new FormData,i=l.fieldName??"file";r.append(i,e,e.name);const n=typeof l.extraFields=="function"?l.extraFields(t):l.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof l.headers=="function"?await l.headers():l.headers??{},s=await fetch(l.endpoint,{method:l.method??"POST",body:r,headers:o,credentials:l.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const a=await s.json().catch(()=>({}));if(l.parseResponse)return l.parseResponse(a,t);const c=a,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 Uh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function bl(l){const e=l.apiBase.replace(/\/$/,""),t=l.pageSize??200,r=l.pathTemplate??Uh;return{async fetchMessages(i,n){const o=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,a={accept:"application/json","content-type":"application/json",...l.extraHeaders??{}};if(l.getToken){const p=await l.getToken();p&&(a.authorization=p)}const c=await fetch(s,{method:"GET",headers:a}),u=await c.json().catch(()=>null);if(l.parseResponse&&u)return l.parseResponse(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 Bh="^[A-Z]{5}[0-9]{4}[A-Z]$",Dh="^[A-Z]{4}[0-9]{5}[A-Z]$",Fh="^[A-Z]{4}0[A-Z0-9]{6}$",yl="^[0-9]{6}$",$h=[{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)",required:!0,pattern:Dh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},{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}]}],submitLabel:"Save"},{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"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Bh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Fh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function qh(l,e){const t=l||{},r={userId:zh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Pe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Pe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Pe(t.us80dForParentsAmount),r.hasParentOverSixty=ho(t.hasParentOverSixty),r.preventiveHealthCheckUp=Pe(t.preventiveHealthCheckUp),r.medicalExpenditure=Pe(t.medicalExpenditure),r.savingBankInterest=Pe(t.savingBankInterest),r.fdInterest=Pe(t.fdInterest),r.dividend=Pe(t.dividend),r.anyOtherIncome=Pe(t.anyOtherIncome),r.cryptoSellValue=Pe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Pe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Pe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Pe(t.grossReceipts),r.businessNetProfit=Pe(t.netProfit),r.agricultureDetails={income:Pe(t.agricultureIncome)},r.exemptIncomeAmount=Pe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Pe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Pe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const i={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Pe(t.immovableAssetCost)};Object.values(i).some(s=>s!==void 0)&&(r.immovableAsset=[i]);const n=fo(t.hpDetails,Hh);n.length&&(r.hpDetails=n);const o=fo(t.salaryDetails,Wh);if(o.length){r.salaryIncome=o;const s=fo(t.salaryDetails,c=>({grossSalary:Pe(c.grossSalary),employerName:Re(c.employerName)}));s.length&&(r.salary=s);const a=vl(t.salaryDetails)[0]??{};r.hraAmount=Pe(a.hraReceived),r.leaveTravelAllowanceAmount=Pe(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Pe(a.leaveEncashment),r.anyOtherAllowanceAmount=Pe(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return $r(r)}function Hh(l){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(l.loanTakenFrom),bankOrInstituteName:Re(l.lenderName),loanAccountNo:Re(l.loanAccountNumber),loanSanctionDate:Vh(l.sanctionDate),totalLoanAmount:Pe(l.totalLoanAmount),interest:Pe(l.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Re(l.typeOfHouseProperty),hasRentalIncome:l.typeOfHouseProperty==="LOP"?!0:ho(l.hasRentalIncome),homeLoanInterest:Pe(l.homeLoanInterest),homeLoanPrinciple:Pe(l.homeLoanPrinciple),housePropertyAddress:Re(l.housePropertyAddress),housePropertyPincode:Re(l.housePropertyPincode),rentalIncome:Pe(l.rentalIncome),nameOfTenant:Re(l.nameOfTenant),propertyTax:Pe(l.propertyTax),hasCoOwnedProperty:ho(l.hasCoOwnedProperty),coOwnerName:Re(l.coOwnerName),coOwnerPan:Re(l.coOwnerPan),coOwnerShare:Re(l.coOwnerShare),loanDetails:t?[e]:void 0}}function Wh(l){return{grossSalaryIncome:Pe(l.grossSalary),salary:Pe(l.basicSalary),employer:{employerName:Re(l.employerName),employerTan:Re(l.employerTan)},allowance:{hraAmount:Pe(l.hraReceived),leaveTravelAllowanceAmount:Pe(l.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Pe(l.leaveEncashment),anyOtherAllowanceAmount:Pe(l.anyOtherAllowance)}}}function zh(l){if(l===void 0||l==="")return;const e=Number(l);return Number.isFinite(e)&&String(e)===String(l)?e:l}function Pe(l){if(l==null||l==="")return;const e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:void 0}function Re(l){if(l==null)return;const e=String(l).trim();return e===""?void 0:e}function ho(l){return l===!0||l===!1?l:void 0}function Vh(l){const e=Re(l);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function vl(l){return Array.isArray(l)?l.filter(e=>e&&typeof e=="object"):[]}function fo(l,e){return vl(l).map(t=>$r(e(t))).filter(t=>t!==void 0)}function $r(l){if(Array.isArray(l)){const e=l.map($r).filter(t=>t!==void 0);return e.length?e:void 0}if(l&&typeof l=="object"){const e={};for(const[t,r]of Object.entries(l)){const i=$r(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return l}function wl(){if(typeof window>"u")return null;const l=window,e=l.__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=e.getChatJwt,r=l.__aikaara_descriptor__??{},i=Qh(r.api?.baseUrl)??Jh(r.auth?.endpoint)??"",n=r.itr?.automationSubmitUrl||Gh(e.configBase,e.slug);return!n&&!i?(console.warn(`[smart-edit] API disabled: no submit URL could be derived (configBase=${e.configBase??"undefined"}, slug=${e.slug??"undefined"}).`),null):(console.info("[smart-edit] API config — submitUrl:",n||"(none)","· baseUrl:",i||"(none)"),{baseUrl:i,getToken:()=>t(),headers:Xh(r.auth?.headers),assessmentYear:r.itr?.assessmentYear||ed(),isRevised:"N",userId:Zh(e.identity),submitUrl:n})}function Gh(l,e){return!l||!e?void 0:`${l.replace(/\/+$/,"")}/api/v1/projects/by-slug/${encodeURIComponent(e)}/itr/automation-data`}async function Kh(l){const e=await l.getToken(),t=l.userId||_l(e,"sub");if(!t)throw new Error("[smart-edit] could not resolve userId for GET /itr/automation/eligible");const r=new URLSearchParams({userId:t,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),i=await fetch(`${l.baseUrl}/itr/automation/eligible?${r}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...l.headers}});if(!i.ok){const n=await i.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/automation/eligible → ${i.status} ${n.slice(0,200)}`)}return kl(await i.json().catch(()=>({})))}async function Yh(l,e){const t=await l.getToken(),r=l.userId||_l(t,"sub"),i=qh(e,{userId:r,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),n=l.submitUrl||`${l.baseUrl}/itr/v1/lanretni/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...l.headers};l.txbdyApiKey&&(o["txbdy-api-key"]=l.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const s=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(i)});if(!s.ok){const a=await s.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${s.status} ${a.slice(0,200)}`)}return kl(await s.json().catch(()=>({})))}function Qh(l){if(!l)return null;let e=l.trim().replace(/\/+$/,"");return e=e.replace(/\/itr$/i,""),e||null}function Jh(l){if(!l)return null;try{return new URL(l).origin}catch{return null}}function Xh(l){const e={};if(!l)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(l))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function Zh(l){if(!l)return;const e=l.userId??l.id??l.ext_uid??l.extUid;return e==null||e===""?void 0:String(e)}function _l(l,e){try{const t=l.split(".")[1];if(!t)return"";const i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))[e];return i==null?"":String(i)}catch{return""}}function kl(l){if(l&&typeof l=="object"){const e=l;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ed(){const l=new Date,e=l.getMonth()>=3?l.getFullYear():l.getFullYear()-1;return`${e}-${e+1}`}class td{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new pl(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),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)}),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)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};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)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:$h,data:{}});const t=wl();if(!(!t||!t.baseUrl))try{const r=await Kh(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-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=wl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Yh(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 xl 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||bc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||xo,position:this.getAttribute("position")||this._config.position||gc,width:Number(this.getAttribute("width"))||this._config.width||dc,height:Number(this.getAttribute("height"))||this._config.height||fc,fontFamily:this._config.fontFamily||mc,borderRadius:this._config.borderRadius??pc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||So,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,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||yc,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,i){if(typeof document>"u")return;const n=document.documentElement,o=(s,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${s}`,a)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??i),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}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(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${n};`).join(`
|
|
8
|
+
`)&&(e=e.replace(Qa,"%0A")),e.includes("\r")&&(e=e.replace(Ja,"%0D")),e.includes(" ")&&(e=e.replace(Xa,"%09")),r.pathname=e,r}var ja,Pr,Xi,Mr,Rr,Zi,Lr,eo,jr,to,Nr,ro,Ur,no,Br,io,_t,oo,qe,Na,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,Va,Dr,Ga,Ka,Ya,Qa,Ja,Xa,_h=Ve(()=>{le(),ue(),ce(),Bu(),eh(),dh(),Oa(),ja=Object.freeze(Object.create(null)),Pr={},Xi=!1,Mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Rr={},Zi=!1,Lr={},eo=!1,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,_t={},oo=!1,qe=yh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Na=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=La,qe.fileURLToPath=Ra,Ua=qe.Url,Ba=qe.format,Da=qe.resolve,Fa=qe.resolveObject,$a=qe.parse,qa=qe.URL,Ha=92,Wa=47,za=97,Va=122,Dr=Na==="win32",Ga=/\//g,Ka=/%/g,Ya=/\\/g,Qa=/\n/g,Ja=/\r/g,Xa=/\t/g}),kh=pe((l,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")}}),so=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.BufferedDuplex=void 0,l.writev=r;var e=It(),t=(De(),Me(Be));function r(n,o){let s=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?s[a]=t.Buffer.from(n[a].chunk,"utf8"):s[a]=n[a].chunk;this._write(t.Buffer.concat(s),"binary",o)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,s){super({objectMode:!0}),this.proxy=o,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,o,s){this.isSocketOpen?this.writeToProxy(n,o,s):this.writeQueue.push({chunk:n,encoding:o,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,s){this.proxy.write(n,o)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:s}=this.writeQueue.shift();this.writeToProxy(n,o,s)}}};l.BufferedDuplex=i}),Fr=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(l,"__esModule",{value:!0}),l.streamBuilder=l.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(kh()),i=e(ht()),n=It(),o=e(pr()),s=so(),a=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function h(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!o.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&c.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=h(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){a("createWebSocket"),a(`protocol: ${w.protocolId} ${w.protocolVersion}`);let x=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";a(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[x],w):v=new r.default(m,[x],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(x,[w],m):v=new WebSocket(x,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{a("streamBuilder");let w=h(m);w.hostname=w.hostname||w.host||"localhost";let x=u(w,k),v=y(k,x,w),E=r.default.createWebSocketStream(v,w.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};l.streamBuilder=g;var b=(k,m)=>{a("browserStreamBuilder");let w,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(k,m),I=P(m,U,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),O?S.addEventListener("open",N):S.onopen=N),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 N(){a("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){a("WebSocket onClose",Y),w.end(),w.destroy()}function q(Y){a("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,w.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 w};l.browserStreamBuilder=b}),ao={};Rt(ao,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Za,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 Za,el=Ve(()=>{le(),ue(),ce(),Za={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),tl=pe((l,e)=>{le(),ue(),ce(),e.exports={}}),rl=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(l,"__esModule",{value:!0});var t=e((el(),Me(ao))),r=e(ht()),i=e(tl()),n=(0,r.default)("mqttjs:tcp"),o=(s,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,i.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,h=a.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};l.default=o}),nl={};Rt(nl,{default:()=>il});var il,xh=Ve(()=>{le(),ue(),ce(),il={}}),ol=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(l,"__esModule",{value:!0});var t=(xh(),Me(nl)),r=e((el(),Me(ao))),i=e(ht()),n=e(tl()),o=(0,i.default)("mqttjs:tls");function s(c){let{host:u,port:h,socksProxy:p,...y}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(c)}var a=(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,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=s(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(y){u.rejectUnauthorized&&c.emit("error",y),h.end()}return h.on("error",p),h};l.default=a}),sl=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),i,n,o;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{i.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{i.close({success(){y()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){i.onOpen(()=>{o.socketReady()}),i.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),i.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),i.onError(p=>{let y=new Error(p.errMsg);o.destroy(y)})}var h=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";a(y);let g=c(y,p);i=wx.connectSocket({url:g,protocols:[f]}),n=s(),o=new r.BufferedDuplex(y,n,i),o._destroy=(k,m)=>{i.close({success(){m&&m(k)}})};let b=o.destroy;return o.destroy=(k,m)=>(o.destroy=b,setTimeout(()=>{i.close({fail(){o._destroy(k,m)}})},0),o),u(),o};l.default=h}),al=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),i,n,o,s=!1;function a(){let y=new t.Transform;return y._write=(f,g,b)=>{i.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{i.closeSocket({success(){f()}})},y}function c(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function h(){s||(s=!0,i.onSocketOpen(()=>{o.socketReady()}),i.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),i.onSocketClose(()=>{o.end(),o.destroy()}),i.onSocketError(y=>{o.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let b=u(f,y);return i=f.my,i.connectSocket({url:b,protocols:g}),n=a(),o=new r.BufferedDuplex(f,n,i),h(),o};l.default=p}),Sh=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(l,"__esModule",{value:!0}),l.connectAsync=u;var t=e(ht()),r=e((_h(),Me(Pa))),i=e(di()),n=e(pr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),s=null;function a(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;h.username=y,h.password=f}else h.username=h.auth}function c(h,p){if(o("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),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...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,a(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(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=Fr().streamBuilder,s.wss=Fr().streamBuilder,s.mqtt=rl().default,s.tcp=rl().default,s.ssl=ol().default,s.tls=s.ssl,s.mqtts=ol().default):(s.ws=Fr().browserStreamBuilder,s.wss=Fr().browserStreamBuilder,s.wx=sl().default,s.wxs=sl().default,s.ali=al().default,s.alis=al().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(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++),o("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new i.default(y,p);return f.on("error",()=>{}),f}function u(h,p,y=!0){return new Promise((f,g)=>{let b=c(h,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}l.default=c}),ll=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=l&&l.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=l&&l.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),i=l&&l.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=l&&l.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=l.KeepaliveManager=l.UniqueMessageIdProvider=l.DefaultMessageIdProvider=l.Store=l.MqttClient=l.connectAsync=l.connect=l.Client=void 0;var o=n(di());l.MqttClient=o.default;var s=n(ms());l.DefaultMessageIdProvider=s.default;var a=n(Nu());l.UniqueMessageIdProvider=a.default;var c=n(ls());l.Store=c.default;var u=r(Sh());l.connect=u.default,Object.defineProperty(l,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ks());l.KeepaliveManager=h.default,l.Client=o.default,i(di(),l),i(Ut(),l),i(as(),l);var p=dr();Object.defineProperty(l,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Eh=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(o,s,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(s,a);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[a]}}),Object.defineProperty(o,c,u)}:function(o,s,a,c){c===void 0&&(c=a),o[c]=s[a]}),t=l&&l.__setModuleDefault||(Object.create?function(o,s){Object.defineProperty(o,"default",{enumerable:!0,value:s})}:function(o,s){o.default=s}),r=l&&l.__importStar||(function(){var o=function(s){return o=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},o(s)};return function(s){if(s&&s.__esModule)return s;var a={};if(s!=null)for(var c=o(s),u=0;u<c.length;u++)c[u]!=="default"&&e(a,s,c[u]);return t(a,s),a}})(),i=l&&l.__exportStar||function(o,s){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(s,a)&&e(s,o,a)};Object.defineProperty(l,"__esModule",{value:!0});var n=r(ll());l.default=n,i(ll(),l)});const Ah=Eh();const Ih={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}/#"},Th=300,Ch={templateId:"7",type:"link",isDeepLink:!0},Oh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class cl{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={...Ih,...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,i={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&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,o)=>{let s=!1;const a=h=>{s||(s=!0,clearTimeout(u),h())},c=(h,p)=>{s||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),a(()=>o(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Ah.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),s||a(()=>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),!s){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),s||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",{}),s||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[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=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 i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...Ch,...this.config.fileTemplate??{},...Ph(t)},i={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??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Th){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,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 i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.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 i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:h,raw:i};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),s=o?.groups?.conversationId,a={topic:e,conversationId:s,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,a))}buildOutgoingEnvelope(e,t){const r={...Oh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={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:i,senderFullname:i,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:o}}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,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=o[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Ph(l){const e={};for(const[t,r]of Object.entries(l))r!==void 0&&(e[t]=r);return e}function ul(l,e){return(l.sender??"").toString()===e}function hl(l,e){const t=(l.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(l){const e={raw:l},t=l.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 l.text=="string"&&l.text.trim().startsWith("{"))try{const i=JSON.parse(l.text);typeof i.message=="string"&&(e.innerMessage=i.message);const n=i.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=l.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function dl(l){const e=lo(l);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 i=r[0],n=i.action,o=n&&typeof n.url=="string"?n.url:void 0,s=typeof i.description=="string"?i.description:void 0,a=l.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!o&&!s?null:{fileName:s,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function fl(l,e,t){const r=hl(l,t),i=lo(l),n=dl(l);let o="";i.innerMessage?o=i.innerMessage:typeof l.text=="string"&&(l.text.trim().startsWith("{")?i.contentType!=="300"&&(o=l.text):o=l.text);const s=typeof l.message_id=="string"?l.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=typeof l.timestamp=="number"?new Date(l.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof l.status=="number"?Mh(l.status):"delivered",h={id:s,externalId:s,conversationId:e,role:c,content:o,createdAt:a,status:u,metadata:{sender:l.sender,sender_fullname:l.sender_fullname??l.senderFullname,app_id:l.app_id,attributes:l.attributes}};return i.contentType&&(h.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:i}}function Mh(l){return l<0?"error":l>=250?"read":l>=150?"delivered":"sent"}class pl extends ir{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 Ao(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Io,this.conversationManager=new Mo(e.conversationId),this.usesAikaara()&&(this.connection=new Eo(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.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 cl({...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 i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),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),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(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(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const i=r.map(s=>fl(s,e,{userId:t}).message).sort((s,a)=>new Date(s.createdAt).getTime()-new Date(a.createdAt).getTime()),n=this.messageStore.messages,o=[...i,...n.filter(s=>!i.some(a=>a.externalId&&a.externalId===s.externalId))];if(this.messageStore.setMessages(o),this.config.onMessage)for(const s of i)try{this.config.onMessage(s)}catch(a){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",a)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);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 i=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:i.fileName,fileUrl:i.url,cloudFileId:i.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 i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,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=t.conversationId??this.conversationManager.conversationId;if(!r)return;const i=this.config.tiledeskIdentity?.userId??"",{message:n,template:o}=fl(e,r,{userId:i,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(ul(e,i)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:s,deduped:a}=this.messageStore.upsertRemoteMessage(n);if(a)this.emit("message:updated",s);else{this.emit("message:received",s),this.config.onMessage?.(s);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:s.role,hasAttachments:Array.isArray(s.attachments)&&s.attachments.length>0,templateId:s.template?.templateId,messageId:s.id,conversationId:s.conversationId}}))}catch{}}if(o.contentType){const c={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:o.contentType,templateId:o.templateId,payload:o.payload,innerMessage:o.innerMessage,raw:e};this.config.onTemplateMessage?.(c)}}handleTiledeskStatusUpdate(e){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{}}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||"",i=e.content||"";i?this.messageStore.updateStreaming(i):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,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.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}}}class Rh extends ir{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const ml={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 Lh(l){const e=l.lastIndexOf(".");return e<0||e===l.length-1?"":l.slice(e+1).toLowerCase()}function jh(l,e,t){const r=Lh(l.name||"");if(r&&e&&e[r])return e[r];const i=l.type;return i&&i.trim().length>0?i:r&&ml[r]?ml[r]:t}function co(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Nh(l,e){const t=e.split(".");let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function gl(l){const e=l.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=jh(t,l.contentTypeMap,l.contentTypeFallback??"application/octet-stream"),o={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},s=l.authHeader?await l.authHeader():void 0,a={accept:"application/json",...l.extraHeaders??{},...s?{authorization:s}:{}};let c=l.signEndpoint.includes("{")?l.signEndpoint:`${l.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const k=c.includes("?")?"&":"?";c=`${c}${k}contentType={contentType}`}const u=co(c,o),h=await fetch(u,{method:l.signMethod??"GET",headers:a});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),y=Nh(p,e);if(!y)throw new Error(`Sign response missing path "${e}"`);const f=l.s3HostRewrite?y.replace(/^https:\/\/[^/]+/i,l.s3HostRewrite):y,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const k=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${k.slice(0,200)}`)}if(l.registerEndpoint){const k=JSON.parse(co(JSON.stringify(l.registerBody??{}),o)),m=await fetch(l.registerEndpoint,{method:"POST",headers:{...a,"content-type":"application/json"},body:JSON.stringify(k)});if(!m.ok){const w=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${w.slice(0,200)}`)}}return{url:l.viewerTemplate?co(l.viewerTemplate,o):y.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function uo(l){return{async upload(e,t){const r=new FormData,i=l.fieldName??"file";r.append(i,e,e.name);const n=typeof l.extraFields=="function"?l.extraFields(t):l.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof l.headers=="function"?await l.headers():l.headers??{},s=await fetch(l.endpoint,{method:l.method??"POST",body:r,headers:o,credentials:l.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const a=await s.json().catch(()=>({}));if(l.parseResponse)return l.parseResponse(a,t);const c=a,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 Uh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function bl(l){const e=l.apiBase.replace(/\/$/,""),t=l.pageSize??200,r=l.pathTemplate??Uh;return{async fetchMessages(i,n){const o=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,a={accept:"application/json","content-type":"application/json",...l.extraHeaders??{}};if(l.getToken){const p=await l.getToken();p&&(a.authorization=p)}const c=await fetch(s,{method:"GET",headers:a}),u=await c.json().catch(()=>null);if(l.parseResponse&&u)return l.parseResponse(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 Bh="^[A-Z]{5}[0-9]{4}[A-Z]$",Dh="^[A-Z]{4}[0-9]{5}[A-Z]$",Fh="^[A-Z]{4}0[A-Z0-9]{6}$",yl="^[0-9]{6}$",$h=[{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)",required:!0,pattern:Dh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},{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}]}],submitLabel:"Save"},{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"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Bh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Fh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function qh(l,e){const t=l||{},r={userId:zh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Pe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Pe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Pe(t.us80dForParentsAmount),r.hasParentOverSixty=ho(t.hasParentOverSixty),r.preventiveHealthCheckUp=Pe(t.preventiveHealthCheckUp),r.medicalExpenditure=Pe(t.medicalExpenditure),r.savingBankInterest=Pe(t.savingBankInterest),r.fdInterest=Pe(t.fdInterest),r.dividend=Pe(t.dividend),r.anyOtherIncome=Pe(t.anyOtherIncome),r.cryptoSellValue=Pe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Pe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Pe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Pe(t.grossReceipts),r.businessNetProfit=Pe(t.netProfit),r.agricultureDetails={income:Pe(t.agricultureIncome)},r.exemptIncomeAmount=Pe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Pe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Pe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const i={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Pe(t.immovableAssetCost)};Object.values(i).some(s=>s!==void 0)&&(r.immovableAsset=[i]);const n=fo(t.hpDetails,Hh);n.length&&(r.hpDetails=n);const o=fo(t.salaryDetails,Wh);if(o.length){r.salaryIncome=o;const s=fo(t.salaryDetails,c=>({grossSalary:Pe(c.grossSalary),employerName:Re(c.employerName)}));s.length&&(r.salary=s);const a=vl(t.salaryDetails)[0]??{};r.hraAmount=Pe(a.hraReceived),r.leaveTravelAllowanceAmount=Pe(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Pe(a.leaveEncashment),r.anyOtherAllowanceAmount=Pe(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return $r(r)}function Hh(l){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(l.loanTakenFrom),bankOrInstituteName:Re(l.lenderName),loanAccountNo:Re(l.loanAccountNumber),loanSanctionDate:Vh(l.sanctionDate),totalLoanAmount:Pe(l.totalLoanAmount),interest:Pe(l.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Re(l.typeOfHouseProperty),hasRentalIncome:l.typeOfHouseProperty==="LOP"?!0:ho(l.hasRentalIncome),homeLoanInterest:Pe(l.homeLoanInterest),homeLoanPrinciple:Pe(l.homeLoanPrinciple),housePropertyAddress:Re(l.housePropertyAddress),housePropertyPincode:Re(l.housePropertyPincode),rentalIncome:Pe(l.rentalIncome),nameOfTenant:Re(l.nameOfTenant),propertyTax:Pe(l.propertyTax),hasCoOwnedProperty:ho(l.hasCoOwnedProperty),coOwnerName:Re(l.coOwnerName),coOwnerPan:Re(l.coOwnerPan),coOwnerShare:Re(l.coOwnerShare),loanDetails:t?[e]:void 0}}function Wh(l){return{grossSalaryIncome:Pe(l.grossSalary),salary:Pe(l.basicSalary),employer:{employerName:Re(l.employerName),employerTan:Re(l.employerTan)},allowance:{hraAmount:Pe(l.hraReceived),leaveTravelAllowanceAmount:Pe(l.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Pe(l.leaveEncashment),anyOtherAllowanceAmount:Pe(l.anyOtherAllowance)}}}function zh(l){if(l===void 0||l==="")return;const e=Number(l);return Number.isFinite(e)&&String(e)===String(l)?e:l}function Pe(l){if(l==null||l==="")return;const e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:void 0}function Re(l){if(l==null)return;const e=String(l).trim();return e===""?void 0:e}function ho(l){return l===!0||l===!1?l:void 0}function Vh(l){const e=Re(l);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function vl(l){return Array.isArray(l)?l.filter(e=>e&&typeof e=="object"):[]}function fo(l,e){return vl(l).map(t=>$r(e(t))).filter(t=>t!==void 0)}function $r(l){if(Array.isArray(l)){const e=l.map($r).filter(t=>t!==void 0);return e.length?e:void 0}if(l&&typeof l=="object"){const e={};for(const[t,r]of Object.entries(l)){const i=$r(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return l}function wl(){if(typeof window>"u")return null;const l=window,e=l.__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=e.getChatJwt,r=l.__aikaara_descriptor__??{},i=Qh(r.api?.baseUrl)??Jh(r.auth?.endpoint)??"",n=r.itr?.automationSubmitUrl||Gh(e.configBase,e.slug);return!n&&!i?(console.warn(`[smart-edit] API disabled: no submit URL could be derived (configBase=${e.configBase??"undefined"}, slug=${e.slug??"undefined"}).`),null):(console.info("[smart-edit] API config — submitUrl:",n||"(none)","· baseUrl:",i||"(none)"),{baseUrl:i,getToken:()=>t(),headers:Xh(r.auth?.headers),assessmentYear:r.itr?.assessmentYear||ed(),isRevised:"N",userId:Zh(e.identity),submitUrl:n})}function Gh(l,e){return!l||!e?void 0:`${l.replace(/\/+$/,"")}/api/v1/projects/by-slug/${encodeURIComponent(e)}/itr/automation-data`}async function Kh(l){const e=await l.getToken(),t=l.userId||_l(e,"sub");if(!t)throw new Error("[smart-edit] could not resolve userId for GET /itr/automation/eligible");const r=new URLSearchParams({userId:t,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),i=await fetch(`${l.baseUrl}/itr/automation/eligible?${r}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...l.headers}});if(!i.ok){const n=await i.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/automation/eligible → ${i.status} ${n.slice(0,200)}`)}return kl(await i.json().catch(()=>({})))}async function Yh(l,e){const t=await l.getToken(),r=l.userId||_l(t,"sub"),i=qh(e,{userId:r,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),n=l.submitUrl||`${l.baseUrl}/itr/v1/lanretni/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...l.headers};l.txbdyApiKey&&(o["txbdy-api-key"]=l.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const s=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(i)});if(!s.ok){const a=await s.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${s.status} ${a.slice(0,200)}`)}return kl(await s.json().catch(()=>({})))}function Qh(l){if(!l)return null;let e=l.trim().replace(/\/+$/,"");return e=e.replace(/\/itr$/i,""),e||null}function Jh(l){if(!l)return null;try{return new URL(l).origin}catch{return null}}function Xh(l){const e={};if(!l)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(l))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function Zh(l){if(!l)return;const e=l.userId??l.id??l.ext_uid??l.extUid;return e==null||e===""?void 0:String(e)}function _l(l,e){try{const t=l.split(".")[1];if(!t)return"";const i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))[e];return i==null?"":String(i)}catch{return""}}function kl(l){if(l&&typeof l=="object"){const e=l;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ed(){const l=new Date,e=l.getMonth()>=3?l.getFullYear():l.getFullYear()-1;return`${e}-${e+1}`}class td{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new pl(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)}),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)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};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)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:$h,data:{}});const t=wl();if(!(!t||!t.baseUrl))try{const r=await Kh(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-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=wl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Yh(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 xl 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||bc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||xo,position:this.getAttribute("position")||this._config.position||gc,width:Number(this.getAttribute("width"))||this._config.width||dc,height:Number(this.getAttribute("height"))||this._config.height||fc,fontFamily:this._config.fontFamily||mc,borderRadius:this._config.borderRadius??pc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||So,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||yc,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,i){if(typeof document>"u")return;const n=document.documentElement,o=(s,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${s}`,a)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??i),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}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(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${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;
|
|
@@ -1467,7 +1467,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1467
1467
|
}
|
|
1468
1468
|
.save-btn:hover { filter: brightness(1.07); }
|
|
1469
1469
|
.save-btn:active { filter: brightness(0.95); }
|
|
1470
|
-
`}}function Ot(l){return l.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qe(l){return l.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",bd],["aikaara-system-pill",_d],["aikaara-option-list",kd],["aikaara-submit-action",xd],["aikaara-modal-action",Ed],["aikaara-chat",Ad],["aikaara-link-modal",Id],["aikaara-compare-plans",Od],["aikaara-smart-edit-modal",Pd],["aikaara-schema-form",Ld]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Fl(l){try{const e=l.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 Xt(l){return typeof l=="function"?await l():l}class $l{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=Fl(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 Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=Hr(a,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=Hr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),b=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await jd(t,l.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 jd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Nd(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${Ud(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function Nd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Wr(l){try{return l()}catch{return}}function Ud(l){return l.replace(/["\\]/g,"\\$&")}const Bd=1800;class Hl{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 ql({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 i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)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(i,{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 s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Bd;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 Dd=3e4,Fd=2e3,$d=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=qd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Hd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=Kd(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dd;return{token:await Gd({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Wd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=zd(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Fd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:$d,o=await Vd(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(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 Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function qd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function Hd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Wd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function zd(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=Vl(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Vd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Vl(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Gd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Kd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function Yd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.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 Qd="aikaara_chat:requestId";function vo(l,e){return`${Qd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Jd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Xd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Zd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Xt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&ef(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function ef(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.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 Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Yd().replace(/-/g,""))}function Ql(l){const e=l._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=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(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 i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:Gl(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??Yl(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&Jd(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.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,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,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:l.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,tiledesk:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function tf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.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:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new zl({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new Hl({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await Zd(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new $l(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?Gl(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?Yl(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Xt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?gl({...x,authHeader:v}):x&&x.mode==="direct"?uo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Jl({container:tf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Xt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}function rf(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,i]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(i,String(n))}return e.configure(l),document.body.appendChild(e),e}function nf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1470
|
+
`}}function Ot(l){return l.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qe(l){return l.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",bd],["aikaara-system-pill",_d],["aikaara-option-list",kd],["aikaara-submit-action",xd],["aikaara-modal-action",Ed],["aikaara-chat",Ad],["aikaara-link-modal",Id],["aikaara-compare-plans",Od],["aikaara-smart-edit-modal",Pd],["aikaara-schema-form",Ld]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Fl(l){try{const e=l.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 Xt(l){return typeof l=="function"?await l():l}class $l{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=Fl(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 Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=Hr(a,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=Hr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),b=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await jd(t,l.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 jd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Nd(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${Ud(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function Nd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Wr(l){try{return l()}catch{return}}function Ud(l){return l.replace(/["\\]/g,"\\$&")}const Bd=1800;class Hl{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 ql({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 i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)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(i,{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 s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Bd;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 Dd=3e4,Fd=2e3,$d=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=qd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Hd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=Kd(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dd;return{token:await Gd({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Wd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=zd(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Fd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:$d,o=await Vd(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(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 Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function qd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function Hd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Wd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function zd(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=Vl(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Vd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Vl(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Gd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Kd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function Yd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.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 Qd="aikaara_chat:requestId";function vo(l,e){return`${Qd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Jd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Xd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Zd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Xt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&ef(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function ef(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.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 Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Yd().replace(/-/g,""))}function Ql(l){const e=l._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=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(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 i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:Gl(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??Yl(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&Jd(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.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,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,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:l.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:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function tf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.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:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new zl({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new Hl({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await Zd(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new $l(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?Gl(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?Yl(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Xt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?gl({...x,authHeader:v}):x&&x.mode==="direct"?uo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Jl({container:tf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Xt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}function rf(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,i]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(i,String(n))}return e.configure(l),document.body.appendChild(e),e}function nf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1471
1471
|
<style>
|
|
1472
1472
|
:host { display: block; margin-top: 8px; }
|
|
1473
1473
|
button {
|