bariweb-widget 0.1.20 → 0.1.21

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.
@@ -1,4 +1,4 @@
1
- import { n as e, r as t, t as n } from "./Watcher-CrSaF4Ov.js";
1
+ import { n as e, r as t, t as n } from "./Watcher-DBoOp_Qp.js";
2
2
  //#region src/lib/AdminUI.ts
3
3
  var r = "\n #bw-admin-panel {\n position: fixed;\n bottom: 160px;\n right: 20px;\n z-index: 2147483647;\n width: 320px;\n background: #0f172a;\n border: 1px solid #334155;\n border-radius: 16px;\n padding: 16px;\n box-shadow: 0 12px 50px rgba(0,0,0,0.6);\n font-family: Inter, system-ui, sans-serif;\n color: #f1f5f9;\n transition: border-color 0.3s;\n }\n #bw-admin-panel.trained {\n border-color: #10b981;\n }\n #bw-admin-panel.discovering {\n border-color: #a78bfa;\n }\n\n .bw-panel-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bw-panel-title {\n font-size: 13px;\n font-weight: 700;\n color: #a78bfa;\n }\n .bw-panel-close {\n background: none;\n border: none;\n color: #64748b;\n cursor: pointer;\n font-size: 16px;\n padding: 0;\n line-height: 1;\n }\n .bw-panel-close:hover { color: #f87171; }\n\n .bw-status-box {\n background: #1e293b;\n border-radius: 10px;\n padding: 12px;\n margin-bottom: 12px;\n border: 1px solid #334155;\n transition: all 0.3s;\n }\n .bw-status-box.trained {\n border-color: #10b981;\n background: rgba(16, 185, 129, 0.08);\n }\n .bw-status-box.draft {\n border-color: #f59e0b;\n background: rgba(245, 158, 11, 0.05);\n }\n\n .bw-status-indicator {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 6px;\n }\n .bw-status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .bw-status-dot.active { background: #4ade80; box-shadow: 0 0 8px #4ade80; animation: bw-pulse 2s infinite; }\n .bw-status-dot.draft { background: #f59e0b; }\n .bw-status-dot.idle { background: #475569; }\n\n @keyframes bw-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.4; }\n }\n\n .bw-status-text {\n font-size: 11px;\n font-weight: 600;\n }\n .bw-status-text.trained { color: #4ade80; }\n .bw-status-text.draft { color: #f59e0b; }\n .bw-status-text.idle { color: #94a3b8; }\n\n .bw-label-display {\n font-size: 14px;\n font-weight: 700;\n color: #e2e8f0;\n margin: 4px 0;\n word-break: break-word;\n }\n .bw-desc-display {\n font-size: 11px;\n color: #94a3b8;\n line-height: 1.4;\n margin-top: 4px;\n }\n\n .bw-fp-mini {\n font-family: monospace;\n font-size: 9px;\n color: #475569;\n margin-bottom: 10px;\n word-break: break-all;\n }\n\n .bw-tokens-list {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n }\n .bw-token-tag {\n background: #334155;\n color: #e2e8f0;\n font-size: 9px;\n padding: 2px 6px;\n border-radius: 4px;\n cursor: help;\n transition: all 0.15s;\n }\n .bw-token-tag:hover {\n background: #7c3aed;\n color: white;\n transform: translateY(-1px);\n }\n\n .bw-discovery-bar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 8px 10px;\n background: rgba(167, 139, 250, 0.08);\n border: 1px solid rgba(167, 139, 250, 0.2);\n border-radius: 8px;\n font-size: 10px;\n color: #a78bfa;\n margin-top: 8px;\n }\n .bw-discovery-bar .spinner {\n width: 12px;\n height: 12px;\n border: 2px solid rgba(167, 139, 250, 0.3);\n border-top-color: #a78bfa;\n border-radius: 50%;\n animation: bw-spin 0.8s linear infinite;\n }\n @keyframes bw-spin {\n to { transform: rotate(360deg); }\n }\n\n .bw-highlight-rect {\n position: absolute;\n pointer-events: none;\n border: 2px solid #7c3aed;\n background: rgba(124, 58, 237, 0.1);\n box-shadow: 0 0 10px #7c3aed;\n z-index: 100000;\n border-radius: 4px;\n transition: all 0.15s ease-out;\n }\n", i = null, a = null;
4
4
  function o() {
@@ -194,7 +194,7 @@ var m = new class {
194
194
  if (n) {
195
195
  this._isDiscovering = !0;
196
196
  try {
197
- let r = await fetch("http://localhost:8000/v1/training/discover", {
197
+ let r = await fetch("https://aidyn-backend.gitlabapp.alem.ai/v1/training/discover", {
198
198
  method: "POST",
199
199
  headers: {
200
200
  "Content-Type": "application/json",
@@ -4,7 +4,7 @@
4
4
 
5
5
  `);p=a.pop()??``;for(let e of a){let t=e.split(`
6
6
  `),a=[],o;for(let e of t)if(e.startsWith(`data:`))a.push(e.replace(/^data:\s*/,``));else if(e.startsWith(`event:`))o=e.replace(/^event:\s*/,``);else if(e.startsWith(`id:`))d=e.replace(/^id:\s*/,``);else if(e.startsWith(`retry:`)){let t=Number.parseInt(e.replace(/^retry:\s*/,``),10);Number.isNaN(t)||(c=t)}let s,l=!1;if(a.length){let e=a.join(`
7
- `);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,h),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;await f(Math.min(c*2**(p-1),s??3e4))}}}()}},a=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},o=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},s=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},c=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(o(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let s=a(r),c=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):l({allowReserved:e,name:n,value:t})).join(s);return r===`label`||r===`matrix`?s+c:c},l=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},u=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=s(r),c=Object.entries(i).map(([t,i])=>l({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+c:c},d=/\{[^{}]+\}/g,f=({path:e,url:t})=>{let n=t,r=t.match(d);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,c({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,u({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${l({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},p=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=f({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function m(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var h=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},ee=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=c({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=u({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=l({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},te=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},ne=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1,re=async({security:e,...t})=>{for(let n of e){if(ne(t,n.name))continue;let e=await h(n,t.auth);if(!e)continue;let r=n.name??`Authorization`;switch(n.in){case`query`:t.query||={},t.query[r]=e;break;case`cookie`:t.headers.append(`Cookie`,`${r}=${e}`);break;default:t.headers.set(r,e);break}}},ie=e=>p({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:ee(e.querySerializer),url:e.url}),ae=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=se(e.headers,t.headers),n},oe=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},se=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?oe(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},ce=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},le=()=>({error:new ce,request:new ce,response:new ce}),ue=ee({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),de={"Content-Type":`application/json`},fe=(e={})=>({...r,headers:de,parseAs:`auto`,querySerializer:ue,...e}),pe=((e={})=>{let t=ae(fe(),e),n=()=>({...t}),r=e=>(t=ae(t,e),n()),a=le(),o=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:se(t.headers,e.headers),serializedBody:void 0};return n.security&&await re({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`),{opts:n,url:ie(n)}},s=async e=>{let{opts:t,url:n}=await o(e),r={redirect:`follow`,...t,body:m(t)},i=new Request(n,r);for(let e of a.request.fns)e&&(i=await e(i,t));let s=t.fetch,c;try{c=await s(i)}catch(e){let n=e;for(let r of a.error.fns)r&&(n=await r(e,void 0,i,t));if(n||={},t.throwOnError)throw n;return t.responseStyle===`data`?void 0:{error:n,request:i,response:void 0}}for(let e of a.response.fns)e&&(c=await e(c,i,t));let l={request:i,response:c};if(c.ok){let e=(t.parseAs===`auto`?te(c.headers.get(`Content-Type`)):t.parseAs)??`json`;if(c.status===204||c.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await c[e]();break;case`formData`:n=new FormData;break;case`stream`:n=c.body;break;default:n={};break}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await c[e]();break;case`json`:{let e=await c.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?c.body:{data:c.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await c.text(),d;try{d=JSON.parse(u)}catch{}let f=d??u,p=f;for(let e of a.error.fns)e&&(p=await e(f,c,i,t));if(p||={},t.throwOnError)throw p;return t.responseStyle===`data`?void 0:{error:p,...l}},c=e=>t=>s({...t,method:e}),l=e=>async t=>{let{opts:n,url:r}=await o(t);return i({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of a.request.fns)e&&(r=await e(r,n));return r},serializedBody:m(n),url:r})};return{buildUrl:e=>ie({...t,...e}),connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),getConfig:n,head:c(`HEAD`),interceptors:a,options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),request:s,setConfig:r,sse:{connect:l(`CONNECT`),delete:l(`DELETE`),get:l(`GET`),head:l(`HEAD`),options:l(`OPTIONS`),patch:l(`PATCH`),post:l(`POST`),put:l(`PUT`),trace:l(`TRACE`)},trace:c(`TRACE`)}})(fe({baseUrl:`http://localhost:8000`})),g=globalThis,me=g.ShadowRoot&&(g.ShadyCSS===void 0||g.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,_=Symbol(),he=new WeakMap,ge=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==_)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(me&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=he.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&he.set(t,e))}return e}toString(){return this.cssText}},_e=e=>new ge(typeof e==`string`?e:e+``,void 0,_),ve=(e,...t)=>new ge(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,_),ye=(e,t)=>{if(me)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=g.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},be=me?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return _e(t)})(e):e,{is:xe,defineProperty:Se,getOwnPropertyDescriptor:Ce,getOwnPropertyNames:we,getOwnPropertySymbols:Te,getPrototypeOf:Ee}=Object,v=globalThis,De=v.trustedTypes,Oe=De?De.emptyScript:``,ke=v.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?Oe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Ae=(e,t)=>!xe(e,t),je={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:Ae};Symbol.metadata??=Symbol(`metadata`),v.litPropertyMetadata??=new WeakMap;var x=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=je){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Se(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=Ce(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??je}static _$Ei(){if(this.hasOwnProperty(y(`elementProperties`)))return;let e=Ee(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y(`properties`))){let e=this.properties,t=[...we(e),...Te(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(be(e))}else e!==void 0&&t.push(be(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ye(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?b:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?b:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??Ae)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};x.elementStyles=[],x.shadowRootOptions={mode:`open`},x[y(`elementProperties`)]=new Map,x[y(`finalized`)]=new Map,ke?.({ReactiveElement:x}),(v.reactiveElementVersions??=[]).push(`2.1.2`);var S=globalThis,Me=e=>e,C=S.trustedTypes,Ne=C?C.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,w=`lit$${Math.random().toFixed(9).slice(2)}$`,Fe=`?`+w,Ie=`<${Fe}>`,T=document,E=()=>T.createComment(``),D=e=>e===null||typeof e!=`object`&&typeof e!=`function`,O=Array.isArray,Le=e=>O(e)||typeof e?.[Symbol.iterator]==`function`,Re=`[
7
+ `);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,h),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;await f(Math.min(c*2**(p-1),s??3e4))}}}()}},a=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},o=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},s=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},c=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(o(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let s=a(r),c=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):l({allowReserved:e,name:n,value:t})).join(s);return r===`label`||r===`matrix`?s+c:c},l=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},u=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=s(r),c=Object.entries(i).map(([t,i])=>l({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+c:c},d=/\{[^{}]+\}/g,f=({path:e,url:t})=>{let n=t,r=t.match(d);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,c({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,u({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${l({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},p=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=f({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function m(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var h=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},ee=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=c({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=u({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=l({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},te=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},ne=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1,re=async({security:e,...t})=>{for(let n of e){if(ne(t,n.name))continue;let e=await h(n,t.auth);if(!e)continue;let r=n.name??`Authorization`;switch(n.in){case`query`:t.query||={},t.query[r]=e;break;case`cookie`:t.headers.append(`Cookie`,`${r}=${e}`);break;default:t.headers.set(r,e);break}}},ie=e=>p({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:ee(e.querySerializer),url:e.url}),ae=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=se(e.headers,t.headers),n},oe=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},se=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?oe(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},ce=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},le=()=>({error:new ce,request:new ce,response:new ce}),ue=ee({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),de={"Content-Type":`application/json`},fe=(e={})=>({...r,headers:de,parseAs:`auto`,querySerializer:ue,...e}),pe=((e={})=>{let t=ae(fe(),e),n=()=>({...t}),r=e=>(t=ae(t,e),n()),a=le(),o=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:se(t.headers,e.headers),serializedBody:void 0};return n.security&&await re({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`),{opts:n,url:ie(n)}},s=async e=>{let{opts:t,url:n}=await o(e),r={redirect:`follow`,...t,body:m(t)},i=new Request(n,r);for(let e of a.request.fns)e&&(i=await e(i,t));let s=t.fetch,c;try{c=await s(i)}catch(e){let n=e;for(let r of a.error.fns)r&&(n=await r(e,void 0,i,t));if(n||={},t.throwOnError)throw n;return t.responseStyle===`data`?void 0:{error:n,request:i,response:void 0}}for(let e of a.response.fns)e&&(c=await e(c,i,t));let l={request:i,response:c};if(c.ok){let e=(t.parseAs===`auto`?te(c.headers.get(`Content-Type`)):t.parseAs)??`json`;if(c.status===204||c.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await c[e]();break;case`formData`:n=new FormData;break;case`stream`:n=c.body;break;default:n={};break}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await c[e]();break;case`json`:{let e=await c.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?c.body:{data:c.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await c.text(),d;try{d=JSON.parse(u)}catch{}let f=d??u,p=f;for(let e of a.error.fns)e&&(p=await e(f,c,i,t));if(p||={},t.throwOnError)throw p;return t.responseStyle===`data`?void 0:{error:p,...l}},c=e=>t=>s({...t,method:e}),l=e=>async t=>{let{opts:n,url:r}=await o(t);return i({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of a.request.fns)e&&(r=await e(r,n));return r},serializedBody:m(n),url:r})};return{buildUrl:e=>ie({...t,...e}),connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),getConfig:n,head:c(`HEAD`),interceptors:a,options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),request:s,setConfig:r,sse:{connect:l(`CONNECT`),delete:l(`DELETE`),get:l(`GET`),head:l(`HEAD`),options:l(`OPTIONS`),patch:l(`PATCH`),post:l(`POST`),put:l(`PUT`),trace:l(`TRACE`)},trace:c(`TRACE`)}})(fe({baseUrl:`https://aidyn-backend.gitlabapp.alem.ai`})),g=globalThis,me=g.ShadowRoot&&(g.ShadyCSS===void 0||g.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,_=Symbol(),he=new WeakMap,ge=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==_)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(me&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=he.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&he.set(t,e))}return e}toString(){return this.cssText}},_e=e=>new ge(typeof e==`string`?e:e+``,void 0,_),ve=(e,...t)=>new ge(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,_),ye=(e,t)=>{if(me)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=g.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},be=me?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return _e(t)})(e):e,{is:xe,defineProperty:Se,getOwnPropertyDescriptor:Ce,getOwnPropertyNames:we,getOwnPropertySymbols:Te,getPrototypeOf:Ee}=Object,v=globalThis,De=v.trustedTypes,Oe=De?De.emptyScript:``,ke=v.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?Oe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Ae=(e,t)=>!xe(e,t),je={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:Ae};Symbol.metadata??=Symbol(`metadata`),v.litPropertyMetadata??=new WeakMap;var x=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=je){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Se(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=Ce(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??je}static _$Ei(){if(this.hasOwnProperty(y(`elementProperties`)))return;let e=Ee(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y(`properties`))){let e=this.properties,t=[...we(e),...Te(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(be(e))}else e!==void 0&&t.push(be(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ye(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?b:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?b:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??Ae)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};x.elementStyles=[],x.shadowRootOptions={mode:`open`},x[y(`elementProperties`)]=new Map,x[y(`finalized`)]=new Map,ke?.({ReactiveElement:x}),(v.reactiveElementVersions??=[]).push(`2.1.2`);var S=globalThis,Me=e=>e,C=S.trustedTypes,Ne=C?C.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,w=`lit$${Math.random().toFixed(9).slice(2)}$`,Fe=`?`+w,Ie=`<${Fe}>`,T=document,E=()=>T.createComment(``),D=e=>e===null||typeof e!=`object`&&typeof e!=`function`,O=Array.isArray,Le=e=>O(e)||typeof e?.[Symbol.iterator]==`function`,Re=`[
8
8
  \f\r]`,k=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ze=/-->/g,Be=/>/g,A=RegExp(`>|${Re}(?:([^\\s"'>=/]+)(${Re}*=${Re}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Ve=/'/g,He=/"/g,Ue=/^(?:script|style|textarea|title)$/i,j=(e=>(t,...n)=>({_$litType$:e,strings:t,values:n}))(1),M=Symbol.for(`lit-noChange`),N=Symbol.for(`lit-nothing`),We=new WeakMap,P=T.createTreeWalker(T,129);function Ge(e,t){if(!O(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var Ke=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=k;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===k?c[1]===`!--`?o=ze:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=A):(Ue.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=A):o=Be:o===A?c[0]===`>`?(o=i??k,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?A:c[3]===`"`?He:Ve):o===He||o===Ve?o=A:o===ze||o===Be?o=k:(o=A,i=void 0);let d=o===A&&e[t+1].startsWith(`/>`)?` `:``;a+=o===k?n+Ie:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+w+d):n+w+(l===-2?t:d)}return[Ge(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},F=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=Ke(t,n);if(this.el=e.createElement(l,r),P.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=P.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(w),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?Je:r[1]===`?`?Ye:r[1]===`@`?Xe:R}),i.removeAttribute(e)}else e.startsWith(w)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ue.test(i.tagName)){let e=i.textContent.split(w),t=e.length-1;if(t>0){i.textContent=C?C.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],E()),P.nextNode(),c.push({type:2,index:++a});i.append(e[t],E())}}}else if(i.nodeType===8)if(i.data===Fe)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(w,e+1))!==-1;)c.push({type:7,index:a}),e+=w.length-1}a++}}static createElement(e,t){let n=T.createElement(`template`);return n.innerHTML=e,n}};function I(e,t,n=e,r){if(t===M)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=D(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=I(e,i._$AS(e,t.values),i,r)),t}var qe=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??T).importNode(t,!0);P.currentNode=r;let i=P.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new L(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new Ze(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=P.nextNode(),a++)}return P.currentNode=T,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},L=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=N,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=I(this,e,t),D(e)?e===N||e==null||e===``?(this._$AH!==N&&this._$AR(),this._$AH=N):e!==this._$AH&&e!==M&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Le(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==N&&D(this._$AH)?this._$AA.nextSibling.data=e:this.T(T.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=F.createElement(Ge(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new qe(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=We.get(e.strings);return t===void 0&&We.set(e.strings,t=new F(e)),t}k(t){O(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(E()),this.O(E()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Me(e).nextSibling;Me(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},R=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=N,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=N}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=I(this,e,t,0),a=!D(e)||e!==this._$AH&&e!==M,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=I(this,r[n+o],t,o),s===M&&(s=this._$AH[o]),a||=!D(s)||s!==this._$AH[o],s===N?e=N:e!==N&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===N?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},Je=class extends R{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===N?void 0:e}},Ye=class extends R{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==N)}},Xe=class extends R{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=I(this,e,t,0)??N)===M)return;let n=this._$AH,r=e===N&&n!==N||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==N&&(n===N||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},Ze=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){I(this,e)}},Qe=S.litHtmlPolyfillSupport;Qe?.(F,L),(S.litHtmlVersions??=[]).push(`3.3.2`);var $e=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new L(t.insertBefore(E(),e),e,void 0,n??{})}return i._$AI(e),i},z=globalThis,B=class extends x{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=$e(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return M}};B._$litElement$=!0,B.finalized=!0,z.litElementHydrateSupport?.({LitElement:B});var et=z.litElementPolyfillSupport;et?.({LitElement:B}),(z.litElementVersions??=[]).push(`4.2.2`);var tt=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},nt={attribute:!0,type:String,converter:b,reflect:!1,hasChanged:Ae},rt=(e=nt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function it(e){return(t,n)=>typeof n==`object`?rt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function V(e){return it({...e,state:!0,attribute:!1})}var at=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function ot(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return at(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return at(n,r,{get(){return a(this)}})}}var st={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ct=e=>(...t)=>({_$litDirective$:e,values:t}),lt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},H=class extends lt{constructor(e){if(super(e),this.it=N,e.type!==st.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===N||e==null)return this._t=void 0,this.it=e;if(e===M)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};H.directiveName=`unsafeHTML`,H.resultType=1;var ut=ct(H),U=e=>j`${ut(`
9
9
  <svg
10
10
  viewBox="0 0 24 24"
@@ -879,7 +879,7 @@
879
879
  html[data-bw-has-custom-content] div:not(bw-widget *) {
880
880
  color: var(--bw-custom-content) !important;
881
881
  }
882
- `}_applySettings(){let e=document.documentElement;this._ensureGlobalStyles(),e.style.setProperty(`--bw-grayscale`,this.settings.monochrome?`100%`:`0%`);let t=1;this.settings.lowSaturation&&(t=.3),this.settings.highSaturation&&(t=2.5),e.style.setProperty(`--bw-saturation`,t.toString()),this.settings.customBgHue===null?e.removeAttribute(`data-bw-has-custom-bg`):(e.style.setProperty(`--bw-custom-bg`,`hsl(${this.settings.customBgHue}, 50%, 95%)`),e.setAttribute(`data-bw-has-custom-bg`,``)),this.settings.customHeaderHue===null?e.removeAttribute(`data-bw-has-custom-header`):(e.style.setProperty(`--bw-custom-header`,`hsl(${this.settings.customHeaderHue}, 70%, 30%)`),e.setAttribute(`data-bw-has-custom-header`,``)),this.settings.customContentHue===null?e.removeAttribute(`data-bw-has-custom-content`):(e.style.setProperty(`--bw-custom-content`,`hsl(${this.settings.customContentHue}, 60%, 40%)`),e.setAttribute(`data-bw-has-custom-content`,``)),this.settings.textScale>1?e.style.fontSize=`${this.settings.textScale*100}%`:e.style.fontSize=``;let n={"data-bw-monochrome":this.settings.monochrome,"data-bw-dark-high-contrast":this.settings.darkHighContrast,"data-bw-bright-high-contrast":this.settings.brightHighContrast,"data-bw-contrast-mode":this.settings.contrastMode,"data-bw-text-spacing":this.settings.textSpacing,"data-bw-dyslexic":this.settings.dyslexicFont,"data-bw-focus-visualizer":this.settings.focusVisualizer,"data-bw-cursor-magnifier":this.settings.cursorMagnifier,"data-bw-no-animations":this.settings.animationsDisabled,"data-bw-link-highlight":this.settings.linkHighlight,"data-bw-highlight-headers":this.settings.highlightHeaders,"data-bw-enlarge-buttons":this.settings.enlargeButtons};Object.entries(n).forEach(([t,n])=>{n?e.setAttribute(t,``):e.removeAttribute(t)});let r=this.host;r&&r.style.setProperty(`--bw-font-scale`,this.settings.textScale.toString())}toggleMonochrome(){this.settings.monochrome=!this.settings.monochrome,this._saveSettings()}toggleDarkHighContrast(){this.settings.darkHighContrast=!this.settings.darkHighContrast,this.settings.darkHighContrast&&(this.settings.brightHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleBrightHighContrast(){this.settings.brightHighContrast=!this.settings.brightHighContrast,this.settings.brightHighContrast&&(this.settings.darkHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleLowSaturation(){this.settings.lowSaturation=!this.settings.lowSaturation,this.settings.lowSaturation&&(this.settings.highSaturation=!1),this._saveSettings()}toggleHighSaturation(){this.settings.highSaturation=!this.settings.highSaturation,this.settings.highSaturation&&(this.settings.lowSaturation=!1),this._saveSettings()}toggleContrastMode(){this.settings.contrastMode=!this.settings.contrastMode,this.settings.contrastMode&&(this.settings.darkHighContrast=!1,this.settings.brightHighContrast=!1),this._saveSettings()}setCustomHue(e){this.settings.activeColorTab===`background`?this.settings.customBgHue=e:this.settings.activeColorTab===`header`?this.settings.customHeaderHue=e:this.settings.customContentHue=e,this._saveSettings()}resetCustomColors(){this.settings.customBgHue=null,this.settings.customHeaderHue=null,this.settings.customContentHue=null,this._saveSettings()}toggleHighlightHeaders(){this.settings.highlightHeaders=!this.settings.highlightHeaders,this._saveSettings()}toggleEnlargeButtons(){this.settings.enlargeButtons=!this.settings.enlargeButtons,this._saveSettings()}incrementTextScale(){this.settings.textScale>=1.5?this.settings.textScale=1:this.settings.textScale=parseFloat((this.settings.textScale+.1).toFixed(1)),this._saveSettings()}toggleTextSpacing(){this.settings.textSpacing=!this.settings.textSpacing,this._saveSettings()}toggleDyslexicFont(){this.settings.dyslexicFont=!this.settings.dyslexicFont,this._saveSettings()}toggleFocusVisualizer(){this.settings.focusVisualizer=!this.settings.focusVisualizer,this._saveSettings()}toggleCursorMagnifier(){this.settings.cursorMagnifier=!this.settings.cursorMagnifier,this._saveSettings()}toggleAnimations(){this.settings.animationsDisabled=!this.settings.animationsDisabled,this._saveSettings()}toggleLinkHighlight(){this.settings.linkHighlight=!this.settings.linkHighlight,this._saveSettings()}reset(){this.settings={...G},this._saveSettings()}};function K(e){try{let t=new URL(e),n=t.pathname;n=n.replace(vt,`:id`),n=n.replace(yt,`/:id`),n=n.replace(bt,`/:slug`),n=n.replace(xt,`/:id`);let r=new URLSearchParams;t.searchParams.forEach((e,t)=>{St.has(t)?r.set(`:${t}`,``):e.length<30&&!/^\d+$/.test(e)&&r.set(t,e)});let i=r.toString();return n.replace(/\/$/,``)+(i?`?${i}`:``)}catch{return e.replace(vt,`:id`).replace(/\/\d{1,20}(?=\/|$)/g,`/:id`).split(`?`)[0]}}function mt(e){let t=[`dialog`,`tooltip`,`menu`,`listbox`,`alertdialog`],n=e;for(;n&&n!==document.body;){let e=n.getAttribute(`role`)||``;if(t.includes(e)||n.hasAttribute(`data-radix-popper-content-wrapper`)||n.hasAttribute(`data-floating-ui-portal`))return!0;let r=typeof n.className==`string`?n.className:``;if(/popover|tooltip|dropdown-menu|floating|overlay/i.test(r))return!0;n=n.parentElement}return!1}function ht(e){let t=[`li`,`article`,`tr`,`dd`],n=e.parentElement,r=0;for(;n&&n!==document.body&&r<8;){let e=n.tagName.toLowerCase();if(t.includes(e))return!0;let i=typeof n.className==`string`?n.className:``;if(/\b(card|item|tile|post|entry|product|row-item|list-item|feed-item|cell)\b/i.test(i)){let e=n.parentElement?.children;if(e&&e.length>2)return!0}let a=n.getAttribute(`role`)||``;if(a===`listitem`||a===`row`||a===`gridcell`)return!0;n=n.parentElement,r++}return!1}function gt(e){let t=e,n=(t.getAttribute(`aria-label`)||t.getAttribute(`title`)||t.innerText||t.getAttribute(`placeholder`)||``).trim().toLowerCase();return!n||n.length<2||n.length>40||/^[\d\s₸$€%.,\-+:()]+$/.test(n)||/^\d{1,2}[./]\d{1,2}/.test(n)||Ct.has(n)?``:n.replace(/^[\p{Emoji}\s]+/u,``).trim().slice(0,30)}function _t(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(16)}function q(){let e=[],t=K(window.location.href);e.push(`route:${t}`);let n=document.querySelector(`h1`);if(n){let t=n.innerText?.trim().toLowerCase();t&&t.length>1&&t.length<50&&!/\d{3,}/.test(t)&&e.push(`h1:${t.slice(0,30)}`)}let r=Array.from(document.querySelectorAll(`input:not([type="hidden"]):not([type="submit"]):not([type="radio"]):not([type="checkbox"]), textarea, select`)).slice(0,8);for(let t of r){if(mt(t))continue;let n=t,r=(n.getAttribute(`name`)||n.getAttribute(`placeholder`)||n.getAttribute(`aria-label`)||``).toLowerCase().trim().slice(0,25);r&&r.length>1&&!Ct.has(r)&&e.push(`field:${r}`)}let i=Array.from(document.querySelectorAll(`nav a, [role="navigation"] a`)).slice(0,6);for(let t of i){if(mt(t))continue;let n=gt(t);n&&e.push(`nav:${n}`)}let a=document.querySelector(`main`)||document.querySelector(`[role="main"]`)||document.getElementById(`root`);return a&&Array.from(a.querySelectorAll(`button:not([aria-hidden="true"]), [role="button"]:not([aria-hidden="true"])`)).filter(e=>!mt(e)&&!ht(e)).map(gt).filter(e=>e.length>1).reduce((e,t)=>e.includes(t)?e:[...e,t],[]).slice(0,3).forEach(t=>e.push(`btn:${t}`)),[...new Set(e)].sort().slice(0,15)}function J(){return`bw-${_t(q().join(`|`))}`}var vt,yt,bt,xt,St,Ct,wt=t((()=>{vt=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,yt=/\/\d{1,20}(?=\/|$)/g,bt=/\/[a-z0-9]+(?:-[a-z0-9]+)*-\d+(?=\/|$)/g,xt=/\/[0-9a-f]{8,}(?=\/|$)/gi,St=new Set([`id`,`userId`,`user_id`,`orderId`,`order_id`,`itemId`,`item_id`,`productId`,`product_id`,`token`,`key`,`ref`,`code`,`session`]),Ct=new Set(`ok,ок,okay,close,закрыть,cancel,отмена,yes,da,no,нет,да,submit,отправить,back,назад,next,далее,more,ещё,еще,menu,меню,...,•,·,loading,загрузка,open,открыть,expand,collapse,toggle,sort`.split(`,`))}));function Tt(e,t){let n=new Set([...e].filter(e=>t.has(e))),r=new Set([...e,...t]);return r.size===0?1:n.size/r.size}var Et,Y,Dt=t((()=>{wt(),Et=class{constructor(e=1500){this._observer=null,this._debounceTimer=null,this._lastTokens=new Set,this._lastUrl=``,this._callbacks=[],this._discoveryCallbacks=[],this._isDiscovering=!1,this.isAutoDiscoveryEnabled=!1,this._debounceMs=e}start(){this._observer||(this._lastTokens=new Set(q()),this._lastUrl=K(window.location.href),this._observer=new MutationObserver(()=>{this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._onMutation(),this._debounceMs)}),this._observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}stop(){this._observer?.disconnect(),this._observer=null,this._debounceTimer&&clearTimeout(this._debounceTimer)}onStateChange(e){this._callbacks.push(e)}onDiscovery(e){this._discoveryCallbacks.push(e)}get isDiscovering(){return this._isDiscovering}getLiveSnapshot(){let e=(e,t)=>{if(e.hasAttribute(`bw-private`)||e.hasAttribute(`data-bw-private`))return`[MASKED]`;if(!t)return t;let n=t.replace(/(?:\d[ \-]*?){13,16}/g,`****`);return n=n.replace(/\b\d{12}\b/g,`****`),n},t=Array.from(document.querySelectorAll(`h1, h2`)).map(t=>e(t,t.innerText?.trim()||``)).filter(Boolean).slice(0,3),n=Array.from(document.querySelectorAll(`button, a[href], [role="button"]`)).map(t=>{let n=t,r=e(n,(n.getAttribute(`aria-label`)||n.innerText||``).trim().slice(0,60));return{id:n.id||``,text:r}}).filter(e=>e.text.length>0).slice(0,30);return{url:window.location.href,headings:t,fingerprint:J(),elements:n}}async _onMutation(){if(document.readyState!==`complete`)return;let e=K(window.location.href),t=new Set(q());if(t.size<2)return;let n=J(),r=e!==this._lastUrl,i=Tt(this._lastTokens,t);if(r||i<.55){let a=r?`URL: ${this._lastUrl} → ${e}`:`Sim: ${i.toFixed(2)}`;console.log(`[Watcher] Screen change (${a})`),this._lastUrl=e,this._lastTokens=t;let o=this.getLiveSnapshot();if(this.isAutoDiscoveryEnabled){let e=this._buildTypedTokens();this._discover(n,e).catch(()=>{})}this._callbacks.forEach(e=>e(o))}}_buildTypedTokens(){let e=new Set,t=[],n=(n,r)=>{let i=r.trim().slice(0,40);if(!i||i.length<2)return;let a=`${n}:${i}`;e.has(a)||(e.add(a),t.push(a))};return document.querySelectorAll(`button, [role="button"]`).forEach(e=>{let t=e.innerText?.trim();t&&n(`btn`,t)}),document.querySelectorAll(`a[href]`).forEach(e=>{let t=(e.getAttribute(`aria-label`)||e.innerText)?.trim();t&&n(`a`,t)}),document.querySelectorAll(`input:not([type=hidden]), textarea, select`).forEach(e=>{let t=e.placeholder||e.name;t&&n(`input`,t)}),t.slice(0,8)}async _discover(e,t){let n=localStorage.getItem(`bw_admin_token`);if(n){this._isDiscovering=!0;try{let r=await fetch(`http://localhost:8000/v1/training/discover`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({fingerprint:e,tokens:t,page_url:window.location.href})});if(r.ok){let e=await r.json();console.log(`[Discovery] ${e.status} — ${e.label}`),this._discoveryCallbacks.forEach(t=>t(e))}else r.status===401?(console.warn(`[Discovery] Token expired — disabling auto-discovery`),localStorage.removeItem(`bw_admin_token`),this.isAutoDiscoveryEnabled=!1):console.warn(`[Discovery] Server error ${r.status}`)}catch(e){console.warn(`[Discovery] Network error`,e)}finally{this._isDiscovering=!1}}}async forceDiscovery(){let e=[...new Set(q())],t=J();await this._discover(t,e)}},Y=new Et(1500)}));Dt();var Ot=`http://localhost:8000`,kt=class{constructor(e){this.isFixing=!1,this.simplifyEnabled=!1,this.autoA11yEnabled=!1,this._onParagraphKeydown=e=>{if(this.simplifyEnabled&&(e.key===`Enter`||e.key===` `)&&e.target instanceof HTMLElement){if(e.target.closest(`bw-widget`)||e.target.closest(`.bw-ai-tooltip`))return;let t=e.target.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(t)){e.preventDefault(),e.stopPropagation();let t=e.target.getBoundingClientRect();this._triggerSimplify(e.target,t.left+window.scrollX,t.bottom+window.scrollY)}}},this._onParagraphClick=async e=>{if(!this.simplifyEnabled)return;let t=e.target;if(t.closest(`bw-widget`)||t.closest(`.bw-ai-tooltip`))return;let n=t.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(n)){let n=t.innerText?.trim();n&&n.length>20&&(e.preventDefault(),e.stopPropagation(),this._triggerSimplify(t,e.pageX,e.pageY))}},(this.host=e).addController(this),this.simplifyEnabled=localStorage.getItem(`bw-ai-simplify`)===`true`,this.autoA11yEnabled=localStorage.getItem(`bw-ai-autofix`)===`true`,Y.onStateChange(()=>{this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup()}),this.autoA11yEnabled&&setTimeout(()=>this.fixMarkup(),1e3)}toggleAutoA11y(){this.autoA11yEnabled=!this.autoA11yEnabled,localStorage.setItem(`bw-ai-autofix`,this.autoA11yEnabled?`true`:`false`),this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup(),this.host.requestUpdate()}hostConnected(){}hostDisconnected(){this.simplifyEnabled&&(document.body.removeEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.classList.remove(`bw-simplify-mode`))}async fixMarkup(){this.isFixing=!0,this.host.requestUpdate();try{let e=[];if(document.querySelectorAll(`img:not([alt]), img[alt=""]`).forEach(t=>{t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-img-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)})}),document.querySelectorAll(`button:not([aria-label]), a:not([aria-label]), [role="button"]:not([aria-label])`).forEach(t=>{if(t.tagName===`INPUT`)return;let n=t;n.innerText?.trim()||n.textContent?.trim()||(t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-btn-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)}))}),e.length===0){console.log(`BariWeb AI: No broken elements found.`);return}console.log(`BariWeb AI: Found ${e.length} broken elements. Processing...`);let t=this.host.clientId||window.BariwebConfig?.clientId||``;for(let n=0;n<e.length;n+=10){let r=e.slice(n,n+10),i=await fetch(`${Ot}/v1/widget/a11y/fix`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({elements:r})});i.ok&&(await i.json()).forEach(e=>{let t=document.querySelector(`[data-bw-ai-id="${e.id}"]`);if(t&&e.value&&(e.attribute===`alt`||e.attribute===`aria-label`)){t.setAttribute(e.attribute,e.value);let n=t,r=n.style.outline;n.style.outline=`3px solid #10b981`,setTimeout(()=>{n.style.outline=r},2e3)}})}}finally{this.isFixing=!1,this.host.requestUpdate()}}toggleSimplify(){if(this.simplifyEnabled=!this.simplifyEnabled,this.simplifyEnabled){if(document.body.addEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.addEventListener(`keydown`,this._onParagraphKeydown,{capture:!0}),document.querySelectorAll(`p, h1, h2, h3, h4, h5, h6, li, article`).forEach(e=>{!e.hasAttribute(`tabindex`)&&e.textContent?.trim().length>20&&(e.setAttribute(`tabindex`,`0`),e.classList.add(`bw-simplify-focusable`))}),document.documentElement.style.setProperty(`--bw-simplify-cursor`,`help`),!document.getElementById(`bw-simplify-mode-style`)){let e=document.createElement(`style`);e.id=`bw-simplify-mode-style`,e.textContent=`
882
+ `}_applySettings(){let e=document.documentElement;this._ensureGlobalStyles(),e.style.setProperty(`--bw-grayscale`,this.settings.monochrome?`100%`:`0%`);let t=1;this.settings.lowSaturation&&(t=.3),this.settings.highSaturation&&(t=2.5),e.style.setProperty(`--bw-saturation`,t.toString()),this.settings.customBgHue===null?e.removeAttribute(`data-bw-has-custom-bg`):(e.style.setProperty(`--bw-custom-bg`,`hsl(${this.settings.customBgHue}, 50%, 95%)`),e.setAttribute(`data-bw-has-custom-bg`,``)),this.settings.customHeaderHue===null?e.removeAttribute(`data-bw-has-custom-header`):(e.style.setProperty(`--bw-custom-header`,`hsl(${this.settings.customHeaderHue}, 70%, 30%)`),e.setAttribute(`data-bw-has-custom-header`,``)),this.settings.customContentHue===null?e.removeAttribute(`data-bw-has-custom-content`):(e.style.setProperty(`--bw-custom-content`,`hsl(${this.settings.customContentHue}, 60%, 40%)`),e.setAttribute(`data-bw-has-custom-content`,``)),this.settings.textScale>1?e.style.fontSize=`${this.settings.textScale*100}%`:e.style.fontSize=``;let n={"data-bw-monochrome":this.settings.monochrome,"data-bw-dark-high-contrast":this.settings.darkHighContrast,"data-bw-bright-high-contrast":this.settings.brightHighContrast,"data-bw-contrast-mode":this.settings.contrastMode,"data-bw-text-spacing":this.settings.textSpacing,"data-bw-dyslexic":this.settings.dyslexicFont,"data-bw-focus-visualizer":this.settings.focusVisualizer,"data-bw-cursor-magnifier":this.settings.cursorMagnifier,"data-bw-no-animations":this.settings.animationsDisabled,"data-bw-link-highlight":this.settings.linkHighlight,"data-bw-highlight-headers":this.settings.highlightHeaders,"data-bw-enlarge-buttons":this.settings.enlargeButtons};Object.entries(n).forEach(([t,n])=>{n?e.setAttribute(t,``):e.removeAttribute(t)});let r=this.host;r&&r.style.setProperty(`--bw-font-scale`,this.settings.textScale.toString())}toggleMonochrome(){this.settings.monochrome=!this.settings.monochrome,this._saveSettings()}toggleDarkHighContrast(){this.settings.darkHighContrast=!this.settings.darkHighContrast,this.settings.darkHighContrast&&(this.settings.brightHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleBrightHighContrast(){this.settings.brightHighContrast=!this.settings.brightHighContrast,this.settings.brightHighContrast&&(this.settings.darkHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleLowSaturation(){this.settings.lowSaturation=!this.settings.lowSaturation,this.settings.lowSaturation&&(this.settings.highSaturation=!1),this._saveSettings()}toggleHighSaturation(){this.settings.highSaturation=!this.settings.highSaturation,this.settings.highSaturation&&(this.settings.lowSaturation=!1),this._saveSettings()}toggleContrastMode(){this.settings.contrastMode=!this.settings.contrastMode,this.settings.contrastMode&&(this.settings.darkHighContrast=!1,this.settings.brightHighContrast=!1),this._saveSettings()}setCustomHue(e){this.settings.activeColorTab===`background`?this.settings.customBgHue=e:this.settings.activeColorTab===`header`?this.settings.customHeaderHue=e:this.settings.customContentHue=e,this._saveSettings()}resetCustomColors(){this.settings.customBgHue=null,this.settings.customHeaderHue=null,this.settings.customContentHue=null,this._saveSettings()}toggleHighlightHeaders(){this.settings.highlightHeaders=!this.settings.highlightHeaders,this._saveSettings()}toggleEnlargeButtons(){this.settings.enlargeButtons=!this.settings.enlargeButtons,this._saveSettings()}incrementTextScale(){this.settings.textScale>=1.5?this.settings.textScale=1:this.settings.textScale=parseFloat((this.settings.textScale+.1).toFixed(1)),this._saveSettings()}toggleTextSpacing(){this.settings.textSpacing=!this.settings.textSpacing,this._saveSettings()}toggleDyslexicFont(){this.settings.dyslexicFont=!this.settings.dyslexicFont,this._saveSettings()}toggleFocusVisualizer(){this.settings.focusVisualizer=!this.settings.focusVisualizer,this._saveSettings()}toggleCursorMagnifier(){this.settings.cursorMagnifier=!this.settings.cursorMagnifier,this._saveSettings()}toggleAnimations(){this.settings.animationsDisabled=!this.settings.animationsDisabled,this._saveSettings()}toggleLinkHighlight(){this.settings.linkHighlight=!this.settings.linkHighlight,this._saveSettings()}reset(){this.settings={...G},this._saveSettings()}};function K(e){try{let t=new URL(e),n=t.pathname;n=n.replace(vt,`:id`),n=n.replace(yt,`/:id`),n=n.replace(bt,`/:slug`),n=n.replace(xt,`/:id`);let r=new URLSearchParams;t.searchParams.forEach((e,t)=>{St.has(t)?r.set(`:${t}`,``):e.length<30&&!/^\d+$/.test(e)&&r.set(t,e)});let i=r.toString();return n.replace(/\/$/,``)+(i?`?${i}`:``)}catch{return e.replace(vt,`:id`).replace(/\/\d{1,20}(?=\/|$)/g,`/:id`).split(`?`)[0]}}function mt(e){let t=[`dialog`,`tooltip`,`menu`,`listbox`,`alertdialog`],n=e;for(;n&&n!==document.body;){let e=n.getAttribute(`role`)||``;if(t.includes(e)||n.hasAttribute(`data-radix-popper-content-wrapper`)||n.hasAttribute(`data-floating-ui-portal`))return!0;let r=typeof n.className==`string`?n.className:``;if(/popover|tooltip|dropdown-menu|floating|overlay/i.test(r))return!0;n=n.parentElement}return!1}function ht(e){let t=[`li`,`article`,`tr`,`dd`],n=e.parentElement,r=0;for(;n&&n!==document.body&&r<8;){let e=n.tagName.toLowerCase();if(t.includes(e))return!0;let i=typeof n.className==`string`?n.className:``;if(/\b(card|item|tile|post|entry|product|row-item|list-item|feed-item|cell)\b/i.test(i)){let e=n.parentElement?.children;if(e&&e.length>2)return!0}let a=n.getAttribute(`role`)||``;if(a===`listitem`||a===`row`||a===`gridcell`)return!0;n=n.parentElement,r++}return!1}function gt(e){let t=e,n=(t.getAttribute(`aria-label`)||t.getAttribute(`title`)||t.innerText||t.getAttribute(`placeholder`)||``).trim().toLowerCase();return!n||n.length<2||n.length>40||/^[\d\s₸$€%.,\-+:()]+$/.test(n)||/^\d{1,2}[./]\d{1,2}/.test(n)||Ct.has(n)?``:n.replace(/^[\p{Emoji}\s]+/u,``).trim().slice(0,30)}function _t(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(16)}function q(){let e=[],t=K(window.location.href);e.push(`route:${t}`);let n=document.querySelector(`h1`);if(n){let t=n.innerText?.trim().toLowerCase();t&&t.length>1&&t.length<50&&!/\d{3,}/.test(t)&&e.push(`h1:${t.slice(0,30)}`)}let r=Array.from(document.querySelectorAll(`input:not([type="hidden"]):not([type="submit"]):not([type="radio"]):not([type="checkbox"]), textarea, select`)).slice(0,8);for(let t of r){if(mt(t))continue;let n=t,r=(n.getAttribute(`name`)||n.getAttribute(`placeholder`)||n.getAttribute(`aria-label`)||``).toLowerCase().trim().slice(0,25);r&&r.length>1&&!Ct.has(r)&&e.push(`field:${r}`)}let i=Array.from(document.querySelectorAll(`nav a, [role="navigation"] a`)).slice(0,6);for(let t of i){if(mt(t))continue;let n=gt(t);n&&e.push(`nav:${n}`)}let a=document.querySelector(`main`)||document.querySelector(`[role="main"]`)||document.getElementById(`root`);return a&&Array.from(a.querySelectorAll(`button:not([aria-hidden="true"]), [role="button"]:not([aria-hidden="true"])`)).filter(e=>!mt(e)&&!ht(e)).map(gt).filter(e=>e.length>1).reduce((e,t)=>e.includes(t)?e:[...e,t],[]).slice(0,3).forEach(t=>e.push(`btn:${t}`)),[...new Set(e)].sort().slice(0,15)}function J(){return`bw-${_t(q().join(`|`))}`}var vt,yt,bt,xt,St,Ct,wt=t((()=>{vt=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,yt=/\/\d{1,20}(?=\/|$)/g,bt=/\/[a-z0-9]+(?:-[a-z0-9]+)*-\d+(?=\/|$)/g,xt=/\/[0-9a-f]{8,}(?=\/|$)/gi,St=new Set([`id`,`userId`,`user_id`,`orderId`,`order_id`,`itemId`,`item_id`,`productId`,`product_id`,`token`,`key`,`ref`,`code`,`session`]),Ct=new Set(`ok,ок,okay,close,закрыть,cancel,отмена,yes,da,no,нет,да,submit,отправить,back,назад,next,далее,more,ещё,еще,menu,меню,...,•,·,loading,загрузка,open,открыть,expand,collapse,toggle,sort`.split(`,`))}));function Tt(e,t){let n=new Set([...e].filter(e=>t.has(e))),r=new Set([...e,...t]);return r.size===0?1:n.size/r.size}var Et,Y,Dt=t((()=>{wt(),Et=class{constructor(e=1500){this._observer=null,this._debounceTimer=null,this._lastTokens=new Set,this._lastUrl=``,this._callbacks=[],this._discoveryCallbacks=[],this._isDiscovering=!1,this.isAutoDiscoveryEnabled=!1,this._debounceMs=e}start(){this._observer||(this._lastTokens=new Set(q()),this._lastUrl=K(window.location.href),this._observer=new MutationObserver(()=>{this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._onMutation(),this._debounceMs)}),this._observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}stop(){this._observer?.disconnect(),this._observer=null,this._debounceTimer&&clearTimeout(this._debounceTimer)}onStateChange(e){this._callbacks.push(e)}onDiscovery(e){this._discoveryCallbacks.push(e)}get isDiscovering(){return this._isDiscovering}getLiveSnapshot(){let e=(e,t)=>{if(e.hasAttribute(`bw-private`)||e.hasAttribute(`data-bw-private`))return`[MASKED]`;if(!t)return t;let n=t.replace(/(?:\d[ \-]*?){13,16}/g,`****`);return n=n.replace(/\b\d{12}\b/g,`****`),n},t=Array.from(document.querySelectorAll(`h1, h2`)).map(t=>e(t,t.innerText?.trim()||``)).filter(Boolean).slice(0,3),n=Array.from(document.querySelectorAll(`button, a[href], [role="button"]`)).map(t=>{let n=t,r=e(n,(n.getAttribute(`aria-label`)||n.innerText||``).trim().slice(0,60));return{id:n.id||``,text:r}}).filter(e=>e.text.length>0).slice(0,30);return{url:window.location.href,headings:t,fingerprint:J(),elements:n}}async _onMutation(){if(document.readyState!==`complete`)return;let e=K(window.location.href),t=new Set(q());if(t.size<2)return;let n=J(),r=e!==this._lastUrl,i=Tt(this._lastTokens,t);if(r||i<.55){let a=r?`URL: ${this._lastUrl} → ${e}`:`Sim: ${i.toFixed(2)}`;console.log(`[Watcher] Screen change (${a})`),this._lastUrl=e,this._lastTokens=t;let o=this.getLiveSnapshot();if(this.isAutoDiscoveryEnabled){let e=this._buildTypedTokens();this._discover(n,e).catch(()=>{})}this._callbacks.forEach(e=>e(o))}}_buildTypedTokens(){let e=new Set,t=[],n=(n,r)=>{let i=r.trim().slice(0,40);if(!i||i.length<2)return;let a=`${n}:${i}`;e.has(a)||(e.add(a),t.push(a))};return document.querySelectorAll(`button, [role="button"]`).forEach(e=>{let t=e.innerText?.trim();t&&n(`btn`,t)}),document.querySelectorAll(`a[href]`).forEach(e=>{let t=(e.getAttribute(`aria-label`)||e.innerText)?.trim();t&&n(`a`,t)}),document.querySelectorAll(`input:not([type=hidden]), textarea, select`).forEach(e=>{let t=e.placeholder||e.name;t&&n(`input`,t)}),t.slice(0,8)}async _discover(e,t){let n=localStorage.getItem(`bw_admin_token`);if(n){this._isDiscovering=!0;try{let r=await fetch(`https://aidyn-backend.gitlabapp.alem.ai/v1/training/discover`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({fingerprint:e,tokens:t,page_url:window.location.href})});if(r.ok){let e=await r.json();console.log(`[Discovery] ${e.status} — ${e.label}`),this._discoveryCallbacks.forEach(t=>t(e))}else r.status===401?(console.warn(`[Discovery] Token expired — disabling auto-discovery`),localStorage.removeItem(`bw_admin_token`),this.isAutoDiscoveryEnabled=!1):console.warn(`[Discovery] Server error ${r.status}`)}catch(e){console.warn(`[Discovery] Network error`,e)}finally{this._isDiscovering=!1}}}async forceDiscovery(){let e=[...new Set(q())],t=J();await this._discover(t,e)}},Y=new Et(1500)}));Dt();var Ot=`https://arif-altas.vercel.app/api`,kt=class{constructor(e){this.isFixing=!1,this.simplifyEnabled=!1,this.autoA11yEnabled=!1,this._onParagraphKeydown=e=>{if(this.simplifyEnabled&&(e.key===`Enter`||e.key===` `)&&e.target instanceof HTMLElement){if(e.target.closest(`bw-widget`)||e.target.closest(`.bw-ai-tooltip`))return;let t=e.target.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(t)){e.preventDefault(),e.stopPropagation();let t=e.target.getBoundingClientRect();this._triggerSimplify(e.target,t.left+window.scrollX,t.bottom+window.scrollY)}}},this._onParagraphClick=async e=>{if(!this.simplifyEnabled)return;let t=e.target;if(t.closest(`bw-widget`)||t.closest(`.bw-ai-tooltip`))return;let n=t.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(n)){let n=t.innerText?.trim();n&&n.length>20&&(e.preventDefault(),e.stopPropagation(),this._triggerSimplify(t,e.pageX,e.pageY))}},(this.host=e).addController(this),this.simplifyEnabled=localStorage.getItem(`bw-ai-simplify`)===`true`,this.autoA11yEnabled=localStorage.getItem(`bw-ai-autofix`)===`true`,Y.onStateChange(()=>{this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup()}),this.autoA11yEnabled&&setTimeout(()=>this.fixMarkup(),1e3)}toggleAutoA11y(){this.autoA11yEnabled=!this.autoA11yEnabled,localStorage.setItem(`bw-ai-autofix`,this.autoA11yEnabled?`true`:`false`),this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup(),this.host.requestUpdate()}hostConnected(){}hostDisconnected(){this.simplifyEnabled&&(document.body.removeEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.classList.remove(`bw-simplify-mode`))}async fixMarkup(){this.isFixing=!0,this.host.requestUpdate();try{let e=[];if(document.querySelectorAll(`img:not([alt]), img[alt=""]`).forEach(t=>{t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-img-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)})}),document.querySelectorAll(`button:not([aria-label]), a:not([aria-label]), [role="button"]:not([aria-label])`).forEach(t=>{if(t.tagName===`INPUT`)return;let n=t;n.innerText?.trim()||n.textContent?.trim()||(t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-btn-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)}))}),e.length===0){console.log(`BariWeb AI: No broken elements found.`);return}console.log(`BariWeb AI: Found ${e.length} broken elements. Processing...`);let t=this.host.clientId||window.BariwebConfig?.clientId||``;for(let n=0;n<e.length;n+=10){let r=e.slice(n,n+10),i=await fetch(`${Ot}/v1/widget/a11y/fix`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({elements:r})});i.ok&&(await i.json()).forEach(e=>{let t=document.querySelector(`[data-bw-ai-id="${e.id}"]`);if(t&&e.value&&(e.attribute===`alt`||e.attribute===`aria-label`)){t.setAttribute(e.attribute,e.value);let n=t,r=n.style.outline;n.style.outline=`3px solid #10b981`,setTimeout(()=>{n.style.outline=r},2e3)}})}}finally{this.isFixing=!1,this.host.requestUpdate()}}toggleSimplify(){if(this.simplifyEnabled=!this.simplifyEnabled,this.simplifyEnabled){if(document.body.addEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.addEventListener(`keydown`,this._onParagraphKeydown,{capture:!0}),document.querySelectorAll(`p, h1, h2, h3, h4, h5, h6, li, article`).forEach(e=>{!e.hasAttribute(`tabindex`)&&e.textContent?.trim().length>20&&(e.setAttribute(`tabindex`,`0`),e.classList.add(`bw-simplify-focusable`))}),document.documentElement.style.setProperty(`--bw-simplify-cursor`,`help`),!document.getElementById(`bw-simplify-mode-style`)){let e=document.createElement(`style`);e.id=`bw-simplify-mode-style`,e.textContent=`
883
883
  body.bw-simplify-mode *:hover {
884
884
  cursor: help !important;
885
885
  background-color: rgba(168, 85, 247, 0.1) !important;
@@ -964,7 +964,7 @@
964
964
  <div class="bw-ai-tooltip-content" role="status" aria-live="polite">
965
965
  Ожидаем ответ от ИИ...
966
966
  </div>
967
- `,document.body.appendChild(i),i.style.left=`${Math.max(10,t-160)}px`,i.style.top=`${n+20}px`;let a=e.style.outline,o=e.style.backgroundColor;e.style.outline=`2px dashed #a855f7`,e.style.backgroundColor=`rgba(168, 85, 247, 0.05)`,i.querySelector(`.bw-ai-tooltip-close`)?.addEventListener(`click`,()=>{i.remove(),e.style.outline=a,e.style.backgroundColor=o});try{let e=this.host.clientId||window.BariwebConfig?.clientId||``,t=await fetch(`${Ot}/v1/widget/a11y/simplify`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":e},body:JSON.stringify({text:r})});if(t.ok){let e=await t.json();if(e.text)i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=e.text,i.focus();else throw Error(`Empty response`)}else throw Error(`Server error`)}catch(e){console.error(`BariWeb AI: Simplify failed`,e),i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=`<span style="color:#ef4444; font-size:13px;">Ошибка создания упрощенного текста. Попробуйте еще раз.</span>`,i.focus()}}},At=`bw-tts-enabled-v1`,jt=class{constructor(){this.enabled=!1,this.enabled=this.loadEnabled(),`speechSynthesis`in window&&(window.speechSynthesis.getVoices(),window.speechSynthesis.onvoiceschanged=()=>{window.speechSynthesis.getVoices()})}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e;try{localStorage.setItem(At,e?`1`:`0`)}catch{}e||this.stop()}stop(){`speechSynthesis`in window&&window.speechSynthesis.cancel()}speak(e){if(!this.enabled||!(`speechSynthesis`in window))return;let t=(e||``).trim();if(t)try{window.speechSynthesis.resume(),window.speechSynthesis.cancel();let e=new SpeechSynthesisUtterance(t),n=this.detectLanguage(t);e.lang=n;let r=this.pickVoice(n);r&&(e.voice=r),e.rate=1,e.pitch=1,e.volume=1,window.speechSynthesis.speak(e)}catch(e){console.warn(`TTS speak failed`,e)}}loadEnabled(){try{let e=localStorage.getItem(At);return e===null?!1:e!==`0`}catch{return!1}}detectLanguage(e){return/[\u04D8\u04D9\u0492\u0493\u04AE\u04AF\u049A\u049B\u04E8\u04E9\u04BA\u04BB\u0406\u0456\u04A2\u04A3]/u.test(e)?`kk-KZ`:/[\u0400-\u04FF]/u.test(e)?`ru-RU`:/[a-z]/i.test(e)?`en-US`:`ru-RU`}pickVoice(e){if(!(`speechSynthesis`in window))return null;let t=window.speechSynthesis.getVoices();if(!t||t.length===0)return null;let n=e.split(`-`)[0].toLowerCase();return t.find(t=>t.lang.toLowerCase()===e.toLowerCase())||t.find(e=>e.lang.toLowerCase().startsWith(n))||t[0]||null}};wt();var Mt=`http://localhost:8000`,Nt=5,Pt=[/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];function Ft(e){if(e.type!==`click_element`||!e.element_id)return!1;let t=document.getElementById(e.element_id);if(!t)return!1;if(t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`)return!0;let n=[t.textContent?.trim()||``,t.getAttribute(`aria-label`)||``,t.getAttribute(`title`)||``,t.getAttribute(`name`)||``,t.getAttribute(`value`)||``].join(` `);return Pt.some(e=>e.test(n))}var It=class{constructor(e){this.messages=[],this.isLoading=!1,this.error=null,this._tts=new jt,this._voiceMode=!1,this.pendingConfirmation=null,(this.host=e).addController(this),this._loadMessages()}hostConnected(){}hostDisconnected(){this._tts.stop()}_shouldSpeak(){return this._tts.isEnabled()}_loadMessages(){try{let e=sessionStorage.getItem(`bw-chat-history`);e&&(this.messages=JSON.parse(e),this.messages.length>0&&typeof this.host.setOpen==`function`&&setTimeout(()=>this.host.setOpen(!0),100));let t=sessionStorage.getItem(`bw-auto-resume`);if(t===`true`||t===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`);let e=t===`verify-only`?`Страница загрузилась после отправки формы. Проверь новый DOM: если авторизация прошла успешно (нет формы входа, есть контент приложения) — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась. Продолжай выполнение задачи с учетом нового контекста и DOM.`;setTimeout(()=>{this._agentStep(e)},1e3)}}catch(e){console.error(`Failed to load chat history`,e)}}_saveMessages(){try{sessionStorage.setItem(`bw-chat-history`,JSON.stringify(this.messages))}catch(e){console.error(`Failed to save chat history`,e)}}isVoiceModeActive(){return this._voiceMode}gatherContext(){let e=window.location.href,t=document.body?.innerText?.slice(0,3e3)??``,n=Array.from(document.querySelectorAll(`a[href], button, [role="button"], input:not([type="hidden"]), textarea, select`)).filter(e=>!e.hasAttribute(`bw-private`)).map(e=>{let t=e,n=t.tagName.toLowerCase(),r=n===`input`||n===`textarea`||n===`select`,i=t.getAttribute(`type`)||(n===`input`?`text`:n===`button`?`button`:n),a=t.getAttribute(`name`)||``,o=t.getAttribute(`placeholder`)||``,s=r?(t.value||``).slice(0,80):``;s&&=(s=s.replace(/\b\d{13,19}\b/g,e=>e.slice(0,4)+` **** **** `+e.slice(-4)),s.replace(/\b\d{12}\b/g,`**** **** ****`));let c=t.id&&!t.getAttribute(`data-bw-auto`)?t.id:t.getAttribute(`data-id`)||t.getAttribute(`data-testid`)||``;if(!c){let e=`${n}|${i}|${a}|${o}|${(t.className||``).toString().replace(/\s+/g,`-`).slice(0,40)}|${t.href||``}|${(t.textContent||``).trim().slice(0,30)}|${t.parentElement?.tagName?.toLowerCase()||`root`}`,r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r^e.charCodeAt(t);c=`bw-${(r>>>0).toString(16)}`,t.id=c,t.setAttribute(`data-bw-auto`,`true`)}let l=t.getAttribute(`aria-label`)||``;if(!l&&c){let e=document.querySelector(`label[for="${c}"]`);e&&(l=e.textContent?.trim()||``)}if(!l){let e=t.parentElement;for(;e&&e.tagName.toLowerCase()!==`form`&&e.tagName.toLowerCase()!==`body`;){if(e.tagName.toLowerCase()===`label`){l=(e.textContent||``).replace(t.textContent||``,``).trim();break}e=e.parentElement}}if(l||=(t.textContent||``).trim().slice(0,80),l||=t.getAttribute(`title`)||``,!l&&o&&(l=o),!l&&n===`button`){let e=t.querySelector(`svg`);if(e&&typeof e.className?.baseVal==`string`){let t=e.className.baseVal.match(/lucide-([a-z0-9\-]+)/);l=t?`[icon:${t[1]}]`:`[icon]`}else l=`[btn:${(t.className||``).toString().slice(0,30)}]`}return{id:c,label:l.trim(),tag:n,type:i,name:a,placeholder:o,value:s}}).filter(e=>e.label.length>0||(e.placeholder??``).length>0||(e.name??``).length>0).slice(0,100).map(e=>`[`+[e.tag,e.type||``,e.id,e.name||``,e.placeholder||``,e.value||``,e.label].join(`|`)+`]`).join(``),r=t;return r=r.replace(/\b\d{13,19}\b/g,`**** **** **** ****`),r=r.replace(/\b\d{12}\b/g,`**** **** ****`),{page_text:r,elements:n,page_url:e}}executeAction(e){if(e.type===`click_element`&&e.element_id){let t=document.getElementById(e.element_id);if(t){if(t.tagName.toLowerCase()===`a`&&t.href){let n=t.href;return new URL(n,window.location.origin).origin===window.location.origin&&sessionStorage.setItem(`bw-auto-resume`,`true`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}}return t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`?(sessionStorage.setItem(`bw-auto-resume`,`verify-only`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}):(t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!1})}return{result:`⚠️ Элемент "${e.element_id}" не найден.`,causesNavigation:!1}}if(e.type===`navigate`&&e.url)return sessionStorage.setItem(`bw-auto-resume`,`true`),window.location.href=e.url,{result:`🔀 Перехожу на ${e.url}...`,causesNavigation:!0};if(e.type===`input_text`&&e.element_id&&e.value!==void 0){let t=document.getElementById(e.element_id);if(t){let n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set,r=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,`value`)?.set;return t.tagName.toLowerCase()===`textarea`&&r?r.call(t,e.value):n?n.call(t,e.value):t.value=e.value,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})),{result:`⌨️ Ввел текст "${e.value}" в поле.`,causesNavigation:!1}}return{result:`⚠️ Поле ввода "${e.element_id}" не найдено.`,causesNavigation:!1}}return e.type===`continue`?{result:`🔄 Анализирую страницу...`,causesNavigation:!1}:{result:`⚠️ Неизвестное действие.`,causesNavigation:!1}}async _callAPI(e){let{page_text:t,elements:n,page_url:r}=this.gatherContext(),i=J(),a=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,o=null;try{let e=await fetch(`${Mt}/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({fingerprint:i})});if(e.ok){let t=await e.json();t.matched&&(o=t.label)}}catch(e){console.warn(`Failed to match screen fingerprint`,e)}let s=await fetch(`${Mt}/v1/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({query:e,history:this._compressedHistory(),page_text:t,elements:n,page_url:r,screen_label:o,screen_fingerprint:i})});if(!s.ok)throw Error(`HTTP ${s.status}: ${s.statusText}`);let c=await s.json();if(c.text&&c.text.trimStart().startsWith(`{`))try{let e=JSON.parse(c.text);e.text&&(c.text=e.text,e.action&&!c.action&&(c.action=e.action))}catch{c.text=c.text.replace(/^\{"text"\s*:\s*"/,``).replace(/",?\s*"action".*$/,``)}return c}_compressedHistory(){let e=this.messages.map(e=>({role:e.role,text:e.text})),t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role===`user`){t=n;break}if(t===-1)return e.slice(-5);let n=-1;for(let r=t-1;r>=0;r--)if(e[r].role===`user`){n=r;break}let r=[];if(n!==-1){r.push(e[n]);let i=e.slice(n+1,t).filter(e=>e.role===`assistant`).pop();i&&r.push(i)}r.push(e[t]);let i=e.slice(t+1).filter(e=>e.role===`assistant`);return r.push(...i.slice(-2)),r}async _agentLoop(e,t,n=!1){if(this.isLoading)return;this.isLoading=!0,this.error=null,this._voiceMode=n,t&&(this.messages=[...this.messages,{role:`user`,text:e,timestamp:Date.now()}],this._saveMessages()),this.host.requestUpdate();let r=e,i=0;try{for(;i<Nt;){i++;let e=await this._callAPI(r),t=e.text;if(e.action){if(Ft(e.action)){let t=document.getElementById(e.action.element_id||``)?.textContent?.trim()||e.action.element_id||`кнопку`;this.pendingConfirmation={text:`${e.text}\n\n⚠️ Нажать «${t}»?`,action:e.action,currentQuery:r,step:i},this.messages=[...this.messages,{role:`assistant`,text:`${e.text}\n\n🛑 **Подтвердите действие:** нажать «${t}»?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(e.text),this.isLoading=!1,this.host.requestUpdate();return}let n=this.gatherContext().page_text,{result:a,causesNavigation:o}=this.executeAction(e.action);if(e.action.type===`continue`){this.messages=[...this.messages,{role:`assistant`,text:`🔄 Анализирую...`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Анализирую...`),this.host.requestUpdate(),await this._waitForDom(800),r=`Страница обновилась. Продолжай задачу, прочитай DOM.`;continue}if(t=`${e.text}\n${a}`,o){this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),await this._waitForDom(1500);let e=sessionStorage.getItem(`bw-auto-resume`);if(e===`true`||e===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`),r=e===`verify-only`?`Страница загрузилась после отправки формы (SPA навигация). Проверь новый DOM: если задача выполнена — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась (SPA навигация). Продолжай задачу, прочитай новый DOM.`;continue}break}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),e.action.type===`input_text`&&e.action.element_id?(await this._waitForDom(800),r=(document.getElementById(e.action.element_id)?.value??``).length>0?`✅ Поле заполнено. Переходи к СЛЕДУЮЩЕМУ незаполненному полю или нажми кнопку отправки. НЕ повторяй ввод.`:`⚠️ Поле не получило значение. Попробуй ввести снова в id="${e.action.element_id}".`):(await this._waitForDom(800),r=n===this.gatherContext().page_text?`⚠️ Страница не изменилась. Возможно кнопка не сработала. Проверь DOM.`:`Действие выполнено. Если задача готова — сообщи. Иначе продолжай.`);continue}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t);break}}catch(e){this.error=e.message??`Ошибка соединения`,this.messages=[...this.messages,{role:`assistant`,text:`❌ Ошибка: ${this.error}`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Ошибка: ${this.error}`)}finally{this.isLoading=!1,this.host.requestUpdate()}}async confirmAction(){if(!this.pendingConfirmation)return;let{action:e}=this.pendingConfirmation;this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`✅ Подтверждаю`,timestamp:Date.now()}],this._saveMessages(),this.host.requestUpdate();let{result:t,causesNavigation:n}=this.executeAction(e);this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),!n&&(await this._waitForDom(1200),await this._agentStep(`Действие подтверждено и выполнено. Проверь результат в DOM.`))}cancelAction(){this.pendingConfirmation&&(this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`❌ Отмена`,timestamp:Date.now()},{role:`assistant`,text:`🚫 Действие отменено. Чем ещё могу помочь?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Действие отменено. Чем ещё могу помочь?`),this.host.requestUpdate())}_waitForDom(e){return new Promise(t=>setTimeout(t,e))}async sendMessage(e,t=!1){!e.trim()||this.isLoading||(await this._agentLoop(e,!0,t),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)}))}async _agentStep(e){await this._agentLoop(e,!1,this._voiceMode),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)})}clearMessages(){this.messages=[],this.error=null,this.pendingConfirmation=null,this._saveMessages(),this.host.requestUpdate()}isTtsEnabled(){return this._tts.isEnabled()}setTtsEnabled(e){this._tts.setEnabled(e),this.host.requestUpdate()}async transcribeAudio(e,t){let n=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,r=new FormData;r.append(`language_mode`,t),r.append(`audio`,e,`speech.wav`);let i=await fetch(`${Mt}/v1/stt/transcribe`,{method:`POST`,headers:{"X-Client-ID":n},body:r});if(!i.ok){let e=`HTTP ${i.status}`;try{e=(await i.json())?.detail||e}catch{}throw Error(e)}return await i.json()}};function X(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Lt=n({initAdminMode:()=>Vt,mountAdminPanel:()=>Bt});function Rt(){if(!Z)return;let e=q(),t=J(),n=Q?.is_trained===!0,r=Q&&!Q.is_trained,i=Q?.label||null,a=Q?.description||null,o=n?`active`:r?`draft`:`idle`,s=n?`trained`:r?`draft`:`idle`,c=n?`✅ Обучено`:r?`📝 Черновик (не подтверждено)`:`🔍 Сканирование...`,l=Z.querySelector(`#bw-admin-panel`);l&&(l.className=n?`trained`:`discovering`,l.id=`bw-admin-panel`,n&&l.classList.add(`trained`));let u=Z.querySelector(`#bw-panel-content`);u&&(u.innerHTML=`
967
+ `,document.body.appendChild(i),i.style.left=`${Math.max(10,t-160)}px`,i.style.top=`${n+20}px`;let a=e.style.outline,o=e.style.backgroundColor;e.style.outline=`2px dashed #a855f7`,e.style.backgroundColor=`rgba(168, 85, 247, 0.05)`,i.querySelector(`.bw-ai-tooltip-close`)?.addEventListener(`click`,()=>{i.remove(),e.style.outline=a,e.style.backgroundColor=o});try{let e=this.host.clientId||window.BariwebConfig?.clientId||``,t=await fetch(`${Ot}/v1/widget/a11y/simplify`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":e},body:JSON.stringify({text:r})});if(t.ok){let e=await t.json();if(e.text)i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=e.text,i.focus();else throw Error(`Empty response`)}else throw Error(`Server error`)}catch(e){console.error(`BariWeb AI: Simplify failed`,e),i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=`<span style="color:#ef4444; font-size:13px;">Ошибка создания упрощенного текста. Попробуйте еще раз.</span>`,i.focus()}}},At=`bw-tts-enabled-v1`,jt=class{constructor(){this.enabled=!1,this.enabled=this.loadEnabled(),`speechSynthesis`in window&&(window.speechSynthesis.getVoices(),window.speechSynthesis.onvoiceschanged=()=>{window.speechSynthesis.getVoices()})}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e;try{localStorage.setItem(At,e?`1`:`0`)}catch{}e||this.stop()}stop(){`speechSynthesis`in window&&window.speechSynthesis.cancel()}speak(e){if(!this.enabled||!(`speechSynthesis`in window))return;let t=(e||``).trim();if(t)try{window.speechSynthesis.resume(),window.speechSynthesis.cancel();let e=new SpeechSynthesisUtterance(t),n=this.detectLanguage(t);e.lang=n;let r=this.pickVoice(n);r&&(e.voice=r),e.rate=1,e.pitch=1,e.volume=1,window.speechSynthesis.speak(e)}catch(e){console.warn(`TTS speak failed`,e)}}loadEnabled(){try{let e=localStorage.getItem(At);return e===null?!1:e!==`0`}catch{return!1}}detectLanguage(e){return/[\u04D8\u04D9\u0492\u0493\u04AE\u04AF\u049A\u049B\u04E8\u04E9\u04BA\u04BB\u0406\u0456\u04A2\u04A3]/u.test(e)?`kk-KZ`:/[\u0400-\u04FF]/u.test(e)?`ru-RU`:/[a-z]/i.test(e)?`en-US`:`ru-RU`}pickVoice(e){if(!(`speechSynthesis`in window))return null;let t=window.speechSynthesis.getVoices();if(!t||t.length===0)return null;let n=e.split(`-`)[0].toLowerCase();return t.find(t=>t.lang.toLowerCase()===e.toLowerCase())||t.find(e=>e.lang.toLowerCase().startsWith(n))||t[0]||null}};wt();var Mt=`https://arif-altas.vercel.app/api`,Nt=5,Pt=[/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];function Ft(e){if(e.type!==`click_element`||!e.element_id)return!1;let t=document.getElementById(e.element_id);if(!t)return!1;if(t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`)return!0;let n=[t.textContent?.trim()||``,t.getAttribute(`aria-label`)||``,t.getAttribute(`title`)||``,t.getAttribute(`name`)||``,t.getAttribute(`value`)||``].join(` `);return Pt.some(e=>e.test(n))}var It=class{constructor(e){this.messages=[],this.isLoading=!1,this.error=null,this._tts=new jt,this._voiceMode=!1,this.pendingConfirmation=null,(this.host=e).addController(this),this._loadMessages()}hostConnected(){}hostDisconnected(){this._tts.stop()}_shouldSpeak(){return this._tts.isEnabled()}_loadMessages(){try{let e=sessionStorage.getItem(`bw-chat-history`);e&&(this.messages=JSON.parse(e),this.messages.length>0&&typeof this.host.setOpen==`function`&&setTimeout(()=>this.host.setOpen(!0),100));let t=sessionStorage.getItem(`bw-auto-resume`);if(t===`true`||t===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`);let e=t===`verify-only`?`Страница загрузилась после отправки формы. Проверь новый DOM: если авторизация прошла успешно (нет формы входа, есть контент приложения) — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась. Продолжай выполнение задачи с учетом нового контекста и DOM.`;setTimeout(()=>{this._agentStep(e)},1e3)}}catch(e){console.error(`Failed to load chat history`,e)}}_saveMessages(){try{sessionStorage.setItem(`bw-chat-history`,JSON.stringify(this.messages))}catch(e){console.error(`Failed to save chat history`,e)}}isVoiceModeActive(){return this._voiceMode}gatherContext(){let e=window.location.href,t=document.body?.innerText?.slice(0,3e3)??``,n=Array.from(document.querySelectorAll(`a[href], button, [role="button"], input:not([type="hidden"]), textarea, select`)).filter(e=>!e.hasAttribute(`bw-private`)).map(e=>{let t=e,n=t.tagName.toLowerCase(),r=n===`input`||n===`textarea`||n===`select`,i=t.getAttribute(`type`)||(n===`input`?`text`:n===`button`?`button`:n),a=t.getAttribute(`name`)||``,o=t.getAttribute(`placeholder`)||``,s=r?(t.value||``).slice(0,80):``;s&&=(s=s.replace(/\b\d{13,19}\b/g,e=>e.slice(0,4)+` **** **** `+e.slice(-4)),s.replace(/\b\d{12}\b/g,`**** **** ****`));let c=t.id&&!t.getAttribute(`data-bw-auto`)?t.id:t.getAttribute(`data-id`)||t.getAttribute(`data-testid`)||``;if(!c){let e=`${n}|${i}|${a}|${o}|${(t.className||``).toString().replace(/\s+/g,`-`).slice(0,40)}|${t.href||``}|${(t.textContent||``).trim().slice(0,30)}|${t.parentElement?.tagName?.toLowerCase()||`root`}`,r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r^e.charCodeAt(t);c=`bw-${(r>>>0).toString(16)}`,t.id=c,t.setAttribute(`data-bw-auto`,`true`)}let l=t.getAttribute(`aria-label`)||``;if(!l&&c){let e=document.querySelector(`label[for="${c}"]`);e&&(l=e.textContent?.trim()||``)}if(!l){let e=t.parentElement;for(;e&&e.tagName.toLowerCase()!==`form`&&e.tagName.toLowerCase()!==`body`;){if(e.tagName.toLowerCase()===`label`){l=(e.textContent||``).replace(t.textContent||``,``).trim();break}e=e.parentElement}}if(l||=(t.textContent||``).trim().slice(0,80),l||=t.getAttribute(`title`)||``,!l&&o&&(l=o),!l&&n===`button`){let e=t.querySelector(`svg`);if(e&&typeof e.className?.baseVal==`string`){let t=e.className.baseVal.match(/lucide-([a-z0-9\-]+)/);l=t?`[icon:${t[1]}]`:`[icon]`}else l=`[btn:${(t.className||``).toString().slice(0,30)}]`}return{id:c,label:l.trim(),tag:n,type:i,name:a,placeholder:o,value:s}}).filter(e=>e.label.length>0||(e.placeholder??``).length>0||(e.name??``).length>0).slice(0,100).map(e=>`[`+[e.tag,e.type||``,e.id,e.name||``,e.placeholder||``,e.value||``,e.label].join(`|`)+`]`).join(``),r=t;return r=r.replace(/\b\d{13,19}\b/g,`**** **** **** ****`),r=r.replace(/\b\d{12}\b/g,`**** **** ****`),{page_text:r,elements:n,page_url:e}}executeAction(e){if(e.type===`click_element`&&e.element_id){let t=document.getElementById(e.element_id);if(t){if(t.tagName.toLowerCase()===`a`&&t.href){let n=t.href;return new URL(n,window.location.origin).origin===window.location.origin&&sessionStorage.setItem(`bw-auto-resume`,`true`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}}return t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`?(sessionStorage.setItem(`bw-auto-resume`,`verify-only`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}):(t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!1})}return{result:`⚠️ Элемент "${e.element_id}" не найден.`,causesNavigation:!1}}if(e.type===`navigate`&&e.url)return sessionStorage.setItem(`bw-auto-resume`,`true`),window.location.href=e.url,{result:`🔀 Перехожу на ${e.url}...`,causesNavigation:!0};if(e.type===`input_text`&&e.element_id&&e.value!==void 0){let t=document.getElementById(e.element_id);if(t){let n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set,r=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,`value`)?.set;return t.tagName.toLowerCase()===`textarea`&&r?r.call(t,e.value):n?n.call(t,e.value):t.value=e.value,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})),{result:`⌨️ Ввел текст "${e.value}" в поле.`,causesNavigation:!1}}return{result:`⚠️ Поле ввода "${e.element_id}" не найдено.`,causesNavigation:!1}}return e.type===`continue`?{result:`🔄 Анализирую страницу...`,causesNavigation:!1}:{result:`⚠️ Неизвестное действие.`,causesNavigation:!1}}async _callAPI(e){let{page_text:t,elements:n,page_url:r}=this.gatherContext(),i=J(),a=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,o=null;try{let e=await fetch(`${Mt}/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({fingerprint:i})});if(e.ok){let t=await e.json();t.matched&&(o=t.label)}}catch(e){console.warn(`Failed to match screen fingerprint`,e)}let s=await fetch(`${Mt}/v1/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({query:e,history:this._compressedHistory(),page_text:t,elements:n,page_url:r,screen_label:o,screen_fingerprint:i})});if(!s.ok)throw Error(`HTTP ${s.status}: ${s.statusText}`);let c=await s.json();if(c.text&&c.text.trimStart().startsWith(`{`))try{let e=JSON.parse(c.text);e.text&&(c.text=e.text,e.action&&!c.action&&(c.action=e.action))}catch{c.text=c.text.replace(/^\{"text"\s*:\s*"/,``).replace(/",?\s*"action".*$/,``)}return c}_compressedHistory(){let e=this.messages.map(e=>({role:e.role,text:e.text})),t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role===`user`){t=n;break}if(t===-1)return e.slice(-5);let n=-1;for(let r=t-1;r>=0;r--)if(e[r].role===`user`){n=r;break}let r=[];if(n!==-1){r.push(e[n]);let i=e.slice(n+1,t).filter(e=>e.role===`assistant`).pop();i&&r.push(i)}r.push(e[t]);let i=e.slice(t+1).filter(e=>e.role===`assistant`);return r.push(...i.slice(-2)),r}async _agentLoop(e,t,n=!1){if(this.isLoading)return;this.isLoading=!0,this.error=null,this._voiceMode=n,t&&(this.messages=[...this.messages,{role:`user`,text:e,timestamp:Date.now()}],this._saveMessages()),this.host.requestUpdate();let r=e,i=0;try{for(;i<Nt;){i++;let e=await this._callAPI(r),t=e.text;if(e.action){if(Ft(e.action)){let t=document.getElementById(e.action.element_id||``)?.textContent?.trim()||e.action.element_id||`кнопку`;this.pendingConfirmation={text:`${e.text}\n\n⚠️ Нажать «${t}»?`,action:e.action,currentQuery:r,step:i},this.messages=[...this.messages,{role:`assistant`,text:`${e.text}\n\n🛑 **Подтвердите действие:** нажать «${t}»?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(e.text),this.isLoading=!1,this.host.requestUpdate();return}let n=this.gatherContext().page_text,{result:a,causesNavigation:o}=this.executeAction(e.action);if(e.action.type===`continue`){this.messages=[...this.messages,{role:`assistant`,text:`🔄 Анализирую...`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Анализирую...`),this.host.requestUpdate(),await this._waitForDom(800),r=`Страница обновилась. Продолжай задачу, прочитай DOM.`;continue}if(t=`${e.text}\n${a}`,o){this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),await this._waitForDom(1500);let e=sessionStorage.getItem(`bw-auto-resume`);if(e===`true`||e===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`),r=e===`verify-only`?`Страница загрузилась после отправки формы (SPA навигация). Проверь новый DOM: если задача выполнена — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась (SPA навигация). Продолжай задачу, прочитай новый DOM.`;continue}break}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),e.action.type===`input_text`&&e.action.element_id?(await this._waitForDom(800),r=(document.getElementById(e.action.element_id)?.value??``).length>0?`✅ Поле заполнено. Переходи к СЛЕДУЮЩЕМУ незаполненному полю или нажми кнопку отправки. НЕ повторяй ввод.`:`⚠️ Поле не получило значение. Попробуй ввести снова в id="${e.action.element_id}".`):(await this._waitForDom(800),r=n===this.gatherContext().page_text?`⚠️ Страница не изменилась. Возможно кнопка не сработала. Проверь DOM.`:`Действие выполнено. Если задача готова — сообщи. Иначе продолжай.`);continue}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t);break}}catch(e){this.error=e.message??`Ошибка соединения`,this.messages=[...this.messages,{role:`assistant`,text:`❌ Ошибка: ${this.error}`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Ошибка: ${this.error}`)}finally{this.isLoading=!1,this.host.requestUpdate()}}async confirmAction(){if(!this.pendingConfirmation)return;let{action:e}=this.pendingConfirmation;this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`✅ Подтверждаю`,timestamp:Date.now()}],this._saveMessages(),this.host.requestUpdate();let{result:t,causesNavigation:n}=this.executeAction(e);this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),!n&&(await this._waitForDom(1200),await this._agentStep(`Действие подтверждено и выполнено. Проверь результат в DOM.`))}cancelAction(){this.pendingConfirmation&&(this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`❌ Отмена`,timestamp:Date.now()},{role:`assistant`,text:`🚫 Действие отменено. Чем ещё могу помочь?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Действие отменено. Чем ещё могу помочь?`),this.host.requestUpdate())}_waitForDom(e){return new Promise(t=>setTimeout(t,e))}async sendMessage(e,t=!1){!e.trim()||this.isLoading||(await this._agentLoop(e,!0,t),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)}))}async _agentStep(e){await this._agentLoop(e,!1,this._voiceMode),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)})}clearMessages(){this.messages=[],this.error=null,this.pendingConfirmation=null,this._saveMessages(),this.host.requestUpdate()}isTtsEnabled(){return this._tts.isEnabled()}setTtsEnabled(e){this._tts.setEnabled(e),this.host.requestUpdate()}async transcribeAudio(e,t){let n=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,r=new FormData;r.append(`language_mode`,t),r.append(`audio`,e,`speech.wav`);let i=await fetch(`${Mt}/v1/stt/transcribe`,{method:`POST`,headers:{"X-Client-ID":n},body:r});if(!i.ok){let e=`HTTP ${i.status}`;try{e=(await i.json())?.detail||e}catch{}throw Error(e)}return await i.json()}};function X(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Lt=n({initAdminMode:()=>Vt,mountAdminPanel:()=>Bt});function Rt(){if(!Z)return;let e=q(),t=J(),n=Q?.is_trained===!0,r=Q&&!Q.is_trained,i=Q?.label||null,a=Q?.description||null,o=n?`active`:r?`draft`:`idle`,s=n?`trained`:r?`draft`:`idle`,c=n?`✅ Обучено`:r?`📝 Черновик (не подтверждено)`:`🔍 Сканирование...`,l=Z.querySelector(`#bw-admin-panel`);l&&(l.className=n?`trained`:`discovering`,l.id=`bw-admin-panel`,n&&l.classList.add(`trained`));let u=Z.querySelector(`#bw-panel-content`);u&&(u.innerHTML=`
968
968
  <div class="bw-status-box ${n?`trained`:r?`draft`:``}">
969
969
  <div class="bw-status-indicator">
970
970
  <span class="bw-status-dot ${o}"></span>
@@ -1160,7 +1160,7 @@
1160
1160
  border-radius: 4px;
1161
1161
  transition: all 0.15s ease-out;
1162
1162
  }
1163
- `,Z=null,Q=null}));Dt();var Wt=`bw-stt-lang-v1`,Gt=200,Kt=.015,qt=1200,Jt=2e4,Yt=350,Xt={ru:{announceVoiceInputAvailable:`Голосовой ввод доступен. Кнопка в нижнем правом углу.`,announceWidgetOpened:`Виджет открыт.`,announceSwitchedToChat:`Переход в чат. Голосовой ввод доступен.`,errorMicNotSupported:`Микрофон не поддерживается.`,errorNoMicAccess:`Нет доступа к микрофону.`,errorProcessing:`Ошибка обработки.`,errorTooShort:`Слишком короткая запись.`,errorSpeechNotRecognized:`Речь не распознана.`,errorRecognition:`Ошибка распознавания.`,screenLabelPrefix:`На странице:`,chatEmptyTitle:`Ваш помощник`,chatEmptySub:`Опишите задачу — я найду нужные кнопки и заполню поля за вас.`,confirmAction:`Подтвердить действие`,cancel:`Отменить`,listening:`Слушаю... (остановлюсь по тишине)`,recognizingSpeech:`Распознаю речь...`,micAria:`Включить голосовой ввод (удерживайте для записи)`,inputPlaceholder:`Введите сообщение...`,inputAria:`Текстовое поле ввода сообщения`,ttsDisableAria:`Выключить озвучку ответа`,ttsEnableAria:`Включить озвучку ответа`,sendAria:`Отправить сообщение`,tileTextSize:`Размер текста`,tileMonochrome:`Ч/Б`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Тёмный`,tileLinks:`Ссылки`,valueHighlight:`Выделить`,tileSpacing:`Отступы`,valueEnlarge:`Увеличить`,tileFont:`Шрифт`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Голос`,valueRecording:`Запись...`,valuePress:`Нажмите`,colorSetup:`Настройка цвета`,tabBackground:`Фон`,tabHeader:`Шапка`,tabText:`Текст`,decrease:`Уменьшить`,hue:`Оттенок`,increase:`Увеличить`,recognitionLanguage:`Язык`,changeRecognitionLanguage:`Изменить язык распознавания`,languageAuto:`Автоопределение`,languageKz:`Казахский`,languageRu:`Русский`,languageEn:`Английский`,aiSimplify:`AI Упрощение текста`,aiBlindMode:`Режим для незрячих (AI)`,on:`ВКЛ`,off:`ВЫКЛ`,resetSettings:`Сбросить настройки`,adminMode:`Режим администратора`,adminAccess:`Admin доступ`,adminLoggedIn:`Вы вошли как администратор`,adminLogout:`Выйти из аккаунта`,adminPrompt:`Введите ключ для активации режима обучения`,adminLogin:`Войти`,close:`Закрыть`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Настройки`,madeInKazakhstan:`Сделано в Казахстане 🇰🇿`,closeWidgetAria:`Закрыть`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Открыть/Закрыть меню доступности`,adminKeyPlaceholder:`Admin Key`},kz:{announceVoiceInputAvailable:`Дауыстық енгізу қолжетімді. Түйме төменгі оң жақ бұрышта.`,announceWidgetOpened:`Виджет ашылды.`,announceSwitchedToChat:`Чатқа ауысты. Дауыстық енгізу қолжетімді.`,errorMicNotSupported:`Микрофонға қолдау жоқ.`,errorNoMicAccess:`Микрофонға рұқсат жоқ.`,errorProcessing:`Өңдеу қатесі.`,errorTooShort:`Жазба тым қысқа.`,errorSpeechNotRecognized:`Сөйлеу танылмады.`,errorRecognition:`Тану қатесі.`,screenLabelPrefix:`Бетте:`,chatEmptyTitle:`Сіздің көмекшіңіз`,chatEmptySub:`Міндетті сипаттаңыз — мен керек батырмаларды тауып, өрістерді толтырамын.`,confirmAction:`Әрекетті растау`,cancel:`Бас тарту`,listening:`Тыңдап тұрмын... (үнсіздікте тоқтаймын)`,recognizingSpeech:`Сөйлеуді танып жатырмын...`,micAria:`Дауыстық енгізуді қосу (жазу үшін ұстап тұрыңыз)`,inputPlaceholder:`Хабарлама енгізіңіз...`,inputAria:`Хабарлама енгізу өрісі`,ttsDisableAria:`Жауап дауысын өшіру`,ttsEnableAria:`Жауап дауысын қосу`,sendAria:`Хабарламаны жіберу`,tileTextSize:`Мәтін өлшемі`,tileMonochrome:`Қ/А`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Қою`,tileLinks:`Сілтемелер`,valueHighlight:`Белгілеу`,tileSpacing:`Аралықтар`,valueEnlarge:`Үлкейту`,tileFont:`Қаріп`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Дауыс`,valueRecording:`Жазып жатыр...`,valuePress:`Басыңыз`,colorSetup:`Түсті баптау`,tabBackground:`Фон`,tabHeader:`Тақырып`,tabText:`Мәтін`,decrease:`Азайту`,hue:`Реңк`,increase:`Көбейту`,recognitionLanguage:`Тіл`,changeRecognitionLanguage:`Тану тілін өзгерту`,languageAuto:`Автоанықтау`,languageKz:`Қазақша`,languageRu:`Орысша`,languageEn:`Ағылшынша`,aiSimplify:`AI мәтінді жеңілдету`,aiBlindMode:`Көру қабілеті нашарларға режим (AI)`,on:`ҚОС`,off:`ӨШІК`,resetSettings:`Баптауларды қалпына келтіру`,adminMode:`Әкімші режимі`,adminAccess:`Admin қолжетімділігі`,adminLoggedIn:`Сіз әкімші ретінде кірдіңіз`,adminLogout:`Аккаунттан шығу`,adminPrompt:`Оқыту режимін қосу үшін кілт енгізіңіз`,adminLogin:`Кіру`,close:`Жабу`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Баптаулар`,madeInKazakhstan:`Қазақстанда жасалған 🇰🇿`,closeWidgetAria:`Жабу`,widgetDialogAria:`BariWeb қолжетімділік виджеті`,triggerAria:`Қолжетімділік мәзірін ашу/жабу`,adminKeyPlaceholder:`Admin Key`},en:{announceVoiceInputAvailable:`Voice input is available. The button is in the bottom-right corner.`,announceWidgetOpened:`Widget opened.`,announceSwitchedToChat:`Switched to chat. Voice input is available.`,errorMicNotSupported:`Microphone is not supported.`,errorNoMicAccess:`No access to microphone.`,errorProcessing:`Processing error.`,errorTooShort:`Recording is too short.`,errorSpeechNotRecognized:`Speech was not recognized.`,errorRecognition:`Recognition error.`,screenLabelPrefix:`On page:`,chatEmptyTitle:`Your assistant`,chatEmptySub:`Describe your task — I will find the right buttons and fill fields for you.`,confirmAction:`Confirm action`,cancel:`Cancel`,listening:`Listening... (will stop on silence)`,recognizingSpeech:`Recognizing speech...`,micAria:`Enable voice input (hold to record)`,inputPlaceholder:`Type a message...`,inputAria:`Message input field`,ttsDisableAria:`Disable answer voice`,ttsEnableAria:`Enable answer voice`,sendAria:`Send message`,tileTextSize:`Text size`,tileMonochrome:`B/W`,valueMonochrome:`Monochrome`,tileContrast:`Contrast`,valueDark:`Dark`,tileLinks:`Links`,valueHighlight:`Highlight`,tileSpacing:`Spacing`,valueEnlarge:`Enlarge`,tileFont:`Font`,valueDyslexia:`Dyslexia`,tileCursor:`Cursor`,tileVoice:`Voice`,valueRecording:`Recording...`,valuePress:`Press`,colorSetup:`Color setup`,tabBackground:`Background`,tabHeader:`Header`,tabText:`Text`,decrease:`Decrease`,hue:`Hue`,increase:`Increase`,recognitionLanguage:`Language`,changeRecognitionLanguage:`Change recognition language`,languageAuto:`Auto detect`,languageKz:`Kazakh`,languageRu:`Russian`,languageEn:`English`,aiSimplify:`AI text simplification`,aiBlindMode:`Blind mode (AI)`,on:`ON`,off:`OFF`,resetSettings:`Reset settings`,adminMode:`Administrator mode`,adminAccess:`Admin access`,adminLoggedIn:`You are logged in as administrator`,adminLogout:`Log out`,adminPrompt:`Enter key to activate training mode`,adminLogin:`Log in`,close:`Close`,inclusion:`Inclusion`,tabChat:`Chat`,tabSettings:`Settings`,madeInKazakhstan:`Made in Kazakhstan 🇰🇿`,closeWidgetAria:`Close`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Open/close accessibility menu`,adminKeyPlaceholder:`Admin Key`}},$=class extends B{static{this.styles=[dt]}constructor(){super(),this._a11y=new pt(this),this._aiA11y=new kt(this),this._chat=new It(this),this.clientId=``,this._isOpen=!1,this._activeTab=`chat`,this._inputValue=``,this._isAdmin=!1,this._adminPassword=``,this._authError=``,this._currentScreenLabel=``,this._sttState=`idle`,this._sttLanguageMode=`auto`,this._sttError=``,this._adminClickCount=0,this._showAdminLogin=!1,this._mediaStream=null,this._audioContext=null,this._analyser=null,this._scriptProcessor=null,this._pcmChunks=[],this._sampleRate=44100,this._recordingStartTs=0,this._silenceStartedTs=null,this._silenceIntervalId=null,this._maxDurationTimeoutId=null,this._adminClickTimer=null,this._hadPendingConfirmation=!1,this._handleGlobalKeydown=e=>{this._isOpen&&e.altKey&&e.code===`KeyV`&&(e.preventDefault(),this._toggleVoice())};try{let e=localStorage.getItem(Wt);(e===`auto`||e===`kz`||e===`ru`||e===`en`)&&(this._sttLanguageMode=e)}catch{}this._checkAuthStatus()}_setSttLanguageMode(e){this._sttLanguageMode=e;try{localStorage.setItem(Wt,e)}catch{}}_uiLang(){return this._sttLanguageMode===`kz`?`kz`:this._sttLanguageMode===`en`?`en`:`ru`}_t(e){return Xt[this._uiLang()][e]??Xt.ru[e]??e}async _checkAuthStatus(){let e=localStorage.getItem(`bw_admin_token`);if(e)try{(await fetch(`http://localhost:8000/auth/login/widget/verify`,{headers:{Authorization:`Bearer ${e}`}})).ok?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{try{let t=JSON.parse(atob(e.split(`.`)[1]));t.exp*1e3>Date.now()&&t.role===`admin`?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{localStorage.removeItem(`bw_admin_token`)}}}async _loadAdminUI(){try{let{initAdminMode:e}=await Promise.resolve().then(()=>(Ut(),Lt));e(),Y.isAutoDiscoveryEnabled=!0}catch(e){console.error(`Admin UI load failed`,e)}}async _handleAdminLogin(){this._authError=``;let e=this.clientId||window.BariwebConfig?.clientId||``;if(!e){this._authError=`Client ID not configured`;return}try{let t=await fetch(`http://localhost:8000/auth/login/widget`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_public_id:e,admin_key:this._adminPassword})});if(t.ok){let{access_token:e}=await t.json();localStorage.setItem(`bw_admin_token`,e),this._isAdmin=!0,this._showAdminLogin=!1,this._loadAdminUI()}else this._authError=(await t.json().catch(()=>({}))).detail||`Invalid admin key`}catch{this._authError=`Connection failed`}}_handleAdminLogout(){localStorage.removeItem(`bw_admin_token`),this._isAdmin=!1,this._adminPassword=``,this._showAdminLogin=!1,Y.isAutoDiscoveryEnabled=!1,document.querySelector(`#bw-admin-wrapper`)?.remove()}_handleLogoClick(){this._adminClickCount++,this._adminClickCount>=5&&(this._showAdminLogin=!this._showAdminLogin,this._adminClickCount=0),this._adminClickTimer&&clearTimeout(this._adminClickTimer),this._adminClickTimer=setTimeout(()=>{this._adminClickCount=0},2e3)}connectedCallback(){super.connectedCallback(),Y.start(),Y.onStateChange(async e=>{try{let t=this.clientId||window.BariwebConfig?.clientId||``,n=await fetch(`http://localhost:8000/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({fingerprint:e.fingerprint})});if(n.ok){let e=await n.json();this._currentScreenLabel=e.matched?e.label:``}}catch{}}),window.addEventListener(`keydown`,this._handleGlobalKeydown)}updated(e){super.updated(e);let t=!!this._chat.pendingConfirmation;t&&!this._hadPendingConfirmation&&this._chat.isVoiceModeActive()&&setTimeout(()=>{this._sttState===`idle`&&this._startRecording()},500),this._hadPendingConfirmation=t}disconnectedCallback(){super.disconnectedCallback(),Y.stop(),this._cleanupRecording(),window.removeEventListener(`keydown`,this._handleGlobalKeydown)}_beep(e){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t.currentTime),r.gain.setValueAtTime(.1,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-5,t.currentTime+.1),n.connect(r),r.connect(t.destination),n.start(),n.stop(t.currentTime+.1)}catch{}}_toggle(){this._isOpen=!this._isOpen,this._isOpen&&this._scrollMessages()}setOpen(e){this._isOpen=e,e&&this._scrollMessages()}_setTab(e){this._activeTab=e,e===`chat`&&(this._scrollMessages(),setTimeout(()=>{this.renderRoot?.querySelector(`#bw-voice-btn`)?.focus()},300))}_handleInput(e){this._inputValue=e.target.value}_handleKeydown(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this._handleSend()),e.code===`Space`&&e.target.tagName!==`INPUT`&&(e.preventDefault(),this._sttState===`idle`&&this._startRecording())}async _handleSend(){let e=this._inputValue.trim();if(!e||this._chat.isLoading||this._sttState!==`idle`)return;this._inputValue=``;let t=this._chat.sendMessage(e,!1);this._scrollMessages(),await t,this._scrollMessages()}_scrollMessages(){this.updateComplete.then(()=>{this._messagesEl&&(this._messagesEl.scrollTop=this._messagesEl.scrollHeight)})}_getCurrentHue(){let e=this._a11y.settings;return e.activeColorTab===`background`?e.customBgHue||0:e.activeColorTab===`header`?e.customHeaderHue||0:e.customContentHue||0}_resetWidgetSettings(){this._a11y.reset(),this._aiA11y.simplifyEnabled&&this._aiA11y.toggleSimplify(),this._aiA11y.autoA11yEnabled&&this._aiA11y.toggleAutoA11y(),this._setSttLanguageMode(`auto`),this.requestUpdate()}_clearSttTimers(){this._silenceIntervalId!==null&&(window.clearInterval(this._silenceIntervalId),this._silenceIntervalId=null),this._maxDurationTimeoutId!==null&&(window.clearTimeout(this._maxDurationTimeoutId),this._maxDurationTimeoutId=null)}_cleanupRecording(){this._clearSttTimers(),this._analyser=null,this._scriptProcessor&&=(this._scriptProcessor.disconnect(),this._scriptProcessor.onaudioprocess=null,null),this._audioContext&&=(this._audioContext.close().catch(()=>{}),null),this._mediaStream&&=(this._mediaStream.getTracks().forEach(e=>e.stop()),null),this._pcmChunks=[],this._silenceStartedTs=null}async _toggleVoice(){if(this._sttState!==`processing`){if(this._sttState===`recording`){this._stopRecording();return}await this._startRecording()}}async _startRecording(){if(!navigator.mediaDevices?.getUserMedia){this._sttState=`error`,this._sttError=this._t(`errorMicNotSupported`);return}try{this._cleanupRecording(),this._sttError=``;let e=await navigator.mediaDevices.getUserMedia({audio:!0});this._mediaStream=e,this._pcmChunks=[],this._recordingStartTs=Date.now(),this._silenceStartedTs=null,this._audioContext=new AudioContext,this._sampleRate=this._audioContext.sampleRate;let t=this._audioContext.createMediaStreamSource(e);this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,t.connect(this._analyser),this._scriptProcessor=this._audioContext.createScriptProcessor(4096,1,1),t.connect(this._scriptProcessor),this._scriptProcessor.connect(this._audioContext.destination),this._scriptProcessor.onaudioprocess=e=>{this._sttState===`recording`&&(this._pcmChunks.push(new Float32Array(e.inputBuffer.getChannelData(0))),e.outputBuffer.getChannelData(0).fill(0))},this._sttState=`recording`,this._beep(880),this._maxDurationTimeoutId=window.setTimeout(()=>{this._sttState===`recording`&&this._stopRecording()},Jt);let n=new Uint8Array(this._analyser.fftSize);this._silenceIntervalId=window.setInterval(()=>{if(!this._analyser||this._sttState!==`recording`)return;this._analyser.getByteTimeDomainData(n);let e=0;for(let t=0;t<n.length;t++){let r=(n[t]-128)/128;e+=r*r}Math.sqrt(e/n.length)<Kt?this._silenceStartedTs?Date.now()-this._silenceStartedTs>=qt&&this._stopRecording():this._silenceStartedTs=Date.now():this._silenceStartedTs=null},Gt)}catch{this._sttState=`error`,this._sttError=this._t(`errorNoMicAccess`),this._cleanupRecording()}}_stopRecording(){this._sttState===`recording`&&(this._clearSttTimers(),this._sttState=`processing`,this._beep(440),this._finalizeRecording().catch(e=>{this._sttState=`error`,this._sttError=e?.message||this._t(`errorProcessing`)}))}async _finalizeRecording(){let e=Date.now()-this._recordingStartTs,t=this._pcmChunks.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let e of this._pcmChunks)n.set(e,r),r+=e.length;let i=this._encodeWav(n,this._sampleRate);if(this._cleanupRecording(),e<Yt||i.size===0){this._sttState=`error`,this._sttError=this._t(`errorTooShort`);return}try{let e=(await this._chat.transcribeAudio(i,this._sttLanguageMode)).text?.trim();if(!e){this._sttState=`error`,this._sttError=this._t(`errorSpeechNotRecognized`);return}await this._chat.sendMessage(e,!0),this._sttState=`idle`,this._sttError=``,this._inputValue=``,this._scrollMessages()}catch(e){this._sttState=`error`,this._sttError=e?.message||this._t(`errorRecognition`)}}_encodeWav(e,t){let n=t*2,r=e.length*2,i=new ArrayBuffer(44+r),a=new DataView(i),o=(e,t)=>{for(let n=0;n<t.length;n++)a.setUint8(e+n,t.charCodeAt(n))};o(0,`RIFF`),a.setUint32(4,36+r,!0),o(8,`WAVE`),o(12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),o(36,`data`),a.setUint32(40,r,!0);let s=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));a.setInt16(s,n<0?n*32768:n*32767,!0),s+=2}return new Blob([i],{type:`audio/wav`})}_vibrate(){`vibrate`in navigator&&navigator.vibrate(20)}_renderChatTab(){let e=this._chat.messages,t=this._chat.isLoading,n=this._chat.pendingConfirmation,r=t||this._sttState!==`idle`,i=e=>this._t(e);return j`
1163
+ `,Z=null,Q=null}));Dt();var Wt=`bw-stt-lang-v1`,Gt=200,Kt=.015,qt=1200,Jt=2e4,Yt=350,Xt={ru:{announceVoiceInputAvailable:`Голосовой ввод доступен. Кнопка в нижнем правом углу.`,announceWidgetOpened:`Виджет открыт.`,announceSwitchedToChat:`Переход в чат. Голосовой ввод доступен.`,errorMicNotSupported:`Микрофон не поддерживается.`,errorNoMicAccess:`Нет доступа к микрофону.`,errorProcessing:`Ошибка обработки.`,errorTooShort:`Слишком короткая запись.`,errorSpeechNotRecognized:`Речь не распознана.`,errorRecognition:`Ошибка распознавания.`,screenLabelPrefix:`На странице:`,chatEmptyTitle:`Ваш помощник`,chatEmptySub:`Опишите задачу — я найду нужные кнопки и заполню поля за вас.`,confirmAction:`Подтвердить действие`,cancel:`Отменить`,listening:`Слушаю... (остановлюсь по тишине)`,recognizingSpeech:`Распознаю речь...`,micAria:`Включить голосовой ввод (удерживайте для записи)`,inputPlaceholder:`Введите сообщение...`,inputAria:`Текстовое поле ввода сообщения`,ttsDisableAria:`Выключить озвучку ответа`,ttsEnableAria:`Включить озвучку ответа`,sendAria:`Отправить сообщение`,tileTextSize:`Размер текста`,tileMonochrome:`Ч/Б`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Тёмный`,tileLinks:`Ссылки`,valueHighlight:`Выделить`,tileSpacing:`Отступы`,valueEnlarge:`Увеличить`,tileFont:`Шрифт`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Голос`,valueRecording:`Запись...`,valuePress:`Нажмите`,colorSetup:`Настройка цвета`,tabBackground:`Фон`,tabHeader:`Шапка`,tabText:`Текст`,decrease:`Уменьшить`,hue:`Оттенок`,increase:`Увеличить`,recognitionLanguage:`Язык`,changeRecognitionLanguage:`Изменить язык распознавания`,languageAuto:`Автоопределение`,languageKz:`Казахский`,languageRu:`Русский`,languageEn:`Английский`,aiSimplify:`AI Упрощение текста`,aiBlindMode:`Режим для незрячих (AI)`,on:`ВКЛ`,off:`ВЫКЛ`,resetSettings:`Сбросить настройки`,adminMode:`Режим администратора`,adminAccess:`Admin доступ`,adminLoggedIn:`Вы вошли как администратор`,adminLogout:`Выйти из аккаунта`,adminPrompt:`Введите ключ для активации режима обучения`,adminLogin:`Войти`,close:`Закрыть`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Настройки`,madeInKazakhstan:`Сделано в Казахстане 🇰🇿`,closeWidgetAria:`Закрыть`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Открыть/Закрыть меню доступности`,adminKeyPlaceholder:`Admin Key`},kz:{announceVoiceInputAvailable:`Дауыстық енгізу қолжетімді. Түйме төменгі оң жақ бұрышта.`,announceWidgetOpened:`Виджет ашылды.`,announceSwitchedToChat:`Чатқа ауысты. Дауыстық енгізу қолжетімді.`,errorMicNotSupported:`Микрофонға қолдау жоқ.`,errorNoMicAccess:`Микрофонға рұқсат жоқ.`,errorProcessing:`Өңдеу қатесі.`,errorTooShort:`Жазба тым қысқа.`,errorSpeechNotRecognized:`Сөйлеу танылмады.`,errorRecognition:`Тану қатесі.`,screenLabelPrefix:`Бетте:`,chatEmptyTitle:`Сіздің көмекшіңіз`,chatEmptySub:`Міндетті сипаттаңыз — мен керек батырмаларды тауып, өрістерді толтырамын.`,confirmAction:`Әрекетті растау`,cancel:`Бас тарту`,listening:`Тыңдап тұрмын... (үнсіздікте тоқтаймын)`,recognizingSpeech:`Сөйлеуді танып жатырмын...`,micAria:`Дауыстық енгізуді қосу (жазу үшін ұстап тұрыңыз)`,inputPlaceholder:`Хабарлама енгізіңіз...`,inputAria:`Хабарлама енгізу өрісі`,ttsDisableAria:`Жауап дауысын өшіру`,ttsEnableAria:`Жауап дауысын қосу`,sendAria:`Хабарламаны жіберу`,tileTextSize:`Мәтін өлшемі`,tileMonochrome:`Қ/А`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Қою`,tileLinks:`Сілтемелер`,valueHighlight:`Белгілеу`,tileSpacing:`Аралықтар`,valueEnlarge:`Үлкейту`,tileFont:`Қаріп`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Дауыс`,valueRecording:`Жазып жатыр...`,valuePress:`Басыңыз`,colorSetup:`Түсті баптау`,tabBackground:`Фон`,tabHeader:`Тақырып`,tabText:`Мәтін`,decrease:`Азайту`,hue:`Реңк`,increase:`Көбейту`,recognitionLanguage:`Тіл`,changeRecognitionLanguage:`Тану тілін өзгерту`,languageAuto:`Автоанықтау`,languageKz:`Қазақша`,languageRu:`Орысша`,languageEn:`Ағылшынша`,aiSimplify:`AI мәтінді жеңілдету`,aiBlindMode:`Көру қабілеті нашарларға режим (AI)`,on:`ҚОС`,off:`ӨШІК`,resetSettings:`Баптауларды қалпына келтіру`,adminMode:`Әкімші режимі`,adminAccess:`Admin қолжетімділігі`,adminLoggedIn:`Сіз әкімші ретінде кірдіңіз`,adminLogout:`Аккаунттан шығу`,adminPrompt:`Оқыту режимін қосу үшін кілт енгізіңіз`,adminLogin:`Кіру`,close:`Жабу`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Баптаулар`,madeInKazakhstan:`Қазақстанда жасалған 🇰🇿`,closeWidgetAria:`Жабу`,widgetDialogAria:`BariWeb қолжетімділік виджеті`,triggerAria:`Қолжетімділік мәзірін ашу/жабу`,adminKeyPlaceholder:`Admin Key`},en:{announceVoiceInputAvailable:`Voice input is available. The button is in the bottom-right corner.`,announceWidgetOpened:`Widget opened.`,announceSwitchedToChat:`Switched to chat. Voice input is available.`,errorMicNotSupported:`Microphone is not supported.`,errorNoMicAccess:`No access to microphone.`,errorProcessing:`Processing error.`,errorTooShort:`Recording is too short.`,errorSpeechNotRecognized:`Speech was not recognized.`,errorRecognition:`Recognition error.`,screenLabelPrefix:`On page:`,chatEmptyTitle:`Your assistant`,chatEmptySub:`Describe your task — I will find the right buttons and fill fields for you.`,confirmAction:`Confirm action`,cancel:`Cancel`,listening:`Listening... (will stop on silence)`,recognizingSpeech:`Recognizing speech...`,micAria:`Enable voice input (hold to record)`,inputPlaceholder:`Type a message...`,inputAria:`Message input field`,ttsDisableAria:`Disable answer voice`,ttsEnableAria:`Enable answer voice`,sendAria:`Send message`,tileTextSize:`Text size`,tileMonochrome:`B/W`,valueMonochrome:`Monochrome`,tileContrast:`Contrast`,valueDark:`Dark`,tileLinks:`Links`,valueHighlight:`Highlight`,tileSpacing:`Spacing`,valueEnlarge:`Enlarge`,tileFont:`Font`,valueDyslexia:`Dyslexia`,tileCursor:`Cursor`,tileVoice:`Voice`,valueRecording:`Recording...`,valuePress:`Press`,colorSetup:`Color setup`,tabBackground:`Background`,tabHeader:`Header`,tabText:`Text`,decrease:`Decrease`,hue:`Hue`,increase:`Increase`,recognitionLanguage:`Language`,changeRecognitionLanguage:`Change recognition language`,languageAuto:`Auto detect`,languageKz:`Kazakh`,languageRu:`Russian`,languageEn:`English`,aiSimplify:`AI text simplification`,aiBlindMode:`Blind mode (AI)`,on:`ON`,off:`OFF`,resetSettings:`Reset settings`,adminMode:`Administrator mode`,adminAccess:`Admin access`,adminLoggedIn:`You are logged in as administrator`,adminLogout:`Log out`,adminPrompt:`Enter key to activate training mode`,adminLogin:`Log in`,close:`Close`,inclusion:`Inclusion`,tabChat:`Chat`,tabSettings:`Settings`,madeInKazakhstan:`Made in Kazakhstan 🇰🇿`,closeWidgetAria:`Close`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Open/close accessibility menu`,adminKeyPlaceholder:`Admin Key`}},$=class extends B{static{this.styles=[dt]}constructor(){super(),this._a11y=new pt(this),this._aiA11y=new kt(this),this._chat=new It(this),this.clientId=``,this._isOpen=!1,this._activeTab=`chat`,this._inputValue=``,this._isAdmin=!1,this._adminPassword=``,this._authError=``,this._currentScreenLabel=``,this._sttState=`idle`,this._sttLanguageMode=`auto`,this._sttError=``,this._adminClickCount=0,this._showAdminLogin=!1,this._mediaStream=null,this._audioContext=null,this._analyser=null,this._scriptProcessor=null,this._pcmChunks=[],this._sampleRate=44100,this._recordingStartTs=0,this._silenceStartedTs=null,this._silenceIntervalId=null,this._maxDurationTimeoutId=null,this._adminClickTimer=null,this._hadPendingConfirmation=!1,this._handleGlobalKeydown=e=>{this._isOpen&&e.altKey&&e.code===`KeyV`&&(e.preventDefault(),this._toggleVoice())};try{let e=localStorage.getItem(Wt);(e===`auto`||e===`kz`||e===`ru`||e===`en`)&&(this._sttLanguageMode=e)}catch{}this._checkAuthStatus()}_setSttLanguageMode(e){this._sttLanguageMode=e;try{localStorage.setItem(Wt,e)}catch{}}_uiLang(){return this._sttLanguageMode===`kz`?`kz`:this._sttLanguageMode===`en`?`en`:`ru`}_t(e){return Xt[this._uiLang()][e]??Xt.ru[e]??e}async _checkAuthStatus(){let e=localStorage.getItem(`bw_admin_token`);if(e)try{(await fetch(`https://aidyn-backend.gitlabapp.alem.ai/auth/login/widget/verify`,{headers:{Authorization:`Bearer ${e}`}})).ok?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{try{let t=JSON.parse(atob(e.split(`.`)[1]));t.exp*1e3>Date.now()&&t.role===`admin`?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{localStorage.removeItem(`bw_admin_token`)}}}async _loadAdminUI(){try{let{initAdminMode:e}=await Promise.resolve().then(()=>(Ut(),Lt));e(),Y.isAutoDiscoveryEnabled=!0}catch(e){console.error(`Admin UI load failed`,e)}}async _handleAdminLogin(){this._authError=``;let e=this.clientId||window.BariwebConfig?.clientId||``;if(!e){this._authError=`Client ID not configured`;return}try{let t=await fetch(`https://aidyn-backend.gitlabapp.alem.ai/auth/login/widget`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_public_id:e,admin_key:this._adminPassword})});if(t.ok){let{access_token:e}=await t.json();localStorage.setItem(`bw_admin_token`,e),this._isAdmin=!0,this._showAdminLogin=!1,this._loadAdminUI()}else this._authError=(await t.json().catch(()=>({}))).detail||`Invalid admin key`}catch{this._authError=`Connection failed`}}_handleAdminLogout(){localStorage.removeItem(`bw_admin_token`),this._isAdmin=!1,this._adminPassword=``,this._showAdminLogin=!1,Y.isAutoDiscoveryEnabled=!1,document.querySelector(`#bw-admin-wrapper`)?.remove()}_handleLogoClick(){this._adminClickCount++,this._adminClickCount>=5&&(this._showAdminLogin=!this._showAdminLogin,this._adminClickCount=0),this._adminClickTimer&&clearTimeout(this._adminClickTimer),this._adminClickTimer=setTimeout(()=>{this._adminClickCount=0},2e3)}connectedCallback(){super.connectedCallback(),Y.start(),Y.onStateChange(async e=>{try{let t=this.clientId||window.BariwebConfig?.clientId||``,n=await fetch(`https://aidyn-backend.gitlabapp.alem.ai/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({fingerprint:e.fingerprint})});if(n.ok){let e=await n.json();this._currentScreenLabel=e.matched?e.label:``}}catch{}}),window.addEventListener(`keydown`,this._handleGlobalKeydown)}updated(e){super.updated(e);let t=!!this._chat.pendingConfirmation;t&&!this._hadPendingConfirmation&&this._chat.isVoiceModeActive()&&setTimeout(()=>{this._sttState===`idle`&&this._startRecording()},500),this._hadPendingConfirmation=t}disconnectedCallback(){super.disconnectedCallback(),Y.stop(),this._cleanupRecording(),window.removeEventListener(`keydown`,this._handleGlobalKeydown)}_beep(e){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t.currentTime),r.gain.setValueAtTime(.1,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-5,t.currentTime+.1),n.connect(r),r.connect(t.destination),n.start(),n.stop(t.currentTime+.1)}catch{}}_toggle(){this._isOpen=!this._isOpen,this._isOpen&&this._scrollMessages()}setOpen(e){this._isOpen=e,e&&this._scrollMessages()}_setTab(e){this._activeTab=e,e===`chat`&&(this._scrollMessages(),setTimeout(()=>{this.renderRoot?.querySelector(`#bw-voice-btn`)?.focus()},300))}_handleInput(e){this._inputValue=e.target.value}_handleKeydown(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this._handleSend()),e.code===`Space`&&e.target.tagName!==`INPUT`&&(e.preventDefault(),this._sttState===`idle`&&this._startRecording())}async _handleSend(){let e=this._inputValue.trim();if(!e||this._chat.isLoading||this._sttState!==`idle`)return;this._inputValue=``;let t=this._chat.sendMessage(e,!1);this._scrollMessages(),await t,this._scrollMessages()}_scrollMessages(){this.updateComplete.then(()=>{this._messagesEl&&(this._messagesEl.scrollTop=this._messagesEl.scrollHeight)})}_getCurrentHue(){let e=this._a11y.settings;return e.activeColorTab===`background`?e.customBgHue||0:e.activeColorTab===`header`?e.customHeaderHue||0:e.customContentHue||0}_resetWidgetSettings(){this._a11y.reset(),this._aiA11y.simplifyEnabled&&this._aiA11y.toggleSimplify(),this._aiA11y.autoA11yEnabled&&this._aiA11y.toggleAutoA11y(),this._setSttLanguageMode(`auto`),this.requestUpdate()}_clearSttTimers(){this._silenceIntervalId!==null&&(window.clearInterval(this._silenceIntervalId),this._silenceIntervalId=null),this._maxDurationTimeoutId!==null&&(window.clearTimeout(this._maxDurationTimeoutId),this._maxDurationTimeoutId=null)}_cleanupRecording(){this._clearSttTimers(),this._analyser=null,this._scriptProcessor&&=(this._scriptProcessor.disconnect(),this._scriptProcessor.onaudioprocess=null,null),this._audioContext&&=(this._audioContext.close().catch(()=>{}),null),this._mediaStream&&=(this._mediaStream.getTracks().forEach(e=>e.stop()),null),this._pcmChunks=[],this._silenceStartedTs=null}async _toggleVoice(){if(this._sttState!==`processing`){if(this._sttState===`recording`){this._stopRecording();return}await this._startRecording()}}async _startRecording(){if(!navigator.mediaDevices?.getUserMedia){this._sttState=`error`,this._sttError=this._t(`errorMicNotSupported`);return}try{this._cleanupRecording(),this._sttError=``;let e=await navigator.mediaDevices.getUserMedia({audio:!0});this._mediaStream=e,this._pcmChunks=[],this._recordingStartTs=Date.now(),this._silenceStartedTs=null,this._audioContext=new AudioContext,this._sampleRate=this._audioContext.sampleRate;let t=this._audioContext.createMediaStreamSource(e);this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,t.connect(this._analyser),this._scriptProcessor=this._audioContext.createScriptProcessor(4096,1,1),t.connect(this._scriptProcessor),this._scriptProcessor.connect(this._audioContext.destination),this._scriptProcessor.onaudioprocess=e=>{this._sttState===`recording`&&(this._pcmChunks.push(new Float32Array(e.inputBuffer.getChannelData(0))),e.outputBuffer.getChannelData(0).fill(0))},this._sttState=`recording`,this._beep(880),this._maxDurationTimeoutId=window.setTimeout(()=>{this._sttState===`recording`&&this._stopRecording()},Jt);let n=new Uint8Array(this._analyser.fftSize);this._silenceIntervalId=window.setInterval(()=>{if(!this._analyser||this._sttState!==`recording`)return;this._analyser.getByteTimeDomainData(n);let e=0;for(let t=0;t<n.length;t++){let r=(n[t]-128)/128;e+=r*r}Math.sqrt(e/n.length)<Kt?this._silenceStartedTs?Date.now()-this._silenceStartedTs>=qt&&this._stopRecording():this._silenceStartedTs=Date.now():this._silenceStartedTs=null},Gt)}catch{this._sttState=`error`,this._sttError=this._t(`errorNoMicAccess`),this._cleanupRecording()}}_stopRecording(){this._sttState===`recording`&&(this._clearSttTimers(),this._sttState=`processing`,this._beep(440),this._finalizeRecording().catch(e=>{this._sttState=`error`,this._sttError=e?.message||this._t(`errorProcessing`)}))}async _finalizeRecording(){let e=Date.now()-this._recordingStartTs,t=this._pcmChunks.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let e of this._pcmChunks)n.set(e,r),r+=e.length;let i=this._encodeWav(n,this._sampleRate);if(this._cleanupRecording(),e<Yt||i.size===0){this._sttState=`error`,this._sttError=this._t(`errorTooShort`);return}try{let e=(await this._chat.transcribeAudio(i,this._sttLanguageMode)).text?.trim();if(!e){this._sttState=`error`,this._sttError=this._t(`errorSpeechNotRecognized`);return}await this._chat.sendMessage(e,!0),this._sttState=`idle`,this._sttError=``,this._inputValue=``,this._scrollMessages()}catch(e){this._sttState=`error`,this._sttError=e?.message||this._t(`errorRecognition`)}}_encodeWav(e,t){let n=t*2,r=e.length*2,i=new ArrayBuffer(44+r),a=new DataView(i),o=(e,t)=>{for(let n=0;n<t.length;n++)a.setUint8(e+n,t.charCodeAt(n))};o(0,`RIFF`),a.setUint32(4,36+r,!0),o(8,`WAVE`),o(12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),o(36,`data`),a.setUint32(40,r,!0);let s=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));a.setInt16(s,n<0?n*32768:n*32767,!0),s+=2}return new Blob([i],{type:`audio/wav`})}_vibrate(){`vibrate`in navigator&&navigator.vibrate(20)}_renderChatTab(){let e=this._chat.messages,t=this._chat.isLoading,n=this._chat.pendingConfirmation,r=t||this._sttState!==`idle`,i=e=>this._t(e);return j`
1164
1164
  <div class="chat-messages" id="bw-chat-messages">
1165
1165
  ${this._currentScreenLabel?j`
1166
1166
  <div class="screen-label-badge">
@@ -1413,4 +1413,4 @@
1413
1413
  ${this._isOpen?W.close:W.accessibility}
1414
1414
  </button>
1415
1415
  </div>
1416
- `}};X([it({type:String,attribute:`client-id`})],$.prototype,`clientId`,void 0),X([V()],$.prototype,`_isOpen`,void 0),X([V()],$.prototype,`_activeTab`,void 0),X([V()],$.prototype,`_inputValue`,void 0),X([V()],$.prototype,`_isAdmin`,void 0),X([V()],$.prototype,`_adminPassword`,void 0),X([V()],$.prototype,`_authError`,void 0),X([V()],$.prototype,`_currentScreenLabel`,void 0),X([V()],$.prototype,`_sttState`,void 0),X([V()],$.prototype,`_sttLanguageMode`,void 0),X([V()],$.prototype,`_sttError`,void 0),X([V()],$.prototype,`_adminClickCount`,void 0),X([V()],$.prototype,`_showAdminLogin`,void 0),X([ot(`.chat-messages`)],$.prototype,`_messagesEl`,void 0),$=X([tt(`bw-widget`)],$);var Zt=()=>{let e=document.querySelector(`bw-widget`)?.getAttribute(`client-id`);if(e)return e;let t=(document.currentScript||document.querySelector(`script[src*="bariweb"]`))?.getAttribute(`data-client-id`);return t||=document.querySelector(`script[data-client-id]`)?.getAttribute(`data-client-id`)||``,t||window.__BARIWEB_CLIENT_ID__||``},Qt=Zt();window.__BARIWEB_CLIENT_ID__=Qt,pe.setConfig({baseUrl:`http://localhost:8000`}),pe.interceptors.request.use(e=>{let t=Zt();return e.headers.set(`X-Client-ID`,t),e})})();
1416
+ `}};X([it({type:String,attribute:`client-id`})],$.prototype,`clientId`,void 0),X([V()],$.prototype,`_isOpen`,void 0),X([V()],$.prototype,`_activeTab`,void 0),X([V()],$.prototype,`_inputValue`,void 0),X([V()],$.prototype,`_isAdmin`,void 0),X([V()],$.prototype,`_adminPassword`,void 0),X([V()],$.prototype,`_authError`,void 0),X([V()],$.prototype,`_currentScreenLabel`,void 0),X([V()],$.prototype,`_sttState`,void 0),X([V()],$.prototype,`_sttLanguageMode`,void 0),X([V()],$.prototype,`_sttError`,void 0),X([V()],$.prototype,`_adminClickCount`,void 0),X([V()],$.prototype,`_showAdminLogin`,void 0),X([ot(`.chat-messages`)],$.prototype,`_messagesEl`,void 0),$=X([tt(`bw-widget`)],$);var Zt=()=>{let e=document.querySelector(`bw-widget`)?.getAttribute(`client-id`);if(e)return e;let t=(document.currentScript||document.querySelector(`script[src*="bariweb"]`))?.getAttribute(`data-client-id`);return t||=document.querySelector(`script[data-client-id]`)?.getAttribute(`data-client-id`)||``,t||window.__BARIWEB_CLIENT_ID__||``},Qt=Zt();window.__BARIWEB_CLIENT_ID__=Qt,pe.setConfig({baseUrl:`https://arif-altas.vercel.app/api`}),pe.interceptors.request.use(e=>{let t=Zt();return e.headers.set(`X-Client-ID`,t),e})})();
package/dist/bariweb.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as e, t } from "./Watcher-CrSaF4Ov.js";
1
+ import { r as e, t } from "./Watcher-DBoOp_Qp.js";
2
2
  //#region src/lib/api/core/bodySerializer.gen.ts
3
3
  var n = { bodySerializer: (e) => JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t) };
4
4
  Object.entries({
@@ -489,7 +489,7 @@ var m = async (e, t) => {
489
489
  },
490
490
  trace: c("TRACE")
491
491
  };
492
- })(ue({ baseUrl: "http://localhost:8000" })), _ = globalThis, v = _.ShadowRoot && (_.ShadyCSS === void 0 || _.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype, y = Symbol(), fe = /* @__PURE__ */ new WeakMap(), pe = class {
492
+ })(ue({ baseUrl: "https://aidyn-backend.gitlabapp.alem.ai" })), _ = globalThis, v = _.ShadowRoot && (_.ShadyCSS === void 0 || _.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype, y = Symbol(), fe = /* @__PURE__ */ new WeakMap(), pe = class {
493
493
  constructor(e, t, n) {
494
494
  if (this._$cssResult$ = !0, n !== y) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
495
495
  this.cssText = e, this.t = t;
@@ -2022,7 +2022,7 @@ var it = nt(q), J = (e) => I`${it(`
2022
2022
  reset() {
2023
2023
  this.settings = { ...X }, this._saveSettings();
2024
2024
  }
2025
- }, ct = "http://localhost:8000", lt = class {
2025
+ }, ct = "https://arif-altas.vercel.app/api", lt = class {
2026
2026
  constructor(e) {
2027
2027
  this.isFixing = !1, this.simplifyEnabled = !1, this.autoA11yEnabled = !1, this._onParagraphKeydown = (e) => {
2028
2028
  if (this.simplifyEnabled && (e.key === "Enter" || e.key === " ") && e.target instanceof HTMLElement) {
@@ -2216,7 +2216,7 @@ var it = nt(q), J = (e) => I`${it(`
2216
2216
  let n = e.split("-")[0].toLowerCase();
2217
2217
  return t.find((t) => t.lang.toLowerCase() === e.toLowerCase()) || t.find((e) => e.lang.toLowerCase().startsWith(n)) || t[0] || null;
2218
2218
  }
2219
- }, Z = "http://localhost:8000", ft = 5, pt = [/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];
2219
+ }, Z = "https://arif-altas.vercel.app/api", ft = 5, pt = [/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];
2220
2220
  function mt(e) {
2221
2221
  if (e.type !== "click_element" || !e.element_id) return !1;
2222
2222
  let t = document.getElementById(e.element_id);
@@ -2844,7 +2844,7 @@ var gt = "bw-stt-lang-v1", _t = 200, vt = .015, yt = 1200, bt = 2e4, xt = 350, S
2844
2844
  async _checkAuthStatus() {
2845
2845
  let e = localStorage.getItem("bw_admin_token");
2846
2846
  if (e) try {
2847
- (await fetch("http://localhost:8000/auth/login/widget/verify", { headers: { Authorization: `Bearer ${e}` } })).ok ? (this._isAdmin = !0, this._loadAdminUI()) : localStorage.removeItem("bw_admin_token");
2847
+ (await fetch("https://aidyn-backend.gitlabapp.alem.ai/auth/login/widget/verify", { headers: { Authorization: `Bearer ${e}` } })).ok ? (this._isAdmin = !0, this._loadAdminUI()) : localStorage.removeItem("bw_admin_token");
2848
2848
  } catch {
2849
2849
  try {
2850
2850
  let t = JSON.parse(atob(e.split(".")[1]));
@@ -2856,7 +2856,7 @@ var gt = "bw-stt-lang-v1", _t = 200, vt = .015, yt = 1200, bt = 2e4, xt = 350, S
2856
2856
  }
2857
2857
  async _loadAdminUI() {
2858
2858
  try {
2859
- let { initAdminMode: e } = await import("./AdminUI-CGKuDZdZ.js");
2859
+ let { initAdminMode: e } = await import("./AdminUI-CK2vbxtW.js");
2860
2860
  e(), t.isAutoDiscoveryEnabled = !0;
2861
2861
  } catch (e) {
2862
2862
  console.error("Admin UI load failed", e);
@@ -2870,7 +2870,7 @@ var gt = "bw-stt-lang-v1", _t = 200, vt = .015, yt = 1200, bt = 2e4, xt = 350, S
2870
2870
  return;
2871
2871
  }
2872
2872
  try {
2873
- let t = await fetch("http://localhost:8000/auth/login/widget", {
2873
+ let t = await fetch("https://aidyn-backend.gitlabapp.alem.ai/auth/login/widget", {
2874
2874
  method: "POST",
2875
2875
  headers: { "Content-Type": "application/json" },
2876
2876
  body: JSON.stringify({
@@ -2897,7 +2897,7 @@ var gt = "bw-stt-lang-v1", _t = 200, vt = .015, yt = 1200, bt = 2e4, xt = 350, S
2897
2897
  connectedCallback() {
2898
2898
  super.connectedCallback(), t.start(), t.onStateChange(async (e) => {
2899
2899
  try {
2900
- let t = this.clientId || window.BariwebConfig?.clientId || "", n = await fetch("http://localhost:8000/v1/training/match-screen", {
2900
+ let t = this.clientId || window.BariwebConfig?.clientId || "", n = await fetch("https://aidyn-backend.gitlabapp.alem.ai/v1/training/match-screen", {
2901
2901
  method: "POST",
2902
2902
  headers: {
2903
2903
  "Content-Type": "application/json",
@@ -3415,7 +3415,7 @@ var Ct = () => {
3415
3415
  let t = (document.currentScript || document.querySelector("script[src*=\"bariweb\"]"))?.getAttribute("data-client-id");
3416
3416
  return t ||= document.querySelector("script[data-client-id]")?.getAttribute("data-client-id") || "", t || window.__BARIWEB_CLIENT_ID__ || "";
3417
3417
  }, wt = Ct();
3418
- window.__BARIWEB_CLIENT_ID__ = wt, de.setConfig({ baseUrl: "http://localhost:8000" }), de.interceptors.request.use((e) => {
3418
+ window.__BARIWEB_CLIENT_ID__ = wt, de.setConfig({ baseUrl: "https://arif-altas.vercel.app/api" }), de.interceptors.request.use((e) => {
3419
3419
  let t = Ct();
3420
3420
  return e.headers.set("X-Client-ID", t), e;
3421
3421
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bariweb-widget",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "type": "module",
5
5
  "main": "./dist/bariweb.iife.js",
6
6
  "module": "./dist/bariweb.js",
@@ -18,7 +18,7 @@
18
18
  "dev": "vite",
19
19
  "build": "tsc && vite build",
20
20
  "preview": "vite preview",
21
- "generate-api": "bunx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/lib/api"
21
+ "generate-api": "bunx @hey-api/openapi-ts -i https://aidyn-backend.gitlabapp.alem.ai/openapi.json -o src/lib/api"
22
22
  },
23
23
  "dependencies": {
24
24
  "@hey-api/openapi-ts": "^0.94.5",