@aikaara/chat-sdk 1.5.24 → 1.5.25
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/{AikaaraLinkButton-DSPDgkZv.cjs → AikaaraLinkButton-BaOKaIAZ.cjs} +1 -1
- package/dist/{AikaaraLinkButton-DUkMTDJ9.mjs → AikaaraLinkButton-DuUkgMrC.mjs} +1 -1
- package/dist/{MountTenant-p_VfY0Qt.mjs → MountTenant-B-NNZzU9.mjs} +3 -3
- package/dist/{MountTenant-DATypl45.cjs → MountTenant-BrUAO0_L.cjs} +2 -2
- package/dist/cdn/aikaara-chat.iife.js +1 -1
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- 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
|
`+oe.prev+oe.base;return Ie+I.call(K,","+Ie)+`
|
|
6
6
|
`+oe.prev}function xe(K,oe){var Ie=pe(K),Te=[];if(Ie){Te.length=K.length;for(var Oe=0;Oe<K.length;Oe++)Te[Oe]=se(K,Oe)?oe(K[Oe],K):""}var Ne=typeof T=="function"?T(K):[],it;if($){it={};for(var ot=0;ot<Ne.length;ot++)it["$"+Ne[ot]]=Ne[ot]}for(var He in K)se(K,He)&&(Ie&&String(Number(He))===He&&He<K.length||$&&it["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Te.push(oe(He,K)+": "+oe(K[He],K)):Te.push(He+": "+oe(K[He],K))));if(typeof T=="function")for(var st=0;st<Ne.length;st++)X.call(K,Ne[st])&&Te.push("["+oe(Ne[st])+"]: "+oe(K[Ne[st]],K));return Te}return Br}function rh(){if(ho)return qr;ho=!0;var o=er(),e=Fd(),t=th(),r=gr(),i=o("%WeakMap%",!0),n=o("%Map%",!0),s=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=p(y,w);return m&&m.value},h=function(y,w,m){var k=p(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return qr=function(){var y,w,m,k={assert:function(_){if(!k.has(_))throw new r("Side channel does not contain "+t(_))},get:function(_){if(i&&_&&(typeof _=="object"||typeof _=="function")){if(y)return s(y,_)}else if(n){if(w)return c(w,_)}else if(m)return g(m,_)},has:function(_){if(i&&_&&(typeof _=="object"||typeof _=="function")){if(y)return l(y,_)}else if(n){if(w)return d(w,_)}else if(m)return b(m,_);return!1},set:function(_,v){i&&_&&(typeof _=="object"||typeof _=="function")?(y||(y=new i),a(y,_,v)):n?(w||(w=new n),u(w,_,v)):(m||(m={key:{},next:null}),h(m,_,v))}};return k},qr}function No(){if(fo)return Hr;fo=!0;var o=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Hr={default:t.RFC3986,formatters:{RFC1738:function(r){return o.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Hr}function Al(){if(po)return Wr;po=!0;var o=No(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),i=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],_=0;_<m.length;++_)typeof m[_]<"u"&&k.push(m[_]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},s=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var _=w;return t(w)&&!t(m)&&(_=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,k):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,k):v[E]=S,v},_)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,_){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,P=[],O=0;O<I.length;++O){var j=I.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||_===o.RFC1738&&(j===40||j===41)){P[P.length]=I.charAt(O);continue}if(j<128){P[P.length]=r[j];continue}if(j<2048){P[P.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){P[P.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=P.join("")}return E},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var _=w[k],v=_.obj[_.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return i(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},h=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Wr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:s},Wr}function nh(){if(mo)return zr;mo=!0;var o=rh(),e=Al(),t=No(),r=Object.prototype.hasOwnProperty,i={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,k,_,v,E,S,I,P,O,j,T,F,$,U,X,z){for(var W=y,ne=z,D=0,G=!1;(ne=ne.get(p))!==void 0&&!G;){var L=ne.get(y);if(D+=1,typeof L<"u"){if(L===D)throw new RangeError("Cyclic object value");G=!0}typeof ne.get(p)>"u"&&(D=0)}if(typeof P=="function"?W=P(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(M){return M instanceof Date?T(M):M})),W===null){if(v)return I&&!U?I(w,u.encoder,X,"key",F):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var Y=U?w:I(w,u.encoder,X,"key",F);return[$(Y)+"="+$(I(W,u.encoder,X,"value",F))]}return[$(w)+"="+$(String(W))]}var pe=[];if(typeof W>"u")return pe;var te;if(m==="comma"&&n(W))U&&I&&(W=e.maybeMap(W,I)),te=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))te=P;else{var ve=Object.keys(W);te=O?ve.sort(O):ve}var J=S?w.replace(/\./g,"%2E"):w,R=k&&n(W)&&W.length===1?J+"[]":J;if(_&&n(W)&&W.length===0)return R+"[]";for(var ie=0;ie<te.length;++ie){var V=te[ie],Q=typeof V=="object"&&typeof V.value<"u"?V.value:W[V];if(!(E&&Q===null)){var Z=j&&S?V.replace(/\./g,"%2E"):V,be=n(W)?typeof m=="function"?m(R,Z):R:R+(j?"."+Z:"["+Z+"]");z.set(y,D);var se=o();se.set(p,z),a(pe,b(Q,be,m,k,_,v,E,S,m==="comma"&&U&&n(W)?null:I,P,O,j,T,F,$,U,X,se))}}return pe},h=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=b.filter);var _;if(b.arrayFormat in i?_=b.arrayFormat:"indices"in b?_=b.indices?"indices":"repeat":_=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:_,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return zr=function(b,y){var w=b,m=h(y),k,_;typeof m.filter=="function"?(_=m.filter,w=_("",w)):n(m.filter)&&(_=m.filter,k=_);var v=[];if(typeof w!="object"||w===null)return"";var E=i[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=o(),P=0;P<k.length;++P){var O=k[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},zr}function ih(){if(go)return Vr;go=!0;var o=Al(),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:o.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(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var h={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,_=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?_="utf-8":w[k]===s&&(_="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,P;S===-1?(I=g.decoder(v,r.decoder,_,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,_,"key"),P=o.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,_,"value")})),P&&g.interpretNumericEntities&&_==="iso-8859-1"&&(P=i(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(h,I);O&&g.duplicates==="combine"?h[I]=o.combine(h[I],P):(!O||g.duplicates==="last")&&(h[I]=P)}return h},c=function(p,g,h,b){for(var y=b?g:n(g,h),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var _=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?_.replace(/%2E/g,"."):_,E=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(E)&&k!==v&&String(E)===v&&E>=0&&h.parseArrays&&E<=h.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,h,b){if(p){var y=h.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),_=k?y.slice(0,k.index):y,v=[];if(_){if(!h.plainObjects&&e.call(Object.prototype,_)&&!h.allowPrototypes)return;v.push(_)}for(var E=0;h.depth>0&&(k=m.exec(y))!==null&&E<h.depth;){if(E+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=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 g=typeof p.charset>"u"?r.charset:p.charset,h=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,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:g,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"||o.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:h,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 Vr=function(p,g){var h=d(g);if(p===""||p===null||typeof p>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,h):p,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],_=u(k,b[k],h,typeof p=="string");y=o.merge(y,_,h)}return h.allowSparse===!0?y:o.compact(y)},Vr}function oh(){if(bo)return Kr;bo=!0;var o=nh(),e=ih(),t=No();return Kr={formats:t,parse:e,stringify:o},Kr}function sh(){if(yo)return Ct;yo=!0;var o=Tt;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
|
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},h={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=oh();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(P);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var F=i.exec(T);if(F)return this.path=T,this.href=T,this.pathname=F[1],F[2]?(this.search=F[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var $=t.exec(T);if($){$=$[0];var U=$.toLowerCase();this.protocol=U,T=T.substr($.length)}if(S||$||T.match(/^\/\/[^@/]+@[^@/]+/)){var X=T.substr(0,2)==="//";X&&!($&&h[$])&&(T=T.substr(2),this.slashes=!0)}if(!h[$]&&(X||$&&!b[$])){for(var z=-1,W=0;W<c.length;W++){var ne=T.indexOf(c[W]);ne!==-1&&(z===-1||ne<z)&&(z=ne)}var D,G;z===-1?G=T.lastIndexOf("@"):G=T.lastIndexOf("@",z),G!==-1&&(D=T.slice(0,G),T=T.slice(G+1),this.auth=decodeURIComponent(D)),z=-1;for(var W=0;W<l.length;W++){var ne=T.indexOf(l[W]);ne!==-1&&(z===-1||ne<z)&&(z=ne)}z===-1&&(z=T.length),this.host=T.slice(0,z),T=T.slice(z),this.parseHost(),this.hostname=this.hostname||"";var L=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!L)for(var Y=this.hostname.split(/\./),W=0,pe=Y.length;W<pe;W++){var te=Y[W];if(te&&!te.match(d)){for(var ve="",J=0,R=te.length;J<R;J++)te.charCodeAt(J)>127?ve+="x":ve+=te[J];if(!ve.match(d)){var ie=Y.slice(0,W),V=Y.slice(W+1),Q=te.match(p);Q&&(ie.push(Q[1]),V.unshift(Q[2])),V.length&&(T="/"+V.join(".")+T),this.hostname=ie.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),L||(this.hostname=o.toASCII(this.hostname));var Z=this.port?":"+this.port:"",be=this.hostname||"";this.host=be+Z,this.href+=this.host,L&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var W=0,pe=a.length;W<pe;W++){var se=a[W];if(T.indexOf(se)!==-1){var M=encodeURIComponent(se);M===se&&(M=escape(se)),T=T.split(se).join(M)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));var re=T.indexOf("?");if(re!==-1?(this.search=T.substr(re),this.query=T.substr(re+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,re)):E&&(this.search="",this.query={}),T&&(this.pathname=T),b[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Z=this.pathname||"",he=this.search||"";this.path=Z+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",P=!1,O="";this.host?P=v+this.host:this.hostname&&(P=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(P+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||O&&"?"+O||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||b[E])&&P!==!1?(P="//"+(P||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+P+S+j+I};function k(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function _(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var F=j[T];F!=="protocol"&&(S[F]=v[F])}return b[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(!b[v.protocol]){for(var $=Object.keys(v),U=0;U<$.length;U++){var X=$[U];S[X]=v[X]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!h[v.protocol]){for(var pe=(v.pathname||"").split("/");pe.length&&!(v.host=pe.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),pe[0]!==""&&pe.unshift(""),pe.length<2&&pe.unshift(""),S.pathname=pe.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 z=S.pathname||"",W=S.search||"";S.path=z+W}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var ne=S.pathname&&S.pathname.charAt(0)==="/",D=v.host||v.pathname&&v.pathname.charAt(0)==="/",G=D||ne||S.host&&v.pathname,L=G,Y=S.pathname&&S.pathname.split("/")||[],pe=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!b[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Y[0]===""?Y[0]=S.host:Y.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(pe[0]===""?pe[0]=v.host:pe.unshift(v.host)),v.host=null),G=G&&(pe[0]===""||Y[0]==="")),D)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,Y=pe;else if(pe.length)Y||(Y=[]),Y.pop(),Y=Y.concat(pe),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Y.shift(),S.hostname=S.host;var ve=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;ve&&(S.auth=ve.shift(),S.hostname=ve.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(!Y.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var J=Y.slice(-1)[0],R=(S.host||v.host||Y.length>1)&&(J==="."||J==="..")||J==="",ie=0,V=Y.length;V>=0;V--)J=Y[V],J==="."?Y.splice(V,1):J===".."?(Y.splice(V,1),ie++):ie&&(Y.splice(V,1),ie--);if(!G&&!L)for(;ie--;ie)Y.unshift("..");G&&Y[0]!==""&&(!Y[0]||Y[0].charAt(0)!=="/")&&Y.unshift(""),R&&Y.join("/").substr(-1)!=="/"&&Y.push("");var Q=Y[0]===""||Y[0]&&Y[0].charAt(0)==="/";if(te){S.hostname=Q?"":Y.length?Y.shift():"",S.host=S.hostname;var ve=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;ve&&(S.auth=ve.shift(),S.hostname=ve.shift(),S.host=S.hostname)}return G=G||S.host&&Y.length,G&&!Q&&Y.unshift(""),Y.length>0?S.pathname=Y.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)},Ct.parse=w,Ct.resolve=k,Ct.resolveObject=_,Ct.format=m,Ct.Url=e,Ct}function Il(o){if(typeof o=="string")o=new URL(o);else if(!(o instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(o.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Jr?ah(o):lh(o)}function ah(o){let e=o.hostname,t=o.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(Bl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,i=t[2];if(r<$l||r>Ul||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function lh(o){if(o.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=o.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 Tl(o){let e=co.resolve(o),t=o.charCodeAt(o.length-1);(t===Dl||Jr&&t===jl)&&e[e.length-1]!==co.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Fl,"%25")),!Jr&&e.includes("\\")&&(e=e.replace(ql,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(Hl,"%0A")),e.includes("\r")&&(e=e.replace(Wl,"%0D")),e.includes(" ")&&(e=e.replace(zl,"%09")),r.pathname=e,r}var Cl,Br,uo,Fr,qr,ho,Hr,fo,Wr,po,zr,mo,Vr,go,Kr,bo,Ct,yo,Ke,Js,Pl,Ol,Ll,Ml,Nl,Rl,jl,Dl,$l,Ul,Jr,Bl,Fl,ql,Hl,Wl,zl,ch=Qe(()=>{le(),ue(),ce(),Ad(),qd(),eh(),Sl(),Cl=Object.freeze(Object.create(null)),Br={},uo=!1,Fr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,qr={},ho=!1,Hr={},fo=!1,Wr={},po=!1,zr={},mo=!1,Vr={},go=!1,Kr={},bo=!1,Ct={},yo=!1,Ke=sh(),Ke.parse,Ke.resolve,Ke.resolveObject,Ke.format,Ke.Url,Js=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ke.URL=typeof URL<"u"?URL:null,Ke.pathToFileURL=Tl,Ke.fileURLToPath=Il,Pl=Ke.Url,Ol=Ke.format,Ll=Ke.resolve,Ml=Ke.resolveObject,Nl=Ke.parse,Rl=Ke.URL,jl=92,Dl=47,$l=97,Ul=122,Jr=Js==="win32",Bl=/\//g,Fl=/%/g,ql=/\\/g,Hl=/\n/g,Wl=/\r/g,zl=/\t/g}),uh=me((o,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")}}),Ro=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.BufferedDuplex=void 0,o.writev=r;var e=Ft(),t=(qe(),Re(Fe));function r(n,s){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",s)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};o.BufferedDuplex=i}),wr=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(o,"__esModule",{value:!0}),o.streamBuilder=o.browserStreamBuilder=void 0;var t=(qe(),Re(Fe)),r=e(uh()),i=e(vt()),n=Ft(),s=e(on()),a=Ro(),l=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function p(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let _=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${_}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[_],k):v=new r.default(m,[_],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",_=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(_,[k],m):v=new WebSocket(_,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let _=u(k,w),v=g(w,_,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=_,v.on("close",()=>{E.destroy()}),E};o.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,_=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,X);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=I,k.socket=S):(k=new a.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",F),S.addEventListener("message",$)):(S.onclose=T,S.onerror=F,S.onmessage=$);function O(z,W,ne){let D=new n.Transform({objectMode:z.objectMode});return D._write=W,D._flush=ne,D}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(z){l("WebSocket onClose",z),k.end(),k.destroy()}function F(z){l("WebSocket onError",z);let W=new Error("WebSocket error");W.event=z,k.destroy(W)}async function $(z){if(!I||!I.readable||!I.writable)return;let{data:W}=z;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function U(z,W,ne){if(S.bufferedAmount>_){setTimeout(U,v,z,W,ne);return}E&&typeof z=="string"&&(z=t.Buffer.from(z,"utf8"));try{S.send(z)}catch(D){return ne(D)}ne()}function X(z){S.close(),z()}return k};o.browserStreamBuilder=y}),jo={};Qt(jo,{Server:()=>$e,Socket:()=>$e,Stream:()=>$e,_createServerHandle:()=>$e,_normalizeArgs:()=>$e,_setSimultaneousAccepts:()=>$e,connect:()=>$e,createConnection:()=>$e,createServer:()=>$e,default:()=>Vl,isIP:()=>$e,isIPv4:()=>$e,isIPv6:()=>$e});function $e(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Vl,Kl=Qe(()=>{le(),ue(),ce(),Vl={_createServerHandle:$e,_normalizeArgs:$e,_setSimultaneousAccepts:$e,connect:$e,createConnection:$e,createServer:$e,isIP:$e,isIPv4:$e,isIPv6:$e,Server:$e,Socket:$e,Stream:$e}}),Gl=me((o,e)=>{le(),ue(),ce(),e.exports={}}),Qs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0});var t=e((Kl(),Re(jo))),r=e(vt()),i=e(Gl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,i.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};o.default=s}),Yl={};Qt(Yl,{default:()=>Jl});var Jl,dh=Qe(()=>{le(),ue(),ce(),Jl={}}),Xs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(o,"__esModule",{value:!0});var t=(dh(),Re(Yl)),r=e((Kl(),Re(jo))),i=e(vt()),n=e(Gl()),s=(0,i.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let h=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,s("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};o.default=l}),Zs=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s;function a(){let p=new t.Transform;return p._write=(g,h,b)=>{i.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{i.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let h=p.protocol==="wxs"?"wss":"ws",b=`${h}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${h}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){i.onOpen(()=>{s.socketReady()}),i.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),i.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),i.onError(p=>{let g=new Error(p.errMsg);s.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);i=wx.connectSocket({url:b,protocols:[h]}),n=a(),s=new r.BufferedDuplex(g,n,i),s._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{i.close({fail(){s._destroy(w,m)}})},0),s),u(),s};o.default=d}),ea=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{i.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{i.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,i.onSocketOpen(()=>{s.socketReady()}),i.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),i.onSocketClose(()=>{s.end(),s.destroy()}),i.onSocketError(g=>{s.destroy(g)}))}var p=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return i=h.my,i.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(h,n,i),d(),s};o.default=p}),hh=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(o,"__esModule",{value:!0}),o.connectAsync=u;var t=e(vt()),r=e((ch(),Re(El))),i=e(Pi()),n=e(on());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,h]=p;d.username=g,d.password=h}else d.username=d.auth}function c(d,p){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof je<"u"&&(p.socksProxy=je.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=wr().streamBuilder,a.wss=wr().streamBuilder,a.mqtt=Qs().default,a.tcp=Qs().default,a.ssl=Xs().default,a.tls=a.ssl,a.mqtts=Xs().default):(a.ws=wr().browserStreamBuilder,a.wss=wr().browserStreamBuilder,a.wx=Zs().default,a.wxs=Zs().default,a.ali=ea().default,a.alis=ea().default)),!a[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let h=new i.default(g,p);return h.on("error",()=>{}),h}function u(d,p,g=!0){return new Promise((h,b)=>{let y=c(d,p),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}o.default=c}),ta=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=o&&o.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=o&&o.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),i=o&&o.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=o&&o.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=o.KeepaliveManager=o.UniqueMessageIdProvider=o.DefaultMessageIdProvider=o.Store=o.MqttClient=o.connectAsync=o.connect=o.Client=void 0;var s=n(Pi());o.MqttClient=s.default;var a=n(hl());o.DefaultMessageIdProvider=a.default;var l=n(Sd());o.UniqueMessageIdProvider=l.default;var c=n(Ya());o.Store=c.default;var u=r(hh());o.connect=u.default,Object.defineProperty(o,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(vl());o.KeepaliveManager=d.default,o.Client=s.default,i(Pi(),o),i(Zt(),o),i(Ga(),o);var p=rn();Object.defineProperty(o,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),fh=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(s,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=o&&o.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=o&&o.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),i=o&&o.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(o,"__esModule",{value:!0});var n=r(ta());o.default=n,i(ta(),o)});const ph=fh();const mh={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}/#"},gh=300,bh={templateId:"7",type:"link",isDeepLink:!0},yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ql{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={...mh,...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,s)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=ph.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.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={...bh,...this.config.fileTemplate??{},...vh(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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=gh){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??"",d=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:d,raw:i};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,l))}buildOutgoingEnvelope(e,t){const r={...yh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:s}}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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function vh(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(e[t]=r);return e}function Xl(o,e){return(o.sender??"").toString()===e}function Zl(o,e){const t=(o.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 Do(o){const e={raw:o},t=o.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 o.text=="string"&&o.text.trim().startsWith("{"))try{const i=o.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(i);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=o.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 ec(o){const e=Do(o);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,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof i.description=="string"?i.description:void 0,l=o.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function ra(o,e,t){const r=Zl(o,t),i=Do(o),n=ec(o);let s="";i.innerMessage?s=i.innerMessage:typeof o.text=="string"&&(o.text.trim().startsWith("{")?i.contentType!=="300"&&(s=o.text):s=o.text);const a=typeof o.message_id=="string"?o.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof o.timestamp=="number"?new Date(o.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof o.status=="number"?wh(o.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:o.sender,sender_fullname:o.sender_fullname??o.senderFullname,app_id:o.app_id,attributes:o.attributes}};return i.contentType&&(d.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:i}}function wh(o){return o<0?"error":o>=250?"read":o>=150?"delivered":"sent"}class tc extends xo{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 ga(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new ba,this.conversationManager=new va(e.conversationId),this.usesAikaara()&&(this.connection=new ma(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ql({...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(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const i=r.map(l=>ra(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=i.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of i){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}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=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const i=t.conversationId??r;if(!i)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=ra(e,i,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(Xl(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:i,role:s.role==="tool"?"system":s.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",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}}}const na={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 kh(o){const e=o.lastIndexOf(".");return e<0||e===o.length-1?"":o.slice(e+1).toLowerCase()}function xh(o,e,t){const r=kh(o.name||"");if(r&&e&&e[r])return e[r];const i=o.type;return i&&i.trim().length>0?i:r&&na[r]?na[r]:t}function dn(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function _h(o,e){const t=e.split(".");let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function rc(o){const e=o.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=xh(t,o.contentTypeMap,o.contentTypeFallback??"application/octet-stream"),s={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=o.authHeader?await o.authHeader():void 0,l={accept:"application/json",...o.extraHeaders??{},...a?{authorization:a}:{}};let c=o.signEndpoint.includes("{")?o.signEndpoint:`${o.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=dn(c,s),d=await fetch(u,{method:o.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=_h(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=o.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,o.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(o.registerEndpoint){const w=JSON.parse(dn(JSON.stringify(o.registerBody??{}),s)),m=await fetch(o.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:o.viewerTemplate?dn(o.viewerTemplate,s):g.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function $o(o){return{async upload(e,t){const r=new FormData,i=o.fieldName??"file";r.append(i,e,e.name);const n=typeof o.extraFields=="function"?o.extraFields(t):o.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const s=typeof o.headers=="function"?await o.headers():o.headers??{},a=await fetch(o.endpoint,{method:o.method??"POST",body:r,headers:s,credentials:o.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(o.parseResponse)return o.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,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 Sh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function nc(o){const e=o.apiBase.replace(/\/$/,""),t=o.pageSize??200,r=o.pathTemplate??Sh;return{async fetchMessages(i,n){const s=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)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...o.extraHeaders??{}};if(o.getToken){const p=await o.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(o.parseResponse&&u)return o.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Eh="^[A-Z]{4}[0-9]{5}[A-Z]$",Ah="^\\S{12}$",ic="^[A-Z]{4}0[A-Z0-9]{6}$",oc="^[0-9]{6}$",Ih={id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},Th={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:Eh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},Ch={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:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:Ah,maxLength:12}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,uppercase:!0,pattern:ic,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:oc}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"},{id:"us80eeInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},Ph={id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},Oh={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"},Lh={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},Mh={id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureExpenditure",type:"number",label:"Expenditure on Agriculture",currency:"₹",min:0},{id:"agricultureLandGroup",type:"group",title:"Land Details",hint:"Optional - leave blank if you only need to report income",fields:[{id:"agricultureLandInAcre",type:"number",label:"Land Area (Acres)",min:0},{id:"agricultureLandDistrict",type:"text",label:"District"},{id:"agricultureLandPincode",type:"text",label:"Pincode",maxLength:6,pattern:oc},{id:"agricultureLandOwner",type:"radio",label:"Ownership",options:[{value:"Owned",label:"Owned"},{value:"Held on lease",label:"Held on lease"}]},{id:"agricultureLandType",type:"radio",label:"Type of Land",options:[{value:"Irrigated",label:"Irrigated"},{value:"Rain-fed",label:"Rain-fed"}]}]}],submitLabel:"Save"},Nh={id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:ic,maxLength:11}]}],submitLabel:"Save"},Rh=[Th,Lh,Ph,Oh,Ih,Ch,Mh,Nh];function jh(o,e){const t=o||{},r={userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Jh()};r.us80cAmount=_e(t.us80cAmount),r.us80dForSelfAndFamilyAmount=_e(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=_e(t.us80dForParentsAmount),r.hasParentOverSixty=pr(t.hasParentOverSixty),r.preventiveHealthCheckUp=_e(t.preventiveHealthCheckUp),r.medicalExpenditure=_e(t.medicalExpenditure),r.savingBankInterest=_e(t.savingBankInterest),r.fdInterest=_e(t.fdInterest),r.dividend=_e(t.dividend),r.anyOtherIncome=_e(t.anyOtherIncome),r.familyPension=_e(t.familyPension),r.cryptoSellValue=_e(t.cryptoSellPrice),r.cryptoPurchaseAmount=_e(t.cryptoPurchasePrice),r.vdaPurchaseCost=_e(t.cryptoPurchasePrice);const i=(_e(t.bizReceiptsBank)??0)+(_e(t.bizReceiptsCash)??0),n=(_e(t.profReceiptsBank)??0)+(_e(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||i>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?i||void 0:n||void 0,r.agricultureDetails=ac(t),r.exemptIncomeAmount=_e(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),_e(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(_e(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const a={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:_e(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=hn(t.hpDetails,Dh);l.length&&(r.hpDetails=l);const c=hn(t.salaryDetails,$h);if(c.length){r.salaryIncome=c;const u=hn(t.salaryDetails,p=>({grossSalary:_e(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=sn(t.salaryDetails)[0]??{};r.hraAmount=_e(d.hraReceived),r.leaveTravelAllowanceAmount=_e(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=_e(d.leaveEncashment),r.anyOtherAllowanceAmount=_e(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return rt(r)}function Dh(o){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(o.loanTakenFrom),bankOrInstituteName:Ee(o.lenderName),loanAccountNo:Ee(o.loanAccountNumber),loanSanctionDate:Qr(o.sanctionDate),totalLoanAmount:_e(o.totalLoanAmount),loanOutstandingAmount:_e(o.outstandingAmount),interest:_e(o.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Ee(o.typeOfHouseProperty),hasRentalIncome:o.typeOfHouseProperty==="LOP"?!0:pr(o.hasRentalIncome),homeLoanInterest:_e(o.homeLoanInterest),homeLoanPrinciple:_e(o.homeLoanPrinciple),housePropertyAddress:Ee(o.housePropertyAddress),housePropertyPincode:Ee(o.housePropertyPincode),rentalIncome:_e(o.rentalIncome),nameOfTenant:Ee(o.nameOfTenant),propertyTax:_e(o.propertyTax),hasCoOwnedProperty:pr(o.hasCoOwnedProperty),coOwnerName:Ee(o.coOwnerName),coOwnerPan:Ee(o.coOwnerPan),coOwnerShare:Ee(o.coOwnerShare),loanDetails:t?[e]:void 0}}function $h(o){return{grossSalaryIncome:_e(o.grossSalary),salary:_e(o.basicSalary),totalTdsDeposited:_e(o.totalTdsDeposited),employer:{employerName:Ee(o.employerName),employerTan:Ee(o.employerTan)},allowance:{hraAmount:_e(o.hraReceived),leaveTravelAllowanceAmount:_e(o.leaveTravelAllowance),leaveEncashmentAllowanceAmount:_e(o.leaveEncashment),anyOtherAllowanceAmount:_e(o.anyOtherAllowance)}}}function Uh(o,e){const t=[];for(const r of o){const i=Ee(r.employerName),n=Ee(r.employerTan),s=_e(r.grossSalary),a=_e(r.basicSalary),l=_e(r.totalTdsDeposited);i===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:i??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function Bh(o,e){const t=Ee(o.aadhaarNumber),r=Ee(o.bankAccountNumber),i=Ee(o.bankIfscCode);return t===void 0&&r===void 0&&i===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:i}]}}function Fh(o,e){return{userId:nt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:_e(o.savingBankInterest)??0,fdInterest:_e(o.fdInterest)??0,dividend:_e(o.dividend)??0,anyOtherIncome:_e(o.anyOtherIncome)??0,familyPension:_e(o.familyPension)??0}}function qh(o,e){const t=_e(o.cryptoSellPrice),r=_e(o.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Hh(o,e){const t=(i,n,s,a)=>{const l=Ee(o[n]),c=_e(o[s]),u=_e(o[a]);return l===void 0&&c===void 0&&u===void 0?null:{businessType:i,businessCode:l??"",cashAmount:u??0,bankAmount:c??0}},r=[t("BUSINESS","bizNature","bizReceiptsBank","bizReceiptsCash"),t("PROFESSIONAL","profNature","profReceiptsBank","profReceiptsCash")].filter(i=>i!==null);return r.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Wh(o){return Ee(o.lenderName)!==void 0||Ee(o.loanAccountNumber)!==void 0||_e(o.totalLoanAmount)!==void 0||_e(o.outstandingAmount)!==void 0||_e(o.homeLoanInterest)!==void 0}function sc(o){const e=Ee(o.typeOfHouseProperty)?.toUpperCase();return _e(o.rentalIncome)!==void 0||Ee(o.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function zh(o,e){const t=sn(o.hpDetails).filter(Wh).map(r=>{const i=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:Qr(r.sanctionDate),totalLoanAmount:_e(r.totalLoanAmount),loanOutstandingAmount:_e(r.outstandingAmount),interest:_e(r.homeLoanInterest)});return rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:_e(r.homeLoanInterest),homeLoanPrinciple:_e(r.homeLoanPrinciple),propertyTax:_e(r.propertyTax),eligible80EEAAmount:_e(r.eligible80EEAAmount),eligible80EEAmount:_e(r.eligible80EEAmount),hasCoOwnedProperty:pr(r.hasCoOwnedProperty)??!1,hasRentalIncome:sc(r),loanDetails:[i]})});return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Vh(o,e){const t=sn(o.hpDetails).filter(sc).map(r=>rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:_e(r.rentalIncome),propertyTax:_e(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:_e(r.homeLoanInterest)}));return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Kh(o,e){const t=o||{},r=g=>({userId:nt(e.userId),assessmentYear:e.assessmentYear,deductions:rt(g)}),i=[],n=_e(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?i.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const s=Ee(t.us80ccd1bPanNo),a=_e(t.us80ccd1bAmount);a!==void 0&&i.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=_e(t.us80ccd2Amount);l!==void 0&&i.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=_e(t.us80eInterest);c!==void 0&&i.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:Qr(t.us80eLoanSanctionDate),totalLoanAmount:_e(t.us80eLoanAmount),loanOutstandingAmount:_e(t.us80eOutstandingLoan)}));const u=_e(t.us80eeInterest);u!==void 0&&i.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:Qr(t.us80eeLoanSanctionDate),totalLoanAmount:_e(t.us80eeLoanAmount),loanOutstandingAmount:_e(t.us80eeOutstandingLoan),vehicleRegistrationNo:Ee(t.us80eeVehicleRegistrationNumber)}));const d=_e(t.us80dForSelfAndFamilyAmount);d!==void 0&&i.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=_e(t.us80dForParentsAmount);return p!==void 0&&i.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:pr(t.hasParentOverSixty)??!1})),i}function Gh(o,e){const t=o||{},r=_e(t.us80gDonationInCash),i=_e(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&i===void 0&&n===void 0)return null;const s=(i??0)>0;return{userId:nt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:i,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionReferenceNo:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function ac(o){const e=o||{},t=_e(e.agricultureIncome),r=_e(e.agricultureExpenditure),i=rt({landInAcre:_e(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(i).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[i]:void 0})}function Yh(o,e){const t=ac(o);return t?{userId:nt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function nt(o){if(o===void 0||o==="")return;const e=Number(o);return Number.isFinite(e)&&String(e)===String(o)?e:o}function _e(o){if(o==null||o==="")return;const e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:void 0}function Ee(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function pr(o){return o===!0||o===!1?o:void 0}function Jh(){const o=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())}T${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}.${e(o.getMilliseconds(),3)}`}function Qr(o){const e=Ee(o);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function sn(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function hn(o,e){return sn(o).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(o){if(Array.isArray(o)){const e=o.map(rt).filter(t=>t!==void 0);return e.length?e:void 0}if(o&&typeof o=="object"){const e={};for(const[t,r]of Object.entries(o)){const i=rt(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return o}function Qh(o){const e=o&&typeof o=="object"?o:{},t={},r=De(e.employers),i=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(X=>{const z=pn(X.salary),W=pn(X.perquisites),ne=pn(X.profitsInLieuOfSalaryType),D=z+W+ne,G=tf(X.allowance);return{employerName:Ce(X.employerName),employerTan:Ce(X.employerTAN),basicSalary:z||void 0,grossSalary:D||void 0,hraReceived:G.hra,leaveTravelAllowance:G.lta,leaveEncashment:G.leaveEncashment,anyOtherAllowance:G.other,totalTdsDeposited:ef(X,i,r)??Me(X.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(X=>{const z=De(X.loanDetails),W=z.length?z[0]:void 0,ne=Me(X.grossAnnualRentReceived),D=z.length?z.reduce((te,ve)=>te+(Me(ve.interest)??0),0):void 0,G=De(X.tenant),L=De(X.coOwners),Y=G[0],pe=L[0];return{typeOfHouseProperty:Ce(X.propertyType),loanTakenFrom:Ce(W?.loanTakenFrom),lenderName:Ce(W?.bankOrInstituteName),loanAccountNumber:Ce(W?.loanAccountNo),sanctionDate:fn(W?.loanSanctionDate),totalLoanAmount:Me(W?.totalLoanAmount),outstandingAmount:Me(W?.loanOutstandingAmount),homeLoanInterest:D,homeLoanPrinciple:void 0,housePropertyAddress:Ce(X.address),housePropertyPincode:Ce(X.pinCode),rentalIncome:ne,nameOfTenant:Ce(Y?.name),tenantPanNumber:Ce(Y?.panNumber),eligible80EEAmount:Me(X.eligible80EEAmount),eligible80EEAAmount:Me(X.eligible80EEAAmount),propertyTax:Me(X.propertyTax),hasCoOwnedProperty:L.length>0,coOwnerName:Ce(pe?.name),coOwnerPan:Ce(pe?.panNumber),coOwnerShare:Me(pe?.share)?.toString()}}));const s=De(e.deductionUS80CDetails),a=At(s.map(X=>Me(X.amount))),l=s.find(X=>Ce(X.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=De(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=De(e.deductionUS80DDetails),p=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS"),h=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Me(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??h?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??h?.accountNo),t.us80dForParentsAmount=Me(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??b?.accountNo),t.hasParentOverSixty=rf(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=De(e.donations)[0];t.us80gDonationInCash=Me(w?.amountInCash??w?.donationInCash),t.us80gDonationOnline=Me(w?.amountOtherThanCash??w?.amount??w?.donationAmount),t.us80gNameOfCharity=Ce(w?.nameOfCharity??w?.donorName??w?.trustName),t.us80gCharityPan=Ce(w?.panNumber??w?.charityPan),t.us80gTrustAddress=Ce(w?.address??w?.charityAddress),t.us80gPincode=Ce(w?.pinCode??w?.pincode),t.us80gTransactionRefNo=Ce(w?.transactionReferenceNo??w?.transactionRefNo),t.us80gIfscCode=Ce(w?.ifscCode??w?.ifsCode);const m=De(e.loanDetails),k=X=>m.find(z=>Ce(z.loanType)?.toUpperCase()===X),_=k("EDUCATION"),v=k("ELECTRIC_VEHICLE");t.us80eLoanTakenFrom=Ce(_?.loanTakenFrom),t.us80eBankName=Ce(_?.bankOrInstituteName),t.us80eLoanAccountNumber=Ce(_?.loanAccountNo),t.us80eLoanSanctionDate=fn(_?.loanSanctionDate),t.us80eLoanAmount=Me(_?.totalLoanAmount),t.us80eOutstandingLoan=Me(_?.loanOutstandingAmount),t.us80eInterest=Me(_?.interest),t.us80eeLoanTakenFrom=Ce(v?.loanTakenFrom),t.us80eeBankName=Ce(v?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(v?.loanAccountNo),t.us80eeLoanSanctionDate=fn(v?.loanSanctionDate),t.us80eeLoanAmount=Me(v?.totalLoanAmount),t.us80eeOutstandingLoan=Me(v?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(v?.vehicleRegistrationNo),t.us80eeInterest=Me(v?.interest);const E=De(e.insurances);t.preventiveHealthCheckUp=At(E.map(X=>Me(X.preventiveCheckUp))),t.medicalExpenditure=At(E.map(X=>Me(X.medicalExpenditure)));const S=De(e.incomes),I=X=>At(S.filter(z=>Ce(z.incomeType)===X).map(z=>Me(z.amount)));t.savingBankInterest=I("SAVING_INTEREST"),t.fdInterest=I("FD_RD_INTEREST"),t.anyOtherIncome=I("ANY_OTHER"),t.familyPension=I("FAMILY_PENSION"),t.dividend=At(De(e.dividendIncomes).map(X=>Me(X.income)));const P=e.business;if(P){const X=De(P.presumptiveIncomes),z=D=>{const G=Ce(D.businessType)?.trim().toUpperCase()??"";if(G.includes("PROFESSION")||G==="44ADA")return!0;if(G.includes("BUSINESS")||G==="44AD"||G==="PRESUMPTIVE")return!1;const L=De(D.incomes),Y=pe=>Me(L.find(te=>Ce(te.incomeType)===pe)?.receipts)??0;return Y("ANY_OTHER")>0?!0:(Y("BANK")>0||Y("CASH")>0,!1)},W=D=>X.find(G=>z(G)===D),ne=(D,G)=>{if(!D)return;const L=De(D.incomes),Y=te=>Me(L.find(ve=>Ce(ve.incomeType)===te)?.receipts),pe=Y("BANK")||Y("ANY_OTHER");t[G.nature]=Ce(D.natureOfBusiness),t[G.bank]=pe||void 0,t[G.cash]=Y("CASH")||void 0,t[G.net]=At(L.map(te=>Me(te.presumptiveIncome)))||void 0};ne(W(!1),{nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),ne(W(!0),{nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const O=De(e.capitalGain).filter(X=>Ce(X.assetType)?.toUpperCase()==="VDA").flatMap(X=>De(X.assetDetails));O.length&&(t.cryptoSellPrice=At(O.map(X=>Me(X.sellValue))),t.cryptoPurchasePrice=At(O.map(X=>Me(X.purchaseCost))));const j=e.agriculturalDetails,T=e.agriculturalIncome;t.agricultureIncome=Me(T?.netAgriculturalIncome)??Me(T?.grossAgriculturalReceipts)??Me(j?.income),t.agricultureExpenditure=Me(T?.expenditureIncurredOnAgriculture)??Me(j?.expenditure);const $=De(j?.agricultureLandDetails??j?.agriculturalLandDetails??e.agriculturalLandDetails)[0];$&&(t.agricultureLandInAcre=Me($.landInAcre),t.agricultureLandDistrict=Ce($.nameOfDistrict),t.agricultureLandPincode=Ce($.pinCode),t.agricultureLandOwner=Xh($.owner),t.agricultureLandType=Zh($.typeOfLand)),t.aadhaarNumber=Ce(e.aadharNumber);const U=De(e.bankDetails)[0];return U&&(t.bankAccountNumber=Ce(U.accountNumber),t.bankIfscCode=Ce(U.ifsCode)),lc(t)}function Xh(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function Zh(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function fn(o){const e=Ce(o);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function pn(o){return De(o).reduce((e,t)=>e+(Me(t.taxableAmount)??0),0)}function ef(o,e,t){if(!e.length)return;const r=Ce(o.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Me(n.totalTdsDeposited)}const i=Ce(o.employerName)?.trim().toLowerCase();if(i){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===i)return Me(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Me(e[0].totalTdsDeposited)}function tf(o){const e=De(o);if(!e.length)return{};let t,r,i,n;for(const s of e){const a=Me(s.exemptAmount)??Me(s.allowanceAmount);switch(Ce(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":i=a;break;default:n=(n??0)+(Me(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:i,other:n}}function At(o){let e=0,t=!1;for(const r of o)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function Me(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""&&Number.isFinite(Number(o)))return Number(o)}function Ce(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function rf(o){if(typeof o=="boolean")return o;if(typeof o=="string"){const e=o.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof o=="number")return o===1?!0:o===0?!1:void 0}function lc(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(Array.isArray(r)?e[t]=r.map(i=>i&&typeof i=="object"?lc(i):i):e[t]=r);return e}function mn(){if(typeof window>"u")return null;const o=window,e=o.__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=o.__aikaara_descriptor__??{},r=pf(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const i=mf(e.slug),n=typeof i?.tenantJwt=="string"?i.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(i&&i.userId!=null&&i.userId!==""?String(i.userId):bf(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:gf(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||yf(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function nf(o){const e=await o.getToken(),t=o.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${o.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...o.headers}});if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${i.slice(0,200)}`)}return Qh(Uo(await r.json().catch(()=>({}))))}async function of(o,e){const t=await o.getToken(),r=o.userId,i={...jh(e,{userId:r,assessmentYear:o.assessmentYear,isRevised:o.isRevised}),sendSummary:!0},n=o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...o.headers};o.txbdyApiKey&&(s["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(i)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Uo(await a.json().catch(()=>({})))}async function sf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/salary`,e)}async function af(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function ia(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function lf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function cf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function uf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/deductions`,e)}async function df(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function hf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/hp-income`,e)}async function ff(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/vda`,e)}async function _t(o,e,t){const i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await o.getToken()}`,...o.headers};o.txbdyApiKey&&(i["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:i,body:JSON.stringify(t)});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Uo(await n.json().catch(()=>({})))}function pf(o){const e=[o.cloud?.listEndpoint,o.cloud?.downloadEndpoint,o.upload?.signEndpoint,o.login?.pan?.basicPanEndpoint,o.login?.pan?.panDetailEndpoint,o.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function mf(o){if(!o||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${o}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function gf(o){const e={};if(!o)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(o))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function bf(o){if(!o)return;const e=o.userId??o.id??o.ext_uid??o.extUid;return e==null||e===""?void 0:String(e)}function Uo(o){if(o&&typeof o=="object"){const e=o;return e.data&&typeof e.data=="object"?e.data:e}return{}}function yf(){const o=new Date,e=o.getMonth()>=3?o.getFullYear():o.getFullYear()-1;return`${e}-${e+1}`}const vf=["No, I have a concerns"];class wf{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new tc(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.shouldOpenSmartEdit(t.text),i=this.client.config.templateActionAttributes??{},n=t.attributes?.action??{},s={...t.attributes,action:{...i,...n}};this.handleSend(t.text,s).then(()=>{r&&this.openSmartEdit()})})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages,r=Array.isArray(t)?t:vf;if(!Array.isArray(r)||r.length===0)return!1;const i=s=>s.trim().toLowerCase(),n=i(e);return r.some(s=>typeof s=="string"&&i(s)===n)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Rh,data:{}});const t=mn();if(!(!t||!t.baseUrl))try{const r=await nf(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=mn();if(!r)return;const i={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=Uh(n,i);s&&await sf(r,s)}else if(e==="bank-details"){const n=Bh(t,i);n&&await af(r,n)}else if(e==="other-sources")await ia(r,Fh(t,i));else if(e==="business-profession"){const n=Hh(t,i);n&&await lf(r,n)}else if(e==="crypto-income"){const n=qh(t,i);n&&await ff(r,n)}else if(e==="agricultural-income"){const n=Yh(t,i);n&&await cf(r,n)}else if(e==="deductions"){for(const s of Kh(t,i))await uf(r,s);const n=Gh(t,i);n&&await ia(r,n)}else if(e==="house-property"){const n=zh(t,i);n&&await df(r,n);const s=Vh(t,i);s&&await hf(r,s)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=mn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await of(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 cc 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||ou,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||qo,position:this.getAttribute("position")||this._config.position||iu,width:Number(this.getAttribute("width"))||this._config.width||eu,height:Number(this.getAttribute("height"))||this._config.height||tu,fontFamily:this._config.fontFamily||nu,borderRadius:this._config.borderRadius??ru,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ho,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||su,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,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??i),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("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(Hl,"%0A")),e.includes("\r")&&(e=e.replace(Wl,"%0D")),e.includes(" ")&&(e=e.replace(zl,"%09")),r.pathname=e,r}var Cl,Br,uo,Fr,qr,ho,Hr,fo,Wr,po,zr,mo,Vr,go,Kr,bo,Ct,yo,Ke,Js,Pl,Ol,Ll,Ml,Nl,Rl,jl,Dl,$l,Ul,Jr,Bl,Fl,ql,Hl,Wl,zl,ch=Qe(()=>{le(),ue(),ce(),Ad(),qd(),eh(),Sl(),Cl=Object.freeze(Object.create(null)),Br={},uo=!1,Fr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,qr={},ho=!1,Hr={},fo=!1,Wr={},po=!1,zr={},mo=!1,Vr={},go=!1,Kr={},bo=!1,Ct={},yo=!1,Ke=sh(),Ke.parse,Ke.resolve,Ke.resolveObject,Ke.format,Ke.Url,Js=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ke.URL=typeof URL<"u"?URL:null,Ke.pathToFileURL=Tl,Ke.fileURLToPath=Il,Pl=Ke.Url,Ol=Ke.format,Ll=Ke.resolve,Ml=Ke.resolveObject,Nl=Ke.parse,Rl=Ke.URL,jl=92,Dl=47,$l=97,Ul=122,Jr=Js==="win32",Bl=/\//g,Fl=/%/g,ql=/\\/g,Hl=/\n/g,Wl=/\r/g,zl=/\t/g}),uh=me((o,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")}}),Ro=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.BufferedDuplex=void 0,o.writev=r;var e=Ft(),t=(qe(),Re(Fe));function r(n,s){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",s)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};o.BufferedDuplex=i}),wr=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(o,"__esModule",{value:!0}),o.streamBuilder=o.browserStreamBuilder=void 0;var t=(qe(),Re(Fe)),r=e(uh()),i=e(vt()),n=Ft(),s=e(on()),a=Ro(),l=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function p(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let _=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${_}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[_],k):v=new r.default(m,[_],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",_=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(_,[k],m):v=new WebSocket(_,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let _=u(k,w),v=g(w,_,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=_,v.on("close",()=>{E.destroy()}),E};o.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,_=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,X);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=I,k.socket=S):(k=new a.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",F),S.addEventListener("message",$)):(S.onclose=T,S.onerror=F,S.onmessage=$);function O(z,W,ne){let D=new n.Transform({objectMode:z.objectMode});return D._write=W,D._flush=ne,D}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(z){l("WebSocket onClose",z),k.end(),k.destroy()}function F(z){l("WebSocket onError",z);let W=new Error("WebSocket error");W.event=z,k.destroy(W)}async function $(z){if(!I||!I.readable||!I.writable)return;let{data:W}=z;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function U(z,W,ne){if(S.bufferedAmount>_){setTimeout(U,v,z,W,ne);return}E&&typeof z=="string"&&(z=t.Buffer.from(z,"utf8"));try{S.send(z)}catch(D){return ne(D)}ne()}function X(z){S.close(),z()}return k};o.browserStreamBuilder=y}),jo={};Qt(jo,{Server:()=>$e,Socket:()=>$e,Stream:()=>$e,_createServerHandle:()=>$e,_normalizeArgs:()=>$e,_setSimultaneousAccepts:()=>$e,connect:()=>$e,createConnection:()=>$e,createServer:()=>$e,default:()=>Vl,isIP:()=>$e,isIPv4:()=>$e,isIPv6:()=>$e});function $e(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Vl,Kl=Qe(()=>{le(),ue(),ce(),Vl={_createServerHandle:$e,_normalizeArgs:$e,_setSimultaneousAccepts:$e,connect:$e,createConnection:$e,createServer:$e,isIP:$e,isIPv4:$e,isIPv6:$e,Server:$e,Socket:$e,Stream:$e}}),Gl=me((o,e)=>{le(),ue(),ce(),e.exports={}}),Qs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0});var t=e((Kl(),Re(jo))),r=e(vt()),i=e(Gl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,i.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};o.default=s}),Yl={};Qt(Yl,{default:()=>Jl});var Jl,dh=Qe(()=>{le(),ue(),ce(),Jl={}}),Xs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(o,"__esModule",{value:!0});var t=(dh(),Re(Yl)),r=e((Kl(),Re(jo))),i=e(vt()),n=e(Gl()),s=(0,i.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let h=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,s("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};o.default=l}),Zs=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s;function a(){let p=new t.Transform;return p._write=(g,h,b)=>{i.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{i.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let h=p.protocol==="wxs"?"wss":"ws",b=`${h}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${h}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){i.onOpen(()=>{s.socketReady()}),i.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),i.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),i.onError(p=>{let g=new Error(p.errMsg);s.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);i=wx.connectSocket({url:b,protocols:[h]}),n=a(),s=new r.BufferedDuplex(g,n,i),s._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{i.close({fail(){s._destroy(w,m)}})},0),s),u(),s};o.default=d}),ea=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{i.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{i.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,i.onSocketOpen(()=>{s.socketReady()}),i.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),i.onSocketClose(()=>{s.end(),s.destroy()}),i.onSocketError(g=>{s.destroy(g)}))}var p=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return i=h.my,i.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(h,n,i),d(),s};o.default=p}),hh=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(o,"__esModule",{value:!0}),o.connectAsync=u;var t=e(vt()),r=e((ch(),Re(El))),i=e(Pi()),n=e(on());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,h]=p;d.username=g,d.password=h}else d.username=d.auth}function c(d,p){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof je<"u"&&(p.socksProxy=je.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=wr().streamBuilder,a.wss=wr().streamBuilder,a.mqtt=Qs().default,a.tcp=Qs().default,a.ssl=Xs().default,a.tls=a.ssl,a.mqtts=Xs().default):(a.ws=wr().browserStreamBuilder,a.wss=wr().browserStreamBuilder,a.wx=Zs().default,a.wxs=Zs().default,a.ali=ea().default,a.alis=ea().default)),!a[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let h=new i.default(g,p);return h.on("error",()=>{}),h}function u(d,p,g=!0){return new Promise((h,b)=>{let y=c(d,p),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}o.default=c}),ta=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=o&&o.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=o&&o.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),i=o&&o.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=o&&o.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=o.KeepaliveManager=o.UniqueMessageIdProvider=o.DefaultMessageIdProvider=o.Store=o.MqttClient=o.connectAsync=o.connect=o.Client=void 0;var s=n(Pi());o.MqttClient=s.default;var a=n(hl());o.DefaultMessageIdProvider=a.default;var l=n(Sd());o.UniqueMessageIdProvider=l.default;var c=n(Ya());o.Store=c.default;var u=r(hh());o.connect=u.default,Object.defineProperty(o,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(vl());o.KeepaliveManager=d.default,o.Client=s.default,i(Pi(),o),i(Zt(),o),i(Ga(),o);var p=rn();Object.defineProperty(o,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),fh=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(s,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=o&&o.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=o&&o.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),i=o&&o.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(o,"__esModule",{value:!0});var n=r(ta());o.default=n,i(ta(),o)});const ph=fh();const mh={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}/#"},gh=300,bh={templateId:"7",type:"link",isDeepLink:!0},yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ql{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={...mh,...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,s)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=ph.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.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={...bh,...this.config.fileTemplate??{},...vh(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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=gh){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??"",d=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:d,raw:i};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,l))}buildOutgoingEnvelope(e,t){const r={...yh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:s}}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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function vh(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(e[t]=r);return e}function Xl(o,e){return(o.sender??"").toString()===e}function Zl(o,e){const t=(o.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 Do(o){const e={raw:o},t=o.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 o.text=="string"&&o.text.trim().startsWith("{"))try{const i=o.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(i);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=o.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 ec(o){const e=Do(o);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,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof i.description=="string"?i.description:void 0,l=o.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function ra(o,e,t){const r=Zl(o,t),i=Do(o),n=ec(o);let s="";i.innerMessage?s=i.innerMessage:typeof o.text=="string"&&(o.text.trim().startsWith("{")?i.contentType!=="300"&&(s=o.text):s=o.text);const a=typeof o.message_id=="string"?o.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof o.timestamp=="number"?new Date(o.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof o.status=="number"?wh(o.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:o.sender,sender_fullname:o.sender_fullname??o.senderFullname,app_id:o.app_id,attributes:o.attributes}};return i.contentType&&(d.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:i}}function wh(o){return o<0?"error":o>=250?"read":o>=150?"delivered":"sent"}class tc extends xo{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 ga(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new ba,this.conversationManager=new va(e.conversationId),this.usesAikaara()&&(this.connection=new ma(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ql({...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(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const i=r.map(l=>ra(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=i.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of i){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}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=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const i=t.conversationId??r;if(!i)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=ra(e,i,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(Xl(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:i,role:s.role==="tool"?"system":s.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",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}}}const na={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 kh(o){const e=o.lastIndexOf(".");return e<0||e===o.length-1?"":o.slice(e+1).toLowerCase()}function xh(o,e,t){const r=kh(o.name||"");if(r&&e&&e[r])return e[r];const i=o.type;return i&&i.trim().length>0?i:r&&na[r]?na[r]:t}function dn(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function _h(o,e){const t=e.split(".");let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function rc(o){const e=o.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=xh(t,o.contentTypeMap,o.contentTypeFallback??"application/octet-stream"),s={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=o.authHeader?await o.authHeader():void 0,l={accept:"application/json",...o.extraHeaders??{},...a?{authorization:a}:{}};let c=o.signEndpoint.includes("{")?o.signEndpoint:`${o.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=dn(c,s),d=await fetch(u,{method:o.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=_h(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=o.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,o.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(o.registerEndpoint){const w=JSON.parse(dn(JSON.stringify(o.registerBody??{}),s)),m=await fetch(o.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:o.viewerTemplate?dn(o.viewerTemplate,s):g.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function $o(o){return{async upload(e,t){const r=new FormData,i=o.fieldName??"file";r.append(i,e,e.name);const n=typeof o.extraFields=="function"?o.extraFields(t):o.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const s=typeof o.headers=="function"?await o.headers():o.headers??{},a=await fetch(o.endpoint,{method:o.method??"POST",body:r,headers:s,credentials:o.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(o.parseResponse)return o.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,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 Sh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function nc(o){const e=o.apiBase.replace(/\/$/,""),t=o.pageSize??200,r=o.pathTemplate??Sh;return{async fetchMessages(i,n){const s=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)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...o.extraHeaders??{}};if(o.getToken){const p=await o.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(o.parseResponse&&u)return o.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Eh="^[A-Z]{4}[0-9]{5}[A-Z]$",Ah="^\\S{12}$",ic="^[A-Z]{4}0[A-Z0-9]{6}$",oc="^[0-9]{6}$",Ih={id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},Th={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:Eh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},Ch={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:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:Ah,maxLength:12}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,uppercase:!0,pattern:ic,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:oc}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"},{id:"us80eeInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},Ph={id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},Oh={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"},Lh={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},Mh={id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureExpenditure",type:"number",label:"Expenditure on Agriculture",currency:"₹",min:0},{id:"agricultureLandGroup",type:"group",title:"Land Details",hint:"Optional - leave blank if you only need to report income",fields:[{id:"agricultureLandInAcre",type:"number",label:"Land Area (Acres)",min:0},{id:"agricultureLandDistrict",type:"text",label:"District"},{id:"agricultureLandPincode",type:"text",label:"Pincode",maxLength:6,pattern:oc},{id:"agricultureLandOwner",type:"radio",label:"Ownership",options:[{value:"Owned",label:"Owned"},{value:"Held on lease",label:"Held on lease"}]},{id:"agricultureLandType",type:"radio",label:"Type of Land",options:[{value:"Irrigated",label:"Irrigated"},{value:"Rain-fed",label:"Rain-fed"}]}]}],submitLabel:"Save"},Nh={id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:ic,maxLength:11}]}],submitLabel:"Save"},Rh=[Th,Lh,Ph,Oh,Ih,Ch,Mh,Nh];function jh(o,e){const t=o||{},r={userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Jh()};r.us80cAmount=_e(t.us80cAmount),r.us80dForSelfAndFamilyAmount=_e(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=_e(t.us80dForParentsAmount),r.hasParentOverSixty=pr(t.hasParentOverSixty),r.preventiveHealthCheckUp=_e(t.preventiveHealthCheckUp),r.medicalExpenditure=_e(t.medicalExpenditure),r.savingBankInterest=_e(t.savingBankInterest),r.fdInterest=_e(t.fdInterest),r.dividend=_e(t.dividend),r.anyOtherIncome=_e(t.anyOtherIncome),r.familyPension=_e(t.familyPension),r.cryptoSellValue=_e(t.cryptoSellPrice),r.cryptoPurchaseAmount=_e(t.cryptoPurchasePrice),r.vdaPurchaseCost=_e(t.cryptoPurchasePrice);const i=(_e(t.bizReceiptsBank)??0)+(_e(t.bizReceiptsCash)??0),n=(_e(t.profReceiptsBank)??0)+(_e(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||i>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?i||void 0:n||void 0,r.agricultureDetails=ac(t),r.exemptIncomeAmount=_e(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),_e(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(_e(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const a={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:_e(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=hn(t.hpDetails,Dh);l.length&&(r.hpDetails=l);const c=hn(t.salaryDetails,$h);if(c.length){r.salaryIncome=c;const u=hn(t.salaryDetails,p=>({grossSalary:_e(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=sn(t.salaryDetails)[0]??{};r.hraAmount=_e(d.hraReceived),r.leaveTravelAllowanceAmount=_e(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=_e(d.leaveEncashment),r.anyOtherAllowanceAmount=_e(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return rt(r)}function Dh(o){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(o.loanTakenFrom),bankOrInstituteName:Ee(o.lenderName),loanAccountNo:Ee(o.loanAccountNumber),loanSanctionDate:Qr(o.sanctionDate),totalLoanAmount:_e(o.totalLoanAmount),loanOutstandingAmount:_e(o.outstandingAmount),interest:_e(o.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Ee(o.typeOfHouseProperty),hasRentalIncome:o.typeOfHouseProperty==="LOP"?!0:pr(o.hasRentalIncome),homeLoanInterest:_e(o.homeLoanInterest),homeLoanPrinciple:_e(o.homeLoanPrinciple),housePropertyAddress:Ee(o.housePropertyAddress),housePropertyPincode:Ee(o.housePropertyPincode),rentalIncome:_e(o.rentalIncome),nameOfTenant:Ee(o.nameOfTenant),propertyTax:_e(o.propertyTax),hasCoOwnedProperty:pr(o.hasCoOwnedProperty),coOwnerName:Ee(o.coOwnerName),coOwnerPan:Ee(o.coOwnerPan),coOwnerShare:Ee(o.coOwnerShare),loanDetails:t?[e]:void 0}}function $h(o){return{grossSalaryIncome:_e(o.grossSalary),salary:_e(o.basicSalary),totalTdsDeposited:_e(o.totalTdsDeposited),employer:{employerName:Ee(o.employerName),employerTan:Ee(o.employerTan)},allowance:{hraAmount:_e(o.hraReceived),leaveTravelAllowanceAmount:_e(o.leaveTravelAllowance),leaveEncashmentAllowanceAmount:_e(o.leaveEncashment),anyOtherAllowanceAmount:_e(o.anyOtherAllowance)}}}function Uh(o,e){const t=[];for(const r of o){const i=Ee(r.employerName),n=Ee(r.employerTan),s=_e(r.grossSalary),a=_e(r.basicSalary),l=_e(r.totalTdsDeposited);i===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:i??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function Bh(o,e){const t=Ee(o.aadhaarNumber),r=Ee(o.bankAccountNumber),i=Ee(o.bankIfscCode);return t===void 0&&r===void 0&&i===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:i}]}}function Fh(o,e){return{userId:nt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:_e(o.savingBankInterest)??0,fdInterest:_e(o.fdInterest)??0,dividend:_e(o.dividend)??0,anyOtherIncome:_e(o.anyOtherIncome)??0,familyPension:_e(o.familyPension)??0}}function qh(o,e){const t=_e(o.cryptoSellPrice),r=_e(o.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Hh(o,e){const t=(i,n,s,a)=>{const l=Ee(o[n]),c=_e(o[s]),u=_e(o[a]);return l===void 0&&c===void 0&&u===void 0?null:{businessType:i,businessCode:l??"",cashAmount:u??0,bankAmount:c??0}},r=[t("BUSINESS","bizNature","bizReceiptsBank","bizReceiptsCash"),t("PROFESSIONAL","profNature","profReceiptsBank","profReceiptsCash")].filter(i=>i!==null);return r.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Wh(o){return Ee(o.lenderName)!==void 0||Ee(o.loanAccountNumber)!==void 0||_e(o.totalLoanAmount)!==void 0||_e(o.outstandingAmount)!==void 0||_e(o.homeLoanInterest)!==void 0}function sc(o){const e=Ee(o.typeOfHouseProperty)?.toUpperCase();return _e(o.rentalIncome)!==void 0||Ee(o.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function zh(o,e){const t=sn(o.hpDetails).filter(Wh).map(r=>{const i=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:Qr(r.sanctionDate),totalLoanAmount:_e(r.totalLoanAmount),loanOutstandingAmount:_e(r.outstandingAmount),interest:_e(r.homeLoanInterest)});return rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:_e(r.homeLoanInterest),homeLoanPrinciple:_e(r.homeLoanPrinciple),propertyTax:_e(r.propertyTax),eligible80EEAAmount:_e(r.eligible80EEAAmount),eligible80EEAmount:_e(r.eligible80EEAmount),hasCoOwnedProperty:pr(r.hasCoOwnedProperty)??!1,hasRentalIncome:sc(r),loanDetails:[i]})});return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Vh(o,e){const t=sn(o.hpDetails).filter(sc).map(r=>rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:_e(r.rentalIncome),propertyTax:_e(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:_e(r.homeLoanInterest)}));return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Kh(o,e){const t=o||{},r=g=>({userId:nt(e.userId),assessmentYear:e.assessmentYear,deductions:rt(g)}),i=[],n=_e(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?i.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const s=Ee(t.us80ccd1bPanNo),a=_e(t.us80ccd1bAmount);a!==void 0&&i.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=_e(t.us80ccd2Amount);l!==void 0&&i.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=_e(t.us80eInterest);c!==void 0&&i.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:Qr(t.us80eLoanSanctionDate),totalLoanAmount:_e(t.us80eLoanAmount),loanOutstandingAmount:_e(t.us80eOutstandingLoan)}));const u=_e(t.us80eeInterest);u!==void 0&&i.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:Qr(t.us80eeLoanSanctionDate),totalLoanAmount:_e(t.us80eeLoanAmount),loanOutstandingAmount:_e(t.us80eeOutstandingLoan),vehicleRegistrationNo:Ee(t.us80eeVehicleRegistrationNumber)}));const d=_e(t.us80dForSelfAndFamilyAmount);d!==void 0&&i.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=_e(t.us80dForParentsAmount);return p!==void 0&&i.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:pr(t.hasParentOverSixty)??!1})),i}function Gh(o,e){const t=o||{},r=_e(t.us80gDonationInCash),i=_e(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&i===void 0&&n===void 0)return null;const s=(i??0)>0;return{userId:nt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:i,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionRefNum:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function ac(o){const e=o||{},t=_e(e.agricultureIncome),r=_e(e.agricultureExpenditure),i=rt({landInAcre:_e(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(i).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[i]:void 0})}function Yh(o,e){const t=ac(o);return t?{userId:nt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function nt(o){if(o===void 0||o==="")return;const e=Number(o);return Number.isFinite(e)&&String(e)===String(o)?e:o}function _e(o){if(o==null||o==="")return;const e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:void 0}function Ee(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function pr(o){return o===!0||o===!1?o:void 0}function Jh(){const o=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())}T${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}.${e(o.getMilliseconds(),3)}`}function Qr(o){const e=Ee(o);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function sn(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function hn(o,e){return sn(o).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(o){if(Array.isArray(o)){const e=o.map(rt).filter(t=>t!==void 0);return e.length?e:void 0}if(o&&typeof o=="object"){const e={};for(const[t,r]of Object.entries(o)){const i=rt(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return o}function Qh(o){const e=o&&typeof o=="object"?o:{},t={},r=De(e.employers),i=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(X=>{const z=pn(X.salary),W=pn(X.perquisites),ne=pn(X.profitsInLieuOfSalaryType),D=z+W+ne,G=tf(X.allowance);return{employerName:Ce(X.employerName),employerTan:Ce(X.employerTAN),basicSalary:z||void 0,grossSalary:D||void 0,hraReceived:G.hra,leaveTravelAllowance:G.lta,leaveEncashment:G.leaveEncashment,anyOtherAllowance:G.other,totalTdsDeposited:ef(X,i,r)??Me(X.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(X=>{const z=De(X.loanDetails),W=z.length?z[0]:void 0,ne=Me(X.grossAnnualRentReceived),D=z.length?z.reduce((te,ve)=>te+(Me(ve.interest)??0),0):void 0,G=De(X.tenant),L=De(X.coOwners),Y=G[0],pe=L[0];return{typeOfHouseProperty:Ce(X.propertyType),loanTakenFrom:Ce(W?.loanTakenFrom),lenderName:Ce(W?.bankOrInstituteName),loanAccountNumber:Ce(W?.loanAccountNo),sanctionDate:fn(W?.loanSanctionDate),totalLoanAmount:Me(W?.totalLoanAmount),outstandingAmount:Me(W?.loanOutstandingAmount),homeLoanInterest:D,homeLoanPrinciple:void 0,housePropertyAddress:Ce(X.address),housePropertyPincode:Ce(X.pinCode),rentalIncome:ne,nameOfTenant:Ce(Y?.name),tenantPanNumber:Ce(Y?.panNumber),eligible80EEAmount:Me(X.eligible80EEAmount),eligible80EEAAmount:Me(X.eligible80EEAAmount),propertyTax:Me(X.propertyTax),hasCoOwnedProperty:L.length>0,coOwnerName:Ce(pe?.name),coOwnerPan:Ce(pe?.panNumber),coOwnerShare:Me(pe?.share)?.toString()}}));const s=De(e.deductionUS80CDetails),a=At(s.map(X=>Me(X.amount))),l=s.find(X=>Ce(X.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=De(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=De(e.deductionUS80DDetails),p=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS"),h=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Me(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??h?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??h?.accountNo),t.us80dForParentsAmount=Me(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??b?.accountNo),t.hasParentOverSixty=rf(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=De(e.donations)[0];t.us80gDonationInCash=Me(w?.amountInCash??w?.donationInCash),t.us80gDonationOnline=Me(w?.amountOtherThanCash??w?.amount??w?.donationAmount),t.us80gNameOfCharity=Ce(w?.nameOfCharity??w?.donorName??w?.trustName),t.us80gCharityPan=Ce(w?.panNumber??w?.charityPan),t.us80gTrustAddress=Ce(w?.address??w?.charityAddress),t.us80gPincode=Ce(w?.pinCode??w?.pincode),t.us80gTransactionRefNo=Ce(w?.transactionRefNum??w?.transactionReferenceNo??w?.transactionRefNo),t.us80gIfscCode=Ce(w?.ifscCode??w?.ifsCode);const m=De(e.loanDetails),k=X=>m.find(z=>Ce(z.loanType)?.toUpperCase()===X),_=k("EDUCATION"),v=k("ELECTRIC_VEHICLE");t.us80eLoanTakenFrom=Ce(_?.loanTakenFrom),t.us80eBankName=Ce(_?.bankOrInstituteName),t.us80eLoanAccountNumber=Ce(_?.loanAccountNo),t.us80eLoanSanctionDate=fn(_?.loanSanctionDate),t.us80eLoanAmount=Me(_?.totalLoanAmount),t.us80eOutstandingLoan=Me(_?.loanOutstandingAmount),t.us80eInterest=Me(_?.interest),t.us80eeLoanTakenFrom=Ce(v?.loanTakenFrom),t.us80eeBankName=Ce(v?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(v?.loanAccountNo),t.us80eeLoanSanctionDate=fn(v?.loanSanctionDate),t.us80eeLoanAmount=Me(v?.totalLoanAmount),t.us80eeOutstandingLoan=Me(v?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(v?.vehicleRegistrationNo),t.us80eeInterest=Me(v?.interest);const E=De(e.insurances);t.preventiveHealthCheckUp=At(E.map(X=>Me(X.preventiveCheckUp))),t.medicalExpenditure=At(E.map(X=>Me(X.medicalExpenditure)));const S=De(e.incomes),I=X=>At(S.filter(z=>Ce(z.incomeType)===X).map(z=>Me(z.amount)));t.savingBankInterest=I("SAVING_INTEREST"),t.fdInterest=I("FD_RD_INTEREST"),t.anyOtherIncome=I("ANY_OTHER"),t.familyPension=I("FAMILY_PENSION"),t.dividend=At(De(e.dividendIncomes).map(X=>Me(X.income)));const P=e.business;if(P){const X=De(P.presumptiveIncomes),z=D=>{const G=Ce(D.businessType)?.trim().toUpperCase()??"";if(G.includes("PROFESSION")||G==="44ADA")return!0;if(G.includes("BUSINESS")||G==="44AD"||G==="PRESUMPTIVE")return!1;const L=De(D.incomes),Y=pe=>Me(L.find(te=>Ce(te.incomeType)===pe)?.receipts)??0;return Y("ANY_OTHER")>0?!0:(Y("BANK")>0||Y("CASH")>0,!1)},W=D=>X.find(G=>z(G)===D),ne=(D,G)=>{if(!D)return;const L=De(D.incomes),Y=te=>Me(L.find(ve=>Ce(ve.incomeType)===te)?.receipts),pe=Y("BANK")||Y("ANY_OTHER");t[G.nature]=Ce(D.natureOfBusiness),t[G.bank]=pe||void 0,t[G.cash]=Y("CASH")||void 0,t[G.net]=At(L.map(te=>Me(te.presumptiveIncome)))||void 0};ne(W(!1),{nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),ne(W(!0),{nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const O=De(e.capitalGain).filter(X=>Ce(X.assetType)?.toUpperCase()==="VDA").flatMap(X=>De(X.assetDetails));O.length&&(t.cryptoSellPrice=At(O.map(X=>Me(X.sellValue))),t.cryptoPurchasePrice=At(O.map(X=>Me(X.purchaseCost))));const j=e.agriculturalDetails,T=e.agriculturalIncome;t.agricultureIncome=Me(T?.netAgriculturalIncome)??Me(T?.grossAgriculturalReceipts)??Me(j?.income),t.agricultureExpenditure=Me(T?.expenditureIncurredOnAgriculture)??Me(j?.expenditure);const $=De(j?.agricultureLandDetails??j?.agriculturalLandDetails??e.agriculturalLandDetails)[0];$&&(t.agricultureLandInAcre=Me($.landInAcre),t.agricultureLandDistrict=Ce($.nameOfDistrict),t.agricultureLandPincode=Ce($.pinCode),t.agricultureLandOwner=Xh($.owner),t.agricultureLandType=Zh($.typeOfLand)),t.aadhaarNumber=Ce(e.aadharNumber);const U=De(e.bankDetails)[0];return U&&(t.bankAccountNumber=Ce(U.accountNumber),t.bankIfscCode=Ce(U.ifsCode)),lc(t)}function Xh(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function Zh(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function fn(o){const e=Ce(o);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function pn(o){return De(o).reduce((e,t)=>e+(Me(t.taxableAmount)??0),0)}function ef(o,e,t){if(!e.length)return;const r=Ce(o.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Me(n.totalTdsDeposited)}const i=Ce(o.employerName)?.trim().toLowerCase();if(i){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===i)return Me(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Me(e[0].totalTdsDeposited)}function tf(o){const e=De(o);if(!e.length)return{};let t,r,i,n;for(const s of e){const a=Me(s.exemptAmount)??Me(s.allowanceAmount);switch(Ce(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":i=a;break;default:n=(n??0)+(Me(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:i,other:n}}function At(o){let e=0,t=!1;for(const r of o)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function Me(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""&&Number.isFinite(Number(o)))return Number(o)}function Ce(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function rf(o){if(typeof o=="boolean")return o;if(typeof o=="string"){const e=o.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof o=="number")return o===1?!0:o===0?!1:void 0}function lc(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(Array.isArray(r)?e[t]=r.map(i=>i&&typeof i=="object"?lc(i):i):e[t]=r);return e}function mn(){if(typeof window>"u")return null;const o=window,e=o.__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=o.__aikaara_descriptor__??{},r=pf(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const i=mf(e.slug),n=typeof i?.tenantJwt=="string"?i.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(i&&i.userId!=null&&i.userId!==""?String(i.userId):bf(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:gf(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||yf(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function nf(o){const e=await o.getToken(),t=o.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${o.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...o.headers}});if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${i.slice(0,200)}`)}return Qh(Uo(await r.json().catch(()=>({}))))}async function of(o,e){const t=await o.getToken(),r=o.userId,i={...jh(e,{userId:r,assessmentYear:o.assessmentYear,isRevised:o.isRevised}),sendSummary:!0},n=o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...o.headers};o.txbdyApiKey&&(s["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(i)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Uo(await a.json().catch(()=>({})))}async function sf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/salary`,e)}async function af(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function ia(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function lf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function cf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function uf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/deductions`,e)}async function df(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function hf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/hp-income`,e)}async function ff(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/vda`,e)}async function _t(o,e,t){const i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await o.getToken()}`,...o.headers};o.txbdyApiKey&&(i["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:i,body:JSON.stringify(t)});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Uo(await n.json().catch(()=>({})))}function pf(o){const e=[o.cloud?.listEndpoint,o.cloud?.downloadEndpoint,o.upload?.signEndpoint,o.login?.pan?.basicPanEndpoint,o.login?.pan?.panDetailEndpoint,o.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function mf(o){if(!o||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${o}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function gf(o){const e={};if(!o)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(o))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function bf(o){if(!o)return;const e=o.userId??o.id??o.ext_uid??o.extUid;return e==null||e===""?void 0:String(e)}function Uo(o){if(o&&typeof o=="object"){const e=o;return e.data&&typeof e.data=="object"?e.data:e}return{}}function yf(){const o=new Date,e=o.getMonth()>=3?o.getFullYear():o.getFullYear()-1;return`${e}-${e+1}`}const vf=["No, I have a concerns"];class wf{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new tc(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.shouldOpenSmartEdit(t.text),i=this.client.config.templateActionAttributes??{},n=t.attributes?.action??{},s={...t.attributes,action:{...i,...n}};this.handleSend(t.text,s).then(()=>{r&&this.openSmartEdit()})})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages,r=Array.isArray(t)?t:vf;if(!Array.isArray(r)||r.length===0)return!1;const i=s=>s.trim().toLowerCase(),n=i(e);return r.some(s=>typeof s=="string"&&i(s)===n)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Rh,data:{}});const t=mn();if(!(!t||!t.baseUrl))try{const r=await nf(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=mn();if(!r)return;const i={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=Uh(n,i);s&&await sf(r,s)}else if(e==="bank-details"){const n=Bh(t,i);n&&await af(r,n)}else if(e==="other-sources")await ia(r,Fh(t,i));else if(e==="business-profession"){const n=Hh(t,i);n&&await lf(r,n)}else if(e==="crypto-income"){const n=qh(t,i);n&&await ff(r,n)}else if(e==="agricultural-income"){const n=Yh(t,i);n&&await cf(r,n)}else if(e==="deductions"){for(const s of Kh(t,i))await uf(r,s);const n=Gh(t,i);n&&await ia(r,n)}else if(e==="house-property"){const n=zh(t,i);n&&await df(r,n);const s=Vh(t,i);s&&await hf(r,s)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=mn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await of(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 cc 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||ou,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||qo,position:this.getAttribute("position")||this._config.position||iu,width:Number(this.getAttribute("width"))||this._config.width||eu,height:Number(this.getAttribute("height"))||this._config.height||tu,fontFamily:this._config.fontFamily||nu,borderRadius:this._config.borderRadius??ru,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ho,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||su,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,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??i),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("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;
|
|
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
757
757
|
}
|
|
758
758
|
</style>
|
|
759
759
|
<slot></slot>
|
|
760
|
-
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?jf(t):void 0,i=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Nf[i];if(n&&!customElements.get(i)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${i} failed to load`,s)):r?.scriptUrl&&!customElements.get(i)&&kc(r.scriptUrl).then(()=>Mf(i)).then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,s)),customElements.get(i)){const s=document.createElement(i);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof s[a]=="function")try{s[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${i}>`,c)}}s.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(s),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&s.setConsumedValues?.(this._consumedValues),s.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const s=this.payloadData;if(s.length>0&&s.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:s.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of s)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const s=this.payloadData;typeof s.message=="string"&&(s.okLabel||s.action||s.ok)&&this.mountModal(s)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=t?Rf[t.replace(/_/g,"-").toLowerCase()]:void 0;if(r){this.mountScheduleWidget(r,e);return}const i=e.data;if(i){if(t==="text"){const n=document.createElement("aikaara-text-input");n.setPayload(i),this.appendChild(n);return}if(t==="checkbox"||t==="radio"||t==="button"){const n=document.createElement("aikaara-option-list");n.setPayload({name:i.name??"",title:i.title,options:i.options??[],type:t}),this.appendChild(n);return}if(t==="submit"){const n=document.createElement("aikaara-submit-action"),s=this.getAttribute("message-id")??void 0;n.setPayload({name:i.name??"Submit",action:i.action??{message:i.name??"Submit"},messageId:s}),this.appendChild(n);return}t==="modal"&&this.mountModal({message:i.message??"",okLabel:i.okLabel,cancelLabel:i.cancelLabel,action:i.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-
|
|
760
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?jf(t):void 0,i=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Nf[i];if(n&&!customElements.get(i)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${i} failed to load`,s)):r?.scriptUrl&&!customElements.get(i)&&kc(r.scriptUrl).then(()=>Mf(i)).then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,s)),customElements.get(i)){const s=document.createElement(i);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof s[a]=="function")try{s[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${i}>`,c)}}s.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(s),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&s.setConsumedValues?.(this._consumedValues),s.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const s=this.payloadData;if(s.length>0&&s.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:s.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of s)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const s=this.payloadData;typeof s.message=="string"&&(s.okLabel||s.action||s.ok)&&this.mountModal(s)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=t?Rf[t.replace(/_/g,"-").toLowerCase()]:void 0;if(r){this.mountScheduleWidget(r,e);return}const i=e.data;if(i){if(t==="text"){const n=document.createElement("aikaara-text-input");n.setPayload(i),this.appendChild(n);return}if(t==="checkbox"||t==="radio"||t==="button"){const n=document.createElement("aikaara-option-list");n.setPayload({name:i.name??"",title:i.title,options:i.options??[],type:t}),this.appendChild(n);return}if(t==="submit"){const n=document.createElement("aikaara-submit-action"),s=this.getAttribute("message-id")??void 0;n.setPayload({name:i.name??"Submit",action:i.action??{message:i.name??"Submit"},messageId:s}),this.appendChild(n);return}t==="modal"&&this.mountModal({message:i.message??"",okLabel:i.okLabel,cancelLabel:i.cancelLabel,action:i.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-BaOKaIAZ.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:i})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:$f(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountScheduleWidget(e,t){const r=document.createElement(e),n={...t.data??t};if(delete n.type,!n.messageId){const s=this.getAttribute("message-id");s&&(n.messageId=s)}r.setPayload?.(n),this.appendChild(r)}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Df=new Set(["type","url","name","openLinkInNewTab","orderId"]);function $f(o){const e={};for(const[t,r]of Object.entries(o))Df.has(t)||(e[t]=r);return e}function Uf(o){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,i]of Object.entries(o))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}class _c extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
|
|
761
761
|
<style>
|
|
762
762
|
:host {
|
|
763
763
|
display: flex;
|