\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`${n}>\n`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${O(e,!0)}`}br(e){return" "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let i=this.parser.parseInline(n),s=J(e);if(null===s)return i;let o='"+i+"",o}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let s=J(e);if(null===s)return O(n);let o=`",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:O(e.text)}},L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},b=class e{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new y,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n{let s=e[i].flat(1/0);n=n.concat(this.walkTokens(s,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){let n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let i=e.renderer.apply(this,t);return!1===i&&(i=n.apply(this,t)),i}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){let t=this.defaults.renderer||new y(this.defaults);for(let n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;let i=n,s=e.renderer[i],o=t[i];t[i]=(...e)=>{let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new w(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;let i=n,s=e.tokenizer[i],o=t[i];t[i]=(...e)=>{let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new P;for(let n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;let i=n,s=e.hooks[i],o=t[i];P.passThroughHooks.has(n)?t[i]=e=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await s.call(t,e);return o.call(t,n)})();let i=s.call(t,e);return o.call(t,i)}:t[i]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await s.apply(t,e);return!1===n&&(n=await o.apply(t,e)),n})();let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,i=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(i.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let i={...n},s={...this.defaults,...i},o=this.onError(!!s.silent,!!s.async);if(!0===this.defaults.async&&!1===i.async)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||null===t)return o(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let n=s.hooks?await s.hooks.preprocess(t):t,i=await(s.hooks?await s.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,s),o=s.hooks?await s.hooks.processAllTokens(i):i;s.walkTokens&&await Promise.all(this.walkTokens(o,s.walkTokens));let r=await(s.hooks?await s.hooks.provideParser(e):e?b.parse:b.parseInline)(o,s);return s.hooks?await s.hooks.postprocess(r):r})().catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let n=(s.hooks?s.hooks.provideLexer(e):e?x.lex:x.lexInline)(t,s);s.hooks&&(n=s.hooks.processAllTokens(n)),s.walkTokens&&this.walkTokens(n,s.walkTokens);let i=(s.hooks?s.hooks.provideParser(e):e?b.parse:b.parseInline)(n,s);return s.hooks&&(i=s.hooks.postprocess(i)),i}catch(e){return o(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){let e="
An error occurred:
"+O(n.message+"",!0)+"
";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},M=new D;function g(e,t){return M.parse(e,t)}g.options=g.setOptions=function(e){return M.setOptions(e),g.defaults=M.defaults,G(g.defaults),g},g.getDefaults=z,g.defaults=T,g.use=function(...e){return M.use(...e),g.defaults=M.defaults,G(g.defaults),g},g.walkTokens=function(e,t){return M.walkTokens(e,t)},g.parseInline=M.parseInline,g.Parser=b,g.parser=b.parse,g.Renderer=y,g.TextRenderer=L,g.Lexer=x,g.lexer=x.lex,g.Tokenizer=w,g.Hooks=P,g.parse=g;var jt=g.options,Ft=g.setOptions,Ut=g.use,Kt=g.walkTokens,Wt=g.parseInline,Xt=null,Jt=b.parse,Vt=x.lex;const API_URL="https://api.ls-ai.ru",WIDGET_WS_PATH="/ws/widget",WIDGET_API_KEY="sk-dcf035645ae2ba0972e26cc543c39ba4614e89fd0e113e998c78754f9218fb72";function httpOriginToWsBase(){return API_URL.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/$/,"")}let ws=null,reconnectTimer=null,reconnectDelayMs=3e3;const pendingOutgoing=[],messageListeners=new Set,openListeners=new Set;function subscribeWidgetWs(e){return messageListeners.add(e),()=>messageListeners.delete(e)}function onWidgetSocketOpen(e){return openListeners.add(e),()=>openListeners.delete(e)}function dispatch(e){for(const t of messageListeners)try{t(e)}catch(e){console.error("WidgetWs listener error",e)}}function flushPending(){if(ws&&ws.readyState===WebSocket.OPEN)for(;pendingOutgoing.length;){const e=pendingOutgoing.shift();if(e)try{ws.send(e)}catch{pendingOutgoing.unshift(e);break}}}function notifyOpen(){for(const e of openListeners)try{e()}catch(e){console.error("WidgetWs onOpen handler error",e)}}function clearReconnectTimer(){reconnectTimer&&(clearTimeout(reconnectTimer),reconnectTimer=null)}function scheduleReconnect(e){clearReconnectTimer(),reconnectTimer=setTimeout((()=>{reconnectTimer=null,connectInternal()}),e)}function connectInternal(){if(ws&&(ws.readyState===WebSocket.CONNECTING||ws.readyState===WebSocket.OPEN))return;const e=`${httpOriginToWsBase()}${WIDGET_WS_PATH}?api_key=${encodeURIComponent(WIDGET_API_KEY)}`;try{ws=new WebSocket(e)}catch(e){return console.error("WidgetWebSocket: failed to create",e),void scheduleReconnect(reconnectDelayMs)}ws.onopen=()=>{reconnectDelayMs=3e3,flushPending(),notifyOpen()},ws.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}"system"!==t.domain||"ping"!==t.type?dispatch(t):sendWidgetEnvelope("system","pong",{})},ws.onerror=()=>{},ws.onclose=e=>{ws=null,4001===e.code?(reconnectDelayMs=Math.min(2*reconnectDelayMs,12e4),scheduleReconnect(Math.max(reconnectDelayMs,6e4))):scheduleReconnect(reconnectDelayMs)}}function initWidgetWebSocket(){connectInternal()}function sendWidgetEnvelope(e,t,n){const i=JSON.stringify({v:1,domain:e,type:t,payload:n??{},ts:(new Date).toISOString()});if(ws?.readyState===WebSocket.OPEN)try{ws.send(i)}catch{pendingOutgoing.push(i)}else pendingOutgoing.push(i)}function widgetWsRpc(e,t,n,i=25e3){const s=()=>new Promise(((s,o)=>{let r=!1,a=null;const l=setTimeout((()=>{r||(r=!0,a?.(),o(new Error("Widget WS timeout")))}),i);a=subscribeWidgetWs((e=>{if("widget"===e.domain){if(e.type===n){if(r)return;return r=!0,clearTimeout(l),a?.(),void s()}if("error"===e.type){if(r)return;r=!0,clearTimeout(l),a?.(),o(new Error(String(e.payload?.message??"error")))}}})),sendWidgetEnvelope("widget",e,t)})),o=rpcTail.then((()=>s()),(()=>s()));return rpcTail=o.catch((()=>{})),o}function widgetWsRpcResult(e,t,n,i=25e3){const s=()=>new Promise(((s,o)=>{let r=!1,a=null;const l=setTimeout((()=>{r||(r=!0,a?.(),o(new Error("Widget WS timeout")))}),i);a=subscribeWidgetWs((e=>{if("widget"===e.domain){if(e.type===n){if(r)return;return r=!0,clearTimeout(l),a?.(),void s(e.payload??{})}if("error"===e.type){if(r)return;r=!0,clearTimeout(l),a?.(),o(new Error(String(e.payload?.message??"error")))}}})),sendWidgetEnvelope("widget",e,t)})),o=rpcTail.then((()=>s()),(()=>s()));return rpcTail=o.catch((()=>{})),o}let rpcTail=Promise.resolve();function getWidgetSocketReadyState(){return ws?.readyState??null}function normalizeBugBody(e){const t={};if(null==e)return t;if("string"==typeof e)return t.payload=e,t;for(const[n,i]of Object.entries(e))t[n]="string"==typeof i?i:JSON.stringify(i);return t}class BugReport{report(e){let t={};if("string"==typeof e.headers)try{t=JSON.parse(e.headers)}catch{t={}}else e.headers&&"object"==typeof e.headers&&(t=e.headers);widgetWsRpc("bug_report",{url:String(e.url??""),headers:t,body:normalizeBugBody(e.body),error:void 0!==e.error&&null!==e.error?"string"==typeof e.error?e.error:JSON.stringify(e.error):""},"bug_report_ok",15e3).catch((()=>{}))}}const isString=e=>"string"==typeof e,defer=()=>{let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));return n.resolve=e,n.reject=t,n},makeString=e=>null==e?"":String(e),copy=(e,t,n)=>{e.forEach((e=>{t[e]&&(n[e]=t[e])}))},lastOfPathSeparatorRegExp=/###/g,cleanKey=e=>e&&e.includes("###")?e.replace(lastOfPathSeparatorRegExp,"."):e,canNotTraverseDeeper=e=>!e||isString(e),getLastOfPath=(e,t,n)=>{const i=isString(t)?t.split("."):t;let s=0;for(;s{const{obj:i,k:s}=getLastOfPath(e,t,Object);if(void 0!==i||1===t.length)return void(i[s]=n);let o=t[t.length-1],r=t.slice(0,t.length-1),a=getLastOfPath(e,r,Object);for(;void 0===a.obj&&r.length;)o=`${r[r.length-1]}.${o}`,r=r.slice(0,r.length-1),a=getLastOfPath(e,r,Object),a?.obj&&void 0!==a.obj[`${a.k}.${o}`]&&(a.obj=void 0);a.obj[`${a.k}.${o}`]=n},pushPath=(e,t,n,i)=>{const{obj:s,k:o}=getLastOfPath(e,t,Object);s[o]=s[o]||[],s[o].push(n)},getPath=(e,t)=>{const{obj:n,k:i}=getLastOfPath(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,i))return n[i]},getPathWithDefaults=(e,t,n)=>{const i=getPath(e,n);return void 0!==i?i:getPath(t,n)},deepExtend=(e,t,n)=>{for(const i in t)"__proto__"!==i&&"constructor"!==i&&(i in e?isString(e[i])||e[i]instanceof String||isString(t[i])||t[i]instanceof String?n&&(e[i]=t[i]):deepExtend(e[i],t[i],n):e[i]=t[i]);return e},regexEscape=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),_entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},i18next_escape=e=>isString(e)?e.replace(/[&<>"'\/]/g,(e=>_entityMap[e])):e;class RegExpCache{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(void 0!==t)return t;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const chars=[" ",",","?","!",";"],looksLikeObjectPathRegExpCache=new RegExpCache(20),looksLikeObjectPath=(e,t,n)=>{t=t||"",n=n||"";const i=chars.filter((e=>!t.includes(e)&&!n.includes(e)));if(0===i.length)return!0;const s=looksLikeObjectPathRegExpCache.getRegExp(`(${i.map((e=>"?"===e?"\\?":e)).join("|")})`);let o=!s.test(e);if(!o){const t=e.indexOf(n);t>0&&!s.test(e.substring(0,t))&&(o=!0)}return o},deepFind=(e,t,n=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}const i=t.split(n);let s=e;for(let e=0;ee?.replace(/_/g,"-"),consoleLogger={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Logger{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||consoleLogger,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,n,i){return i&&!this.debug?null:(isString(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Logger(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new Logger(this.logger,e)}}var baseLogger=new Logger;class EventEmitter{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach((e=>{this.observers[e]||(this.observers[e]=new Map);const n=this.observers[e].get(t)||0;this.observers[e].set(t,n+1)})),this}off(e,t){this.observers[e]&&(t?this.observers[e].delete(t):delete this.observers[e])}once(e,t){const n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n),this}emit(e,...t){if(this.observers[e]){Array.from(this.observers[e].entries()).forEach((([e,n])=>{for(let i=0;i{for(let s=0;s-1&&this.options.ns.splice(t,1)}getResource(e,t,n,i={}){const s=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,o=void 0!==i.ignoreJSONStructure?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let r;e.includes(".")?r=e.split("."):(r=[e,t],n&&(Array.isArray(n)?r.push(...n):isString(n)&&s?r.push(...n.split(s)):r.push(n)));const a=getPath(this.data,r);return a||t||n||!e.includes(".")||(e=r[0],t=r[1],n=r.slice(2).join(".")),!a&&o&&isString(n)?deepFind(this.data?.[e]?.[t],n,s):a}addResource(e,t,n,i,s={silent:!1}){const o=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator;let r=[e,t];n&&(r=r.concat(o?n.split(o):n)),e.includes(".")&&(r=e.split("."),i=t,t=r[1]),this.addNamespaces(t),setPath(this.data,r,i),s.silent||this.emit("added",e,t,n,i)}addResources(e,t,n,i={silent:!1}){for(const i in n)(isString(n[i])||Array.isArray(n[i]))&&this.addResource(e,t,i,n[i],{silent:!0});i.silent||this.emit("added",e,t,n)}addResourceBundle(e,t,n,i,s,o={silent:!1,skipCopy:!1}){let r=[e,t];e.includes(".")&&(r=e.split("."),i=n,n=t,t=r[1]),this.addNamespaces(t);let a=getPath(this.data,r)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),i?deepExtend(a,n,s):a={...a,...n},setPath(this.data,r,a),o.silent||this.emit("added",e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return void 0!==this.getResource(e,t)}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find((e=>t[e]&&Object.keys(t[e]).length>0))}toJSON(){return this.data}}var postProcessor={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,i,s){return e.forEach((e=>{t=this.processors[e]?.process(t,n,i,s)??t})),t}};const PATH_KEY=Symbol("i18next/PATH_KEY");function createProxy(){const e=[],t=Object.create(null);let n;return t.get=(i,s)=>(n?.revoke?.(),s===PATH_KEY?e:(e.push(s),n=Proxy.revocable(i,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function keysFromSelector(e,t){const{[PATH_KEY]:n}=e(createProxy()),i=t?.keySeparator??".",s=t?.nsSeparator??":";if(n.length>1&&s){const e=t?.ns,o=Array.isArray(e)?e:null;if(o&&o.length>1&&o.slice(1).includes(n[0]))return`${n[0]}${s}${n.slice(1).join(i)}`}return n.join(i)}const shouldHandleAsObject=e=>!isString(e)&&"boolean"!=typeof e&&"number"!=typeof e;class Translator extends EventEmitter{constructor(e,t={}){super(),copy(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=baseLogger.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const n={...t};if(null==e)return!1;const i=this.resolve(e,n);if(void 0===i?.res)return!1;const s=shouldHandleAsObject(i.res);return!1!==n.returnObjects||!s}extractFromKey(e,t){let n=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===n&&(n=":");const i=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator;let s=t.ns||this.options.defaultNS||[];const o=n&&e.includes(n),r=!(this.options.userDefinedKeySeparator||t.keySeparator||this.options.userDefinedNsSeparator||t.nsSeparator||looksLikeObjectPath(e,n,i));if(o&&!r){const t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:isString(s)?[s]:s};const o=e.split(n);(n!==i||n===i&&this.options.ns.includes(o[0]))&&(s=o.shift()),e=o.join(i)}return{key:e,namespaces:isString(s)?[s]:s}}translate(e,t,n){let i="object"==typeof t?{...t}:t;if("object"!=typeof i&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof i&&(i={...i}),i||(i={}),null==e)return"";"function"==typeof e&&(e=keysFromSelector(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map((e=>"function"==typeof e?keysFromSelector(e,{...this.options,...i}):String(e)));const s=void 0!==i.returnDetails?i.returnDetails:this.options.returnDetails,o=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,{key:r,namespaces:a}=this.extractFromKey(e[e.length-1],i),l=a[a.length-1];let c=void 0!==i.nsSeparator?i.nsSeparator:this.options.nsSeparator;void 0===c&&(c=":");const p=i.lng||this.language,d=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===p?.toLowerCase())return d?s?{res:`${l}${c}${r}`,usedKey:r,exactUsedKey:r,usedLng:p,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${c}${r}`:s?{res:r,usedKey:r,exactUsedKey:r,usedLng:p,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:r;const h=this.resolve(e,i);let u=h?.res;const g=h?.usedKey||r,m=h?.exactUsedKey||r,f=void 0!==i.joinArrays?i.joinArrays:this.options.joinArrays,b=!this.i18nFormat||this.i18nFormat.handleAsObject,x=void 0!==i.count&&!isString(i.count),y=Translator.hasDefaultValue(i),w=x?this.pluralResolver.getSuffix(p,i.count,i):"",k=i.ordinal&&x?this.pluralResolver.getSuffix(p,i.count,{ordinal:!1}):"",v=x&&!i.ordinal&&0===i.count,A=v&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${w}`]||i[`defaultValue${k}`]||i.defaultValue;let S=u;b&&!u&&y&&(S=A);const C=shouldHandleAsObject(S),L=Object.prototype.toString.apply(S);if(!(b&&S&&C)||["[object Number]","[object Function]","[object RegExp]"].includes(L)||isString(f)&&Array.isArray(S))if(b&&isString(f)&&Array.isArray(u))u=u.join(f),u&&(u=this.extendTranslation(u,e,i,n));else{let t=!1,s=!1;!this.isValidLookup(u)&&y&&(t=!0,u=A),this.isValidLookup(u)||(s=!0,u=r);const a=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&s?void 0:u,d=y&&A!==u&&this.options.updateMissing;if(s||t||d){if(this.logger.log(d?"updateKey":"missingKey",p,l,r,d?A:u),o){const e=this.resolve(r,{...i,keySeparator:!1});e&&e.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let e=[];const t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let n=0;n{const s=y&&n!==u?n:a;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,s,d,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,s,d,i),this.emit("missingKey",e,l,t,u)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?e.forEach((e=>{const t=this.pluralResolver.getSuffixes(e,i);v&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!t.includes(`${this.options.pluralSeparator}zero`)&&t.push(`${this.options.pluralSeparator}zero`),t.forEach((t=>{n([e],r+t,i[`defaultValue${t}`]||A)}))})):n(e,r,A))}u=this.extendTranslation(u,e,i,h,n),s&&u===r&&this.options.appendNamespaceToMissingKey&&(u=`${l}${c}${r}`),(s||t)&&this.options.parseMissingKeyHandler&&(u=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${c}${r}`:r,t?u:void 0,i))}else{if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,S,{...i,ns:a}):`key '${r} (${this.language})' returned an object instead of string.`;return s?(h.res=e,h.usedParams=this.getUsedParamsDetails(i),h):e}if(o){const e=Array.isArray(S),t=e?[]:{},n=e?m:g;for(const e in S)if(Object.prototype.hasOwnProperty.call(S,e)){const s=`${n}${o}${e}`;t[e]=y&&!u?this.translate(s,{...i,defaultValue:shouldHandleAsObject(A)?A[e]:void 0,joinArrays:!1,ns:a}):this.translate(s,{...i,joinArrays:!1,ns:a}),t[e]===s&&(t[e]=S[e])}u=t}}return s?(h.res=u,h.usedParams=this.getUsedParamsDetails(i),h):u}extendTranslation(e,t,n,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const o=isString(e)&&(void 0!==n?.interpolation?.skipOnVariables?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let r;if(o){const t=e.match(this.interpolator.nestingRegexp);r=t&&t.length}let a=n.replace&&!isString(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(a={...this.options.interpolation.defaultVariables,...a}),e=this.interpolator.interpolate(e,a,n.lng||this.language||i.usedLng,n),o){const t=e.match(this.interpolator.nestingRegexp);r<(t&&t.length)&&(n.nest=!1)}!n.lng&&i&&i.res&&(n.lng=this.language||i.usedLng),!1!==n.nest&&(e=this.interpolator.nest(e,((...e)=>s?.[0]!==e[0]||n.context?this.translate(...e,t):(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null)),n)),n.interpolation&&this.interpolator.reset()}const o=n.postProcess||this.options.postProcess,r=isString(o)?[o]:o;return null!=e&&r?.length&&!1!==n.applyPostProcessor&&(e=postProcessor.handle(r,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,i,s,o,r;return isString(e)&&(e=[e]),Array.isArray(e)&&(e=e.map((e=>"function"==typeof e?keysFromSelector(e,{...this.options,...t}):e))),e.forEach((e=>{if(this.isValidLookup(n))return;const a=this.extractFromKey(e,t),l=a.key;i=l;let c=a.namespaces;this.options.fallbackNS&&(c=c.concat(this.options.fallbackNS));const p=void 0!==t.count&&!isString(t.count),d=p&&!t.ordinal&&0===t.count,h=void 0!==t.context&&(isString(t.context)||"number"==typeof t.context)&&""!==t.context,u=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);c.forEach((e=>{this.isValidLookup(n)||(r=e,this.checkedLoadedFor[`${u[0]}-${e}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(r)||(this.checkedLoadedFor[`${u[0]}-${e}`]=!0,this.logger.warn(`key "${i}" for languages "${u.join(", ")}" won't get resolved as namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),u.forEach((i=>{if(this.isValidLookup(n))return;o=i;const r=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(r,l,i,e,t);else{let e;p&&(e=this.pluralResolver.getSuffix(i,t.count,t));const n=`${this.options.pluralSeparator}zero`,s=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(t.ordinal&&e.startsWith(s)&&r.push(l+e.replace(s,this.options.pluralSeparator)),r.push(l+e),d&&r.push(l+n)),h){const i=`${l}${this.options.contextSeparator||"_"}${t.context}`;r.push(i),p&&(t.ordinal&&e.startsWith(s)&&r.push(i+e.replace(s,this.options.pluralSeparator)),r.push(i+e),d&&r.push(i+n))}}let a;for(;a=r.pop();)this.isValidLookup(n)||(s=a,n=this.getResource(i,e,a,t))})))}))})),{res:n,usedKey:i,exactUsedKey:s,usedLng:o,usedNS:r}}isValidLookup(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}getResource(e,t,n,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,n,i):this.resourceStore.getResource(e,t,n,i)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!isString(e.replace);let i=n?e.replace:e;if(n&&void 0!==e.count&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!n){i={...i};for(const e of t)delete i[e]}return i}static hasDefaultValue(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&t.startsWith("defaultValue")&&void 0!==e[t])return!0;return!1}}class LanguageUtil{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=baseLogger.create("languageUtils")}getScriptPartFromCode(e){if(!(e=getCleanedCode(e))||!e.includes("-"))return null;const t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}getLanguagePartFromCode(e){if(!(e=getCleanedCode(e))||!e.includes("-"))return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(isString(e)&&e.includes("-")){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch(e){}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach((e=>{if(t)return;const n=this.formatLanguageCode(e);this.options.supportedLngs&&!this.isSupportedCode(n)||(t=n)})),!t&&this.options.supportedLngs&&e.forEach((e=>{if(t)return;const n=this.getScriptPartFromCode(e);if(this.isSupportedCode(n))return t=n;const i=this.getLanguagePartFromCode(e);if(this.isSupportedCode(i))return t=i;t=this.options.supportedLngs.find((e=>e===i||!(!e.includes("-")&&!i.includes("-"))&&(!(!e.includes("-")||i.includes("-")||e.slice(0,e.indexOf("-"))!==i)||!!(e.startsWith(i)&&i.length>1))))})),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),isString(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||(n=e[this.getScriptPartFromCode(t)]),n||(n=e[this.formatLanguageCode(t)]),n||(n=e[this.getLanguagePartFromCode(t)]),n||(n=e.default),n||[]}toResolveHierarchy(e,t){const n=this.getFallbackCodes((!1===t?[]:t)||this.options.fallbackLng||[],e),i=[],s=e=>{e&&(this.isSupportedCode(e)?i.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return isString(e)&&(e.includes("-")||e.includes("_"))?("languageOnly"!==this.options.load&&s(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&s(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&s(this.getLanguagePartFromCode(e))):isString(e)&&s(this.formatLanguageCode(e)),n.forEach((e=>{i.includes(e)||s(this.formatLanguageCode(e))})),i}}const suffixesOrder={zero:0,one:1,two:2,few:3,many:4,other:5},dummyRule={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class PluralResolver{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=baseLogger.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const n=getCleanedCode("dev"===e?"en":e),i=t.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:n,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(n,{type:i})}catch(n){if("undefined"==typeof Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),dummyRule;if(!e.match(/-|_/))return dummyRule;const i=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(i,t)}return this.pluralRulesCache[s]=o,o}needsPlural(e,t={}){let n=this.getRule(e,t);return n||(n=this.getRule("dev",t)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map((e=>`${t}${e}`))}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||(n=this.getRule("dev",t)),n?n.resolvedOptions().pluralCategories.sort(((e,t)=>suffixesOrder[e]-suffixesOrder[t])).map((e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`)):[]}getSuffix(e,t,n={}){const i=this.getRule(e,n);return i?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,n))}}const deepFindWithDefaults=(e,t,n,i=".",s=!0)=>{let o=getPathWithDefaults(e,t,n);return!o&&s&&isString(n)&&(o=deepFind(e,n,i),void 0===o&&(o=deepFind(t,n,i))),o},regexSafe=e=>e.replace(/\$/g,"$$$$");class Interpolator{constructor(e={}){this.logger=baseLogger.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:n,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:r,suffixEscaped:a,formatSeparator:l,unescapeSuffix:c,unescapePrefix:p,nestingPrefix:d,nestingPrefixEscaped:h,nestingSuffix:u,nestingSuffixEscaped:g,nestingOptionsSeparator:m,maxReplaces:f,alwaysFormat:b}=e.interpolation;this.escape=void 0!==t?t:i18next_escape,this.escapeValue=void 0===n||n,this.useRawValueToEscape=void 0!==i&&i,this.prefix=s?regexEscape(s):o||"{{",this.suffix=r?regexEscape(r):a||"}}",this.formatSeparator=l||",",this.unescapePrefix=c?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":c||"",this.nestingPrefix=d?regexEscape(d):h||regexEscape("$t("),this.nestingSuffix=u?regexEscape(u):g||regexEscape(")"),this.nestingOptionsSeparator=m||",",this.maxReplaces=f||1e3,this.alwaysFormat=void 0!==b&&b,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,i){let s,o,r;const a=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=e=>{if(!e.includes(this.formatSeparator)){const s=deepFindWithDefaults(t,a,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(s,void 0,n,{...i,...t,interpolationkey:e}):s}const s=e.split(this.formatSeparator),o=s.shift().trim(),r=s.join(this.formatSeparator).trim();return this.format(deepFindWithDefaults(t,a,o,this.options.keySeparator,this.options.ignoreJSONStructure),r,n,{...i,...t,interpolationkey:o})};this.resetRegExp();const c=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=void 0!==i?.interpolation?.skipOnVariables?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>regexSafe(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?regexSafe(this.escape(e)):regexSafe(e)}].forEach((t=>{for(r=0;s=t.regex.exec(e);){const n=s[1].trim();if(o=l(n),void 0===o)if("function"==typeof c){const t=c(e,s,i);o=isString(t)?t:""}else if(i&&Object.prototype.hasOwnProperty.call(i,n))o="";else{if(p){o=s[0];continue}this.logger.warn(`missed to pass in variable ${n} for interpolating ${e}`),o=""}else isString(o)||this.useRawValueToEscape||(o=makeString(o));const a=t.safeValue(o);if(e=e.replace(s[0],a),p?(t.regex.lastIndex+=o.length,t.regex.lastIndex-=s[0].length):t.regex.lastIndex=0,r++,r>=this.maxReplaces)break}})),e}nest(e,t,n={}){let i,s,o;const r=(e,t)=>{const n=this.nestingOptionsSeparator;if(!e.includes(n))return e;const i=e.split(new RegExp(`${regexEscape(n)}[ ]*{`));let s=`{${i[1]}`;e=i[0],s=this.interpolate(s,o);const r=s.match(/'/g),a=s.match(/"/g);((r?.length??0)%2==0&&!a||(a?.length??0)%2!=0)&&(s=s.replace(/'/g,'"'));try{o=JSON.parse(s),t&&(o={...t,...o})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${n}${s}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,e};for(;i=this.nestingRegexp.exec(e);){let a=[];o={...n},o=o.replace&&!isString(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const l=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(-1!==l&&(a=i[1].slice(l).split(this.formatSeparator).map((e=>e.trim())).filter(Boolean),i[1]=i[1].slice(0,l)),s=t(r.call(this,i[1].trim(),o),o),s&&i[0]===e&&!isString(s))return s;isString(s)||(s=makeString(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),a.length&&(s=a.reduce(((e,t)=>this.format(e,t,n.lng,{...n,interpolationkey:i[1].trim()})),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const parseFormatStr=e=>{let t=e.toLowerCase().trim();const n={};if(e.includes("(")){const i=e.split("(");t=i[0].toLowerCase().trim();const s=i[1].slice(0,-1);if("currency"!==t||s.includes(":"))if("relativetime"!==t||s.includes(":")){s.split(";").forEach((e=>{if(e){const[t,...i]=e.split(":"),s=i.join(":").trim().replace(/^'+|'+$/g,""),o=t.trim();n[o]||(n[o]=s),"false"===s&&(n[o]=!1),"true"===s&&(n[o]=!0),isNaN(s)||(n[o]=parseInt(s,10))}}))}else n.range||(n.range=s.trim());else n.currency||(n.currency=s.trim())}return{formatName:t,formatOptions:n}},createCachedFormatter=e=>{const t={};return(n,i,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const r=i+JSON.stringify(o);let a=t[r];return a||(a=e(getCleanedCode(i),s),t[r]=a),a(n)}},createNonCachedFormatter=e=>(t,n,i)=>e(getCleanedCode(n),i)(t);class Formatter{constructor(e={}){this.logger=baseLogger.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const n=t.cacheInBuiltFormats?createCachedFormatter:createNonCachedFormatter;this.formats={number:n(((e,t)=>{const n=new Intl.NumberFormat(e,{...t});return e=>n.format(e)})),currency:n(((e,t)=>{const n=new Intl.NumberFormat(e,{...t,style:"currency"});return e=>n.format(e)})),datetime:n(((e,t)=>{const n=new Intl.DateTimeFormat(e,{...t});return e=>n.format(e)})),relativetime:n(((e,t)=>{const n=new Intl.RelativeTimeFormat(e,{...t});return e=>n.format(e,t.range||"day")})),list:n(((e,t)=>{const n=new Intl.ListFormat(e,{...t});return e=>n.format(e)}))}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=createCachedFormatter(t)}format(e,t,n,i={}){if(!t)return e;if(null==e)return e;const s=t.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&!s[0].includes(")")&&s.find((e=>e.includes(")")))){const e=s.findIndex((e=>e.includes(")")));s[0]=[s[0],...s.splice(1,e)].join(this.formatSeparator)}return s.reduce(((e,t)=>{const{formatName:s,formatOptions:o}=parseFormatStr(t);if(this.formats[s]){let t=e;try{const r=i?.formatParams?.[i.interpolationkey]||{},a=r.locale||r.lng||i.locale||i.lng||n;t=this.formats[s](e,a,{...o,...i,...r})}catch(e){this.logger.warn(e)}return t}return this.logger.warn(`there was no format function for ${s}`),e}),e)}}const removePending=(e,t)=>{void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)};class Connector extends EventEmitter{constructor(e,t,n,i={}){super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=i,this.logger=baseLogger.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,i.backend,i)}queueLoad(e,t,n,i){const s={},o={},r={},a={};return e.forEach((e=>{let i=!0;t.forEach((t=>{const r=`${e}|${t}`;!n.reload&&this.store.hasResourceBundle(e,t)?this.state[r]=2:this.state[r]<0||(1===this.state[r]?void 0===o[r]&&(o[r]=!0):(this.state[r]=1,i=!1,void 0===o[r]&&(o[r]=!0),void 0===s[r]&&(s[r]=!0),void 0===a[t]&&(a[t]=!0)))})),i||(r[e]=!0)})),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(r),toLoadNamespaces:Object.keys(a)}}loaded(e,t,n){const i=e.split("|"),s=i[0],o=i[1];t&&this.emit("failedLoading",s,o,t),!t&&n&&this.store.addResourceBundle(s,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);const r={};this.queue.forEach((n=>{pushPath(n.loaded,[s],o),removePending(n,e),t&&n.errors.push(t),0!==n.pendingCount||n.done||(Object.keys(n.loaded).forEach((e=>{r[e]||(r[e]={});const t=n.loaded[e];t.length&&t.forEach((t=>{void 0===r[e][t]&&(r[e][t]=!0)}))})),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())})),this.emit("loaded",r),this.queue=this.queue.filter((e=>!e.done))}read(e,t,n,i=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:e,ns:t,fcName:n,tried:i,wait:s,callback:o});this.readingCalls++;const r=(r,a)=>{if(this.readingCalls--,this.waitingReads.length>0){const e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}r&&a&&i{this.read(e,t,n,i+1,2*s,o)}),s):o(r,a)},a=this.backend[n].bind(this.backend);if(2!==a.length)return a(e,t,r);try{const n=a(e,t);n&&"function"==typeof n.then?n.then((e=>r(null,e))).catch(r):r(null,n)}catch(e){r(e)}}prepareLoading(e,t,n={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();isString(e)&&(e=this.languageUtils.toResolveHierarchy(e)),isString(t)&&(t=[t]);const s=this.queueLoad(e,t,n,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach((e=>{this.loadOne(e)}))}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=""){const n=e.split("|"),i=n[0],s=n[1];this.read(i,s,"read",void 0,void 0,((n,o)=>{n&&this.logger.warn(`${t}loading namespace ${s} for language ${i} failed`,n),!n&&o&&this.logger.log(`${t}loaded namespace ${s} for language ${i}`,o),this.loaded(e,n,o)}))}saveMissing(e,t,n,i,s,o={},r=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(t)){if(null!=n&&""!==n){if(this.backend?.create){const a={...o,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let s;s=5===l.length?l(e,t,n,i,a):l(e,t,n,i),s&&"function"==typeof s.then?s.then((e=>r(null,e))).catch(r):r(null,s)}catch(e){r(e)}else l(e,t,n,i,r,a)}e&&e[0]&&this.store.addResource(e[0],t,n,i)}}else this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")}}const get=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if("object"==typeof e[1]&&(t=e[1]),isString(e[1])&&(t.defaultValue=e[1]),isString(e[2])&&(t.tDescription=e[2]),"object"==typeof e[2]||"object"==typeof e[3]){const n=e[3]||e[2];Object.keys(n).forEach((e=>{t[e]=n[e]}))}return t},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),transformOptions=e=>(isString(e.ns)&&(e.ns=[e.ns]),isString(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),isString(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&!e.supportedLngs.includes("cimode")&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),noop=()=>{},bindMemberFunctions=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach((t=>{"function"==typeof e[t]&&(e[t]=e[t].bind(e))}))};class I18n extends EventEmitter{constructor(e={},t){if(super(),this.options=transformOptions(e),this.services={},this.logger=baseLogger,this.modules={external:[]},bindMemberFunctions(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout((()=>{this.init(e,t)}),0)}}init(e={},t){this.isInitializing=!0,"function"==typeof e&&(t=e,e={}),null==e.defaultNS&&e.ns&&(isString(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=get();this.options={...n,...this.options,...transformOptions(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator),"function"!=typeof this.options.overloadTranslationOptionHandler&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const i=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?baseLogger.init(i(this.modules.logger),this.options):baseLogger.init(null,this.options),e=this.modules.formatter?this.modules.formatter:Formatter;const t=new LanguageUtil(this.options);this.store=new ResourceStore(this.options.resources,this.options);const n=this.services;n.logger=baseLogger,n.resourceStore=this.store,n.languageUtils=t,n.pluralResolver=new PluralResolver(t,{prepend:this.options.pluralSeparator}),e&&(n.formatter=i(e),n.formatter.init&&n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new Interpolator(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new Connector(i(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on("*",((e,...t)=>{this.emit(e,...t)})),this.modules.languageDetector&&(n.languageDetector=i(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=i(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new Translator(this.services,this.options),this.translator.on("*",((e,...t)=>{this.emit(e,...t)})),this.modules.external.forEach((e=>{e.init&&e.init(this)}))}if(this.format=this.options.interpolation.format,t||(t=noop),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&"dev"!==e[0]&&(this.options.lng=e[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((e=>{this[e]=(...t)=>this.store[e](...t)}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((e=>{this[e]=(...t)=>(this.store[e](...t),this)}));const s=defer(),o=()=>{const e=(e,n)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),s.resolve(n),t(e,n)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?o():setTimeout(o,0),s}loadResources(e,t=noop){let n=t;const i=isString(e)?e:this.language;if("function"==typeof e&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===i?.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return n();const e=[],t=t=>{if(!t)return;if("cimode"===t)return;this.services.languageUtils.toResolveHierarchy(t).forEach((t=>{"cimode"!==t&&(e.includes(t)||e.push(t))}))};if(i)t(i);else{this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((e=>t(e)))}this.options.preload?.forEach?.((e=>t(e))),this.services.backendConnector.load(e,this.options.ns,(e=>{e||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),n(e)}))}else n(null)}reloadResources(e,t,n){const i=defer();return"function"==typeof e&&(n=e,e=void 0),"function"==typeof t&&(n=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),n||(n=noop),this.services.backendConnector.reload(e,t,(e=>{i.resolve(),n(e)})),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&postProcessor.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}setResolvedLanguage(e){if(e&&this.languages&&!["cimode","dev"].includes(e)){for(let e=0;e{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},s=(s,o)=>{o?this.isLanguageChangingTo===e&&(i(o),this.translator.changeLanguage(o),this.isLanguageChangingTo=void 0,this.emit("languageChanged",o),this.logger.log("languageChanged",o)):this.isLanguageChangingTo=void 0,n.resolve(((...e)=>this.t(...e))),t&&t(s,((...e)=>this.t(...e)))},o=t=>{e||t||!this.services.languageDetector||(t=[]);const n=isString(t)?t:t&&t[0],o=this.store.hasLanguageSomeTranslations(n)?n:this.services.languageUtils.getBestMatchFromCodes(isString(t)?[t]:t);o&&(this.language||i(o),this.translator.language||this.translator.changeLanguage(o),this.services.languageDetector?.cacheUserLanguage?.(o)),this.loadResources(o,(e=>{s(e,o)}))};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e):o(this.services.languageDetector.detect()),n}getFixedT(e,t,n){const i=(e,t,...s)=>{let o;o="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(s)):{...t},o.lng=o.lng||i.lng,o.lngs=o.lngs||i.lngs,o.ns=o.ns||i.ns,""!==o.keyPrefix&&(o.keyPrefix=o.keyPrefix||n||i.keyPrefix);const r={...this.options,...o};"function"==typeof o.keyPrefix&&(o.keyPrefix=keysFromSelector(o.keyPrefix,r));const a=this.options.keySeparator||".";let l;return o.keyPrefix&&Array.isArray(e)?l=e.map((e=>("function"==typeof e&&(e=keysFromSelector(e,r)),`${o.keyPrefix}${a}${e}`))):("function"==typeof e&&(e=keysFromSelector(e,r)),l=o.keyPrefix?`${o.keyPrefix}${a}${e}`:e),this.t(l,o)};return isString(e)?i.lng=e:i.lngs=e,i.ns=t,i.keyPrefix=n,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=t.lng||this.resolvedLanguage||this.languages[0],i=!!this.options&&this.options.fallbackLng,s=this.languages[this.languages.length-1];if("cimode"===n.toLowerCase())return!0;const o=(e,t)=>{const n=this.services.backendConnector.state[`${e}|${t}`];return-1===n||0===n||2===n};if(t.precheck){const e=t.precheck(this,o);if(void 0!==e)return e}return!!this.hasResourceBundle(n,e)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!o(n,e)||i&&!o(s,e)))}loadNamespaces(e,t){const n=defer();return this.options.ns?(isString(e)&&(e=[e]),e.forEach((e=>{this.options.ns.includes(e)||this.options.ns.push(e)})),this.loadResources((e=>{n.resolve(),t&&t(e)})),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){const n=defer();isString(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter((e=>!i.includes(e)&&this.services.languageUtils.isSupportedCode(e)));return s.length?(this.options.preload=i.concat(s),this.loadResources((e=>{n.resolve(),t&&t(e)})),n):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const t=new Intl.Locale(e);if(t&&t.getTextInfo){const e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch(e){}const t=this.services?.languageUtils||new LanguageUtil(get());return e.toLowerCase().indexOf("-latn")>1?"ltr":["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].includes(t.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const n=new I18n(e,t);return n.createInstance=I18n.createInstance,n}cloneInstance(e={},t=noop){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new I18n(i);void 0===e.debug&&void 0===e.prefix||(s.logger=s.logger.clone(e));if(["store","services","language"].forEach((e=>{s[e]=this[e]})),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},n){const e=Object.keys(this.store.data).reduce(((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce(((n,i)=>(n[i]={...e[t][i]},n)),e[t]),e)),{});s.store=new ResourceStore(e,i),s.services.resourceStore=s.store}if(e.interpolation){const t={...get().interpolation,...this.options.interpolation,...e.interpolation},n={...i,interpolation:t};s.services.interpolator=new Interpolator(n)}return s.translator=new Translator(s.services,i),s.translator.on("*",((e,...t)=>{s.emit(e,...t)})),s.init(i,t),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const instance=I18n.createInstance(),createInstance=instance.createInstance,dir=instance.dir,init=instance.init,loadResources=instance.loadResources,reloadResources=instance.reloadResources,use=instance.use,changeLanguage=instance.changeLanguage,getFixedT=instance.getFixedT,t=instance.t,exists=instance.exists,setDefaultNamespace=instance.setDefaultNamespace,hasLoadedNamespace=instance.hasLoadedNamespace,loadNamespaces=instance.loadNamespaces,loadLanguages=instance.loadLanguages;let notifyBox;const LSWMessageNotifier=class{author;constructor(e="Support"){this.author=e}newMessageNotify(e){const n=document.createElement("div");n.style.fontFamily='"Helvetica Neue",Arial,Helvetica,sans-serif',n.style.position="absolute",n.style.display="flex",n.style.width="300px",n.style.height="6rem",n.style.overflow="hidden",n.style.backgroundColor="white",n.style.boxShadow="0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)",n.style.maxWidth="24rem",n.style.borderRadius="0.75rem",n.style.bottom="19px",n.style.right="0";const i=document.createElement("div");i.style.marginLeft="0.625rem",i.style.marginRight="0.625rem",i.style.overflow="hidden",i.style.width="100%",i.style.cursor="pointer",i.addEventListener("click",(()=>{togglePopup(),notifyBox&¬ifyBox.removeChild(n)}));const s=document.createElement("p");s.textContent=t("support"),s.style.marginTop="0.375rem",s.style.fontSize="1rem",s.style.fontWeight="bold",s.style.color="peru",s.style.lineHeight="2rem",s.style.marginRight="0.75rem",s.style.overflow="hidden",s.style.textOverflow="ellipsis",s.style.whiteSpace="nowrap",s.style.marginBottom="0";const o=document.createElement("p");o.innerHTML=e,o.style.overflow="hidden",o.style.lineHeight="1.25rem",o.style.wordBreak="break-word",o.style.color="#7f7f7f",o.style.maxHeight="2.5rem",o.style.fontSize="small",o.style.marginTop="0";const r=document.createElement("button");r.style.width="4rem",r.style.cursor="pointer",r.style.outline="none",r.style.border="none",r.style.background="none";const a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.setAttribute("xmlns","http://www.w3.org/2000/svg"),a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("stroke-width","2"),a.setAttribute("stroke","rgba(31,41,55)"),a.setAttribute("fill","none"),a.style.width="1.75rem",a.style.height="1.75rem";const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M6 18L18 6M6 6l12 12"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("stroke-linecap","round"),a.appendChild(l),r.appendChild(a),i.appendChild(s),i.appendChild(o),n.appendChild(i),n.appendChild(r);const c=document.querySelector("#lsw_chat_popup");notifyBox&&c&&"none"==c.style.display&&(notifyBox.appendChild(n),setTimeout((()=>{notifyBox&¬ifyBox.removeChild(n)}),5e3)),r.addEventListener("click",(()=>{notifyBox&¬ifyBox.removeChild(n)}))}};function createNotifyBox(){if(notifyBox)return notifyBox;const e="-20,63".split(",").map((e=>Number(e)));return e[1]+=73,notifyBox=document.createElement("div"),notifyBox.style.display="flex",notifyBox.style.flexDirection="column",notifyBox.style[e[0]>0?"left":"right"]=Math.abs(e[0])+"px",notifyBox.style[e[1]>0?"bottom":"top"]=Math.abs(e[1])+"px",notifyBox.style.position="fixed",notifyBox.style.zIndex="500",document.body.appendChild(notifyBox),notifyBox}const messageNotifier=LSWMessageNotifier,assistant_service_API_URL=null;let operatorOnline=!1,tunnelHandlersInstalled=!1;function installTunnelHandlers(){tunnelHandlersInstalled||(tunnelHandlersInstalled=!0,subscribeWidgetWs((e=>{if("widget"===e.domain){if("operator_message"===e.type){const t=e.payload?.threadId,n=localStorage.getItem("aiwi_thread_id");if(t&&n&&t!==n)return;operatorOnline=!0;const i=String(e.payload?.text??"");return assistant_service_messageNotifier.newMessageNotify(i),void addMessage(i)}if("operator_disconnected"!==e.type){if("admin_presence"===e.type){const t=Boolean(e.payload?.online);window.dispatchEvent(new CustomEvent("lsw-widget-admin-presence",{detail:{online:t}}))}}else operatorOnline=!1}})))}function bootstrapWidgetSocketIntegration(){installTunnelHandlers(),onWidgetSocketOpen((()=>{const e=localStorage.getItem("aiwi_thread_id");e&&sendWidgetEnvelope("widget","thread_subscribe",{thread_id:e})}))}let activeRunStream=null;function streamEventDataString(e){if(null==e||"object"!=typeof e)return"";if(!("data"in e))return"";const t=e.data;return"string"==typeof t?t:null!=t?String(t):""}class AssistantRunStream{_lsAiWsStream=!0;closed=!1;removeGlobal=null;listeners=new Map;constructor(){activeRunStream&&activeRunStream.close(),activeRunStream=this,this.removeGlobal=subscribeWidgetWs((e=>{if(this.closed||activeRunStream!==this)return;if("widget"!==e.domain)return;if("ai_stream_end"===e.type)return activeRunStream===this&&(activeRunStream=null),this.closed=!0,this.removeGlobal?.(),this.removeGlobal=null,void this.listeners.clear();if("ai_stream"!==e.type)return;const t=String(e.payload?.event??""),n=e.payload.data,i={data:null==n?"":"string"==typeof n?n:JSON.stringify(n)};for(const e of this.listeners.get(t)??[])try{e(i)}catch(e){console.error(e)}}))}addEventListener(e,t){if(!t||"function"!=typeof t)return;const n=this.listeners.get(e)??[];n.push(t),this.listeners.set(e,n)}close(){this.closed||(this.closed=!0,activeRunStream===this&&(activeRunStream=null),this.removeGlobal?.(),this.removeGlobal=null,this.listeners.clear())}}function isRunStreamSource(e){return"object"==typeof e&&null!==e&&("undefined"!=typeof EventSource&&e instanceof EventSource||!0===e._lsAiWsStream)}let assistant_service_messageNotifier=new messageNotifier;const bugReport=new BugReport,typingIndicatorDiv=document.createElement("div");function replacePhoneNumbers(e){return e.replace(/\+?\d[\d\-\(\) ]{9,}\d/g,(e=>`${e}`))}function addReplyElement(e,t="",n){let i="";if("object"==typeof t){if(t.date){let e=new Date(t.date);i=`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}`}t=t.text||""}const s=document.createElement("div");s.style.position="relative",s.style.marginBottom="2em",s.className="flex";const o=document.createElement("div");o.style.position="relative",o.style.paddingRight="3em",o.classList.add("py-2","px-4","max-w-[70%]"),n?(s.style.justifyContent="flex-end",o.classList.add("me-message")):o.classList.add("you-message"),o.innerHTML=replacePhoneNumbers(t),s.appendChild(o),e.appendChild(s),e.scrollTop=e.scrollHeight;const r=document.createElement("div");return r.innerHTML=i,r.classList.add("clock"),o.appendChild(r),s}async function addMessageToStorage(e,t){let n=!1;const i="string"==typeof e?e:e.content,s=localStorage.getItem("aiwi_messages"),o=s?JSON.parse(s):[];o.length&&(n=!0),o.push({role:t?"user":"assistant",content:i,date:"string"==typeof e?(new Date).valueOf():e.date}),localStorage.setItem("aiwi_messages",JSON.stringify(o));const r=localStorage.getItem("aiwi_thread_id");return n&&r&&await widgetWsRpc("chat_notify",{thread:r},"chat_notify_ok",2e4).catch((e=>console.error("error chat notify",e))),n}async function addMessage(e,t){const n=messages;if(n){if(inputTextInChat&&(inputTextInChat.value=""),"object"==typeof e&&null!==e&&isRunStreamSource(e)){let t,i;return e.addEventListener("textCreated",(()=>{t=addReplyElement(n)})),e.addEventListener("typing",(()=>{i=addReplyElement(n,typingIndicatorDiv.outerHTML)})),e.addEventListener("textDelta",(e=>{const i=streamEventDataString(e),s=t.querySelector("div");s&&(s.innerHTML=g.parse(s.innerText+i).toString(),n.scrollTop=n.scrollHeight)})),void e.addEventListener("messageDone",(s=>{i?.parentNode&&i.parentNode.removeChild(i),e.close();const o=streamEventDataString(s);if(o)try{const e=JSON.parse(o);let i="";if(!e?.content?.length)return;if((i=e.content[0].text.value)||(i="Что-то пошло не так. Попробуйте позже пожалуйста."),/\[spam\]/.test(i))return void console.log("stop spam!");0,t?.querySelector("div")?t.querySelector("div").innerHTML=g.parse(i).toString():t=addReplyElement(n,{text:i,date:(new Date).valueOf()}),assistant_service_messageNotifier.newMessageNotify(i),addMessageToStorage(i)}catch(e){console.error("error processing message",e)}}))}("string"!=typeof e&&e?e:[{role:t?"user":"assistant",content:e,date:(new Date).valueOf()}]).forEach((t=>{let i="user"==t.role;if(t.content){if(!i&&/\[spam\]/.test(t.content))return void console.log("stop spam!");0,addReplyElement(n,{text:g.parse(t.content).toString(),date:t.date},i)}if(e){const n=localStorage.getItem("aiwi_messages"),s=n?JSON.parse(n):[];s.push({role:i?"user":"assistant",content:t.content,date:(new Date).valueOf()}),"string"==typeof e&&localStorage.setItem("aiwi_messages",JSON.stringify(s))}}))}else console.log("chatMessages div not found")}function createTonnel(){installTunnelHandlers();const e=localStorage.getItem("aiwi_thread_id");e&&sendWidgetEnvelope("widget","thread_subscribe",{thread_id:e})}function clearChat(){messages&&(messages.innerHTML="")}async function createThread(){const e=localStorage.getItem("aiwi_thread_id"),t=localStorage.getItem("aiwi_messages");if(e)return t&&(clearChat(),addMessage(JSON.parse(t))),t?null:e;const n="Здравствуйте, могу проконсультировать по услугам",i={};let s;n&&(i.messages=[{role:"assistant",content:n}]),"undefined"!=typeof document&&document.referrer&&(i.referer=document.referrer),"undefined"!=typeof navigator&&(i.userAgent=navigator.userAgent);try{s=await widgetWsRpcResult("thread_create",i,"thread_create_ok",6e4)}catch(e){return void console.error("createThread:",e)}if(s?.id){const e=localStorage.getItem("aiwi_thread_id");return e&&e!==s.id&&sendWidgetEnvelope("widget","thread_unsubscribe",{}),localStorage.setItem("aiwi_thread_id",s.id),createTonnel(),s.id}}async function getMessages(){const e=localStorage.getItem("aiwi_thread_id");if(!e)return"Проблема ;(";const t=await fetch(`${assistant_service_API_URL}/assistants/threads/${e}/messages`).then((e=>e.json())).catch((e=>console.log("error",e)));return t?.body?.data?.length&&"assistant"==t.body.data[0].role?t.body.data[0].content[0].text.value:"Что-то произошло. Не смогу ответить ("}function sendMessageByThread(e){}async function tryAiUserMessage(e,t){const n=new AssistantRunStream;try{const i=await widgetWsRpcResult("ai_user_message",{thread_id:e,content:t},"ai_message_ok",12e4);if("relay_only"===i.mode)return n.close(),"";if("stream"===i.mode)return n;n.close()}catch(e){throw n.close(),e}return""}async function sendMessage(e){let t=localStorage.getItem("aiwi_thread_id")||await createThread();if(!t)return"Не могу ответить. Попробуйте позже. ";if(operatorOnline){try{await widgetWsRpc("message_to_admin",{thread_id:t,message:e},"message_to_admin_ok",25e3)}catch{operatorOnline=!1}return""}addMessage();try{const n=await tryAiUserMessage(t,e);return n}catch(n){const i=n instanceof Error?n.message:String(n);if(/not found|Thread not found|404/i.test(i)||/Чат устарел|устарел/i.test(i)){if(localStorage.removeItem("aiwi_thread_id"),t=await createThread(),!t)return"Не могу ответить. Попробуйте позже. ";try{const n=await tryAiUserMessage(t,e);return n}catch(n){bugReport.report({url:"ws:ai_user_message",headers:"{}",body:{thread_id:t,content:e},error:n})}}else bugReport.report({url:"ws:ai_user_message",headers:"{}",body:{thread_id:t,content:e},error:n})}return"Что-то идет не так. Попробуйте позже."}typingIndicatorDiv.classList.add("typing-indicator"),typingIndicatorDiv.classList.add("flex"),typingIndicatorDiv.classList.add("items-center"),typingIndicatorDiv.classList.add("space-x-1"),typingIndicatorDiv.innerHTML='\n \n ';var metric_service=__webpack_require__(608);Reflect.defineProperty(attention,"name",{value:"default",configurable:!0});let atDiv=document.createElement("div");const defaultImg="data:image/webp;base64,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";function attention(e,t=!1){const n=document.createElement("style");n.innerHTML=`\n .lswa-widget-button-popup-show {\n display: block;\n -webkit-animation: show .4s linear forwards;\n animation: show .4s linear forwards;\n }\n .lswa-widget-button-popup-btn-hide {\n position: absolute;\n top: 4px;\n right: 4px;\n display: inline-block;\n height: 20px;\n width: 20px;\n background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2210%22%20height%3D%2210%22%20viewBox%3D%220%200%2010%2010%22%3E%3Cpath%20fill%3D%22%23525C68%22%20fill-rule%3D%22evenodd%22%20d%3D%22M6.41%205.07l2.867-2.864-1.34-1.34L5.07%203.73%202.207.867l-1.34%201.34L3.73%205.07.867%207.938l1.34%201.34L5.07%206.41l2.867%202.867%201.34-1.34L6.41%205.07z%22/%3E%3C/svg%3E');\n background-repeat: no-repeat;\n background-position: center;\n opacity: .2;\n -webkit-transition: opacity .3s;\n transition: opacity .3s;\n cursor: pointer;\n }\n .lswa-widget-button-popup-inner {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-flow: row;\n flex-flow: row;\n }\n .lswa-widget-button-popup-image {\n margin: 0 10px 0 0;\n width: 42px;\n text-align: center;\n }\n .lswa-widget-button-popup-image-item {\n display: inline-block;\n width: 42px;\n height: 42px;\n border-radius: 100%;\n background-repeat: no-repeat;\n background-position: center;\n background-size: cover;\n background-image: url(${defaultImg});\n }\n .lswa-widget-button-popup-name {\n font: bold 14px "Helvetica Neue",Arial,Helvetica,sans-serif;\n color: #000;\n }\n .lswa-widget-button-popup-description {\n margin: 4px 0 0 0;\n font: 13px "Helvetica Neue",Arial,Helvetica,sans-serif;\n color: #424956;\n }\n .lswa-widget-button-popup-triangle {\n position: absolute;\n display: block;\n width: 8px;\n height: 8px;\n background: #fff;\n border-right: 1px solid #aaaaaa82;\n border-bottom: 1px solid #aaaaaa82;\n bottom: 20px;\n }\n .lswa-widget-button-popup {\n padding: 12px 20px 12px 14px;\n max-width: 312px;\n border: 1px solid #aaaaaa82;\n background: #fff;\n border-radius: 15px;\n box-sizing: border-box;\n z-index: 1;\n cursor: pointer;\n }\n `,e.append(n),atDiv.style.display="none",atDiv.style.position="relative",atDiv.classList.add("lswa-widget-button-popup","lswa-widget-button-popup-show");const i=document.createElement("span");i.classList.add("lswa-widget-button-popup-btn-hide"),i.addEventListener("click",(()=>{atDiv.style.display="none"})),atDiv.innerHTML=`\n