acbridge 0.0.1 → 1.0.1

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.
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var eM=Object.create;var Jf=Object.defineProperty;var tM=Object.getOwnPropertyDescriptor;var nM=Object.getOwnPropertyNames;var rM=Object.getPrototypeOf,oM=Object.prototype.hasOwnProperty;var ct=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(o){throw n=[o],o}};var oe=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Xt=(t,e)=>{for(var n in e)Jf(t,n,{get:e[n],enumerable:!0})},iM=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of nM(e))!oM.call(t,r)&&r!==n&&Jf(t,r,{get:()=>e[r],enumerable:!(o=tM(e,r))||o.enumerable});return t};var G=(t,e,n)=>(n=t!=null?eM(rM(t)):{},iM(e||!t||!t.__esModule?Jf(n,"default",{value:t,enumerable:!0}):n,t));var wr=oe((mX,$T)=>{"use strict";var PT=["nodebuffer","arraybuffer","fragments"],DT=typeof Blob<"u";DT&&PT.push("blob");$T.exports={BINARY_TYPES:PT,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:DT,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $a=oe((gX,td)=>{"use strict";var{EMPTY_BUFFER:xj}=wr(),Rb=Buffer[Symbol.species];function Sj(t,e){if(t.length===0)return xj;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),o=0;for(let r=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return o<e?new Rb(n.buffer,n.byteOffset,o):n}function OT(t,e,n,o,r){for(let i=0;i<r;i++)n[o+i]=t[i]^e[i&3]}function LT(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function _j(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ab(t){if(Ab.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Rb(t):ArrayBuffer.isView(t)?e=new Rb(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ab.readOnly=!1),e}td.exports={concat:Sj,mask:OT,toArrayBuffer:_j,toBuffer:Ab,unmask:LT};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");td.exports.mask=function(e,n,o,r,i){i<48?OT(e,n,o,r,i):t.mask(e,n,o,r,i)},td.exports.unmask=function(e,n){e.length<32?LT(e,n):t.unmask(e,n)}}catch{}});var UT=oe((hX,MT)=>{"use strict";var NT=Symbol("kDone"),Pb=Symbol("kRun"),Db=class{constructor(e){this[NT]=()=>{this.pending--,this[Pb]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Pb]()}[Pb](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[NT])}}};MT.exports=Db});var as=oe((yX,zT)=>{"use strict";var Oa=require("zlib"),FT=$a(),Ij=UT(),{kStatusCode:BT}=wr(),Tj=Buffer[Symbol.species],Ej=Buffer.from([0,0,255,255]),rd=Symbol("permessage-deflate"),kr=Symbol("total-length"),is=Symbol("callback"),no=Symbol("buffers"),ss=Symbol("error"),nd,$b=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!nd){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;nd=new Ij(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[is];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,o=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!o)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(o.server_no_context_takeover=!0),n.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(o.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?o.client_max_window_bits=n.clientMaxWindowBits:(o.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(o=>{let r=n[o];if(r.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(r=r[0],o==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${o}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${r}`)}else if(o==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${o}": ${r}`);r=i}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${r}`)}else throw new Error(`Unknown parameter "${o}"`);n[o]=r})}),e}decompress(e,n,o){nd.add(r=>{this._decompress(e,n,(i,s)=>{r(),o(i,s)})})}compress(e,n,o){nd.add(r=>{this._compress(e,n,(i,s)=>{r(),o(i,s)})})}_decompress(e,n,o){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,s=typeof this.params[i]!="number"?Oa.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Oa.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[rd]=this,this._inflate[kr]=0,this._inflate[no]=[],this._inflate.on("error",Rj),this._inflate.on("data",jT)}this._inflate[is]=o,this._inflate.write(e),n&&this._inflate.write(Ej),this._inflate.flush(()=>{let i=this._inflate[ss];if(i){this._inflate.close(),this._inflate=null,o(i);return}let s=FT.concat(this._inflate[no],this._inflate[kr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kr]=0,this._inflate[no]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),o(null,s)})}_compress(e,n,o){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,s=typeof this.params[i]!="number"?Oa.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Oa.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[kr]=0,this._deflate[no]=[],this._deflate.on("data",Cj)}this._deflate[is]=o,this._deflate.write(e),this._deflate.flush(Oa.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=FT.concat(this._deflate[no],this._deflate[kr]);n&&(i=new Tj(i.buffer,i.byteOffset,i.length-4)),this._deflate[is]=null,this._deflate[kr]=0,this._deflate[no]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),o(null,i)})}};zT.exports=$b;function Cj(t){this[no].push(t),this[kr]+=t.length}function jT(t){if(this[kr]+=t.length,this[rd]._maxPayload<1||this[kr]<=this[rd]._maxPayload){this[no].push(t);return}this[ss]=new RangeError("Max payload size exceeded"),this[ss].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ss][BT]=1009,this.removeListener("data",jT),this.reset()}function Rj(t){if(this[rd]._inflate=null,this[ss]){this[is](this[ss]);return}t[BT]=1007,this[is](t)}});var cs=oe((vX,od)=>{"use strict";var{isUtf8:HT}=require("buffer"),{hasBlob:Aj}=wr(),Pj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Dj(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ob(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function $j(t){return Aj&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}od.exports={isBlob:$j,isValidStatusCode:Dj,isValidUTF8:Ob,tokenChars:Pj};if(HT)od.exports.isValidUTF8=function(t){return t.length<24?Ob(t):HT(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");od.exports.isValidUTF8=function(e){return e.length<32?Ob(e):t(e)}}catch{}});var Fb=oe((bX,JT)=>{"use strict";var{Writable:Oj}=require("stream"),KT=as(),{BINARY_TYPES:Lj,EMPTY_BUFFER:GT,kStatusCode:Nj,kWebSocket:Mj}=wr(),{concat:Lb,toArrayBuffer:Uj,unmask:Fj}=$a(),{isValidStatusCode:Bj,isValidUTF8:WT}=cs(),id=Buffer[Symbol.species],tn=0,ZT=1,qT=2,VT=3,Nb=4,Mb=5,sd=6,Ub=class extends Oj{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Lj[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Mj]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=tn}_write(e,n,o){if(this._opcode===8&&this._state==tn)return o();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){o(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(o)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new id(o.buffer,o.byteOffset+e,o.length-e),new id(o.buffer,o.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let o=this._buffers[0],r=n.length-e;e>=o.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(o.buffer,o.byteOffset,e),r),this._buffers[0]=new id(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case tn:this.getInfo(e);break;case ZT:this.getPayloadLength16(e);break;case qT:this.getPayloadLength64(e);break;case VT:this.getMask();break;case Nb:this.getData(e);break;case Mb:case sd:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let o=(n[0]&64)===64;if(o&&!this._extensions[KT.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(o){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(o){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=ZT:this._payloadLength===127?this._state=qT:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),o=n.readUInt32BE(0);if(o>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=o*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=VT:this._state=Nb}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Nb}getData(e){let n=GT;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Fj(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Mb,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[KT.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return n(r);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===tn&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=tn;return}let n=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=Lb(o,n):this._binaryType==="arraybuffer"?r=Uj(Lb(o,n)):this._binaryType==="blob"?r=new Blob(o):r=o,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=tn):(this._state=sd,setImmediate(()=>{this.emit("message",r,!0),this._state=tn,this.startLoop(e)}))}else{let r=Lb(o,n);if(!this._skipUTF8Validation&&!WT(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Mb||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=tn):(this._state=sd,setImmediate(()=>{this.emit("message",r,!1),this._state=tn,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,GT),this.end();else{let o=e.readUInt16BE(0);if(!Bj(o)){let i=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let r=new id(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!WT(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",o,r),this.end()}this._state=tn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=tn):(this._state=sd,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=tn,this.startLoop(n)}))}createError(e,n,o,r,i){this._loop=!1,this._errored=!0;let s=new e(o?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Nj]=r,s}};JT.exports=Ub});var zb=oe((kX,QT)=>{"use strict";var{Duplex:wX}=require("stream"),{randomFillSync:jj}=require("crypto"),{types:{isUint8Array:zj}}=require("util"),YT=as(),{EMPTY_BUFFER:Hj,kWebSocket:Kj,NOOP:Gj}=wr(),{isBlob:ls,isValidStatusCode:Wj}=cs(),{mask:XT,toBuffer:zo}=$a(),nn=Symbol("kByteLength"),Zj=Buffer.alloc(4),ad=8*1024,Ho,us=ad,vn=0,qj=1,Vj=2,Bb=class t{constructor(e,n,o){this._extensions=n||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=vn,this.onerror=Gj,this[Kj]=void 0}static frame(e,n){let o,r=!1,i=2,s=!1;n.mask&&(o=n.maskBuffer||Zj,n.generateMask?n.generateMask(o):(us===ad&&(Ho===void 0&&(Ho=Buffer.alloc(ad)),jj(Ho,0,ad),us=0),o[0]=Ho[us++],o[1]=Ho[us++],o[2]=Ho[us++],o[3]=Ho[us++]),s=(o[0]|o[1]|o[2]|o[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[nn]!==void 0?a=n[nn]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(r?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=o[0],l[i-3]=o[1],l[i-2]=o[2],l[i-1]=o[3],s?[l,e]:r?(XT(e,o,l,i,a),[l]):(XT(e,o,e,0,a),[l,e])):[l,e]}close(e,n,o,r){let i;if(e===void 0)i=Hj;else{if(typeof e!="number"||!Wj(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(zj(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[nn]:i.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==vn?this.enqueue([this.dispatch,i,!1,s,r]):this.sendFrame(t.frame(i,s),r)}ping(e,n,o){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ls(e)?(r=e.size,i=!1):(e=zo(e),r=e.length,i=zo.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[nn]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ls(e)?this._state!==vn?this.enqueue([this.getBlobData,e,!1,s,o]):this.getBlobData(e,!1,s,o):this._state!==vn?this.enqueue([this.dispatch,e,!1,s,o]):this.sendFrame(t.frame(e,s),o)}pong(e,n,o){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ls(e)?(r=e.size,i=!1):(e=zo(e),r=e.length,i=zo.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[nn]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ls(e)?this._state!==vn?this.enqueue([this.getBlobData,e,!1,s,o]):this.getBlobData(e,!1,s,o):this._state!==vn?this.enqueue([this.dispatch,e,!1,s,o]):this.sendFrame(t.frame(e,s),o)}send(e,n,o){let r=this._extensions[YT.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ls(e)?(a=e.size,c=!1):(e=zo(e),a=e.length,c=zo.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[nn]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};ls(e)?this._state!==vn?this.enqueue([this.getBlobData,e,this._compress,l,o]):this.getBlobData(e,this._compress,l,o):this._state!==vn?this.enqueue([this.dispatch,e,this._compress,l,o]):this.dispatch(e,this._compress,l,o)}getBlobData(e,n,o,r){this._bufferedBytes+=o[nn],this._state=Vj,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(jb,this,a,r);return}this._bufferedBytes-=o[nn];let s=zo(i);n?this.dispatch(s,n,o,r):(this._state=vn,this.sendFrame(t.frame(s,o),r),this.dequeue())}).catch(i=>{process.nextTick(Jj,this,i,r)})}dispatch(e,n,o,r){if(!n){this.sendFrame(t.frame(e,o),r);return}let i=this._extensions[YT.extensionName];this._bufferedBytes+=o[nn],this._state=qj,i.compress(e,o.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");jb(this,c,r);return}this._bufferedBytes-=o[nn],this._state=vn,o.readOnly=!1,this.sendFrame(t.frame(a,o),r),this.dequeue()})}dequeue(){for(;this._state===vn&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][nn],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][nn],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};QT.exports=Bb;function jb(t,e,n){typeof n=="function"&&n(e);for(let o=0;o<t._queue.length;o++){let r=t._queue[o],i=r[r.length-1];typeof i=="function"&&i(e)}}function Jj(t,e,n){jb(t,e,n),t.onerror(e)}});var cE=oe((xX,aE)=>{"use strict";var{kForOnEventAttribute:La,kListener:Hb}=wr(),eE=Symbol("kCode"),tE=Symbol("kData"),nE=Symbol("kError"),rE=Symbol("kMessage"),oE=Symbol("kReason"),ds=Symbol("kTarget"),iE=Symbol("kType"),sE=Symbol("kWasClean"),xr=class{constructor(e){this[ds]=null,this[iE]=e}get target(){return this[ds]}get type(){return this[iE]}};Object.defineProperty(xr.prototype,"target",{enumerable:!0});Object.defineProperty(xr.prototype,"type",{enumerable:!0});var Ko=class extends xr{constructor(e,n={}){super(e),this[eE]=n.code===void 0?0:n.code,this[oE]=n.reason===void 0?"":n.reason,this[sE]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[eE]}get reason(){return this[oE]}get wasClean(){return this[sE]}};Object.defineProperty(Ko.prototype,"code",{enumerable:!0});Object.defineProperty(Ko.prototype,"reason",{enumerable:!0});Object.defineProperty(Ko.prototype,"wasClean",{enumerable:!0});var ps=class extends xr{constructor(e,n={}){super(e),this[nE]=n.error===void 0?null:n.error,this[rE]=n.message===void 0?"":n.message}get error(){return this[nE]}get message(){return this[rE]}};Object.defineProperty(ps.prototype,"error",{enumerable:!0});Object.defineProperty(ps.prototype,"message",{enumerable:!0});var Na=class extends xr{constructor(e,n={}){super(e),this[tE]=n.data===void 0?null:n.data}get data(){return this[tE]}};Object.defineProperty(Na.prototype,"data",{enumerable:!0});var Yj={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[La]&&r[Hb]===e&&!r[La])return;let o;if(t==="message")o=function(i,s){let a=new Na("message",{data:s?i:i.toString()});a[ds]=this,cd(e,this,a)};else if(t==="close")o=function(i,s){let a=new Ko("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ds]=this,cd(e,this,a)};else if(t==="error")o=function(i){let s=new ps("error",{error:i,message:i.message});s[ds]=this,cd(e,this,s)};else if(t==="open")o=function(){let i=new xr("open");i[ds]=this,cd(e,this,i)};else return;o[La]=!!n[La],o[Hb]=e,n.once?this.once(t,o):this.on(t,o)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Hb]===e&&!n[La]){this.removeListener(t,n);break}}};aE.exports={CloseEvent:Ko,ErrorEvent:ps,Event:xr,EventTarget:Yj,MessageEvent:Na};function cd(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ld=oe((SX,lE)=>{"use strict";var{tokenChars:Ma}=cs();function Kn(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Xj(t){let e=Object.create(null),n=Object.create(null),o=!1,r=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Ma[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);l===44?(Kn(e,m,n),n=Object.create(null)):s=m,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Ma[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),Kn(n,t.slice(c,u),!0),l===44&&(Kn(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Ma[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:o||(o=!0),r=!1}else if(i)if(Ma[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Ma[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let m=t.slice(c,u);o&&(m=m.replace(/\\/g,""),o=!1),Kn(n,a,m),l===44&&(Kn(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(c,u);return s===void 0?Kn(e,f,n):(a===void 0?Kn(n,f,!0):o?Kn(n,a,f.replace(/\\/g,"")):Kn(n,a,f),Kn(e,s,n)),e}function Qj(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(o=>[e].concat(Object.keys(o).map(r=>{let i=o[r];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lE.exports={format:Qj,parse:Xj}});var fd=oe((TX,kE)=>{"use strict";var ez=require("events"),tz=require("https"),nz=require("http"),pE=require("net"),rz=require("tls"),{randomBytes:oz,createHash:iz}=require("crypto"),{Duplex:_X,Readable:IX}=require("stream"),{URL:Kb}=require("url"),ro=as(),sz=Fb(),az=zb(),{isBlob:cz}=cs(),{BINARY_TYPES:uE,CLOSE_TIMEOUT:lz,EMPTY_BUFFER:ud,GUID:uz,kForOnEventAttribute:Gb,kListener:dz,kStatusCode:pz,kWebSocket:Qe,NOOP:fE}=wr(),{EventTarget:{addEventListener:fz,removeEventListener:mz}}=cE(),{format:gz,parse:hz}=ld(),{toBuffer:yz}=$a(),mE=Symbol("kAborted"),Wb=[8,13],Sr=["CONNECTING","OPEN","CLOSING","CLOSED"],vz=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ce=class t extends ez{constructor(e,n,o){super(),this._binaryType=uE[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ud,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(o=n,n=[]):n=[n]),gE(this,e,n,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uE.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,o){let r=new sz({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),i=new az(e,this._extensions,o.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[Qe]=this,i[Qe]=this,e[Qe]=this,r.on("conclude",kz),r.on("drain",xz),r.on("error",Sz),r.on("message",_z),r.on("ping",Iz),r.on("pong",Tz),i.onerror=Ez,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",vE),e.on("data",pd),e.on("end",bE),e.on("error",wE),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ro.extensionName]&&this._extensions[ro.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Bt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yE(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,o){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=n=void 0):typeof n=="function"&&(o=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Zb(this,e,o);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ud,n,o)}pong(e,n,o){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=n=void 0):typeof n=="function"&&(o=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Zb(this,e,o);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ud,n,o)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,o){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(o=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Zb(this,e,o);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[ro.extensionName]||(r.compress=!1),this._sender.send(e||ud,r,o)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Bt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ce,"CONNECTING",{enumerable:!0,value:Sr.indexOf("CONNECTING")});Object.defineProperty(Ce.prototype,"CONNECTING",{enumerable:!0,value:Sr.indexOf("CONNECTING")});Object.defineProperty(Ce,"OPEN",{enumerable:!0,value:Sr.indexOf("OPEN")});Object.defineProperty(Ce.prototype,"OPEN",{enumerable:!0,value:Sr.indexOf("OPEN")});Object.defineProperty(Ce,"CLOSING",{enumerable:!0,value:Sr.indexOf("CLOSING")});Object.defineProperty(Ce.prototype,"CLOSING",{enumerable:!0,value:Sr.indexOf("CLOSING")});Object.defineProperty(Ce,"CLOSED",{enumerable:!0,value:Sr.indexOf("CLOSED")});Object.defineProperty(Ce.prototype,"CLOSED",{enumerable:!0,value:Sr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Gb])return e[dz];return null},set(e){for(let n of this.listeners(t))if(n[Gb]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Gb]:!0})}})});Ce.prototype.addEventListener=fz;Ce.prototype.removeEventListener=mz;kE.exports=Ce;function gE(t,e,n,o){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:lz,protocolVersion:Wb[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!Wb.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Wb.join(", ")})`);let i;if(e instanceof Kb)i=e;else try{i=new Kb(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let h=new SyntaxError(c);if(t._redirects===0)throw h;dd(t,h);return}let l=s?443:80,u=oz(16).toString("base64"),d=s?tz.request:nz.request,f=new Set,m;if(r.createConnection=r.createConnection||(s?wz:bz),r.defaultPort=r.defaultPort||l,r.port=i.port||l,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(m=new ro({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=gz({[ro.extensionName]:m.offer()})),n.length){for(let h of n){if(typeof h!="string"||!vz.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let h=r.path.split(":");r.socketPath=h[0],r.path=h[1]}let g;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?r.socketPath:i.host;let h=o&&o.headers;if(o={...o,headers:{}},h)for(let[y,b]of Object.entries(h))o.headers[y.toLowerCase()]=b}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,h||delete r.headers.host,r.auth=void 0)}r.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),g=t._req=d(r),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(r);r.timeout&&g.on("timeout",()=>{Bt(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[mE]||(g=t._req=null,dd(t,h))}),g.on("response",h=>{let y=h.headers.location,b=h.statusCode;if(y&&r.followRedirects&&b>=300&&b<400){if(++t._redirects>r.maxRedirects){Bt(t,g,"Maximum redirects exceeded");return}g.abort();let w;try{w=new Kb(y,e)}catch{let I=new SyntaxError(`Invalid URL: ${y}`);dd(t,I);return}gE(t,w,n,o)}else t.emit("unexpected-response",g,h)||Bt(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,y,b)=>{if(t.emit("upgrade",h),t.readyState!==Ce.CONNECTING)return;g=t._req=null;let w=h.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Bt(t,y,"Invalid Upgrade header");return}let x=iz("sha1").update(u+uz).digest("base64");if(h.headers["sec-websocket-accept"]!==x){Bt(t,y,"Invalid Sec-WebSocket-Accept header");return}let I=h.headers["sec-websocket-protocol"],E;if(I!==void 0?f.size?f.has(I)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":f.size&&(E="Server sent no subprotocol"),E){Bt(t,y,E);return}I&&(t._protocol=I);let C=h.headers["sec-websocket-extensions"];if(C!==void 0){if(!m){Bt(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=hz(C)}catch{Bt(t,y,"Invalid Sec-WebSocket-Extensions header");return}let U=Object.keys(F);if(U.length!==1||U[0]!==ro.extensionName){Bt(t,y,"Server indicated an extension that was not requested");return}try{m.accept(F[ro.extensionName])}catch{Bt(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ro.extensionName]=m}t.setSocket(y,b,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(g,t):g.end()}function dd(t,e){t._readyState=Ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function bz(t){return t.path=t.socketPath,pE.connect(t)}function wz(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=pE.isIP(t.host)?"":t.host),rz.connect(t)}function Bt(t,e,n){t._readyState=Ce.CLOSING;let o=new Error(n);Error.captureStackTrace(o,Bt),e.setHeader?(e[mE]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(dd,t,o)):(e.destroy(o),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Zb(t,e,n){if(e){let o=cz(e)?e.size:yz(e).length;t._socket?t._sender._bufferedBytes+=o:t._bufferedAmount+=o}if(n){let o=new Error(`WebSocket is not open: readyState ${t.readyState} (${Sr[t.readyState]})`);process.nextTick(n,o)}}function kz(t,e){let n=this[Qe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Qe]!==void 0&&(n._socket.removeListener("data",pd),process.nextTick(hE,n._socket),t===1005?n.close():n.close(t,e))}function xz(){let t=this[Qe];t.isPaused||t._socket.resume()}function Sz(t){let e=this[Qe];e._socket[Qe]!==void 0&&(e._socket.removeListener("data",pd),process.nextTick(hE,e._socket),e.close(t[pz])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function dE(){this[Qe].emitClose()}function _z(t,e){this[Qe].emit("message",t,e)}function Iz(t){let e=this[Qe];e._autoPong&&e.pong(t,!this._isServer,fE),e.emit("ping",t)}function Tz(t){this[Qe].emit("pong",t)}function hE(t){t.resume()}function Ez(t){let e=this[Qe];e.readyState!==Ce.CLOSED&&(e.readyState===Ce.OPEN&&(e._readyState=Ce.CLOSING,yE(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yE(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vE(){let t=this[Qe];if(this.removeListener("close",vE),this.removeListener("data",pd),this.removeListener("end",bE),t._readyState=Ce.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Qe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",dE),t._receiver.on("finish",dE))}function pd(t){this[Qe]._receiver.write(t)||this.pause()}function bE(){let t=this[Qe];t._readyState=Ce.CLOSING,t._receiver.end(),this.end()}function wE(){let t=this[Qe];this.removeListener("error",wE),this.on("error",fE),t&&(t._readyState=Ce.CLOSING,this.destroy())}});var IE=oe((CX,_E)=>{"use strict";var EX=fd(),{Duplex:Cz}=require("stream");function xE(t){t.emit("close")}function Rz(){!this.destroyed&&this._writableState.finished&&this.destroy()}function SE(t){this.removeListener("error",SE),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Az(t,e){let n=!0,o=new Cz({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&o._readableState.objectMode?i.toString():i;o.push(a)||t.pause()}),t.once("error",function(i){o.destroyed||(n=!1,o.destroy(i))}),t.once("close",function(){o.destroyed||o.push(null)}),o._destroy=function(r,i){if(t.readyState===t.CLOSED){i(r),process.nextTick(xE,o);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(r),process.nextTick(xE,o)}),n&&t.terminate()},o._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){o._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),o._readableState.endEmitted&&o.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},o._read=function(){t.isPaused&&t.resume()},o._write=function(r,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){o._write(r,i,s)});return}t.send(r,s)},o.on("end",Rz),o.on("error",SE),o}_E.exports=Az});var qb=oe((RX,TE)=>{"use strict";var{tokenChars:Pz}=cs();function Dz(t){let e=new Set,n=-1,o=-1,r=0;for(r;r<t.length;r++){let s=t.charCodeAt(r);if(o===-1&&Pz[s]===1)n===-1&&(n=r);else if(r!==0&&(s===32||s===9))o===-1&&n!==-1&&(o=r);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);o===-1&&(o=r);let a=t.slice(n,o);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=o=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}TE.exports={parse:Dz}});var $E=oe((PX,DE)=>{"use strict";var $z=require("events"),md=require("http"),{Duplex:AX}=require("stream"),{createHash:Oz}=require("crypto"),EE=ld(),Go=as(),Lz=qb(),Nz=fd(),{CLOSE_TIMEOUT:Mz,GUID:Uz,kWebSocket:Fz}=wr(),Bz=/^[+/0-9A-Za-z]{22}==$/,CE=0,RE=1,PE=2,Vb=class extends $z{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Mz,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Nz,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=md.createServer((o,r)=>{let i=md.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=jz(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,s)=>{this.handleUpgrade(r,i,s,o)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=CE}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===PE){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ua,this);return}if(e&&this.once("close",e),this._state!==RE)if(this._state=RE,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ua,this):process.nextTick(Ua,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ua(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,o,r){n.on("error",AE);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Wo(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Wo(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Bz.test(i)){Wo(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Wo(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Fa(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Lz.parse(c)}catch{Wo(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Go({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=EE.parse(u);m[Go.extensionName]&&(f.accept(m[Go.extensionName]),d[Go.extensionName]=f)}catch{Wo(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(m,g,h,y)=>{if(!m)return Fa(n,g||401,h,y);this.completeUpgrade(d,i,l,e,n,o,r)});return}if(!this.options.verifyClient(f))return Fa(n,401)}this.completeUpgrade(d,i,l,e,n,o,r)}completeUpgrade(e,n,o,r,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[Fz])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>CE)return Fa(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Oz("sha1").update(n+Uz).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(o.size){let d=this.options.handleProtocols?this.options.handleProtocols(o,r):o.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Go.extensionName]){let d=e[Go.extensionName].params,f=EE.format({[Go.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,r),i.write(l.concat(`\r
3
+ `).join(`\r
4
+ `)),i.removeListener("error",AE),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ua,this)})),a(u,r)}};DE.exports=Vb;function jz(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let o of Object.keys(e))t.removeListener(o,e[o])}}function Ua(t){t._state=PE,t.emit("close")}function AE(){this.destroy()}function Fa(t,e,n,o){n=n||md.STATUS_CODES[e],o={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...o},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${md.STATUS_CODES[e]}\r
5
+ `+Object.keys(o).map(r=>`${r}: ${o[r]}`).join(`\r
6
+ `)+`\r
7
+ \r
8
+ `+n)}function Wo(t,e,n,o,r,i){if(t.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,Wo),t.emit("wsClientError",s,n,e)}else Fa(n,o,r,i)}});var BE={};Xt(BE,{PerMessageDeflate:()=>NE.default,Receiver:()=>ME.default,Sender:()=>UE.default,WebSocket:()=>_r.default,WebSocketServer:()=>gd.default,createWebSocketStream:()=>OE.default,default:()=>zz,extension:()=>LE.default,subprotocol:()=>FE.default});var OE,LE,NE,ME,UE,FE,_r,gd,zz,hd=ct(()=>{OE=G(IE(),1),LE=G(ld(),1),NE=G(as(),1),ME=G(Fb(),1),UE=G(zb(),1),FE=G(qb(),1),_r=G(fd(),1),gd=G($E(),1),zz=_r.default});var Id=oe(cw=>{"use strict";Object.defineProperty(cw,"__esModule",{value:!0});cw.default=d6;var yC=/[A-Z]/g;function vC(t){return t.toLowerCase()}function d6(t,e){let n=t.replace(yC,vC),o=e.replace(yC,vC);return n===o}});var lw=oe(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.DnsTxt=void 0;var Td=class{constructor(e={}){this.binary=e?e.binary:!1}encode(e={}){return Object.entries(e).map(([n,o])=>{let r=`${n}=${o}`;return Buffer.from(r)})}decode(e){var n={};try{let r=e.toString().split(/=(.+)/),i=r[0],s=r[1];n[i]=s}catch{}return n}decodeAll(e){return e.filter(n=>n.length>1).map(n=>this.decode(n)).reduce((n,o)=>{var r=n;let[i]=Object.keys(o),[s]=Object.values(o);return r[i]=s,r},{})}};Ha.DnsTxt=Td;Ha.default=Td});var uw=oe(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.toType=hs.toString=void 0;var bC=t=>"_"+t,p6=t=>["name","protocol","subtype"].includes(t),f6=t=>{let e={name:t.name,protocol:t.protocol,subtype:t.subtype};return Object.entries(e).filter(([o,r])=>p6(o)&&r!==void 0).reduce((o,[r,i])=>(typeof i==="object"?i.map(s=>o.push(bC(s))):o.push(bC(i)),o),[]).join(".")};hs.toString=f6;var m6=t=>{let e=t.split("."),n;for(let o in e)e[o][0]==="_"&&(e[o]=e[o].slice(1));return e.includes("sub")&&(n=e.shift(),e.shift()),{name:e.shift(),protocol:e.shift()||null,subtype:n}};hs.toType=m6});var dw=oe(qo=>{"use strict";var kC=qo&&qo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qo,"__esModule",{value:!0});qo.Service=void 0;var wC=kC(require("os")),g6=kC(lw()),h6=require("events"),y6=uw(),ys=".local",Ed=class extends h6.EventEmitter{constructor(e,n,o){if(super(),this.start=n,this.stop=o,this.probe=!0,this.published=!1,this.activated=!1,this.destroyed=!1,this.txtService=new g6.default,!e.name)throw new Error("ServiceConfig requires `name` property to be set");if(!e.type)throw new Error("ServiceConfig requires `type` property to be set");if(!e.port)throw new Error("ServiceConfig requires `port` property to be set");this.name=e.name.split(".").join("-"),this.protocol=e.protocol||"tcp",this.type=(0,y6.toString)({name:e.type,protocol:this.protocol}),this.port=e.port,this.host=e.host||wC.default.hostname(),this.fqdn=`${this.name}.${this.type}${ys}`,this.txt=e.txt,this.subtypes=e.subtypes,this.disableIPv6=!!e.disableIPv6}records(){var e=[this.RecordPTR(this),this.RecordSRV(this),this.RecordTXT(this),this.RecordServicePTR(this)];for(let o of this.subtypes||[])e.push(this.RecordSubtypePTR(this,o));let n=Object.values(wC.default.networkInterfaces());for(let o of n){let r=o;for(let i of r)if(!(i.internal||i.mac==="00:00:00:00:00:00"))switch(i.family){case"IPv4":e.push(this.RecordA(this,i.address));break;case"IPv6":if(this.disableIPv6)break;e.push(this.RecordAAAA(this,i.address));break}}return e}RecordPTR(e){return{name:`${e.type}${ys}`,type:"PTR",ttl:28800,data:e.fqdn}}RecordServicePTR(e){return{name:`_services._dns-sd._udp${ys}`,type:"PTR",ttl:120,data:`${e.type}${ys}`}}RecordSubtypePTR(e,n){return{name:`_${n}._sub.${e.type}${ys}`,type:"PTR",ttl:28800,data:`${e.name}.${e.type}${ys}`}}RecordSRV(e){return{name:e.fqdn,type:"SRV",ttl:120,data:{port:e.port,target:e.host}}}RecordTXT(e){return{name:e.fqdn,type:"TXT",ttl:4500,data:this.txtService.encode(e.txt)}}RecordA(e,n){return{name:e.host,type:"A",ttl:120,data:n}}RecordAAAA(e,n){return{name:e.host,type:"AAAA",ttl:120,data:n}}};qo.Service=Ed;qo.default=Ed});var SC=oe(Vo=>{"use strict";var xC=Vo&&Vo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vo,"__esModule",{value:!0});Vo.Registry=void 0;var v6=xC(Id()),pw=xC(dw()),b6=3600*1e3,w6=3,k6=function(){},Cd=class{constructor(e){this.services=[],this.server=e}publish(e){let n=e.probe!==!1,o=new pw.default(e,r.bind(null,this),i.bind(null,this));function r(s,{probe:a=n}={}){o.activated||(o.activated=!0,s.services.push(o),o instanceof pw.default&&(a?s.probe(s.server.mdns,o,c=>{if(c){o.stop!==void 0&&o.stop(),console.log(new Error("Service name is already in use on the network"));return}s.announce(s.server,o)}):s.announce(s.server,o)))}function i(s,a){if(a||(a=k6),!o.activated||!(o instanceof pw.default))return process.nextTick(a);s.teardown(s.server,o,a);let c=s.services.indexOf(o);c!==-1&&s.services.splice(c,1)}return o.start(),o}unpublishAll(e){this.teardown(this.server,this.services,e),this.services=[]}destroy(){this.services.map(e=>e.destroyed=!0)}probe(e,n,o){var r=!1,i=0,s;let a=()=>{!n.activated||n.destroyed||e.query(n.fqdn,"ANY",function(){r=!0,s=setTimeout(++i<3?a:u,250),s.unref()})},c=d=>{r&&(d.answers.some(l)||d.additionals.some(l))&&u(!0)},l=d=>(0,v6.default)(d.name,n.fqdn),u=d=>{e.removeListener("response",c),clearTimeout(s),o(!!d)};e.on("response",c),setTimeout(a,Math.random()*250)}announce(e,n){var o=1e3,r=n.records();e.register(r);let i=()=>{!n.activated||n.destroyed||e.mdns.respond(r,function(){n.published||(n.activated=!0,n.published=!0,n.emit("up")),o=o*w6,o<b6&&!n.destroyed&&setTimeout(i,o).unref()})};i()}teardown(e,n,o){Array.isArray(n)||(n=[n]),n=n.filter(i=>i.activated);var r=n.flatMap(function(i){i.activated=!1;var s=i.records();return s.forEach(a=>{a.ttl=0}),s});if(r.length===0)return o&&process.nextTick(o);e.unregister(r),e.mdns.respond(r,function(){n.forEach(function(i){i.published=!1}),typeof o=="function"&&o.apply(null,arguments)})}};Vo.Registry=Cd;Vo.default=Cd});var _C=oe(fw=>{"use strict";fw.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};fw.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var IC=oe(mw=>{"use strict";mw.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};mw.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var TC=oe(gw=>{"use strict";gw.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};gw.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var EC=oe(hw=>{"use strict";hw.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};hw.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var CC=oe(yw=>{"use strict";yw.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};yw.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var PC=oe((AC,vw)=>{var RC=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=d,t.encode=u,t.familyOf=l,t.name=void 0,t.sizeOf=c,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,n=4,o=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,r=16,i={name:"v4",size:n,isFormat:f=>e.test(f),encode(f,m,g){g=~~g,m=m||new Uint8Array(g+n);let h=f.length,y=0;for(let b=0;b<h;){let w=f.charCodeAt(b++);w===46?(m[g++]=y,y=0):y=y*10+(w-48)}return m[g]=y,m},decode(f,m){return m=~~m,`${f[m++]}.${f[m++]}.${f[m++]}.${f[m]}`}};t.v4=i;let s={name:"v6",size:r,isFormat:f=>f.length>0&&o.test(f),encode(f,m,g){g=~~g;let h=g+r,y=-1,b=0,w=0,x=!0,I=!1;m=m||new Uint8Array(g+r);for(let E=0;E<f.length;E++){let C=f.charCodeAt(E);C===58?(x?y!==-1?(g<h&&(m[g]=0),g<h-1&&(m[g+1]=0),g+=2):g<h&&(y=g):(I===!0?(g<h&&(m[g]=w),g++):(g<h&&(m[g]=b>>8),g<h-1&&(m[g+1]=b&255),g+=2),b=0,w=0),x=!0,I=!1):C===46?(g<h&&(m[g]=w),g++,w=0,b=0,x=!1,I=!0):(x=!1,C>=97?C-=87:C>=65?C-=55:(C-=48,w=w*10+C),b=(b<<4)+C)}if(x===!1)I===!0?(g<h&&(m[g]=w),g++):(g<h&&(m[g]=b>>8),g<h-1&&(m[g+1]=b&255),g+=2);else if(y===0)g<h&&(m[g]=0),g<h-1&&(m[g+1]=0),g+=2;else if(y!==-1){g+=2;for(let E=Math.min(g-1,h-1);E>=y+2;E--)m[E]=m[E-2];m[y]=0,m[y+1]=0,y=g}if(y!==g&&y!==-1)for(g>h-2&&(g=h-2);h>y;)m[--h]=g<h&&g>y?m[--g]:0;else for(;g<h;)m[g++]=0;return m},decode(f,m){m=~~m;let g="";for(let h=0;h<r;h+=2)h!==0&&(g+=":"),g+=(f[m+h]<<8|f[m+h+1]).toString(16);return g.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=s;let a="ip";t.name=a;function c(f){if(i.isFormat(f))return i.size;if(s.isFormat(f))return s.size;throw Error(`Invalid ip address: ${f}`)}function l(f){return c(f)===i.size?1:2}function u(f,m,g){g=~~g;let h=c(f);return typeof m=="function"&&(m=m(g+h)),h===i.size?i.encode(f,m,g):s.encode(f,m,g)}function d(f,m,g){if(m=~~m,g=g||f.length-m,g===i.size)return i.decode(f,m,g);if(g===s.size)return s.decode(f,m,g);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${s.size} for v6.`)}return"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return RC}):typeof vw=="object"&&typeof AC=="object"&&(vw.exports=RC)});var OC=oe(z=>{"use strict";var H=require("buffer").Buffer,Or=_C(),x6=IC(),S6=TC(),Ad=EC(),bw=CC(),Jo=PC(),_6=0,DC=32768,ww=32768,I6=~ww,$C=32768,T6=~$C,O=z.name={};O.encode=function(t,e,n,{mail:o=!1}={}){e||(e=H.alloc(O.encodingLength(t))),n||(n=0);let r=n,i=t.replace(/^\.|\.$/gm,"");if(i.length){let s=[];if(o){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):s.length===0&&a.length?s.push(a+"."+c):s.push(c)})}else s=i.split(".");for(let a=0;a<s.length;a++){let c=e.write(s[a],n+1);e[n]=c,n+=c+1}}return e[n++]=0,O.encode.bytes=n-r,e};O.encode.bytes=0;O.decode=function(t,e,{mail:n=!1}={}){e||(e=0);let o=[],r=e,i=0,s=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(s+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let l=t.toString("utf-8",e,e+c);n&&(l=l.replace(/\./g,"\\.")),o.push(l),e+=c,s+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let l=t.readUInt16BE(e-1)-49152;if(l>=r)throw new Error("Cannot decode name (bad pointer)");e=l,r=l,s+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return O.decode.bytes=s,o.length===0?".":o.join(".")};O.decode.bytes=0;O.encodingLength=function(t){return t==="."||t===".."?1:H.byteLength(t.replace(/^\.|\.$/gm,""))+2};var te={};te.encode=function(t,e,n){e||(e=H.alloc(te.encodingLength(t))),n||(n=0);let o=e.write(t,n+1);return e[n]=o,te.encode.bytes=o+1,e};te.encode.bytes=0;te.decode=function(t,e){e||(e=0);let n=t[e],o=t.toString("utf-8",e+1,e+1+n);return te.decode.bytes=n+1,o};te.decode.bytes=0;te.encodingLength=function(t){return H.byteLength(t)+1};var kn={};kn.encode=function(t,e,n){e||(e=kn.encodingLength(t)),n||(n=0);let o=(t.flags||0)&32767,r=t.type==="response"?DC:_6;return e.writeUInt16BE(t.id||0,n),e.writeUInt16BE(o|r,n+2),e.writeUInt16BE(t.questions.length,n+4),e.writeUInt16BE(t.answers.length,n+6),e.writeUInt16BE(t.authorities.length,n+8),e.writeUInt16BE(t.additionals.length,n+10),e};kn.encode.bytes=12;kn.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let n=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:n&DC?"response":"query",flags:n&32767,flag_qr:(n>>15&1)===1,opcode:S6.toString(n>>11&15),flag_aa:(n>>10&1)===1,flag_tc:(n>>9&1)===1,flag_rd:(n>>8&1)===1,flag_ra:(n>>7&1)===1,flag_z:(n>>6&1)===1,flag_ad:(n>>5&1)===1,flag_cd:(n>>4&1)===1,rcode:x6.toString(n&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};kn.decode.bytes=12;kn.encodingLength=function(){return 12};var Ir=z.unknown={};Ir.encode=function(t,e,n){return e||(e=H.alloc(Ir.encodingLength(t))),n||(n=0),e.writeUInt16BE(t.length,n),t.copy(e,n+2),Ir.encode.bytes=t.length+2,e};Ir.encode.bytes=0;Ir.decode=function(t,e){e||(e=0);let n=t.readUInt16BE(e),o=t.slice(e+2,e+2+n);return Ir.decode.bytes=n+2,o};Ir.decode.bytes=0;Ir.encodingLength=function(t){return t.length+2};var Tr=z.ns={};Tr.encode=function(t,e,n){return e||(e=H.alloc(Tr.encodingLength(t))),n||(n=0),O.encode(t,e,n+2),e.writeUInt16BE(O.encode.bytes,n),Tr.encode.bytes=O.encode.bytes+2,e};Tr.encode.bytes=0;Tr.decode=function(t,e){e||(e=0);let n=t.readUInt16BE(e),o=O.decode(t,e+2);return Tr.decode.bytes=n+2,o};Tr.decode.bytes=0;Tr.encodingLength=function(t){return O.encodingLength(t)+2};var Er=z.soa={};Er.encode=function(t,e,n){e||(e=H.alloc(Er.encodingLength(t))),n||(n=0);let o=n;return n+=2,O.encode(t.mname,e,n),n+=O.encode.bytes,O.encode(t.rname,e,n,{mail:!0}),n+=O.encode.bytes,e.writeUInt32BE(t.serial||0,n),n+=4,e.writeUInt32BE(t.refresh||0,n),n+=4,e.writeUInt32BE(t.retry||0,n),n+=4,e.writeUInt32BE(t.expire||0,n),n+=4,e.writeUInt32BE(t.minimum||0,n),n+=4,e.writeUInt16BE(n-o-2,o),Er.encode.bytes=n-o,e};Er.encode.bytes=0;Er.decode=function(t,e){e||(e=0);let n=e,o={};return e+=2,o.mname=O.decode(t,e),e+=O.decode.bytes,o.rname=O.decode(t,e,{mail:!0}),e+=O.decode.bytes,o.serial=t.readUInt32BE(e),e+=4,o.refresh=t.readUInt32BE(e),e+=4,o.retry=t.readUInt32BE(e),e+=4,o.expire=t.readUInt32BE(e),e+=4,o.minimum=t.readUInt32BE(e),e+=4,Er.decode.bytes=e-n,o};Er.decode.bytes=0;Er.encodingLength=function(t){return 22+O.encodingLength(t.mname)+O.encodingLength(t.rname)};var Cr=z.txt={};Cr.encode=function(t,e,n){Array.isArray(t)||(t=[t]);for(let r=0;r<t.length;r++)if(typeof t[r]=="string"&&(t[r]=H.from(t[r])),!H.isBuffer(t[r]))throw new Error("Must be a Buffer");e||(e=H.alloc(Cr.encodingLength(t))),n||(n=0);let o=n;return n+=2,t.forEach(function(r){e[n++]=r.length,r.copy(e,n,0,r.length),n+=r.length}),e.writeUInt16BE(n-o-2,o),Cr.encode.bytes=n-o,e};Cr.encode.bytes=0;Cr.decode=function(t,e){e||(e=0);let n=e,o=t.readUInt16BE(e);e+=2;let r=[];for(;o>0;){let i=t[e++];if(--o,o<i)throw new Error("Buffer overflow");r.push(t.slice(e,e+i)),e+=i,o-=i}return Cr.decode.bytes=e-n,r};Cr.decode.bytes=0;Cr.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(n){typeof n=="string"?e+=H.byteLength(n)+1:e+=n.length+1}),e};var Rr=z.null={};Rr.encode=function(t,e,n){e||(e=H.alloc(Rr.encodingLength(t))),n||(n=0),typeof t=="string"&&(t=H.from(t)),t||(t=H.alloc(0));let o=n;n+=2;let r=t.length;return t.copy(e,n,0,r),n+=r,e.writeUInt16BE(n-o-2,o),Rr.encode.bytes=n-o,e};Rr.encode.bytes=0;Rr.decode=function(t,e){e||(e=0);let n=e,o=t.readUInt16BE(e);e+=2;let r=t.slice(e,e+o);return e+=o,Rr.decode.bytes=e-n,r};Rr.decode.bytes=0;Rr.encodingLength=function(t){return t?(H.isBuffer(t)?t.length:H.byteLength(t))+2:2};var Ar=z.hinfo={};Ar.encode=function(t,e,n){e||(e=H.alloc(Ar.encodingLength(t))),n||(n=0);let o=n;return n+=2,te.encode(t.cpu,e,n),n+=te.encode.bytes,te.encode(t.os,e,n),n+=te.encode.bytes,e.writeUInt16BE(n-o-2,o),Ar.encode.bytes=n-o,e};Ar.encode.bytes=0;Ar.decode=function(t,e){e||(e=0);let n=e,o={};return e+=2,o.cpu=te.decode(t,e),e+=te.decode.bytes,o.os=te.decode(t,e),e+=te.decode.bytes,Ar.decode.bytes=e-n,o};Ar.decode.bytes=0;Ar.encodingLength=function(t){return te.encodingLength(t.cpu)+te.encodingLength(t.os)+2};var bn=z.ptr={},E6=z.cname=bn,C6=z.dname=bn;bn.encode=function(t,e,n){return e||(e=H.alloc(bn.encodingLength(t))),n||(n=0),O.encode(t,e,n+2),e.writeUInt16BE(O.encode.bytes,n),bn.encode.bytes=O.encode.bytes+2,e};bn.encode.bytes=0;bn.decode=function(t,e){e||(e=0);let n=O.decode(t,e+2);return bn.decode.bytes=O.decode.bytes+2,n};bn.decode.bytes=0;bn.encodingLength=function(t){return O.encodingLength(t)+2};var Pr=z.srv={};Pr.encode=function(t,e,n){e||(e=H.alloc(Pr.encodingLength(t))),n||(n=0),e.writeUInt16BE(t.priority||0,n+2),e.writeUInt16BE(t.weight||0,n+4),e.writeUInt16BE(t.port||0,n+6),O.encode(t.target,e,n+8);let o=O.encode.bytes+6;return e.writeUInt16BE(o,n),Pr.encode.bytes=o+2,e};Pr.encode.bytes=0;Pr.decode=function(t,e){e||(e=0);let n=t.readUInt16BE(e),o={};return o.priority=t.readUInt16BE(e+2),o.weight=t.readUInt16BE(e+4),o.port=t.readUInt16BE(e+6),o.target=O.decode(t,e+8),Pr.decode.bytes=n+2,o};Pr.decode.bytes=0;Pr.encodingLength=function(t){return 8+O.encodingLength(t.target)};var Ht=z.caa={};Ht.ISSUER_CRITICAL=128;Ht.encode=function(t,e,n){let o=Ht.encodingLength(t);return e||(e=H.alloc(Ht.encodingLength(t))),n||(n=0),t.issuerCritical&&(t.flags=Ht.ISSUER_CRITICAL),e.writeUInt16BE(o-2,n),n+=2,e.writeUInt8(t.flags||0,n),n+=1,te.encode(t.tag,e,n),n+=te.encode.bytes,e.write(t.value,n),n+=H.byteLength(t.value),Ht.encode.bytes=o,e};Ht.encode.bytes=0;Ht.decode=function(t,e){e||(e=0);let n=t.readUInt16BE(e);e+=2;let o=e,r={};return r.flags=t.readUInt8(e),e+=1,r.tag=te.decode(t,e),e+=te.decode.bytes,r.value=t.toString("utf-8",e,o+n),r.issuerCritical=!!(r.flags&Ht.ISSUER_CRITICAL),Ht.decode.bytes=n+2,r};Ht.decode.bytes=0;Ht.encodingLength=function(t){return te.encodingLength(t.tag)+te.encodingLength(t.value)+2};var oo=z.mx={};oo.encode=function(t,e,n){e||(e=H.alloc(oo.encodingLength(t))),n||(n=0);let o=n;return n+=2,e.writeUInt16BE(t.preference||0,n),n+=2,O.encode(t.exchange,e,n),n+=O.encode.bytes,e.writeUInt16BE(n-o-2,o),oo.encode.bytes=n-o,e};oo.encode.bytes=0;oo.decode=function(t,e){e||(e=0);let n=e,o={};return e+=2,o.preference=t.readUInt16BE(e),e+=2,o.exchange=O.decode(t,e),e+=O.decode.bytes,oo.decode.bytes=e-n,o};oo.encodingLength=function(t){return 4+O.encodingLength(t.exchange)};var Dr=z.a={};Dr.encode=function(t,e,n){return e||(e=H.alloc(Dr.encodingLength(t))),n||(n=0),e.writeUInt16BE(4,n),n+=2,Jo.v4.encode(t,e,n),Dr.encode.bytes=6,e};Dr.encode.bytes=0;Dr.decode=function(t,e){e||(e=0),e+=2;let n=Jo.v4.decode(t,e);return Dr.decode.bytes=6,n};Dr.decode.bytes=0;Dr.encodingLength=function(){return 6};var $r=z.aaaa={};$r.encode=function(t,e,n){return e||(e=H.alloc($r.encodingLength(t))),n||(n=0),e.writeUInt16BE(16,n),n+=2,Jo.v6.encode(t,e,n),$r.encode.bytes=18,e};$r.encode.bytes=0;$r.decode=function(t,e){e||(e=0),e+=2;let n=Jo.v6.decode(t,e);return $r.decode.bytes=18,n};$r.decode.bytes=0;$r.encodingLength=function(){return 18};var Ct=z.option={};Ct.encode=function(t,e,n){e||(e=H.alloc(Ct.encodingLength(t))),n||(n=0);let o=n,r=bw.toCode(t.code);if(e.writeUInt16BE(r,n),n+=2,t.data)e.writeUInt16BE(t.data.length,n),n+=2,t.data.copy(e,n),n+=t.data.length;else switch(r){case 8:let i=t.sourcePrefixLength||0,s=t.family||Jo.familyOf(t.ip),a=Jo.encode(t.ip,H.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,n),n+=2,e.writeUInt16BE(s,n),n+=2,e.writeUInt8(i,n++),e.writeUInt8(t.scopePrefixLength||0,n++),a.copy(e,n,0,c),n+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,n),n+=2,e.writeUInt16BE(t.timeout,n),n+=2):(e.writeUInt16BE(0,n),n+=2);break;case 12:let l=t.length||0;e.writeUInt16BE(l,n),n+=2,e.fill(0,n,n+l),n+=l;break;case 14:let u=t.tags.length*2;e.writeUInt16BE(u,n),n+=2;for(let d of t.tags)e.writeUInt16BE(d,n),n+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Ct.encode.bytes=n-o,e};Ct.encode.bytes=0;Ct.decode=function(t,e){e||(e=0);let n={};n.code=t.readUInt16BE(e),n.type=bw.toString(n.code),e+=2;let o=t.readUInt16BE(e);switch(e+=2,n.data=t.slice(e,e+o),n.code){case 8:n.family=t.readUInt16BE(e),e+=2,n.sourcePrefixLength=t.readUInt8(e++),n.scopePrefixLength=t.readUInt8(e++);let r=H.alloc(n.family===1?4:16);t.copy(r,0,e,e+o-4),n.ip=Jo.decode(r);break;case 11:o>0&&(n.timeout=t.readUInt16BE(e),e+=2);break;case 14:n.tags=[];for(let i=0;i<o;i+=2)n.tags.push(t.readUInt16BE(e)),e+=2}return Ct.decode.bytes=o+4,n};Ct.decode.bytes=0;Ct.encodingLength=function(t){if(t.data)return t.data.length+4;switch(bw.toCode(t.code)){case 8:let n=t.sourcePrefixLength||0;return Math.ceil(n/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var Gt=z.opt={};Gt.encode=function(t,e,n){e||(e=H.alloc(Gt.encodingLength(t))),n||(n=0);let o=n,r=vs(t,Ct);return e.writeUInt16BE(r,n),n=Ka(t,Ct,e,n+2),Gt.encode.bytes=n-o,e};Gt.encode.bytes=0;Gt.decode=function(t,e){e||(e=0);let n=e,o=[],r=t.readUInt16BE(e);e+=2;let i=0;for(;r>0;)o[i++]=Ct.decode(t,e),e+=Ct.decode.bytes,r-=Ct.decode.bytes;return Gt.decode.bytes=e-n,o};Gt.decode.bytes=0;Gt.encodingLength=function(t){return 2+vs(t||[],Ct)};var bt=z.dnskey={};bt.PROTOCOL_DNSSEC=3;bt.ZONE_KEY=128;bt.SECURE_ENTRYPOINT=32768;bt.encode=function(t,e,n){e||(e=H.alloc(bt.encodingLength(t))),n||(n=0);let o=n,r=t.key;if(!H.isBuffer(r))throw new Error("Key must be a Buffer");return n+=2,e.writeUInt16BE(t.flags,n),n+=2,e.writeUInt8(bt.PROTOCOL_DNSSEC,n),n+=1,e.writeUInt8(t.algorithm,n),n+=1,r.copy(e,n,0,r.length),n+=r.length,bt.encode.bytes=n-o,e.writeUInt16BE(bt.encode.bytes-2,o),e};bt.encode.bytes=0;bt.decode=function(t,e){e||(e=0);let n=e;var o={},r=t.readUInt16BE(e);if(e+=2,o.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==bt.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,o.algorithm=t.readUInt8(e),e+=1,o.key=t.slice(e,n+r+2),e+=o.key.length,bt.decode.bytes=e-n,o};bt.decode.bytes=0;bt.encodingLength=function(t){return 6+H.byteLength(t.key)};var Gn=z.rrsig={};Gn.encode=function(t,e,n){e||(e=H.alloc(Gn.encodingLength(t))),n||(n=0);let o=n,r=t.signature;if(!H.isBuffer(r))throw new Error("Signature must be a Buffer");return n+=2,e.writeUInt16BE(Or.toType(t.typeCovered),n),n+=2,e.writeUInt8(t.algorithm,n),n+=1,e.writeUInt8(t.labels,n),n+=1,e.writeUInt32BE(t.originalTTL,n),n+=4,e.writeUInt32BE(t.expiration,n),n+=4,e.writeUInt32BE(t.inception,n),n+=4,e.writeUInt16BE(t.keyTag,n),n+=2,O.encode(t.signersName,e,n),n+=O.encode.bytes,r.copy(e,n,0,r.length),n+=r.length,Gn.encode.bytes=n-o,e.writeUInt16BE(Gn.encode.bytes-2,o),e};Gn.encode.bytes=0;Gn.decode=function(t,e){e||(e=0);let n=e;var o={},r=t.readUInt16BE(e);return e+=2,o.typeCovered=Or.toString(t.readUInt16BE(e)),e+=2,o.algorithm=t.readUInt8(e),e+=1,o.labels=t.readUInt8(e),e+=1,o.originalTTL=t.readUInt32BE(e),e+=4,o.expiration=t.readUInt32BE(e),e+=4,o.inception=t.readUInt32BE(e),e+=4,o.keyTag=t.readUInt16BE(e),e+=2,o.signersName=O.decode(t,e),e+=O.decode.bytes,o.signature=t.slice(e,n+r+2),e+=o.signature.length,Gn.decode.bytes=e-n,o};Gn.decode.bytes=0;Gn.encodingLength=function(t){return 20+O.encodingLength(t.signersName)+H.byteLength(t.signature)};var Wn=z.rp={};Wn.encode=function(t,e,n){e||(e=H.alloc(Wn.encodingLength(t))),n||(n=0);let o=n;return n+=2,O.encode(t.mbox||".",e,n,{mail:!0}),n+=O.encode.bytes,O.encode(t.txt||".",e,n),n+=O.encode.bytes,Wn.encode.bytes=n-o,e.writeUInt16BE(Wn.encode.bytes-2,o),e};Wn.encode.bytes=0;Wn.decode=function(t,e){e||(e=0);let n=e,o={};return e+=2,o.mbox=O.decode(t,e,{mail:!0})||".",e+=O.decode.bytes,o.txt=O.decode(t,e)||".",e+=O.decode.bytes,Wn.decode.bytes=e-n,o};Wn.decode.bytes=0;Wn.encodingLength=function(t){return 2+O.encodingLength(t.mbox||".")+O.encodingLength(t.txt||".")};var et={};et.encode=function(t,e,n){e||(e=H.alloc(et.encodingLength(t))),n||(n=0);let o=n;for(var r=[],i=0;i<t.length;i++){var s=Or.toType(t[i]);r[s>>8]===void 0&&(r[s>>8]=[]),r[s>>8][s>>3&31]|=1<<7-(s&7)}for(i=0;i<r.length;i++)if(r[i]!==void 0){var a=H.from(r[i]);e.writeUInt8(i,n),n+=1,e.writeUInt8(a.length,n),n+=1,a.copy(e,n),n+=a.length}return et.encode.bytes=n-o,e};et.encode.bytes=0;et.decode=function(t,e,n){e||(e=0);let o=e;for(var r=[];e-o<n;){var i=t.readUInt8(e);e+=1;var s=t.readUInt8(e);e+=1;for(var a=0;a<s;a++)for(var c=t.readUInt8(e+a),l=0;l<8;l++)if(c&1<<7-l){var u=Or.toString(i<<8|a<<3|l);r.push(u)}e+=s}return et.decode.bytes=e-o,r};et.decode.bytes=0;et.encodingLength=function(t){for(var e=[],n=0;n<t.length;n++){var o=Or.toType(t[n]);e[o>>8]=Math.max(e[o>>8]||0,o&255)}var r=0;for(n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r};var Zn=z.nsec={};Zn.encode=function(t,e,n){e||(e=H.alloc(Zn.encodingLength(t))),n||(n=0);let o=n;return n+=2,O.encode(t.nextDomain,e,n),n+=O.encode.bytes,et.encode(t.rrtypes,e,n),n+=et.encode.bytes,Zn.encode.bytes=n-o,e.writeUInt16BE(Zn.encode.bytes-2,o),e};Zn.encode.bytes=0;Zn.decode=function(t,e){e||(e=0);let n=e;var o={},r=t.readUInt16BE(e);return e+=2,o.nextDomain=O.decode(t,e),e+=O.decode.bytes,o.rrtypes=et.decode(t,e,r-(e-n)),e+=et.decode.bytes,Zn.decode.bytes=e-n,o};Zn.decode.bytes=0;Zn.encodingLength=function(t){return 2+O.encodingLength(t.nextDomain)+et.encodingLength(t.rrtypes)};var qn=z.nsec3={};qn.encode=function(t,e,n){e||(e=H.alloc(qn.encodingLength(t))),n||(n=0);let o=n,r=t.salt;if(!H.isBuffer(r))throw new Error("salt must be a Buffer");let i=t.nextDomain;if(!H.isBuffer(i))throw new Error("nextDomain must be a Buffer");return n+=2,e.writeUInt8(t.algorithm,n),n+=1,e.writeUInt8(t.flags,n),n+=1,e.writeUInt16BE(t.iterations,n),n+=2,e.writeUInt8(r.length,n),n+=1,r.copy(e,n,0,r.length),n+=r.length,e.writeUInt8(i.length,n),n+=1,i.copy(e,n,0,i.length),n+=i.length,et.encode(t.rrtypes,e,n),n+=et.encode.bytes,qn.encode.bytes=n-o,e.writeUInt16BE(qn.encode.bytes-2,o),e};qn.encode.bytes=0;qn.decode=function(t,e){e||(e=0);let n=e;var o={},r=t.readUInt16BE(e);e+=2,o.algorithm=t.readUInt8(e),e+=1,o.flags=t.readUInt8(e),e+=1,o.iterations=t.readUInt16BE(e),e+=2;let i=t.readUInt8(e);e+=1,o.salt=t.slice(e,e+i),e+=i;let s=t.readUInt8(e);return e+=1,o.nextDomain=t.slice(e,e+s),e+=s,o.rrtypes=et.decode(t,e,r-(e-n)),e+=et.decode.bytes,qn.decode.bytes=e-n,o};qn.decode.bytes=0;qn.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+et.encodingLength(t.rrtypes)};var Vn=z.ds={};Vn.encode=function(t,e,n){e||(e=H.alloc(Vn.encodingLength(t))),n||(n=0);let o=n,r=t.digest;if(!H.isBuffer(r))throw new Error("Digest must be a Buffer");return n+=2,e.writeUInt16BE(t.keyTag,n),n+=2,e.writeUInt8(t.algorithm,n),n+=1,e.writeUInt8(t.digestType,n),n+=1,r.copy(e,n,0,r.length),n+=r.length,Vn.encode.bytes=n-o,e.writeUInt16BE(Vn.encode.bytes-2,o),e};Vn.encode.bytes=0;Vn.decode=function(t,e){e||(e=0);let n=e;var o={},r=t.readUInt16BE(e);return e+=2,o.keyTag=t.readUInt16BE(e),e+=2,o.algorithm=t.readUInt8(e),e+=1,o.digestType=t.readUInt8(e),e+=1,o.digest=t.slice(e,n+r+2),e+=o.digest.length,Vn.decode.bytes=e-n,o};Vn.decode.bytes=0;Vn.encodingLength=function(t){return 6+H.byteLength(t.digest)};var Kt=z.sshfp={};Kt.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};Kt.encode=function(e,n,o){n||(n=H.alloc(Kt.encodingLength(e))),o||(o=0);let r=o;o+=2,n[o]=e.algorithm,o+=1,n[o]=e.hash,o+=1;let i=H.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==Kt.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(n,o),o+=i.byteLength,Kt.encode.bytes=o-r,n.writeUInt16BE(Kt.encode.bytes-2,r),n};Kt.encode.bytes=0;Kt.decode=function(e,n){n||(n=0);let o=n,r={};n+=2,r.algorithm=e[n],n+=1,r.hash=e[n],n+=1;let i=Kt.getFingerprintLengthForHashType(r.hash);return r.fingerprint=e.slice(n,n+i).toString("hex").toUpperCase(),n+=i,Kt.decode.bytes=n-o,r};Kt.decode.bytes=0;Kt.encodingLength=function(t){return 4+H.from(t.fingerprint,"hex").byteLength};var Jn=z.naptr={};Jn.encode=function(t,e,n){e||(e=H.alloc(Jn.encodingLength(t))),n||(n=0);let o=n;return n+=2,e.writeUInt16BE(t.order||0,n),n+=2,e.writeUInt16BE(t.preference||0,n),n+=2,te.encode(t.flags,e,n),n+=te.encode.bytes,te.encode(t.services,e,n),n+=te.encode.bytes,te.encode(t.regexp,e,n),n+=te.encode.bytes,O.encode(t.replacement,e,n),n+=O.encode.bytes,Jn.encode.bytes=n-o,e.writeUInt16BE(Jn.encode.bytes-2,o),e};Jn.encode.bytes=0;Jn.decode=function(t,e){e||(e=0);let n=e,o={};return e+=2,o.order=t.readUInt16BE(e),e+=2,o.preference=t.readUInt16BE(e),e+=2,o.flags=te.decode(t,e),e+=te.decode.bytes,o.services=te.decode(t,e),e+=te.decode.bytes,o.regexp=te.decode(t,e),e+=te.decode.bytes,o.replacement=O.decode(t,e),e+=O.decode.bytes,Jn.decode.bytes=e-n,o};Jn.decode.bytes=0;Jn.encodingLength=function(t){return te.encodingLength(t.flags)+te.encodingLength(t.services)+te.encodingLength(t.regexp)+O.encodingLength(t.replacement)+6};var Yn=z.tlsa={};Yn.encode=function(t,e,n){e||(e=H.alloc(Yn.encodingLength(t))),n||(n=0);let o=n,r=t.certificate;if(!H.isBuffer(r))throw new Error("Certificate must be a Buffer");return n+=2,e.writeUInt8(t.usage,n),n+=1,e.writeUInt8(t.selector,n),n+=1,e.writeUInt8(t.matchingType,n),n+=1,r.copy(e,n,0,r.length),n+=r.length,Yn.encode.bytes=n-o,e.writeUInt16BE(Yn.encode.bytes-2,o),e};Yn.encode.bytes=0;Yn.decode=function(t,e){e||(e=0);let n=e,o={},r=t.readUInt16BE(e);return e+=2,o.usage=t.readUInt8(e),e+=1,o.selector=t.readUInt8(e),e+=1,o.matchingType=t.readUInt8(e),e+=1,o.certificate=t.slice(e,n+r+2),e+=o.certificate.length,Yn.decode.bytes=e-n,o};Yn.decode.bytes=0;Yn.encodingLength=function(t){return 5+H.byteLength(t.certificate)};var kw=z.record=function(t){switch(t.toUpperCase()){case"A":return Dr;case"PTR":return bn;case"CNAME":return E6;case"DNAME":return C6;case"TXT":return Cr;case"NULL":return Rr;case"AAAA":return $r;case"SRV":return Pr;case"HINFO":return Ar;case"CAA":return Ht;case"NS":return Tr;case"SOA":return Er;case"MX":return oo;case"OPT":return Gt;case"DNSKEY":return bt;case"RRSIG":return Gn;case"RP":return Wn;case"NSEC":return Zn;case"NSEC3":return qn;case"SSHFP":return Kt;case"DS":return Vn;case"NAPTR":return Jn;case"TLSA":return Yn}return Ir},at=z.answer={};at.encode=function(t,e,n){e||(e=H.alloc(at.encodingLength(t))),n||(n=0);let o=n;if(O.encode(t.name,e,n),n+=O.encode.bytes,e.writeUInt16BE(Or.toType(t.type),n),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,n+2),e.writeUInt8(t.extendedRcode||0,n+4),e.writeUInt8(t.ednsVersion||0,n+5),e.writeUInt16BE(t.flags||0,n+6),n+=8,Gt.encode(t.options||[],e,n),n+=Gt.encode.bytes}else{let r=Ad.toClass(t.class===void 0?"IN":t.class);t.flush&&(r|=ww),e.writeUInt16BE(r,n+2),e.writeUInt32BE(t.ttl||0,n+4),n+=8;let i=kw(t.type);i.encode(t.data,e,n),n+=i.encode.bytes}return at.encode.bytes=n-o,e};at.encode.bytes=0;at.decode=function(t,e){e||(e=0);let n={},o=e;if(n.name=O.decode(t,e),e+=O.decode.bytes,n.type=Or.toString(t.readUInt16BE(e)),n.type==="OPT")n.udpPayloadSize=t.readUInt16BE(e+2),n.extendedRcode=t.readUInt8(e+4),n.ednsVersion=t.readUInt8(e+5),n.flags=t.readUInt16BE(e+6),n.flag_do=(n.flags>>15&1)===1,n.options=Gt.decode(t,e+8),e+=8+Gt.decode.bytes;else{let r=t.readUInt16BE(e+2);n.ttl=t.readUInt32BE(e+4),n.class=Ad.toString(r&I6),n.flush=!!(r&ww);let i=kw(n.type);n.data=i.decode(t,e+8),e+=8+i.decode.bytes}return at.decode.bytes=e-o,n};at.decode.bytes=0;at.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return O.encodingLength(t.name)+8+kw(t.type).encodingLength(e)};var wn=z.question={};wn.encode=function(t,e,n){e||(e=H.alloc(wn.encodingLength(t))),n||(n=0);let o=n;return O.encode(t.name,e,n),n+=O.encode.bytes,e.writeUInt16BE(Or.toType(t.type),n),n+=2,e.writeUInt16BE(Ad.toClass(t.class===void 0?"IN":t.class),n),n+=2,wn.encode.bytes=n-o,t};wn.encode.bytes=0;wn.decode=function(t,e){e||(e=0);let n=e,o={};return o.name=O.decode(t,e),e+=O.decode.bytes,o.type=Or.toString(t.readUInt16BE(e)),e+=2,o.class=Ad.toString(t.readUInt16BE(e)),e+=2,o.class&$C&&(o.class&=T6),wn.decode.bytes=e-n,o};wn.decode.bytes=0;wn.encodingLength=function(t){return O.encodingLength(t.name)+4};z.AUTHORITATIVE_ANSWER=1024;z.TRUNCATED_RESPONSE=512;z.RECURSION_DESIRED=256;z.RECURSION_AVAILABLE=128;z.AUTHENTIC_DATA=32;z.CHECKING_DISABLED=16;z.DNSSEC_OK=32768;z.encode=function(t,e,n){let o=!e;o&&(e=H.alloc(z.encodingLength(t))),n||(n=0);let r=n;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),kn.encode(t,e,n),n+=kn.encode.bytes,n=Ka(t.questions,wn,e,n),n=Ka(t.answers,at,e,n),n=Ka(t.authorities,at,e,n),n=Ka(t.additionals,at,e,n),z.encode.bytes=n-r,o&&z.encode.bytes!==e.length?e.slice(0,z.encode.bytes):e};z.encode.bytes=0;z.decode=function(t,e){e||(e=0);let n=e,o=kn.decode(t,e);return e+=kn.decode.bytes,e=Rd(o.questions,wn,t,e),e=Rd(o.answers,at,t,e),e=Rd(o.authorities,at,t,e),e=Rd(o.additionals,at,t,e),z.decode.bytes=e-n,o};z.decode.bytes=0;z.encodingLength=function(t){return kn.encodingLength(t)+vs(t.questions||[],wn)+vs(t.answers||[],at)+vs(t.authorities||[],at)+vs(t.additionals||[],at)};z.streamEncode=function(t){let e=z.encode(t),n=H.alloc(2);n.writeUInt16BE(e.byteLength);let o=H.concat([n,e]);return z.streamEncode.bytes=o.byteLength,o};z.streamEncode.bytes=0;z.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let n=z.decode(t.slice(2));return z.streamDecode.bytes=z.decode.bytes,n};z.streamDecode.bytes=0;function vs(t,e){let n=0;for(let o=0;o<t.length;o++)n+=e.encodingLength(t[o]);return n}function Ka(t,e,n,o){for(let r=0;r<t.length;r++)e.encode(t[r],n,o),o+=e.encode.bytes;return o}function Rd(t,e,n,o){for(let r=0;r<t.length;r++)t[r]=e.decode(n,o),o+=e.decode.bytes;return o}});var MC=oe((vQ,NC)=>{"use strict";var LC=O6;process.nextTick($6,42);NC.exports=R6;function R6(t){var e=o;return n;function n(r){e(r||P6)}function o(r){var i=[r];e=s,t(a);function s(c){i.push(c)}function a(c){var l=arguments;for(e=A6(c)?o:u;i.length;)u(i.shift());function u(d){LC(D6,d,l)}}}}function A6(t){return Object.prototype.toString.call(t)==="[object Error]"}function P6(){}function D6(t,e){t.apply(null,e)}function $6(t){t===42&&(LC=process.nextTick)}function O6(t,e,n){process.nextTick(function(){t(e,n)})}});var BC=oe((bQ,FC)=>{var xw=OC(),L6=require("dgram"),N6=MC(),M6=require("events"),_w=require("os"),Sw=function(){};FC.exports=function(t){t||(t={});var e=new M6.EventEmitter,n=typeof t.port=="number"?t.port:5353,o=t.type||"udp4",r=t.ip||t.host||(o==="udp4"?"224.0.0.251":null),i={address:r,port:n},s={},a=!1,c=null;if(o==="udp6"&&(!r||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var l=t.socket||L6.createSocket({type:o,reuseAddr:t.reuseAddr!==!1,toString:function(){return o}});l.on("error",function(d){d.code==="EACCES"||d.code==="EADDRINUSE"?e.emit("error",d):e.emit("warning",d)}),l.on("message",function(d,f){try{d=xw.decode(d)}catch(m){e.emit("warning",m);return}e.emit("packet",d,f),d.type==="query"&&e.emit("query",d,f),d.type==="response"&&e.emit("response",d,f)}),l.on("listening",function(){n||(n=i.port=l.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),l.setMulticastTTL(t.ttl||255),l.setMulticastLoopback(t.loopback!==!1))});var u=N6(function(d){if(!n||t.bind===!1)return d(null);l.once("error",d),l.bind(n,t.bind||t.interface,function(){l.removeListener("error",d),d(null)})});return u(function(d){if(d)return e.emit("error",d);e.emit("ready")}),e.send=function(d,f,m){if(typeof f=="function")return e.send(d,null,f);m||(m=Sw),f?!f.host&&!f.address&&(f.address=i.address):f=i,u(g);function g(h){if(a)return m();if(h)return m(h);var y=xw.encode(d);l.send(y,0,y.length,f.port,f.address||f.host,m)}},e.response=e.respond=function(d,f,m){Array.isArray(d)&&(d={answers:d}),d.type="response",d.flags=(d.flags||0)|xw.AUTHORITATIVE_ANSWER,e.send(d,f,m)},e.query=function(d,f,m,g){if(typeof f=="function")return e.query(d,null,null,f);if(typeof f=="object"&&f&&f.port)return e.query(d,null,f,m);if(typeof m=="function")return e.query(d,f,null,m);g||(g=Sw),typeof d=="string"&&(d=[{name:d,type:f||"ANY"}]),Array.isArray(d)&&(d={type:"query",questions:d}),d.type="query",e.send(d,m,g)},e.destroy=function(d){if(d||(d=Sw),a)return process.nextTick(d);a=!0,clearInterval(c);for(var f in s)try{l.dropMembership(r,f)}catch{}s={},l.close(d)},e.update=function(){for(var d=t.interface?[].concat(t.interface):F6(),f=!1,m=0;m<d.length;m++){var g=d[m];if(!s[g])try{l.addMembership(r,g),s[g]=!0,f=!0}catch(h){e.emit("warning",h)}}if(f){if(l.setMulticastInterface)try{l.setMulticastInterface(t.interface||U6())}catch(h){e.emit("warning",h)}e.emit("networkInterface")}},e};function U6(){for(var t=_w.networkInterfaces(),e=Object.keys(t),n=0;n<e.length;n++)for(var o=t[e[n]],r=0;r<o.length;r++){var i=o[r];if(UC(i.family)&&!i.internal)return _w.platform()==="darwin"&&e[n]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function F6(){for(var t=_w.networkInterfaces(),e=Object.keys(t),n=[],o=0;o<e.length;o++)for(var r=t[e[o]],i=0;i<r.length;i++){var s=r[i];if(UC(s.family)){n.push(s.address);break}}return n}function UC(t){return t===4||t==="IPv4"}});var zC=oe((wQ,jC)=>{"use strict";jC.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var o,r,i;if(Array.isArray(e)){if(o=e.length,o!=n.length)return!1;for(r=o;r--!==0;)if(!t(e[r],n[r]))return!1;return!0}if(e instanceof Map&&n instanceof Map){if(e.size!==n.size)return!1;for(r of e.entries())if(!n.has(r[0]))return!1;for(r of e.entries())if(!t(r[1],n.get(r[0])))return!1;return!0}if(e instanceof Set&&n instanceof Set){if(e.size!==n.size)return!1;for(r of e.entries())if(!n.has(r[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(n)){if(o=e.length,o!=n.length)return!1;for(r=o;r--!==0;)if(e[r]!==n[r])return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),o=i.length,o!==Object.keys(n).length)return!1;for(r=o;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[r]))return!1;for(r=o;r--!==0;){var s=i[r];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var HC=oe(Yo=>{"use strict";var Iw=Yo&&Yo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Yo,"__esModule",{value:!0});Yo.Server=void 0;var B6=Iw(BC()),j6=Iw(zC()),z6=Iw(Id()),Pd=class{constructor(e,n){this.registry={},this.mdns=(0,B6.default)(e),this.mdns.setMaxListeners(0),this.mdns.on("query",this.respondToQuery.bind(this)),this.errorCallback=n??function(o){throw o}}register(e){let n=o=>{var r=this.registry[o.type];if(!r)r=this.registry[o.type]=[];else if(r.some(this.isDuplicateRecord(o)))return;r.push(o)};Array.isArray(e)?e.forEach(n):n(e)}unregister(e){let n=o=>{let r=o.type;r in this.registry&&(this.registry[r]=this.registry[r].filter(i=>i.name!==o.name))};Array.isArray(e)?e.forEach(n):n(e)}respondToQuery(e){let n=this;e.questions.forEach(o=>{var r=o.type,i=o.name,s=r==="ANY"?Object.keys(n.registry).map(n.recordsFor.bind(n,i)).flat(1):n.recordsFor(i,r);if(s.length!==0){var a=[];r!=="ANY"&&(s.forEach(c=>{c.type==="PTR"&&(a=a.concat(n.recordsFor(c.data,"SRV")).concat(n.recordsFor(c.data,"TXT")))}),a.filter(function(c){return c.type==="SRV"}).map(function(c){return c.data.target}).filter(this.unique()).forEach(function(c){a=a.concat(n.recordsFor(c,"A")).concat(n.recordsFor(c,"AAAA"))})),n.mdns.respond({answers:s,additionals:a},c=>{c&&this.errorCallback(c)})}})}recordsFor(e,n){return n in this.registry?this.registry[n].filter(o=>{var r=~e.indexOf(".")?o.name:o.name.split(".")[0];return(0,z6.default)(r,e)}):[]}isDuplicateRecord(e){return n=>e.type===n.type&&e.name===n.name&&(0,j6.default)(e.data,n.data)}unique(){var e=[];return n=>~e.indexOf(n)?!1:(e.push(n),!0)}};Yo.Server=Pd;Yo.default=Pd});var KC=oe(Tw=>{"use strict";Object.defineProperty(Tw,"__esModule",{value:!0});Tw.default=(t,e)=>{if(e===void 0)return!0;let n=t.txt,o=Object.entries(e).map(([r,i])=>{let s=n[r];return!(s===void 0||i!=s)});return o.length==0?!0:!o.includes(!1)}});var GC=oe(Ew=>{"use strict";Object.defineProperty(Ew,"__esModule",{value:!0});Ew.default=t=>Object.keys(t).filter(e=>!e.includes("binary")).reduce((e,n)=>Object.assign(e,{[n]:t[n]}),{})});var WC=oe(Cw=>{"use strict";Object.defineProperty(Cw,"__esModule",{value:!0});Cw.default=H6;function H6(t,e){if(t===void 0||e===void 0)return!1;let n=Object.keys(t),o=Object.keys(e);if(n.length!=o.length)return!1;for(let r of n)if(t[r]!=e[r])return!1;return!0}});var VC=oe(Xo=>{"use strict";var Ga=Xo&&Xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xo,"__esModule",{value:!0});Xo.Browser=void 0;var K6=Ga(lw()),io=Ga(Id()),G6=require("events"),Rw=uw(),ZC=Ga(KC()),W6=Ga(GC()),Z6=Ga(WC()),qC=".local",q6="_services._dns-sd._udp"+qC,Dd=class t extends G6.EventEmitter{constructor(e,n,o){if(super(),this.onresponse=void 0,this.serviceMap={},this.wildcard=!1,this._services=[],typeof n=="function")return new t(e,null,n);this.mdns=e,this.txt=new K6.default(n!==null&&n.txt!=null?n.txt:void 0),n===null||n.type===void 0?(this.name=q6,this.wildcard=!0):(this.name=(0,Rw.toString)({name:n.type,protocol:n.protocol||"tcp"})+qC,n.name&&(this.name=n.name+"."+this.name),this.wildcard=!1),n!=null&&n.txt!==void 0&&(this.txtQuery=(0,W6.default)(n.txt)),o&&this.on("up",o),this.start()}start(){if(!(this.onresponse||this.name===void 0)){var e=this,n={};this.wildcard||(n[this.name]=!0),this.onresponse=(o,r)=>{e.wildcard&&o.answers.forEach(s=>{s.type!=="PTR"||s.name!==e.name||s.name in n||(n[s.data]=!0,e.mdns.query(s.data,"PTR"))});let i=Date.now();Object.keys(n).forEach(function(s){e.goodbyes(s,o).forEach(e.removeService.bind(e));var a=e.buildServicesFor(s,o,e.txt,r,i);a.length!==0&&a.forEach(c=>{let l=e._services.find(u=>(0,io.default)(u.fqdn,c.fqdn));if(l){e.updateServiceSrv(l,c),e.updateServiceTxt(l,c);return}e.addService(c)})})},this.mdns.on("response",this.onresponse),this.update()}}stop(){this.onresponse&&(this.mdns.removeListener("response",this.onresponse),this.onresponse=void 0)}update(){this.mdns.query(this.name,"PTR")}expire(){let e=Date.now();this._services=this._services.filter(n=>!n.ttl||n.lastSeen===void 0?!0:n.lastSeen+n.ttl*1e3<e?(this.emit("down",n),!1):!0)}get services(){return this._services}addService(e){(0,ZC.default)(e,this.txtQuery)!==!1&&(this._services.push(e),this.serviceMap[e.fqdn]=!0,this.emit("up",e))}updateServiceSrv(e,n){(e.name!==n.name||e.host!==n.host||e.port!==n.port||e.type!==n.type||e.protocol!==n.protocol)&&(this.replaceService(n),this.emit("srv-update",n,e))}updateServiceTxt(e,n){if(!(0,Z6.default)(n.txt,e?.txt||{})){if(!(0,ZC.default)(n,this.txtQuery)){this.removeService(n.fqdn);return}this.replaceService(n),this.emit("txt-update",n,e)}}replaceService(e){this._services=this._services.map(n=>(0,io.default)(n.fqdn,e.fqdn)?e:n)}removeService(e){var n,o;this._services.some(function(r,i){if((0,io.default)(r.fqdn,e))return n=r,o=i,!0}),!(!n||o===void 0)&&(this._services.splice(o,1),delete this.serviceMap[e],this.emit("down",n))}goodbyes(e,n){return n.answers.concat(n.additionals).filter(o=>o.type==="PTR"&&o.ttl===0&&(0,io.default)(o.name,e)).map(o=>o.data)}buildServicesFor(e,n,o,r,i){var s=n.answers.concat(n.additionals).filter(a=>a.ttl>0);return s.filter(a=>a.type==="PTR"&&(0,io.default)(a.name,e)).map(a=>{let c={addresses:[],subtypes:[],ttl:a.ttl,lastSeen:i};if(s.filter(l=>l.type==="PTR"&&(0,io.default)(l.data,a.data)&&l.name.includes("._sub")).forEach(l=>{let u=(0,Rw.toType)(l.name);c.subtypes.push(u.subtype)}),s.filter(l=>(l.type==="SRV"||l.type==="TXT")&&(0,io.default)(l.name,a.data)).forEach(l=>{if(l.type==="SRV"){var u=l.name.split("."),d=u[0],f=(0,Rw.toType)(u.slice(1,-1).join("."));c.name=d,c.fqdn=l.name,c.host=l.data.target,c.referer=r,c.port=l.data.port,c.type=f.name,c.protocol=f.protocol}else l.type==="TXT"&&(c.rawTxt=l.data,c.txt=this.txt.decodeAll(l.data))}),!!c.name)return s.filter(l=>(l.type==="A"||l.type==="AAAA")&&(0,io.default)(l.name,c.host)).forEach(l=>c.addresses.push(l.data)),c}).filter(a=>!!a)}};Xo.Browser=Dd;Xo.default=Dd});var JC=oe(Lr=>{"use strict";var $d=Lr&&Lr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.Browser=Lr.Service=void 0;var V6=$d(SC()),J6=$d(HC()),Aw=$d(VC());Lr.Browser=Aw.default;var Y6=$d(dw());Lr.Service=Y6.default;var Pw=class{constructor(e={},n){this.server=new J6.default(e,n),this.registry=new V6.default(this.server)}publish(e){return this.registry.publish(e)}unpublishAll(e){return this.registry.unpublishAll(e)}find(e=null,n){return new Aw.default(this.server.mdns,e,n)}findOne(e=null,n=1e4,o){let r=new Aw.default(this.server.mdns,e);var i;return r.once("up",s=>{i!==void 0&&clearTimeout(i),r.stop(),o&&o(s)}),i=setTimeout(()=>{r.stop(),o&&o(null)},n),r}destroy(e){this.registry.destroy(),this.server.mdns.destroy(e)}};Lr.default=Pw});var XC=oe((wt,YC)=>{"use strict";var X6=wt&&wt.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(e,n);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,r)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),Q6=wt&&wt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),e4=wt&&wt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var o=[];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(o[o.length]=r);return o},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var o=t(e),r=0;r<o.length;r++)o[r]!=="default"&&X6(n,e,o[r]);return Q6(n,e),n}})();Object.defineProperty(wt,"__esModule",{value:!0});wt.Browser=wt.Service=wt.Bonjour=void 0;var Wa=e4(JC());Object.defineProperty(wt,"Service",{enumerable:!0,get:function(){return Wa.Service}});Object.defineProperty(wt,"Browser",{enumerable:!0,get:function(){return Wa.Browser}});var Qo=class extends Wa.default{};wt.Bonjour=Qo;wt.default=Qo;YC.exports=Object.assign(Qo,{Bonjour:Qo,Service:Wa.Service,Browser:Wa.Browser,default:Qo})});var N5,cp,dk,RA,M5,U5,AA=ct(()=>{N5=1,cp=2,dk=3,RA=4,M5=5,U5=6});function PA(t){return{type:"auth",access_token:t}}function DA(){return{type:"supported_features",id:1,features:{coalesce_messages:1}}}function $A(){return{type:"get_states"}}function OA(){return{type:"get_config"}}function LA(){return{type:"get_services"}}function NA(){return{type:"auth/current_user"}}function MA(t,e,n,o,r){let i={type:"call_service",domain:t,service:e,target:o,return_response:r};return n&&(i.service_data=n),i}function UA(t){let e={type:"subscribe_events"};return t&&(e.event_type=t),e}function pk(t){return{type:"unsubscribe_events",subscription:t}}function FA(){return{type:"ping"}}function BA(t,e){return{type:"result",success:!1,error:{code:t,message:e}}}var lp=ct(()=>{});function jA(t){let e={},n=t.split("&");for(let o=0;o<n.length;o++){let r=n[o].split("="),i=decodeURIComponent(r[0]),s=r.length>1?decodeURIComponent(r[1]):void 0;e[i]=s}return e}var zA,up,dc=ct(()=>{zA=(t,e,n=!1)=>{let o;return function(...r){let i=this,s=()=>{o=void 0,n||t.apply(i,r)},a=n&&!o;clearTimeout(o),o=setTimeout(s,e),a&&t.apply(i,r)}},up=(t,e,n,o)=>{let[r,i,s]=t.split(".",3);return Number(r)>e||Number(r)===e&&(o===void 0?Number(i)>=n:Number(i)>n)||o!==void 0&&Number(r)===e&&Number(i)===n&&Number(s)>=o}});function mk(t){if(!t.auth)throw 4;let e=t.auth,n=e.expired?e.refreshAccessToken().then(()=>{n=void 0},()=>{n=void 0}):void 0,o=e.wsUrl;dp&&console.log("[Auth phase] Initializing",o);function r(i,s,a){dp&&console.log("[Auth Phase] New connection",o);let c=new WebSocket(o),l=!1,u=()=>{if(c.removeEventListener("close",u),l){a(2);return}if(i===0){a(1);return}let m=i===-1?-1:i-1;setTimeout(()=>r(m,s,a),1e3)},d=async m=>{try{e.expired&&await(n||e.refreshAccessToken()),c.send(JSON.stringify(PA(e.accessToken)))}catch(g){l=g===2,c.close()}},f=async m=>{let g=JSON.parse(m.data);switch(dp&&console.log("[Auth phase] Received",g),g.type){case KA:l=!0,c.close();break;case GA:c.removeEventListener("open",d),c.removeEventListener("message",f),c.removeEventListener("close",u),c.removeEventListener("error",u),c.haVersion=g.ha_version,up(c.haVersion,2022,9)&&c.send(JSON.stringify(DA())),s(c);break;default:dp&&g.type!==HA&&console.warn("[Auth phase] Unhandled message",g)}};c.addEventListener("open",d),c.addEventListener("message",f),c.addEventListener("close",u),c.addEventListener("error",u)}return new Promise((i,s)=>r(t.setupRetry,i,s))}var dp,HA,KA,GA,gk=ct(()=>{lp();dc();dp=!1,HA="auth_required",KA="auth_invalid",GA="auth_ok"});var pc,fc,hk=ct(()=>{lp();pc=!1,fc=class{constructor(e,n){this._handleMessage=o=>{let r=JSON.parse(o.data);Array.isArray(r)||(r=[r]),r.forEach(i=>{pc&&console.log("Received",i);let s=this.commands.get(i.id);switch(i.type){case"event":s?s.callback(i.event):(console.warn(`Received event for unknown subscription ${i.id}. Unsubscribing.`),this.sendMessagePromise(pk(i.id)).catch(a=>{pc&&console.warn(` Error unsubsribing from unknown subscription ${i.id}`,a)}));break;case"result":s&&(i.success?(s.resolve(i.result),"subscribe"in s||this.commands.delete(i.id)):(s.reject(i.error),this.commands.delete(i.id)));break;case"pong":s?(s.resolve(),this.commands.delete(i.id)):console.warn(`Received unknown pong response ${i.id}`);break;default:pc&&console.warn("Unhandled message",i)}})},this._handleClose=async()=>{let o=this.commands;if(this.commandId=1,this.oldSubscriptions=this.commands,this.commands=new Map,this.socket=void 0,o.forEach(s=>{"subscribe"in s||s.reject(BA(3,"Connection lost"))}),this.closeRequested)return;this.fireEvent("disconnected");let r=Object.assign(Object.assign({},this.options),{setupRetry:0}),i=s=>{setTimeout(async()=>{if(!this.closeRequested){pc&&console.log("Trying to reconnect");try{let a=await r.createSocket(r);this._setSocket(a)}catch(a){if(this._queuedMessages){let c=this._queuedMessages;this._queuedMessages=void 0;for(let l of c)l.reject&&l.reject(3)}a===2?this.fireEvent("reconnect-error",a):i(s+1)}}},Math.min(s,5)*1e3)};this.suspendReconnectPromise&&(await this.suspendReconnectPromise,this.suspendReconnectPromise=void 0,this._queuedMessages=[]),i(0)},this.options=n,this.commandId=2,this.commands=new Map,this.eventListeners=new Map,this.closeRequested=!1,this._setSocket(e)}get connected(){return this.socket!==void 0&&this.socket.readyState==this.socket.OPEN}_setSocket(e){this.socket=e,this.haVersion=e.haVersion,e.addEventListener("message",this._handleMessage),e.addEventListener("close",this._handleClose);let n=this.oldSubscriptions;n&&(this.oldSubscriptions=void 0,n.forEach(r=>{"subscribe"in r&&r.subscribe&&r.subscribe().then(i=>{r.unsubscribe=i,r.resolve()})}));let o=this._queuedMessages;if(o){this._queuedMessages=void 0;for(let r of o)r.resolve()}this.fireEvent("ready")}addEventListener(e,n){let o=this.eventListeners.get(e);o||(o=[],this.eventListeners.set(e,o)),o.push(n)}removeEventListener(e,n){let o=this.eventListeners.get(e);if(!o)return;let r=o.indexOf(n);r!==-1&&o.splice(r,1)}fireEvent(e,n){(this.eventListeners.get(e)||[]).forEach(o=>o(this,n))}suspendReconnectUntil(e){this.suspendReconnectPromise=e}suspend(){if(!this.suspendReconnectPromise)throw new Error("Suspend promise not set");this.socket&&this.socket.close()}reconnect(e=!1){if(this.socket){if(!e){this.socket.close();return}this.socket.removeEventListener("message",this._handleMessage),this.socket.removeEventListener("close",this._handleClose),this.socket.close(),this._handleClose()}}close(){this.closeRequested=!0,this.socket&&this.socket.close()}async subscribeEvents(e,n){return this.subscribeMessage(e,UA(n))}ping(){return this.sendMessagePromise(FA())}sendMessage(e,n){if(!this.connected)throw 3;if(pc&&console.log("Sending",e),this._queuedMessages){if(n)throw new Error("Cannot queue with commandId");this._queuedMessages.push({resolve:()=>this.sendMessage(e)});return}n||(n=this._genCmdId()),e.id=n,this.socket.send(JSON.stringify(e))}sendMessagePromise(e){return new Promise((n,o)=>{if(this._queuedMessages){this._queuedMessages.push({reject:o,resolve:async()=>{try{n(await this.sendMessagePromise(e))}catch(i){o(i)}}});return}let r=this._genCmdId();this.commands.set(r,{resolve:n,reject:o}),this.sendMessage(e,r)})}async subscribeMessage(e,n,o){if(this._queuedMessages&&await new Promise((i,s)=>{this._queuedMessages.push({resolve:i,reject:s})}),o?.preCheck&&!await o.preCheck())throw new Error("Pre-check failed");let r;return await new Promise((i,s)=>{let a=this._genCmdId();r={resolve:i,reject:s,callback:e,subscribe:o?.resubscribe!==!1?()=>this.subscribeMessage(e,n,o):void 0,unsubscribe:async()=>{this.connected&&await this.sendMessagePromise(pk(a)),this.commands.delete(a)}},this.commands.set(a,r);try{this.sendMessage(n,a)}catch{}}),()=>r.unsubscribe()}_genCmdId(){return++this.commandId}}});function F5(){let{protocol:t,host:e,pathname:n,search:o}=location;return`${t}//${e}${n}${o}`}function B5(t,e,n,o){let r=`${t}/auth/authorize?response_type=code&redirect_uri=${encodeURIComponent(n)}`;return e!==null&&(r+=`&client_id=${encodeURIComponent(e)}`),o&&(r+=`&state=${encodeURIComponent(o)}`),r}function j5(t,e,n,o){n+=(n.includes("?")?"&":"?")+"auth_callback=1",document.location.href=B5(t,e,n,o)}async function VA(t,e,n){let o=typeof location<"u"&&location;if(o&&o.protocol==="https:"){let a=document.createElement("a");if(a.href=t,a.protocol==="http:"&&a.hostname!=="localhost")throw 5}let r=new FormData;e!==null&&r.append("client_id",e),Object.keys(n).forEach(a=>{r.append(a,n[a])});let i=await fetch(`${t}/auth/token`,{method:"POST",credentials:"same-origin",body:r});if(!i.ok)throw i.status===400||i.status===403?2:new Error("Unable to fetch tokens");let s=await i.json();return s.hassUrl=t,s.clientId=e,s.expires=qA(s.expires_in),s}function WA(t,e,n){return VA(t,e,{code:n,grant_type:"authorization_code"})}function z5(t){return btoa(JSON.stringify(t))}function H5(t){return JSON.parse(atob(t))}function K5(t,e){return new mc({hassUrl:t,clientId:null,expires:Date.now()+1e11,refresh_token:"",access_token:e,expires_in:1e11})}async function G5(t={}){let e,n=t.hassUrl;n&&n[n.length-1]==="/"&&(n=n.substr(0,n.length-1));let o=t.clientId!==void 0?t.clientId:ZA(),r=t.limitHassInstance===!0;if(t.authCode&&n&&(e=await WA(n,o,t.authCode),t.saveTokens&&t.saveTokens(e)),!e){let i=jA(location.search.substr(1));if("auth_callback"in i){let s=H5(i.state);if(r&&(s.hassUrl!==n||s.clientId!==o))throw 6;e=await WA(s.hassUrl,s.clientId,i.code),t.saveTokens&&t.saveTokens(e)}}if(!e&&t.loadTokens&&(e=await t.loadTokens()),e&&(n===void 0||e.hassUrl===n))return new mc(e,t.saveTokens);if(n===void 0)throw 4;return j5(n,o,t.redirectUrl||F5(),z5({hassUrl:n,clientId:o})),new Promise(()=>{})}var ZA,qA,mc,JA=ct(()=>{dc();ZA=()=>`${location.protocol}//${location.host}/`,qA=t=>t*1e3+Date.now();mc=class{constructor(e,n){this.data=e,this._saveTokens=n}get wsUrl(){return`ws${this.data.hassUrl.substr(4)}/api/websocket`}get accessToken(){return this.data.access_token}get expired(){return Date.now()>this.data.expires}async refreshAccessToken(){if(!this.data.refresh_token)throw new Error("No refresh_token");let e=await VA(this.data.hassUrl,this.data.clientId,{grant_type:"refresh_token",refresh_token:this.data.refresh_token});e.refresh_token=this.data.refresh_token,this.data=e,this._saveTokens&&this._saveTokens(e)}async revoke(){if(!this.data.refresh_token)throw new Error("No refresh_token to revoke");let e=new FormData;e.append("token",this.data.refresh_token),await fetch(`${this.data.hassUrl}/auth/revoke`,{method:"POST",credentials:"same-origin",body:e}),this._saveTokens&&this._saveTokens(null)}}});var yk,vk=ct(()=>{yk=t=>{let e=[];function n(r){let i=[];for(let s=0;s<e.length;s++)e[s]===r?r=null:i.push(e[s]);e=i}function o(r,i){t=i?r:Object.assign(Object.assign({},t),r);let s=e;for(let a=0;a<s.length;a++)s[a](t)}return{get state(){return t},action(r){function i(s){o(s,!1)}return function(){let s=[t];for(let c=0;c<arguments.length;c++)s.push(arguments[c]);let a=r.apply(this,s);if(a!=null)return a instanceof Promise?a.then(i):i(a)}},setState:o,clearState(){t=void 0},subscribe(r){return e.push(r),()=>{n(r)}}}}});var W5,Is,Mr,Z5,gc=ct(()=>{vk();W5=5e3,Is=!1,Mr=(t,e,n,o,r={unsubGrace:!0})=>{if(t[e])return t[e];let i=0,s,a,c=yk(),l=()=>{if(!n)throw new Error("Collection does not support refresh");return n(t).then(h=>c.setState(h,!0))},u=()=>l().catch(h=>{if(t.connected)throw h}),d=()=>{if(a!==void 0){Is&&console.log(`Prevented unsubscribe for ${e}`),clearTimeout(a),a=void 0;return}Is&&console.log(`Subscribing to ${e}`),o&&(s=o(t,c)),n&&(t.addEventListener("ready",u),u()),t.addEventListener("disconnected",g)},f=()=>{Is&&console.log(`Unsubscribing from ${e}`),a=void 0,s&&s.then(h=>{h()}),c.clearState(),t.removeEventListener("ready",l),t.removeEventListener("disconnected",g)},m=()=>{Is&&console.log(`Scheduling unsubscribing from ${e}`),a=setTimeout(f,W5)},g=()=>{a&&(clearTimeout(a),f())};return t[e]={get state(){return c.state},refresh:l,subscribe(h){i++,Is&&console.log(`New subscriber for ${e}. Active subscribers: ${i}`),i===1&&d();let y=c.subscribe(h);return c.state!==void 0&&setTimeout(()=>h(c.state),0),()=>{y(),i--,Is&&console.log(`Unsubscribe for ${e}. Active subscribers: ${i}`),i||(r.unsubGrace?m():f())}}},t[e]},Z5=(t,e,n,o,r)=>Mr(o,t,e,n).subscribe(r)});var bk,wk,kk,q5,V5,hc=ct(()=>{lp();bk=t=>t.sendMessagePromise($A()),wk=t=>t.sendMessagePromise(LA()),kk=t=>t.sendMessagePromise(OA()),q5=t=>t.sendMessagePromise(NA()),V5=(t,e,n,o,r,i)=>t.sendMessagePromise(MA(e,n,o,r,i))});function J5(t,e){return t===void 0?null:{components:t.components.concat(e.data.component)}}var YA,Y5,XA,X5,Q5,eH,tH,nH,rH,QA=ct(()=>{gc();hc();YA=t=>kk(t),Y5=(t,e)=>Promise.all([t.subscribeEvents(e.action(J5),"component_loaded"),t.subscribeEvents(()=>YA(t).then(n=>e.setState(n,!0)),"core_config_updated")]).then(n=>()=>n.forEach(o=>o())),XA=t=>Mr(t,"_cnf",YA,Y5),X5=(t,e)=>XA(t).subscribe(e),Q5="NOT_RUNNING",eH="STARTING",tH="RUNNING",nH="STOPPING",rH="FINAL_WRITE"});function oH(t,e,n){var o;let r=e.state;if(r===void 0)return;let{domain:i,service:s}=n.data;if(!(!((o=r.domain)===null||o===void 0)&&o.service)){let a=Object.assign(Object.assign({},r[i]),{[s]:{description:"",fields:{}}});e.setState({[i]:a})}sH(t,e)}function iH(t,e){if(t===void 0)return null;let{domain:n,service:o}=e.data,r=t[n];if(!r||!(o in r))return null;let i={};return Object.keys(r).forEach(s=>{s!==o&&(i[s]=r[s])}),{[n]:i}}var sH,eP,aH,tP,cH,nP=ct(()=>{gc();hc();dc();sH=zA((t,e)=>eP(t).then(n=>e.setState(n,!0)),5e3),eP=t=>wk(t),aH=(t,e)=>Promise.all([t.subscribeEvents(n=>oH(t,e,n),"service_registered"),t.subscribeEvents(e.action(iH),"service_removed")]).then(n=>()=>n.forEach(o=>o())),tP=t=>Mr(t,"_srv",eP,aH),cH=(t,e)=>tP(t).subscribe(e)});function lH(t,e){let n=Object.assign({},t.state);if(e.a)for(let o in e.a){let r=e.a[o],i=new Date(r.lc*1e3).toISOString();n[o]={entity_id:o,state:r.s,attributes:r.a,context:typeof r.c=="string"?{id:r.c,parent_id:null,user_id:null}:r.c,last_changed:i,last_updated:r.lu?new Date(r.lu*1e3).toISOString():i}}if(e.r)for(let o of e.r)delete n[o];if(e.c)for(let o in e.c){let r=n[o];if(!r){console.warn("Received state update for unknown entity",o);continue}r=Object.assign({},r);let{"+":i,"-":s}=e.c[o],a=i?.a||s?.a,c=a?Object.assign({},r.attributes):r.attributes;if(i&&(i.s!==void 0&&(r.state=i.s),i.c&&(typeof i.c=="string"?r.context=Object.assign(Object.assign({},r.context),{id:i.c}):r.context=Object.assign(Object.assign({},r.context),i.c)),i.lc?r.last_updated=r.last_changed=new Date(i.lc*1e3).toISOString():i.lu&&(r.last_updated=new Date(i.lu*1e3).toISOString()),i.a&&Object.assign(c,i.a)),s?.a)for(let l of s.a)delete c[l];a&&(r.attributes=c),n[o]=r}t.setState(n,!0)}function dH(t,e){let n=t.state;if(n===void 0)return;let{entity_id:o,new_state:r}=e.data;if(r)t.setState({[r.entity_id]:r});else{let i=Object.assign({},n);delete i[o],t.setState(i,!0)}}async function pH(t){let e=await bk(t),n={};for(let o=0;o<e.length;o++){let r=e[o];n[r.entity_id]=r}return n}var uH,fH,rP,mH,oP=ct(()=>{gc();hc();dc();uH=(t,e)=>t.subscribeMessage(n=>lH(e,n),{type:"subscribe_entities"});fH=(t,e)=>t.subscribeEvents(n=>dH(e,n),"state_changed"),rP=t=>up(t.haVersion,2022,4,0)?Mr(t,"_ent",void 0,uH):Mr(t,"_ent",pH,fH),mH=(t,e)=>rP(t).subscribe(e)});var iP=ct(()=>{});var sP={};Xt(sP,{Auth:()=>mc,Connection:()=>fc,ERR_CANNOT_CONNECT:()=>N5,ERR_CONNECTION_LOST:()=>dk,ERR_HASS_HOST_REQUIRED:()=>RA,ERR_INVALID_AUTH:()=>cp,ERR_INVALID_AUTH_CALLBACK:()=>U5,ERR_INVALID_HTTPS_TO_HTTP:()=>M5,MSG_TYPE_AUTH_INVALID:()=>KA,MSG_TYPE_AUTH_OK:()=>GA,MSG_TYPE_AUTH_REQUIRED:()=>HA,STATE_FINAL_WRITE:()=>rH,STATE_NOT_RUNNING:()=>Q5,STATE_RUNNING:()=>tH,STATE_STARTING:()=>eH,STATE_STOPPING:()=>nH,callService:()=>V5,configColl:()=>XA,createCollection:()=>Z5,createConnection:()=>gH,createLongLivedTokenAuth:()=>K5,createSocket:()=>mk,createStore:()=>yk,entitiesColl:()=>rP,genClientId:()=>ZA,genExpires:()=>qA,getAuth:()=>G5,getCollection:()=>Mr,getConfig:()=>kk,getServices:()=>wk,getStates:()=>bk,getUser:()=>q5,servicesColl:()=>tP,subscribeConfig:()=>X5,subscribeEntities:()=>mH,subscribeServices:()=>cH});async function gH(t){let e=Object.assign({setupRetry:0,createSocket:mk},t),n=await e.createSocket(e);return new fc(n,e)}var aP=ct(()=>{gk();hk();JA();gc();hk();QA();nP();oP();AA();gk();iP();hc();vk()});var B1={};Xt(B1,{CONNACK_ERRORS:()=>O1,DISCONNECT_PACKET:()=>D1,PINGREQ_PACKET:()=>P1,PacketReader:()=>Qp,connectMqtt:()=>wG,decodeConnack:()=>L1,decodeConnect:()=>vG,decodePublish:()=>U1,decodeSuback:()=>bG,encodeConnect:()=>$1,encodePuback:()=>F1,encodePublish:()=>M1,encodeSubscribe:()=>N1,encodeVarInt:()=>R1,readVarInt:()=>A1});function R1(t){if(t<0||t>268435455)throw new Error(`mqtt: remaining length ${t} is too large`);let e=[],n=t;do{let o=n%128;n=Math.floor(n/128),n>0&&(o|=128),e.push(o)}while(n>0);return Buffer.from(e)}function A1(t,e){let n=0,o=1;for(let r=0;r<4;r+=1){let i=t[e+r];if(i===void 0)return null;if(n+=(i&127)*o,(i&128)===0)return{value:n,next:e+r+1};o*=128}throw new Error("mqtt: malformed remaining length (more than 4 continuation bytes)")}function Ns(t){let e=Buffer.from(t,"utf8"),n=Buffer.alloc(2);return n.writeUInt16BE(e.length,0),Buffer.concat([n,e])}function Nc(t,e){let n=t.readUInt16BE(e);return{value:t.subarray(e+2,e+2+n).toString("utf8"),next:e+2+n}}function $1(t){let e=t.username,n=e?t.password:void 0,o=2;e&&(o|=128),n&&(o|=64);let r=Buffer.alloc(4);return r.writeUInt8(4,0),r.writeUInt8(o,1),r.writeUInt16BE(t.keepaliveSec,2),ef(1,0,Buffer.concat([Ns("MQTT"),r,Ns(t.clientId),...e?[Ns(e)]:[],...n?[Ns(n)]:[]]))}function vG(t){let e=Nc(t,0),n=t.readUInt8(e.next),o=t.readUInt8(e.next+1),r=t.readUInt16BE(e.next+2),i=Nc(t,e.next+4),s=i.next,a,c;if(o&128){let l=Nc(t,s);a=l.value,s=l.next}return o&64&&(c=Nc(t,s).value),{protocol:e.value,level:n,cleanSession:(o&2)!==0,keepaliveSec:r,clientId:i.value,...a!==void 0?{username:a}:{},...c!==void 0?{password:c}:{}}}function bG(t){let e=[...t.subarray(2)];return{packetId:t.readUInt16BE(0),codes:e,failed:e.some(n=>n===128)}}function M1(t,e,n={}){let o=n.qos??0,r=o<<1|(n.retain?1:0),i=[Ns(t)];if(o>0){let s=Buffer.alloc(2);s.writeUInt16BE(n.packetId??1,0),i.push(s)}return i.push(Buffer.from(e,"utf8")),ef(3,r,Buffer.concat(i))}function U1(t,e){let n=t>>1&3,o=Nc(e,0),r=o.next,i;return n>0&&(i=e.readUInt16BE(r),r+=2),{topic:o.value,payload:e.subarray(r).toString("utf8"),retain:(t&1)!==0,qos:n,...i!==void 0?{packetId:i}:{}}}function F1(t){let e=Buffer.alloc(2);return e.writeUInt16BE(t,0),ef(4,0,e)}async function wG(t,e){let n=await import("node:net"),o=t.tls?await import("node:tls"):null,r=o?o.connect({host:t.host,port:t.port,servername:t.host}):n.connect({host:t.host,port:t.port});r.setNoDelay(!0);let i=new Qp,s=1,a=!1,c=null,l=()=>(s=s>=65535?1:s+1,s),u=()=>{a||(a=!0,c&&clearInterval(c),c=null,r.destroy(),e.onClose())};return await new Promise((d,f)=>{let m=setTimeout(()=>{r.destroy(),f(new Error(`mqtt: ${t.host}:${t.port} did not answer within ${C1}ms`))},C1),g=h=>{clearTimeout(m),h?(r.destroy(),f(h)):d()};r.once("error",h=>g(new Error(`mqtt: cannot reach ${t.host}:${t.port} \u2014 ${h.message}`))),r.on("data",h=>{let y;try{y=i.push(h)}catch(b){g(b instanceof Error?b:new Error(String(b))),u();return}for(let b of y){if(b.type===2){let w=L1(b.body);g(w.code===0?void 0:new Error(`mqtt: ${t.host} refused the connection \u2014 ${O1[w.code]??`code ${w.code}`}`));continue}if(b.type===3){let w=U1(b.flags,b.body);w.qos===1&&w.packetId!==void 0&&r.write(F1(w.packetId)),e.onMessage(w.topic,w.payload)}}}),r.once("close",u),r.once(t.tls?"secureConnect":"connect",()=>{r.write($1({clientId:t.clientId,keepaliveSec:E1,...t.username?{username:t.username}:{},...t.password?{password:t.password}:{}}))})}),c=setInterval(()=>{a||r.write(P1)},E1/2*1e3),c.unref?.(),{async subscribe(d){if(a)throw new Error("mqtt: not connected");r.write(N1(l(),d))},async publish(d,f,m){if(a)throw new Error("mqtt: not connected");r.write(M1(d,f,m?.retain?{retain:!0}:{}))},async close(){if(!a){a=!0,c&&clearInterval(c),c=null,r.removeListener("close",u);try{r.write(D1)}catch{}r.destroy()}}}}var ef,P1,D1,O1,L1,N1,Qp,E1,C1,j1=ct(()=>{"use strict";ef=(t,e,n)=>Buffer.concat([Buffer.from([t<<4|e]),R1(n.length),n]),P1=Buffer.from([192,0]),D1=Buffer.from([224,0]);O1={1:"the broker refused protocol version 3.1.1",2:"the broker rejected the client id",3:"the broker is unavailable",4:"bad username or password",5:"not authorised \u2014 check the broker's ACL for this user"},L1=t=>({sessionPresent:(t.readUInt8(0)&1)!==0,code:t.readUInt8(1)}),N1=(t,e,n=0)=>{let o=Buffer.alloc(2);return o.writeUInt16BE(t,0),ef(8,2,Buffer.concat([o,Ns(e),Buffer.from([n])]))};Qp=class{buffer=Buffer.alloc(0);push(e){this.buffer=this.buffer.length===0?e:Buffer.concat([this.buffer,e]);let n=[];for(;!(this.buffer.length<2);){let o=this.buffer.readUInt8(0),r=A1(this.buffer,1);if(!r)break;let i=r.next+r.value;if(this.buffer.length<i)break;n.push({type:o>>4,flags:o&15,body:this.buffer.subarray(r.next,i)}),this.buffer=this.buffer.subarray(i)}return n}},E1=60,C1=1e4});var MN=require("node:crypto"),Hs=require("node:fs"),UN=require("node:path");var K0=require("node:crypto"),Nt=require("node:fs"),G0=G(require("node:os"),1),mt=G(require("node:path"),1);var h0=G(require("node:os"),1),y0=G(require("node:path"),1),Te=process.env.BRIDGE_SECRET_DIR||y0.default.join(h0.default.homedir(),".claude-bridge");var w0=require("node:crypto"),Yf=require("node:fs"),Ks=G(require("node:path"),1);var Mn=require("node:fs"),b0=G(require("node:path"),1);function sM(t){return[...new Set(t.split(`
9
+ `).map(e=>e.trim()).filter(Boolean))]}function v0(t){try{return sM((0,Mn.readFileSync)(t,"utf8"))}catch{return[]}}function Yc(t){let e=n=>{try{if(n.length===0){(0,Mn.rmSync)(t,{force:!0});return}(0,Mn.mkdirSync)(b0.default.dirname(t),{recursive:!0,mode:448});let o=`${t}.tmp`;(0,Mn.writeFileSync)(o,`${n.join(`
10
+ `)}
11
+ `,{mode:384}),(0,Mn.renameSync)(o,t)}catch{}};return{add(n){let o=v0(t);o.includes(n)||e([...o,n])},remove(n){let o=v0(t);o.includes(n)&&e(o.filter(r=>r!==n))}}}var aM=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/;function lr(t){return aM.test(t)&&!t.includes("..")?t:`h_${(0,w0.createHash)("sha256").update(t,"utf8").digest("hex").slice(0,24)}`}function Xf(t){return Ks.default.join(Te,"users",t)}function Ot(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1]??"","base64url").toString("utf8"));return typeof e.sub=="string"&&e.sub?e.sub:null}catch{return null}}function Qf(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1]??"","base64url").toString("utf8"));return typeof e.nid=="string"&&e.nid?e.nid:null}catch{return null}}var Xc=Ks.default.join(Te,"active-user.json");function k0(){try{let t=JSON.parse((0,Yf.readFileSync)(Xc,"utf8"));return typeof t.sub=="string"&&t.sub?t.sub:null}catch{return null}}function cM(t){if(!t||t.includes("/")||t.includes("\\")||t.includes("..")||t.includes("\0"))throw new Error(`unsafe credential segment: ${JSON.stringify(t)}`)}function ur(t){cM(t);let e=Xf(t);return{accessFile:Ks.default.join(e,"relay-access-token"),refreshFile:Ks.default.join(e,"relay-refresh-token")}}var em="hub-endpoint.json";function x0(t){if(t?.isDevBuild!==!0)return!1;let e=t.env??process.env;return e.BRIDGE_VOICE==="1"||e.BRIDGE_VOICE==="true"}var lM=[{name:"pem",re:/-----BEGIN[ A-Z]*PRIVATE KEY-----[\s\S]*?-----END[ A-Z]*PRIVATE KEY-----/g},{name:"aws-akia",re:/AKIA[0-9A-Z]{16}/g},{name:"github",re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b/g},{name:"slack",re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic",re:/\bsk-ant-[A-Za-z0-9_-]{20,}/g},{name:"openai",re:/\bsk-[A-Za-z0-9]{32,}\b/g},{name:"jwt",re:/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g},{name:"bearer",re:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g},{name:"workos",re:/\bwos_[A-Za-z0-9]{20,}\b/g},{name:"client-secret",re:/client_secret["'\s:=]{1,4}[A-Za-z0-9._~+/=-]{16,}/gi},{name:"doppler",re:/\bdp\.(?:st|pt|sa|scim|audit)\.[A-Za-z0-9._-]{16,}/g}],uM=/[A-Za-z0-9+/_=]{32,}/g;function dM(t){return(/[a-z]/.test(t)?1:0)+(/[A-Z]/.test(t)?1:0)+(/[0-9]/.test(t)?1:0)+(/[+/_=]/.test(t)?1:0)}var pM=256*1024;function fM(t,e){let n=t;for(let o of lM)n=n.replace(o.re,`[REDACTED:${o.name}]`);for(let o of e.knownSecrets)o&&o.length>=8&&(n=n.split(o).join("[REDACTED:known]"));return n=n.replace(uM,o=>dM(o)>=3?"[REDACTED:high-entropy]":o),e.homedir&&(n=n.split(e.homedir).join("~")),n}function tm(t,e){if(typeof t=="string")return fM(t,e);if(Array.isArray(t))return t.map(n=>tm(n,e));if(t&&typeof t=="object"){let n={};for(let[o,r]of Object.entries(t))n[o]=tm(r,e);return n}return t}function nm(t){if(Array.isArray(t))return t.map(nm);if(t&&typeof t=="object"){let e=t,n=e.type==="thinking",o={};for(let[r,i]of Object.entries(e))n&&r==="signature"||(o[r]=nm(i));return o}return t}function mM(t){return typeof Buffer<"u"?Buffer.byteLength(t,"utf8"):new TextEncoder().encode(t).length}function S0(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n.type;if(o==="file-history-snapshot"||o==="attachment")return null;let r=nm(n),i=tm(r,e),s=mM(JSON.stringify(i));return s>pM?{type:i.type??null,uuid:i.uuid??null,timestamp:i.timestamp??null,parentUuid:i.parentUuid??null,truncated:s}:i}var I0=require("node:fs"),xi=G(require("node:path"),1);var gM=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function _0(t){if(typeof t!="string")return{kind:"invalid"};let e=gM.exec(t);return e?e[1]==="0"&&e[2]==="0"&&e[3]==="0"?{kind:"dev"}:{kind:"release",version:t}:{kind:"invalid"}}function rm(t=process.env,e=process.argv){let n=_0(t.BRIDGE_CLIENT_VERSION);if(n.kind==="release")return n.version;if(n.kind==="dev")return null;let o=xi.default.join(Te,"payload"),r=e[1];if(!r)return null;let i=xi.default.relative(o,xi.default.resolve(r));if(i===""||i.startsWith("..")||xi.default.isAbsolute(i))return null;try{let s=JSON.parse((0,I0.readFileSync)(xi.default.join(o,"version.json"),"utf8")),a=_0(s.version);return a.kind==="release"?a.version:null}catch{return null}}var T0=require("node:fs"),E0=G(require("node:path"),1);var Qc=class extends Error{constructor(n,o){super(n);this.status=o;this.name="RelayError"}status},hM=t=>t.replace(/\/+$/,"");async function yM(t,e,n,o){return fetch(`${hM(t)}${e}`,{method:"POST",headers:{"content-type":"application/json",...o?{authorization:`Bearer ${o}`}:{}},body:n===void 0?void 0:JSON.stringify(n)})}async function vM(t,e){let n=await yM(t,"/node/token",void 0,e);if(!n.ok)throw new Qc(`refresh rejected (${n.status})`,n.status);return await n.json()}function C0(t,e={}){let n=e.log??(c=>console.warn(c)),o=Ot(t.refresh_token),r=Ot(t.access_token),i=o??r;if(o&&r&&o!==r&&n(`credential: access-token sub (${r}) differs from refresh-token sub (${o}) \u2014 trusting the refresh sub (the refresh loop re-mints the access token)`),!i)throw new Error("credential: refusing to persist an unattributable token pair (no decodable sub in refresh or access token)");let s=lr(i),a=ur(s);return pe(a.refreshFile,t.refresh_token),pe(a.accessFile,t.access_token),{sub:i,segment:s}}var bM="__none__";function el(){let t=k0();if(t)return ur(lr(t));let[e,n]=kM();return e&&!n?ur(e.segment):ur(bM)}function wM(t){let e;try{e=(0,T0.readdirSync)(E0.default.join(Te,"users"),{withFileTypes:!0})}catch{return[]}let n=[];for(let o of e){if(!o.isDirectory())continue;let r;try{r=ur(o.name)}catch{continue}let i=X(r.refreshFile),s=i?Ot(i):null;if(t){if(!s)continue;n.push({sub:s,segment:o.name});continue}let a=s?null:X(r.accessFile),c=s??(a?Ot(a):null);c&&n.push({sub:c,segment:o.name})}return n}function kM(){return wM(!1)}function Gs(t=el()){return X(t.refreshFile)}function R0(t=el()){it(t.accessFile),it(t.refreshFile)}function A0(t=el()){let e=X(t.accessFile);if(!e)return null;try{let n=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString());return typeof n.exp=="number"?n.exp-Math.floor(Date.now()/1e3):null}catch{return null}}async function xM(t,e=60,n,o=el()){let r=A0(o);if(r!==null&&r>e)return!0;let i=Gs(o);if(!i)return r!==null&&r>0;try{return C0(await vM(t,i)),!0}catch(s){return n?.(`token refresh failed: ${s instanceof Error?s.message:String(s)}`),s instanceof Qc&&(s.status===400||s.status===401)&&R0(o),!1}}var SM=(t,e)=>new Promise(n=>{if(e?.aborted)return n();let o=setTimeout(()=>{e?.removeEventListener("abort",r),n()},t),r=()=>{clearTimeout(o),n()};e?.addEventListener("abort",r,{once:!0})});async function P0(t,e={}){let{log:n,signal:o}=e;for(;!o?.aborted;){await xM(t,60,n,e.paths);let r=A0(e.paths),i=Math.min(300,Math.max(30,(r??60)-60));n?.(`access ttl ${r??"?"}s \u2014 next refresh in ${i}s`),await SM(i*1e3,o)}}function D0(t=Gs()){return t!==null}var tl=G(require("node:path"),1);function om(t){if(!t)return!1;try{return t.available()}catch{return!1}}function $0(t){return om(t)?"keyring":"file"}function im(t){let{file:e,account:n}=t,o=()=>X(e);return{backend(){return $0(t.keyring)},read(){if(om(t.keyring))try{let r=t.keyring.get(n);if(r!==null)return r;let i=o();if(i===null)return null;try{t.keyring.set(n,i),it(e),t.index?.add(n)}catch{}return i}catch{}return o()},write(r){if(om(t.keyring))try{t.keyring.set(n,r),it(e),t.index?.add(n);return}catch{}pe(e,r,384)},delete(){if(t.keyring){try{t.keyring.delete(n)}catch{}t.index?.remove(n)}it(e)}}}function sm(t,e,n){let o=t.providerSecretFile(e,n);return im({keyring:am(),file:o,account:`${e}/${n}`,index:Yc(tl.default.join(tl.default.dirname(tl.default.dirname(o)),".keyring-index"))})}var _M="AC Bridge",Kr,IM=new Set(["win32","darwin"]);function am(t={}){if(Kr!==void 0)return Kr;Kr=null;let e=t.require??null;if(!IM.has(t.platform??process.platform))return Kr;try{let n=e??TM();if(!n)return Kr;let{Entry:o}=n("@napi-rs/keyring"),r=i=>new o(_M,i);Kr={available(){try{return r("__acb_probe__").getPassword(),!0}catch{return!1}},get:i=>r(i).getPassword(),set:(i,s)=>r(i).setPassword(s),delete:i=>{r(i).deletePassword()}}}catch{Kr=null}return Kr}function TM(){try{return typeof require=="function"?require:null}catch{return null}}var lm={udpDstFixed:[4002,6666,6667],udpDstMulticast:[5353],udpSrcBroadcastReply:[9999,20002,38899,56700,1900,1982]},I9=[...lm.udpDstFixed,...lm.udpDstMulticast],T9=lm.udpSrcBroadcastReply;var L0=require("node:crypto");function N0(t={}){if(process.env.BRIDGE_NODE_ID)return process.env.BRIDGE_NODE_ID;let e=t.configFile??Si,n=X(e);if(n)try{let r=JSON.parse(n);if(typeof r.nodeId=="string"&&r.nodeId.length>0)return r.nodeId}catch{}let o=(0,L0.randomUUID)();return dm({nodeId:o},{configFile:e}),o}function dm(t,e={}){let n=e.configFile??Si,o={},r=X(n);if(r)try{o=JSON.parse(r)}catch{o={}}for(let[i,s]of Object.entries(t))s===null?delete o[i]:s!==void 0&&(o[i]=s);return pe(n,JSON.stringify(o,null,2)+`
12
+ `,384),o}var nl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAD9CAYAAABTCakVAAA+DElEQVR42u1dd7wdVfFP6L0pTUoABZGqIB1CBAICQghpgCACIQgo6E8RUEKNoCDFghCUngoSVARBQoBEaSKELkoHAUFqSPLevbs7vz3cOb5z550yZ+/e93bvnj/m85LbdveU75nynZkBADAgSJAg1ZQwCEGCBAAIUlJZNJV1U9k2leGpHJbK91P5TSrTU7kjlRdTeT+Vhal0p1JHiZR/C+lK5YNUnk/lIfzuTalMTuWXqXwzlRGp7JHKZ1JZPIx/AIAgfSNLp7JbKl9L5XLcmC/ipq7hxu7Cvwvx32KDx7i5Y0US5W+i/D/WfE6CRE25Tg1fE//+MJV/Idj8NJWvprJXKiuGOQsAECSbLJ/KvqmcmcqMVN5UTmwpiWZDS4kMr9PvJBoQcL2u/k5kAA8JHP9J5XepTEhl71SWCHMbACBIb1kfT06htv9TObEj8ld3gseWUzxhfIcrLgDRaRQR0UKEVjI7lXNT2RO1mjD/AQAqJ+IkPCiVSam8ihukptjisWXzuTZjbPl+3hIzNAodeMnnXJDKozgOh6eySlgbAQA6VdZJ5RhUiRcqKr3tpE4YQBAZQCE2gELcwkZPmKaES/OINc8gAHA+mjzjUvlkWDMBAMosn0CPvPCeP6ac8DFRjxOGeh47bHGfU7mV0z7JYErEjN+i5o50OArt4LJUxiCAhnUVAKDQMjCVoRg2W6g5nblqeZzRNk+Ym1+8Dxk3fxatwgVgNr+F6vi8FSMMi4S1FgCgSCLi8Gen8pISMos04TfI4cT0OZld1wNozfbPw88QM8yMmDgTX0nlrFTWCmsvAEB/EnBGp3IXcd6Z4ul5ONVsm76dTr/Y42TP8l2T38IU6pTgKrSs36YyBLWvsC4DAPSJmj8OvfcR8XKbNnTUYijO9p3IQejhnN6tOgFjyO4ETCwbPbGAKvWlCDLSiaksFdZoAIB2yOLoxX9GUfFdaisNg0EG1TpxgEfEDAXqfg8yqvxxBhMlZpgtNm6DbWwjJarybCpHBZpyAIC8ZMlUvqfE613U2azEGd1nIaeTOWaYDe0yEbjhQpcJYHIWRobXXsGciEA2CgCQmazzbdz4NQ0FN3FQbaknuxWnWWRQ9yWpJnFsklY2MUcLyeIHcAFXFqG/LcbmjVROChpBAACurJTKaam8rsmaa3WxZnUAxuDnjc8rxOgr0AIPgKMB+DgQqcPwDeRkfDqs8QAAOhHOo9MxbTYyeJ5jhvoaW2xV7gkaA98J6Lpeqw5An1i+Dgg4Dj+OEzDxAFnbs3dh1uLKYc0HAJByOKbWdms2D01q4XiubTx4zsbgpuq6Tr88Tn3XaZvVqcl9Bs64+mhXkpH5VionYDg3AEBFZQdoFL6IDIvK5M3P4gRsxRa3/XakkTqJVNQNn7P9hqo+14k5FFl+z9dM4ZgAEUPb0WlsLjMrRuD/cgCAasmKmHpbJ4s9Ypw4rhPMFqvmbmrXe+rG7Fb486JuwKxUrk/lJ6kcm8pIaBQS+RzmJ7hotAPRASpqEmwAjeo/e+LviPDa+Uh1vg3t6roCOImn6dKKBpB4Oj1ddOObUxkUAKDzZTcMEdUZarqNzBNnVNu54TAdgIh/z0vl9lSuwQ05GDdrf3m5F0tlM0zY+TU0yoh9BM3VhGynNjf27wMeiQVUIsP91PC+T4GKFS6pEoPvuxY731VIw+VY82X6xZpQX0ROd7Eo70vlEmjUD/hsicZ7TWjUKDwbk3i68HlisFc1ckUKErKJI+BXPeJEWsQ9/qVKeQZVeEixcf4KPXXyIsbm57zPobuakoHod2tKost1qRzaYTnxK6AZIUJxTxv8LlwWYpYcBI45kijzIMqZfS0AQPkTds6ARuWZmkEd5XjZIyb1l2NzUqebSGj5YypHp7JxhVRPWSDlD4p2QB2QrRCBXCaAaa7qxJEqCrisEQCgfCKKaj5l8G5zNr6PeeBagJSv/g90pu0KoVCmrHi8OzounyYRh9ihsXFCnjFT09CZF0LeSWU8+loCAJSAu389OVHqHqE+HycgJ1NNXltQin+cyoZhwztlA2RjPkfGkGuy2cwzFylLt0YkIL2cyk4BAIory6AXmtbbizRkHl+GmcleNYGKDNFNwzBayFfP5rj9MppI3QbzIAIeNyO2mHEmDUAnwlw5IABA8UR0qnmCbH4TAEQWGz9h2I6xIzVVLJILUvlU2MS5agW/UYDAh2XJIRu5AF2+JxuwfCMAQHFkWCrvWSiiNB6dWMJKJvtdx56jav6b6HQM5a3b20PhYujpiOTiGiSO9OHEcVjQ79cV3sBVnUAlLvuC+D64y3HFnj6A2JEMpP5fLATRS+94NEHCJu0bEXF60XHoXYVfkEUL8DUB6PsPlJ0zUOZ8/SmWEyCxoLor2YdjAsgyVMciGy5syv6RldFD/4EjIsAtaRaBu0IxPQBEPsF2AQD6tub+3YwMMWoCRB48APqeSh1+E0/8UJ66OLIqpvl2KTF8myPQpgFETE0yIX6fkQEA2i9DEXE5seHYQubh5pOrAPAqhqdCLnlxRYRZL0WfkIub0YoJoAOVbrz2CgEA2iMjNCG+VjSAyJEgIr/3dionB9JO6UyDCw18EB8nIEcDoKFfUZh09QAA+YpgzX0I7vp6WZ2AOi+/mNArUlktbKjSyuaYB1LXRIISh53v0iRt0aTZSEoLAJCD7I9psN2GSeSq/xFzUsW/56aybdhAHSNHo+8mYmYeRox1lIC9TPkdZTAHij5xI3Hj22ywLCZAonlfOo9+FjZMR4rQ5GYqZkFiiAL4agCRhWMwu+ggUPTNXwNe+a3YAQARAwBEnbhRYaN0tCyGiVj1DExAV2k4U9n2hzFyFQDAU+3v1iBs5AkAsQMA5OafUibHTZCW5YsKdZzjK0rA3NbdlYMgrvFoUddXUTf/QgcyJx5RAN3ESjrnf8savw2SSyn4X5FsQ1u5MhNARMCrTfA48hUCAFhEZH99pJz+Ols/yagB1Mlr9yO3PGyGasvB6GSOHGHAyOKDShwORskanFs0HknRQn0fgbmKblYNQJ1UMQmi3NO3ApMviCIic/Nq6F2ZyIcH4GIZSiez4AmsGQCgWdbDjRkxHX1ZnIBiAp6BChV8DOIteyssQheblOME1OWciHV4b1EOoKKg7/OErBF58rhtoRuJvKIU1zolXZiiQOghqexVwHsbginZnVL0ZDeFdFZ3rEFuiTLqjBa/e20AAIBlU3nMwcpztehKQF8ySr4m/Al3lThPX9iMLysL54KC2c9yXm7tsCjBq5owtIkHwKkPqStMc2HVAeBmaG5jZVKnIk8noKr6i042ZWkPPQb9E2oX2xPI4pmnUR/bnZIs4tjfSWUcgrZ8/XZlzAXQbqa8JzSWK6HRe7GMILA2moy+TEAuAMQY7Tq8qgDwc4fqngC/SaeumqtYkD8u0YI7X0koeU+JG19Dnq1biV6ISrVzFOfSlm26t/vxGjVkt8nX34XmphpfwdePUUyvGmZxlhEEhNY4yxEh8AWAmDgGBQjsWTUAOMJCqOC24jY1i5De/mNKtNAGIhNRJScdgu9N1jyb3OjHQ3MT0NltuLdBmhCq9KXMh+bOuwcomoFaY//0kvMFfmehk+sqSbkAgB5eIuN0g6oAwM5KYg+3BTU3DCg3yEElW2QraUJQ4/G9SeT5xNhtje9NI4tyfhvMgcGElyGutx/RAOS97Y6v/5OcmD8hv1m2EKyo/XdVRhMgYSQYibl/qj/yBvp6IHdA9p0LKTmluyjdUvx9HQGmDE6mbRXP+Wc0DqLx+P55mqjGevi9O8l4LVDCnOK7h0GjbiK3H4HognMuOhpH4Gs7aZxhwxTTQNUApO/iBaLN/ERRqX+HgPIMrocyaWmnQqP6T8JMBuIUplFBYHZfE4X6cgAHKWpuzNj8piytxAAOwpbasQQLaSpOttgE1yljQxeH1AC2VgCujhx2+VtzSOh0gaJKTsBrCPkAeHUNHlFU3W6kZUuNTTU1hivMTfnedcrvPEFMgFPx9ZOIpnNPCU2C77WgAego6THxl9zZlyHVvszC+hu4mzP4OgHl4ImFv29JPMsRcVSKjbmcspEkH+I4ooYLFfQK5fQfgKE31ZQS47AivvcOMYuOYPAxIqJpTMLrdUFzy64toLlC7xCyaK/E55GLem98/SriT/hvSf0C1xjCepwu05HhNTUl/cxOA4ATLCc4tye8CRy6lROp6LIX0WhquLnFe38hC2Ebxu9dRjSAV5X3FhL1fLzjtzbSgOvviabRjeq9y4bfAL8jNL6J0FM//3qyDt4rKQAsgv4XUyKRSwPQ5bhQzWDLTgGAldA2j0j6JZdNZSvqGJXM4bc/meganp6yoKVQwd9P5RLm722KJ70Ek2OVBTqfhJvOdfzWJhqQvlmx3Segb2A9T7tZ/f+15BpvlDg6IMZ4BsMH4HICmnwDd3YKAFznoPJyQoG65h3dGAYr06IZrgGAXXMg6QxDx6L6ek0BSfHvcxy/s5lmzG/J+fnPg+b2XnM6IKV4jobMxuEB2DJW5XePKDsAjAG/fu4ub6qKmD8q4YL5EvSuUrtem67VRez5sxnaBNWy/tiG6If0DdQZoFSWUmPPgr1DkU3Vt7EM32l3/ko7B2YtJeRnqsHmovOasqmuL+liWRo98vJZ/t7Ga3WTsZvA1ADaCQDyOqcgBbZTuiqtm8prFie3LlyYMGjGAlRuKysA3Gng87uce7Z6AGLzz4RyN2UUYb0HU3kolc+38To1spBcGsDmmgV4R0gRZstWmKdhWuOcdOJIE/4Wa/6osgHAGZpUSo7t79IAZqFTMSw4PgBIJ+AEBgBQs+tPYRy9U6PfAX7FYZcJIF8TWuP2ZQGAHZRQlqnvmg0IdBqA+K0XMfmligtrdXR4HknUZuGd/y2mC4u2VMtoTACuE3BzzYINGoC/DAV9NeuICQIm7eAlkolZSABYAimeNjXeRQDSaQACAEZXYPGIbLqRhLUnNv/zCknkUuU9lVlXQ16AzgnIMQE20SzO28OGzpzpWnfQ2WNNlqGt7ZiYw4uKDgBngbkza9ayXmJQpldg0ZyrUIRfg55a8t8mlFGhDsr6BjeTBfU2AQCVLenSAHRRgAAA2Ss4/VuTRanrQmV6j/q+pD9g66ICwHqEfRYznYA2TrV44H9VQPUXav1HyjPXMYQq2XPq+HRh0o54by5570OFpbeAUIHPYnjn6YK8K2zmzLIHyXuIHMlAJicgPRDvLyoA3AT6cl6JJ82Xqj7bV2CxbESyGsUY/hB66gHQfgYb4XtPk037rsK+W0CYgGcxNACqgs4MG7klOUc5vaMMPADTnhhbNAD4Apg78CSOTL/EMhgndejC2IVkLm6nbG41HZgCgGRAfg7fm01MrhctuQAuH8CWGhMgOAFbTyGeA/py4z4mAN0vL0NOZe7yetCrHCm7nI6sMckhv69DF8X1iq1/uhJDrpNxOA3fu5SMjTABZOGIX5DFdZNynQWeTMAtNCGoAACty/qE/MVpX+dyjou/hxYFADYhpw2nMIKLL/0SlLeEt002JJmA7yOSr6ikzsr3xykbc4FCn51E8gAuRFv9JjJmCwiZ5BwmAAQnYP4yTJk/Uz0AW99BnVn9FORQWSmPh/sruJtwJgbtQEeJFCfjzh26EA7QTOyqRJ2XabeDCNX05FS+6sGCnE+YgC4i0KYaDeDOsHlzkx+BuQK2jxNQfe//+hsAdteEOmIL3TF2RALqmD/eqYvgMM14yY0uCnL8EhoVg4blcK0FxAdwDkOTo/ZpMAHy5cg8RXw2Lh6AK9X4DUL+6nMAeJC50W0AoLIERfx75Q5eBMcQAKiTkz5PWUCYgC4fwGZ9mAswsKIgsCM0l1eLDAxYsDgBgRyY3+8vANg9Q0afyUEo7dRvdvgCOA56NyttFwDMJ0BzFkMDoDbon9vAd5iEPqOnlHBmleQqgy+A4wTURc7+Cy10vWrlQWYT50SU0QSQn3mmApN/HNEABACs3eJvrogU4nUtJgAnCvA5DUst72Sgo0mo84YKAsAncNNGYK4IZCPK6ajFZ/Q1AOxKsv04JkBkAQC1nFUny+EapmMrDSE2RvpvhCzAbTUAwE0G2lQzZ2q/v3UUenJWmUJA5uGKmgIXMjSAxLJf6PtvZfUFZH2AWzXJDhGD7GP69zvQU822k+Vg6N0ldg3l/UGYTbYU8/cuJuzBqcp7H3maABtrnIC3KHkKXWi/XsG8t8Whdyny28g1nqwoAKwHzaXRspgA9HA9pa8AYEdiw5jKdrmcgOrnD6/IxO9P1D5hCy+tqMeyjr9IJFkLehdXpbbe3WS8n7f4AFwawLoayul0dMp2EdByNfQQ/oQX8FnmQk8vwxtJmvgDFY4KjCdJPnXgtR9PDAfrW1kc6Flu/B7gNem0OQFVraFKsealka8v4/0PKe+9Rk7zccp7VyosQLVQ5FwCpO8RDcAnCrAYLiLVQXk+9NR3UOf3cOV5LsasRLUB6NWgbwxygRILT9AkqDJN+HFCEOIyAU0AcXa7AWAT6F3swMcJqIv7f75iEy9i/K8gb3+ospFq5HQcr/hbasp4CXNpSXzvMbI531Ku8yEhAp3FuDeRgTgPf1MkGq0JjUKmdM5PhOYqvzW8L1mt6WGyqC+EnjqRTynPsWOFAUDI3tDTJ9PGBOT20xAHwLLtBIDziRc78TABdOrNbRVfAFLW1rDEZJ7AEdC7pfSu0FMPQN2cswgA+KQDq1qKWql4Gw15RWonc4jJcADSU/9BDoWfayIOq4V5/1gLuE+TLMTlz+j22YntAoDF0eOctYOvTrYLi+BjWVnRAGgy0MmabMC9lbBit7LJVR7Fm8qCqilqeJZIA2UvSqbic+T1w/D1R4nP4MIwx0bZTfGxxBlNAPW1J9oFAEdCc62/xFMDoNGCe8LkN50E/yGq4LeUnHKaK7G38j3hoZ+hcfLNVuar3oKjdRGMW0uAWqhEbF4kGoC8xlToKWMl/n4nzLFV7mM4AROHE1A194a0AwDuz3DKJ4bEhrrPTVZELlI2q9jkstX2DzQawO6M3xuCm7WG0YFWKNZ7obovnFaHKK8/S7QM+d4ueO1uNEU2CPPrTBJTfQGmZCCVCpwYXo98nKvcG/y0JlRhcgK6CAwRqohh4nvb3mchVXYf5fV9yfgKJx23RJqoM/A1aF8p9RkkpfWLJLdAtEJbPcwtSx6F5u5CcUYNQIaXV8oTAM4Ce+8+lwmQkBNsbIkn6gvovBQ02QP7yDy4UQHgiwo0Ftsh41Dc1+Q2/P46mCEpOhR9vcMBYCz0VHLmOgFtPTa+mRcACBvwZQYycSoCxag2lrUl1Epoq6v2+MF9dO3PIvgUkdu+A+RQnILIIEx3VYkywzsYABZFB14E7ma5CQMYnsgLAHYAfaMDHx+A+tq4kttqNZLMc2NQX9siY6B3Qc3LOvyZDyVcEO6e0gGA0Ca2zgMATgFzDbPEkgtAMwUl+WPZEk/QCPJcdaTjhg2bvxyhWU+/6vBnXhKZopwQIMfXdlIeAHArmIsZcpmAEgB+VvIJGqlJ550VNmtb5EhNyuxlFXjun4C5VZ6LB+Dd25Fjl3yUgZesK23UjV7pASXXAGhFnwAA7ZGjKqgBSOJVxMytSRwawPvgqL7kupk9wK9CiekzUYekfo7SmDYBANqnAdTJZri0Is/+gMehq9v8oIzZkFYA4CImP9lVFFRM5A87BAAoLTa0z2qfD6BOAPdXFXn24zScG1voz/S60+x23cgLLfL91RvZsAMmZqTGCRg0gPbFxWmzlKoAwKqGyBt386vyelYA2JLw/mNH+CEGc0+AhzpkYlQnYOIwAb6AefGisu5Ehdob8h4a9v0MdDCfaLBTx2ocYJdVaJxuA7+CIDYtYHAWADgH3HX/OBqAmMAzO2RSdGFAXQNNWlxDfO4lJY+/ynIqGRfhHB4P+gKiND/+8gqN07csuQDgoQHUbcBpu4F7wa88UWwIF9aZyStlcgK6fABfhObqt3KxbxUA4OMWZlSbnKT53DhNNKlKAPAFhh/AlCREowH/8gWAJZUcZY6X38YDEL+zRIeaACYNYHeF1x0rqbE7BwD4mNdP28VNtmgA6hqbWDFT6S0LvT5magEy/2ZjHwDYHfzKftsAopOYcqM02s1s0Jd6opxu8dkdAwA0AYA8OK51AEBcQR+AkCtIhqAPE5ACwPE+AHAS9FSa4fgATMlAQr7bQRMymkkF3kfjwQ4A0JBbNABwjcUJGFcwDKjWj6xlTAaiXbem+wDAjdC77r9L9TD1Pd+iwzQA2j3nboMGQMM44v87BQD4GADomrmOaQJUTQNYSmOK+4o8fN70AYCXDASgxJGeSCfsvZIMtEhl3QtlMYYJoA6srrTZVzTqa/AB9JgA1LdkAgBKBJroSKTZ3xbyKqncZ9hv3ChAoozj2hwAWMGgdnDSE6nde1MJBlhU4rkfkbbuYPaN1vAAdBrAfmhCqaBYd2gAh0Ojlt6vkYNRtoX6DaSwigV7gocPwAQAR5GxtmkAq6CnW9YNmNFBADCBaJO+IKBGoQ7hAMC+wOvuYwtLyIV/dAkG+Dzo3ZxhFwcTMHZoAF/WUIbFNXY1/O4l0NxIQ4DRtiVapIeQcRHP+gMHwcXlBByr0aImMijrcl727BAA2I5hjrtMADk2V3EA4FTI3qmUOr3WLMEAT9EknRzISAaS6HqvwwmodtoxqacLNOBZptyJszWnzhyPKMA1Fg2AwwScqll/B3aQFvBWCxqAugb/yQGASRang0868GslGVwfABjZghOwbtEsapoJG++4b9FYYwyaG4u2aWw+hb+/vuNzP9Zkoj1oAQC6ZlwagIsINF2zNjupfNh0jRbgwwNQNbMlXQDwACP/WOeUiMhpV5a+b1M16rpLA1A/e49BA4g8AYBqWKdZ7llsSLWPwKPou8lzXA6CRnVZaVfbinJeonE6/Q3sBWa4PICIYQJMJwBe7zAN4FiDGcBtH15X+AC72gBgIE461wGoYwJKAPh2SQZ3GlE1bQDAdQLuS5yAclHu7NAA1HG1aQDXE62lDvbGkKIn3y/xXoW6vZFjTARz80Ny7/PA3M7rIs3C+3uLADBW4wS8nGECyHnpJA1gGzA35YmZp7/cl0fZAGAdcPf+c5kAkvY6tEQAwLUfR2mcTXcZTIC6JmS4s0MD4ALA3Zr7mGIJcT4Dzf3n3nWo9dtr7qeG5oDu8xdr1sLDHkQgUxSAywScrtG2OkkDWBQdw75EoFgTiZpoA4D9wF7Xn5MOLJFmqQ7UAKgT0AQA+3oyAWsam85mAswm6nEdn0P32d1AX7D1R5bf30UzvzXo6Qno0gAiSwr4Hzw0AHrPJgC4QfPZTish/pAm8ScmvpfEwc+powZmBICxFu4xBwDkxV4p0cBOzWACqAv9LgMRqJuMifjeDjmZAH8hExvhc5hSmBOiItd1ISFFdjZoAMM9TIC/WQCA4wQ8yoMJWAUAuI5hArhC80LetgHAZR5xfhPS1EpGxNDZjzYAoKf6TEsyELW/BudkAszR3IdJAzhYo0rrWnar8iUDk3E40wlo0wCy+ABcNQFv7HAn4ABM5vF1AtIeg7I47+ImALgZeH3KbeBQw7BQGTUA1+kxRqMBzPTgAZiYgN2eGsBs6F10ZaoDtGgSkw0ABmvmW9zjATmYALd6EoHU+760whrAUA8noK3NeITkIi0APMtwLrhMALFQvlqQQVuVEcOeolk8HB6AywlY0zgBTUzAumZcuQDg0gBGGyI2tgq7O3maABdrAOCRFpmAPk7AGzXz4gIAQVL7LOTf0qxdsrwhRd+nX6Ccx1EmAOhibPCEYQLs1s+DtRguKqkOPoShMJsJEDFCSCM1TMBZDB6AvI/BDCJQwnAC3qsBgKmWe6YORpcGsC3o+87bACBmAsCfNCbANcwwYB4+ALHhr1aiIg+VhLE6AEOztuo/nFCgGNNv6QBgCeA3IlAFNAizXD8P1ClK3LSGWslMDwCwaQCUB2CKAujSgXexaAAU0cd7AEBk0QD2NSwEWxRgK8PJwTUBYgcRiK4lbj0AEwD81oMHcJSS+CVrEv6pJABwb4tMwIRGU6hKFEG25p+0N/nAfh6oyeS0qyGRxUYFVjfHCKYTMAJ7RSBqAgx2AEDCNAFmaSZ1uuGzK6DnV130kUNL28oQBrRFAWImANzG1AB8OgPdqDnlhltIVFRbmV8SU2BGC7kA6rqdqgOAnYjjygUAprTDZwrC76eLbH4OVODRmpNmtsEEqJGxtGkA3ZrxtZkAMzUm2VTL5wW/4w1l87sKa2wIvQtS2ohAOicgVwOIUCXnhAE5AODyAUzRzGGTZ7zAclUOPoAI8zF6AcB+BAC4KgWd+FsL4tmnzRUXeJgAIxhEoNgjGShyAEDNEwCmkPTlGrjbZi2GKbIbM8ZvWQRM9RpCg9jE8PkLPUwAbk1AHxPgRrImbQAwSWPGdUE5SrYfn4MJIP4+rgOA0WBu7WVr/kk1gKkF0wCkSugCAG4ykDo2NU8egIkK3OUJAOvjid6N8lwq6+Y8hkfib8taCTaT5EKNymkDgDrwawJy0oFv0PAAhjPMQ7VoZhmYq6OZxB+XCfCeDgDGgr4rqU9Z8DoUo3TzFA1gfZQDD2A09O4O/GeDCdCtSZAyUYEXegKADHHuhlpFu04vETn5MiN56KceGsAt5PTl+AA46cARUwOYrNEAukuiAQz11ABMZntNBwAToHdJL18egPj+D9o4ACJZaQjGRNuhASQeGoAEgHvBXlWJ4wTs0gDq6SUiqZwPvYtQ2jQAGko1pQPTMOBESxQgJvM9wmEeqvfb5dAAVsO5W7qfx3mDHHwAcoyWoABwuUMDcAGAHPjD2/TwslR5HVWYYY4oANcJOK1FJ+C9BqebLhloV4cGkDCZgEWTczycgH/UHDRcE+ByBwBwIjnTNQBkMgFEFt4VCBDi1BSVefqzy9WyjJwczn6NZWq3+uPXGOx+Xw1gRJtO/nnQXKz0fTAXwZhMwMwVBeDyAEZrGGezGNmArpqAdxFzQXxnXIkA4GCNTT2J6QT0SQa6nOkEtM3hVEMUYBmwFyaVc/hkP47zIsw96soXEP/fggLAlBZNAKkBDGvDgx9A7HRpx+zgmGSOCeBTD4A6YeoWJqCOSDPYkn//usJZEG3ZVykRAAxER+B8hV03yOID4PIAqBZlqwhEta0RlvmmG6gbT1cdZ4Dea1c/j3U3+FcE0jkOd6QAMJVB9EkcpkEdnUbtaMhRI6pbt+VEzcID8NEAXOnA+2pi+7aSYEJWxOseWABbs5XCFa57b0UDmGiJAnA1gGmaOawbNIBJGodldz+P8QcZiEC6zw2lADCNucldJsBObQYAVQPYmekEtPEAfJKBuJ2B9tE4sEJjkNYrArlMAI4pOkXDBOw20NenaBy5/Q0A72RIB9Z95isUAKaDu/S3ywQQ8vkM6uNyDvowDb+5TIApmgWxgMEEzKIBzHJEAaIAAL0AgFKfr2MkA0UWALhBsz5tGoCOB7CchTMQk3z6AQ5NbrM2UotfBf/WYDrezjAOAGQJA27u8TBnQKO6rbCrXsSNY9p4NY39vTMDACIlRyFPAIgtJsA+4FcWvGqtweg6u57JBJyYoxOQAsDyDtIQBwAuwoNGzP2/MXks7/F7oUUmoBEAbmD6AChAALGltvJkNdEkjk+DvhBHpCF77MSYZI4GQNV6k/o4RrOpTZ2BdBzsIQEAtE7ASeCuCMSNAriKgk7TcC5qeHLbOAMuJ+AI4ktK8NDJ25n7HGSvCKTu42G+PgCXdiA38DbMB7laY+N1YbxfV6NeFwXgAkDskQtgaypxkOZ3ZzFyAeTiGRwAAH6vWUuTGCaAiwocM/040zQaQN2gAeh8SSYN4DLNGu1qQ1TseQYdmOMEPMAUBWjFBKh72Lk3GUJll1hMAAoAO+bABJyiASJuOrApDLgn6MuC7xoA4H/jrcpkCxMwYWgA0z2IQFM1fpyaAQB0mmQN7L0aYhKpOjjn8Xvd8/Q3gcRwHQ+AowEkDgDYg/kgNxgAYALYC3FwnYBZwoAcJiD1Q+hMgD0MTMDgA2g0jKlBcw8J3ZyP0zgLObkAHA1AFwVYlmkCdDM02kTRAA7KefzmGTY5eJKBepkA13smGJhMgH2YD3Ia6CvP7sPkAbh8ADRzcT4jtTZLWXCdBrAb0Vjk2GwXAOBj77ikX3fh+C1vAAC6oSbmZALU2wAAJ2vutx1zvjAHHkCMdPUBlPQQQWtFQesens9PYkhDppwKmW0IB442+AB2ZEYBuCaACwDGaNR6HQBsQRJ85En3qQAA/5NlHBl4R3jwAKZD76rHIxiHgysKoAMAkwmwBuYKdClr7u9tGLeoxWQg+Z39TclACZgrAuk0ABoFOMLjYcSGuAAaNdl+asnIGmmwqbdnePa5UQCuCUC1kJkGbsMsaK5LeGfY9F5yhEcuwDTNfI9gmAuuXADdOrKFAbfC9HBRq+FSTNnOm2kZEXU/azLQXhQAxmfMBQCCkKe2YTEcmNEJGDN4AFM0UQCf1mAzLQQn8Tun4GJcImxqL9ExAV25AFwNIGKaADo+Sa0fx2QFzwiAzV+3AwWAozUDbutHbjIB2lEQZJjGqWYLA/pQgXW5ALbGIJzegEFal7Gak9pVEShh8ACma0hDXQYNYIom+7M/qcDbeHj+bfT9WPJtbPYtN55IqcCT2/Dg+0FzfbqYSQTi1ASc4hEFoJ2B6kG1bzsAcKIAPk7A6ZroQpdBA5isCSf3ZzbgMOCn7LtMgOUoAIwAfYca32SgdtRYXx9V+Drh1q8O7oIgeQIAlwcQpHXRaaRXMAHApyJQZAGA88i6qCERp7/GZIzG/s/iAxDjsxgFgD01PgCf/oByo7WrM/A06ClQKa5zJYNsEjN4AD5hwDGa3w0mQN+YANx0YJcTcJrGtKgZ0pjXhkZPhUhR/8/vxzH5bsZMQLpn/3cY0lM2An6RAdN7C9v08CJkdCii8n6ObCtfJ6CPBsCpBxCkbwFgukcykKkvgKmOwSCMVF2HDu7+rB48sUUAkK+9AobWYHXw7wwE5H3xGysVhG7KSeLwKQo6RqM+3h02a9sBgEsFTpgaQKLxASxTgjH5rWbP+VKBxb/n6ABAsow4BUFtSNNdAM67zgToytEECBpA34YBXclA04Ff1m26IR24DFWYHgG/1mCmCMANJgB4y4MDYGsPPrpAABA5wje+yUA0JTk4AdvrBEw8fACcsuCTNSDeVRIAWGjQun3SgZt6LNILzAR3D0BXFEAM/o/6eaCu0ywIrg+gzggDxo5cgCD5RgGytAc3zeEkDbDMR5ZdkcdjQ4vZzQkBqib6WBMATAJ98QAfDUBcYEY/D9ZoEi7stsTrJ0PvRpgcHkAcAKAwGsB0jc/HNIeHE1+XWB93lGA8DsF7baU3YEwT9uhFTrX4ALhhQCH/LMCAfTOVp6DREuxuDOnYNABOCOkg4FUECpKPE7AO/q3B5BzaktLOTuW/qBUKrXfNEozHhY7T3qYBUC7DeiYAGKXJu/dtD160dsuu4oyTPZyABwGvMUjWRI8NoBxtqvvKCUiB+TJHFIDT4VnN1Vi0ROPxO9B37eb661Qf3SImANgZmktZJRlNAHGRL5VkYCdncALmTQUWSU0v4m+Lv5sGAPBKBroBeteWPLDDxuNtpgZgqgosgfFx9XfpRZa2cAE4FYHUjKlvl2Rgp0Dv4h3DPaIAM3O4hzuU3+1GtA8mQG/vtY8JMLyDxmJt6F1uzLczkDycp9kAYACyhCLLho8NDgjaCnt6iQCA2x58lEYtbVUDGIheaBVA3woA4N0ZqJMBYCT0rjjs8gPo+niI75/pAoAbQV8QhGsCyO++UGIAaLU5qI8srUll7QoAAEdCa70BOwkALlDWSJZkoMjE0dFd7AwwVwTiOAHVSdikQwFAfeY/t3j9ZUlosY6RC7XUlKguIxpqTCgJZTXPikCc9uDTOlwDeNDhl+NsfgkA67sA4MsZIwFU1RByUgkG91porjXgqwG0CgDCI/s+iUu/Sby/dcW0OrtCGgA3HXgy9K4VMaJDxmEtaK5f4CsqCLxOf193wRURKSLPdOBYM2G3lGCAjyVpxuLv1h5RgD/ncA8zyeJV/QofQPvrLRTdBHBpAGcrn5Vz2ClNWA42OACz1AOYwQEAIY8ZAMCnVoCkWC5S8AEWhRFuU0DgdrAXZKiTKEAeLLKhCujWFBLLKtBcXbgoJKu+1gBcALByKnOhpwjrlA4ah6sMGjm3epe6dn7EBYBroXczTl8NQCLx0JIMtKgwPMRBDhmlMQHyKgkm8s5Fyactif1Pqcf/Jt8TrK5PViQd+ArHd/aAzuu/+HLG7Fxaq1PrGLWhb7eGi82hAlNv7EUdNBljCBrnpQGYZHVCzKojIUS+f7kSNfhuB4YBaZGPiRXRfqR8HnpXwzYBAFjelwCwBhcANlNUYm5z0NjAPX62gyZklCaR5NY2Xm8pNKNUDUCGVzdV5khGDpbtcB7ArysGACdrNPEsyUBifTypu4bt4m84NnrE0ACkGbB+hwGA6gRst1Pub2Q8b1eiNVQ72L5Dw4BSrqwYAMyxROS4yUAyN+dKXwC4Dnp3ZzWZAboIgLowj+yQCTlQYwL8sQ9OATVC8X9KYlIXiR7sQ6I5ok35SiUd60M0h0qVAGA5Ep3y5QHEJAPwq74AMEJjAviGAXuVICq5bKT4RiSyXtjmawqqsOjicgJuaDUzsUYmWvai3zWVDxVacRm7Em+AZk1d2QTjKgQAY8Ddq5PLAhQHxWq+ALAY9JQg4jQjiCw3LMoQL9khEyNO4HcwPi8KqKzQT/exLwKQCgBDDNlxvynpWB+AXvAuDO0NrBAAXGs5cMGTBjzHdB3XTdzqSAoyZQPS98RJ9fUOmpyBBViMn0YAkCfkQgWMniN+iqklH+9FoFq2/wAM93Io+C4QEPM/PisAjNN4Ym25ALa+gneHBJfc5WdKGHCCwYEr5uUmTXQhtCovrgwmJjUn689WEHT7rACwiiYji2P/67yRNTy1wgTnrwlsQF57icyLCgDfQ5NMvH5uGL9CyjUWp7pvMtAHNm2VczOPGzQAn5qBMhPpvDC5fSL3EvNrosI2VP0Gb4axKpwsAz31IWJwl+l32f/WuhycG7qUkQuQGLz/9Gb+U1F7rq/lh4pvoAudaQOQCloj6uGSYbwKJcdYTn+bBgAG+/+wVgFgFAk3ZfUByAU5Kkxy20UUFv0Oov9xJJuRhnY/EcarUDLXElL30QKk2b18qwAgMq3mtcgDUCMETwUtoE9kYwxZDiPkGlpbfvkwVoVK/Y2YoXWOCeCsV+mTkuhKB7bdbEz4818Pk91WGYp2ZA3Dg0fj6/soySVSRVw0jFehTv/Iklvj4wQUc3tiXgCwGzRXzeFUBIoN2oH4+3CY7LbKJGiuWSCjAMui40/O5ewwVoWRPaGn9gO3ApcLAD6fFwCIMMIzDHWE21YsIrTWIPnKX8lYP6C8tx00Cr8KUNgijFWhIjc1S8TNlwfwHw5ZzecGvwf6UmE+uQKqs/DvYdJblsOh0eLqTfQeqxWdVFAOY11s2QH3lq4ID8fW1732c861fW5yNWguT+XLA9A5Bw8Mk99SvHgBNFd8lQUf7iaOpPvCeBVa7lSyPWNwd+KmApqI21Z5A4CQaWCuTxYD32Mp33+yYgkeecp2ikNPLh5Z8ulqMifTwngVVnZScjoiDxPAZmo/xL2+783uAu4CBTYNgN64WMBHhkWQ2WmklouqYxhJvLcfJxc8SCHkHgLkiUMDAIcJIH7r2HYBgJBHwNw4xKYB6ByEEfLWlwgLwSrrY374UEVj2luJ6UsAGEnSlh/BhKEwhsWUL0FzxSOO6eyy/0UNheXaCQBfAXujQq7KolbV+U1YDEY5DGP5ddzwE5TFQ0uCBZ9KuXw4T0JzwZPIY/ProgDa0t95A8AAjB9HDAAA4NUSiLhOiwrK38kYvqAw/WqKml9DezKMWTnkXEKgiyz8GVfRD/l3gS+zsxX7s86wVxIGAMjTa3JYFFp5h5hX85T35igOpJeCQ7U0shaJ4OgAgKv+q38v9b2XVh7iAeD3DYjBXU5MLOTNK7ogVsVQkAiziirAanOQeWQMP1TeEwU/T0/lMmiUcg+bqzynf42wY1UAAM8woPyNDfsSAIZqAICTC2B7gEcqmij0C2XsaoQqPY+M00dtuP7KBkfsYhatQqdqirn7LH5PfX0J9B2FgjCNsm1vQ+8uWiYTgKtV35Xlflp9mPvBXhXIRVukGoPQAsZXcFE8Dc19FLqVDfkW0ZTyLOIxEDkCNQSascRDLerSvU+ci5+DRn9CcZ9PpLIuvr4i0sW78f1BynfU3ou7VxwALlXmOQJ7LU3ag8PEEhS/NaQ/AGAo6JuBuDoL27SABRXjqA8k6dbSK7wyvv8g5NuOXJXNCZFIBZe/KJtW7Uf4G3I/v8DXvwPNbcx/ha9vRKIVd1V4828O+toaPhqAzjy4P+s95ZXEkLV2mamRyGMVSlMdiLa/esrXlBP0UGUjdiEfIK9r765xxsp7+pBoJUvjezPIwr0RX/81mcM/4OvDCHnstYpu/kWQoVfPCACx5dDctz8BYCPlBOPkLbvajckFN70iC2NR6N0CvK6o1gPQdhabdZOcrz1cAwDC9FhSiS7I11fH79xOwOp3Bs3gLiVhST31XqkoAPxS0e5oYhwnCmAyD2a0cl952jV1B6PJJ1VYboKzK7I4Xofm/P3uPmJHDiNzsABPKhWUZGeZZfA7t5C5moSv/1yxVcXf32s0gKgVdbXEcjTZ5LpCOhwAoHtKzMvaRQCADUlYw5UIZNIMdEDwpQoskN+S039uH133i2T8/0Ick2oZN+oDkGB1krLI1Y1+Cb6+gaIBqK9Xicb9Lpib58YacABwVwQSr/201fvL80Evt4CAyzywlUB6DYkTnbxIPo200G5k+g3uw2tfj/P2GuEf7A+NsmLz8N/y9XVSeR6/82gqn8TXhdlwB55K/8TPye/8BF+/TdEkqmL33+845V1MQJMJIKIzqxQJAFbTxDc5TEDb5pef+6smttyp/oD+Wqim+1nU4Lg09URcPMT6/yc/JRtbpwXEBvPABQCX5XGPeT/w8WCvFxA7Yp2mwiHi9DgtLKggJZL9SJqvaY3rgAEcPgDxd9MiAsBADHV0Q+/y0xHwqgmZCBFCHd0uLKwgJRCpDccadd92+tcdB6eu1VuhAECGBRdokoWSFgEgwhDSemGBBSm4XMXwg8UGH4DLBJif5x5oZw57DXiVgjgxz0ghyLwCoZptkOLK98Fc+yJ2mAAmJ6D6/tfzvN92DsQllvCfbYBcnOgIU2S3DYstSMFkHPRuveZqnsOpCCTNgxvzvud2DsbSGC5yOTNMiBhbCBOys23QBIIUyenXhf4vXeTLtfltJoA89NYuEwAI2YowymKmBhA50FO+9gamn4YFGKS/k3zec8TxIwYI1EHfU7MGPe3dSgUAQr4N7tbhHA3ApD28jYy2sBCD9IcIwtPLYK+TaXIC0s2vW/d1pF8PKCsADEAijynn2UQDThxMQjXxRLRB2jksxiB9LJ9SWJEu/ktk0IRjR56AMHXXKDsAbA/NXWk5GYE+RKIaUiO3D4sySB/J6kh5jgwJb7Z1bfMB0EIfo9r5HH05YD9mcAPoJgdmiFCmWb6GPISwQIO0U1bGPIiageXH9QFEliiA+P817X6Wvi58cSvTDLDFQ3UIW4fmqjbBHAjSzpp+fzNsZlsdDB1QRBYQEIfZip0EALKQ5Ezg9RRIwC+XQFXDRCONMyuWeRak/fIJaJRit0WxXJV7I0YugPj3yL54pv4YxCUw7zzKsMltZZHogHZjHnsIEwbJQ8Q6eg7XlS0qlVh4ABwmoJDz++q5+tOB8iJxoHCZgNyehPK3RT77mLCAg7ToxH7Lks/P7Ydh0wCkH+vP0Iel8fu7UsrrmsgAxwSIGe9RbeDCkKseJIOMgEYvBlf/vsiS6+LKB5C/+xKaGQOqAAADMKf5bYcnNfF8T9eBWKKrSKNcNCzqIEz5ATSXObPV7YsYJoApDCiu8UEqX+jrZyzCIA9GhI0YA8nxD8QW1UsM9MMhVBjEIUtBo9ipTd3nagC05L0uCtDd7nh/kQFArZ7CVfNdGoAOeaUWUEPe9jFhoQfRiKg/OdfAzecAALfUnQoAp/bX8xZp4MdD79LitmQgk3NQBwB1g/p1N/oiwsIPIkRUMH6BYatnMQF0ICAOo6v685mLNPiCKHQ6YVdxw4CulOPIoiWI6kWiwGJoXFldEanrP0Q6ua02f5bOPabDSvz9OfRzM9wiTsYBSOTh9BzkAIAu08rkiLm8L9hXQQol22J8n9Ogg6MB2MKAasivEE1wizopX8GTOc5BA7BxrXXFRp6FajQjqbqIMvMTwNyl12YCmPxPkYOsJmVGUcahyBM0FHqKLHDIFtx6a5zPCQ3kT9BohR02S2cSe+ZC70adtlh+lDEKQOtaivThVQIA8EQU+ngVmpsq2qIAOiIRFwBMoCDadm0SNk1HyHKpXGGgoSceh0TCcBAmGoefSB9es0hjUoZJGwQ9RRe4LEGdE7DO2PA6VK9hnHZyKluHTVRaEfUjnzBs0sQDAEyefZd/SkQX1i7auJSp+MJjBhDg8gC4GkCiAY66AgTTQoJRqURU07kEzbpugyPPpS0mjChAZNE+hV9p3SKOT5kmchCiqAwTQkYASBzMwYQBMOL/d6YyGqrRs7CsefsiJXy+B5M0YpqFru/I367j5l+jqONUtkkVLZdmGxIyIgYAcE0GDtFImgf/hkb322AeFENWSuVkaNSJjMDelNYnYYejAdDfe7poNn/ZAWAAEifEBL/r2NytOgET5smgmgkinnxtKl9NZdWwGftUdkBW3UILmcxVjSryIJTZOAJiLfwMSlCQpswTvi76BepgL84Qe4RwXN2KuJEDCQiPILtxh/5mfHWorI4Ze0+DubtOYkkzp8I1JV1Vf88syxh2AoXzSk0OAaf1kuvU5+Qa2JyH1IEo0p5vSOWEVLYJgNASZXxPzNZbAD0VekyqvcnLb/osp/CMDgDkXF+A9xgAoA/la8jjrnvmAiQep3rM8AybuAi6BSYW7z0IYKLry46pLBs2uFE2xs31MhPUXZ2pYw8egO0wUMljR5ZtXDtpgXwObfA60wmYgB8ngFv7LfHQENSKRfIUEZGOqamcmMouFY8yfAY1prugp/kGx7HH0QZ8eACJgwr8Mmp1AwIA9H8u96MEBGzJQNySYhHwy5D5VjE2dYipKyeLKGJyMTTqJnRyRSPhwT8Qk7JeUCItHB+MT/FYjg9ABx6RZl39tchhvqoBgEzy+LFCGnJleOkonq5ipFz/QWKxJ23/d7VG/1WHkJFEjUbRw+F7qdzu8OX4OmRdoGvzAbiuLe/xirIDcqcnfDzLWFSRh7qeME56zoJ0tUezEVWkKrwA88nXKtm8bJnKWdAoDS9Ddl0e9jyHt5FYnHgJ+BfupMlAglx0RCfsk063IUUPgm+ijdZtcdhFDnU+8rDxk4ybn6MJJAaq8vUFz1wUlXbOTeUfDB9L4jm2HB9NwpwPVxhQrKFZJQTdygKAWuTxPIM96aIJc2nEHJUUGIuUu3CpSlpDzkHR4vSX4glv875zfDKJp83v0q5sYUIdENSQ8dlRPpiqeZX3hkaDh5oj8SPxIBH5nja+GkDsoK4mBARuKEDkQFxfFLr8yOF4izNEUbJoWLaKUqb+ffLf3eiQ3LET90RV2WNXQu+e7pwwITe2zP0eh6XmYxZIEJjaj0SjzUjaLdfpxjm1XQxNjhbF/ZwkcP0CGj0tBwQA6CzZKZUHLad74kEV5vIKXNmHPpsltgBAHR2EfT2mwjE2j3nqu56bqxlwtQsXCYjOt6AXD+70fRAYZgBfh0ZLphrY67f7OKpcC5xjsybAJ7iY7mnLPhzHy8GvkrPLCeijYXEiARyNrIYe/tOhIh2kAgD05BScodCJfW3NmOFsapWpFhuIKzat4vo+Gr9zPEAqcfAmuE6/GPxCrpzW3c+hZliZtR82f7N8MpVrNA7CCPw99D4e6sTzs9xwl3BgrdbmMTuOgGYWrSXJyQTg/Bb9TB1P/dPwIBgQACCI4ODfqziCIiYpxdeRlWXDcOxp9d/tDA2Oc2TXcYtwJMAjWvmy/mzAIQFe1G/4VFXXetjsdtkKvcCvOFhkPmQWjs3rS2CxObtealNE4PsOTz8H/GLwr8oTt6hhCfkvNAp2VL5JbNjk/CpEh0GjwIcpKy3x4J/7aAU+GoCpLt0eOY/H4dC7tHaSQVWPoTWCEDdFW4b13kZ+wlJhTQcAyCqH4qkaGTYBt7gEV2V2Za+5gKcG+Xaf3QidpVnYd1yeRZwRBExjVENVf92wfgMA5CEiRDQSGgU9uPUGs9r7ruo1rg1XR2JQXtV4Hm2Bfpt4mD6u77u0qzomGwkT7jNhzQYAaGelGrHI3iQU49iyYH3CfdwQo41W+1BOz3ommLvq2Oi1XM++Kwc/NoQ+I7LxRTepU1JZOazPAAB9qRWMgUa/gDo0NzExbXgAv4o1PixB9TPv5vB8m+KJWvfUZnzYeglkq9AkQfdxNNFCvcUAAP0qYrNcBI3a9HVDFqJPXJ9LojF9vrvFTSG+O9fg94jBP4Tpk/NvCt+p3ZpugUa1pIFh7QUAKFr0YN9UrlPAwFZgJGHYvKYCF7bqRWKjLNnCc4wHcy0+HyKUTzjTVLmpG5/nPiQhrRjWWQCAsoDBttBoanIbpsq6Ohv70INNmy5qEQDEPS8w8CCyMhU5QEHZmK8gS1PkbgwK6ykAQCcAwh5ISHkcmvsIZKHVxpYU4a4Wklse8WD4ZeFA2BqriHbal+A4BfU+AEBHi2gldjA02pC/aslD4PQeoADwfgs8f1s33bw0ALnpRcHTGakcn8rmYU0EAKiybIb59cJ/8Dz0rmJk4x9QHsCTGa7/Wczt5+Q6cJiA6v3IZ/kwlT+gj2FwOOUDAASxZyoeiKm3N6NTUTrEpDdcV75MbLgbMhB+HvTgHSSGTV5TqNOChvtHaPQ3ODiQcwIABGldRHXaYdBoLSYKcszCWD0lxpzt+bsna/IdODH7eegzEAAleheMhUYdxtApOQBAkD4UUQ59DQSHH6aynafpMR9P7oVIIpqLtGehSVwNjeq4AnQOSmV//M7iYdwDAAQpv6yGSTOLhbEIABAkSJAOlv8HOib1/JuFBpoAAAAASUVORK5CYII=";var U0="linear-gradient(135deg,#3aa0ff 0%,#6a6ff6 52%,#8a4ff0 100%)",CM=[58,160,255],M0=[106,111,246],RM=[138,79,240];function AM(t){let[e,n]=t<=.5?[CM,M0]:[M0,RM],o=t<=.5?t/.5:(t-.5)/.5,r=(i,s)=>Math.round(i+(s-i)*o);return`rgb(${r(e[0],n[0])},${r(e[1],n[1])},${r(e[2],n[2])})`}var PM=Array.from({length:65},(t,e)=>{let n=e/64,o=Math.exp(-(((n-.5)/.16)**2)),r=Math.round((3+o*(.8+.2*Math.abs(Math.sin(e*1.9)))*153)*10)/10,i=(1.5+e%5*.2).toFixed(1),s=(Math.abs(n-.5)*.7).toFixed(2);return`<span style="height:${r}px;background:${AM(n)};opacity:${r<6?.92:1};animation:wave ${i}s ease-in-out ${s}s infinite"></span>`}).join("");var F0=`-webkit-mask:url("${nl}") center/contain no-repeat;mask:url("${nl}") center/contain no-repeat`,OM="https://ac-bridge.com",lq=`*{box-sizing:border-box}
13
+ :root{--ac-bg:#07070f;--ac-surface-2:rgba(255,255,255,.03);--ac-border:rgba(148,132,255,.16);--ac-hairline:rgba(255,255,255,.06);--ac-text:#e9e8f4;--ac-dim:#9b9ab3;--ac-mute:#80809d;--ac-accent:#38bdf8;--ac-accent-soft:#7dd3fc;--ac-accent-3:#34d399;--ac-input:rgba(148,132,255,.16);--ac-brand-grad:${U0};--ac-brand-grad-text:linear-gradient(92deg,#67e8f9,#38bdf8 40%,#a78bfa 75%,#c084fc)}
14
+ html{background:var(--ac-bg)}
15
+ body{margin:0;min-height:100vh;background:var(--ac-bg);color:var(--ac-text);font-family:'Sora',ui-sans-serif,system-ui,sans-serif;-webkit-font-smoothing:antialiased}
16
+ .mono{font-family:'Space Mono',ui-monospace,'SFMono-Regular',monospace}
17
+ .page{display:flex;min-height:100vh;flex-direction:column}
18
+ .split{flex:1}
19
+ @media(min-width:1024px){.split{display:grid;grid-template-columns:1fr 1fr}}
20
+
21
+ /* \u2500\u2500 AuthAside: the left brand panel \u2500\u2500 */
22
+ .aside{position:relative;display:flex;flex-direction:column;overflow:hidden;background:linear-gradient(160deg,rgba(56,189,248,.08),rgba(139,92,246,.12));padding:32px 32px 48px}
23
+ @media(min-width:1024px){.aside{min-height:100vh;padding:40px 56px 48px}}
24
+ .mesh{pointer-events:none;position:absolute;inset:0;overflow:hidden}
25
+ .mesh .dots{position:absolute;inset:0;background-image:radial-gradient(rgba(255,255,255,.045) 1px,transparent 1px);background-size:30px 30px;-webkit-mask-image:radial-gradient(ellipse 70% 100% at 20% 0%,#000,transparent);mask-image:radial-gradient(ellipse 70% 100% at 20% 0%,#000,transparent)}
26
+ .mesh .aur{position:absolute;top:-160px;width:640px;height:400px;animation:aur 14s ease-in-out infinite}
27
+ .mesh .aur.a{left:8%;background:radial-gradient(closest-side,rgba(56,189,248,.16),transparent)}
28
+ .mesh .aur.b{left:24%;background:radial-gradient(closest-side,rgba(139,92,246,.18),transparent);animation-delay:-7s}
29
+ .lockup{position:relative;display:inline-flex;width:fit-content;align-items:center;gap:10px;color:var(--ac-text);text-decoration:none}
30
+ .lockup .mk{display:block;flex-shrink:0;width:30px;height:30px;background:var(--ac-brand-grad);${F0}}
31
+ .lockup .wm{font-weight:700;font-size:15px;letter-spacing:-.01em;line-height:1}
32
+ .mid{position:relative;display:flex;flex:1;flex-direction:column;justify-content:center;padding:40px 0}
33
+
34
+ /* VoiceBadge \u2014 640x200, 65 bars, orb hole punched by a mask (numbers are the component's verbatim) */
35
+ .badge{position:relative;margin:0 auto 36px;width:100%;max-width:640px;height:200px}
36
+ .bars{position:absolute;inset:0;display:flex;align-items:center;justify-content:space-between;padding:0 20px;-webkit-mask-image:radial-gradient(circle at 50% 50%,transparent 54px,#000 80px);mask-image:radial-gradient(circle at 50% 50%,transparent 54px,#000 80px)}
37
+ .bars span{width:4px;border-radius:4px;flex:0 0 auto;transform-origin:center}
38
+ .orb{position:absolute;left:50%;top:50%;display:flex;width:140px;height:140px;transform:translate(-50%,-50%);align-items:center;justify-content:center}
39
+ .orb .glow{position:absolute;width:154px;height:154px;border-radius:50%;background:radial-gradient(circle,rgba(34,197,94,0) 49px,rgba(34,197,94,.34) 55px,rgba(34,197,94,.12) 63px,rgba(34,197,94,0) 74px);filter:blur(2px);animation:glow 2.6s ease-in-out infinite}
40
+ .orb .mk{position:relative;width:106px;height:106px;background:var(--ac-brand-grad);${F0};filter:drop-shadow(0 6px 16px rgba(0,0,0,.55))}
41
+
42
+ .eyebrow{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.16em;color:var(--ac-accent-soft)}
43
+ .aside .eyebrow{margin-bottom:16px}
44
+ h1{margin:0;font-size:38px;font-weight:700;line-height:1.05;letter-spacing:-.02em;color:var(--ac-text)}
45
+ h1 .grad{background:var(--ac-brand-grad-text);-webkit-background-clip:text;background-clip:text;color:transparent}
46
+ .lede{margin:16px 0 0;max-width:440px;font-size:15px;line-height:1.625;color:var(--ac-dim)}
47
+ .livepill{margin-top:24px;display:inline-flex;width:fit-content;align-items:center;gap:10px;border-radius:999px;border:1px solid var(--ac-border);background:var(--ac-surface-2);padding:8px 14px;font-size:11px;color:var(--ac-dim)}
48
+ .livepill .dot{width:8px;height:8px;flex:0 0 auto;border-radius:50%;background:var(--ac-accent-3);animation:pulse 2s ease-in-out infinite}
49
+ .caps{margin-top:32px;font-size:11px;text-transform:uppercase;letter-spacing:.16em;color:var(--ac-mute)}
50
+
51
+ /* \u2500\u2500 The sign-in column \u2500\u2500 */
52
+ .right{position:relative;display:flex;min-height:100vh;flex-direction:column;padding:24px}
53
+ @media(min-width:640px){.right{padding:24px 40px}}
54
+ .topright{display:flex;justify-content:flex-end;font-size:13px;color:var(--ac-dim)}
55
+ .topright a,.newto a{font-weight:600;color:var(--ac-accent-soft);text-decoration:none}
56
+ .topright a:hover,.newto a:hover{color:var(--ac-accent)}
57
+ .center{display:flex;flex:1;align-items:center;justify-content:center;padding:32px 0}
58
+ .card{width:100%;max-width:420px}
59
+ h2{margin:12px 0 0;font-size:26px;font-weight:700;letter-spacing:-.02em;color:var(--ac-text)}
60
+ .sub{margin:6px 0 0;font-size:14px;color:var(--ac-dim)}
61
+ .ssos{margin-top:24px;display:flex;flex-direction:column;gap:10px}
62
+ a.sso{display:flex;width:100%;align-items:center;gap:12px;border-radius:28px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.04);padding:12px 16px;font-size:15px;font-weight:500;color:var(--ac-text);text-decoration:none;transition:background .15s,border-color .15s}
63
+ a.sso:hover{border-color:rgba(255,255,255,.24);background:rgba(255,255,255,.09)}
64
+ a.sso:focus-visible,.inp:focus-visible,.cta:focus-visible{outline:2px solid var(--ac-accent);outline-offset:2px}
65
+ a.sso .arw{margin-left:auto;flex:0 0 auto;color:var(--ac-mute)}
66
+ .rule{margin:20px 0;display:flex;align-items:center;gap:12px}
67
+ .rule .hair{height:1px;flex:1;background:var(--ac-hairline)}
68
+ .rule .rl{font-size:10.5px;text-transform:uppercase;letter-spacing:.16em;color:var(--ac-mute)}
69
+ form.email{display:flex;flex-direction:column;gap:12px}
70
+ form.email label{display:flex;flex-direction:column;gap:6px}
71
+ form.email .flt{font-size:10.5px;text-transform:uppercase;letter-spacing:.1em;color:var(--ac-mute)}
72
+ .inp{height:36px;width:100%;min-width:0;border-radius:12px;border:1px solid var(--ac-input);background:rgba(148,132,255,.05);padding:4px 12px;font-family:inherit;font-size:14px;color:var(--ac-text);outline:none;transition:border-color .15s,box-shadow .15s}
73
+ .inp::placeholder{color:var(--ac-mute)}
74
+ .inp:focus{border-color:var(--ac-accent);box-shadow:0 0 0 3px rgba(56,189,248,.5)}
75
+ .cta{height:48px;width:100%;border:0;border-radius:28px;background:linear-gradient(90deg,#38bdf8,#8b5cf6);color:#fff;font-family:inherit;font-size:15px;font-weight:500;cursor:pointer;box-shadow:0 10px 26px -8px rgba(88,80,236,.6);transition:transform .15s,filter .15s,box-shadow .15s}
76
+ .cta:hover{transform:translateY(-2px);filter:brightness(1.1);box-shadow:0 16px 34px -10px rgba(88,80,236,.7)}
77
+ .newto{margin:20px 0 0;text-align:center;font-size:13px;color:var(--ac-dim)}
78
+
79
+ /* \u2500\u2500 SiteFooter \u2500\u2500 */
80
+ .foot{border-top:1px solid var(--ac-hairline);padding:22px 20px 26px}
81
+ @media(min-width:640px){.foot{padding-left:32px;padding-right:32px}}
82
+ @media(min-width:1024px){.foot{padding-left:40px;padding-right:40px}}
83
+ .foot .inner{margin:0 auto;display:flex;max-width:1400px;flex-direction:column;gap:12px}
84
+ .foot .row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 18px}
85
+ .foot .lockup .mk{width:26px;height:26px}
86
+ .foot nav{display:flex;flex-wrap:wrap;align-items:center;gap:6px 20px;font-size:13px;color:var(--ac-mute)}
87
+ .foot nav a{color:inherit;text-decoration:none;transition:color .15s}
88
+ .foot nav a:hover{color:var(--ac-text)}
89
+ .foot .cr{font-size:11.5px;color:var(--ac-mute)}
90
+ .foot .disc{font-size:12.5px;color:var(--ac-mute)}
91
+
92
+ @keyframes wave{0%,100%{transform:scaleY(.82)}50%{transform:scaleY(1)}}
93
+ @keyframes glow{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.8;transform:scale(1.04)}}
94
+ @keyframes aur{0%,5%{opacity:0}12%,28%{opacity:1}38%,100%{opacity:0}}
95
+ @keyframes pulse{0%,100%{opacity:1;box-shadow:0 0 0 0 rgba(56,189,248,.6)}50%{opacity:.5;box-shadow:0 0 0 7px rgba(56,189,248,0)}}
96
+ @media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}`,uq=`<a class="lockup" href="${OM}/" data-testid="nav-brand" aria-label="AC Bridge home"><span class="mk"></span><span class="wm">AC Bridge</span></a>`;var Lt=G(require("node:path"),1);function rl(t={}){let e=X(t.file??Xc);if(!e)return null;try{let n=JSON.parse(e);return typeof n.sub!="string"||!n.sub?null:{sub:n.sub,...typeof n.email=="string"?{email:n.email}:{},updatedAt:typeof n.updatedAt=="number"?n.updatedAt:0}}catch{return null}}function B0(t,e={}){let n={sub:t.sub,...t.email?{email:t.email}:{},updatedAt:Date.now()};pe(e.file??Xc,`${JSON.stringify(n,null,2)}
97
+ `,384)}function UM(){let t=rl()?.sub;if(!t)return null;let e=ur(lr(t)),n=X(e.refreshFile),o=n?Ot(n):null;if(o)return o;let r=X(e.accessFile);return r?Ot(r):null}function pm(t={}){let e=t.readActiveUser??(()=>rl()),n=t.readCredentialSub??UM,o=t.log??(a=>console.warn(a)),r=e()?.sub??null,i=n();if(!r||!i)return null;if(r!==i)return o(`user-scope: active-user pointer sub (${r}) does not match the credential sub (${i}) \u2014 refusing to resolve a scope (stale-pointer guard)`),null;let s=lr(r);return{sub:r,segment:s,dir:Xf(s)}}function ol(t){let e=t.dir;return{dir:e,providerSecretFile(n,o){return Ws("provider",n),Ws("secret name",o),Lt.default.join(e,"providers",n,`${o}.json`)},providerAccountsFile(n){return Ws("provider",n),Lt.default.join(e,"providers",n,"accounts.json")},localConfigFile:Lt.default.join(e,"local-config.json"),localDiscoveredFile:Lt.default.join(e,"local-discovered.json"),entitlementFile:Lt.default.join(e,"entitlement.json"),revertSessionFile:Lt.default.join(e,"revert-session.json"),telemetrySpoolDir:Lt.default.join(e,"telemetry","spool"),userConfigFile:Lt.default.join(e,"config.json"),relayAccessFile:Lt.default.join(e,"relay-access-token"),relayRefreshFile:Lt.default.join(e,"relay-refresh-token"),hubTokenFile:Lt.default.join(e,"hub-token"),workspaceFile:Lt.default.join(e,"workspace.json")}}var dr=require("node:fs"),lt=G(require("node:path"),1);var FM="layout-version.json",z0=3,BM=["providers","local-config.json","local-discovered.json","entitlement.json","revert-session.json","telemetry"];function H0(t={}){let e=t.secretDir??Te,n=t.now??(()=>new Date),o=lt.default.join(e,FM);if(WM(o))return{archived:[],skipped:!0,credentialRelocated:null,credentialArchived:!1};let r=lt.default.join(e,`legacy-${GM(n())}`),i=!1,s=()=>(i||((0,dr.mkdirSync)(r,{recursive:!0,mode:448}),i=!0),r),a=BM.filter(d=>(0,dr.existsSync)(lt.default.join(e,d))),c=[];for(let d of a)try{s(),(0,dr.renameSync)(lt.default.join(e,d),lt.default.join(r,d)),c.push(d)}catch(f){if(f.code==="ENOENT")continue;console.warn(`archiveLegacyUserState: failed to archive "${d}": ${f.message}`)}let l=c.length===a.length;it(lt.default.join(e,"hub-token"));let u=l?KM(e,s):{relocated:null,archived:!1,ok:!0};return l&&u.ok&&(dm({onboardedAt:null},{configFile:lt.default.join(e,"config.json")}),ZM(o,n)),{archived:c,skipped:!1,credentialRelocated:u.relocated,credentialArchived:u.archived}}function jM(t){return{accessFile:lt.default.join(t,"relay-access-token"),refreshFile:lt.default.join(t,"relay-refresh-token")}}function zM(t,e){let n=lt.default.join(t,"users",e);return{accessFile:lt.default.join(n,"relay-access-token"),refreshFile:lt.default.join(n,"relay-refresh-token")}}function j0(t,e){try{return(0,dr.mkdirSync)(lt.default.dirname(e),{recursive:!0,mode:448}),(0,dr.renameSync)(t,e),"moved"}catch(n){return n.code==="ENOENT"?"absent":(console.warn(`archiveLegacyUserState: failed to relocate credential to "${e}": ${n.message}`),"failed")}}function il(t,e,n){try{let o=t();return(0,dr.renameSync)(e,lt.default.join(o,n)),"moved"}catch(o){return o.code==="ENOENT"?"absent":(console.warn(`archiveLegacyUserState: failed to archive credential "${n}": ${o.message}`),"failed")}}function HM(t,e){let n=lt.default.join(t,"active-user.json");if(rl({file:n})===null)try{B0({sub:e},{file:n})}catch(o){console.warn(`archiveLegacyUserState: failed to heal the active-user pointer to "${e}": ${o.message}`)}}function KM(t,e){let n=jM(t),o=X(n.refreshFile),r=X(n.accessFile);if(!o&&!r)return{relocated:null,archived:!1,ok:!0};let i=o?Ot(o):null,s=r?Ot(r):null,a=i??s;if(!a){let f=o?il(e,n.refreshFile,"relay-refresh-token"):"absent",m=r?il(e,n.accessFile,"relay-access-token"):"absent";return{relocated:null,archived:f==="moved"||m==="moved",ok:f!=="failed"&&m!=="failed"}}i&&s&&i!==s&&console.warn(`archiveLegacyUserState: access-token sub (${s}) differs from refresh-token sub (${i}) \u2014 relocating the refresh to its sub and archiving the access (the refresh loop re-mints a matching access)`);let c=lr(a),l=zM(t,c),u=!0,d=!1;if(o){let f=i===a?j0(n.refreshFile,l.refreshFile):il(e,n.refreshFile,"relay-refresh-token");f==="failed"?u=!1:f==="moved"&&i!==a&&(d=!0)}if(r){let f=s===a?j0(n.accessFile,l.accessFile):il(e,n.accessFile,"relay-access-token");f==="failed"?u=!1:f==="moved"&&s!==a&&(d=!0)}return u&&HM(t,a),{relocated:{sub:a,segment:c},archived:d,ok:u}}function GM(t){return t.toISOString().replace(/[:.]/g,"-")}function WM(t){let e=X(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n.version=="number"&&n.version>=z0}catch{return!1}}function ZM(t,e){let n={version:z0,migratedAt:e().toISOString()};pe(t,`${JSON.stringify(n,null,2)}
98
+ `,384)}var sl=mt.default.join(Te,"hub-token"),W0=Number(process.env.BRIDGE_HUB_PORT)||8790,Si=mt.default.join(Te,"config.json"),Wq=mt.default.join(Te,"hub.log"),cm=mt.default.join(Te,"hub.pid"),fm=mt.default.join(Te,em),Zq=mt.default.join(Te,"daemon.pid"),qq=mt.default.join(Te,"daemon-beacon.json"),Vq=mt.default.join(Te,"daemon.log"),qM=mt.default.join(Te,"hub-stop-reason.json"),LM=mt.default.join(Te,"app-path"),Z0=mt.default.join(Te,"hub-relay-status.json"),al=mt.default.join(Te,"hub-holders.json"),Zs=mt.default.join(Te,"sessions");function pe(t,e,n=384){let o=mt.default.dirname(t),r=(n&63)===0;if((0,Nt.mkdirSync)(o,{recursive:!0,...r?{mode:448}:{}}),r)try{(0,Nt.chmodSync)(o,448)}catch{}let i=`${t}.tmp-${process.pid}-${process.hrtime.bigint()}`;(0,Nt.writeFileSync)(i,e,{mode:n});try{(0,Nt.renameSync)(i,t)}catch(s){try{(0,Nt.rmSync)(i,{force:!0})}catch{}throw s}}function X(t){try{return(0,Nt.readFileSync)(t,"utf8").trim()||null}catch{return null}}function mm(t,e){let n=e?.write??((r,i)=>pe(r,i,384)),o=e?.now??Date.now;try{n(qM,JSON.stringify({signal:t,ts:o()}))}catch{}}var VM=["app","daemon","run","cli"];function cl(t){return typeof t=="string"&&VM.includes(t)}function q0(){let t={};try{let e=X(Si);e&&(t=JSON.parse(e))}catch{}return process.env.BRIDGE_MACHINE||t.machine||G0.default.hostname().split(".")[0]||"node"}function it(t){try{(0,Nt.rmSync)(t,{force:!0})}catch{}}function V0(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function Ws(t,e){if(!e||e.includes("/")||e.includes("\\")||e.includes("..")||e.includes("\0"))throw new Error(`unsafe ${t}: ${JSON.stringify(e)}`)}function qs(t,e){return Ws("provider",t),`${t}_${(0,K0.createHash)("sha256").update(e).digest("hex").slice(0,12)}`}var p={};Xt(p,{$brand:()=>hm,$input:()=>Mh,$output:()=>Nh,NEVER:()=>gm,TimePrecision:()=>jh,ZodAny:()=>Av,ZodArray:()=>Ov,ZodBase64:()=>Lu,ZodBase64URL:()=>Nu,ZodBigInt:()=>es,ZodBigIntFormat:()=>Fu,ZodBoolean:()=>Qi,ZodCIDRv4:()=>$u,ZodCIDRv6:()=>Ou,ZodCUID:()=>Tu,ZodCUID2:()=>Eu,ZodCatch:()=>nb,ZodCodec:()=>Ta,ZodCustom:()=>Ea,ZodCustomStringFormat:()=>Yi,ZodDate:()=>ka,ZodDefault:()=>Jv,ZodDiscriminatedUnion:()=>Nv,ZodE164:()=>Mu,ZodEmail:()=>Su,ZodEmoji:()=>_u,ZodEnum:()=>Vi,ZodError:()=>TF,ZodExactOptional:()=>Zv,ZodFile:()=>Gv,ZodFirstPartyTypeKind:()=>gb,ZodFunction:()=>pb,ZodGUID:()=>ha,ZodIPv4:()=>Pu,ZodIPv6:()=>Du,ZodISODate:()=>yu,ZodISODateTime:()=>hu,ZodISODuration:()=>bu,ZodISOTime:()=>vu,ZodIntersection:()=>Mv,ZodIssueCode:()=>CF,ZodJWT:()=>Uu,ZodKSUID:()=>Au,ZodLazy:()=>lb,ZodLiteral:()=>Kv,ZodMAC:()=>Sv,ZodMap:()=>zv,ZodNaN:()=>ob,ZodNanoID:()=>Iu,ZodNever:()=>Dv,ZodNonOptional:()=>Gu,ZodNull:()=>Cv,ZodNullable:()=>Vv,ZodNumber:()=>Xi,ZodNumberFormat:()=>Fo,ZodObject:()=>Sa,ZodOptional:()=>Ku,ZodPipe:()=>Ia,ZodPrefault:()=>Xv,ZodPreprocess:()=>ib,ZodPromise:()=>db,ZodReadonly:()=>sb,ZodRealError:()=>Tt,ZodRecord:()=>qi,ZodSet:()=>Hv,ZodString:()=>Ji,ZodStringFormat:()=>ge,ZodSuccess:()=>tb,ZodSymbol:()=>Tv,ZodTemplateLiteral:()=>cb,ZodTransform:()=>Wv,ZodTuple:()=>Fv,ZodType:()=>J,ZodULID:()=>Cu,ZodURL:()=>wa,ZodUUID:()=>jn,ZodUndefined:()=>Ev,ZodUnion:()=>_a,ZodUnknown:()=>Pv,ZodVoid:()=>$v,ZodXID:()=>Ru,ZodXor:()=>Lv,_ZodString:()=>xu,_default:()=>Yv,_function:()=>MI,any:()=>mI,array:()=>xa,base64:()=>Y_,base64url:()=>X_,bigint:()=>lI,boolean:()=>Iv,catch:()=>rb,check:()=>UI,cidrv4:()=>V_,cidrv6:()=>J_,clone:()=>gt,codec:()=>$I,coerce:()=>hb,config:()=>Le,core:()=>mr,cuid:()=>j_,cuid2:()=>z_,custom:()=>FI,date:()=>hI,decode:()=>hv,decodeAsync:()=>vv,describe:()=>BI,discriminatedUnion:()=>xI,e164:()=>Q_,email:()=>P_,emoji:()=>F_,encode:()=>gv,encodeAsync:()=>yv,endsWith:()=>Ui,enum:()=>zu,exactOptional:()=>qv,file:()=>RI,flattenError:()=>na,float32:()=>iI,float64:()=>sI,formatError:()=>ra,fromJSONSchema:()=>ZI,function:()=>MI,getErrorMap:()=>AF,globalRegistry:()=>st,gt:()=>Fn,gte:()=>yt,guid:()=>D_,hash:()=>oI,hex:()=>rI,hostname:()=>nI,httpUrl:()=>U_,includes:()=>Ni,instanceof:()=>zI,int:()=>wu,int32:()=>aI,int64:()=>uI,intersection:()=>Uv,invertCodec:()=>OI,ipv4:()=>W_,ipv6:()=>q_,iso:()=>Zi,json:()=>KI,jwt:()=>eI,keyof:()=>yI,ksuid:()=>G_,lazy:()=>ub,length:()=>Mo,literal:()=>CI,locales:()=>da,looseObject:()=>wI,looseRecord:()=>_I,lowercase:()=>Oi,lt:()=>Un,lte:()=>Ut,mac:()=>Z_,map:()=>II,maxLength:()=>No,maxSize:()=>Yr,meta:()=>jI,mime:()=>Fi,minLength:()=>fr,minSize:()=>Bn,multipleOf:()=>Jr,nan:()=>DI,nanoid:()=>B_,nativeEnum:()=>EI,negative:()=>su,never:()=>Bu,nonnegative:()=>cu,nonoptional:()=>eb,nonpositive:()=>au,normalize:()=>Bi,null:()=>Rv,nullable:()=>va,nullish:()=>AI,number:()=>_v,object:()=>vI,optional:()=>ya,overwrite:()=>gn,parse:()=>dv,parseAsync:()=>pv,partialRecord:()=>SI,pipe:()=>ku,positive:()=>iu,prefault:()=>Qv,preprocess:()=>GI,prettifyError:()=>Rm,promise:()=>NI,property:()=>lu,readonly:()=>ab,record:()=>jv,refine:()=>fb,regex:()=>$i,regexes:()=>Mt,registry:()=>Ul,safeDecode:()=>wv,safeDecodeAsync:()=>xv,safeEncode:()=>bv,safeEncodeAsync:()=>kv,safeParse:()=>fv,safeParseAsync:()=>mv,set:()=>TI,setErrorMap:()=>RF,size:()=>Lo,slugify:()=>Ki,startsWith:()=>Mi,strictObject:()=>bI,string:()=>ga,stringFormat:()=>tI,stringbool:()=>HI,success:()=>PI,superRefine:()=>mb,symbol:()=>pI,templateLiteral:()=>LI,toJSONSchema:()=>fu,toLowerCase:()=>zi,toUpperCase:()=>Hi,transform:()=>Hu,treeifyError:()=>Cm,trim:()=>ji,tuple:()=>Bv,uint32:()=>cI,uint64:()=>dI,ulid:()=>H_,undefined:()=>fI,union:()=>ju,unknown:()=>Uo,uppercase:()=>Li,url:()=>M_,util:()=>P,uuid:()=>$_,uuidv4:()=>O_,uuidv6:()=>L_,uuidv7:()=>N_,void:()=>gI,xid:()=>K_,xor:()=>kI});var mr={};Xt(mr,{$ZodAny:()=>oh,$ZodArray:()=>lh,$ZodAsyncError:()=>mn,$ZodBase64:()=>qg,$ZodBase64URL:()=>Vg,$ZodBigInt:()=>Al,$ZodBigIntFormat:()=>eh,$ZodBoolean:()=>aa,$ZodCIDRv4:()=>Gg,$ZodCIDRv6:()=>Wg,$ZodCUID:()=>$g,$ZodCUID2:()=>Og,$ZodCatch:()=>Eh,$ZodCheck:()=>be,$ZodCheckBigIntFormat:()=>lg,$ZodCheckEndsWith:()=>kg,$ZodCheckGreaterThan:()=>_l,$ZodCheckIncludes:()=>bg,$ZodCheckLengthEquals:()=>gg,$ZodCheckLessThan:()=>Sl,$ZodCheckLowerCase:()=>yg,$ZodCheckMaxLength:()=>fg,$ZodCheckMaxSize:()=>ug,$ZodCheckMimeType:()=>Sg,$ZodCheckMinLength:()=>mg,$ZodCheckMinSize:()=>dg,$ZodCheckMultipleOf:()=>ag,$ZodCheckNumberFormat:()=>cg,$ZodCheckOverwrite:()=>_g,$ZodCheckProperty:()=>xg,$ZodCheckRegex:()=>hg,$ZodCheckSizeEquals:()=>pg,$ZodCheckStartsWith:()=>wg,$ZodCheckStringFormat:()=>Pi,$ZodCheckUpperCase:()=>vg,$ZodCodec:()=>la,$ZodCustom:()=>Lh,$ZodCustomStringFormat:()=>Xg,$ZodDate:()=>ch,$ZodDefault:()=>Sh,$ZodDiscriminatedUnion:()=>ph,$ZodE164:()=>Jg,$ZodEmail:()=>Rg,$ZodEmoji:()=>Pg,$ZodEncodeError:()=>Gr,$ZodEnum:()=>yh,$ZodError:()=>ta,$ZodExactOptional:()=>kh,$ZodFile:()=>bh,$ZodFunction:()=>Dh,$ZodGUID:()=>Eg,$ZodIPv4:()=>zg,$ZodIPv6:()=>Hg,$ZodISODate:()=>Fg,$ZodISODateTime:()=>Ug,$ZodISODuration:()=>jg,$ZodISOTime:()=>Bg,$ZodIntersection:()=>fh,$ZodJWT:()=>Yg,$ZodKSUID:()=>Mg,$ZodLazy:()=>Oh,$ZodLiteral:()=>vh,$ZodMAC:()=>Kg,$ZodMap:()=>gh,$ZodNaN:()=>Ch,$ZodNanoID:()=>Dg,$ZodNever:()=>sh,$ZodNonOptional:()=>Ih,$ZodNull:()=>rh,$ZodNullable:()=>xh,$ZodNumber:()=>Rl,$ZodNumberFormat:()=>Qg,$ZodObject:()=>TS,$ZodObjectJIT:()=>uh,$ZodOptional:()=>Dl,$ZodPipe:()=>$l,$ZodPrefault:()=>_h,$ZodPreprocess:()=>Rh,$ZodPromise:()=>$h,$ZodReadonly:()=>Ah,$ZodRealError:()=>It,$ZodRecord:()=>mh,$ZodRegistry:()=>Ml,$ZodSet:()=>hh,$ZodString:()=>Oo,$ZodStringFormat:()=>me,$ZodSuccess:()=>Th,$ZodSymbol:()=>th,$ZodTemplateLiteral:()=>Ph,$ZodTransform:()=>wh,$ZodTuple:()=>Pl,$ZodType:()=>V,$ZodULID:()=>Lg,$ZodURL:()=>Ag,$ZodUUID:()=>Cg,$ZodUndefined:()=>nh,$ZodUnion:()=>ca,$ZodUnknown:()=>ih,$ZodVoid:()=>ah,$ZodXID:()=>Ng,$ZodXor:()=>dh,$brand:()=>hm,$constructor:()=>k,$input:()=>Mh,$output:()=>Nh,Doc:()=>sa,JSONSchema:()=>C_,JSONSchemaGenerator:()=>mu,NEVER:()=>gm,TimePrecision:()=>jh,_any:()=>cy,_array:()=>gy,_base64:()=>tu,_base64url:()=>nu,_bigint:()=>ty,_boolean:()=>Qh,_catch:()=>vF,_check:()=>E_,_cidrv4:()=>Ql,_cidrv6:()=>eu,_coercedBigint:()=>ny,_coercedBoolean:()=>ey,_coercedDate:()=>fy,_coercedNumber:()=>Zh,_coercedString:()=>Fh,_cuid:()=>Wl,_cuid2:()=>Zl,_custom:()=>yy,_date:()=>py,_decode:()=>ml,_decodeAsync:()=>hl,_default:()=>gF,_discriminatedUnion:()=>rF,_e164:()=>ru,_email:()=>Fl,_emoji:()=>Kl,_encode:()=>fl,_encodeAsync:()=>gl,_endsWith:()=>Ui,_enum:()=>lF,_file:()=>hy,_float32:()=>Vh,_float64:()=>Jh,_gt:()=>Fn,_gte:()=>yt,_guid:()=>pa,_includes:()=>Ni,_int:()=>qh,_int32:()=>Yh,_int64:()=>ry,_intersection:()=>oF,_ipv4:()=>Yl,_ipv6:()=>Xl,_isoDate:()=>Hh,_isoDateTime:()=>zh,_isoDuration:()=>Gh,_isoTime:()=>Kh,_jwt:()=>ou,_ksuid:()=>Jl,_lazy:()=>xF,_length:()=>Mo,_literal:()=>dF,_lowercase:()=>Oi,_lt:()=>Un,_lte:()=>Ut,_mac:()=>Bh,_map:()=>aF,_max:()=>Ut,_maxLength:()=>No,_maxSize:()=>Yr,_mime:()=>Fi,_min:()=>yt,_minLength:()=>fr,_minSize:()=>Bn,_multipleOf:()=>Jr,_nan:()=>my,_nanoid:()=>Gl,_nativeEnum:()=>uF,_negative:()=>su,_never:()=>uy,_nonnegative:()=>cu,_nonoptional:()=>hF,_nonpositive:()=>au,_normalize:()=>Bi,_null:()=>ay,_nullable:()=>mF,_number:()=>Wh,_optional:()=>fF,_overwrite:()=>gn,_parse:()=>Ei,_parseAsync:()=>Ci,_pipe:()=>bF,_positive:()=>iu,_promise:()=>SF,_property:()=>lu,_readonly:()=>wF,_record:()=>sF,_refine:()=>vy,_regex:()=>$i,_safeDecode:()=>vl,_safeDecodeAsync:()=>wl,_safeEncode:()=>yl,_safeEncodeAsync:()=>bl,_safeParse:()=>Ri,_safeParseAsync:()=>Ai,_set:()=>cF,_size:()=>Lo,_slugify:()=>Ki,_startsWith:()=>Mi,_string:()=>Uh,_stringFormat:()=>Gi,_stringbool:()=>xy,_success:()=>yF,_superRefine:()=>by,_symbol:()=>iy,_templateLiteral:()=>kF,_toLowerCase:()=>zi,_toUpperCase:()=>Hi,_transform:()=>pF,_trim:()=>ji,_tuple:()=>iF,_uint32:()=>Xh,_uint64:()=>oy,_ulid:()=>ql,_undefined:()=>sy,_union:()=>tF,_unknown:()=>ly,_uppercase:()=>Li,_url:()=>fa,_uuid:()=>Bl,_uuidv4:()=>jl,_uuidv6:()=>zl,_uuidv7:()=>Hl,_void:()=>dy,_xid:()=>Vl,_xor:()=>nF,clone:()=>gt,config:()=>Le,createStandardJSONSchemaMethod:()=>Wi,createToJSONSchemaMethod:()=>Sy,decode:()=>S2,decodeAsync:()=>I2,describe:()=>wy,encode:()=>x2,encodeAsync:()=>_2,extractDefs:()=>Qr,finalize:()=>eo,flattenError:()=>na,formatError:()=>ra,globalConfig:()=>Po,globalRegistry:()=>st,initializeContext:()=>Xr,isValidBase64:()=>Zg,isValidBase64URL:()=>xS,isValidJWT:()=>SS,locales:()=>da,meta:()=>ky,parse:()=>dl,parseAsync:()=>pl,prettifyError:()=>Rm,process:()=>fe,regexes:()=>Mt,registry:()=>Ul,safeDecode:()=>E2,safeDecodeAsync:()=>R2,safeEncode:()=>T2,safeEncodeAsync:()=>C2,safeParse:()=>Am,safeParseAsync:()=>Pm,toDotPath:()=>tS,toJSONSchema:()=>fu,treeifyError:()=>Cm,util:()=>P,version:()=>Ig});var J0,gm=Object.freeze({status:"aborted"});function k(t,e,n){function o(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:t});function s(a){var c;let l=n?.Parent?new i:this;o(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var hm=Symbol("zod_brand"),mn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Gr=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(J0=globalThis).__zod_globalConfig??(J0.__zod_globalConfig={});var Po=globalThis.__zod_globalConfig;function Le(t){return t&&Object.assign(Po,t),Po}var P={};Xt(P,{BIGINT_FORMAT_RANGES:()=>Tm,Class:()=>vm,NUMBER_FORMAT_RANGES:()=>Im,aborted:()=>Vr,allowsEval:()=>km,assert:()=>e2,assertEqual:()=>JM,assertIs:()=>XM,assertNever:()=>QM,assertNotEqual:()=>YM,assignProp:()=>Zr,base64ToUint8Array:()=>X0,base64urlToUint8Array:()=>y2,cached:()=>Ii,captureStackTrace:()=>ul,cleanEnum:()=>h2,cleanRegex:()=>Ys,clone:()=>gt,cloneDef:()=>n2,createTransparentProxy:()=>c2,defineLazy:()=>ee,esc:()=>ll,escapeRegex:()=>Qt,explicitlyAborted:()=>Em,extend:()=>d2,finalizeIssue:()=>ht,floatSafeRemainder:()=>bm,getElementAtPath:()=>r2,getEnumValues:()=>Js,getLengthableOrigin:()=>ea,getParsedType:()=>a2,getSizableOrigin:()=>Qs,hexToUint8Array:()=>b2,isObject:()=>Do,isPlainObject:()=>qr,issue:()=>Ti,joinValues:()=>_,jsonStringifyReplacer:()=>_i,merge:()=>f2,mergeDefs:()=>pr,normalizeParams:()=>D,nullish:()=>Wr,numKeys:()=>s2,objectClone:()=>t2,omit:()=>u2,optionalKeys:()=>_m,parsedType:()=>A,partial:()=>m2,pick:()=>l2,prefixIssues:()=>_t,primitiveTypes:()=>Sm,promiseAllObject:()=>o2,propertyKeyTypes:()=>Xs,randomString:()=>i2,required:()=>g2,safeExtend:()=>p2,shallowClone:()=>xm,slugify:()=>wm,stringifyPrimitive:()=>R,uint8ArrayToBase64:()=>Q0,uint8ArrayToBase64url:()=>v2,uint8ArrayToHex:()=>w2,unwrapMessage:()=>Vs});function JM(t){return t}function YM(t){return t}function XM(t){}function QM(t){throw new Error("Unexpected value in exhaustive check")}function e2(t){}function Js(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,r])=>e.indexOf(+o)===-1).map(([o,r])=>r)}function _(t,e="|"){return t.map(n=>R(n)).join(e)}function _i(t,e){return typeof e=="bigint"?e.toString():e}function Ii(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Wr(t){return t==null}function Ys(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function bm(t,e){let n=t/e,o=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<r?0:n-o}var Y0=Symbol("evaluating");function ee(t,e,n){let o;Object.defineProperty(t,e,{get(){if(o!==Y0)return o===void 0&&(o=Y0,o=n()),o},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function t2(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Zr(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function pr(...t){let e={};for(let n of t){let o=Object.getOwnPropertyDescriptors(n);Object.assign(e,o)}return Object.defineProperties({},e)}function n2(t){return pr(t._zod.def)}function r2(t,e){return e?e.reduce((n,o)=>n?.[o],t):t}function o2(t){let e=Object.keys(t),n=e.map(o=>t[o]);return Promise.all(n).then(o=>{let r={};for(let i=0;i<e.length;i++)r[e[i]]=o[i];return r})}function i2(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let o=0;o<t;o++)n+=e[Math.floor(Math.random()*e.length)];return n}function ll(t){return JSON.stringify(t)}function wm(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ul="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Do(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var km=Ii(()=>{if(Po.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function qr(t){if(Do(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(Do(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function xm(t){return qr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function s2(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var a2=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Xs=new Set(["string","number","symbol"]),Sm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gt(t,e,n){let o=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(o._zod.parent=t),o}function D(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function c2(t){let e;return new Proxy({},{get(n,o,r){return e??(e=t()),Reflect.get(e,o,r)},set(n,o,r,i){return e??(e=t()),Reflect.set(e,o,r,i)},has(n,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(n,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(n,o,r){return e??(e=t()),Reflect.defineProperty(e,o,r)}})}function R(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function _m(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Im={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Tm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function l2(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=pr(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=n.shape[a])}return Zr(this,"shape",s),s},checks:[]});return gt(t,i)}function u2(t,e){let n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=pr(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Zr(this,"shape",s),s},checks:[]});return gt(t,i)}function d2(t,e){if(!qr(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=pr(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return Zr(this,"shape",i),i}});return gt(t,r)}function p2(t,e){if(!qr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=pr(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return Zr(this,"shape",o),o}});return gt(t,n)}function f2(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=pr(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e._zod.def.shape};return Zr(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return gt(t,n)}function m2(t,e,n){let r=e._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=pr(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let l in n){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(c[l]=t?new t({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=t?new t({type:"optional",innerType:a[l]}):a[l];return Zr(this,"shape",c),c},checks:[]});return gt(e,s)}function g2(t,e,n){let o=pr(e._zod.def,{get shape(){let r=e._zod.def.shape,i={...r};if(n)for(let s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)i[s]=new t({type:"nonoptional",innerType:r[s]});return Zr(this,"shape",i),i}});return gt(e,o)}function Vr(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Em(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function _t(t,e){return e.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(t),n})}function Vs(t){return typeof t=="string"?t:t?.message}function ht(t,e,n){let o=t.message?t.message:Vs(t.inst?._zod.def?.error?.(t))??Vs(e?.error?.(t))??Vs(n.customError?.(t))??Vs(n.localeError?.(t))??"Invalid input",{inst:r,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=o,e?.reportInput&&(a.input=s),a}function Qs(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ea(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function A(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Ti(...t){let[e,n,o]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:o}:{...e}}function h2(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function X0(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function Q0(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function y2(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return X0(e+n)}function v2(t){return Q0(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function b2(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)n[o/2]=Number.parseInt(e.slice(o,o+2),16);return n}function w2(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var vm=class{constructor(...e){}};var eS=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,_i,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ta=k("$ZodError",eS),It=k("$ZodError",eS,{Parent:Error});function na(t,e=n=>n.message){let n={},o=[];for(let r of t.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(e(r))):o.push(e(r));return{formErrors:o,fieldErrors:n}}function ra(t,e=n=>n.message){let n={_errors:[]},o=(r,i=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)n._errors.push(e(s));else{let c=n,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(e(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return o(t),n}function Cm(t,e=n=>n.message){let n={errors:[]},o=(r,i=[])=>{var s,a;for(let c of r.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>o({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){n.errors.push(e(c));continue}let u=n,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(e(c)),d++}}};return o(t),n}function tS(t){let e=[],n=t.map(o=>typeof o=="object"?o.key:o);for(let o of n)typeof o=="number"?e.push(`[${o}]`):typeof o=="symbol"?e.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?e.push(`[${JSON.stringify(o)}]`):(e.length&&e.push("."),e.push(o));return e.join("")}function Rm(t){let e=[],n=[...t.issues].sort((o,r)=>(o.path??[]).length-(r.path??[]).length);for(let o of n)e.push(`\u2716 ${o.message}`),o.path?.length&&e.push(` \u2192 at ${tS(o.path)}`);return e.join(`
99
+ `)}var Ei=t=>(e,n,o,r)=>{let i=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new mn;if(s.issues.length){let a=new(r?.Err??t)(s.issues.map(c=>ht(c,i,Le())));throw ul(a,r?.callee),a}return s.value},dl=Ei(It),Ci=t=>async(e,n,o,r)=>{let i=o?{...o,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(r?.Err??t)(s.issues.map(c=>ht(c,i,Le())));throw ul(a,r?.callee),a}return s.value},pl=Ci(It),Ri=t=>(e,n,o)=>{let r=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new mn;return i.issues.length?{success:!1,error:new(t??ta)(i.issues.map(s=>ht(s,r,Le())))}:{success:!0,data:i.value}},Am=Ri(It),Ai=t=>async(e,n,o)=>{let r=o?{...o,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>ht(s,r,Le())))}:{success:!0,data:i.value}},Pm=Ai(It),fl=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Ei(t)(e,n,r)},x2=fl(It),ml=t=>(e,n,o)=>Ei(t)(e,n,o),S2=ml(It),gl=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Ci(t)(e,n,r)},_2=gl(It),hl=t=>async(e,n,o)=>Ci(t)(e,n,o),I2=hl(It),yl=t=>(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Ri(t)(e,n,r)},T2=yl(It),vl=t=>(e,n,o)=>Ri(t)(e,n,o),E2=vl(It),bl=t=>async(e,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Ai(t)(e,n,r)},C2=bl(It),wl=t=>async(e,n,o)=>Ai(t)(e,n,o),R2=wl(It);var Mt={};Xt(Mt,{base64:()=>Zm,base64url:()=>kl,bigint:()=>eg,boolean:()=>ng,browserEmail:()=>M2,cidrv4:()=>Gm,cidrv6:()=>Wm,cuid:()=>Dm,cuid2:()=>$m,date:()=>Jm,datetime:()=>Xm,domain:()=>B2,duration:()=>Um,e164:()=>Vm,email:()=>Bm,emoji:()=>jm,extendedDuration:()=>A2,guid:()=>Fm,hex:()=>j2,hostname:()=>F2,html5Email:()=>O2,httpProtocol:()=>qm,idnEmail:()=>N2,integer:()=>tg,ipv4:()=>zm,ipv6:()=>Hm,ksuid:()=>Nm,lowercase:()=>ig,mac:()=>Km,md5_base64:()=>H2,md5_base64url:()=>K2,md5_hex:()=>z2,nanoid:()=>Mm,null:()=>rg,number:()=>xl,rfc5322Email:()=>L2,sha1_base64:()=>W2,sha1_base64url:()=>Z2,sha1_hex:()=>G2,sha256_base64:()=>V2,sha256_base64url:()=>J2,sha256_hex:()=>q2,sha384_base64:()=>X2,sha384_base64url:()=>Q2,sha384_hex:()=>Y2,sha512_base64:()=>tU,sha512_base64url:()=>nU,sha512_hex:()=>eU,string:()=>Qm,time:()=>Ym,ulid:()=>Om,undefined:()=>og,unicodeEmail:()=>nS,uppercase:()=>sg,uuid:()=>$o,uuid4:()=>P2,uuid6:()=>D2,uuid7:()=>$2,xid:()=>Lm});var Dm=/^[cC][0-9a-z]{6,}$/,$m=/^[0-9a-z]+$/,Om=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lm=/^[0-9a-vA-V]{20}$/,Nm=/^[A-Za-z0-9]{27}$/,Mm=/^[a-zA-Z0-9_-]{21}$/,Um=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,A2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Fm=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,$o=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,P2=$o(4),D2=$o(6),$2=$o(7),Bm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,O2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,L2=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,nS=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,N2=nS,M2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,U2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jm(){return new RegExp(U2,"u")}var zm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Km=t=>{let e=Qt(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},Gm=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Wm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kl=/^[A-Za-z0-9_-]*$/,F2=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,B2=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,qm=/^https?$/,Vm=/^\+[1-9]\d{6,14}$/,rS="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Jm=new RegExp(`^${rS}$`);function oS(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ym(t){return new RegExp(`^${oS(t)}$`)}function Xm(t){let e=oS({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${e}(?:${n.join("|")})`;return new RegExp(`^${rS}T(?:${o})$`)}var Qm=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},eg=/^-?\d+n?$/,tg=/^-?\d+$/,xl=/^-?\d+(?:\.\d+)?$/,ng=/^(?:true|false)$/i,rg=/^null$/i;var og=/^undefined$/i;var ig=/^[^A-Z]*$/,sg=/^[^a-z]*$/,j2=/^[0-9a-fA-F]*$/;function oa(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function ia(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var z2=/^[0-9a-fA-F]{32}$/,H2=oa(22,"=="),K2=ia(22),G2=/^[0-9a-fA-F]{40}$/,W2=oa(27,"="),Z2=ia(27),q2=/^[0-9a-fA-F]{64}$/,V2=oa(43,"="),J2=ia(43),Y2=/^[0-9a-fA-F]{96}$/,X2=oa(64,""),Q2=ia(64),eU=/^[0-9a-fA-F]{128}$/,tU=oa(86,"=="),nU=ia(86);var be=k("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),sS={number:"number",bigint:"bigint",object:"date"},Sl=k("$ZodCheckLessThan",(t,e)=>{be.init(t,e);let n=sS[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,i=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),_l=k("$ZodCheckGreaterThan",(t,e)=>{be.init(t,e);let n=sS[typeof e.value];t._zod.onattach.push(o=>{let r=o._zod.bag,i=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ag=k("$ZodCheckMultipleOf",(t,e)=>{be.init(t,e),t._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):bm(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),cg=k("$ZodCheckNumberFormat",(t,e)=>{be.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),o=n?"int":"number",[r,i]=Im[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=r,a.maximum=i,n&&(a.pattern=tg)}),t._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}}),lg=k("$ZodCheckBigIntFormat",(t,e)=>{be.init(t,e);let[n,o]=Tm[e.format];t._zod.onattach.push(r=>{let i=r._zod.bag;i.format=e.format,i.minimum=n,i.maximum=o}),t._zod.check=r=>{let i=r.value;i<n&&r.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),i>o&&r.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}}),ug=k("$ZodCheckMaxSize",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.size!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let r=o.value;r.size<=e.maximum||o.issues.push({origin:Qs(r),code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),dg=k("$ZodCheckMinSize",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.size!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let r=o.value;r.size>=e.minimum||o.issues.push({origin:Qs(r),code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),pg=k("$ZodCheckSizeEquals",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.size!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag;r.minimum=e.size,r.maximum=e.size,r.size=e.size}),t._zod.check=o=>{let r=o.value,i=r.size;if(i===e.size)return;let s=i>e.size;o.issues.push({origin:Qs(r),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),fg=k("$ZodCheckMaxLength",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let r=o.value;if(r.length<=e.maximum)return;let s=ea(r);o.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),mg=k("$ZodCheckMinLength",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let r=o.value;if(r.length>=e.minimum)return;let s=ea(r);o.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),gg=k("$ZodCheckLengthEquals",(t,e)=>{var n;be.init(t,e),(n=t._zod.def).when??(n.when=o=>{let r=o.value;return!Wr(r)&&r.length!==void 0}),t._zod.onattach.push(o=>{let r=o._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=o=>{let r=o.value,i=r.length;if(i===e.length)return;let s=ea(r),a=i>e.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Pi=k("$ZodCheckStringFormat",(t,e)=>{var n,o;be.init(t,e),t._zod.onattach.push(r=>{let i=r._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),hg=k("$ZodCheckRegex",(t,e)=>{Pi.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),yg=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ig),Pi.init(t,e)}),vg=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sg),Pi.init(t,e)}),bg=k("$ZodCheckIncludes",(t,e)=>{be.init(t,e);let n=Qt(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=o,t._zod.onattach.push(r=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),wg=k("$ZodCheckStartsWith",(t,e)=>{be.init(t,e);let n=new RegExp(`^${Qt(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),kg=k("$ZodCheckEndsWith",(t,e)=>{be.init(t,e);let n=new RegExp(`.*${Qt(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});function iS(t,e,n){t.issues.length&&e.issues.push(..._t(n,t.issues))}var xg=k("$ZodCheckProperty",(t,e)=>{be.init(t,e),t._zod.check=n=>{let o=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(o instanceof Promise)return o.then(r=>iS(r,n,e.property));iS(o,n,e.property)}}),Sg=k("$ZodCheckMimeType",(t,e)=>{be.init(t,e);let n=new Set(e.mime);t._zod.onattach.push(o=>{o._zod.bag.mime=e.mime}),t._zod.check=o=>{n.has(o.value.type)||o.issues.push({code:"invalid_value",values:e.mime,input:o.value.type,inst:t,continue:!e.abort})}}),_g=k("$ZodCheckOverwrite",(t,e)=>{be.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var sa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
100
+ `).filter(s=>s),r=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...n,r.join(`
101
+ `))}};var Ig={major:4,minor:4,patch:3};var V=k("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Ig;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let r of o)for(let i of r._zod.onattach)i(t);if(o.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(s,a,c)=>{let l=Vr(s),u;for(let d of a){if(d._zod.def.when){if(Em(s)||!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new mn;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=Vr(s,f)))});else{if(s.issues.length===f)continue;l||(l=Vr(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(Vr(s))return s.aborted=!0,s;let l=r(a,o,c);if(l instanceof Promise){if(c.async===!1)throw new mn;return l.then(u=>t._zod.parse(u,c))}return t._zod.parse(l,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let l=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>i(u,s,a)):i(l,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new mn;return c.then(l=>r(l,o,a))}return r(c,o,a)}}ee(t,"~standard",()=>({validate:r=>{try{let i=Am(t,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Pm(t,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Oo=k("$ZodString",(t,e)=>{V.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Qm(t._zod.bag),t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),me=k("$ZodStringFormat",(t,e)=>{Pi.init(t,e),Oo.init(t,e)}),Eg=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Fm),me.init(t,e)}),Cg=k("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=$o(o))}else e.pattern??(e.pattern=$o());me.init(t,e)}),Rg=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Bm),me.init(t,e)}),Ag=k("$ZodURL",(t,e)=>{me.init(t,e),t._zod.check=n=>{try{let o=n.value.trim();if(!e.normalize&&e.protocol?.source===qm.source&&!/^https?:\/\//i.test(o)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let r=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=r.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Pg=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=jm()),me.init(t,e)}),Dg=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Mm),me.init(t,e)}),$g=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Dm),me.init(t,e)}),Og=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=$m),me.init(t,e)}),Lg=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Om),me.init(t,e)}),Ng=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Lm),me.init(t,e)}),Mg=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Nm),me.init(t,e)}),Ug=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Xm(e)),me.init(t,e)}),Fg=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Jm),me.init(t,e)}),Bg=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ym(e)),me.init(t,e)}),jg=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Um),me.init(t,e)}),zg=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=zm),me.init(t,e),t._zod.bag.format="ipv4"}),Hg=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Hm),me.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Kg=k("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=Km(e.delimiter)),me.init(t,e),t._zod.bag.format="mac"}),Gg=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Gm),me.init(t,e)}),Wg=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Wm),me.init(t,e),t._zod.check=n=>{let o=n.value.split("/");try{if(o.length!==2)throw new Error;let[r,i]=o;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Zg(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var qg=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Zm),me.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Zg(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function xS(t){if(!kl.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Zg(n)}var Vg=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kl),me.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{xS(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Jg=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vm),me.init(t,e)});function SS(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let r=JSON.parse(atob(o));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||e&&(!("alg"in r)||r.alg!==e))}catch{return!1}}var Yg=k("$ZodJWT",(t,e)=>{me.init(t,e),t._zod.check=n=>{SS(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Xg=k("$ZodCustomStringFormat",(t,e)=>{me.init(t,e),t._zod.check=n=>{e.fn(n.value)||n.issues.push({code:"invalid_format",format:e.format,input:n.value,inst:t,continue:!e.abort})}}),Rl=k("$ZodNumber",(t,e)=>{V.init(t,e),t._zod.pattern=t._zod.bag.pattern??xl,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:t,...i?{received:i}:{}}),n}}),Qg=k("$ZodNumberFormat",(t,e)=>{cg.init(t,e),Rl.init(t,e)}),aa=k("$ZodBoolean",(t,e)=>{V.init(t,e),t._zod.pattern=ng,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:t}),n}}),Al=k("$ZodBigInt",(t,e)=>{V.init(t,e),t._zod.pattern=eg,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),eh=k("$ZodBigIntFormat",(t,e)=>{lg.init(t,e),Al.init(t,e)}),th=k("$ZodSymbol",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:t}),n}}),nh=k("$ZodUndefined",(t,e)=>{V.init(t,e),t._zod.pattern=og,t._zod.values=new Set([void 0]),t._zod.parse=(n,o)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:t}),n}}),rh=k("$ZodNull",(t,e)=>{V.init(t,e),t._zod.pattern=rg,t._zod.values=new Set([null]),t._zod.parse=(n,o)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:t}),n}}),oh=k("$ZodAny",(t,e)=>{V.init(t,e),t._zod.parse=n=>n}),ih=k("$ZodUnknown",(t,e)=>{V.init(t,e),t._zod.parse=n=>n}),sh=k("$ZodNever",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),ah=k("$ZodVoid",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:t}),n}}),ch=k("$ZodDate",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=new Date(n.value)}catch{}let r=n.value,i=r instanceof Date;return i&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...i?{received:"Invalid Date"}:{},inst:t}),n}});function cS(t,e,n){t.issues.length&&e.issues.push(..._t(n,t.issues)),e.value[n]=t.value}var lh=k("$ZodArray",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:t}),n;n.value=Array(r.length);let i=[];for(let s=0;s<r.length;s++){let a=r[s],c=e.element._zod.run({value:a,issues:[]},o);c instanceof Promise?i.push(c.then(l=>cS(l,n,s))):cS(c,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function Cl(t,e,n,o,r,i){let s=n in o;if(t.issues.length){if(r&&i&&!s)return;e.issues.push(..._t(n,t.issues))}if(!s&&!r){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?s&&(e.value[n]=void 0):e.value[n]=t.value}function _S(t){let e=Object.keys(t.shape);for(let o of e)if(!t.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let n=_m(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function IS(t,e,n,o,r,i){let s=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:e[f],issues:[]},o);m instanceof Promise?t.push(m.then(g=>Cl(g,n,f,e,u,d))):Cl(m,n,f,e,u,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>n):n}var TS=k("$ZodObject",(t,e)=>{if(V.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let o=Ii(()=>_S(e));ee(t._zod,"propValues",()=>{let a=e.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let r=Do,i=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=o.value);let l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],g=m._zod.optin==="optional",h=m._zod.optout==="optional",y=m._zod.run({value:l[f],issues:[]},c);y instanceof Promise?u.push(y.then(b=>Cl(b,a,f,l,g,h))):Cl(y,a,f,l,g,h)}return i?IS(u,l,a,c,o.value,t):u.length?Promise.all(u).then(()=>a):a}}),uh=k("$ZodObjectJIT",(t,e)=>{TS.init(t,e);let n=t._zod.parse,o=Ii(()=>_S(e)),r=f=>{let m=new sa(["shape","payload","ctx"]),g=o.value,h=x=>{let I=ll(x);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};m.write("const input = payload.value;");let y=Object.create(null),b=0;for(let x of g.keys)y[x]=`key_${b++}`;m.write("const newResult = {};");for(let x of g.keys){let I=y[x],E=ll(x),C=f[x],F=C?._zod?.optin==="optional",U=C?._zod?.optout==="optional";m.write(`const ${I} = ${h(x)};`),F&&U?m.write(`
102
+ if (${I}.issues.length) {
103
+ if (${E} in input) {
104
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
105
+ ...iss,
106
+ path: iss.path ? [${E}, ...iss.path] : [${E}]
107
+ })));
108
+ }
109
+ }
110
+
111
+ if (${I}.value === undefined) {
112
+ if (${E} in input) {
113
+ newResult[${E}] = undefined;
114
+ }
115
+ } else {
116
+ newResult[${E}] = ${I}.value;
117
+ }
118
+
119
+ `):F?m.write(`
120
+ if (${I}.issues.length) {
121
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
122
+ ...iss,
123
+ path: iss.path ? [${E}, ...iss.path] : [${E}]
124
+ })));
125
+ }
126
+
127
+ if (${I}.value === undefined) {
128
+ if (${E} in input) {
129
+ newResult[${E}] = undefined;
130
+ }
131
+ } else {
132
+ newResult[${E}] = ${I}.value;
133
+ }
134
+
135
+ `):m.write(`
136
+ const ${I}_present = ${E} in input;
137
+ if (${I}.issues.length) {
138
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
139
+ ...iss,
140
+ path: iss.path ? [${E}, ...iss.path] : [${E}]
141
+ })));
142
+ }
143
+ if (!${I}_present && !${I}.issues.length) {
144
+ payload.issues.push({
145
+ code: "invalid_type",
146
+ expected: "nonoptional",
147
+ input: undefined,
148
+ path: [${E}]
149
+ });
150
+ }
151
+
152
+ if (${I}_present) {
153
+ if (${I}.value === undefined) {
154
+ newResult[${E}] = undefined;
155
+ } else {
156
+ newResult[${E}] = ${I}.value;
157
+ }
158
+ }
159
+
160
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");let w=m.compile();return(x,I)=>w(f,x,I)},i,s=Do,a=!Po.jitless,l=a&&km.value,u=e.catchall,d;t._zod.parse=(f,m)=>{d??(d=o.value);let g=f.value;return s(g)?a&&l&&m?.async===!1&&m.jitless!==!0?(i||(i=r(e.shape)),f=i(f,m),u?IS([],g,f,m,d,t):f):n(f,m):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:t}),f)}});function lS(t,e,n,o){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let r=t.filter(i=>!Vr(i));return r.length===1?(e.value=r[0].value,r[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>ht(s,o,Le())))}),e)}var ca=k("$ZodUnion",(t,e)=>{V.init(t,e),ee(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),ee(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),ee(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),ee(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){let o=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${o.map(r=>Ys(r.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,r)=>{if(n)return n(o,r);let i=!1,s=[];for(let a of e.options){let c=a._zod.run({value:o.value,issues:[]},r);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>lS(a,o,t,r)):lS(s,o,t,r)}});function uS(t,e,n,o){let r=t.filter(i=>i.issues.length===0);return r.length===1?(e.value=r[0].value,e):(r.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>ht(s,o,Le())))}):e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:[],inclusive:!1}),e)}var dh=k("$ZodXor",(t,e)=>{ca.init(t,e),e.inclusive=!1;let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,r)=>{if(n)return n(o,r);let i=!1,s=[];for(let a of e.options){let c=a._zod.run({value:o.value,issues:[]},r);c instanceof Promise?(s.push(c),i=!0):s.push(c)}return i?Promise.all(s).then(a=>uS(a,o,t,r)):uS(s,o,t,r)}}),ph=k("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,ca.init(t,e);let n=t._zod.parse;ee(t._zod,"propValues",()=>{let r={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){r[a]||(r[a]=new Set);for(let l of c)r[a].add(l)}}return r});let o=Ii(()=>{let r=e.options,i=new Map;for(let s of r){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});t._zod.parse=(r,i)=>{let s=r.value;if(!Do(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),r;let a=o.value.get(s?.[e.discriminator]);return a?a._zod.run(r,i):e.unionFallback||i.direction==="backward"?n(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:s,path:[e.discriminator],inst:t}),r)}}),fh=k("$ZodIntersection",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value,i=e.left._zod.run({value:r,issues:[]},o),s=e.right._zod.run({value:r,issues:[]},o);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>dS(n,c,l)):dS(n,i,s)}});function Tg(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(qr(t)&&qr(e)){let n=Object.keys(e),o=Object.keys(t).filter(i=>n.indexOf(i)!==-1),r={...t,...e};for(let i of o){let s=Tg(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<t.length;o++){let r=t[o],i=e[o],s=Tg(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function dS(t,e,n){let o=new Map,r;for(let a of e.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).r=!0;else t.issues.push(a);let i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&r&&t.issues.push({...r,keys:i}),Vr(t))return t;let s=Tg(e.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var Pl=k("$ZodTuple",(t,e)=>{V.init(t,e);let n=e.items;t._zod.parse=(o,r)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let s=[],a=pS(n,"optin"),c=pS(n,"optout");if(!e.rest){if(i.length<a)return o.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:t,origin:"array"}),o;i.length>n.length&&o.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:t,origin:"array"})}let l=new Array(n.length);for(let u=0;u<n.length;u++){let d=n[u]._zod.run({value:i[u],issues:[]},r);d instanceof Promise?s.push(d.then(f=>{l[u]=f})):l[u]=d}if(e.rest){let u=n.length-1,d=i.slice(n.length);for(let f of d){u++;let m=e.rest._zod.run({value:f,issues:[]},r);m instanceof Promise?s.push(m.then(g=>fS(g,o,u))):fS(m,o,u)}}return s.length?Promise.all(s).then(()=>mS(l,o,n,i,c)):mS(l,o,n,i,c)}});function pS(t,e){for(let n=t.length-1;n>=0;n--)if(t[n]._zod[e]!=="optional")return n+1;return 0}function fS(t,e,n){t.issues.length&&e.issues.push(..._t(n,t.issues)),e.value[n]=t.value}function mS(t,e,n,o,r){for(let i=0;i<n.length;i++){let s=t[i],a=i<o.length;if(s.issues.length){if(!a&&i>=r){e.value.length=i;break}e.issues.push(..._t(i,s.issues))}e.value[i]=s.value}for(let i=e.value.length-1;i>=o.length&&(n[i]._zod.optout==="optional"&&e.value[i]===void 0);i--)e.value.length=i;return e}var mh=k("$ZodRecord",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!qr(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:t}),n;let i=[],s=e.keyType._zod.values;if(s){n.value={};let a=new Set;for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){a.add(typeof l=="number"?l.toString():l);let u=e.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(m=>ht(m,o,Le())),input:l,path:[l],inst:t});continue}let d=u.value,f=e.valueType._zod.run({value:r[l],issues:[]},o);f instanceof Promise?i.push(f.then(m=>{m.issues.length&&n.issues.push(..._t(l,m.issues)),n.value[d]=m.value})):(f.issues.length&&n.issues.push(..._t(l,f.issues)),n.value[d]=f.value)}let c;for(let l in r)a.has(l)||(c=c??[],c.push(l));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xl.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?n.value[a]=r[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>ht(d,o,Le())),input:a,path:[a],inst:t});continue}let u=e.valueType._zod.run({value:r[a],issues:[]},o);u instanceof Promise?i.push(u.then(d=>{d.issues.length&&n.issues.push(..._t(a,d.issues)),n.value[c.value]=d.value})):(u.issues.length&&n.issues.push(..._t(a,u.issues)),n.value[c.value]=u.value)}}return i.length?Promise.all(i).then(()=>n):n}}),gh=k("$ZodMap",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!(r instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:r,inst:t}),n;let i=[];n.value=new Map;for(let[s,a]of r){let c=e.keyType._zod.run({value:s,issues:[]},o),l=e.valueType._zod.run({value:a,issues:[]},o);c instanceof Promise||l instanceof Promise?i.push(Promise.all([c,l]).then(([u,d])=>{gS(u,d,n,s,r,t,o)})):gS(c,l,n,s,r,t,o)}return i.length?Promise.all(i).then(()=>n):n}});function gS(t,e,n,o,r,i,s){t.issues.length&&(Xs.has(typeof o)?n.issues.push(..._t(o,t.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:i,issues:t.issues.map(a=>ht(a,s,Le()))})),e.issues.length&&(Xs.has(typeof o)?n.issues.push(..._t(o,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:i,key:o,issues:e.issues.map(a=>ht(a,s,Le()))})),n.value.set(t.value,e.value)}var hh=k("$ZodSet",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;if(!(r instanceof Set))return n.issues.push({input:r,inst:t,expected:"set",code:"invalid_type"}),n;let i=[];n.value=new Set;for(let s of r){let a=e.valueType._zod.run({value:s,issues:[]},o);a instanceof Promise?i.push(a.then(c=>hS(c,n))):hS(a,n)}return i.length?Promise.all(i).then(()=>n):n}});function hS(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}var yh=k("$ZodEnum",(t,e)=>{V.init(t,e);let n=Js(e.entries),o=new Set(n);t._zod.values=o,t._zod.pattern=new RegExp(`^(${n.filter(r=>Xs.has(typeof r)).map(r=>typeof r=="string"?Qt(r):r.toString()).join("|")})$`),t._zod.parse=(r,i)=>{let s=r.value;return o.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),vh=k("$ZodLiteral",(t,e)=>{if(V.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?Qt(o):o?Qt(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,r)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),o}}),bh=k("$ZodFile",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{let r=n.value;return r instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:r,inst:t}),n}}),wh=k("$ZodTransform",(t,e)=>{V.init(t,e),t._zod.optin="optional",t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Gr(t.constructor.name);let r=e.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n.fallback=!0,n));if(r instanceof Promise)throw new mn;return n.value=r,n.fallback=!0,n}});function yS(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Dl=k("$ZodOptional",(t,e)=>{V.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ee(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ys(n.source)})?$`):void 0}),t._zod.parse=(n,o)=>{if(e.innerType._zod.optin==="optional"){let r=n.value,i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>yS(s,r)):yS(i,r)}return n.value===void 0?n:e.innerType._zod.run(n,o)}}),kh=k("$ZodExactOptional",(t,e)=>{Dl.init(t,e),ee(t._zod,"values",()=>e.innerType._zod.values),ee(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,o)=>e.innerType._zod.run(n,o)}),xh=k("$ZodNullable",(t,e)=>{V.init(t,e),ee(t._zod,"optin",()=>e.innerType._zod.optin),ee(t._zod,"optout",()=>e.innerType._zod.optout),ee(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ys(n.source)}|null)$`):void 0}),ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,o)=>n.value===null?n:e.innerType._zod.run(n,o)}),Sh=k("$ZodDefault",(t,e)=>{V.init(t,e),t._zod.optin="optional",ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);if(n.value===void 0)return n.value=e.defaultValue,n;let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>vS(i,e)):vS(r,e)}});function vS(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var _h=k("$ZodPrefault",(t,e)=>{V.init(t,e),t._zod.optin="optional",ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,o))}),Ih=k("$ZodNonOptional",(t,e)=>{V.init(t,e),ee(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),t._zod.parse=(n,o)=>{let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>bS(i,t)):bS(r,t)}});function bS(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Th=k("$ZodSuccess",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Gr("ZodSuccess");let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>(n.value=i.issues.length===0,n)):(n.value=r.issues.length===0,n)}}),Eh=k("$ZodCatch",(t,e)=>{V.init(t,e),t._zod.optin="optional",ee(t._zod,"optout",()=>e.innerType._zod.optout),ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>ht(s,o,Le()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=e.catchValue({...n,error:{issues:r.issues.map(i=>ht(i,o,Le()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Ch=k("$ZodNaN",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),$l=k("$ZodPipe",(t,e)=>{V.init(t,e),ee(t._zod,"values",()=>e.in._zod.values),ee(t._zod,"optin",()=>e.in._zod.optin),ee(t._zod,"optout",()=>e.out._zod.optout),ee(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if(o.direction==="backward"){let i=e.out._zod.run(n,o);return i instanceof Promise?i.then(s=>Il(s,e.in,o)):Il(i,e.in,o)}let r=e.in._zod.run(n,o);return r instanceof Promise?r.then(i=>Il(i,e.out,o)):Il(r,e.out,o)}});function Il(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var la=k("$ZodCodec",(t,e)=>{V.init(t,e),ee(t._zod,"values",()=>e.in._zod.values),ee(t._zod,"optin",()=>e.in._zod.optin),ee(t._zod,"optout",()=>e.out._zod.optout),ee(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if((o.direction||"forward")==="forward"){let i=e.in._zod.run(n,o);return i instanceof Promise?i.then(s=>Tl(s,e,o)):Tl(i,e,o)}else{let i=e.out._zod.run(n,o);return i instanceof Promise?i.then(s=>Tl(s,e,o)):Tl(i,e,o)}}});function Tl(t,e,n){if(t.issues.length)return t.aborted=!0,t;if((n.direction||"forward")==="forward"){let r=e.transform(t.value,t);return r instanceof Promise?r.then(i=>El(t,i,e.out,n)):El(t,r,e.out,n)}else{let r=e.reverseTransform(t.value,t);return r instanceof Promise?r.then(i=>El(t,i,e.in,n)):El(t,r,e.in,n)}}function El(t,e,n,o){return t.issues.length?(t.aborted=!0,t):n._zod.run({value:e,issues:t.issues},o)}var Rh=k("$ZodPreprocess",(t,e)=>{$l.init(t,e)}),Ah=k("$ZodReadonly",(t,e)=>{V.init(t,e),ee(t._zod,"propValues",()=>e.innerType._zod.propValues),ee(t._zod,"values",()=>e.innerType._zod.values),ee(t._zod,"optin",()=>e.innerType?._zod?.optin),ee(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);let r=e.innerType._zod.run(n,o);return r instanceof Promise?r.then(wS):wS(r)}});function wS(t){return t.value=Object.freeze(t.value),t}var Ph=k("$ZodTemplateLiteral",(t,e)=>{V.init(t,e);let n=[];for(let o of e.parts)if(typeof o=="object"&&o!==null){if(!o._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);let r=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!r)throw new Error(`Invalid template literal part: ${o._zod.traits}`);let i=r.startsWith("^")?1:0,s=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(i,s))}else if(o===null||Sm.has(typeof o))n.push(Qt(`${o}`));else throw new Error(`Invalid template literal part: ${o}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(o,r)=>typeof o.value!="string"?(o.issues.push({input:o.value,inst:t,expected:"string",code:"invalid_type"}),o):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(o.value)||o.issues.push({input:o.value,inst:t,code:"invalid_format",format:e.format??"template_literal",pattern:t._zod.pattern.source}),o)}),Dh=k("$ZodFunction",(t,e)=>(V.init(t,e),t._def=e,t._zod.def=e,t.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...o){let r=t._def.input?dl(t._def.input,o):o,i=Reflect.apply(n,this,r);return t._def.output?dl(t._def.output,i):i}},t.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...o){let r=t._def.input?await pl(t._def.input,o):o,i=await Reflect.apply(n,this,r);return t._def.output?await pl(t._def.output,i):i}},t._zod.parse=(n,o)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:t}),n):(t._def.output&&t._def.output._zod.def.type==="promise"?n.value=t.implementAsync(n.value):n.value=t.implement(n.value),n),t.input=(...n)=>{let o=t.constructor;return Array.isArray(n[0])?new o({type:"function",input:new Pl({type:"tuple",items:n[0],rest:n[1]}),output:t._def.output}):new o({type:"function",input:n[0],output:t._def.output})},t.output=n=>{let o=t.constructor;return new o({type:"function",input:t._def.input,output:n})},t)),$h=k("$ZodPromise",(t,e)=>{V.init(t,e),t._zod.parse=(n,o)=>Promise.resolve(n.value).then(r=>e.innerType._zod.run({value:r,issues:[]},o))}),Oh=k("$ZodLazy",(t,e)=>{V.init(t,e),ee(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),ee(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),ee(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),ee(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),ee(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,o)=>t._zod.innerType._zod.run(n,o)}),Lh=k("$ZodCustom",(t,e)=>{be.init(t,e),V.init(t,e),t._zod.parse=(n,o)=>n,t._zod.check=n=>{let o=n.value,r=e.fn(o);if(r instanceof Promise)return r.then(i=>kS(i,n,o,t));kS(r,n,o,t)}});function kS(t,e,n,o){if(!t){let r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(r.params=o._zod.def.params),e.issues.push(Ti(r))}}var da={};Xt(da,{ar:()=>ES,az:()=>CS,be:()=>AS,bg:()=>PS,ca:()=>DS,cs:()=>$S,da:()=>OS,de:()=>LS,el:()=>NS,en:()=>Ol,eo:()=>MS,es:()=>US,fa:()=>FS,fi:()=>BS,fr:()=>jS,frCA:()=>zS,he:()=>HS,hr:()=>KS,hu:()=>GS,hy:()=>ZS,id:()=>qS,is:()=>VS,it:()=>JS,ja:()=>YS,ka:()=>XS,kh:()=>QS,km:()=>Ll,ko:()=>e_,lt:()=>n_,mk:()=>r_,ms:()=>o_,nl:()=>i_,no:()=>s_,ota:()=>a_,pl:()=>l_,ps:()=>c_,pt:()=>u_,ro:()=>d_,ru:()=>f_,sl:()=>m_,sv:()=>g_,ta:()=>h_,th:()=>y_,tr:()=>v_,ua:()=>b_,uk:()=>Nl,ur:()=>w_,uz:()=>k_,vi:()=>x_,yo:()=>I_,zhCN:()=>S_,zhTW:()=>__});var oU=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function e(r){return t[r]??null}let n={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${r.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${i}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`}case"invalid_value":return r.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${R(r.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${r.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${r.prefix}"`:i.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${i.suffix}"`:i.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${i.includes}"`:i.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${i.pattern}`:`${n[i.format]??r.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${r.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${r.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${r.keys.length>1?"\u0629":""}: ${_(r.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};function ES(){return{localeError:oU()}}var iU=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${r.expected}, daxil olan ${a}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${i}, daxil olan ${a}`}case"invalid_value":return r.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${R(r.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${i}${r.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${i}${r.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${i.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:i.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${i.suffix}" il\u0259 bitm\u0259lidir`:i.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${i.includes}" daxil olmal\u0131d\u0131r`:i.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${i.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${n[i.format]??r.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${r.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${r.keys.length>1?"lar":""}: ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${r.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};function CS(){return{localeError:iU()}}function RS(t,e,n,o){let r=Math.abs(t),i=r%10,s=r%100;return s>=11&&s<=19?o:i===1?e:i>=2&&i<=4?n:o}var sU=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function e(r){return t[r]??null}let n={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},o={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${r.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${i}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${R(r.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),c=RS(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${r.maximum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),c=RS(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${r.minimum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${n[i.format]??r.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${r.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${_(r.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${r.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};function AS(){return{localeError:sU()}}var aU=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function e(r){return t[r]??null}let n={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},o={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${r.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${i}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${R(r.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${i}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${i}${r.minimum.toString()} ${s.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;if(i.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${i.prefix}"`;if(i.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${i.suffix}"`;if(i.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${i.includes}"`;if(i.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${i.pattern}`;let s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return i.format==="emoji"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="datetime"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="date"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),i.format==="time"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="duration"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${s} ${n[i.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${r.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${r.keys.length>1?"\u043E\u0432\u0435":""}: ${_(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${r.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};function PS(){return{localeError:aU()}}var cU=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function e(r){return t[r]??null}let n={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${r.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${i}, s'ha rebut ${a}`}case"invalid_value":return r.values.length===1?`Valor inv\xE0lid: s'esperava ${R(r.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${_(r.values," o ")}`;case"too_big":{let i=r.inclusive?"com a m\xE0xim":"menys de",s=e(r.origin);return s?`Massa gran: s'esperava que ${r.origin??"el valor"} contingu\xE9s ${i} ${r.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${r.origin??"el valor"} fos ${i} ${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?"com a m\xEDnim":"m\xE9s de",s=e(r.origin);return s?`Massa petit: s'esperava que ${r.origin} contingu\xE9s ${i} ${r.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${r.origin} fos ${i} ${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${i.prefix}"`:i.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format inv\xE0lid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${i.pattern}`:`Format inv\xE0lid per a ${n[i.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${r.divisor}`;case"unrecognized_keys":return`Clau${r.keys.length>1?"s":""} no reconeguda${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${r.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${r.origin}`;default:return"Entrada inv\xE0lida"}}};function DS(){return{localeError:cU()}}var lU=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function e(r){return t[r]??null}let n={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},o={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${r.expected}, obdr\u017Eeno ${a}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${i}, obdr\u017Eeno ${a}`}case"invalid_value":return r.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${R(r.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${i}${r.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${i}${r.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${i.prefix}"`:i.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${i.suffix}"`:i.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${i.includes}"`:i.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${i.pattern}`:`Neplatn\xFD form\xE1t ${n[i.format]??r.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${r.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${_(r.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${r.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${r.origin}`;default:return"Neplatn\xFD vstup"}}};function $S(){return{localeError:lU()}}var uU=()=>{let t={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function e(r){return t[r]??null}let n={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ugyldigt input: forventede instanceof ${r.expected}, fik ${a}`:`Ugyldigt input: forventede ${i}, fik ${a}`}case"invalid_value":return r.values.length===1?`Ugyldig v\xE6rdi: forventede ${R(r.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin),a=o[r.origin]??r.origin;return s?`For stor: forventede ${a??"value"} ${s.verb} ${i} ${r.maximum.toString()} ${s.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${i} ${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin),a=o[r.origin]??r.origin;return s?`For lille: forventede ${a} ${s.verb} ${i} ${r.minimum.toString()} ${s.unit}`:`For lille: forventede ${a} havde ${i} ${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ugyldig streng: skal starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: skal ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: skal indeholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${n[i.format]??r.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${_(r.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${r.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${r.origin}`;default:return"Ugyldigt input"}}};function OS(){return{localeError:uU()}}var dU=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function e(r){return t[r]??null}let n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},o={nan:"NaN",number:"Zahl",array:"Array"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${r.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${i}, erhalten ${a}`}case"invalid_value":return r.values.length===1?`Ung\xFCltige Eingabe: erwartet ${R(r.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${i}${r.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${i}${r.maximum.toString()} ist`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Zu klein: erwartet, dass ${r.origin} ${i}${r.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${r.origin} ${i}${r.minimum.toString()} ist`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ung\xFCltiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ung\xFCltiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ung\xFCltiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${i.pattern} entsprechen`:`Ung\xFCltig: ${n[i.format]??r.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${r.divisor} sein`;case"unrecognized_keys":return`${r.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${_(r.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${r.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${r.origin}`;default:return"Ung\xFCltige Eingabe"}}};function LS(){return{localeError:dU()}}var pU=()=>{let t={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function e(r){return t[r]??null}let n={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return typeof r.expected=="string"&&/^[A-Z]/.test(r.expected)?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${r.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${a}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${i}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${a}`}case"invalid_value":return r.values.length===1?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${R(r.values[0])}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${r.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${i}${r.maximum.toString()} ${s.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${r.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${r.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${i}${r.minimum.toString()} ${s.unit}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${r.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${i.prefix}"`:i.format==="ends_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${i.suffix}"`:i.format==="includes"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${i.includes}"`:i.format==="regex"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${i.pattern}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${n[i.format]??r.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${r.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${r.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${r.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${_(r.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${r.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${r.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};function NS(){return{localeError:pU()}}var fU=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${R(r.values[0])}`:`Invalid option: expected one of ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${i}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${i}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${n[i.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return r.options&&Array.isArray(r.options)&&r.options.length>0?`Invalid discriminator value. Expected ${r.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Ol(){return{localeError:fU()}}var mU=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function e(r){return t[r]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},o={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${r.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${i}, ricevi\u011Dis ${a}`}case"invalid_value":return r.values.length===1?`Nevalida enigo: atendi\u011Dis ${R(r.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${i}${r.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Tro malgranda: atendi\u011Dis ke ${r.origin} havu ${i}${r.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${r.origin} estu ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${n[i.format]??r.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${r.divisor}`;case"unrecognized_keys":return`Nekonata${r.keys.length>1?"j":""} \u015Dlosilo${r.keys.length>1?"j":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${r.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${r.origin}`;default:return"Nevalida enigo"}}};function MS(){return{localeError:mU()}}var gU=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function e(r){return t[r]??null}let n={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${r.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${i}, recibido ${a}`}case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: se esperaba ${R(r.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin),a=o[r.origin]??r.origin;return s?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${i}${r.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin),a=o[r.origin]??r.origin;return s?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${i}${r.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inv\xE1lida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${i.pattern}`:`Inv\xE1lido ${n[i.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Llave${r.keys.length>1?"s":""} desconocida${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${o[r.origin]??r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${o[r.origin]??r.origin}`;default:return"Entrada inv\xE1lida"}}};function US(){return{localeError:gU()}}var hU=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function e(r){return t[r]??null}let n={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},o={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${r.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${i} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return r.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${R(r.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${_(r.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${r.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${i}${r.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${i}${r.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:i.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:i.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${i.includes}" \u0628\u0627\u0634\u062F`:i.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${i.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${n[i.format]??r.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${r.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${r.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${_(r.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${r.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${r.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};function FS(){return{localeError:hU()}}var yU=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function e(r){return t[r]??null}let n={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Virheellinen tyyppi: odotettiin instanceof ${r.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${i}, oli ${a}`}case"invalid_value":return r.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${R(r.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${i}${r.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${i}${r.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${i.includes}"`:i.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${i.pattern}`:`Virheellinen ${n[i.format]??r.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${r.divisor} monikerta`;case"unrecognized_keys":return`${r.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${_(r.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};function BS(){return{localeError:yU()}}var vU=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(r){return t[r]??null}let n={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},o={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Entr\xE9e invalide : instanceof ${r.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${i} attendu, ${a} re\xE7u`}case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : ${R(r.values[0])} attendu`:`Option invalide : une valeur parmi ${_(r.values,"|")} attendue`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Trop grand : ${o[r.origin]??"valeur"} doit ${s.verb} ${i}${r.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${o[r.origin]??"valeur"} doit \xEAtre ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Trop petit : ${o[r.origin]??"valeur"} doit ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`Trop petit : ${o[r.origin]??"valeur"} doit \xEAtre ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${i.pattern}`:`${n[i.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${_(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}};function jS(){return{localeError:vU()}}var bU=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(r){return t[r]??null}let n={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Entr\xE9e invalide : attendu instanceof ${r.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${i}, re\xE7u ${a}`}case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : attendu ${R(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"\u2264":"<",s=e(r.origin);return s?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${i}${r.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?"\u2265":">",s=e(r.origin);return s?`Trop petit : attendu que ${r.origin} ait ${i}${r.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${r.origin} soit ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${i.pattern}`:`${n[i.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${_(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}};function zS(){return{localeError:bU()}}var wU=()=>{let t={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},e={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},n=l=>l?t[l]:void 0,o=l=>{let u=n(l);return u?u.label:l??t.unknown.label},r=l=>`\u05D4${o(l)}`,i=l=>(n(l)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",s=l=>l?e[l]??null:null,a={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},c={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{let u=l.expected,d=c[u??""]??o(u),f=A(l.input),m=c[f]??t[f]?.label??f;return/^[A-Z]/.test(l.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${l.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${m}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${m}`}case"invalid_value":{if(l.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${R(l.values[0])}`;let u=l.values.map(m=>R(m));if(l.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u[0]} \u05D0\u05D5 ${u[1]}`;let d=u[u.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u.slice(0,-1).join(", ")} \u05D0\u05D5 ${d}`}case"too_big":{let u=s(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${u?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${l.maximum.toString()} ${u?.unit??""} ${l.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(l.origin==="number"){let g=l.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${l.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${l.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${g}`}if(l.origin==="array"||l.origin==="set"){let g=l.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",h=l.inclusive?`${l.maximum} ${u?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${l.maximum} ${u?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${h}`.trim()}let f=l.inclusive?"<=":"<",m=i(l.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${f}${l.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${m} ${f}${l.maximum.toString()}`}case"too_small":{let u=s(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${u?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${l.minimum.toString()} ${u?.unit??""} ${l.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(l.origin==="number"){let g=l.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${l.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${l.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${g}`}if(l.origin==="array"||l.origin==="set"){let g=l.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(l.minimum===1&&l.inclusive){let y=(l.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`}let h=l.inclusive?`${l.minimum} ${u?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${l.minimum} ${u?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${h}`.trim()}let f=l.inclusive?">=":">",m=i(l.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${f}${l.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${m} ${f}${l.minimum.toString()}`}case"invalid_format":{let u=l;if(u.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${u.prefix}"`;if(u.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${u.suffix}"`;if(u.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${u.includes}"`;if(u.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${u.pattern}`;let d=a[u.format],f=d?.label??u.format,g=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${f} \u05DC\u05D0 ${g}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${l.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${l.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${l.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${_(l.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${r(l.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};function HS(){return{localeError:wU()}}var kU=()=>{let t={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function e(r){return t[r]??null}let n={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},o={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Neispravan unos: o\u010Dekuje se instanceof ${r.expected}, a primljeno je ${a}`:`Neispravan unos: o\u010Dekuje se ${i}, a primljeno je ${a}`}case"invalid_value":return r.values.length===1?`Neispravna vrijednost: o\u010Dekivano ${R(r.values[0])}`:`Neispravna opcija: o\u010Dekivano jedno od ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin),a=o[r.origin]??r.origin;return s?`Preveliko: o\u010Dekivano da ${a??"vrijednost"} ima ${i}${r.maximum.toString()} ${s.unit??"elemenata"}`:`Preveliko: o\u010Dekivano da ${a??"vrijednost"} bude ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin),a=o[r.origin]??r.origin;return s?`Premalo: o\u010Dekivano da ${a} ima ${i}${r.minimum.toString()} ${s.unit}`:`Premalo: o\u010Dekivano da ${a} bude ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Neispravan tekst: mora zapo\u010Dinjati s "${i.prefix}"`:i.format==="ends_with"?`Neispravan tekst: mora zavr\u0161avati s "${i.suffix}"`:i.format==="includes"?`Neispravan tekst: mora sadr\u017Eavati "${i.includes}"`:i.format==="regex"?`Neispravan tekst: mora odgovarati uzorku ${i.pattern}`:`Neispravna ${n[i.format]??r.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${r.divisor}`;case"unrecognized_keys":return`Neprepoznat${r.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${_(r.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${o[r.origin]??r.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${o[r.origin]??r.origin}`;default:return"Neispravan unos"}}};function KS(){return{localeError:kU()}}var xU=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function e(r){return t[r]??null}let n={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},o={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${r.expected}, a kapott \xE9rt\xE9k ${a}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${i}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return r.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${R(r.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`T\xFAl nagy: ${r.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${i}${r.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${r.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} m\xE9rete t\xFAl kicsi ${i}${r.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} t\xFAl kicsi ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\xC9rv\xE9nytelen string: "${i.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:i.format==="ends_with"?`\xC9rv\xE9nytelen string: "${i.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:i.format==="includes"?`\xC9rv\xE9nytelen string: "${i.includes}" \xE9rt\xE9ket kell tartalmaznia`:i.format==="regex"?`\xC9rv\xE9nytelen string: ${i.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${n[i.format]??r.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${r.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${r.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${r.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};function GS(){return{localeError:xU()}}function WS(t,e,n){return Math.abs(t)===1?e:n}function Di(t){if(!t)return"";let e=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],n=t[t.length-1];return t+(e.includes(n)?"\u0576":"\u0568")}var SU=()=>{let t={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function e(r){return t[r]??null}let n={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},o={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${r.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${i}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`}case"invalid_value":return r.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${R(r.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),c=WS(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Di(r.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${r.maximum.toString()} ${c}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Di(r.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),c=WS(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Di(r.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${r.minimum.toString()} ${c}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Di(r.origin)} \u056C\u056B\u0576\u056B ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${i.prefix}"-\u0578\u057E`:i.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${i.suffix}"-\u0578\u057E`:i.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${i.includes}"`:i.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${i.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${n[i.format]??r.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${r.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${r.keys.length>1?"\u0576\u0565\u0580":""}. ${_(r.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${Di(r.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${Di(r.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};function ZS(){return{localeError:SU()}}var _U=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function e(r){return t[r]??null}let n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Input tidak valid: diharapkan instanceof ${r.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${i}, diterima ${a}`}case"invalid_value":return r.values.length===1?`Input tidak valid: diharapkan ${R(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${i}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Terlalu kecil: diharapkan ${r.origin} memiliki ${i}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${r.origin} menjadi ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${n[i.format]??r.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${r.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${r.origin}`;default:return"Input tidak valid"}}};function qS(){return{localeError:_U()}}var IU=()=>{let t={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function e(r){return t[r]??null}let n={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},o={nan:"NaN",number:"n\xFAmer",array:"fylki"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera instanceof ${r.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera ${i}`}case"invalid_value":return r.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${R(r.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin??"gildi"} hafi ${i}${r.maximum.toString()} ${s.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin??"gildi"} s\xE9 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin} hafi ${i}${r.minimum.toString()} ${s.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin} s\xE9 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${i.prefix}"`:i.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${i.suffix}"`:i.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${i.includes}"`:i.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${i.pattern}`:`Rangt ${n[i.format]??r.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${r.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${r.keys.length>1?"ir lyklar":"ur lykill"}: ${_(r.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${r.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${r.origin}`;default:return"Rangt gildi"}}};function VS(){return{localeError:IU()}}var TU=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function e(r){return t[r]??null}let n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"numero",array:"vettore"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Input non valido: atteso instanceof ${r.expected}, ricevuto ${a}`:`Input non valido: atteso ${i}, ricevuto ${a}`}case"invalid_value":return r.values.length===1?`Input non valido: atteso ${R(r.values[0])}`:`Opzione non valida: atteso uno tra ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Troppo grande: ${r.origin??"valore"} deve avere ${i}${r.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Troppo piccolo: ${r.origin} deve avere ${i}${r.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${r.origin} deve essere ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Input non valido: ${n[i.format]??r.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${r.divisor}`;case"unrecognized_keys":return`Chiav${r.keys.length>1?"i":"e"} non riconosciut${r.keys.length>1?"e":"a"}: ${_(r.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${r.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${r.origin}`;default:return"Input non valido"}}};function JS(){return{localeError:TU()}}var EU=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function e(r){return t[r]??null}let n={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},o={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${r.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${i}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return r.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${R(r.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${_(r.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let i=r.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=e(r.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${s.unit??"\u8981\u7D20"}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let i=r.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=e(r.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${s.unit}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${i.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${n[i.format]??r.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${r.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${r.keys.length>1?"\u7FA4":""}: ${_(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};function YS(){return{localeError:EU()}}var CU=()=>{let t={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function e(r){return t[r]??null}let n={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},o={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${r.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`}case"invalid_value":return r.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${R(r.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${_(r.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${s.verb} ${i}${r.maximum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin} ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin} \u10D8\u10E7\u10DD\u10E1 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${i.prefix}"-\u10D8\u10D7`:i.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${i.suffix}"-\u10D8\u10D7`:i.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${i.includes}"-\u10E1`:i.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${i.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${r.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${r.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${_(r.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${r.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${r.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};function XS(){return{localeError:CU()}}var RU=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function e(r){return t[r]??null}let n={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},o={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${r.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`}case"invalid_value":return r.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${R(r.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${r.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${i} ${r.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${i} ${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${i.prefix}"`:i.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${i.suffix}"`:i.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${i.includes}"`:i.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${i.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${r.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${_(r.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};function Ll(){return{localeError:RU()}}function QS(){return Ll()}var AU=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${r.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${i}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return r.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${R(r.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${_(r.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let i=r.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=i==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(r.origin),c=a?.unit??"\uC694\uC18C";return a?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()}${c} ${i}${s}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()} ${i}${s}`}case"too_small":{let i=r.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=i==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(r.origin),c=a?.unit??"\uC694\uC18C";return a?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()}${c} ${i}${s}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()} ${i}${s}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:i.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${i.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${n[i.format]??r.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${r.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${_(r.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${r.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${r.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};function e_(){return{localeError:AU()}}var ua=t=>t.charAt(0).toUpperCase()+t.slice(1);function t_(t){let e=Math.abs(t),n=e%10,o=e%100;return o>=11&&o<=19||n===0?"many":n===1?"one":"few"}var PU=()=>{let t={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function e(r,i,s,a){let c=t[r]??null;return c===null?c:{unit:c.unit[i],verb:c.verb[a][s?"inclusive":"notInclusive"]}}let n={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},o={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${r.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${i}`}case"invalid_value":return r.values.length===1?`Privalo b\u016Bti ${R(r.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${_(r.values,"|")} pasirinkim\u0173`;case"too_big":{let i=o[r.origin]??r.origin,s=e(r.origin,t_(Number(r.maximum)),r.inclusive??!1,"smaller");if(s?.verb)return`${ua(i??r.origin??"reik\u0161m\u0117")} ${s.verb} ${r.maximum.toString()} ${s.unit??"element\u0173"}`;let a=r.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${ua(i??r.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${r.maximum.toString()} ${s?.unit}`}case"too_small":{let i=o[r.origin]??r.origin,s=e(r.origin,t_(Number(r.minimum)),r.inclusive??!1,"bigger");if(s?.verb)return`${ua(i??r.origin??"reik\u0161m\u0117")} ${s.verb} ${r.minimum.toString()} ${s.unit??"element\u0173"}`;let a=r.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${ua(i??r.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${r.minimum.toString()} ${s?.unit}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${i.prefix}"`:i.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${i.suffix}"`:i.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${i.includes}"`:i.format==="regex"?`Eilut\u0117 privalo atitikti ${i.pattern}`:`Neteisingas ${n[i.format]??r.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${r.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${r.keys.length>1?"i":"as"} rakt${r.keys.length>1?"ai":"as"}: ${_(r.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let i=o[r.origin]??r.origin;return`${ua(i??r.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};function n_(){return{localeError:PU()}}var DU=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e(r){return t[r]??null}let n={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},o={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${r.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${R(r.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${i}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0438\u043C\u0430 ${i}${r.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${i.pattern}`:`Invalid ${n[i.format]??r.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${_(r.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${r.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${r.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};function r_(){return{localeError:DU()}}var $U=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function e(r){return t[r]??null}let n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"nombor"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Input tidak sah: dijangka instanceof ${r.expected}, diterima ${a}`:`Input tidak sah: dijangka ${i}, diterima ${a}`}case"invalid_value":return r.values.length===1?`Input tidak sah: dijangka ${R(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Terlalu besar: dijangka ${r.origin??"nilai"} ${s.verb} ${i}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Terlalu kecil: dijangka ${r.origin} ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${r.origin} adalah ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${n[i.format]??r.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${_(r.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${r.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${r.origin}`;default:return"Input tidak sah"}}};function o_(){return{localeError:$U()}}var OU=()=>{let t={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function e(r){return t[r]??null}let n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},o={nan:"NaN",number:"getal"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ongeldige invoer: verwacht instanceof ${r.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${i}, ontving ${a}`}case"invalid_value":return r.values.length===1?`Ongeldige invoer: verwacht ${R(r.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin),a=r.origin==="date"?"laat":r.origin==="string"?"lang":"groot";return s?`Te ${a}: verwacht dat ${r.origin??"waarde"} ${i}${r.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`:`Te ${a}: verwacht dat ${r.origin??"waarde"} ${i}${r.maximum.toString()} is`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin),a=r.origin==="date"?"vroeg":r.origin==="string"?"kort":"klein";return s?`Te ${a}: verwacht dat ${r.origin} ${i}${r.minimum.toString()} ${s.unit} ${s.verb}`:`Te ${a}: verwacht dat ${r.origin} ${i}${r.minimum.toString()} is`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${n[i.format]??r.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${r.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${r.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${r.origin}`;default:return"Ongeldige invoer"}}};function i_(){return{localeError:OU()}}var LU=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function e(r){return t[r]??null}let n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"tall",array:"liste"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ugyldig input: forventet instanceof ${r.expected}, fikk ${a}`:`Ugyldig input: forventet ${i}, fikk ${a}`}case"invalid_value":return r.values.length===1?`Ugyldig verdi: forventet ${R(r.values[0])}`:`Ugyldig valg: forventet en av ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${i}${r.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`For lite(n): forventet ${r.origin} til \xE5 ha ${i}${r.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${r.origin} til \xE5 ha ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${n[i.format]??r.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${_(r.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${r.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${r.origin}`;default:return"Ugyldig input"}}};function s_(){return{localeError:LU()}}var NU=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function e(r){return t[r]??null}let n={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},o={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`F\xE2sit giren: umulan instanceof ${r.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${i}, al\u0131nan ${a}`}case"invalid_value":return r.values.length===1?`F\xE2sit giren: umulan ${R(r.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${i}${r.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${i}${r.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${i}${r.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${i}${r.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let i=r;return i.format==="starts_with"?`F\xE2sit metin: "${i.prefix}" ile ba\u015Flamal\u0131.`:i.format==="ends_with"?`F\xE2sit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`F\xE2sit metin: "${i.includes}" ihtiv\xE2 etmeli.`:i.format==="regex"?`F\xE2sit metin: ${i.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${n[i.format]??r.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${r.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${r.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};function a_(){return{localeError:NU()}}var MU=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function e(r){return t[r]??null}let n={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},o={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${r.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${i} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return r.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${R(r.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${_(r.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${r.maximum.toString()} \u0648\u064A`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${i}${r.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${i}${r.minimum.toString()} \u0648\u064A`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:i.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:i.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${i.includes}" \u0648\u0644\u0631\u064A`:i.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${i.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${n[i.format]??r.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${r.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${r.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${_(r.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${r.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${r.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};function c_(){return{localeError:MU()}}var UU=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function e(r){return t[r]??null}let n={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},o={nan:"NaN",number:"liczba",array:"tablica"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${r.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${i}, otrzymano ${a}`}case"invalid_value":return r.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${R(r.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${r.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${r.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${i.prefix}"`:i.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${i.suffix}"`:i.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${i.includes}"`:i.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${i.pattern}`:`Nieprawid\u0142ow(y/a/e) ${n[i.format]??r.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${r.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${r.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${r.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};function l_(){return{localeError:UU()}}var FU=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function e(r){return t[r]??null}let n={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",number:"n\xFAmero",null:"nulo"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Tipo inv\xE1lido: esperado instanceof ${r.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${i}, recebido ${a}`}case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: esperado ${R(r.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${i}${r.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Muito pequeno: esperado que ${r.origin} tivesse ${i}${r.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${r.origin} fosse ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${i.prefix}"`:i.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inv\xE1lido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${i.pattern}`:`${n[i.format]??r.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Chave${r.keys.length>1?"s":""} desconhecida${r.keys.length>1?"s":""}: ${_(r.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${r.origin}`;default:return"Campo inv\xE1lido"}}};function u_(){return{localeError:FU()}}var BU=()=>{let t={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function e(r){return t[r]??null}let n={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},o={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return`Intrare invalid\u0103: a\u0219teptat ${i}, primit ${a}`}case"invalid_value":return r.values.length===1?`Intrare invalid\u0103: a\u0219teptat ${R(r.values[0])}`:`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Prea mare: a\u0219teptat ca ${r.origin??"valoarea"} ${s.verb} ${i}${r.maximum.toString()} ${s.unit??"elemente"}`:`Prea mare: a\u0219teptat ca ${r.origin??"valoarea"} s\u0103 fie ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Prea mic: a\u0219teptat ca ${r.origin} ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`Prea mic: a\u0219teptat ca ${r.origin} s\u0103 fie ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${i.prefix}"`:i.format==="ends_with"?`\u0218ir invalid: trebuie s\u0103 se termine cu "${i.suffix}"`:i.format==="includes"?`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${i.includes}"`:i.format==="regex"?`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${i.pattern}`:`Format invalid: ${n[i.format]??r.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${r.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${_(r.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${r.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${r.origin}`;default:return"Intrare invalid\u0103"}}};function d_(){return{localeError:BU()}}function p_(t,e,n,o){let r=Math.abs(t),i=r%10,s=r%100;return s>=11&&s<=19?o:i===1?e:i>=2&&i<=4?n:o}var jU=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function e(r){return t[r]??null}let n={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},o={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${r.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${i}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${R(r.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),c=p_(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${r.maximum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),c=p_(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${r.minimum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${r.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0438":""}: ${_(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${r.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};function f_(){return{localeError:jU()}}var zU=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function e(r){return t[r]??null}let n={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},o={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${r.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${i}, prejeto ${a}`}case"invalid_value":return r.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${R(r.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} imelo ${i}${r.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${r.origin} imelo ${i}${r.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${n[i.format]??r.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${r.divisor}`;case"unrecognized_keys":return`Neprepoznan${r.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${_(r.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${r.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${r.origin}`;default:return"Neveljaven vnos"}}};function m_(){return{localeError:zU()}}var HU=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function e(r){return t[r]??null}let n={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},o={nan:"NaN",number:"antal",array:"lista"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${r.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${i}, fick ${a}`}case"invalid_value":return r.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${R(r.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${i}${r.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${r.origin??"v\xE4rdet"} att ha ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${i}${r.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${i.includes}"`:i.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${i.pattern}"`:`Ogiltig(t) ${n[i.format]??r.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${_(r.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${r.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${r.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};function g_(){return{localeError:HU()}}var KU=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function e(r){return t[r]??null}let n={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${r.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`}case"invalid_value":return r.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${R(r.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${_(r.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${r.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${r.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${i}${r.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${i}${r.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${i.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${r.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${r.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};function h_(){return{localeError:KU()}}var GU=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function e(r){return t[r]??null}let n={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},o={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${r.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${i} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`}case"invalid_value":return r.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${R(r.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=e(r.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${r.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=e(r.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${r.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${i.prefix}"`:i.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${i.suffix}"`:i.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${i.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:i.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${i.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${n[i.format]??r.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${r.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${_(r.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};function y_(){return{localeError:GU()}}var WU=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function e(r){return t[r]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${r.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${i}, al\u0131nan ${a}`}case"invalid_value":return r.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${R(r.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${i}${r.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${i}${r.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Ge\xE7ersiz metin: "${i.prefix}" ile ba\u015Flamal\u0131`:i.format==="ends_with"?`Ge\xE7ersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Ge\xE7ersiz metin: "${i.includes}" i\xE7ermeli`:i.format==="regex"?`Ge\xE7ersiz metin: ${i.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[i.format]??r.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${r.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${r.keys.length>1?"lar":""}: ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${r.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};function v_(){return{localeError:WU()}}var ZU=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function e(r){return t[r]??null}let n={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},o={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${r.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${i}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${R(r.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${i}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} \u0431\u0443\u0434\u0435 ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0456":""}: ${_(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${r.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};function Nl(){return{localeError:ZU()}}function b_(){return Nl()}var qU=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function e(r){return t[r]??null}let n={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},o={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${r.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${i} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return r.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${R(r.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${_(r.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${i}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${i}${r.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u06D2 ${i}${r.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u0627 ${i}${r.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${i.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${r.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${r.keys.length>1?"\u0632":""}: ${_(r.keys,"\u060C ")}`;case"invalid_key":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};function w_(){return{localeError:qU()}}var VU=()=>{let t={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function e(r){return t[r]??null}let n={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},o={nan:"NaN",number:"raqam",array:"massiv"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${r.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${i}, qabul qilingan ${a}`}case"invalid_value":return r.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${R(r.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Juda katta: kutilgan ${r.origin??"qiymat"} ${i}${r.maximum.toString()} ${s.unit} ${s.verb}`:`Juda katta: kutilgan ${r.origin??"qiymat"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Juda kichik: kutilgan ${r.origin} ${i}${r.minimum.toString()} ${s.unit} ${s.verb}`:`Juda kichik: kutilgan ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${i.prefix}" bilan boshlanishi kerak`:i.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${i.suffix}" bilan tugashi kerak`:i.format==="includes"?`Noto\u2018g\u2018ri satr: "${i.includes}" ni o\u2018z ichiga olishi kerak`:i.format==="regex"?`Noto\u2018g\u2018ri satr: ${i.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${n[i.format]??r.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${r.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${r.keys.length>1?"lar":""}: ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${r.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};function k_(){return{localeError:VU()}}var JU=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function e(r){return t[r]??null}let n={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},o={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${r.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${i}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`}case"invalid_value":return r.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${R(r.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${i}${r.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${s.verb} ${i}${r.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${i.prefix}"`:i.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${i.suffix}"`:i.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${i.includes}"`:i.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${i.pattern}`:`${n[i.format]??r.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${r.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${_(r.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};function x_(){return{localeError:JU()}}var YU=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function e(r){return t[r]??null}let n={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},o={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${r.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${i}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return r.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${R(r.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${i}${r.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${i}${r.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.prefix}" \u5F00\u5934`:i.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.suffix}" \u7ED3\u5C3E`:i.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${i.pattern}`:`\u65E0\u6548${n[i.format]??r.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${r.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${_(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${r.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};function S_(){return{localeError:YU()}}var XU=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function e(r){return t[r]??null}let n={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},o={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${r.expected}\uFF0C\u4F46\u6536\u5230 ${a}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${i}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return r.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${R(r.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${i}${r.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${i}${r.maximum.toString()}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${i}${r.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${i}${r.minimum.toString()}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.prefix}" \u958B\u982D`:i.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.suffix}" \u7D50\u5C3E`:i.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${i.pattern}`:`\u7121\u6548\u7684 ${n[i.format]??r.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${r.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${r.keys.length>1?"\u5011":""}\uFF1A${_(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};function __(){return{localeError:XU()}}var QU=()=>{let t={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function e(r){return t[r]??null}let n={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},o={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return r=>{switch(r.code){case"invalid_type":{let i=o[r.expected]??r.expected,s=A(r.input),a=o[s]??s;return/^[A-Z]/.test(r.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${r.expected}, \xE0m\u1ECD\u0300 a r\xED ${a}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${i}, \xE0m\u1ECD\u0300 a r\xED ${a}`}case"invalid_value":return r.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${R(r.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${_(r.values,"|")}`;case"too_big":{let i=r.inclusive?"<=":"<",s=e(r.origin);return s?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${r.origin??"iye"} ${s.verb} ${i}${r.maximum} ${s.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${r.maximum}`}case"too_small":{let i=r.inclusive?">=":">",s=e(r.origin);return s?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${r.origin} ${s.verb} ${i}${r.minimum} ${s.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${r.minimum}`}case"invalid_format":{let i=r;return i.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${i.prefix}"`:i.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${i.suffix}"`:i.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${i.includes}"`:i.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${i.pattern}`:`A\u1E63\xEC\u1E63e: ${n[i.format]??r.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${r.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${_(r.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${r.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${r.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};function I_(){return{localeError:QU()}}var T_,Nh=Symbol("ZodOutput"),Mh=Symbol("ZodInput"),Ml=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let o=n[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let o={...this.get(n)??{}};delete o.id;let r={...o,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ul(){return new Ml}(T_=globalThis).__zod_globalRegistry??(T_.__zod_globalRegistry=Ul());var st=globalThis.__zod_globalRegistry;function Uh(t,e){return new t({type:"string",...D(e)})}function Fh(t,e){return new t({type:"string",coerce:!0,...D(e)})}function Fl(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...D(e)})}function pa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...D(e)})}function Bl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...D(e)})}function jl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(e)})}function zl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(e)})}function Hl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(e)})}function fa(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...D(e)})}function Kl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...D(e)})}function Gl(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(e)})}function Wl(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...D(e)})}function Zl(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(e)})}function ql(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...D(e)})}function Vl(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...D(e)})}function Jl(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(e)})}function Yl(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(e)})}function Xl(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(e)})}function Bh(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...D(e)})}function Ql(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(e)})}function eu(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(e)})}function tu(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...D(e)})}function nu(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...D(e)})}function ru(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...D(e)})}function ou(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...D(e)})}var jh={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function zh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(e)})}function Hh(t,e){return new t({type:"string",format:"date",check:"string_format",...D(e)})}function Kh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...D(e)})}function Gh(t,e){return new t({type:"string",format:"duration",check:"string_format",...D(e)})}function Wh(t,e){return new t({type:"number",checks:[],...D(e)})}function Zh(t,e){return new t({type:"number",coerce:!0,checks:[],...D(e)})}function qh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...D(e)})}function Vh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...D(e)})}function Jh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...D(e)})}function Yh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...D(e)})}function Xh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...D(e)})}function Qh(t,e){return new t({type:"boolean",...D(e)})}function ey(t,e){return new t({type:"boolean",coerce:!0,...D(e)})}function ty(t,e){return new t({type:"bigint",...D(e)})}function ny(t,e){return new t({type:"bigint",coerce:!0,...D(e)})}function ry(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...D(e)})}function oy(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...D(e)})}function iy(t,e){return new t({type:"symbol",...D(e)})}function sy(t,e){return new t({type:"undefined",...D(e)})}function ay(t,e){return new t({type:"null",...D(e)})}function cy(t){return new t({type:"any"})}function ly(t){return new t({type:"unknown"})}function uy(t,e){return new t({type:"never",...D(e)})}function dy(t,e){return new t({type:"void",...D(e)})}function py(t,e){return new t({type:"date",...D(e)})}function fy(t,e){return new t({type:"date",coerce:!0,...D(e)})}function my(t,e){return new t({type:"nan",...D(e)})}function Un(t,e){return new Sl({check:"less_than",...D(e),value:t,inclusive:!1})}function Ut(t,e){return new Sl({check:"less_than",...D(e),value:t,inclusive:!0})}function Fn(t,e){return new _l({check:"greater_than",...D(e),value:t,inclusive:!1})}function yt(t,e){return new _l({check:"greater_than",...D(e),value:t,inclusive:!0})}function iu(t){return Fn(0,t)}function su(t){return Un(0,t)}function au(t){return Ut(0,t)}function cu(t){return yt(0,t)}function Jr(t,e){return new ag({check:"multiple_of",...D(e),value:t})}function Yr(t,e){return new ug({check:"max_size",...D(e),maximum:t})}function Bn(t,e){return new dg({check:"min_size",...D(e),minimum:t})}function Lo(t,e){return new pg({check:"size_equals",...D(e),size:t})}function No(t,e){return new fg({check:"max_length",...D(e),maximum:t})}function fr(t,e){return new mg({check:"min_length",...D(e),minimum:t})}function Mo(t,e){return new gg({check:"length_equals",...D(e),length:t})}function $i(t,e){return new hg({check:"string_format",format:"regex",...D(e),pattern:t})}function Oi(t){return new yg({check:"string_format",format:"lowercase",...D(t)})}function Li(t){return new vg({check:"string_format",format:"uppercase",...D(t)})}function Ni(t,e){return new bg({check:"string_format",format:"includes",...D(e),includes:t})}function Mi(t,e){return new wg({check:"string_format",format:"starts_with",...D(e),prefix:t})}function Ui(t,e){return new kg({check:"string_format",format:"ends_with",...D(e),suffix:t})}function lu(t,e,n){return new xg({check:"property",property:t,schema:e,...D(n)})}function Fi(t,e){return new Sg({check:"mime_type",mime:t,...D(e)})}function gn(t){return new _g({check:"overwrite",tx:t})}function Bi(t){return gn(e=>e.normalize(t))}function ji(){return gn(t=>t.trim())}function zi(){return gn(t=>t.toLowerCase())}function Hi(){return gn(t=>t.toUpperCase())}function Ki(){return gn(t=>wm(t))}function gy(t,e,n){return new t({type:"array",element:e,...D(n)})}function tF(t,e,n){return new t({type:"union",options:e,...D(n)})}function nF(t,e,n){return new t({type:"union",options:e,inclusive:!1,...D(n)})}function rF(t,e,n,o){return new t({type:"union",options:n,discriminator:e,...D(o)})}function oF(t,e,n){return new t({type:"intersection",left:e,right:n})}function iF(t,e,n,o){let r=n instanceof V,i=r?o:n,s=r?n:null;return new t({type:"tuple",items:e,rest:s,...D(i)})}function sF(t,e,n,o){return new t({type:"record",keyType:e,valueType:n,...D(o)})}function aF(t,e,n,o){return new t({type:"map",keyType:e,valueType:n,...D(o)})}function cF(t,e,n){return new t({type:"set",valueType:e,...D(n)})}function lF(t,e,n){let o=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new t({type:"enum",entries:o,...D(n)})}function uF(t,e,n){return new t({type:"enum",entries:e,...D(n)})}function dF(t,e,n){return new t({type:"literal",values:Array.isArray(e)?e:[e],...D(n)})}function hy(t,e){return new t({type:"file",...D(e)})}function pF(t,e){return new t({type:"transform",transform:e})}function fF(t,e){return new t({type:"optional",innerType:e})}function mF(t,e){return new t({type:"nullable",innerType:e})}function gF(t,e,n){return new t({type:"default",innerType:e,get defaultValue(){return typeof n=="function"?n():xm(n)}})}function hF(t,e,n){return new t({type:"nonoptional",innerType:e,...D(n)})}function yF(t,e){return new t({type:"success",innerType:e})}function vF(t,e,n){return new t({type:"catch",innerType:e,catchValue:typeof n=="function"?n:()=>n})}function bF(t,e,n){return new t({type:"pipe",in:e,out:n})}function wF(t,e){return new t({type:"readonly",innerType:e})}function kF(t,e,n){return new t({type:"template_literal",parts:e,...D(n)})}function xF(t,e){return new t({type:"lazy",getter:e})}function SF(t,e){return new t({type:"promise",innerType:e})}function yy(t,e,n){let o=D(n);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function vy(t,e,n){return new t({type:"custom",check:"custom",fn:e,...D(n)})}function by(t,e){let n=E_(o=>(o.addIssue=r=>{if(typeof r=="string")o.issues.push(Ti(r,o.value,n._zod.def));else{let i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),o.issues.push(Ti(i))}},t(o.value,o)),e);return n}function E_(t,e){let n=new be({check:"custom",...D(e)});return n._zod.check=t,n}function wy(t){let e=new be({check:"describe"});return e._zod.onattach=[n=>{let o=st.get(n)??{};st.add(n,{...o,description:t})}],e._zod.check=()=>{},e}function ky(t){let e=new be({check:"meta"});return e._zod.onattach=[n=>{let o=st.get(n)??{};st.add(n,{...o,...t})}],e._zod.check=()=>{},e}function xy(t,e){let n=D(e),o=n.truthy??["true","1","yes","on","y","enabled"],r=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(o=o.map(m=>typeof m=="string"?m.toLowerCase():m),r=r.map(m=>typeof m=="string"?m.toLowerCase():m));let i=new Set(o),s=new Set(r),a=t.Codec??la,c=t.Boolean??aa,l=t.String??Oo,u=new l({type:"string",error:n.error}),d=new c({type:"boolean",error:n.error}),f=new a({type:"pipe",in:u,out:d,transform:((m,g)=>{let h=m;return n.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:s.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((m,g)=>m===!0?o[0]||"true":r[0]||"false"),error:n.error});return f}function Gi(t,e,n,o={}){let r=D(o),i={...D(o),check:"string_format",type:"string",format:e,fn:typeof n=="function"?n:a=>n.test(a),...r};return n instanceof RegExp&&(i.pattern=n),new t(i)}function Xr(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??st,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function fe(t,e,n={path:[],schemaPath:[]}){var o;let r=t._zod.def,i=e.seen.get(t);if(i)return i.count++,n.schemaPath.includes(t)&&(i.cycle=n.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,s);let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,u);else{let f=s.schema,m=e.processors[r.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);m(t,e,f,u)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),fe(d,e,u),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),e.io==="input"&&vt(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function Qr(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let r=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(g=>g);if(d)return{ref:f(d)};let m=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=m,{defId:m,ref:`${f("__shared")}#/${a}/${m}`}}if(s[1]===n)return{ref:"#"};let l=`#/${a}/`,u=s[1].schema.id??`__schema${t.counter++}`;return{defId:u,ref:l+u}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:l}=r(s);a.def={...a.schema},l&&(a.defId=l);let u=a.schema;for(let d in u)delete u[d];u.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
161
+
162
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let l=t.external.registry.get(s[0])?.id;if(e!==s[0]&&l){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function eo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){o(d);let m=t.seen.get(d),g=m.schema;if(g.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(g)):Object.assign(l,g),Object.assign(l,u),a._zod.parent===d)for(let y in l)y==="$ref"||y==="allOf"||y in u||delete l[y];if(g.$ref&&m.def)for(let y in l)y==="$ref"||y==="allOf"||y in m.def&&JSON.stringify(l[y])===JSON.stringify(m.def[y])&&delete l[y]}let f=a._zod.parent;if(f&&f!==d){o(f);let m=t.seen.get(f);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(let g in l)g==="$ref"||g==="allOf"||g in m.def&&JSON.stringify(l[g])===JSON.stringify(m.def[g])&&delete l[g]}t.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())o(a[0]);let r={};if(t.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");r.$id=t.external.uri(a)}Object.assign(r,n.def??n.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&r.id===i&&delete r.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Wi(e,"input",t.processors),output:Wi(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function vt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return vt(o.element,n);if(o.type==="set")return vt(o.valueType,n);if(o.type==="lazy")return vt(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return vt(o.innerType,n);if(o.type==="intersection")return vt(o.left,n)||vt(o.right,n);if(o.type==="record"||o.type==="map")return vt(o.keyType,n)||vt(o.valueType,n);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:vt(o.in,n)||vt(o.out,n);if(o.type==="object"){for(let r in o.shape)if(vt(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(vt(r,n))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(vt(r,n))return!0;return!!(o.rest&&vt(o.rest,n))}return!1}var Sy=(t,e={})=>n=>{let o=Xr({...n,processors:e});return fe(t,o),Qr(o,t),eo(o,t)},Wi=(t,e,n={})=>o=>{let{libraryOptions:r,target:i}=o??{},s=Xr({...r??{},target:i,io:e,processors:n});return fe(t,s),Qr(s,t),eo(s,t)};var _F={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_y=(t,e,n,o)=>{let r=n;r.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=t._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),a&&(r.format=_F[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){let u=[...c];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Iy=(t,e,n,o)=>{let r=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=t._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof l=="number"&&l<=(s??Number.POSITIVE_INFINITY),m=e.target==="draft-04"||e.target==="openapi-3.0";d?m?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:typeof i=="number"&&(r.minimum=i),f?m?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:typeof s=="number"&&(r.maximum=s),typeof c=="number"&&(r.multipleOf=c)},Ty=(t,e,n,o)=>{n.type="boolean"},Ey=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Cy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Ry=(t,e,n,o)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ay=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Py=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Dy=(t,e,n,o)=>{n.not={}},$y=(t,e,n,o)=>{},Oy=(t,e,n,o)=>{},Ly=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Ny=(t,e,n,o)=>{let r=t._zod.def,i=Js(r.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},My=(t,e,n,o)=>{let r=t._zod.def,i=[];for(let s of r.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},Uy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Fy=(t,e,n,o)=>{let r=n,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=i.source},By=(t,e,n,o)=>{let r=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=t._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),c?c.length===1?(i.contentMediaType=c[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(r,i)},jy=(t,e,n,o)=>{n.type="boolean"},zy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Hy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Ky=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Gy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Wy=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Zy=(t,e,n,o)=>{let r=n,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(r.minItems=s),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=fe(i.element,e,{...o,path:[...o.path,"items"]})},qy=(t,e,n,o)=>{let r=n,i=t._zod.def;r.type="object",r.properties={};let s=i.shape;for(let l in s)r.properties[l]=fe(s[l],e,{...o,path:[...o.path,"properties",l]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(l=>{let u=i.shape[l]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=fe(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(r.additionalProperties=!1)},du=(t,e,n,o)=>{let r=t._zod.def,i=r.inclusive===!1,s=r.options.map((a,c)=>fe(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},Vy=(t,e,n,o)=>{let r=t._zod.def,i=fe(r.left,e,{...o,path:[...o.path,"allOf",0]}),s=fe(r.right,e,{...o,path:[...o.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},Jy=(t,e,n,o)=>{let r=n,i=t._zod.def;r.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((f,m)=>fe(f,e,{...o,path:[...o.path,s,m]})),l=i.rest?fe(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(r.prefixItems=c,l&&(r.items=l)):e.target==="openapi-3.0"?(r.items={anyOf:c},l&&r.items.anyOf.push(l),r.minItems=c.length,l||(r.maxItems=c.length)):(r.items=c,l&&(r.additionalItems=l));let{minimum:u,maximum:d}=t._zod.bag;typeof u=="number"&&(r.minItems=u),typeof d=="number"&&(r.maxItems=d)},Yy=(t,e,n,o)=>{let r=n,i=t._zod.def;r.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let u=fe(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let d of c)r.patternProperties[d.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(r.propertyNames=fe(i.keyType,e,{...o,path:[...o.path,"propertyNames"]})),r.additionalProperties=fe(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let l=s._zod.values;if(l){let u=[...l].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(r.required=u)}},Xy=(t,e,n,o)=>{let r=t._zod.def,i=fe(r.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},Qy=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType},ev=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},tv=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},nv=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},rv=(t,e,n,o)=>{let r=t._zod.def,i=r.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?r.out:r.in:r.out;fe(s,e,o);let a=e.seen.get(t);a.ref=s},ov=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType,n.readOnly=!0},iv=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType},pu=(t,e,n,o)=>{let r=t._zod.def;fe(r.innerType,e,o);let i=e.seen.get(t);i.ref=r.innerType},sv=(t,e,n,o)=>{let r=t._zod.innerType;fe(r,e,o);let i=e.seen.get(t);i.ref=r},uu={string:_y,number:Iy,boolean:Ty,bigint:Ey,symbol:Cy,null:Ry,undefined:Ay,void:Py,never:Dy,any:$y,unknown:Oy,date:Ly,enum:Ny,literal:My,nan:Uy,template_literal:Fy,file:By,success:jy,custom:zy,function:Hy,transform:Ky,map:Gy,set:Wy,array:Zy,object:qy,union:du,intersection:Vy,tuple:Jy,record:Yy,nullable:Xy,nonoptional:Qy,default:ev,prefault:tv,catch:nv,pipe:rv,readonly:ov,promise:iv,optional:pu,lazy:sv};function fu(t,e){if("_idmap"in t){let o=t,r=Xr({...e,processors:uu}),i={};for(let c of o._idmap.entries()){let[l,u]=c;fe(u,r)}let s={},a={registry:o,uri:e?.uri,defs:i};r.external=a;for(let c of o._idmap.entries()){let[l,u]=c;Qr(r,u),s[l]=eo(r,u)}if(Object.keys(i).length>0){let c=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let n=Xr({...e,processors:uu});return fe(t,n),Qr(n,t),eo(n,t)}var mu=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=Xr({processors:uu,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return fe(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),Qr(this.ctx,e);let o=eo(this.ctx,e),{"~standard":r,...i}=o;return i}};var C_={};var ma={};Xt(ma,{ZodAny:()=>Av,ZodArray:()=>Ov,ZodBase64:()=>Lu,ZodBase64URL:()=>Nu,ZodBigInt:()=>es,ZodBigIntFormat:()=>Fu,ZodBoolean:()=>Qi,ZodCIDRv4:()=>$u,ZodCIDRv6:()=>Ou,ZodCUID:()=>Tu,ZodCUID2:()=>Eu,ZodCatch:()=>nb,ZodCodec:()=>Ta,ZodCustom:()=>Ea,ZodCustomStringFormat:()=>Yi,ZodDate:()=>ka,ZodDefault:()=>Jv,ZodDiscriminatedUnion:()=>Nv,ZodE164:()=>Mu,ZodEmail:()=>Su,ZodEmoji:()=>_u,ZodEnum:()=>Vi,ZodExactOptional:()=>Zv,ZodFile:()=>Gv,ZodFunction:()=>pb,ZodGUID:()=>ha,ZodIPv4:()=>Pu,ZodIPv6:()=>Du,ZodIntersection:()=>Mv,ZodJWT:()=>Uu,ZodKSUID:()=>Au,ZodLazy:()=>lb,ZodLiteral:()=>Kv,ZodMAC:()=>Sv,ZodMap:()=>zv,ZodNaN:()=>ob,ZodNanoID:()=>Iu,ZodNever:()=>Dv,ZodNonOptional:()=>Gu,ZodNull:()=>Cv,ZodNullable:()=>Vv,ZodNumber:()=>Xi,ZodNumberFormat:()=>Fo,ZodObject:()=>Sa,ZodOptional:()=>Ku,ZodPipe:()=>Ia,ZodPrefault:()=>Xv,ZodPreprocess:()=>ib,ZodPromise:()=>db,ZodReadonly:()=>sb,ZodRecord:()=>qi,ZodSet:()=>Hv,ZodString:()=>Ji,ZodStringFormat:()=>ge,ZodSuccess:()=>tb,ZodSymbol:()=>Tv,ZodTemplateLiteral:()=>cb,ZodTransform:()=>Wv,ZodTuple:()=>Fv,ZodType:()=>J,ZodULID:()=>Cu,ZodURL:()=>wa,ZodUUID:()=>jn,ZodUndefined:()=>Ev,ZodUnion:()=>_a,ZodUnknown:()=>Pv,ZodVoid:()=>$v,ZodXID:()=>Ru,ZodXor:()=>Lv,_ZodString:()=>xu,_default:()=>Yv,_function:()=>MI,any:()=>mI,array:()=>xa,base64:()=>Y_,base64url:()=>X_,bigint:()=>lI,boolean:()=>Iv,catch:()=>rb,check:()=>UI,cidrv4:()=>V_,cidrv6:()=>J_,codec:()=>$I,cuid:()=>j_,cuid2:()=>z_,custom:()=>FI,date:()=>hI,describe:()=>BI,discriminatedUnion:()=>xI,e164:()=>Q_,email:()=>P_,emoji:()=>F_,enum:()=>zu,exactOptional:()=>qv,file:()=>RI,float32:()=>iI,float64:()=>sI,function:()=>MI,guid:()=>D_,hash:()=>oI,hex:()=>rI,hostname:()=>nI,httpUrl:()=>U_,instanceof:()=>zI,int:()=>wu,int32:()=>aI,int64:()=>uI,intersection:()=>Uv,invertCodec:()=>OI,ipv4:()=>W_,ipv6:()=>q_,json:()=>KI,jwt:()=>eI,keyof:()=>yI,ksuid:()=>G_,lazy:()=>ub,literal:()=>CI,looseObject:()=>wI,looseRecord:()=>_I,mac:()=>Z_,map:()=>II,meta:()=>jI,nan:()=>DI,nanoid:()=>B_,nativeEnum:()=>EI,never:()=>Bu,nonoptional:()=>eb,null:()=>Rv,nullable:()=>va,nullish:()=>AI,number:()=>_v,object:()=>vI,optional:()=>ya,partialRecord:()=>SI,pipe:()=>ku,prefault:()=>Qv,preprocess:()=>GI,promise:()=>NI,readonly:()=>ab,record:()=>jv,refine:()=>fb,set:()=>TI,strictObject:()=>bI,string:()=>ga,stringFormat:()=>tI,stringbool:()=>HI,success:()=>PI,superRefine:()=>mb,symbol:()=>pI,templateLiteral:()=>LI,transform:()=>Hu,tuple:()=>Bv,uint32:()=>cI,uint64:()=>dI,ulid:()=>H_,undefined:()=>fI,union:()=>ju,unknown:()=>Uo,url:()=>M_,uuid:()=>$_,uuidv4:()=>O_,uuidv6:()=>L_,uuidv7:()=>N_,void:()=>gI,xid:()=>K_,xor:()=>kI});var gu={};Xt(gu,{endsWith:()=>Ui,gt:()=>Fn,gte:()=>yt,includes:()=>Ni,length:()=>Mo,lowercase:()=>Oi,lt:()=>Un,lte:()=>Ut,maxLength:()=>No,maxSize:()=>Yr,mime:()=>Fi,minLength:()=>fr,minSize:()=>Bn,multipleOf:()=>Jr,negative:()=>su,nonnegative:()=>cu,nonpositive:()=>au,normalize:()=>Bi,overwrite:()=>gn,positive:()=>iu,property:()=>lu,regex:()=>$i,size:()=>Lo,slugify:()=>Ki,startsWith:()=>Mi,toLowerCase:()=>zi,toUpperCase:()=>Hi,trim:()=>ji,uppercase:()=>Li});var Zi={};Xt(Zi,{ZodISODate:()=>yu,ZodISODateTime:()=>hu,ZodISODuration:()=>bu,ZodISOTime:()=>vu,date:()=>cv,datetime:()=>av,duration:()=>uv,time:()=>lv});var hu=k("ZodISODateTime",(t,e)=>{Ug.init(t,e),ge.init(t,e)});function av(t){return zh(hu,t)}var yu=k("ZodISODate",(t,e)=>{Fg.init(t,e),ge.init(t,e)});function cv(t){return Hh(yu,t)}var vu=k("ZodISOTime",(t,e)=>{Bg.init(t,e),ge.init(t,e)});function lv(t){return Kh(vu,t)}var bu=k("ZodISODuration",(t,e)=>{jg.init(t,e),ge.init(t,e)});function uv(t){return Gh(bu,t)}var R_=(t,e)=>{ta.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ra(t,n)},flatten:{value:n=>na(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,_i,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,_i,2)}},isEmpty:{get(){return t.issues.length===0}}})},TF=k("ZodError",R_),Tt=k("ZodError",R_,{Parent:Error});var dv=Ei(Tt),pv=Ci(Tt),fv=Ri(Tt),mv=Ai(Tt),gv=fl(Tt),hv=ml(Tt),yv=gl(Tt),vv=hl(Tt),bv=yl(Tt),wv=vl(Tt),kv=bl(Tt),xv=wl(Tt);var A_=new WeakMap;function ba(t,e,n){let o=Object.getPrototypeOf(t),r=A_.get(o);if(r||(r=new Set,A_.set(o,r)),!r.has(e)){r.add(e);for(let i in n){let s=n[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var J=k("ZodType",(t,e)=>(V.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Wi(t,"input"),output:Wi(t,"output")}}),t.toJSONSchema=Sy(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,o)=>dv(t,n,o,{callee:t.parse}),t.safeParse=(n,o)=>fv(t,n,o),t.parseAsync=async(n,o)=>pv(t,n,o,{callee:t.parseAsync}),t.safeParseAsync=async(n,o)=>mv(t,n,o),t.spa=t.safeParseAsync,t.encode=(n,o)=>gv(t,n,o),t.decode=(n,o)=>hv(t,n,o),t.encodeAsync=async(n,o)=>yv(t,n,o),t.decodeAsync=async(n,o)=>vv(t,n,o),t.safeEncode=(n,o)=>bv(t,n,o),t.safeDecode=(n,o)=>wv(t,n,o),t.safeEncodeAsync=async(n,o)=>kv(t,n,o),t.safeDecodeAsync=async(n,o)=>xv(t,n,o),ba(t,"ZodType",{check(...n){let o=this.def;return this.clone(P.mergeDefs(o,{checks:[...o.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,o){return gt(this,n,o)},brand(){return this},register(n,o){return n.add(this,o),this},refine(n,o){return this.check(fb(n,o))},superRefine(n,o){return this.check(mb(n,o))},overwrite(n){return this.check(gn(n))},optional(){return ya(this)},exactOptional(){return qv(this)},nullable(){return va(this)},nullish(){return ya(va(this))},nonoptional(n){return eb(this,n)},array(){return xa(this)},or(n){return ju([this,n])},and(n){return Uv(this,n)},transform(n){return ku(this,Hu(n))},default(n){return Yv(this,n)},prefault(n){return Qv(this,n)},catch(n){return rb(this,n)},pipe(n){return ku(this,n)},readonly(){return ab(this)},describe(n){let o=this.clone();return st.add(o,{description:n}),o},meta(...n){if(n.length===0)return st.get(this);let o=this.clone();return st.add(o,n[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return st.get(t)?.description},configurable:!0}),t)),xu=k("_ZodString",(t,e)=>{Oo.init(t,e),J.init(t,e),t._zod.processJSONSchema=(o,r,i)=>_y(t,o,r,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,ba(t,"_ZodString",{regex(...o){return this.check($i(...o))},includes(...o){return this.check(Ni(...o))},startsWith(...o){return this.check(Mi(...o))},endsWith(...o){return this.check(Ui(...o))},min(...o){return this.check(fr(...o))},max(...o){return this.check(No(...o))},length(...o){return this.check(Mo(...o))},nonempty(...o){return this.check(fr(1,...o))},lowercase(o){return this.check(Oi(o))},uppercase(o){return this.check(Li(o))},trim(){return this.check(ji())},normalize(...o){return this.check(Bi(...o))},toLowerCase(){return this.check(zi())},toUpperCase(){return this.check(Hi())},slugify(){return this.check(Ki())}})}),Ji=k("ZodString",(t,e)=>{Oo.init(t,e),xu.init(t,e),t.email=n=>t.check(Fl(Su,n)),t.url=n=>t.check(fa(wa,n)),t.jwt=n=>t.check(ou(Uu,n)),t.emoji=n=>t.check(Kl(_u,n)),t.guid=n=>t.check(pa(ha,n)),t.uuid=n=>t.check(Bl(jn,n)),t.uuidv4=n=>t.check(jl(jn,n)),t.uuidv6=n=>t.check(zl(jn,n)),t.uuidv7=n=>t.check(Hl(jn,n)),t.nanoid=n=>t.check(Gl(Iu,n)),t.guid=n=>t.check(pa(ha,n)),t.cuid=n=>t.check(Wl(Tu,n)),t.cuid2=n=>t.check(Zl(Eu,n)),t.ulid=n=>t.check(ql(Cu,n)),t.base64=n=>t.check(tu(Lu,n)),t.base64url=n=>t.check(nu(Nu,n)),t.xid=n=>t.check(Vl(Ru,n)),t.ksuid=n=>t.check(Jl(Au,n)),t.ipv4=n=>t.check(Yl(Pu,n)),t.ipv6=n=>t.check(Xl(Du,n)),t.cidrv4=n=>t.check(Ql($u,n)),t.cidrv6=n=>t.check(eu(Ou,n)),t.e164=n=>t.check(ru(Mu,n)),t.datetime=n=>t.check(av(n)),t.date=n=>t.check(cv(n)),t.time=n=>t.check(lv(n)),t.duration=n=>t.check(uv(n))});function ga(t){return Uh(Ji,t)}var ge=k("ZodStringFormat",(t,e)=>{me.init(t,e),xu.init(t,e)}),Su=k("ZodEmail",(t,e)=>{Rg.init(t,e),ge.init(t,e)});function P_(t){return Fl(Su,t)}var ha=k("ZodGUID",(t,e)=>{Eg.init(t,e),ge.init(t,e)});function D_(t){return pa(ha,t)}var jn=k("ZodUUID",(t,e)=>{Cg.init(t,e),ge.init(t,e)});function $_(t){return Bl(jn,t)}function O_(t){return jl(jn,t)}function L_(t){return zl(jn,t)}function N_(t){return Hl(jn,t)}var wa=k("ZodURL",(t,e)=>{Ag.init(t,e),ge.init(t,e)});function M_(t){return fa(wa,t)}function U_(t){return fa(wa,{protocol:Mt.httpProtocol,hostname:Mt.domain,...P.normalizeParams(t)})}var _u=k("ZodEmoji",(t,e)=>{Pg.init(t,e),ge.init(t,e)});function F_(t){return Kl(_u,t)}var Iu=k("ZodNanoID",(t,e)=>{Dg.init(t,e),ge.init(t,e)});function B_(t){return Gl(Iu,t)}var Tu=k("ZodCUID",(t,e)=>{$g.init(t,e),ge.init(t,e)});function j_(t){return Wl(Tu,t)}var Eu=k("ZodCUID2",(t,e)=>{Og.init(t,e),ge.init(t,e)});function z_(t){return Zl(Eu,t)}var Cu=k("ZodULID",(t,e)=>{Lg.init(t,e),ge.init(t,e)});function H_(t){return ql(Cu,t)}var Ru=k("ZodXID",(t,e)=>{Ng.init(t,e),ge.init(t,e)});function K_(t){return Vl(Ru,t)}var Au=k("ZodKSUID",(t,e)=>{Mg.init(t,e),ge.init(t,e)});function G_(t){return Jl(Au,t)}var Pu=k("ZodIPv4",(t,e)=>{zg.init(t,e),ge.init(t,e)});function W_(t){return Yl(Pu,t)}var Sv=k("ZodMAC",(t,e)=>{Kg.init(t,e),ge.init(t,e)});function Z_(t){return Bh(Sv,t)}var Du=k("ZodIPv6",(t,e)=>{Hg.init(t,e),ge.init(t,e)});function q_(t){return Xl(Du,t)}var $u=k("ZodCIDRv4",(t,e)=>{Gg.init(t,e),ge.init(t,e)});function V_(t){return Ql($u,t)}var Ou=k("ZodCIDRv6",(t,e)=>{Wg.init(t,e),ge.init(t,e)});function J_(t){return eu(Ou,t)}var Lu=k("ZodBase64",(t,e)=>{qg.init(t,e),ge.init(t,e)});function Y_(t){return tu(Lu,t)}var Nu=k("ZodBase64URL",(t,e)=>{Vg.init(t,e),ge.init(t,e)});function X_(t){return nu(Nu,t)}var Mu=k("ZodE164",(t,e)=>{Jg.init(t,e),ge.init(t,e)});function Q_(t){return ru(Mu,t)}var Uu=k("ZodJWT",(t,e)=>{Yg.init(t,e),ge.init(t,e)});function eI(t){return ou(Uu,t)}var Yi=k("ZodCustomStringFormat",(t,e)=>{Xg.init(t,e),ge.init(t,e)});function tI(t,e,n={}){return Gi(Yi,t,e,n)}function nI(t){return Gi(Yi,"hostname",Mt.hostname,t)}function rI(t){return Gi(Yi,"hex",Mt.hex,t)}function oI(t,e){let n=e?.enc??"hex",o=`${t}_${n}`,r=Mt[o];if(!r)throw new Error(`Unrecognized hash format: ${o}`);return Gi(Yi,o,r,e)}var Xi=k("ZodNumber",(t,e)=>{Rl.init(t,e),J.init(t,e),t._zod.processJSONSchema=(o,r,i)=>Iy(t,o,r,i),ba(t,"ZodNumber",{gt(o,r){return this.check(Fn(o,r))},gte(o,r){return this.check(yt(o,r))},min(o,r){return this.check(yt(o,r))},lt(o,r){return this.check(Un(o,r))},lte(o,r){return this.check(Ut(o,r))},max(o,r){return this.check(Ut(o,r))},int(o){return this.check(wu(o))},safe(o){return this.check(wu(o))},positive(o){return this.check(Fn(0,o))},nonnegative(o){return this.check(yt(0,o))},negative(o){return this.check(Un(0,o))},nonpositive(o){return this.check(Ut(0,o))},multipleOf(o,r){return this.check(Jr(o,r))},step(o,r){return this.check(Jr(o,r))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function _v(t){return Wh(Xi,t)}var Fo=k("ZodNumberFormat",(t,e)=>{Qg.init(t,e),Xi.init(t,e)});function wu(t){return qh(Fo,t)}function iI(t){return Vh(Fo,t)}function sI(t){return Jh(Fo,t)}function aI(t){return Yh(Fo,t)}function cI(t){return Xh(Fo,t)}var Qi=k("ZodBoolean",(t,e)=>{aa.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ty(t,n,o,r)});function Iv(t){return Qh(Qi,t)}var es=k("ZodBigInt",(t,e)=>{Al.init(t,e),J.init(t,e),t._zod.processJSONSchema=(o,r,i)=>Ey(t,o,r,i),t.gte=(o,r)=>t.check(yt(o,r)),t.min=(o,r)=>t.check(yt(o,r)),t.gt=(o,r)=>t.check(Fn(o,r)),t.gte=(o,r)=>t.check(yt(o,r)),t.min=(o,r)=>t.check(yt(o,r)),t.lt=(o,r)=>t.check(Un(o,r)),t.lte=(o,r)=>t.check(Ut(o,r)),t.max=(o,r)=>t.check(Ut(o,r)),t.positive=o=>t.check(Fn(BigInt(0),o)),t.negative=o=>t.check(Un(BigInt(0),o)),t.nonpositive=o=>t.check(Ut(BigInt(0),o)),t.nonnegative=o=>t.check(yt(BigInt(0),o)),t.multipleOf=(o,r)=>t.check(Jr(o,r));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function lI(t){return ty(es,t)}var Fu=k("ZodBigIntFormat",(t,e)=>{eh.init(t,e),es.init(t,e)});function uI(t){return ry(Fu,t)}function dI(t){return oy(Fu,t)}var Tv=k("ZodSymbol",(t,e)=>{th.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Cy(t,n,o,r)});function pI(t){return iy(Tv,t)}var Ev=k("ZodUndefined",(t,e)=>{nh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ay(t,n,o,r)});function fI(t){return sy(Ev,t)}var Cv=k("ZodNull",(t,e)=>{rh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ry(t,n,o,r)});function Rv(t){return ay(Cv,t)}var Av=k("ZodAny",(t,e)=>{oh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>$y(t,n,o,r)});function mI(){return cy(Av)}var Pv=k("ZodUnknown",(t,e)=>{ih.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Oy(t,n,o,r)});function Uo(){return ly(Pv)}var Dv=k("ZodNever",(t,e)=>{sh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Dy(t,n,o,r)});function Bu(t){return uy(Dv,t)}var $v=k("ZodVoid",(t,e)=>{ah.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Py(t,n,o,r)});function gI(t){return dy($v,t)}var ka=k("ZodDate",(t,e)=>{ch.init(t,e),J.init(t,e),t._zod.processJSONSchema=(o,r,i)=>Ly(t,o,r,i),t.min=(o,r)=>t.check(yt(o,r)),t.max=(o,r)=>t.check(Ut(o,r));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});function hI(t){return py(ka,t)}var Ov=k("ZodArray",(t,e)=>{lh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Zy(t,n,o,r),t.element=e.element,ba(t,"ZodArray",{min(n,o){return this.check(fr(n,o))},nonempty(n){return this.check(fr(1,n))},max(n,o){return this.check(No(n,o))},length(n,o){return this.check(Mo(n,o))},unwrap(){return this.element}})});function xa(t,e){return gy(Ov,t,e)}function yI(t){let e=t._zod.def.shape;return zu(Object.keys(e))}var Sa=k("ZodObject",(t,e)=>{uh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>qy(t,n,o,r),P.defineLazy(t,"shape",()=>e.shape),ba(t,"ZodObject",{keyof(){return zu(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Uo()})},loose(){return this.clone({...this._zod.def,catchall:Uo()})},strict(){return this.clone({...this._zod.def,catchall:Bu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return P.extend(this,n)},safeExtend(n){return P.safeExtend(this,n)},merge(n){return P.merge(this,n)},pick(n){return P.pick(this,n)},omit(n){return P.omit(this,n)},partial(...n){return P.partial(Ku,this,n[0])},required(...n){return P.required(Gu,this,n[0])}})});function vI(t,e){let n={type:"object",shape:t??{},...P.normalizeParams(e)};return new Sa(n)}function bI(t,e){return new Sa({type:"object",shape:t,catchall:Bu(),...P.normalizeParams(e)})}function wI(t,e){return new Sa({type:"object",shape:t,catchall:Uo(),...P.normalizeParams(e)})}var _a=k("ZodUnion",(t,e)=>{ca.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>du(t,n,o,r),t.options=e.options});function ju(t,e){return new _a({type:"union",options:t,...P.normalizeParams(e)})}var Lv=k("ZodXor",(t,e)=>{_a.init(t,e),dh.init(t,e),t._zod.processJSONSchema=(n,o,r)=>du(t,n,o,r),t.options=e.options});function kI(t,e){return new Lv({type:"union",options:t,inclusive:!1,...P.normalizeParams(e)})}var Nv=k("ZodDiscriminatedUnion",(t,e)=>{_a.init(t,e),ph.init(t,e)});function xI(t,e,n){return new Nv({type:"union",options:e,discriminator:t,...P.normalizeParams(n)})}var Mv=k("ZodIntersection",(t,e)=>{fh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Vy(t,n,o,r)});function Uv(t,e){return new Mv({type:"intersection",left:t,right:e})}var Fv=k("ZodTuple",(t,e)=>{Pl.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Jy(t,n,o,r),t.rest=n=>t.clone({...t._zod.def,rest:n})});function Bv(t,e,n){let o=e instanceof V,r=o?n:e,i=o?e:null;return new Fv({type:"tuple",items:t,rest:i,...P.normalizeParams(r)})}var qi=k("ZodRecord",(t,e)=>{mh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Yy(t,n,o,r),t.keyType=e.keyType,t.valueType=e.valueType});function jv(t,e,n){return!e||!e._zod?new qi({type:"record",keyType:ga(),valueType:t,...P.normalizeParams(e)}):new qi({type:"record",keyType:t,valueType:e,...P.normalizeParams(n)})}function SI(t,e,n){let o=gt(t);return o._zod.values=void 0,new qi({type:"record",keyType:o,valueType:e,...P.normalizeParams(n)})}function _I(t,e,n){return new qi({type:"record",keyType:t,valueType:e,mode:"loose",...P.normalizeParams(n)})}var zv=k("ZodMap",(t,e)=>{gh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Gy(t,n,o,r),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Bn(...n)),t.nonempty=n=>t.check(Bn(1,n)),t.max=(...n)=>t.check(Yr(...n)),t.size=(...n)=>t.check(Lo(...n))});function II(t,e,n){return new zv({type:"map",keyType:t,valueType:e,...P.normalizeParams(n)})}var Hv=k("ZodSet",(t,e)=>{hh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Wy(t,n,o,r),t.min=(...n)=>t.check(Bn(...n)),t.nonempty=n=>t.check(Bn(1,n)),t.max=(...n)=>t.check(Yr(...n)),t.size=(...n)=>t.check(Lo(...n))});function TI(t,e){return new Hv({type:"set",valueType:t,...P.normalizeParams(e)})}var Vi=k("ZodEnum",(t,e)=>{yh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(o,r,i)=>Ny(t,o,r,i),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(o,r)=>{let i={};for(let s of o)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Vi({...e,checks:[],...P.normalizeParams(r),entries:i})},t.exclude=(o,r)=>{let i={...e.entries};for(let s of o)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Vi({...e,checks:[],...P.normalizeParams(r),entries:i})}});function zu(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Vi({type:"enum",entries:n,...P.normalizeParams(e)})}function EI(t,e){return new Vi({type:"enum",entries:t,...P.normalizeParams(e)})}var Kv=k("ZodLiteral",(t,e)=>{vh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>My(t,n,o,r),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function CI(t,e){return new Kv({type:"literal",values:Array.isArray(t)?t:[t],...P.normalizeParams(e)})}var Gv=k("ZodFile",(t,e)=>{bh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>By(t,n,o,r),t.min=(n,o)=>t.check(Bn(n,o)),t.max=(n,o)=>t.check(Yr(n,o)),t.mime=(n,o)=>t.check(Fi(Array.isArray(n)?n:[n],o))});function RI(t){return hy(Gv,t)}var Wv=k("ZodTransform",(t,e)=>{wh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Ky(t,n,o,r),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Gr(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(P.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(P.issue(s))}};let r=e.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Hu(t){return new Wv({type:"transform",transform:t})}var Ku=k("ZodOptional",(t,e)=>{Dl.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>pu(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function ya(t){return new Ku({type:"optional",innerType:t})}var Zv=k("ZodExactOptional",(t,e)=>{kh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>pu(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function qv(t){return new Zv({type:"optional",innerType:t})}var Vv=k("ZodNullable",(t,e)=>{xh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Xy(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function va(t){return new Vv({type:"nullable",innerType:t})}function AI(t){return ya(va(t))}var Jv=k("ZodDefault",(t,e)=>{Sh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ev(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Yv(t,e){return new Jv({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():P.shallowClone(e)}})}var Xv=k("ZodPrefault",(t,e)=>{_h.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>tv(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function Qv(t,e){return new Xv({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():P.shallowClone(e)}})}var Gu=k("ZodNonOptional",(t,e)=>{Ih.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Qy(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function eb(t,e){return new Gu({type:"nonoptional",innerType:t,...P.normalizeParams(e)})}var tb=k("ZodSuccess",(t,e)=>{Th.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>jy(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function PI(t){return new tb({type:"success",innerType:t})}var nb=k("ZodCatch",(t,e)=>{Eh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>nv(t,n,o,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function rb(t,e){return new nb({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var ob=k("ZodNaN",(t,e)=>{Ch.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Uy(t,n,o,r)});function DI(t){return my(ob,t)}var Ia=k("ZodPipe",(t,e)=>{$l.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>rv(t,n,o,r),t.in=e.in,t.out=e.out});function ku(t,e){return new Ia({type:"pipe",in:t,out:e})}var Ta=k("ZodCodec",(t,e)=>{Ia.init(t,e),la.init(t,e)});function $I(t,e,n){return new Ta({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function OI(t){let e=t._zod.def;return new Ta({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var ib=k("ZodPreprocess",(t,e)=>{Ia.init(t,e),Rh.init(t,e)}),sb=k("ZodReadonly",(t,e)=>{Ah.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>ov(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function ab(t){return new sb({type:"readonly",innerType:t})}var cb=k("ZodTemplateLiteral",(t,e)=>{Ph.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Fy(t,n,o,r)});function LI(t,e){return new cb({type:"template_literal",parts:t,...P.normalizeParams(e)})}var lb=k("ZodLazy",(t,e)=>{Oh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>sv(t,n,o,r),t.unwrap=()=>t._zod.def.getter()});function ub(t){return new lb({type:"lazy",getter:t})}var db=k("ZodPromise",(t,e)=>{$h.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>iv(t,n,o,r),t.unwrap=()=>t._zod.def.innerType});function NI(t){return new db({type:"promise",innerType:t})}var pb=k("ZodFunction",(t,e)=>{Dh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>Hy(t,n,o,r)});function MI(t){return new pb({type:"function",input:Array.isArray(t?.input)?Bv(t?.input):t?.input??xa(Uo()),output:t?.output??Uo()})}var Ea=k("ZodCustom",(t,e)=>{Lh.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,o,r)=>zy(t,n,o,r)});function UI(t){let e=new be({check:"custom"});return e._zod.check=t,e}function FI(t,e){return yy(Ea,t??(()=>!0),e)}function fb(t,e={}){return vy(Ea,t,e)}function mb(t,e){return by(t,e)}var BI=wy,jI=ky;function zI(t,e={}){let n=new Ea({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...P.normalizeParams(e)});return n._zod.bag.Class=t,n._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:n,path:[...n._zod.def.path??[]]})},n}var HI=(...t)=>xy({Codec:Ta,Boolean:Qi,String:Ji},...t);function KI(t){let e=ub(()=>ju([ga(t),_v(),Iv(),Rv(),xa(e),jv(ga(),e)]));return e}function GI(t,e){return new ib({type:"pipe",in:Hu(t),out:e})}var CF={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function RF(t){Le({customError:t})}function AF(){return Le().customError}var gb;gb||(gb={});var $={...ma,...gu,iso:Zi},PF=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function DF(t,e){let n=t.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function $F(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=t.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===o){let r=n[1];if(!r||!e.defs[r])throw new Error(`Reference not found: ${t}`);return e.defs[r]}throw new Error(`Reference not found: ${t}`)}function WI(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return $.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let r=t.$ref;if(e.refs.has(r))return e.refs.get(r);if(e.processing.has(r))return $.lazy(()=>{if(!e.refs.has(r))throw new Error(`Circular reference not resolved: ${r}`);return e.refs.get(r)});e.processing.add(r);let i=$F(r,e),s=ut(i,e);return e.refs.set(r,s),e.processing.delete(r),s}if(t.enum!==void 0){let r=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&r.length===1&&r[0]===null)return $.null();if(r.length===0)return $.never();if(r.length===1)return $.literal(r[0]);if(r.every(s=>typeof s=="string"))return $.enum(r);let i=r.map(s=>$.literal(s));return i.length<2?i[0]:$.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return $.literal(t.const);let n=t.type;if(Array.isArray(n)){let r=n.map(i=>{let s={...t,type:i};return WI(s,e)});return r.length===0?$.never():r.length===1?r[0]:$.union(r)}if(!n)return $.any();let o;switch(n){case"string":{let r=$.string();if(t.format){let i=t.format;i==="email"?r=r.check($.email()):i==="uri"||i==="uri-reference"?r=r.check($.url()):i==="uuid"||i==="guid"?r=r.check($.uuid()):i==="date-time"?r=r.check($.iso.datetime()):i==="date"?r=r.check($.iso.date()):i==="time"?r=r.check($.iso.time()):i==="duration"?r=r.check($.iso.duration()):i==="ipv4"?r=r.check($.ipv4()):i==="ipv6"?r=r.check($.ipv6()):i==="mac"?r=r.check($.mac()):i==="cidr"?r=r.check($.cidrv4()):i==="cidr-v6"?r=r.check($.cidrv6()):i==="base64"?r=r.check($.base64()):i==="base64url"?r=r.check($.base64url()):i==="e164"?r=r.check($.e164()):i==="jwt"?r=r.check($.jwt()):i==="emoji"?r=r.check($.emoji()):i==="nanoid"?r=r.check($.nanoid()):i==="cuid"?r=r.check($.cuid()):i==="cuid2"?r=r.check($.cuid2()):i==="ulid"?r=r.check($.ulid()):i==="xid"?r=r.check($.xid()):i==="ksuid"&&(r=r.check($.ksuid()))}typeof t.minLength=="number"&&(r=r.min(t.minLength)),typeof t.maxLength=="number"&&(r=r.max(t.maxLength)),t.pattern&&(r=r.regex(new RegExp(t.pattern))),o=r;break}case"number":case"integer":{let r=n==="integer"?$.number().int():$.number();typeof t.minimum=="number"&&(r=r.min(t.minimum)),typeof t.maximum=="number"&&(r=r.max(t.maximum)),typeof t.exclusiveMinimum=="number"?r=r.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(r=r.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?r=r.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(r=r.lt(t.maximum)),typeof t.multipleOf=="number"&&(r=r.multipleOf(t.multipleOf)),o=r;break}case"boolean":{o=$.boolean();break}case"null":{o=$.null();break}case"object":{let r={},i=t.properties||{},s=new Set(t.required||[]);for(let[c,l]of Object.entries(i)){let u=ut(l,e);r[c]=s.has(c)?u:u.optional()}if(t.propertyNames){let c=ut(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?ut(t.additionalProperties,e):$.any();if(Object.keys(r).length===0){o=$.record(c,l);break}let u=$.object(r).passthrough(),d=$.looseRecord(c,l);o=$.intersection(u,d);break}if(t.patternProperties){let c=t.patternProperties,l=Object.keys(c),u=[];for(let f of l){let m=ut(c[f],e),g=$.string().regex(new RegExp(f));u.push($.looseRecord(g,m))}let d=[];if(Object.keys(r).length>0&&d.push($.object(r).passthrough()),d.push(...u),d.length===0)o=$.object({}).passthrough();else if(d.length===1)o=d[0];else{let f=$.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)f=$.intersection(f,d[m]);o=f}break}let a=$.object(r);t.additionalProperties===!1?o=a.strict():typeof t.additionalProperties=="object"?o=a.catchall(ut(t.additionalProperties,e)):o=a.passthrough();break}case"array":{let r=t.prefixItems,i=t.items;if(r&&Array.isArray(r)){let s=r.map(c=>ut(c,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?ut(i,e):void 0;a?o=$.tuple(s).rest(a):o=$.tuple(s),typeof t.minItems=="number"&&(o=o.check($.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check($.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=i.map(c=>ut(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?ut(t.additionalItems,e):void 0;a?o=$.tuple(s).rest(a):o=$.tuple(s),typeof t.minItems=="number"&&(o=o.check($.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check($.maxLength(t.maxItems)))}else if(i!==void 0){let s=ut(i,e),a=$.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=$.array($.any());break}default:throw new Error(`Unsupported type: ${n}`)}return o}function ut(t,e){if(typeof t=="boolean")return t?$.any():$.never();let n=WI(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(l=>ut(l,e)),c=$.union(a);n=o?$.intersection(n,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(l=>ut(l,e)),c=$.xor(a);n=o?$.intersection(n,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)n=o?n:$.any();else{let a=o?n:ut(t.allOf[0],e),c=o?0:1;for(let l=c;l<t.allOf.length;l++)a=$.intersection(a,ut(t.allOf[l],e));n=a}t.nullable===!0&&e.version==="openapi-3.0"&&(n=$.nullable(n)),t.readOnly===!0&&(n=$.readonly(n)),t.default!==void 0&&(n=n.default(t.default));let r={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(r[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(r[a]=t[a]);for(let a of Object.keys(t))PF.has(a)||(r[a]=t[a]);return Object.keys(r).length>0&&e.registry.add(n,r),t.description&&(n=n.describe(t.description)),n}function ZI(t,e){if(typeof t=="boolean")return t?$.any():$.never();let n;try{n=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=DF(n,e?.defaultTarget),r=n.$defs||n.definitions||{},i={version:o,defs:r,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??st};return ut(n,i)}var hb={};Xt(hb,{bigint:()=>MF,boolean:()=>NF,date:()=>UF,number:()=>LF,string:()=>OF});function OF(t){return Fh(Ji,t)}function LF(t){return Zh(Xi,t)}function NF(t){return ey(Qi,t)}function MF(t){return ny(es,t)}function UF(t){return fy(ka,t)}Le(Ol());var ie=p.number().min(0).max(100),yr=p.number().int().min(1e3).max(12e3),hr=p.number(),Q=p.number().int().nonnegative(),hn=p.enum(["hue","matter","smartthings","homeassistant","nest","alexa","google","kasa","wiz","lifx","shelly","govee","tapo","tuya","yeelight","nanoleaf","meross","ewelink","wled","elgato","roku","mqtt","esphome","mock","other"]),FF=p.enum(["local","cloud","offline","unknown"]),Ca=p.enum(["light","plug","switch","dimmer","thermostat","lock","cover","garageDoor","valve","fan","sensor","binarySensor","camera","doorbell","speaker","tv","mediaPlayer","vacuum","appliance","airPurifier","humidifier","waterHeater","evCharger","sceneController","remote","scene","group","bridge","other"]),BF=p.enum(["temperature","humidity","illuminance","pressure","co2","pm25","pm10","voc","airQuality","noise","uvIndex","windSpeed","distance","generic"]),jF=p.enum(["motion","occupancy","presence","contact","leak","smoke","co","gas","tamper","vibration","glassBreak","button","person","sound","moisture","generic"]),en={temperature:"Cel",humidity:"%",illuminance:"lx",pressure:"hPa",co2:"ppm",pm25:"ug/m3",pm10:"ug/m3",voc:"ppb",airQuality:"index",noise:"dB",uvIndex:"index",windSpeed:"m/s",distance:"m",generic:""},_e=(t,e)=>p.object({type:p.literal(t),instance:p.string().optional(),...e}),zF=_e("power",{state:p.object({on:p.boolean().nullable()})}),HF=_e("brightness",{state:p.object({level:ie.nullable()})}),KF=_e("colorTemperature",{config:p.object({minKelvin:yr,maxKelvin:yr}),state:p.object({kelvin:yr.nullable()})}),GF=_e("color",{config:p.object({modes:p.array(p.enum(["hs","rgb","xy"])).default(["hs"])}),state:p.object({hue:p.number().min(0).max(360).nullable(),saturation:ie.nullable()})}),WF=_e("segmentColor",{config:p.object({segments:p.number().int().min(1)}),state:p.object({colors:p.array(p.object({hue:p.number().min(0).max(360).nullable(),saturation:ie.nullable()})).nullable()})}),bb=p.enum(["off","heat","cool","auto","eco","fanOnly","dry"]),ZF=_e("thermostat",{config:p.object({modes:p.array(bb),minC:hr,maxC:hr,supportsRange:p.boolean().default(!1)}),state:p.object({mode:bb.nullable(),currentC:hr.nullable(),setpointC:hr.nullable().optional(),heatC:hr.nullable().optional(),coolC:hr.nullable().optional(),action:p.enum(["idle","heating","cooling","fan"]).nullable().optional()})}),qF=_e("humidity",{config:p.object({settable:p.boolean().default(!1),minPct:ie.default(0),maxPct:ie.default(100)}),state:p.object({currentPct:ie.nullable().optional(),targetPct:ie.nullable().optional()})}),VF=_e("lock",{state:p.object({state:p.enum(["locked","unlocked","jammed","unknown"])})}),JF=_e("cover",{config:p.object({kind:p.enum(["blind","shade","curtain","awning","garage","door","window","valve","generic"]),supportsPosition:p.boolean().default(!1),supportsTilt:p.boolean().default(!1)}),state:p.object({position:ie.nullable().optional(),tilt:ie.nullable().optional(),state:p.enum(["open","closed","opening","closing","stopped","partial","unknown"])})}),YF=_e("fan",{config:p.object({presets:p.array(p.string()).default([]),supportsOscillate:p.boolean().default(!1)}),state:p.object({on:p.boolean().nullable(),level:ie.nullable().optional(),preset:p.string().nullable().optional(),oscillating:p.boolean().nullable().optional()})}),XF=_e("mode",{config:p.object({options:p.array(p.string())}),state:p.object({value:p.string().nullable()})}),QF=_e("toggle",{state:p.object({on:p.boolean().nullable()})}),eB=_e("range",{config:p.object({min:p.number(),max:p.number(),step:p.number().optional(),unit:p.string().optional()}),state:p.object({value:p.number().nullable()})}),tB=_e("mediaTransport",{state:p.object({state:p.enum(["playing","paused","stopped","buffering","idle"]).nullable(),metadata:p.object({title:p.string().optional(),artist:p.string().optional(),album:p.string().optional(),artworkUrl:p.string().optional()}).nullable().optional(),positionSec:p.number().nonnegative().nullable().optional(),durationSec:p.number().nonnegative().nullable().optional(),shuffle:p.boolean().nullable().optional(),repeat:p.enum(["off","one","all"]).nullable().optional()})}),nB=_e("volume",{state:p.object({level:ie.nullable(),muted:p.boolean().nullable()})}),rB=_e("inputSource",{config:p.object({sources:p.array(p.string())}),state:p.object({source:p.string().nullable()})}),oB=_e("startStop",{config:p.object({supportsPause:p.boolean().default(!1)}),state:p.object({state:p.enum(["running","paused","stopped","unknown"])})}),iB=_e("scene",{state:p.object({lastActivated:Q.nullable().optional()})}),sB=_e("camera",{config:p.object({protocols:p.array(p.enum(["rtsp","webrtc","hls","snapshot"]))}),state:p.object({streaming:p.boolean().nullable().optional()})}),aB=_e("sensor",{config:p.object({measurement:BF,unit:p.string()}),state:p.object({value:p.number().nullable(),ts:Q.nullable().optional()})}),cB=_e("binarySensor",{config:p.object({sensorType:jF}),state:p.object({active:p.boolean().nullable(),lastChanged:Q.nullable().optional()})}),lB=_e("battery",{state:p.object({level:ie.nullable(),charging:p.boolean().nullable().optional(),low:p.boolean().nullable().optional()})}),uB=_e("energyMeter",{state:p.object({power:p.number().nullable().optional(),energy:p.number().nullable().optional(),voltage:p.number().nullable().optional(),current:p.number().nullable().optional()})}),dB=_e("doorbell",{state:p.object({lastPress:Q.nullable().optional()})}),pB=_e("connectivity",{config:p.object({transport:p.enum(["wifi","thread","zigbee","zwave","ethernet","ble","cloud","matter","unknown"])}),state:p.object({online:p.boolean().nullable(),signal:p.number().nullable().optional()})}),qI=p.enum(["flash","strobe","pulse","colorFade","colorLoop","candle","rainbow","siren","meter"]),Ft=p.object({hue:p.number().min(0).max(360),saturation:ie}),gr=p.number().int().min(20).max(6e5),yb=p.number().int().min(1).max(1e3).nullable().default(null),Bo=p.discriminatedUnion("kind",[p.object({kind:p.literal("flash"),count:p.number().int().min(1).max(100).default(3),onMs:gr.default(300),offMs:gr.default(300),color:Ft.nullable().default(null),brightness:ie.nullable().default(null)}),p.object({kind:p.literal("strobe"),hz:p.number().min(.5).max(25).default(8),durationMs:gr.default(3e3),color:Ft.nullable().default(null)}),p.object({kind:p.literal("pulse"),periodMs:gr.default(2e3),minPct:ie.default(5),maxPct:ie.default(100),color:Ft.nullable().default(null),cycles:yb}),p.object({kind:p.literal("colorFade"),from:Ft.nullable().default(null),to:Ft,durationMs:gr.default(2e3),easing:p.enum(["linear","ease"]).default("ease")}),p.object({kind:p.literal("colorLoop"),colors:p.array(Ft).min(2).max(16),holdMs:gr.default(1e3),fadeMs:p.number().int().min(0).max(6e5).default(800),loops:yb,direction:p.enum(["forward","pingpong"]).default("forward")}),p.object({kind:p.literal("candle"),intensity:ie.default(50),warmthKelvin:yr.nullable().default(null),durationMs:gr.nullable().default(null)}),p.object({kind:p.literal("rainbow"),cycleMs:gr.default(4e3),saturation:ie.default(100),brightness:ie.default(100),loops:yb}),p.object({kind:p.literal("siren"),colorA:Ft.default({hue:0,saturation:100}),colorB:Ft.default({hue:240,saturation:100}),hz:p.number().min(.5).max(10).default(4),durationMs:gr.nullable().default(null)}),p.object({kind:p.literal("meter"),source:p.enum(["context","usage","cost"]),stops:p.array(p.object({at:p.number().min(0),color:Ft})).min(2).max(6).default([{at:0,color:{hue:120,saturation:90}},{at:75,color:{hue:40,saturation:95}},{at:95,color:{hue:0,saturation:95}}])})]),fB=_e("effect",{config:p.object({kinds:p.array(qI).default(["flash"]),supportsColor:p.boolean().default(!1)}),state:p.object({active:qI.nullable()})}),mB=p.discriminatedUnion("type",[zF,HF,KF,GF,WF,ZF,qF,VF,JF,YF,XF,QF,eB,tB,nB,rB,oB,iB,sB,aB,cB,lB,uB,dB,pB,fB]),yn=p.enum(["power","brightness","colorTemperature","color","segmentColor","thermostat","humidity","lock","cover","fan","mode","toggle","range","mediaTransport","volume","inputSource","startStop","scene","camera","sensor","binarySensor","battery","energyMeter","doorbell","connectivity","effect"]),YI=p.enum(["needs-password"]),gB=p.object({sourceId:p.string(),provider:hn,providerAccountId:p.string(),nativeId:p.string(),nativeType:p.string().optional(),reachability:p.enum(["local","cloud"]),online:p.boolean(),attention:YI.nullable().optional(),credentialRef:p.string().nullable().optional(),lastSeen:Q.nullable().optional()}),hB=p.object({id:p.string(),name:p.string(),providerRefs:p.array(p.object({provider:hn,nativeId:p.string()})).default([])}),yB=p.object({accountId:p.string(),provider:hn,displayName:p.string(),reachability:p.enum(["local","cloud"]),status:p.enum(["linked","needs_reauth","revoked"]),expiresAt:Q.nullable().optional()}),vB=p.object({id:p.string(),type:Ca,name:p.string(),areaId:p.string().nullable(),manufacturer:p.string().nullable().optional(),model:p.string().nullable().optional(),firmwareVersion:p.string().nullable().optional(),online:p.boolean(),reachability:FF,attention:YI.nullable().optional(),parentId:p.string().nullable().optional(),members:p.array(p.string()).optional(),sources:p.array(gB).min(1),preferredSourceId:p.string(),capabilities:p.array(mB),updatedAt:Q,raw:p.unknown().optional()}),XI=p.object({version:p.literal(1),nodeId:p.string(),updatedAt:Q,areas:p.array(hB),accounts:p.array(yB),devices:p.array(vB)}),bB=p.enum(["relay-do-sealed","hub-local"]),EY=p.object({accountId:p.string(),provider:hn,providerAccountId:p.string(),nodeId:p.string(),credentialLocation:bB,scopes:p.array(p.string()).default([]),status:p.enum(["linked","needs_reauth","revoked"]),displayName:p.string(),expiresAt:Q.nullable().optional(),linkedAt:Q}),VI=p.enum(["open","guarded","locked"]),vb=p.enum(["allow","confirm","deny"]),wB=p.enum(["voice","claude","app","rules"]),CY=p.object({tier:VI.default("open"),perConsumer:p.partialRecord(wB,VI).default({}),perClass:p.partialRecord(yn,vb).default({}),perDeviceType:p.partialRecord(Ca,vb).default({}),perDevice:p.record(p.string(),vb).default({}),confirmWindowSec:p.number().default(60)}),Ne=p.object({}),JI=t=>t.type==="cover"&&(t.config.kind==="garage"||t.config.kind==="door"),vr={power:[{command:"turnOn",params:Ne},{command:"turnOff",params:Ne},{command:"toggle",params:Ne}],brightness:[{command:"setBrightness",params:p.object({level:ie})},{command:"adjustBrightness",params:p.object({delta:p.number().min(-100).max(100)})}],colorTemperature:[{command:"setColorTemperature",params:p.object({kelvin:yr})}],color:[{command:"setColor",params:p.object({hue:p.number().min(0).max(360),saturation:ie})}],segmentColor:[{command:"setSegmentColors",voice:!1,params:p.object({segments:p.array(p.object({index:p.number().int().nonnegative(),hue:p.number().min(0).max(360),saturation:ie})).min(1).max(512)})}],thermostat:[{command:"setThermostatMode",params:p.object({mode:bb})},{command:"setSetpoint",params:p.object({celsius:hr})},{command:"setRange",params:p.object({heatCelsius:hr,coolCelsius:hr}),gate:t=>t.type==="thermostat"&&t.config.supportsRange}],humidity:[{command:"setHumidity",params:p.object({percent:ie}),gate:t=>t.type==="humidity"&&t.config.settable}],lock:[{command:"lock",params:Ne},{command:"unlock",params:Ne,confirm:!0}],cover:[{command:"open",params:Ne,confirm:JI},{command:"close",params:Ne},{command:"stop",params:Ne},{command:"setPosition",params:p.object({position:ie}),confirm:JI,gate:t=>t.type==="cover"&&t.config.supportsPosition},{command:"setTilt",params:p.object({tilt:ie}),gate:t=>t.type==="cover"&&t.config.supportsTilt}],fan:[{command:"turnOn",params:Ne},{command:"turnOff",params:Ne},{command:"setFanSpeed",params:p.object({level:ie})},{command:"setFanPreset",params:p.object({preset:p.string()}),gate:t=>t.type==="fan"&&t.config.presets.length>0},{command:"setOscillate",params:p.object({oscillating:p.boolean()}),gate:t=>t.type==="fan"&&t.config.supportsOscillate}],mode:[{command:"setMode",params:p.object({value:p.string()})}],toggle:[{command:"setToggle",params:p.object({on:p.boolean()})}],range:[{command:"setRange",params:p.object({value:p.number()})},{command:"adjustRange",params:p.object({delta:p.number()})}],mediaTransport:[{command:"play",params:Ne},{command:"pause",params:Ne},{command:"stop",params:Ne},{command:"next",params:Ne},{command:"previous",params:Ne},{command:"seek",params:p.object({positionSec:p.number().nonnegative()})},{command:"setShuffle",params:p.object({on:p.boolean()})},{command:"setRepeat",params:p.object({mode:p.enum(["off","one","all"])})}],volume:[{command:"setVolume",params:p.object({level:ie})},{command:"adjustVolume",params:p.object({delta:p.number().min(-100).max(100)})},{command:"setMute",params:p.object({muted:p.boolean()})}],inputSource:[{command:"selectInput",params:p.object({source:p.string()})}],startStop:[{command:"start",params:Ne},{command:"stop",params:Ne},{command:"pause",params:Ne,gate:t=>t.type==="startStop"&&t.config.supportsPause},{command:"resume",params:Ne,gate:t=>t.type==="startStop"&&t.config.supportsPause}],scene:[{command:"activate",params:Ne}],effect:[{command:"startEffect",params:p.object({spec:Bo})},{command:"stopEffect",params:Ne}],camera:[{command:"getStream",params:p.object({protocol:p.enum(["rtsp","webrtc","hls"])}),voice:!1,returns:p.object({url:p.string(),token:p.string().optional(),expiresAt:Q.optional()})},{command:"getSnapshot",params:Ne,voice:!1,returns:p.object({url:p.string(),expiresAt:Q.optional()})}],sensor:[],binarySensor:[],battery:[],energyMeter:[],doorbell:[],connectivity:[]},kB=new Set(["garageDoor","door","lock"]);function Ra(t,e,n){let o=typeof n.confirm=="function"?n.confirm(e):!!n.confirm,r=kB.has(t.type)&&(vr[e.type]?.some(i=>i.command===n.command)??!1);return o||r}var Wu=t=>Math.round(1e6/t),QI=t=>Math.round(1e6/t),eT=t=>Math.round(t/255*100);var ts=t=>(t-32)*5/9,Zu=t=>t*9/5+32;var xB=p.discriminatedUnion("kind",[p.object({kind:p.literal("literal"),hue:p.number().min(0).max(360),saturation:ie}),p.object({kind:p.literal("token"),token:p.enum(["main","session"])})]),qu=p.enum(["main","session","hold","off"]),Vu=p.object({color:xB.optional(),brightnessPct:ie.nullable().optional(),brightnessScale:p.number().min(0).max(2).optional(),kelvin:yr.nullable().optional(),power:p.boolean().optional()}),wb=t=>Math.max(0,Math.min(100,Math.round(t)));function kb(t,e,n){let o;t.color===void 0?o=e.hs:t.color.kind==="literal"?o={hue:t.color.hue,saturation:t.color.saturation}:o=t.color.token==="session"?n??e.hs:e.hs;let r;t.brightnessPct!==void 0?r=t.brightnessPct:t.brightnessScale!==void 0?r=wb((e.brightness??100)*t.brightnessScale):r=e.brightness;let i=t.kelvin!==void 0,s=i?t.kelvin??null:e.kelvin;i&&t.kelvin!=null?o=null:o!=null&&(s=null);let a=t.power!==void 0?t.power:o!=null||r!=null||s!=null?!0:null;return{hs:o,brightness:r,kelvin:s,power:a}}function Ju(t){if(t.power===!1)return[{capability:"power",command:"turnOff",params:{}}];let e=[];return t.brightness!=null&&e.push({capability:"brightness",command:"setBrightness",params:{level:wb(t.brightness)}}),t.hs!=null?e.push({capability:"color",command:"setColor",params:{hue:Math.round(t.hs.hue),saturation:wb(t.hs.saturation)}}):t.kelvin!=null&&e.push({capability:"colorTemperature",command:"setColorTemperature",params:{kelvin:Math.round(t.kelvin)}}),t.power===!0&&e.push({capability:"power",command:"turnOn",params:{}}),e}var Yu=p.enum(["added","removed","permission_request","started","ended","working","finished","error","idle","needs_permission","promptSubmitted","toolStart","toolEnd","subagentStart","subagentFinished","compacting","resumed","aborted","contextLow","contextCritical","needsInput","planReady","rateLimited","compactDone","permissionDenied","taskCompleted","usageHigh","modePlan","modeAuto","modeBypass","modeNormal","modelChanged","workflowStarted","sandboxEscalation","reviewChanged","costHigh","longRunning"]),br=p.enum(["claude","codex"]);var tT=p.discriminatedUnion("kind",[p.object({kind:p.literal("deviceState"),deviceId:p.string(),capability:p.string(),instance:p.string().optional(),op:p.enum(["eq","neq","gt","lt","gte","lte","changed"]).default("changed"),path:p.string().optional(),value:p.unknown().optional()}),p.object({kind:p.literal("edge"),deviceId:p.string(),event:p.string()}),p.object({kind:p.literal("session"),event:Yu,repo:p.string().optional(),sessionId:p.string().optional(),agent:br.optional()}),p.object({kind:p.literal("schedule"),cron:p.string()})]),nT=p.object({deviceId:p.string(),capability:p.string(),instance:p.string().optional(),op:p.enum(["eq","neq","gt","lt","gte","lte"]),path:p.string().optional(),value:p.unknown()}),rT=p.discriminatedUnion("kind",[p.object({kind:p.literal("device"),deviceId:p.string(),capability:p.string(),instance:p.string().optional(),command:p.string(),params:p.unknown().optional()}),p.object({kind:p.literal("session"),sessionId:p.string(),text:p.string()}),p.object({kind:p.literal("notify"),title:p.string(),body:p.string()}),p.object({kind:p.literal("intent"),deviceId:p.string(),instance:p.string().optional(),look:Vu.optional(),effect:Bo.optional(),returnTo:qu.optional(),hold:p.boolean().default(!1)})]),Aa=p.object({id:p.string(),name:p.string().default(""),enabled:p.boolean().default(!0),trigger:tT,conditions:p.array(nT).default([]),actions:p.array(rT).min(1),allowSecurity:p.boolean().default(!1)});var ns=p.enum(["started","ended","working","finished","error","idle","needs_permission","subagentFinished","compacting","resumed","contextLow","contextCritical","needsInput","planReady","rateLimited","subagentStart","compactDone","permissionDenied","taskCompleted","usageHigh","modePlan","modeAuto","modeBypass","modeNormal","modelChanged","workflowStarted","sandboxEscalation","reviewChanged","costHigh","longRunning"]),oT=p.object({id:p.string(),name:p.string(),cwd:p.string(),online:p.boolean().default(!0),state:ns.optional(),bridgeId:p.string().optional(),bridgeName:p.string().optional(),agent:br.optional()}),iT=p.enum(["allow","deny"]),BY=p.object({sessionId:p.string().nullable(),text:p.string(),ts:Q.optional()}),Xu=p.object({latestReply:p.string().nullable(),ts:p.number().nullable(),cursor:p.number().int().nonnegative(),hasMore:p.boolean()}),jY=p.object({requestId:p.string(),behavior:iT,ts:Q.optional()}),zY=p.object({id:p.string(),sessionId:p.string().nullable(),args:p.unknown(),ts:Q.optional()}),SB=p.object({type:p.literal("register"),userToken:p.string().optional(),sessions:p.array(oT),claudeSessionId:p.string().optional()}),_B=p.object({type:p.literal("sessions.update"),sessions:p.array(oT)}),IB=p.object({type:p.literal("prompt"),sessionId:p.string(),requestId:p.string(),text:p.string(),ts:Q.optional()});var TB=p.object({type:p.literal("reply"),sessionId:p.string(),requestId:p.string(),text:p.string(),seq:p.number().int().nonnegative().optional(),final:p.boolean().optional(),ts:Q.optional()}),EB=p.object({type:p.literal("permission_request"),sessionId:p.string(),requestId:p.string(),tool:p.string(),description:p.string(),preview:p.string(),ts:Q.optional()}),CB=p.object({type:p.literal("permission_verdict"),sessionId:p.string(),requestId:p.string(),behavior:iT,ts:Q.optional()}),RB=p.object({type:p.literal("command"),id:p.string(),requestId:p.string(),sessionId:p.string().nullable(),args:p.unknown(),ts:Q.optional()}),AB=p.object({type:p.literal("command_result"),requestId:p.string(),id:p.string(),sessionId:p.string().nullable().optional(),result:p.unknown().optional(),error:p.string().optional(),ts:Q.optional()}),PB=p.object({type:p.literal("devices.update"),doc:XI}),DB=p.object({type:p.literal("device_command"),requestId:p.string(),deviceId:p.string(),sourceId:p.string().nullable().optional(),ruleId:p.string().optional(),capability:yn,instance:p.string().optional(),command:p.string(),params:p.unknown(),consumer:p.enum(["voice","claude","app","rules"]),sessionId:p.string().optional(),confirm:p.boolean().optional()}),$B=p.object({type:p.literal("device_query"),requestId:p.string(),kind:p.enum(["list","get"]),deviceId:p.string().optional()}),OB=p.object({type:p.literal("device_result"),requestId:p.string(),deviceId:p.string().optional(),ok:p.boolean(),verified:p.boolean().optional(),state:p.unknown().optional(),result:p.unknown().optional(),error:p.string().optional()}),LB=p.object({type:p.literal("device_event"),deviceId:p.string(),capability:yn,instance:p.string().optional(),event:p.string(),payload:p.unknown().optional(),ts:Q}),NB=p.object({type:p.literal("device_source_event"),provider:hn,providerAccountId:p.string(),nativeId:p.string(),patch:p.array(p.object({type:yn,instance:p.string().optional(),state:p.unknown()})).optional(),edge:p.object({capability:yn,instance:p.string().optional(),event:p.string(),payload:p.unknown().optional()}).optional(),online:p.boolean().optional(),ts:Q}),MB=p.object({type:p.literal("entitlement"),plan:p.enum(["free","paid"]),planStatus:p.enum(["active","past_due","canceled"]).optional(),serviceOk:p.boolean().optional(),capture:p.object({telemetry:p.boolean(),transcripts:p.boolean()}),policyVersion:p.string(),ts:Q}),UB=p.object({type:p.literal("device_config"),version:p.number().int().nonnegative(),config:p.record(p.string(),p.unknown()),ts:Q}),FB=p.object({type:p.literal("disconnect"),code:p.union([p.literal(1012),p.literal(4402),p.literal(4426),p.number().int().min(1e3).max(4999)]),reason:p.string().max(120),ts:Q}),BB=p.object({type:p.literal("device_audit"),requestId:p.string(),consumer:p.enum(["voice","claude","app","rules"]),deviceId:p.string(),ruleId:p.string().optional(),capability:yn,command:p.string(),params:p.unknown(),ok:p.boolean(),confirmRequired:p.boolean(),confirmedBy:p.string().optional(),error:p.string().optional(),ts:Q}),xb=64,jB=p.object({type:p.literal("session_state"),sessionId:p.string(),state:ns,event:p.string(),ts:Q,transitions:p.array(p.object({state:ns,event:p.string(),ts:Q})).max(xb).optional()}),zB=p.object({type:p.literal("notification"),sessionId:p.string(),event:ns,repo:p.string().optional(),title:p.string().optional(),body:p.string().optional()}),HB=p.discriminatedUnion("type",[SB,_B,IB,TB,EB,CB,RB,AB,PB,DB,$B,OB,LB,NB,BB,MB,FB,UB,jB,zB]),Qu=t=>HB.parse(typeof t=="string"?JSON.parse(t):t);var KB=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zn=(t,e)=>t>>>e|t<<32-e;function GB(t){let e=[];for(let n of t){let o=n.codePointAt(0);o<128?e.push(o):o<2048?e.push(192|o>>6,128|o&63):o<65536?e.push(224|o>>12,128|o>>6&63,128|o&63):e.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return Uint8Array.from(e)}function WB(t){let e=GB(t),n=new Uint8Array((e.length+8>>6)+1<<6);n.set(e),n[e.length]=128;let o=new DataView(n.buffer),r=e.length*8;o.setUint32(n.length-8,Math.floor(r/4294967296)),o.setUint32(n.length-4,r>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64);for(let l=0;l<n.length;l+=64){for(let w=0;w<16;w++)s[w]=o.getUint32(l+w*4);for(let w=16;w<64;w++){let x=s[w-15],I=s[w-2],E=zn(x,7)^zn(x,18)^x>>>3,C=zn(I,17)^zn(I,19)^I>>>10;s[w]=s[w-16]+E+s[w-7]+C>>>0}let u=i[0],d=i[1],f=i[2],m=i[3],g=i[4],h=i[5],y=i[6],b=i[7];for(let w=0;w<64;w++){let x=zn(g,6)^zn(g,11)^zn(g,25),I=g&h^~g&y,E=b+x+I+KB[w]+s[w],C=zn(u,2)^zn(u,13)^zn(u,22),F=u&d^u&f^d&f,U=C+F;b=y,y=h,h=g,g=m+E>>>0,m=f,f=d,d=u,u=E+U>>>0}i[0]=i[0]+u>>>0,i[1]=i[1]+d>>>0,i[2]=i[2]+f>>>0,i[3]=i[3]+m>>>0,i[4]=i[4]+g>>>0,i[5]=i[5]+h>>>0,i[6]=i[6]+y>>>0,i[7]=i[7]+b>>>0}let a=new Uint8Array(32),c=new DataView(a.buffer);for(let l=0;l<8;l++)c.setUint32(l*4,i[l]);return a}var sT="abcdefghijklmnopqrstuvwxyz234567";function ZB(t){let e=0,n=0,o="";for(let r of t)for(n=n<<8|r,e+=8;e>=5;)o+=sT[n>>>e-5&31],e-=5;return e>0&&(o+=sT[n<<5-e&31]),o}function rs(t){return ZB(WB(t))}var qB=p.enum(["mdns","ssdp","kasa-udp","wiz-udp","lifx-lan","yeelight","govee-udp","tuya-beacon","arp","http","meethue"]),VB=p.object({protocol:qB,detail:p.string(),at:Q}),JB=p.enum(["connect-now","link-ecosystem","identified-only"]),Hn=p.enum(["kasa","kasa-klap","wiz","lifx","shelly","govee","tapo","tuya","yeelight","nanoleaf","meross","ewelink","wled","elgato","roku","esphome"]),YB=p.enum(["high","medium","low"]),XB=p.object({ip:p.string(),mac:p.string().optional(),hostname:p.string().optional(),port:p.number().int().positive().optional()}),cT=p.object({discoveredId:p.string(),addresses:XB,evidence:p.array(VB).min(1),identity:p.object({name:p.string().optional(),manufacturer:p.string().optional(),model:p.string().optional(),hint:p.string().optional(),vendorId:p.string().optional()}).default({}),bucket:JB,kind:p.string().optional(),suggestedProvider:hn.optional(),localProtocol:Hn.optional(),expectedType:Ca.optional(),expectedCapabilities:p.array(yn).default([]),alreadyLinked:p.object({provider:hn,deviceId:p.string().optional(),accountId:p.string().optional()}).nullable().optional(),confidence:YB,firstSeen:Q,lastSeen:Q});function T(t){return t.trim().toLowerCase().replace(/[^0-9a-f]/g,"").replace(/(..)(?=.)/g,"$1:")}function Pa(t,e){let n=t.mac?`mac:${T(t.mac)}`:`ip:${t.ip}|${e??""}`;return`ldev_${rs(n).slice(0,8)}`}var lT=p.object({key:p.string(),provider:hn,accountId:p.string().optional(),name:p.string(),mac:p.string().optional(),nativeType:p.string().optional(),expectedType:Ca.optional(),state:p.enum(["cloud","not-seen"]),deviceId:p.string().optional()}),uT=p.object({wsl:p.boolean(),multicastOk:p.boolean().nullable(),broadcastOk:p.boolean().nullable(),interop:p.enum(["windows-arp"]).optional(),interfaces:p.array(p.string()).optional(),primaryInterface:p.string().optional()});var QB=p.enum(["running","done","failed"]),qY=p.object({id:p.string(),status:QB,startedAt:Q,finishedAt:Q.optional(),error:p.string().optional(),devices:p.array(cT),accountDevices:p.array(lT).optional(),env:uT,probeStatus:p.record(p.string(),p.string()).optional()}),ej=p.enum(["mdns","ssdp","kasa","wiz","lifx","yeelight","govee","tuya","arp","sweep"]),jo=p.object({autoConnect:p.enum(["unset","off","open-protocols"]).default("unset"),passive:p.boolean().default(!0),protocols:p.partialRecord(ej,p.boolean()).default({}),unidentified:p.boolean().default(!0)}),VY=p.object({scanId:p.string()}),dT=p.object({devices:p.array(cT),accountDevices:p.array(lT).optional(),env:uT,updatedAt:Q}),pT=p.object({discoveredId:p.string().optional(),ip:p.string().optional(),protocol:Hn,name:p.string().optional(),credentials:p.record(p.string(),p.string()).optional()}).refine(t=>t.discoveredId!==void 0||t.ip!==void 0,{message:"either discoveredId or ip is required"}),Sb={tapo:[{key:"username",label:"TP-Link email",secret:!1,helpText:"the TP-Link ID the device was set up with"},{key:"password",label:"Password",secret:!0}],"kasa-klap":[{key:"username",label:"TP-Link email",secret:!1,helpText:"the TP-Link/Kasa ID the device was set up with (leave blank if never linked to the cloud)"},{key:"password",label:"Password",secret:!0}],shelly:[{key:"password",label:"Device password",secret:!0,helpText:'the password set on this Shelly (its username is always "admin")'}],esphome:[{key:"encryptionKey",label:"Encryption key",secret:!0,helpText:"the `api: encryption: key` from this device's ESPHome config (base64) \u2014 leave blank if it has no encryption"}]},tj=new Set(["shelly","esphome"]);function ed(t){return tj.has(t)}var JY=p.object({ok:p.boolean(),deviceId:p.string().optional(),accountId:p.string().optional(),error:p.string().optional(),note:p.string().optional(),linkVia:hn.optional()}),fT=p.object({deviceId:p.string(),purge:p.boolean().default(!1),discoveredId:p.string().optional()}),mT=p.object({deviceId:p.string(),name:p.string()}),gT=p.object({clientId:p.string().min(1),clientSecret:p.string().min(1),region:p.string().min(1)}),YY=p.object({ok:p.boolean(),deviceCount:p.number().int().nonnegative().optional(),sleepyCount:p.number().int().nonnegative().optional(),error:p.string().optional()}),hT=p.object({email:p.string().min(1),password:p.string().min(1),region:p.string().min(1),mfaCode:p.string().optional()}),XY=p.object({ok:p.boolean(),deviceCount:p.number().int().nonnegative().optional(),error:p.string().optional()}),yT=p.object({email:p.string().min(1),password:p.string().min(1),region:p.string().min(1)}),QY=p.object({ok:p.boolean(),deviceCount:p.number().int().nonnegative().optional(),error:p.string().optional()}),vT=p.object({apiKey:p.string().min(1)}),eX=p.object({ok:p.boolean(),deviceCount:p.number().int().nonnegative().optional(),error:p.string().optional()}),tX=p.object({ok:p.boolean(),note:p.string().optional(),error:p.string().optional()}),bT=p.object({sessionId:p.string().optional(),revertOnStop:p.boolean().default(!0)}),_b=p.object({sessionId:p.string().optional()}),wT=p.object({pct:p.number().min(0).max(100),usedTokens:p.number().int().nonnegative().optional(),windowTokens:p.number().int().positive().optional()}),aT=p.object({usedPct:p.number().min(0).max(100),resetsAt:Q.optional()}),kT=p.object({sessionId:p.string().optional(),claudeSessionId:p.string().optional(),state:ns,event:p.string(),ts:Q.optional(),cwd:p.string().optional(),extra:p.record(p.string(),p.unknown()).optional(),context:wT.optional(),mode:p.string().optional(),model:p.string().optional(),agent:br.optional()}),xT=p.object({sessionId:p.string().optional(),claudeSessionId:p.string().optional(),cwd:p.string().optional(),ts:Q.optional(),context:wT.optional(),rateLimits:p.object({fiveHour:aT.optional(),sevenDay:aT.optional()}).optional(),mode:p.string().optional(),model:p.string().optional(),modelName:p.string().optional(),review:p.string().optional(),cost:p.number().nonnegative().optional(),agent:br.optional()}),ST=p.object({sessionId:p.string().optional(),claudeSessionId:p.string().optional(),codexThreadId:p.string().min(1),cwd:p.string().optional(),gitBranch:p.string().optional(),ts:Q.optional(),inputTokens:p.number().int().nonnegative(),cachedInputTokens:p.number().int().nonnegative().default(0),outputTokens:p.number().int().nonnegative(),agent:br.optional()}),nj=p.object({reverted:p.number().int().nonnegative(),failed:p.number().int().nonnegative(),skipped:p.number().int().nonnegative()}),nX=p.object({active:p.boolean(),sessionId:p.string().optional(),generation:p.number().int().nonnegative().optional(),touched:p.number().int().nonnegative().default(0),revertOnStop:p.boolean().default(!0),owner:p.enum(["app","hook"]).optional(),summary:nj.optional()});var os=new Set(["lock","cover","garageDoor","valve","camera","doorbell"]),_T=new Set(["lock","cover","camera","doorbell"]),IT=new Set(["tuya","meross","ewelink","nanoleaf","esphome"]);function TT(t,e=Sb){return t.bucket==="connect-now"&&t.localProtocol!==void 0&&((e[t.localProtocol]?.length??0)===0||ed(t.localProtocol))&&!IT.has(t.localProtocol)&&t.confidence==="high"&&t.addresses.mac!==void 0&&!t.alreadyLinked&&!(t.expectedType!==void 0&&os.has(t.expectedType))&&!t.expectedCapabilities.some(n=>_T.has(n))}function ET(t){let e=t.trim(),n,o=/^(mqtts?|tcp|ssl|tls|wss?):\/\//i.exec(e);if(o){let a=o[1].toLowerCase();(a==="mqtts"||a==="ssl"||a==="tls"||a==="wss")&&(n=!0),e=e.slice(o[0].length)}e=e.replace(/\/.*$/,"");let r=/^(.+):(\d{1,5})$/.exec(e),i=(r?r[1]:e).trim(),s=r?Number(r[2]):void 0;return{host:i,...s!==void 0&&s>=1&&s<=65535?{port:s}:{},...n!==void 0?{tls:n}:{}}}var rj=p.object({deviceId:p.string(),capability:yn,instance:p.string().optional(),command:p.string(),params:p.unknown().optional()}),oj=p.object({deviceId:p.string(),instance:p.string().optional(),look:Vu.optional(),effect:Bo.optional(),returnTo:qu.optional(),hold:p.boolean().default(!1)}),ij=p.object({enabled:p.boolean().default(!0),actions:p.array(rj).default([]),looks:p.array(oj).default([]),allowSecurity:p.boolean().default(!1),threshold:p.number().min(0).max(100).optional(),modelMatch:p.object({models:p.array(p.string()).min(1),direction:p.enum(["becomes","leaves"]).default("becomes")}).optional()}),sj={contextLow:{kind:"percent",default:75,min:50,max:95,step:1,hysteresis:10,unitLabel:"% context"},contextCritical:{kind:"percent",default:90,min:60,max:99,step:1,hysteresis:10,unitLabel:"% context"},usageHigh:{kind:"percent",default:80,min:50,max:95,step:1,hysteresis:10,unitLabel:"% usage"},costHigh:{kind:"dollars",default:5,min:.5,max:50,step:.5,hysteresis:0,unitLabel:"$ spent"},longRunning:{kind:"minutes",default:10,min:1,max:60,step:1,hysteresis:0,unitLabel:"min working"}},to=Object.fromEntries(Object.entries(sj).map(([t,e])=>[t,e.default])),aj=p.object({proactive:p.boolean().default(!0),doNotDisturb:p.boolean().default(!1),announce:p.record(p.string(),p.boolean()).default({})}),cj=p.object({enabled:p.boolean().default(!1),start:p.string().regex(/^\d{2}:\d{2}$/).default("22:00"),end:p.string().regex(/^\d{2}:\d{2}$/).default("07:00"),tz:p.string().optional()}),lj=p.object({id:p.string(),name:p.string().default(""),icon:p.string().default("spark"),gradient:p.tuple([p.string(),p.string(),p.string()]).optional(),deviceScope:p.array(p.string()).default([]),palette:p.array(Ft).default([]),states:p.record(p.string(),ij).default({}),notifications:aj.default({proactive:!0,doNotDisturb:!1,announce:{}}),quietHours:cj.default({enabled:!1,start:"22:00",end:"07:00"}),updatedAt:p.number().optional(),agent:br.optional()}),Eb=p.object({profiles:p.array(lj).default([]),bindings:p.record(p.string(),p.string()).default({}),codexBindings:p.record(p.string(),p.string()).default({})});function CT(t,e){if(!t.enabled)return!1;let n=a=>{let[c,l]=a.split(":").map(u=>Number(u));return(c??0)*60+(l??0)},o=new Date(e),r=o.getHours()*60+o.getMinutes(),i=n(t.start),s=n(t.end);return i===s?!1:i<s?r>=i&&r<s:r>=i||r<s}var uj={started:"Claude started a session",working:"Claude is working",needs_permission:"Claude needs permission",needsInput:"Claude has a question for you",planReady:"Claude's plan is ready for approval",idle:"Claude is waiting for you",finished:"Claude finished",contextLow:"Claude is at {pct} percent context",contextCritical:"Claude's context is nearly full \u2014 {pct} percent",rateLimited:"You've hit your Claude usage limit",error:"Claude hit an error",ended:"Claude session ended",resumed:"Claude session resumed",subagentStart:"Claude started a subagent",subagentFinished:"A Claude subagent finished",compacting:"Claude is compacting its context",compactDone:"Claude finished compacting",permissionDenied:"A Claude tool call was blocked",taskCompleted:"A background Claude task finished",usageHigh:"Claude usage is at {pct} percent of the {window} window",modePlan:"Claude entered plan mode",modeAuto:"Claude is auto accepting edits",modeBypass:"Claude is bypassing permission checks",modeNormal:"Claude is back to normal permission checks",modelChanged:"Claude switched to {model}",workflowStarted:"Claude launched a workflow",reviewChanged:"The pull request review changed to {review}",costHigh:"This session has cost {cost} dollars",longRunning:"Claude has been working {mins} minutes"};var dj={started:"Codex started a session",resumed:"Codex session resumed",working:"Codex is working",finished:"Codex finished",needs_permission:"Codex needs permission",compacting:"Codex is compacting its context",compactDone:"Codex finished compacting",subagentStart:"Codex started a subagent",subagentFinished:"A Codex subagent finished",contextLow:"Codex is at {pct} percent context",contextCritical:"Codex's context is nearly full \u2014 {pct} percent",modePlan:"Codex entered plan mode",modeAuto:"Codex is auto accepting edits",modeBypass:"Codex is bypassing permission checks",modeNormal:"Codex is back to normal permission checks",modelChanged:"Codex switched to {model}",error:"Codex hit an error",idle:"Codex is waiting",ended:"Codex session ended",permissionDenied:"A Codex action was declined",planReady:"Codex has a plan ready for approval",rateLimited:"Codex hit its usage limit",sandboxEscalation:"Codex wants to leave its sandbox",longRunning:"Codex has been working {mins} minutes"};function pj(t,e){return t==="codex"?dj[e]:uj[e]}var Ib="codex::";function Cb(t,e){return t==="codex"?`${Ib}${e}`:e}function Da(t){return t.startsWith(Ib)?{agent:"codex",repo:t.slice(Ib.length)}:{agent:"claude",repo:t}}function fj(t){return typeof t?.id=="string"&&t.id.startsWith("prof:")}function mj(t,e){return!(!vr[t.capability]?.some(o=>o.command===t.command)||e&&!e.devices.some(o=>o.id===t.deviceId))}var gj=new Set(["color","colorTemperature","brightness"]);function RT(t,e,n){let o=n?.voice??!1,r=Eb.safeParse({profiles:t?.profiles,bindings:t?.bindings,codexBindings:t?.codexBindings}),i=[],s={},a={},c={};if(Array.isArray(t?.rules))for(let l of t.rules){let u=Aa.safeParse(l);u.success&&!fj(u.data)&&i.push(u.data)}if(r.success){let l=new Map(r.data.profiles.map(d=>[d.id,d])),u=[["claude",r.data.bindings],["codex",r.data.codexBindings]];for(let[d,f]of u)for(let[m,g]of Object.entries(f)){let h=l.get(g);if(!h)continue;let y=Cb(d,m);s[y]={proactive:h.notifications.proactive,doNotDisturb:h.notifications.doNotDisturb,quietHours:h.quietHours};for(let[b,w]of Object.entries(h.states)){if(!w.enabled)continue;let x=Yu.safeParse(b);if(!x.success)continue;let I=x.data;I in to&&((a[y]??={})[I]=w.threshold??to[I]),I==="modelChanged"&&w.modelMatch&&(c[y]={models:w.modelMatch.models,direction:w.modelMatch.direction});let E=w.actions.filter(L=>h.deviceScope.includes(L.deviceId)&&mj(L,e)),C=new Set(E.filter(L=>L.capability==="power").map(L=>L.deviceId)),W=[...[...new Set(E.filter(L=>gj.has(L.capability)&&!C.has(L.deviceId)).map(L=>L.deviceId))].map(L=>({kind:"device",deviceId:L,capability:"power",command:"turnOn",params:{}})),...E.map(L=>({kind:"device",deviceId:L.deviceId,capability:L.capability,...L.instance?{instance:L.instance}:{},command:L.command,params:L.params}))],N=pj(d,I),M=o&&h.notifications.announce[I]&&N?[{kind:"notify",title:h.name||"AC Bridge",body:N}]:[],ue=w.looks.filter(L=>h.deviceScope.includes(L.deviceId)).map(L=>({kind:"intent",deviceId:L.deviceId,...L.instance?{instance:L.instance}:{},...L.look?{look:L.look}:{},...L.effect?{effect:L.effect}:{},...L.returnTo?{returnTo:L.returnTo}:{},hold:L.hold})),de=[...W,...ue,...M];if(de.length===0)continue;let K=d==="codex"?`prof:codex:${h.id}:${m}:${I}`:`prof:${h.id}:${m}:${I}`;i.push({id:K,name:h.name?`${h.name} \xB7 ${I}`:I,enabled:!0,trigger:{kind:"session",event:I,repo:m,agent:d},conditions:[],actions:de,allowSecurity:w.allowSecurity})}}}return{rules:i,notifyPolicy:s,thresholds:a,modelMatch:c}}var hj=p.object({hs:Ft.nullable().default(null),brightness:ie.nullable().default(null),kelvin:yr.nullable().default(null)}),yj=p.enum(["shared","dedicated"]),vj=p.enum(["focused","priority","mostRecent"]),bj=p.enum(["profile","repo","session"]),wj=p.object({mode:yj.default("shared"),subMode:vj.default("mostRecent"),priorityBy:bj.default("session"),priority:p.array(p.string()).default([]),dedicatedTo:p.string().nullable().default(null)}),kj=p.object({name:p.string().nullable().default(null),instanceNames:p.record(p.string(),p.string()).default({}),favouriteScenes:p.array(p.string()).default([]),groups:p.array(p.string()).default([]),main:hj.default({hs:null,brightness:null,kelvin:null}),arbitration:wj.default({mode:"shared",subMode:"mostRecent",priorityBy:"session",priority:[],dedicatedTo:null}),participate:p.boolean().default(!0),wakeIfOff:p.boolean().default(!0),allowSecurity:p.boolean().default(!1)}),AT=p.record(p.string(),kj).default({});var yd=require("node:crypto"),zE=require("node:http");hd();var Hz=256*1024,jE=64;function Kz(t,e){if(typeof t!="string")return!1;let n=Buffer.from(t),o=Buffer.from(e);return n.length===o.length&&(0,yd.timingSafeEqual)(n,o)}function HE(t){let e=t.host??"127.0.0.1",n=(u,d)=>d?"origin":Kz(u["x-bridge-hub-token"],t.token)?"ok":"token",o=20,r=new Set,i=u=>typeof u=="string"&&u?(0,yd.createHash)("sha256").update(u).digest("hex").slice(0,8):"none",s=(u,d,f)=>{let m=u==="origin"?"origin":i(d["x-bridge-hub-token"]),g=`${u}:${m}:${f}`;r.has(g)||r.size>=o||(r.add(g),console.error(u==="origin"?`[hub] refused ${f}: an Origin header was present (a browser/renderer origin is never allowed)`:`[hub] refused ${f}: hub-token mismatch (presented ${m}) \u2014 that client is reading a STALE or foreign hub-token file, so everything it sends (Profiles signals included) is being dropped`))},a=(0,zE.createServer)((u,d)=>{let f=n(u.headers,u.headers.origin);if(f!=="ok"){s(f,u.headers,"a local API request"),d.writeHead(f==="origin"?403:401,{"content-type":"application/json"}),d.end(JSON.stringify({error:f==="origin"?"forbidden":"unauthorized"}));return}t.onRequest?t.onRequest(u,d):(d.writeHead(404,{"content-type":"application/json"}),d.end('{"error":"not found"}'))}),c=new gd.default({server:a,maxPayload:Hz,verifyClient:u=>{let d=n(u.req.headers,u.origin);return d!=="ok"&&s(d,u.req.headers,"a channel WebSocket upgrade"),d==="ok"}});a.on("error",u=>{console.error(`[hub] channel server error: ${u.message}`),u.code==="EADDRINUSE"&&(console.error(`[hub] port ${t.port} is already in use \u2014 refusing to start (another process holds it).`),process.exit(1))});let l=0;return c.on("connection",u=>{if(l>=jE){console.error(`[hub] channel connection cap (${jE}) reached \u2014 rejecting a new socket`),u.close(1013,"too many connections");return}l+=1;let d={sessionId:null,refused:!1},f=m=>u.readyState!==_r.default.OPEN?!1:(u.send(m),!0);u.on("message",m=>{let g;try{g=Qu(m.toString())}catch(h){console.error("[hub] bad channel frame:",h);return}try{if(g.type==="register"){let h=g.sessions[0];if(h){let y=t.onRegister(h,f,()=>u.close(1008,"replaced"),g.claudeSessionId);d.sessionId=y?h.id:null,d.refused=!y}return}t.onMessage(g,f,d)}catch(h){console.error("[hub] channel dispatch threw:",h)}}),u.on("close",()=>{if(l-=1,d.sessionId)try{t.onDisconnect(d.sessionId)}catch(m){console.error("[hub] channel onDisconnect threw:",m)}})}),a.listen(t.port,e,()=>t.onListening?.(a.address().port)),{port:t.port,close:()=>{c.close(),a.close()}}}var Gz=64*1024;function WE(t,e,n,o,r,i,s,a,c,l){return(u,d)=>{try{Wz(t,e,n,o,r,i,s,a,c??null,l,u,d)}catch{d.writableEnded||Z(d,400,{error:"bad request"})}}}function Wz(t,e,n,o,r,i,s,a,c,l,u,d){let m=new URL(u.url??"/","http://127.0.0.1").pathname.split("/").filter(Boolean),g=u.method??"GET",h=y=>m.length===2&&m[0]==="local"&&m[1]===y;if(g==="POST"&&h("scan")){Be(u,d,()=>Z(d,200,t.startScan()));return}if(g==="GET"&&m.length===3&&m[0]==="local"&&m[1]==="scan"){let y=Zz(m[2]),b=y===null?null:t.getSession(y);Z(d,b?200:404,b??{error:"unknown or expired scan"});return}if(g==="GET"&&h("discovered")){Z(d,200,t.getDiscovered());return}if(g==="GET"&&h("config")){Z(d,200,t.getConfig());return}if(g==="POST"&&h("config")){Be(u,d,y=>{let b=null;try{let x=JSON.parse(y);x&&typeof x=="object"&&!Array.isArray(x)&&(b=x)}catch{}if(b!==null&&Object.keys(b).length===0)return Z(d,400,{error:"POST /local/config needs the full config document \u2014 GET it, change what you want, and POST it back. An empty body would reset every setting."});let w=Et(jo,y,d);if(w)try{Z(d,200,t.applyConfig(w))}catch{jt(d)}});return}if(g==="POST"&&h("connect")){Be(u,d,y=>{let b=Et(pT,y,d);b&&t.connect(b).then(w=>qz(d,w)).catch(()=>jt(d))});return}if(g==="POST"&&h("forget")){Be(u,d,y=>{let b=Et(fT,y,d);b&&t.forget(b).then(w=>GE(d,w)).catch(()=>jt(d))});return}if(g==="POST"&&h("rename")){Be(u,d,y=>{let b=Et(mT,y,d);b&&t.rename(b).then(w=>GE(d,w)).catch(()=>jt(d))});return}if(g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="tuya"&&m[2]==="link"){Be(u,d,y=>{let b=Et(gT,y,d);b&&t.linkTuya(b).then(w=>Z(d,w.ok?200:502,w)).catch(()=>jt(d))});return}if(g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="meross"&&m[2]==="link"){Be(u,d,y=>{let b=Et(hT,y,d);b&&t.linkMeross(b).then(w=>Z(d,w.ok?200:502,w)).catch(()=>jt(d))});return}if(g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="ewelink"&&m[2]==="link"){Be(u,d,y=>{let b=Et(yT,y,d);b&&t.linkEwelink(b).then(w=>Z(d,w.ok?200:502,w)).catch(()=>jt(d))});return}if(g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="govee"&&m[2]==="link"){Be(u,d,y=>{let b=Et(vT,y,d);b&&t.linkGovee(b).then(w=>Z(d,w.ok?200:502,w)).catch(()=>jt(d))});return}if(g==="POST"&&m.length===3&&m[0]==="local"&&m[2]==="unlink"){let y=Hn.safeParse(m[1]);if(!y.success)return Z(d,404,{error:"unknown provider"});t.unlinkProvider(y.data).then(b=>Z(d,200,b)).catch(()=>jt(d));return}if(n&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="session"&&m[2]==="state"){Be(u,d,y=>{let b=Et(kT,y,d);b&&(n(b),Z(d,200,{ok:!0}))});return}if(s&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="session"&&m[2]==="context"){Be(u,d,y=>{let b=Et(xT,y,d);b&&(s(b),Z(d,200,{ok:!0}))});return}if(l&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="session"&&m[2]==="usage"){Be(u,d,y=>{let b=Et(ST,y,d);b&&(l(b),Z(d,200,{ok:!0}))});return}if(o&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="rules"&&m[2]==="refresh"){Be(u,d,()=>{o(),Z(d,200,{ok:!0})});return}if(i&&g==="POST"&&m.length===2&&m[0]==="local"&&m[1]==="reload"){Be(u,d,()=>{i(),Z(d,200,{ok:!0})});return}if(a&&g==="GET"&&h("devices")){Z(d,200,a());return}if(e&&g==="GET"&&h("session")){Z(d,200,{...e.status(),accountSub:c});return}if(e&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="session"){let y=m[2];if(y==="activate"){Be(u,d,b=>{let w=Et(bT,b,d);w&&e.activate(w).then(x=>Z(d,200,x)).catch(()=>jt(d))});return}if(y==="heartbeat"){Be(u,d,b=>{let w=Et(_b,b,d);w&&Z(d,200,e.heartbeat(w.sessionId))});return}if(y==="stop"){Be(u,d,b=>{let w=Et(_b,b,d);w&&e.stop(w.sessionId).then(x=>Z(d,200,x)).catch(()=>jt(d))});return}}if(r&&g==="POST"&&m.length===3&&m[0]==="local"&&m[1]==="hub"){let y=m[2];if(y==="hold"){Be(u,d,b=>{let w;try{w=b?JSON.parse(b):{}}catch{return Z(d,400,{error:"invalid JSON body"})}if(!cl(w.kind)||typeof w.pid!="number"||!Number.isInteger(w.pid)||w.pid<=0)return Z(d,400,{error:"hold needs {kind: app|daemon|run|cli, pid: >0}"});if(w.stream===!0){let x=r.hold({kind:w.kind,pid:w.pid,connected:!0});d.writeHead(200,{"content-type":"application/x-ndjson","cache-control":"no-store"}),d.write(`${JSON.stringify(x)}
163
+ `),u.socket.setTimeout(0),d.on("close",()=>r.release(x.holderId));return}Z(d,200,r.hold({kind:w.kind,pid:w.pid}))});return}if(y==="beat"){Be(u,d,b=>{let w=KE(b);if(w===null)return Z(d,400,{error:"beat needs {holderId}"});let x=r.beat(w);Z(d,x?200:404,x?{ok:!0}:{error:"unknown holder"})});return}if(y==="release"){Be(u,d,b=>{let w=KE(b);if(w===null)return Z(d,400,{error:"release needs {holderId}"});r.release(w),Z(d,200,{ok:!0})});return}if(y==="shutdown"){Be(u,d,()=>{Z(d,200,{ok:!0}),r.shutdown()});return}}Z(d,404,{error:"not found"})}function KE(t){try{let e=t?JSON.parse(t):{};return typeof e.holderId=="string"&&e.holderId?e.holderId:null}catch{return null}}function Zz(t){try{return decodeURIComponent(t)}catch{return null}}function qz(t,e){switch(e.kind){case"ok":Z(t,200,ZE({deviceId:e.deviceId,accountId:e.accountId,...e.note?{note:e.note}:{}}));return;case"unknown-id":Z(t,404,zt("unknown discoveredId","run a scan and use a discoveredId from its results"));return;case"link-ecosystem":Z(t,409,{ok:!1,error:"this device is managed by an ecosystem",note:`link via ${e.provider??"its ecosystem"}`,...e.provider?{linkVia:e.provider}:{}});return;case"identified-only":Z(t,422,zt("no direct local adapter for this device",e.hint??"control it via a linked Home Assistant, or wait for a future adapter"));return;case"protocol-mismatch":Z(t,422,zt("protocol mismatch",e.expected?`this device speaks ${e.expected}`:"this device speaks a different protocol"));return;case"protocol-unsupported":Z(t,422,zt("protocol not yet supported","no local adapter for this protocol is installed"));return;case"mac-unresolved":Z(t,422,zt("mac-unresolved","the device did not reveal a stable identity to connect by"));return;case"credentials-required":Z(t,428,{ok:!1,error:"credentials-required",note:e.note??"this protocol needs an account credential \u2014 supply it and retry"});return;case"pairing-required":Z(t,428,{ok:!1,error:"pairing-required",note:e.note??"hold the device's pairing button until it flashes, then connect again"});return;case"device-rejected":Z(t,422,zt(e.error));return;case"never-auto-floor":Z(t,422,zt("never-auto floor","this device type is never auto-connected \u2014 connect it manually"));return;case"unreachable":Z(t,502,zt("unreachable"));return;case"adapter-init-failed":Z(t,502,zt(e.error,"will retry at hub start"));return;default:{let n=e;jt(t)}}}function GE(t,e){e.kind==="ok"?Z(t,200,ZE(e.note?{note:e.note}:{})):Z(t,404,zt("unknown deviceId"))}var ZE=t=>({ok:!0,...t}),zt=(t,e)=>({ok:!1,error:t,...e?{note:e}:{}}),jt=t=>{t.writableEnded||Z(t,500,zt("internal error"))};function Et(t,e,n){let o;try{o=e?JSON.parse(e):{}}catch{Z(n,400,zt("invalid JSON body"));return}let r=t.safeParse(o);if(!r.success){Z(n,400,zt("invalid request body"));return}return r.data}function Z(t,e,n){let o=JSON.stringify(n);t.writeHead(e,{"content-type":"application/json"}),t.end(o)}function Be(t,e,n){let o=0,r=[];t.on("data",i=>{if(o+=i.length,o>Gz){Z(e,413,{error:"payload too large"}),r.length=0,t.removeAllListeners("data"),t.on("data",()=>{});return}r.push(i)}),t.on("end",()=>{if(!e.writableEnded)try{n(Buffer.concat(r).toString("utf8"))}catch{jt(e)}}),t.on("error",()=>{e.writableEnded||Z(e,400,{error:"bad request"})})}function qE(t,e){let n=e?.write??((i,s)=>pe(i,s,384)),o=e?.now??Date.now,r=e?.file??fm;try{n(r,JSON.stringify({pid:e?.pid??process.pid,port:t.port,startedAt:o(),...t.sub?{sub:t.sub}:{}}))}catch{}}function VE(t){let e=t?.remove??(n=>it(n));try{e(t?.file??fm)}catch{}}function Vz(t,e,n){if(t===null)return"proceed";let o=n(e);return o===null||o===t?"proceed":"stop"}function JE(t,e,n,o){return Vz(e,t,n)==="stop"?(o(),""):t}function YE({envPath:t,scope:e}){return t||(e?ol(e).relayAccessFile:"")}function Jz(t,e){return t===null?e===null?"proceed":"stop":e===null||e===t?"proceed":"stop"}function XE(t,e=2){let n=null,o=0;return r=>Jz(t,r)==="proceed"?(n=null,o=0,"proceed"):(o>0&&r===n?o+=1:(n=r,o=1),o>=e?"stop":"proceed")}var QE=G(require("node:path"),1);function vd(t,e){return e===null?"no-scope":t?t===e?"adopt":"mismatch":"absent"}function eC(t,e){if(e.includes("/")||e.includes("\\")||e.includes(".."))return;let n=X(QE.default.join(t,`${e}.json`));if(n)try{let o=JSON.parse(n);return typeof o.sub=="string"&&o.sub?o.sub:void 0}catch{return}}var Jb={2:{expectedType:"bridge",expectedCapabilities:[]},3:{expectedType:"fan",expectedCapabilities:["power","fan"]},4:{expectedType:"garageDoor",expectedCapabilities:["cover"]},5:{expectedType:"light",expectedCapabilities:["power","brightness"]},6:{expectedType:"lock",expectedCapabilities:["lock"]},7:{expectedType:"plug",expectedCapabilities:["power"]},8:{expectedType:"switch",expectedCapabilities:["power"]},9:{expectedType:"thermostat",expectedCapabilities:["thermostat"]},10:{expectedType:"sensor",expectedCapabilities:["sensor"]},12:{expectedType:"cover",expectedCapabilities:["cover"]},13:{expectedType:"cover",expectedCapabilities:["cover"]},14:{expectedType:"cover",expectedCapabilities:["cover"]},17:{expectedType:"camera",expectedCapabilities:["camera"]},18:{expectedType:"doorbell",expectedCapabilities:["doorbell"]},19:{expectedType:"airPurifier",expectedCapabilities:["power","fan"]},22:{expectedType:"humidifier",expectedCapabilities:["power"]},26:{expectedType:"speaker",expectedCapabilities:["volume"]},28:{expectedType:"valve",expectedCapabilities:[]},31:{expectedType:"tv",expectedCapabilities:["power"]}},Yb="Philips Hue light \u2014 connect via its Hue Bridge (Integrations \u2192 Hue)",tC=[{prefix:"BSB",manufacturer:"Signify",product:"Hue Bridge",hueBridge:!0},{prefix:"LCT",manufacturer:"Signify",product:"Hue color bulb",hueBulb:!0},{prefix:"LTW",manufacturer:"Signify",product:"Hue ambiance bulb",hueBulb:!0},{prefix:"LWB",manufacturer:"Signify",product:"Hue white bulb",hueBulb:!0},{prefix:"LWA",manufacturer:"Signify",product:"Hue white bulb",hueBulb:!0},{prefix:"LCA",manufacturer:"Signify",product:"Hue color bulb",hueBulb:!0},{prefix:"LST",manufacturer:"Signify",product:"Hue lightstrip",hueBulb:!0},{prefix:"LLC",manufacturer:"Signify",product:"Hue accent light",hueBulb:!0},{prefix:"LIFX",manufacturer:"LIFX"},{prefix:"NL",manufacturer:"Nanoleaf"},{prefix:"TRADFRI",manufacturer:"IKEA",product:"Tr\xE5dfri"},{prefix:"Wemo",manufacturer:"Belkin",product:"Wemo"},{prefix:"Socket",manufacturer:"Belkin",product:"Wemo socket"},{prefix:"YL",manufacturer:"Yeelight"},{prefix:"ecobee",manufacturer:"Ecobee",product:"Ecobee thermostat"},{prefix:"EB",manufacturer:"Ecobee"},{prefix:"Eve ",manufacturer:"Eve Systems"},{prefix:"MSS",manufacturer:"Meross"},{prefix:"Rachio",manufacturer:"Rachio",product:"Rachio sprinkler"},{prefix:"Smart Bridge",manufacturer:"Lutron",product:"Cas\xE9ta Smart Bridge"},{prefix:"iSmartGate",manufacturer:"iSmartGate",product:"Garage controller"},{prefix:"Sensibo",manufacturer:"Sensibo"},{prefix:"tado",manufacturer:"tado\xB0"},{prefix:"AC02",manufacturer:"tado\xB0"}];function bd(t){return tC.find(e=>t.startsWith(e.prefix))}function Xb(t){return t!==void 0&&bd(t)?.hueBulb===!0}var nC=[{hostnameGlob:"ring*",macPrefix:"0c:ae:7d",vendor:"Ring",product:"Ring device"},{hostnameGlob:"ring*",macPrefix:"2c:ab:33",vendor:"Ring",product:"Ring device"},{hostnameGlob:"wiz_*",vendor:"WiZ",product:"WiZ light",probeHint:"wiz"},{hostnameGlob:"shelly*",vendor:"Shelly",product:"Shelly device",probeHint:"shelly"},{hostnameGlob:"lifx*",vendor:"LIFX",product:"LIFX light",probeHint:"lifx"},{macPrefix:"d0:73:d5",vendor:"LIFX",product:"LIFX light",probeHint:"lifx"},{macPrefix:"a8:bb:50",vendor:"WiZ",product:"WiZ light",probeHint:"wiz"},{macPrefix:"d8:a0:11",vendor:"WiZ",product:"WiZ light",probeHint:"wiz"},{macPrefix:"44:4f:8e",vendor:"WiZ",product:"WiZ light",probeHint:"wiz"},{macPrefix:"6c:29:90",vendor:"WiZ",product:"WiZ light",probeHint:"wiz"},{hostnameGlob:"hs1*",vendor:"TP-Link Kasa",product:"Kasa smart plug",probeHint:"kasa"},{hostnameGlob:"hs2*",vendor:"TP-Link Kasa",product:"Kasa smart plug",probeHint:"kasa"},{hostnameGlob:"kl*",vendor:"TP-Link Kasa",product:"Kasa smart bulb",probeHint:"kasa"},{hostnameGlob:"kp*",vendor:"TP-Link Kasa",product:"Kasa smart plug",probeHint:"kasa"},{hostnameGlob:"ks2*",vendor:"TP-Link Kasa",product:"Kasa smart switch",probeHint:"kasa"},{hostnameGlob:"lb1*",vendor:"TP-Link Kasa",product:"Kasa smart bulb",probeHint:"kasa"},{hostnameGlob:"ep1*",vendor:"TP-Link Kasa",product:"Kasa smart plug",probeHint:"kasa"},{hostnameGlob:"ep2*",vendor:"TP-Link Kasa",product:"Kasa smart plug",probeHint:"kasa"},{hostnameGlob:"es2*",vendor:"TP-Link Kasa",product:"Kasa smart switch",probeHint:"kasa"},{hostnameGlob:"p1*",macPrefix:"5c:e9:31",vendor:"TP-Link Tapo",product:"Tapo smart plug"},{hostnameGlob:"p1*",macPrefix:"3c:52:a1",vendor:"TP-Link Tapo",product:"Tapo smart plug"},{hostnameGlob:"l5*",macPrefix:"3c:52:a1",vendor:"TP-Link Tapo",product:"Tapo smart bulb"},{hostnameGlob:"l9*",macPrefix:"3c:52:a1",vendor:"TP-Link Tapo",product:"Tapo smart bulb"},{hostnameGlob:"tapo*",vendor:"TP-Link Tapo",product:"Tapo device"},{hostnameGlob:"philips-hue*",vendor:"Signify",product:"Hue Bridge"},{hostnameGlob:"hue-bridge*",vendor:"Signify",product:"Hue Bridge"},{hostnameGlob:"st*",macPrefix:"24:fd:5b",vendor:"SmartThings",product:"SmartThings hub"},{hostnameGlob:"smartthings*",vendor:"SmartThings",product:"SmartThings hub"},{hostnameGlob:"homeassistant*",vendor:"Home Assistant",product:"Home Assistant"},{hostnameGlob:"amazon-*",vendor:"Amazon",product:"Echo / Fire device"},{hostnameGlob:"echo-*",vendor:"Amazon",product:"Echo"},{hostnameGlob:"google-*",vendor:"Google",product:"Google Home / Cast"},{hostnameGlob:"googlehome*",vendor:"Google",product:"Google Home"},{hostnameGlob:"chromecast*",vendor:"Google",product:"Chromecast"},{hostnameGlob:"sonos*",vendor:"Sonos",product:"Sonos speaker"},{hostnameGlob:"tizen*",vendor:"Samsung",product:"Samsung TV"},{hostnameGlob:"yeelink-*",vendor:"Yeelight",product:"Yeelight light"},{hostnameGlob:"wled-*",vendor:"WLED",product:"WLED controller"},{hostnameGlob:"govee_*",vendor:"Govee",product:"Govee light",probeHint:"govee"},{hostnameGlob:"nanoleaf*",vendor:"Nanoleaf",product:"Nanoleaf panels"},{hostnameGlob:"esphome-*",vendor:"ESPHome",product:"ESPHome device"},{hostnameGlob:"tasmota*",vendor:"Tasmota",product:"Tasmota device"},{hostnameGlob:"esp32-*",vendor:"Espressif",product:"ESP32 device"},{hostnameGlob:"esp-*",vendor:"Espressif",product:"ESP device"},{hostnameGlob:"esp_*",vendor:"Espressif",product:"ESP device"},{hostnameGlob:"sonoff*",vendor:"SONOFF (ITEAD)",product:"SONOFF device"},{hostnameGlob:"ewelink*",vendor:"SONOFF (ITEAD)",product:"eWeLink device"},{hostnameGlob:"switchbot*",vendor:"SwitchBot",product:"SwitchBot hub"},{hostnameGlob:"hive*",vendor:"Hive (Centrica)",product:"Hive hub"},{hostnameGlob:"eufy*",vendor:"eufy (Anker)",product:"eufy HomeBase"},{hostnameGlob:"homebase*",vendor:"eufy (Anker)",product:"eufy HomeBase"},{hostnameGlob:"aqara*",vendor:"Aqara (Lumi)",product:"Aqara hub"},{hostnameGlob:"lumi-*",vendor:"Aqara (Lumi)",product:"Aqara hub"},{hostnameGlob:"tado*",vendor:"tado\xB0",product:"tado\xB0 Internet Bridge"},{hostnameGlob:"lepro*",vendor:"Lepro",product:"Lepro light"},{hostnameGlob:"roomba-*",vendor:"iRobot",product:"Roomba"},{hostnameGlob:"irobot-*",vendor:"iRobot",product:"Roomba"},{hostnameGlob:"roborock-*",vendor:"Roborock",product:"Robot vacuum"},{hostnameGlob:"blink*",vendor:"Blink (Amazon)",product:"Blink camera"},{hostnameGlob:"august*",vendor:"August",product:"August lock/bridge"},{hostnameGlob:"ecobee*",vendor:"Ecobee",product:"Ecobee thermostat"},{hostnameGlob:"nest-*",vendor:"Google Nest",product:"Nest device"},{hostnameGlob:"myq-*",vendor:"Chamberlain",product:"myQ garage"},{hostnameGlob:"rachio-*",vendor:"Rachio",product:"Rachio sprinkler"},{hostnameGlob:"sense-*",vendor:"Sense",product:"Sense energy monitor"},{hostnameGlob:"levoit-*",vendor:"Levoit (VeSync)",product:"Levoit purifier/humidifier"},{hostnameGlob:"meross*",vendor:"Meross",product:"Meross device"},{hostnameGlob:"wyze*",vendor:"Wyze",product:"Wyze device"},{hostnameGlob:"flume-gw-*",vendor:"Flume",product:"Flume water monitor"},{hostnameGlob:"airthings-*",vendor:"Airthings",product:"Airthings monitor"}];function rC(t){let e=t.replace(/[.*+?^${}()|[\]\\]/g,n=>n==="*"?".*":`\\${n}`);return new RegExp(`^${e}$`,"i")}function Ba(t){let e=t.mac?T(t.mac):void 0;return nC.find(n=>!(n.hostnameGlob&&(!t.hostname||!rC(n.hostnameGlob).test(t.hostname))||n.macPrefix&&(!e||!e.startsWith(n.macPrefix))))}var ja={kasa:{bucket:"connect-now",confidence:"high",localProtocol:"kasa",identityWeight:2},"kasa-klap":{bucket:"connect-now",confidence:"high",localProtocol:"kasa-klap",identityWeight:2},wiz:{bucket:"connect-now",confidence:"high",localProtocol:"wiz",identityWeight:2},lifx:{bucket:"connect-now",confidence:"high",localProtocol:"lifx",identityWeight:2},shelly:{bucket:"connect-now",confidence:"high",localProtocol:"shelly",identityWeight:2},"shelly-gen1":{bucket:"identified-only",confidence:"high",hint:"Gen1 Shelly \u2014 not controllable directly yet; control it via a linked Home Assistant",identityWeight:2},"hue-bridge":{bucket:"link-ecosystem",confidence:"high",suggestedProvider:"hue",expectedType:"bridge",identityWeight:2},"home-assistant":{bucket:"link-ecosystem",confidence:"high",suggestedProvider:"homeassistant",expectedType:"bridge",identityWeight:2},smartthings:{bucket:"link-ecosystem",confidence:"high",suggestedProvider:"smartthings",expectedType:"bridge",identityWeight:2},hap:{bucket:"identified-only",confidence:"medium",hint:"HomeKit device \u2014 commands shown are expected only",identityWeight:1},"hue-bulb":{bucket:"identified-only",confidence:"medium",expectedType:"light",hint:Yb,identityWeight:1},matter:{bucket:"identified-only",confidence:"medium",hint:"Matter device \u2014 control via the ecosystem it's commissioned into",identityWeight:0},"matter-pairing":{bucket:"identified-only",confidence:"medium",hint:"Matter device in pairing mode \u2014 commissioning isn't supported yet",identityWeight:1},cast:{bucket:"identified-only",confidence:"high",expectedType:"mediaPlayer",expectedCapabilities:["volume","mediaTransport"],hint:"Google Cast device \u2014 no local control in v1",identityWeight:2},sonos:{bucket:"identified-only",confidence:"high",expectedType:"speaker",expectedCapabilities:["volume","mediaTransport"],hint:"Sonos speaker \u2014 control via Home Assistant",identityWeight:2},androidtv:{bucket:"identified-only",confidence:"high",expectedType:"tv",hint:"Android TV \u2014 control via its ecosystem",identityWeight:1},printer:{bucket:"identified-only",confidence:"medium",expectedType:"other",hint:"Network printer",identityWeight:1},miio:{bucket:"identified-only",confidence:"high",hint:"Xiaomi / miIO device \u2014 control via Home Assistant",identityWeight:2},lutron:{bucket:"identified-only",confidence:"high",expectedType:"bridge",hint:"Lutron Cas\xE9ta \u2014 control via Home Assistant",identityWeight:2},bond:{bucket:"identified-only",confidence:"high",expectedType:"bridge",hint:"Bond Bridge \u2014 control via Home Assistant",identityWeight:2},octoprint:{bucket:"identified-only",confidence:"high",expectedType:"other",hint:"OctoPrint 3D-print server",identityWeight:2},apple:{bucket:"identified-only",confidence:"high",hint:"Apple TV / HomePod / AirPlay device \u2014 control via HomeKit or Home Assistant",identityWeight:1},roku:{bucket:"connect-now",confidence:"high",localProtocol:"roku",expectedType:"tv",expectedCapabilities:["power","mediaTransport","volume"],identityWeight:2},wled:{bucket:"connect-now",confidence:"high",localProtocol:"wled",expectedType:"light",expectedCapabilities:["power","brightness","color"],identityWeight:2},esphome:{bucket:"connect-now",confidence:"high",localProtocol:"esphome",identityWeight:1},nanoleaf:{bucket:"connect-now",confidence:"high",localProtocol:"nanoleaf",expectedType:"light",expectedCapabilities:["power","brightness","color"],identityWeight:2},elgato:{bucket:"connect-now",confidence:"high",localProtocol:"elgato",expectedType:"light",expectedCapabilities:["power","brightness","colorTemperature"],identityWeight:2},yeelight:{bucket:"connect-now",confidence:"high",localProtocol:"yeelight",identityWeight:2},ewelink:{bucket:"identified-only",confidence:"high",hint:"SONOFF / eWeLink device \u2014 sign in with eWeLink (acbridge link ewelink) to control it on your network",identityWeight:2},"ewelink-diy":{bucket:"connect-now",confidence:"high",localProtocol:"ewelink",expectedCapabilities:["power"],identityWeight:2},govee:{bucket:"connect-now",confidence:"high",localProtocol:"govee",identityWeight:2},tuya:{bucket:"identified-only",confidence:"low",hint:"Smart Life / Tuya device \u2014 run the Tuya key wizard (acbridge link tuya) to enable local control",identityWeight:0},"tplink-smart":{bucket:"connect-now",confidence:"high",localProtocol:"tapo",identityWeight:2},"kasa-noncontrol":{bucket:"identified-only",confidence:"high",hint:"Kasa device \u2014 no local adapter for this model in v1",identityWeight:2},gateway:{bucket:"identified-only",confidence:"medium",expectedType:"bridge",hint:"Your network's router \u2014 not a controllable smart device",identityWeight:1},"mqtt-broker":{bucket:"link-ecosystem",confidence:"high",suggestedProvider:"mqtt",expectedType:"bridge",hint:"MQTT broker \u2014 link it to bring in everything publishing Home Assistant discovery (Zigbee2MQTT, Tasmota\u2026)",identityWeight:2},"thread-border-router":{bucket:"identified-only",confidence:"high",expectedType:"bridge",hint:"Thread border router \u2014 the Thread devices behind it are reached through their own ecosystem",identityWeight:1},wemo:{bucket:"identified-only",confidence:"high",expectedType:"plug",hint:"Belkin Wemo \u2014 control via Home Assistant",identityWeight:2},hubitat:{bucket:"identified-only",confidence:"high",expectedType:"bridge",hint:"Hubitat Elevation hub \u2014 control via Home Assistant",identityWeight:2},"ssdp-generic":{bucket:"identified-only",confidence:"medium",identityWeight:0},"http-generic":{bucket:"identified-only",confidence:"medium",identityWeight:0},dhcp:{bucket:"identified-only",confidence:"low",identityWeight:0},oui:{bucket:"identified-only",confidence:"low",identityWeight:0},unidentified:{bucket:"identified-only",confidence:"low",identityWeight:0},"mdns-service":{bucket:"identified-only",confidence:"medium",identityWeight:0}},iC={"kasa-udp":6,"wiz-udp":6,"lifx-lan":6,yeelight:6,"govee-udp":6,meethue:6,http:5,mdns:4,ssdp:3,arp:2,"tuya-beacon":1},Yz=new Set(["oui","dhcp","ssdp-generic","http-generic","unidentified","mdns-service"]),Xz=new Set(["unidentified","mdns-service"]),ms={"connect-now":3,"link-ecosystem":2,"identified-only":1},oC={high:3,medium:2,low:1},Qz=["low","medium","high"];function sC(t){let e;for(let n of t){let o=ja[n];(!e||ms[o.bucket]>ms[e.row.bucket]||ms[o.bucket]===ms[e.row.bucket]&&o.identityWeight>e.row.identityWeight)&&(e={kind:n,row:o})}return e??{kind:"oui",row:ja.oui}}function fs(t,e,n){return e===void 0?t:!t||n>t.rank?{value:e,rank:n}:t}var Zo=class{rows=new Map;add(e){let n=e.addresses.mac?T(e.addresses.mac):void 0,o=n?`mac:${n}`:`ip:${e.addresses.ip}`,r=this.rows.get(o),i=!1;if(!r&&n){let c=this.rows.get(`ip:${e.addresses.ip}`);c&&(this.rows.delete(`ip:${e.addresses.ip}`),c.mac=n,c.discoveredId=Pa({ip:c.ip,mac:n}),this.rows.set(o,c),r=c)}if(!r&&!n){let c,l=0;for(let u of this.rows.values())u.ip===e.addresses.ip&&(c=u,l++);l===1&&(r=c)}r||(i=!0,r={discoveredId:Pa({ip:e.addresses.ip,mac:n},e.primaryService),ip:e.addresses.ip,mac:n,primaryService:e.primaryService,evidence:[],kinds:new Set,firstSeen:e.evidence.at,lastSeen:e.evidence.at},this.rows.set(o,r)),r.kinds.add(e.kind),r.firstSeen=Math.min(r.firstSeen,e.evidence.at),r.lastSeen=Math.max(r.lastSeen,e.evidence.at),r.mac!==void 0&&e.addresses.ip!==r.ip&&e.evidence.protocol!=="arp"&&(r.ip=e.addresses.ip),r.hostname===void 0&&e.addresses.hostname!==void 0&&(r.hostname=e.addresses.hostname),r.port===void 0&&e.addresses.port!==void 0&&(r.port=e.addresses.port);let s=r.evidence.find(c=>c.protocol===e.evidence.protocol&&c.detail===e.evidence.detail);s?s.at=Math.max(s.at,e.evidence.at):r.evidence.push({...e.evidence});let a=iC[e.evidence.protocol]*10+ja[e.kind].identityWeight;return r.name=fs(r.name,e.identity?.name,a),r.manufacturer=fs(r.manufacturer,e.identity?.manufacturer,a),r.model=fs(r.model,e.identity?.model,a),e.identity?.hint!==void 0&&(!r.hint||a>r.hint.rank)&&(r.hint={value:e.identity.hint,rank:a},r.hintProtocol=e.evidence.protocol),r.vendorId=fs(r.vendorId,e.identity?.vendorId,a),r.expectedType=fs(r.expectedType,e.expectedType,a),r.expectedCapabilities=fs(r.expectedCapabilities,e.expectedCapabilities,a),{created:i}}prune(e){let n=0;for(let[o,r]of this.rows)r.lastSeen<e&&(this.rows.delete(o),n++);return n}snapshot(){let e=[...this.rows.values()].map(r=>{let{kind:i,row:s}=sC([...r.kinds]),a=1;for(let g of r.kinds)a=Math.max(a,oC[ja[g].confidence]);r.mac||(a=Math.min(a,oC.medium));let c=Qz[a-1]??"low",l={};r.name&&(l.name=r.name.value),r.manufacturer&&(l.manufacturer=r.manufacturer.value),r.model&&(l.model=r.model.value),r.vendorId&&(l.vendorId=r.vendorId.value);let u=!1;if(r.hostname!==void 0){let g=Ba({mac:r.mac,hostname:r.hostname});if(g!==void 0){let h=Yz.has(i);(l.manufacturer===void 0||h)&&(l.manufacturer=g.vendor),g.product!==void 0&&(l.model===void 0||h)&&(l.model=g.product),u=h}}let d;if(s.bucket==="connect-now")d=void 0;else if(s.bucket==="link-ecosystem"){let g=r.hint!==void 0&&r.hintProtocol!=="arp"&&r.hintProtocol!=="tuya-beacon";d=s.hint??(g?r.hint?.value:void 0)}else d=u?s.hint:r.hint?.value??s.hint;d!==void 0&&(l.hint=d);let f={discoveredId:r.discoveredId,addresses:{ip:r.ip},evidence:[...r.evidence].sort((g,h)=>g.at-h.at),identity:l,bucket:s.bucket,kind:i,expectedCapabilities:[...r.expectedCapabilities?.value??s.expectedCapabilities??[]],confidence:c,firstSeen:r.firstSeen,lastSeen:r.lastSeen};r.mac!==void 0&&(f.addresses.mac=r.mac),r.hostname!==void 0&&(f.addresses.hostname=r.hostname),r.port!==void 0&&(f.addresses.port=r.port),s.localProtocol!==void 0&&(f.localProtocol=s.localProtocol),s.suggestedProvider!==void 0&&(f.suggestedProvider=s.suggestedProvider);let m=r.expectedType?.value??s.expectedType;return m!==void 0&&(f.expectedType=m),f}),n=r=>r.identity.name??r.identity.model??r.identity.hint??r.addresses.hostname??r.addresses.ip,o=r=>Xz.has(r.kind)?1:0;return e.sort((r,i)=>ms[i.bucket]-ms[r.bucket]||o(r)-o(i)||n(r).localeCompare(n(i),"en",{sensitivity:"base"})||(r.discoveredId<i.discoveredId?-1:r.discoveredId>i.discoveredId?1:0))}};var fC=require("node:dgram"),mC=require("node:fs/promises"),_d=require("node:os");var aC=require("node:child_process"),cC=require("node:fs"),lC=require("node:fs/promises"),uC=require("node:path"),dC=require("node:util");function we(t){if(t===void 0)return;let e=T(t);return e.length===17?e:void 0}var e6=new TextEncoder;function Ze(t,e,n,o){let r,i=!1,s=!1,a=[],c=()=>{s=!0,a.length=0;try{r?.close()}catch{}for(let y of f){y.dead=!0,y.pending.length=0;try{y.sock?.close()}catch{}}},l=!1,u=y=>{if(!l){l=!0;try{o?.(y)}catch{}}c()},d=(y,b,w)=>{try{r?.send(y,b,w,()=>{})}catch(x){u(x)}},f=[],m=y=>{if(y==="255.255.255.255")return!0;let b=Number(y.split(".")[0]);return Number.isInteger(b)&&b>=224&&b<=239},g=(y,b)=>{try{y.sock?.send(b.msg,b.port,b.address,()=>{})}catch{y.dead=!0}},h=[];try{let y=t.interfaceAddresses?.()??[];y.length>=2&&(h=y)}catch{}try{r=t.createSocket("udp4",{reuseAddr:!0}),r.on("error",u),r.on("message",(y,b)=>{if(!s)try{n(y,b)}catch{}}),r.bind(e.port??0,()=>{if(!s){if(e.broadcast)try{r?.setBroadcast(!0)}catch(y){u(y);return}if(e.membership!==void 0)try{r?.addMembership(e.membership)}catch{}i=!0;for(let y of a.splice(0))d(y.msg,y.port,y.address)}})}catch(y){u(y)}for(let y of h){let b={bound:!1,dead:!1,pending:[]};f.push(b);try{let w=t.createSocket("udp4",{reuseAddr:!0});b.sock=w,w.on("error",()=>{b.dead=!0,b.pending.length=0;try{w.close()}catch{}}),w.on("message",(x,I)=>{if(!(s||b.dead))try{n(x,I)}catch{}}),w.bind(0,y,()=>{if(!(s||b.dead)){if(e.broadcast)try{w.setBroadcast(!0)}catch{b.dead=!0;return}if(e.membership!==void 0)try{w.addMembership(e.membership)}catch{}try{w.setMulticastInterface?.(y)}catch{}b.bound=!0;for(let x of b.pending.splice(0))g(b,x)}})}catch{b.dead=!0}}return{send(y,b,w){if(s)return;let x=typeof y=="string"?e6.encode(y):y;if(i?d(x,b,w):a.push({msg:x,port:b,address:w}),!!m(w))for(let I of f)I.dead||(I.bound?g(I,{msg:x,port:b,address:w}):I.pending.push({msg:x,port:b,address:w}))},close:c}}var Qb=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,xd="00:00:00:00:00:00";function ew(t){let e=[];for(let n of t.split(`
164
+ `).slice(1)){let o=n.trim().split(/\s+/);if(o.length<6)continue;let[r,,i,s]=o;if(!Qb.test(r)||(Number.parseInt(i,16)&2)===0)continue;let a=we(s);a===void 0||a===xd||Sd(r,a)&&e.push({ip:r,mac:a})}return e}function tw(t){let e=[];for(let n of t.split(`
165
+ `)){let o=n.trim().split(/\s+/),r=o[0];if(r===void 0||!Qb.test(r))continue;let i=o.indexOf("lladdr");if(i===-1)continue;let s=o.at(-1);if(s==="INCOMPLETE"||s==="FAILED"||s==="NONE")continue;let a=we(o[i+1]);a===void 0||a===xd||Sd(r,a)&&e.push({ip:r,mac:a})}return e}function Sd(t,e){let n=Number(t.split(".")[0]);return!(!Number.isFinite(n)||n>=224||n===0||t.startsWith("169.254.")||e===xd||e==="ff:ff:ff:ff:ff:ff"||e.startsWith("01:00:5e")||e.startsWith("33:33"))}var t6=new Set(["2","3","4","5","probe","delay","stale","reachable"]);function za(t){let e=t.replace(/^\uFEFF/,"").trim();if(e==="")return[];let n;try{n=JSON.parse(e)}catch{return[]}let o=Array.isArray(n)?n:[n],r=[];for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=typeof s.IPAddress=="string"?s.IPAddress:void 0;if(a===void 0||!Qb.test(a))continue;let c=typeof s.LinkLayerAddress=="string"?we(s.LinkLayerAddress):void 0;c!==void 0&&(s.State!==void 0&&!t6.has(String(s.State).toLowerCase())||typeof s.InterfaceAlias=="string"&&/vEthernet \((?:WSL|Default Switch)|Loopback/i.test(s.InterfaceAlias)||Sd(a,c)&&r.push({ip:a,mac:c}))}return r}function pC(t){let e=[],n=/\((\d{1,3}(?:\.\d{1,3}){3})\) at ([0-9a-f]{1,2}(?::[0-9a-f]{1,2}){5})\b/i;for(let o of t.split(`
166
+ `)){let r=n.exec(o);if(!r)continue;let i=r[1],s=r[2].split(":").map(c=>c.padStart(2,"0")).join(":"),a=we(s);a===void 0||a===xd||Sd(i,a)&&e.push({ip:i,mac:a})}return e}var nw=(0,dC.promisify)(aC.execFile),n6=()=>(0,lC.readFile)("/proc/net/arp","utf8"),r6=async()=>{let{stdout:t}=await nw("ip",["neigh","show"],{timeout:1500,maxBuffer:262144});return t},o6="Get-NetNeighbor -AddressFamily IPv4 | Where-Object { $_.State -in 2,3,4,5 } | Select-Object IPAddress,LinkLayerAddress,State,InterfaceAlias | ConvertTo-Json -Compress",i6=1e3,wd,kd=()=>{let t=Date.now();if(wd&&t-wd.at<i6)return wd.promise;let e=nw("powershell.exe",["-NoProfile","-NonInteractive","-Command",o6],{timeout:5e3,maxBuffer:262144}).then(({stdout:n})=>n);return e.catch(()=>{}),wd={at:t,promise:e},e},s6=async()=>{let{stdout:t}=await nw("arp",["-an"],{timeout:1500,maxBuffer:262144});return t};async function gs(t={}){let e=t.platform??process.platform,n=t.onSourceError??(()=>{});if(e==="darwin")try{return pC(await(t.readArpAn??s6)())}catch(i){return n("arp-an",i),[]}if(e==="win32")try{return za(await(t.readWindowsNeighbors??kd)())}catch(i){return n("windows-neighbors",i),[]}let o=[];try{o=ew(await(t.readProcArp??n6)())}catch(i){n("proc-arp",i)}if(o.length===0)try{o=tw(await(t.readIpNeigh??r6)())}catch(i){n("ip-neigh",i)}let r=t.env??process.env;if(e==="linux"&&(r.WSL_DISTRO_NAME||r.WSL_INTEROP))try{let i=za(await(t.readWindowsNeighbors??kd)()),s=new Set(o.map(a=>a.mac));for(let a of i)s.has(a.mac)||o.push(a)}catch(i){n("windows-neighbors",i)}return o}function rw(t={}){let e=t.env??process.env,n=t.exists??(o=>(0,cC.existsSync)(o));for(let o of(e.PATH??"").split(":"))if(o!=="")try{if(n((0,uC.join)(o,"powershell.exe")))return!0}catch{}return!1}var ow="239.255.90.90",iw=35090,gC=35091;function sw(t){return!t.internal&&(t.family==="IPv4"||t.family===4)}var Me={createSocket:(t,e)=>(0,fC.createSocket)({type:t,reuseAddr:e?.reuseAddr??!0}),interfaceAddresses:()=>Object.values((0,_d.networkInterfaces)()).flatMap(t=>t??[]).filter(sw).map(t=>t.address)};async function aw(t={}){let e=t.timeoutMs??2e3,n=t.sockets??Me,o=await a6(t.readProcVersion??(()=>(0,mC.readFile)("/proc/version","utf8")),t.env??process.env),[r,i]=await Promise.all([c6(n,e).catch(()=>null),l6(n,e).catch(()=>null)]),s;try{s=(t.interfaces??u6)()}catch{s=void 0}let a={wsl:o,multicastOk:r,broadcastOk:i};s!==void 0&&(a.interfaces=s);try{let c=t.windowsInterop??(()=>rw({env:t.env??process.env}));o&&c()&&(a.interop="windows-arp")}catch{}return a}async function a6(t,e){if(e.WSL_DISTRO_NAME||e.WSL_INTEROP)return!0;try{return/microsoft/i.test(await t())}catch{return!1}}function c6(t,e){return new Promise(n=>{let o=[],r=[],i=!1,s=a=>{if(!i){i=!0;for(let c of r)clearTimeout(c);for(let c of o)try{c.close()}catch{}n(a)}};try{let a=`acbridge-mc-${Math.random().toString(36).slice(2)}`,c=new TextEncoder().encode(a),l=t.createSocket("udp4",{reuseAddr:!0});o.push(l),l.on("error",()=>s(null)),l.on("message",u=>{new TextDecoder().decode(u)===a&&s(!0)}),l.bind(iw,()=>{try{l.addMembership(ow)}catch{s(null);return}let u=t.createSocket("udp4",{reuseAddr:!0});o.push(u),u.on("error",()=>s(null)),u.bind(0,()=>{let d=()=>{try{u.setMulticastLoopback(!0),u.send(c,iw,ow,f=>{f&&s(null)})}catch{s(null)}};d(),r.push(setTimeout(d,Math.max(1,Math.floor(e/2))))}),r.push(setTimeout(()=>s(!1),e))})}catch{s(null)}})}function l6(t,e){return new Promise(n=>{let o,r,i=!1,s=a=>{if(!i){i=!0,r&&clearTimeout(r);try{o?.close()}catch{}n(a)}};try{o=t.createSocket("udp4",{reuseAddr:!0});let a=o;a.on("error",()=>s(null)),a.bind(0,()=>{try{a.setBroadcast(!0),a.send(new TextEncoder().encode("acbridge-env-probe"),gC,"255.255.255.255",c=>{if(!c)return s(!0);let l=c.code;s(l==="EACCES"||l==="ENETUNREACH"||l==="EHOSTUNREACH"?!1:null)})}catch{s(null)}}),r=setTimeout(()=>s(null),e)}catch{s(null)}})}function u6(){return Object.entries((0,_d.networkInterfaces)()).filter(([,t])=>t?.some(sw)).map(([t])=>t)}function hC(){let t=[];for(let[e,n]of Object.entries((0,_d.networkInterfaces)()))for(let o of n??[])sw(o)&&o.cidr&&t.push({name:e,cidr:o.cidr});return t}var nR=G(XC(),1);function qa(t){let e={},n=0;for(let o of t.split(/\r?\n/)){let r=o.indexOf(":");if(r<=0)continue;let i=o.slice(0,r).trim().toLowerCase();!i||i.includes(" ")||(e[i]=o.slice(r+1).trim(),n++)}return n>0?e:null}function bs(t){if(t===void 0)return;let e=t.trim().toLowerCase();if(!(!/^[0-9a-f]{16}$/.test(e)||e.slice(6,10)!=="fffe"))return T(e.slice(0,6)+e.slice(10))}function t4(t){if(t===void 0)return;let e=/upnp\/[\d.]+(.*)$/i.exec(t);if(e)for(let n of e[1].split(/[\s,]+/)){let o=n.indexOf("/");if(o>0)return n.slice(0,o)}}function Za(t,e){if(t!==void 0)try{let n=new URL(t);return n.protocol==="http:"&&n.hostname===e?n.href:void 0}catch{return}}function Dw(t,e){let n=t.server,o=t.st,r=t.usn,i=t.location,s=t["hue-bridgeid"];if(s!==void 0){let l={kind:"hue-bridge",identity:{manufacturer:"Signify",model:"Hue Bridge"},expectedType:"bridge",detail:`hue-bridgeid=${s}`.slice(0,72),followUps:[{kind:"hue-config",url:`http://${e}/api/0/config`}]},u=bs(s);return u!==void 0&&(l.mac=u),l}if(`${o??""}${r??""}`.toLowerCase().includes("roku:ecp")||n!==void 0&&n.includes("Roku"))return{kind:"roku",identity:{manufacturer:"Roku"},detail:`st=${(o??r??n??"").slice(0,60)}`};if(n!==void 0&&n.includes("Sonos")||`${o??""}${r??""}`.includes("ZonePlayer")){let l={kind:"sonos",identity:{manufacturer:"Sonos"},detail:`server=${(n??o??"").slice(0,60)}`},u=Za(i,e);return u!==void 0&&(l.followUps=[{kind:"upnp-description",url:u}]),l}if(`${o??""}${r??""}`.includes("Belkin")){let l={kind:"wemo",identity:{manufacturer:"Belkin"},detail:`st=${(o??r??"").slice(0,60)}`},u=Za(i,e);return u!==void 0&&(l.followUps=[{kind:"upnp-description",url:u}]),l}if(/hubitat/i.test(`${n??""}${r??""}${i??""}`)){let l={kind:"hubitat",identity:{manufacturer:"Hubitat"},expectedType:"bridge",detail:`server=${(n??r??"").slice(0,60)}`},u=Za(i,e);return u!==void 0&&(l.followUps=[{kind:"upnp-description",url:u}]),l}if(`${o??""}${r??""}`.includes("InternetGatewayDevice")||i!==void 0&&/igddevicedesc/i.test(i)||n!==void 0&&n.includes("MiniUPnPd")){let l={kind:"gateway",identity:{name:"Router (Internet gateway)"},detail:`server=${(n??o??"").slice(0,60)}`},u=Za(i,e);return u!==void 0&&(l.followUps=[{kind:"upnp-description",url:u}]),l}if(n===void 0&&o===void 0&&r===void 0&&i===void 0)return{kind:"ssdp-generic",detail:"ssdp reply"};let a={kind:"ssdp-generic",detail:n!==void 0?`server=${n.slice(0,60)}`:`st=${(o??r??"").slice(0,60)}`};if(n!==void 0){let l=t4(n);a.identity={hint:`UPnP device (${n.slice(0,40)})`,...l!==void 0?{model:l}:{}}}let c=Za(i,e);return c!==void 0&&(a.followUps=[{kind:"upnp-description",url:c}]),a}var QC=(t,e)=>{let n=t.txt[e];if(n===void 0)return;let o=Number.parseInt(n,10);return Number.isFinite(o)?o:void 0},Re=t=>t.name.trim()||void 0,eR=t=>{if(!t)return;let e=t.split(".")[0]??t;return/-([0-9a-f]{12})$/i.exec(e)?.[1]},tR=t=>{let e=t.txt.mac;return e&&/^[0-9a-f]{12}$/i.test(e.replace(/[:.-]/g,""))?e:void 0},$w=[{type:"hap",protocol:"tcp",extract:t=>{let e=t.txt.md,n=QC(t,"ci"),o=QC(t,"sf"),r=e?bd(e):void 0,i=n!==void 0?Jb[n]:void 0,s=[e!==void 0?`md=${e}`:void 0,n!==void 0?`ci=${n}`:void 0,o!==void 0?`sf=${o}${(o&1)===1?" unpaired":""}`:void 0].filter(c=>c!==void 0).join(" ");if(r?.hueBridge)return{kind:"hue-bridge",identity:{name:Re(t),manufacturer:r.manufacturer,model:r.product},expectedType:"bridge",detail:s};let a={name:Re(t)};return r?(a.manufacturer=r.manufacturer,a.model=r.product??e):e!==void 0&&(a.model=e),{kind:Xb(e)?"hue-bulb":"hap",identity:a,expectedType:i?.expectedType,expectedCapabilities:i?.expectedCapabilities,detail:s||void 0}}},{type:"hue",protocol:"tcp",extract:t=>({kind:"hue-bridge",mac:bs(t.txt.bridgeid),identity:{name:Re(t),manufacturer:"Signify",model:t.txt.modelid??"Hue Bridge"},expectedType:"bridge",detail:t.txt.bridgeid!==void 0?`bridgeid=${t.txt.bridgeid}`:void 0})},{type:"home-assistant",protocol:"tcp",extract:t=>({kind:"home-assistant",identity:{name:Re(t),manufacturer:"Home Assistant"},expectedType:"bridge",detail:t.txt.version!==void 0?`version=${t.txt.version}`:void 0})},{type:"smartthings",protocol:"tcp",extract:t=>({kind:"smartthings",identity:{name:Re(t),manufacturer:"Samsung SmartThings",model:"SmartThings hub"},expectedType:"bridge"})},{type:"shelly",protocol:"tcp",extract:t=>{let e=eR(t.name)??eR(t.fqdn),n=t.txt.gen,o=t.txt.app,r={kind:"shelly",identity:{name:Re(t),manufacturer:"Shelly",model:o},detail:[n!==void 0?`gen=${n}`:void 0,o!==void 0?`app=${o}`:void 0].filter(i=>i!==void 0).join(" ")||void 0,followUp:"shelly-info"};return e!==void 0&&(r.mac=e),r}},{type:"esphomelib",protocol:"tcp",extract:t=>({kind:"esphome",mac:tR(t),identity:{name:Re(t),manufacturer:"ESPHome"},detail:t.txt.version!==void 0?`version=${t.txt.version}`:void 0})},{type:"wled",protocol:"tcp",extract:t=>({kind:"wled",mac:tR(t),identity:{name:Re(t),model:"WLED"}})},{type:"nanoleafapi",protocol:"tcp",extract:t=>({kind:"nanoleaf",identity:{name:Re(t),manufacturer:"Nanoleaf",model:t.txt.md}})},{type:"ewelink",protocol:"tcp",extract:t=>{let e=t.txt.id,n=t.txt.encrypt,o=n!==void 0&&n!=="false"&&n!=="0"&&n!=="",r=t.txt.type;return{kind:o?"ewelink":"ewelink-diy",identity:{name:Re(t),manufacturer:"SONOFF (ITEAD)",...!o&&e!==void 0?{vendorId:e}:{}},detail:[r!==void 0?`type=${r}`:void 0,o?"encrypt":"diy"].filter(i=>i!==void 0).join(" ")||void 0}}},{type:"elg",protocol:"tcp",extract:t=>({kind:"elgato",identity:{name:Re(t),manufacturer:"Elgato",model:t.txt.md}})},{type:"googlecast",protocol:"tcp",extract:t=>({kind:"cast",identity:{name:t.txt.fn??Re(t),manufacturer:"Google Cast",model:t.txt.md},detail:t.txt.md!==void 0?`md=${t.txt.md}`:void 0})},{type:"sonos",protocol:"tcp",extract:t=>({kind:"sonos",identity:{name:Re(t),manufacturer:"Sonos"}})},{type:"androidtvremote2",protocol:"tcp",extract:t=>({kind:"androidtv",identity:{name:Re(t)}})},{type:"ipp",protocol:"tcp",extract:t=>({kind:"printer",identity:{name:Re(t),model:t.txt.ty}})},{type:"miio",protocol:"udp",extract:t=>({kind:"miio",identity:{name:Re(t),manufacturer:"Xiaomi"}})},{type:"lutron",protocol:"tcp",extract:t=>({kind:"lutron",identity:{name:Re(t),manufacturer:"Lutron",model:t.txt.systype??"Cas\xE9ta"}})},{type:"mqtt",protocol:"tcp",extract:t=>({kind:"mqtt-broker",identity:{name:Re(t)}})},{type:"meshcop",protocol:"udp",extract:t=>({kind:"thread-border-router",identity:{name:Re(t),...t.txt.vn!==void 0?{manufacturer:t.txt.vn}:{}}})},{type:"bond",protocol:"tcp",extract:t=>({kind:"bond",identity:{name:Re(t),manufacturer:"Bond"}})},{type:"octoprint",protocol:"tcp",extract:t=>({kind:"octoprint",identity:{name:Re(t),model:"OctoPrint"}})},{type:"airplay",protocol:"tcp",extract:t=>{let e=t.txt.deviceid,n={kind:"apple",identity:{name:Re(t),manufacturer:"Apple",model:t.txt.model},detail:t.txt.model!==void 0?`model=${t.txt.model}`:void 0};return e!==void 0&&/^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/i.test(e)&&(n.mac=e),n}},{type:"raop",protocol:"tcp",extract:t=>{let e=t.name.indexOf("@");return{kind:"apple",identity:{name:(e>=0?t.name.slice(e+1).trim():Re(t))||Re(t),manufacturer:"Apple"}}}},{type:"matter",protocol:"tcp",extract:()=>({kind:"matter"})},{type:"matterc",protocol:"udp",extract:t=>({kind:"matter-pairing",identity:{name:t.txt.dn},detail:t.txt.vp!==void 0?`vp=${t.txt.vp}`:void 0})}];var Od=()=>new nR.Bonjour(void 0,()=>{});function Va(t={},e=Od){let n=t.now??Date.now,o=t.table??$w,r=t.metaQuery??!0,i,s=[],a=!1,c=()=>{if(!a){a=!0;for(let l of s)try{l.stop()}catch{}try{i?.destroy()}catch{}}};return{key:"mdns",start(l,u){if(!(a||u.aborted)){u.addEventListener("abort",c,{once:!0}),i=e();for(let d of o){let f=i.find({type:d.type,protocol:d.protocol});s.push(f),f.on("up",m=>{try{let g=Lw(m,d,n());g&&l(g)}catch{}})}if(r){let d=i.find(null);s.push(d),d.on("up",f=>{try{let m=i4(f,o,n());m&&l(m)}catch{}})}}},refire(){for(let l of s)try{l.update()}catch{}},stop:c}}var n4=new TextDecoder,r4=/^\d{1,3}(?:\.\d{1,3}){3}$/,Ow=t=>r4.test(t)&&t.split(".").every(e=>Number(e)<=255),o4=t=>t.includes(":")&&/^[0-9a-fA-F:.%]+$/.test(t);function rR(t){let e=t.addresses?.find(n=>Ow(n))??(t.refererAddress!==void 0&&Ow(t.refererAddress)?t.refererAddress:void 0);return{ip:e??t.addresses?.find(n=>o4(n)),v4:e}}function Lw(t,e,n){let o=oR(t,e);if(!o)return null;let r=e.extract(o);if(!r)return null;let{ip:i,v4:s}=rR(o);if(i===void 0)return null;let a=`_${e.type}._${e.protocol}`,c={addresses:{ip:i},evidence:{protocol:"mdns",detail:r.detail?`${a} ${r.detail}`:a,at:n},kind:r.kind,primaryService:a};if(r.mac!==void 0){let l=T(r.mac);l.length===17&&(c.addresses.mac=l)}if(o.host!==void 0&&(c.addresses.hostname=o.host),o.port!==void 0&&(c.addresses.port=o.port),r.identity!==void 0&&(c.identity=r.identity),r.expectedType!==void 0&&(c.expectedType=r.expectedType),r.expectedCapabilities!==void 0&&(c.expectedCapabilities=r.expectedCapabilities),s!==void 0){let l=o.refererAddress!==void 0&&Ow(o.refererAddress)?o.refererAddress:s;if(r.followUp==="shelly-info"){let u=o.port!==void 0&&o.port!==80?`:${o.port}`:"";c.followUps=[{kind:"shelly-info",url:`http://${l}${u}/shelly`}]}else r.followUp==="hue-config"&&(c.followUps=[{kind:"hue-config",url:`http://${l}/api/0/config`}])}return c}function i4(t,e,n){if(t===null||typeof t!="object")return null;let o=t,r=typeof o.type=="string"?o.type:void 0,i=o.protocol==="udp"?"udp":"tcp";if(r===void 0||r==="")return null;let s=e.find(d=>d.type===r&&d.protocol===i);if(s)return Lw(t,s,n);let a=oR(t,{type:r,protocol:i,extract:()=>null});if(!a)return null;let{ip:c}=rR(a);if(c===void 0)return null;let l=`_${r}._${i}`,u={addresses:{ip:c},evidence:{protocol:"mdns",detail:l,at:n},kind:"mdns-service",identity:{hint:`Announces ${l} on your network \u2014 no local adapter for this service`},primaryService:l};return a.name!==""&&(u.identity.name=a.name),a.host!==void 0&&(u.addresses.hostname=a.host),a.port!==void 0&&(u.addresses.port=a.port),u}function oR(t,e){if(t===null||typeof t!="object")return null;let n=t,o={},r=n.txt;if(r!==null&&typeof r=="object")for(let[a,c]of Object.entries(r))typeof c=="string"||typeof c=="number"||typeof c=="boolean"?o[a.toLowerCase()]=String(c):c instanceof Uint8Array&&(o[a.toLowerCase()]=n4.decode(c));let i={name:typeof n.name=="string"?n.name:"",type:e.type,protocol:e.protocol,txt:o};typeof n.host=="string"&&(i.host=n.host),typeof n.port=="number"&&(i.port=n.port),typeof n.fqdn=="string"&&(i.fqdn=n.fqdn),Array.isArray(n.addresses)&&(i.addresses=n.addresses.filter(a=>typeof a=="string"));let s=n.referer;if(s!==null&&typeof s=="object"){let a=s.address;typeof a=="string"&&(i.refererAddress=a)}return i}var Ja=require("node:crypto");var sR=6666,aR=6667,cR=(0,Ja.createHash)("md5").update("yGAdlopoPVldABfn").digest(),s4=new TextDecoder,a4=26265,c4=39270;function lR(t){if(t.length<28||t[0]!==0||t[1]!==0||t[2]!==85||t[3]!==170)return null;let e=t.length;return t[e-4]!==0||t[e-3]!==0||t[e-2]!==170||t[e-1]!==85?null:t.subarray(20,e-8)}function uR(t,e){let n=lR(t);if(n===null||n.length===0)return null;try{let o;if(e){if(n.length%16!==0)return null;let i=(0,Ja.createDecipheriv)("aes-128-ecb",cR,null);o=Buffer.concat([i.update(n),i.final()]).toString("utf8")}else o=s4.decode(n);let r=JSON.parse(o);return r!==null&&typeof r=="object"?r:null}catch{return null}}function l4(t){if(t.length<50)return null;let e=Buffer.from(t.buffer,t.byteOffset,t.byteLength);if(e.readUInt32BE(0)!==a4||18+e.readUInt32BE(14)+4!==e.length||e.readUInt32BE(e.length-4)!==c4)return null;let o=e.subarray(18,30),r=e.subarray(30,e.length-4),i=r.subarray(0,r.length-16),s=r.subarray(r.length-16);try{let a=(0,Ja.createDecipheriv)("aes-128-gcm",cR,o);a.setAuthTag(s),a.setAAD(e.subarray(4,18));let c=Buffer.concat([a.update(i),a.final()]);c.length>=4&&(c.readUInt32BE(0)&4294967040)===0&&(c=c.subarray(4));let l=JSON.parse(c.toString("utf8").replace(/\0+$/,"").trim());return l!==null&&typeof l=="object"?l:null}catch{return null}}var iR=t=>typeof t=="string"&&t.length>0?t:void 0;function dR(t,e,n){if(t===null||typeof t!="object")return null;let o=t,r=iR(o.gwId);if(r===void 0)return null;let i=iR(o.version);return{addresses:{ip:e},evidence:{protocol:"tuya-beacon",detail:`beacon gwId=${r.slice(0,8)} v=${i??"?"}`,at:n},kind:"tuya",identity:{vendorId:r},primaryService:"tuya"}}function Ya(t={},e=Me){let n=t.now??Date.now,o=[],r=!1,i=()=>{if(!r){r=!0;for(let s of o)s.close()}};return{key:"tuya",start(s,a){if(!(r||a.aborted)){a.addEventListener("abort",i,{once:!0});for(let[c,l]of[[sR,!1],[aR,!0]])o.push(Ze(e,{port:c},(u,d)=>{let f=uR(u,l)??l4(u),m=dR(f,d.address,n());m&&s(m)},t.onProbeError))}},stop:i}}var u4=30*6e4;function Nw(t){let e=new Zo,n=t.now??Date.now,o=new AbortController,r=!1,i=[Va(t.now?{now:t.now}:{},t.bonjour??Od),Ya(t.now?{now:t.now}:{},t.sockets??Me)].filter(a=>t.config?.protocols?.[a.key]!==!1),s=a=>{r||(e.add(a),e.prune(n()-u4),t.onDevices(e.snapshot()))};for(let a of i)try{a.start(s,o.signal)}catch{}return{stop(){if(!r){r=!0;for(let a of i)try{a.stop()}catch{}o.abort()}}}}function Xa(t){let e=t.split(".");if(e.length!==4)return null;let n=0;for(let o of e){let r=Number(o);if(!Number.isInteger(r)||r<0||r>255)return null;n=n*256+r}return n>>>0}var Mw=t=>[t>>>24&255,t>>>16&255,t>>>8&255,t&255].join(".");function d4(t){let e=t.indexOf("/");if(e===-1)return null;let n=Xa(t.slice(0,e)),o=Number(t.slice(e+1));return n===null||!Number.isInteger(o)||o<0||o>32?null:{host:n,prefix:o}}function p4(t,e){let n=d4(t),o=Xa(e);if(n===null||o===null)return!1;if(n.prefix===0)return!0;let r=4294967295<<32-n.prefix>>>0;return(n.host&r)>>>0===(o&r)>>>0}function pR(t,e){let n;for(let o of t){let r=0;for(let i of e)p4(o.cidr,i)&&r++;r>0&&(n===void 0||r>n.hits)&&(n={name:o.name,hits:r})}return n?.name}var fR=(t,e)=>fetch(t,{signal:e.signal,redirect:"error"}),f4=65536;function m4(t){let e=t.split(".").map(Number);return e.length!==4||e.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:e[0]===10||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&e[1]===168}var xn=t=>typeof t=="string"&&t.length>0?t:void 0,mR=t=>{try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:null}catch{return null}};function gR(t,e,n){let o=mR(t);if(!o)return null;let r=xn(o.app),i=xn(o.type),s=we(xn(o.mac));if(s===void 0&&r===void 0&&i===void 0)return null;let a=typeof o.gen=="number"?o.gen:1,c=o.auth===!0||o.auth_en===!0,l=r??i,u={manufacturer:"Shelly"};l!==void 0&&(u.model=l);let d=xn(o.name)??xn(o.id);d!==void 0&&(u.name=d),c&&(u.hint="Password-protected \u2014 credentials required at connect");let f={addresses:{ip:e},evidence:{protocol:"http",detail:`GET /shelly gen=${a} app=${l??"?"} auth=${c?"yes":"no"}`,at:n},kind:a<2?"shelly-gen1":"shelly",identity:u,primaryService:"http"};return s!==void 0&&(f.addresses.mac=s),l!==void 0&&(/plug/i.test(l)?f.expectedType="plug":/rgbw|duo|vintage|bulb/i.test(l)&&(f.expectedType="light")),xn(o.profile)==="cover"&&(f.expectedType="cover",f.expectedCapabilities=["cover"]),f}function hR(t,e,n){let o=mR(t);if(!o)return null;let r=xn(o.bridgeid);if(r===void 0)return null;let i=we(xn(o.mac))??bs(r),s=xn(o.apiversion),a={manufacturer:"Signify"},c=xn(o.name);c!==void 0&&(a.name=c);let l=xn(o.modelid);l!==void 0&&(a.model=l);let u={addresses:{ip:e},evidence:{protocol:"meethue",detail:`api/0/config bridgeid=${r}${s!==void 0?` api=${s}`:""}`,at:n},kind:"hue-bridge",identity:a,expectedType:"bridge",primaryService:"meethue"};return i!==void 0&&(u.addresses.mac=i),u}var g4={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"},h4=t=>t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>g4[e]??e),Uw=(t,e)=>{let o=new RegExp(`<${e}>([^<]*)</${e}>`).exec(t)?.[1]?.trim();return o?h4(o):void 0};function yR(t,e,n){let o=Uw(t,"friendlyName"),r=Uw(t,"manufacturer"),i=Uw(t,"modelName");if(o===void 0&&r===void 0&&i===void 0)return null;let s={};return o!==void 0&&(s.name=o),r!==void 0&&(s.manufacturer=r),i!==void 0&&(s.model=i),{addresses:{ip:e},evidence:{protocol:"http",detail:`description.xml${i!==void 0?` model=${i}`:""}`,at:n},kind:r!==void 0&&r.includes("Sonos")?"sonos":"ssdp-generic",identity:s,primaryService:"http"}}var y4={"shelly-info":gR,"hue-config":hR,"upnp-description":yR};function Fw(t={},e=fR){let n=t.now??Date.now,o=t.timeoutMs??1500,r=t.maxFetches??32,i=new Set,s=new AbortController,a=!1,c=u=>{try{let d=new URL(u);return d.protocol==="http:"&&m4(d.hostname)?d.hostname:void 0}catch{return}},l=async(u,d,f)=>{let m=AbortSignal.any([s.signal,AbortSignal.timeout(o)]),g=await e(u.url,{signal:m});if(!g.ok)return;let h=(await g.text()).slice(0,f4),y=y4[u.kind](h,d,n());y&&!a&&f(y)};return{wrap(u){return d=>{if(u(d),!!d.followUps)for(let f of d.followUps){if(a||i.has(f.url)||i.size>=r)continue;let m=c(f.url);m!==void 0&&(i.add(f.url),l(f,m,u).catch(()=>{}))}}},stop(){a=!0,s.abort()}}}var vR=new Set(["00:33:7a","10:5a:17","10:d5:61","18:69:d8","18:de:50","1c:90:ff","20:f1:b2","2c:b4:71","30:48:7d","38:1f:8d","38:2c:e5","38:a5:c9","3c:0b:59","4c:a9:19","50:8a:06","50:8b:b9","68:57:2d","70:89:76","7c:f6:66","80:64:7c","84:e3:42","a0:92:08","a8:80:55","b8:06:0d","bc:35:1e","c0:f8:53","c4:82:e1","cc:8c:bf","d0:32:e7","d0:82:e8","d0:82:eb","d4:a6:51","d8:1f:12","d8:c8:0c","d8:d6:68","d8:fc:92","e4:ae:e4","f8:17:2d","fc:3c:d7","fc:67:1f"]),bR={"00:17:88":"Signify (Philips Hue)","c4:29:96":"Signify","fc:26:8c":"Signify","d0:73:d5":"LIFX","50:c7:bf":"TP-Link","1c:3b:f3":"TP-Link","d8:0d:17":"TP-Link","5c:e9:31":"TP-Link","3c:52:a1":"TP-Link","24:0a:c4":"Espressif","24:6f:28":"Espressif","30:ae:a4":"Espressif","5c:cf:7f":"Espressif","ec:fa:bc":"Espressif","a4:cf:12":"Espressif","48:3f:da":"Espressif","70:87:9e":"Beken","80:6d:de":"Beken","c8:47:8c":"Beken",...Object.fromEntries([...vR].map(t=>[t,"Tuya"])),"a8:bb:50":"WiZ","d8:a0:11":"WiZ","44:4f:8e":"WiZ","6c:29:90":"WiZ","94:9f:3e":"Sonos","5c:aa:fd":"Sonos","00:0e:58":"Sonos","fc:65:de":"Amazon","74:c2:46":"Amazon","44:65:0d":"Amazon","0c:47:c9":"Amazon","b8:5f:98":"Amazon","f4:f5:d8":"Google","54:60:09":"Google","1c:f2:9a":"Google","d8:eb:46":"Google","18:b4:30":"Nest Labs","64:16:66":"Nest Labs","d0:52:a8":"SmartThings","24:fd:5b":"SmartThings","28:6d:97":"SAMJIN (SmartThings)","50:14:79":"iRobot","24:9e:7d":"Roborock","b0:4a:39":"Roborock","78:0f:77":"Broadlink","34:ea:34":"Broadlink","2c:aa:8e":"Wyze","44:61:32":"Ecobee","94:10:3e":"Belkin (Wemo)","5c:e7:53":"Govee","d4:13:68":"Govee","e0:2a:25":"Govee","80:8a:f7":"Nanoleaf","f8:24:41":"Yeelight","54:ef:44":"Aqara (Lumi)","18:c2:3c":"Aqara (Lumi)","b0:e9:fe":"SwitchBot","00:1c:2b":"Hive (Centrica)","ec:e5:12":"tado\xB0"};function Bw(t){return bR[T(t).slice(0,8)]}function wR(t){return vR.has(T(t).slice(0,8))}var Ld="239.255.255.250",ei=4001,Nd=4002,ti='{"msg":{"cmd":"scan","data":{"account_topic":"reserve"}}}',v4=new TextDecoder,kR=t=>typeof t=="string"&&t.length>0?t:void 0;function xR(t,e,n){if(t===null||typeof t!="object")return null;let o=t.msg;if(o===null||typeof o!="object")return null;let r=o;if(r.cmd!=="scan")return null;let i=r.data;if(i===null||typeof i!="object")return null;let s=i,a=kR(s.sku),c=kR(s.device),l={manufacturer:"Govee"};return a!==void 0&&(l.model=a),{addresses:{ip:e},evidence:{protocol:"govee-udp",detail:`scan${a!==void 0?` sku=${a}`:""}${c!==void 0?` device=${c}`:""}`,at:n},kind:"govee",identity:l,primaryService:"govee"}}function jw(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=()=>{r||(r=!0,o?.close())};return{key:"govee",start(s,a){r||a.aborted||(a.addEventListener("abort",i,{once:!0}),o=Ze(e,{port:Nd,membership:Ld},(c,l)=>{let u=xR(JSON.parse(v4.decode(c)),l.address,n());u&&s(u)},t.onProbeError),o.send(ti,ei,Ld))},refire(){r||o?.send(ti,ei,Ld)},stop:i}}var Rt=9999,Nr=20002,rn='{"system":{"get_sysinfo":{}}}',ws=Buffer.from("020000010000000000000000463cb5d3","hex"),b4=new TextEncoder,SR=new TextDecoder;function Xn(t){let e=b4.encode(t),n=new Uint8Array(e.length),o=171;for(let r=0;r<e.length;r++)o=o^e[r],n[r]=o;return n}function so(t){let e=new Uint8Array(t.length),n=171;for(let o=0;o<t.length;o++)e[o]=n^t[o],n=t[o];return SR.decode(e)}var Sn=t=>typeof t=="string"&&t.length>0?t:void 0,zw=t=>t===1||t===!0;function Md(t,e,n){if(t===null||typeof t!="object")return null;let o=t.system;if(o===null||typeof o!="object")return null;let r=o.get_sysinfo;if(r===null||typeof r!="object")return null;let i=r,s=Sn(i.mic_type)??Sn(i.type),a=Sn(i.model),c=Sn(i.alias),l=Sn(i.feature),u=we(Sn(i.mac)??Sn(i.mic_mac)),d="kasa",f,m=[];s?.includes("CAM")?(d="kasa-noncontrol",f="camera",m.push("camera")):s?.includes("BULB")?(f="light",m.push("power"),zw(i.is_dimmable)&&m.push("brightness"),zw(i.is_variable_color_temp)&&m.push("colorTemperature"),zw(i.is_color)&&m.push("color")):typeof i.brightness=="number"?(f="dimmer",m.push("power","brightness")):s===void 0||/PLUG|SWITCH/i.test(s)?(f=a!==void 0&&/^(hs2|ks2|es2)/i.test(a)?"switch":"plug",m.push("power")):d="kasa-noncontrol",l?.includes("ENE")&&m.push("energyMeter");let g={manufacturer:"TP-Link Kasa"};c!==void 0&&(g.name=c),a!==void 0&&(g.model=a);let h={addresses:{ip:e},evidence:{protocol:"kasa-udp",detail:a!==void 0?`get_sysinfo model=${a}`:"get_sysinfo",at:n},kind:d,identity:g,expectedCapabilities:m,primaryService:"kasa"};return f!==void 0&&(h.expectedType=f),u!==void 0&&(h.addresses.mac=u),h}var w4={TAPOPLUG:"plug",KASAPLUG:"plug",TAPOBULB:"light",KASABULB:"light",TAPOSWITCH:"switch",KASASWITCH:"switch"};function k4(t){let e=t.slice(t.indexOf(".")+1),n=w4[e];return n!==void 0?{kind:"tplink-smart",expectedType:n}:t.includes("CAM")?{kind:"kasa-noncontrol",expectedType:"camera"}:e.includes("DOORBELL")?{kind:"kasa-noncontrol",expectedType:"doorbell"}:e.includes("HUB")?{kind:"kasa-noncontrol",expectedType:"bridge"}:{kind:"kasa-noncontrol"}}function Ud(t,e,n){if(t.length<=16)return null;let o;try{o=JSON.parse(SR.decode(t.subarray(16)))}catch{return null}if(o===null||typeof o!="object")return null;let r=o.result;if(r===null||typeof r!="object")return null;let i=r,s=Sn(i.device_type);if(s===void 0)return null;let a=s.startsWith("IOT.")?"iot":s.startsWith("SMART.")?"smart":void 0;if(a===void 0)return null;let c=Sn(i.device_model),l=we(Sn(i.mac)),u=i.mgt_encrypt_schm,d=u!==null&&typeof u=="object"?Sn(u.encrypt_type):void 0,f={manufacturer:a==="smart"?"TP-Link":"TP-Link Kasa"};c!==void 0&&(f.model=c);let m=s.includes("CAM")?{kind:"kasa-noncontrol",expectedType:"camera"}:s.includes("BULB")?{kind:"kasa",expectedType:"light"}:/PLUG|SWITCH/i.test(s)?{kind:"kasa",expectedType:"plug"}:{kind:"kasa-noncontrol"};a==="iot"&&d==="KLAP"&&m.kind==="kasa"&&(m.kind="kasa-klap");let h=a==="smart"?k4(s):m,y={addresses:{ip:e},evidence:{protocol:"kasa-udp",detail:`tdp device_type=${s} model=${c??"?"}${d!==void 0?` encrypt=${d}`:""}`,at:n},kind:h.kind,identity:f,primaryService:"kasa"};return l!==void 0&&(y.addresses.mac=l),h.expectedType!==void 0&&(y.expectedType=h.expectedType),{hit:y,family:a}}function Hw(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=new Set,s=()=>{o?.send(Xn(rn),Rt,"255.255.255.255"),o?.send(ws,Nr,"255.255.255.255")},a=()=>{r||(r=!0,o?.close())};return{key:"kasa",start(c,l){r||l.aborted||(l.addEventListener("abort",a,{once:!0}),o=Ze(e,{broadcast:!0},(u,d)=>{if(d.port===Rt){let f=Md(JSON.parse(so(u)),d.address,n());f&&c(f)}else if(d.port===Nr){let f=Ud(u,d.address,n());if(!f)return;c(f.hit),f.family==="iot"&&!i.has(d.address)&&(i.add(d.address),o?.send(Xn(rn),Rt,d.address))}}),s())},refire(){r||s()},stop:a}}var ks={1:{name:"Original",color:!0,ctRange:[2500,9e3]},2:{name:"Original 1000",color:!0,ctRange:[2500,9e3]},3:{name:"Color 650",color:!0,ctRange:[2500,9e3]},10:{name:"LIFX White 800 (LV)",color:!1,ctRange:[2700,6500]},11:{name:"LIFX White 800 (HV)",color:!1,ctRange:[2700,6500]},12:{name:"LIFX LCMv4 White OEM (A19 LV)",color:!1,ctRange:[2700,2700]},13:{name:"LIFX LCMv4 White OEM (A19 HV)",color:!1,ctRange:[2700,2700]},14:{name:"LIFX Carbon Prototype",color:!0,ctRange:[2500,9e3]},15:{name:"LIFX LCMv4 Color (A21)",color:!0,ctRange:[2700,6500]},18:{name:"LIFX White 900 (BR30)",color:!1,ctRange:[2700,6500]},19:{name:"LIFX White 900 (BR30)",color:!1,ctRange:[2700,6500]},20:{name:"LIFX Color 1000 (BR30)",color:!0,ctRange:[2500,9e3]},21:{name:"LIFX LCMv4 Color (GU10)",color:!0,ctRange:[2500,9e3]},22:{name:"LIFX Color 1000",color:!0,ctRange:[2500,9e3]},23:{name:"LIFX (A19)",color:!0,ctRange:[2500,9e3]},24:{name:"LIFX (BR30)",color:!0,ctRange:[2500,9e3]},25:{name:"LIFX+ (A19)",color:!0,ctRange:[2500,9e3]},26:{name:"LIFX+ (BR30)",color:!0,ctRange:[2500,9e3]},27:{name:"LIFX (A19)",color:!0,ctRange:[1500,9e3]},28:{name:"LIFX (BR30)",color:!0,ctRange:[1500,9e3]},29:{name:"LIFX+ (A19)",color:!0,ctRange:[1500,9e3]},30:{name:"LIFX+ (BR30)",color:!0,ctRange:[1500,9e3]},31:{name:"LIFX Z",color:!0,ctRange:[2500,9e3]},32:{name:"LIFX Z",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},33:{name:"LIFX Downlight",color:!0,ctRange:[2500,9e3]},36:{name:"LIFX DL",color:!0,ctRange:[1500,9e3]},37:{name:"LIFX DL",color:!0,ctRange:[1500,9e3]},38:{name:"LIFX Beam",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},39:{name:"LIFX DL WW 700lm",color:!1,ctRange:[1500,9e3]},40:{name:"LIFX DL Colour 700lm",color:!0,ctRange:[1500,9e3]},43:{name:"LIFX (A19)",color:!0,ctRange:[1500,9e3]},44:{name:"LIFX (BR30)",color:!0,ctRange:[1500,9e3]},45:{name:"LIFX+ (A19)",color:!0,ctRange:[1500,9e3]},46:{name:"LIFX+ (BR30)",color:!0,ctRange:[1500,9e3]},49:{name:"LIFX Mini C",color:!0,ctRange:[1500,9e3]},50:{name:"LIFX Mini DD",color:!1,ctRange:[1500,9e3]},51:{name:"LIFX Mini W",color:!1,ctRange:[2700,2700]},52:{name:"LIFX GU10",color:!0,ctRange:[1500,9e3]},53:{name:"LIFX GU10",color:!0,ctRange:[1500,9e3]},54:{name:"LIFX GU10 White",color:!1,ctRange:[2700,2700]},55:{name:"LIFX Tile",color:!0,ctRange:[2500,9e3]},56:{name:"LIFX Beam",color:!0,ctRange:[2500,9e3],extendedMultizone:!0},57:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},59:{name:"LIFX Mini C",color:!0,ctRange:[1500,9e3]},60:{name:"LIFX Mini DD",color:!1,ctRange:[1500,9e3]},61:{name:"LIFX Mini W",color:!1,ctRange:[2700,2700]},62:{name:"LIFX (A19) LCM3",color:!0,ctRange:[1500,9e3]},63:{name:"LIFX (BR30) LCM3",color:!0,ctRange:[1500,9e3]},64:{name:"LIFX+ (A19) LCM3",color:!0,ctRange:[1500,9e3]},65:{name:"LIFX+ (BR30) LCM3",color:!0,ctRange:[1500,9e3]},66:{name:"LIFX Mini W",color:!1,ctRange:[2700,2700]},67:{name:"LIFX Candle WW",color:!1,ctRange:[2200,6500]},68:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},69:{name:"LIFX Filament",color:!1,ctRange:[2200,2200]},70:{name:"LIFX Switch",color:!1,relay:!0},71:{name:"LIFX Switch",color:!1,relay:!0},72:{name:"LIFX A19",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},81:{name:"LIFX Candle WW",color:!1,ctRange:[2200,6500]},82:{name:"LIFX Filament Clear",color:!1,ctRange:[2200,2200]},84:{name:"LIFX Switch",color:!1,relay:!0},85:{name:"LIFX Filament Amber",color:!1,ctRange:[2e3,2e3]},86:{name:"LIFX Filament Smokey",color:!1,ctRange:[2200,2200]},87:{name:"LIFX White",color:!1,ctRange:[2700,2700]},88:{name:"LIFX White",color:!1,ctRange:[2700,2700]},89:{name:"LIFX Switch",color:!1,relay:!0},90:{name:"LIFX Clean A19 1100lm",color:!0,ctRange:[1500,9e3]},91:{name:"LIFX Color 800lm",color:!0,ctRange:[1500,9e3]},92:{name:"LIFX Colour 1000lm",color:!0,ctRange:[1500,9e3]},93:{name:"LIFX Color A19 1100lm",color:!0,ctRange:[1500,9e3]},94:{name:"LIFX Color BR30 1100lm",color:!0,ctRange:[1500,9e3]},95:{name:"Copper",color:!0,ctRange:[2200,6500]},96:{name:"LIFX Candle WW",color:!1,ctRange:[2200,6500]},97:{name:"LIFX Colour A19 1200lm",color:!0,ctRange:[1500,9e3]},98:{name:"LIFX Colour BR30 1100lm",color:!0,ctRange:[1500,9e3]},99:{name:"LIFX Clean A19 1200lm",color:!0,ctRange:[1500,9e3]},100:{name:"LIFX Filament Clear",color:!1,ctRange:[2200,2200]},101:{name:"LIFX Filament Amber",color:!1,ctRange:[2e3,2e3]},102:{name:"LIFX Filament Smokey",color:!1,ctRange:[2200,2200]},103:{name:"LIFX Filament",color:!1,ctRange:[2100,2100]},104:{name:"LIFX Filament",color:!1,ctRange:[2e3,2e3]},105:{name:"LIFX Filament",color:!1,ctRange:[2200,2200]},106:{name:"LIFX Filament",color:!1,ctRange:[2200,2200]},107:{name:"LIFX Filament",color:!1,ctRange:[2e3,2e3]},108:{name:"LIFX Filament",color:!1,ctRange:[2200,2200]},109:{name:"LIFX NV A19 1100lm",color:!0,ctRange:[1500,9e3]},110:{name:"LIFX NV BR30 1100lm",color:!0,ctRange:[1500,9e3]},111:{name:"LIFX NV A19 1200lm",color:!0,ctRange:[1500,9e3]},112:{name:"LIFX NV BR30 1100lm",color:!0,ctRange:[1500,9e3]},113:{name:"LIFX WW 800lm",color:!1,ctRange:[1500,9e3]},114:{name:"LIFX WW 1000lm",color:!1,ctRange:[1500,9e3]},115:{name:"LIFX Switch",color:!1,relay:!0},116:{name:"LIFX Switch US",color:!1,relay:!0},117:{name:"LIFX Z",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},118:{name:"LIFX Z",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},119:{name:"LIFX Beam",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},120:{name:"LIFX Beam",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},121:{name:"LIFX DL",color:!0,ctRange:[1500,9e3]},122:{name:"LIFX DL",color:!0,ctRange:[1500,9e3]},123:{name:"LIFX Mini 3.1 Color US",color:!0,ctRange:[1500,9e3]},124:{name:"LIFX Mini 3.1 Color Intl",color:!0,ctRange:[1500,9e3]},125:{name:"LIFX Mini 3.1 WW US",color:!1,ctRange:[1500,9e3]},126:{name:"LIFX Mini 3.1 WW Intl",color:!1,ctRange:[1500,9e3]},127:{name:"LIFX Mini 3.1 W US",color:!1,ctRange:[2700,2700]},128:{name:"LIFX Mini 3.1 W Intl",color:!1,ctRange:[2700,2700]},129:{name:"LIFX Color 800",color:!0,ctRange:[1500,9e3]},130:{name:"LIFX Colour 1000",color:!0,ctRange:[1500,9e3]},131:{name:"LIFX White to Warm 800",color:!1,ctRange:[1500,9e3]},132:{name:"LIFX White to Warm 1000",color:!1,ctRange:[1500,9e3]},133:{name:"LIFX White 650",color:!1,ctRange:[2700,2700]},134:{name:"LIFX White 800",color:!1,ctRange:[2700,2700]},135:{name:"LIFX GU10 Color US",color:!0,ctRange:[1500,9e3]},136:{name:"LIFX GU10 Color Intl",color:!0,ctRange:[1500,9e3]},137:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},138:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},139:{name:"LIFX A19 US",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},140:{name:"LIFX A19 Intl",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},141:{name:"LIFX Neon",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},142:{name:"LIFX Neon",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},143:{name:"LIFX String",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},144:{name:"LIFX String",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},145:{name:"LIFX Ceiling US",color:!0,ctRange:[1500,9e3]},146:{name:"LIFX Ceiling Intl",color:!0,ctRange:[1500,9e3]},147:{name:"LIFX Round Spot US",color:!0,ctRange:[1500,9e3]},148:{name:"LIFX Square Spot US",color:!0,ctRange:[1500,9e3]},149:{name:"LIFX Round Path US",color:!0,ctRange:[1500,9e3]},150:{name:"LIFX Square Path US",color:!0,ctRange:[1500,9e3]},151:{name:"LIFX Neon Outdoor",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},152:{name:"LIFX Neon Outdoor",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},153:{name:"LIFX PAR38 US",color:!0,ctRange:[1500,9e3]},154:{name:"LIFX PAR38 Intl",color:!0,ctRange:[1500,9e3]},155:{name:"LIFX Sunshine",color:!0,ctRange:[1500,9e3]},156:{name:"LIFX A21 1000lm Intl",color:!0,ctRange:[1500,9e3]},161:{name:"LIFX Neon Outdoor",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},162:{name:"LIFX Neon Outdoor",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},163:{name:"LIFX A19",color:!0,ctRange:[1500,9e3]},164:{name:"LIFX BR30",color:!0,ctRange:[1500,9e3]},165:{name:"LIFX A19 Intl",color:!0,ctRange:[1500,9e3]},166:{name:"LIFX BR30 Intl",color:!0,ctRange:[1500,9e3]},167:{name:"LIFX DL AU",color:!0,ctRange:[1500,9e3]},168:{name:"LIFX DL US",color:!0,ctRange:[1500,9e3]},169:{name:"LIFX A21",color:!0,ctRange:[1500,9e3]},170:{name:"LIFX A21",color:!0,ctRange:[1500,9e3]},171:{name:"LIFX Spot",color:!0,ctRange:[1500,9e3]},172:{name:"LIFX Spot",color:!0,ctRange:[1500,9e3]},173:{name:"LIFX Path",color:!0,ctRange:[1500,9e3]},174:{name:"LIFX Path",color:!0,ctRange:[1500,9e3]},175:{name:"LIFX PAR38",color:!0,ctRange:[1500,9e3]},176:{name:"LIFX Ceiling",color:!0,ctRange:[1500,9e3]},177:{name:"LIFX Ceiling",color:!0,ctRange:[1500,9e3]},178:{name:"LIFX Downlight US",color:!0,ctRange:[1500,9e3]},179:{name:"LIFX Downlight US",color:!0,ctRange:[1500,9e3]},180:{name:"LIFX Downlight US",color:!0,ctRange:[1500,9e3]},181:{name:"LIFX Mini",color:!0,ctRange:[1500,9e3]},182:{name:"LIFX Mini",color:!0,ctRange:[1500,9e3]},185:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},186:{name:"LIFX Candle C Intl",color:!0,ctRange:[1500,9e3]},187:{name:"LIFX Candle",color:!0,ctRange:[1500,9e3]},188:{name:"LIFX Candle Intl",color:!0,ctRange:[1500,9e3]},191:{name:"LIFX Everyday A19",color:!0,ctRange:[2700,6500]},192:{name:"LIFX Everyday A19 Intl",color:!0,ctRange:[2700,6500]},201:{name:"LIFX Ceiling 13x26",color:!0,ctRange:[1500,9e3]},202:{name:"LIFX Ceiling 13x26 Intl",color:!0,ctRange:[1500,9e3]},203:{name:"LIFX String",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},204:{name:"LIFX String",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},205:{name:"LIFX Neon",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},206:{name:"LIFX Neon",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},207:{name:"LIFX Everyday Lightstrip",color:!0,ctRange:[2700,6500],extendedMultizone:!0},208:{name:"LIFX Everyday Lightstrip Intl",color:!0,ctRange:[2700,6500],extendedMultizone:!0},211:{name:"LIFX Everyday Permanent Outdoor US",color:!0,ctRange:[2700,6500],extendedMultizone:!0},213:{name:"LIFX Permanent Outdoor",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},214:{name:"LIFX Permanent Outdoor Intl",color:!0,ctRange:[1500,9e3],extendedMultizone:!0},215:{name:"LIFX Candle C",color:!0,ctRange:[1500,9e3]},216:{name:"LIFX Candle C Intl",color:!0,ctRange:[1500,9e3]},217:{name:"LIFX Tube",color:!0,ctRange:[1500,9e3]},218:{name:"LIFX Tube Intl",color:!0,ctRange:[1500,9e3]},219:{name:"LIFX Luna",color:!0,ctRange:[1500,9e3]},220:{name:"LIFX Luna Intl",color:!0,ctRange:[1500,9e3]},221:{name:"LIFX Spot Intl",color:!0,ctRange:[1500,9e3]},222:{name:"LIFX Path Intl",color:!0,ctRange:[1500,9e3]},223:{name:"LIFX DL",color:!0,ctRange:[1500,9e3]},224:{name:"LIFX DL Intl",color:!0,ctRange:[1500,9e3]},225:{name:"LIFX PAR38 Intl",color:!0,ctRange:[1500,9e3]},226:{name:"LIFX Dimmer Switch",color:!1,relay:!0},229:{name:"LIFX Path Intl",color:!0,ctRange:[1500,9e3]},265:{name:'LIFX Ceiling 13"',color:!0,ctRange:[1500,9e3]},266:{name:'LIFX Ceiling 13" Intl',color:!0,ctRange:[1500,9e3]},267:{name:"LIFX Mirror",color:!0,ctRange:[1500,9e3]},268:{name:"LIFX Mirror Intl",color:!0,ctRange:[1500,9e3]},300:{name:"LIFX Everyday Permanent Outdoor US",color:!0,ctRange:[2700,6500]}};function ni(t){let e=ks[t];if(!e)return{model:`LIFX product ${t}`,expectedCapabilities:["power","brightness"]};let n=["power","brightness"];return e.ctRange&&e.ctRange[0]!==e.ctRange[1]&&n.push("colorTemperature"),e.color&&n.push("color"),{model:e.name,expectedCapabilities:n}}var At=56700,Qa=1112687687,x4=2,_R=3,S4=23,_4=25,I4=32,T4=33;function _n(t){let e=t.payload??new Uint8Array(0),n=new Uint8Array(36+e.length),o=new DataView(n.buffer);if(o.setUint16(0,n.length,!0),o.setUint16(2,5120|(t.tagged?8192:0),!0),o.setUint32(4,Qa,!0),t.targetMac!==void 0){let r=T(t.targetMac).replace(/:/g,"");for(let i=0;i<6;i++)n[8+i]=Number.parseInt(r.slice(i*2,i*2+2),16)}return n[22]=t.resRequired?1:0,n[23]=t.sequence??0,o.setUint16(32,t.type,!0),n.set(e,36),n}function xs(t){if(t.length<36)return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(2,!0),o=t.subarray(8,14),r=o.every(s=>s===0),i={tagged:(n&8192)!==0,source:e.getUint32(4,!0),sequence:t[23],type:e.getUint16(32,!0),payload:t.subarray(36)};if(!r){let s=we([...o].map(a=>a.toString(16).padStart(2,"0")).join(""));s!==void 0&&(i.targetMac=s)}return i}function Fd(t,e,n){if(t.source!==Qa||t.targetMac===void 0)return null;if(t.type===_R){if(t.payload.length<5)return null;let o=new DataView(t.payload.buffer,t.payload.byteOffset,t.payload.byteLength),r=t.payload[0],i=o.getUint32(1,!0);return r!==1||i===0?null:{addresses:{ip:e,mac:t.targetMac,port:i},evidence:{protocol:"lifx-lan",detail:`StateService port=${i}`,at:n},kind:"lifx",identity:{manufacturer:"LIFX"},primaryService:"lifx"}}if(t.type===T4){if(t.payload.length<8)return null;let o=new DataView(t.payload.buffer,t.payload.byteOffset,t.payload.byteLength),r=o.getUint32(0,!0),i=o.getUint32(4,!0);if(r!==1)return null;let s=ni(i);return{addresses:{ip:e,mac:t.targetMac},evidence:{protocol:"lifx-lan",detail:`StateVersion vendor=1 product=${i}`,at:n},kind:"lifx",identity:{manufacturer:"LIFX",model:s.model},expectedType:"light",expectedCapabilities:s.expectedCapabilities,primaryService:"lifx"}}if(t.type===_4){let o=new TextDecoder().decode(t.payload.subarray(0,32)).replace(/\0+$/,"").trim();return o?{addresses:{ip:e,mac:t.targetMac},evidence:{protocol:"lifx-lan",detail:"StateLabel",at:n},kind:"lifx",identity:{name:o},primaryService:"lifx"}:null}return null}function Kw(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=new Set,s=()=>{o?.send(_n({type:x4,tagged:!0,resRequired:!0}),At,"255.255.255.255")},a=()=>{r||(r=!0,o?.close())};return{key:"lifx",start(c,l){r||l.aborted||(l.addEventListener("abort",a,{once:!0}),o=Ze(e,{broadcast:!0},(u,d)=>{let f=xs(u);if(!f)return;let m=Fd(f,d.address,n());if(m&&(c(m),f.type===_R&&f.targetMac!==void 0&&!i.has(f.targetMac))){i.add(f.targetMac);let g=m.addresses.port??At;o?.send(_n({type:I4,targetMac:f.targetMac,sequence:1,resRequired:!0}),g,d.address),o?.send(_n({type:S4,targetMac:f.targetMac,sequence:2,resRequired:!0}),g,d.address)}}),s())},refire(){r||s()},stop:a}}var In=38899,jd='{"method":"registration","params":{"phoneMac":"AAAAAAAAAAAA","register":false,"phoneIp":"1.2.3.4","id":"1"}}',ri='{"method":"getSystemConfig","params":{}}',E4=new TextDecoder,Bd=t=>typeof t=="string"&&t.length>0?t:void 0;function zd(t){let e=t.split("_")[1]??"";return e.includes("RGB")?{expectedType:"light",expectedCapabilities:["power","brightness","colorTemperature","color"]}:e.includes("DDTW")?{expectedType:"fan",expectedCapabilities:["power","fan","brightness","colorTemperature"]}:e.includes("TW")?{expectedType:"light",expectedCapabilities:["power","brightness","colorTemperature"]}:e.includes("SOCKET")?{expectedType:"plug",expectedCapabilities:["power"]}:e.includes("FANDIM")?{expectedType:"fan",expectedCapabilities:["power","fan"]}:{expectedType:"light",expectedCapabilities:["power","brightness"]}}function Hd(t,e,n){if(t===null||typeof t!="object")return null;let o=Bd(t.method),r=t.result;if(r===null||typeof r!="object")return null;let i=r,s=we(Bd(i.mac));if(o==="registration")return s===void 0?null:{method:o,hit:{addresses:{ip:e,mac:s},evidence:{protocol:"wiz-udp",detail:"registration",at:n},kind:"wiz",identity:{manufacturer:"WiZ"},primaryService:"wiz"}};if(o==="getSystemConfig"){let a=Bd(i.moduleName);if(a===void 0)return null;let c=Bd(i.fwVersion),l=zd(a),u={addresses:{ip:e},evidence:{protocol:"wiz-udp",detail:`getSystemConfig moduleName=${a}${c!==void 0?` fw=${c}`:""}`,at:n},kind:"wiz",identity:{manufacturer:"WiZ",model:a},expectedType:l.expectedType,expectedCapabilities:l.expectedCapabilities,primaryService:"wiz"};return s!==void 0&&(u.addresses.mac=s),{method:o,hit:u}}return null}function Gw(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=new Set,s=()=>{o?.send(jd,In,"255.255.255.255")},a=()=>{r||(r=!0,o?.close())};return{key:"wiz",start(c,l){r||l.aborted||(l.addEventListener("abort",a,{once:!0}),o=Ze(e,{broadcast:!0},(u,d)=>{let f=Hd(JSON.parse(E4.decode(u)),d.address,n());f&&(c(f.hit),f.method==="registration"&&!i.has(d.address)&&(i.add(d.address),o?.send(ri,In,d.address)))}),s())},refire(){r||s()},stop:a}}var Kd="239.255.255.250",ao=1982,ec=["M-SEARCH * HTTP/1.1",`HOST: ${Kd}:${ao}`,'MAN: "ssdp:discover"',"ST: wifi_bulb","",""].join(`\r
167
+ `),IR={mono:["power","brightness"],ct_bulb:["power","brightness","colorTemperature"],ceiling:["power","brightness","colorTemperature"],desklamp:["power","brightness","colorTemperature"],color:["power","brightness","colorTemperature","color"],stripe:["power","brightness","colorTemperature","color"],strip:["power","brightness","colorTemperature","color"],bslamp:["power","brightness","colorTemperature","color"]},C4=t=>{for(let[e,n]of Object.entries(IR))if(t.startsWith(e))return n;return["power","brightness"]},R4=new TextDecoder;function Gd(t,e,n){let o=qa(t);if(o===null)return null;let r=o.location;if(r===void 0||!r.startsWith("yeelight://"))return null;let i=Number.parseInt(r.slice(r.lastIndexOf(":")+1),10),s=o.model,a=o.fw_ver,c=o.support,l=o.name,u=[s!==void 0?`model=${s}`:void 0,a!==void 0?`fw=${a}`:void 0,c!==void 0?`support=${c.slice(0,60)}`:void 0].filter(m=>m!==void 0),d={manufacturer:"Yeelight"};s!==void 0&&(d.model=s),l!==void 0&&/^[\x20-\x7e]{1,64}$/.test(l)&&(d.name=l);let f={addresses:{ip:e},evidence:{protocol:"yeelight",detail:u.join(" ")||"wifi_bulb",at:n},kind:"yeelight",identity:d,expectedType:"light",primaryService:"yeelight"};return s!==void 0&&(f.expectedCapabilities=C4(s)),Number.isFinite(i)&&i>0&&(f.addresses.port=i),f}function Ww(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=()=>{r||(r=!0,o?.close())};return{key:"yeelight",start(s,a){r||a.aborted||(a.addEventListener("abort",i,{once:!0}),o=Ze(e,{},(c,l)=>{let u=Gd(R4.decode(c),l.address,n());u&&s(u)}),o.send(ec,ao,Kd))},refire(){r||o?.send(ec,ao,Kd)},stop:i}}var A4={wiz:"wiz",lifx:"lifx","kasa-legacy":"kasa","kasa-tdp":"kasa",govee:"govee",yeelight:"yeelight"},P4=256,D4=256,$4={"50:c7:bf":"kasa-legacy","1c:3b:f3":"kasa-legacy","d8:0d:17":"kasa-legacy","5c:e9:31":"kasa-tdp","3c:52:a1":"kasa-tdp","5c:e7:53":"govee","d4:13:68":"govee","e0:2a:25":"govee","f8:24:41":"yeelight"},O4="00:17:88",TR="enable LAN Control for this device in the Govee app, then rescan",ER="Tapo / newer Kasa \u2014 connect with your TP-Link account",CR=new TextDecoder;function Zw(t={},e=Me){let n=t.now??Date.now,o=t.protocolEnabled??(()=>!0),r=t.env??process.env,i=t.goveeUnicastSweep??!!(r.WSL_DISTRO_NAME||r.WSL_INTEROP),s,a=!1,c,l=new Set,u=0,d=t.emitUnidentified??!0,f=t.maxUnidentified??D4,m=new Set,g=(w,x)=>{if(a||!c)return;let I=x.port===In?"wiz":x.port===At?"lifx":x.port===ao?"yeelight":x.port===Rt||x.port===Nr?"kasa":void 0;if(I===void 0||!o(I))return;let E=null;if(x.port===In)E=Hd(JSON.parse(CR.decode(w)),x.address,n())?.hit??null;else if(x.port===At){let C=xs(w);E=C?Fd(C,x.address,n()):null}else x.port===ao?E=Gd(CR.decode(w),x.address,n()):x.port===Rt?E=Md(JSON.parse(so(w)),x.address,n()):x.port===Nr&&(E=Ud(w,x.address,n())?.hit??null);E&&c(E)},h=(w,x)=>{if(!o(A4[x]))return;let I=`${w.ip}|${x}`;l.has(I)||(l.add(I),s??=Ze(e,{},g),x==="wiz"?s.send(ri,In,w.ip):x==="lifx"?(s.send(_n({type:32,targetMac:w.mac,sequence:1,resRequired:!0}),At,w.ip),s.send(_n({type:23,targetMac:w.mac,sequence:2,resRequired:!0}),At,w.ip)):x==="yeelight"?s.send(ec,ao,w.ip):x==="kasa-legacy"?s.send(Xn(rn),Rt,w.ip):x==="govee"?s.send(ti,ei,w.ip):(s.send(ws,Nr,w.ip),s.send(Xn(rn),Rt,w.ip)))},y=async()=>{let w=await gs({...t.readProcArp?{readProcArp:t.readProcArp}:{},...t.readIpNeigh?{readIpNeigh:t.readIpNeigh}:{},...t.readWindowsNeighbors?{readWindowsNeighbors:t.readWindowsNeighbors}:{},...t.readArpAn?{readArpAn:t.readArpAn}:{},...t.platform!==void 0?{platform:t.platform}:{},...t.env!==void 0?{env:t.env}:{},...t.onProbeError?{onSourceError:(x,I)=>t.onProbeError?.(new Error(`neighbour source ${x} failed: ${String(I)}`))}:{}});if(!(a||!c))for(let x of w){let I=n(),E=x.mac.slice(0,8);i&&o("govee")&&u<P4&&!l.has(`${x.ip}|govee`)&&(u++,h(x,"govee"));let C=Bw(x.mac),F=Ba({mac:x.mac});if(C===void 0&&F===void 0){d&&(m.has(x.mac)||m.size<f)&&(m.add(x.mac),c({addresses:{ip:x.ip,mac:x.mac},evidence:{protocol:"arp",detail:`oui-unknown:${E}`,at:I},kind:"unidentified"}));continue}if(C!==void 0){let N=wR(x.mac),M={addresses:{ip:x.ip,mac:x.mac},evidence:{protocol:"arp",detail:`oui:${C}`,at:I},kind:N?"tuya":"oui",identity:N?{manufacturer:"Tuya"}:{manufacturer:C,hint:C==="Govee"?TR:C==="TP-Link"?ER:`${C} device`},...N?{primaryService:"tuya"}:{}};E===O4&&(M.followUps=[{kind:"hue-config",url:`http://${x.ip}/api/0/config`}]),c(M)}F!==void 0&&c({addresses:{ip:x.ip,mac:x.mac},evidence:{protocol:"arp",detail:`dhcp:${F.vendor}${F.product!==void 0?` ${F.product}`:""}`,at:I},kind:"dhcp",identity:{manufacturer:F.vendor,model:F.product,...F.vendor==="Govee"?{hint:TR}:F.vendor==="TP-Link"?{hint:ER}:{}}});let U=F?.probeHint,W=U==="wiz"?"wiz":U==="lifx"?"lifx":U==="kasa"?"kasa-legacy":U==="govee"?"govee":$4[E];W!==void 0&&h(x,W)}},b=()=>{a||(a=!0,s?.close())};return{key:"arp",start(w,x){a||x.aborted||(x.addEventListener("abort",b,{once:!0}),c=w,y())},refire(){a||y()},stop:b}}var Wd="239.255.255.250",Zd=1900,qw=["M-SEARCH * HTTP/1.1",`HOST: ${Wd}:${Zd}`,'MAN: "ssdp:discover"',"MX: 3","ST: ssdp:all","",""].join(`\r
168
+ `),L4=new TextDecoder;function RR(t,e,n){let o=qa(t);if(o===null)return null;let r=Dw(o,e);if(r===null)return null;let i={addresses:{ip:e},evidence:{protocol:"ssdp",detail:r.detail,at:n},kind:r.kind,primaryService:"ssdp"};return r.mac!==void 0&&(i.addresses.mac=r.mac),r.identity!==void 0&&(i.identity=r.identity),r.expectedType!==void 0&&(i.expectedType=r.expectedType),r.followUps!==void 0&&(i.followUps=r.followUps),i}function Vw(t={},e=Me){let n=t.now??Date.now,o,r=!1,i=()=>{r||(r=!0,o?.close())};return{key:"ssdp",start(s,a){r||a.aborted||(a.addEventListener("abort",i,{once:!0}),o=Ze(e,{},(c,l)=>{let u=RR(L4.decode(c),l.address,n());u&&s(u)}),o.send(qw,Zd,Wd))},refire(){r||o?.send(qw,Zd,Wd)},stop:i}}var AR=require("node:os");var PR=51037,N4=new Uint8Array([0]);function Jw(t,e=1024){let n=new Set,o=[];for(let s of t){let a=s?.cidr;if(typeof a!="string")continue;let c=a.indexOf("/");if(c===-1)continue;let l=Xa(a.slice(0,c)),u=Number(a.slice(c+1));if(l===null||!Number.isInteger(u)||u<0||u>32||(n.add(l),u<24&&(u=24),u>30))continue;let d=4294967295<<32-u>>>0,f=(l&d)>>>0;o.push({network:f,broadcast:(f|~d>>>0)>>>0})}let r=new Set,i=[];for(let{network:s,broadcast:a}of o){for(let c=s+1;c<a&&i.length<e;c++){let l=c>>>0;if(n.has(l))continue;let u=Mw(l);r.has(u)||(r.add(u),i.push(u))}if(i.length>=e)break}return i}function M4(){let t=[];for(let e of Object.values((0,AR.networkInterfaces)()))for(let n of e??[])!n.internal&&(n.family==="IPv4"||n.family===4)&&n.cidr&&t.push({cidr:n.cidr});return t}function U4(t){let e=new Set;for(let n of t){let o=Xa(n.ip);o!==null&&e.add(`${Mw((o&4294967040)>>>0)}/24`)}return[...e].map(n=>({cidr:n}))}function Yw(t={},e=Me){let n=t.interfaces??M4,o=t.maxHosts??1024,r=Math.max(1,t.batchSize??32),i=t.batchDelayMs??15,s,a=!1,c=[],l=()=>{try{return Jw(n(),o)}catch{return[]}},u=async()=>{try{let g=za(await t.readWindowsNeighbors()),h=Jw(U4(g),o);return h.length>0?h:l()}catch{return l()}},d=g=>{if(a||g.length===0)return;s??=Ze(e,{},()=>{});let h=s;for(let y=0;y<g.length;y+=r){let b=g.slice(y,y+r),w=()=>{if(!a)for(let x of b)h.send(N4,PR,x)};y===0||i<=0?w():c.push(setTimeout(w,y/r*i))}},f=()=>{a||(t.readWindowsNeighbors?u().then(d):d(l()))},m=()=>{if(!a){a=!0;for(let g of c)clearTimeout(g);s?.close()}};return{key:"sweep",start(g,h){a||h.aborted||(h.addEventListener("abort",m,{once:!0}),f())},refire(){a||f()},stop:m}}function Xw(t={}){let e=t.now!==void 0?{now:t.now}:{},n=t.config?{...e,protocolEnabled:l=>t.config.protocols?.[l]!==!1,emitUnidentified:t.config.unidentified!==!1}:e,o=t.onProbeError,r=o?{...e,onProbeError:l=>o("govee",l)}:e,i=o?{...e,onProbeError:l=>o("tuya",l)}:e,a=process.platform==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)?{...e,readWindowsNeighbors:kd}:e,c=o?{onProbeError:l=>o("arp",l)}:{};return[Va(e),Vw(e),Hw(e),Gw(e),Kw(e),Ww(e),jw(r),Ya(i),Yw(a),Zw({...n,...c})]}var DR={totalMs:1e4,refireAtMs:[2e3,4e3],envTimeoutMs:2e3,updateDebounceMs:250};async function Qw(t={}){let e={...DR,...t.timing},n=t.now??Date.now,o=t.id??`scan_${n().toString(36)}${Math.random().toString(36).slice(2,6)}`,r=n(),i=t.onProbeError??(()=>{}),s={},a=(M,ue)=>{M in s||(s[M]=ue instanceof Error?ue.message:String(ue));try{i(M,ue)}catch{}},c=(t.probes??Xw({now:n,...t.config?{config:t.config}:{},onProbeError:a})).filter(M=>t.config?.protocols?.[M.key]!==!1),l=t.enrich===!1?void 0:t.enrich??Fw(),u=new Zo,d=new AbortController,f=[],m,g,h={wsl:!1,multicastOk:null,broadcastOk:null},y=!1,b=[];try{b=(t.interfaceCidrs??hC)()}catch{b=[]}let w=M=>{let ue=pR(b,M.map(de=>de.addresses.ip));return ue===void 0?h:{...h,primaryInterface:ue}},x=M=>Object.keys(s).length?{...M,probeStatus:{...s}}:M,I=()=>{let M=u.snapshot();return x({id:o,status:"running",startedAt:r,devices:M,env:w(M)})},E=M=>{try{t.onUpdate?.(M)}catch{}},C=M=>{y||!t.onUpdate||(M?(m!==void 0&&(clearTimeout(m),m=void 0),E(I())):m===void 0&&(m=setTimeout(()=>{m=void 0,y||E(I())},e.updateDebounceMs)))},F=()=>{for(let M of f)clearTimeout(M);m!==void 0&&(clearTimeout(m),m=void 0),g&&t.signal&&t.signal.removeEventListener("abort",g),d.abort();for(let M of c)try{M.stop()}catch(ue){a(M.key,ue)}try{l?.stop()}catch{}},U=()=>{try{return u.snapshot()}catch{return[]}};try{(t.detectEnvFn??aw)({timeoutMs:e.envTimeoutMs}).then(de=>{y||(h=de,C(!0))}).catch(()=>{});let M=de=>{if(!y)try{C(u.add(de).created)}catch{}},ue=l?l.wrap(M):M;for(let de of c)try{Promise.resolve(de.start(ue,d.signal)).catch(K=>a(de.key,K))}catch(K){a(de.key,K)}for(let de of e.refireAtMs)de<=0||de>=e.totalMs||f.push(setTimeout(()=>{for(let K of c)try{K.refire?.()}catch(L){a(K.key,L)}},de));await new Promise(de=>{f.push(setTimeout(de,e.totalMs));let K=t.signal;if(K){if(K.aborted){de();return}g=()=>de(),K.addEventListener("abort",g,{once:!0})}})}catch(M){y=!0,F();let ue=U(),de=x({id:o,status:"failed",startedAt:r,finishedAt:n(),error:M instanceof Error?M.message:String(M),devices:ue,env:w(ue)});return E(de),de}y=!0,F();let W=U(),N=x({id:o,status:"done",startedAt:r,finishedAt:n(),devices:W,env:w(W)});return E(N),N}var F4=p.object({key:p.string().min(1),ip:p.string().min(1),name:p.string().optional(),model:p.string().optional(),providerDeviceId:p.string().optional(),enabled:p.boolean().default(!0)});function Tn(t){return`${t}_lan`}var B4=p.object({accountId:p.string().min(1),mode:p.enum(["manual","auto"]).default("manual"),devices:p.array(p.unknown()).default([])});function j4(t){let e=B4.safeParse(t);if(!e.success)return null;let n=[];for(let o of e.data.devices){let r=F4.safeParse(o);r.success&&n.push({...r.data,key:T(r.data.key)})}return{accountId:e.data.accountId,mode:e.data.mode,devices:n}}function co(t){let e=X(t);if(!e)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n.filter(o=>typeof o=="object"&&o!==null):[]}catch{return[]}}function z4(t,e){pe(t,`${JSON.stringify(e,null,2)}
169
+ `,384)}function $R(t){return{read(e){for(let n of co(t.providerAccountsFile(e))){let o=j4(n);if(o&&o.accountId===Tn(e))return o}return null},write(e,n){let o=t.providerAccountsFile(e),i=co(o).filter(s=>s.accountId!==n.accountId);z4(o,[...i,n])}}}function qd(){let t=new Map;return{read:e=>{let n=t.get(e);return n?structuredClone(n):null},write:(e,n)=>t.set(e,structuredClone(n))}}function OR(t,e,n){let o=T(n.mac),r=t.read(e)??{accountId:Tn(e),mode:"manual",devices:[]},i=r.devices.find(a=>a.key===o),s;return i?(s={created:!1,reEnabled:!i.enabled},i.enabled=!0,i.ip=n.ip,n.name!==void 0&&(i.name=n.name),n.model!==void 0&&(i.model=n.model),n.providerDeviceId!==void 0&&(i.providerDeviceId=n.providerDeviceId)):(r.devices.push({key:o,ip:n.ip,enabled:!0,...n.name!==void 0?{name:n.name}:{},...n.model!==void 0?{model:n.model}:{},...n.providerDeviceId!==void 0?{providerDeviceId:n.providerDeviceId}:{}}),s={created:!0,reEnabled:!1}),t.write(e,r),s}function LR(t,e,n,o){let r=T(n),i=t.read(e);if(!i)return!1;let s=i.devices.find(a=>a.key===r);return s?(o?i.devices=i.devices.filter(a=>a.key!==r):s.enabled=!1,t.write(e,i),!0):!1}function NR(t,e){let n=t.read(e);if(!n||n.devices.length===0)return 0;let o=n.devices.length;return n.devices=[],t.write(e,n),o}function tc(t,e,n,o){let r=T(n),i=t.read(e),s=i?.devices.find(a=>a.key===r);!i||!s||(s.ip=o,t.write(e,i))}function MR(t,e,n,o){let r=T(n),i=t.read(e),s=i?.devices.find(a=>a.key===r);!i||!s||(o?s.name=o:delete s.name,t.write(e,i))}function nc(t){return t?.devices.filter(e=>e.enabled)??[]}function UR(t){let e=[];for(let n of Hn.options){let o=nc(t.read(n));o.length>0&&e.push({provider:n,accountId:Tn(n),devices:o})}return e}function FR(t){let e=X(t);if(e)try{let n=jo.safeParse(JSON.parse(e));if(n.success)return n.data}catch{}return jo.parse({})}function BR(t,e){pe(e,`${JSON.stringify(t,null,2)}
170
+ `)}async function he(t){try{return await t.fn(t.ip)}catch(e){if(t.bail?.())throw e;let n=await t.rediscover();if(!n||n===t.ip)throw e;let o=await t.fn(n);return t.onNewIp?.(n),o}}async function se(t,e={}){let n=T(t);try{return(await gs(e)).find(o=>o.mac===n)?.ip}catch{return}}async function dt(t,e={}){try{return(await gs(e)).find(n=>n.ip===t)?.mac}catch{return}}var H4=t=>/^(https?|wss?):\/\/[^\s]+$/i.test(t),K4=p.object({accountId:p.string().min(1),baseUrl:p.string().refine(H4,"must be an http(s)/ws(s) URL"),unitSystem:p.enum(["metric","imperial"]).optional(),enabled:p.boolean().optional()});function G4(t){let e=[];for(let n of t){let o=K4.safeParse(n);o.success&&o.data.enabled!==!1&&e.push({accountId:o.data.accountId,config:{baseUrl:o.data.baseUrl,...o.data.unitSystem?{unitSystem:o.data.unitSystem}:{}}})}return e}function jR(t){return t?G4(co(t.providerAccountsFile("homeassistant"))):[]}var W4=p.object({accountId:p.string().min(1),host:p.string().min(1),bridgeId:p.string().min(1),name:p.string().optional(),enabled:p.boolean().optional()});function Z4(t){let e=[];for(let n of t){let o=W4.safeParse(n);o.success&&o.data.enabled!==!1&&e.push({accountId:o.data.accountId,config:{host:o.data.host,bridgeId:o.data.bridgeId,...o.data.name?{name:o.data.name}:{}}})}return e}function zR(t){return t?Z4(co(t.providerAccountsFile("hue"))):[]}var q4=p.object({accountId:p.string().min(1),host:p.string().min(1),port:p.number().int().min(1).max(65535).optional(),tls:p.boolean().optional(),username:p.string().optional(),discoveryPrefix:p.string().min(1).optional(),clientId:p.string().min(1).optional(),enabled:p.boolean().optional()});function V4(t){let e=[];for(let n of t){let o=q4.safeParse(n);if(!o.success||o.data.enabled===!1)continue;let r=o.data,i=ET(r.host);i.host&&e.push({accountId:r.accountId,config:{host:i.host,...r.port!==void 0?{port:r.port}:i.port!==void 0?{port:i.port}:{},...r.tls!==void 0?{tls:r.tls}:i.tls!==void 0?{tls:i.tls}:{},...r.username?{username:r.username}:{},...r.discoveryPrefix?{discoveryPrefix:r.discoveryPrefix}:{},...r.clientId?{clientId:r.clientId}:{}}})}return e}function HR(t){return t?V4(co(t.providerAccountsFile("mqtt"))):[]}var ii=require("node:crypto");var tk=new Set(["pir","mcs","wsdcg","ywbj","rqbj","sj","sos","ms","co2bj","cobj","pm25","ldcg","wnykq","sfkzq"]);function Vd(t){return t!==void 0&&tk.has(t)}var En=(t,e)=>typeof t=="string"?t.toLowerCase()===e:typeof t=="boolean"?t:t===1||t==="1"?!0:t===0||t==="0"?!1:null,ek=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="open"||t==="opened"?!0:t===0||t==="0"||t==="closed"?!1:null,KR=t=>typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&t.trim()!==""&&Number.isFinite(Number(t))?Number(t):null,J4={pir:{cap:"binarySensor",sensorType:"motion",active:t=>En(t,"pir")},pir_state:{cap:"binarySensor",sensorType:"motion",active:t=>En(t,"pir")},presence_state:{cap:"binarySensor",sensorType:"presence",active:t=>En(t,"presence")},doorcontact_state:{cap:"binarySensor",sensorType:"contact",active:ek},watersensor_state:{cap:"binarySensor",sensorType:"leak",active:t=>En(t,"alarm")},smoke_sensor_status:{cap:"binarySensor",sensorType:"smoke",active:t=>En(t,"alarm")},smoke_sensor_state:{cap:"binarySensor",sensorType:"smoke",active:t=>En(t,"alarm")},gas_sensor_status:{cap:"binarySensor",sensorType:"gas",active:t=>En(t,"alarm")},gas_sensor_state:{cap:"binarySensor",sensorType:"gas",active:t=>En(t,"alarm")},co_status:{cap:"binarySensor",sensorType:"co",active:t=>En(t,"alarm")},co_state:{cap:"binarySensor",sensorType:"co",active:t=>En(t,"alarm")},temper_alarm:{cap:"binarySensor",sensorType:"tamper",active:ek},sos_state:{cap:"binarySensor",sensorType:"button",active:ek},va_temperature:{cap:"sensor",measurement:"temperature",divide:10},temp_current:{cap:"sensor",measurement:"temperature",divide:10},va_humidity:{cap:"sensor",measurement:"humidity"},humidity_value:{cap:"sensor",measurement:"humidity"},bright_value:{cap:"sensor",measurement:"illuminance"},illuminance_value:{cap:"sensor",measurement:"illuminance"},pm25_value:{cap:"sensor",measurement:"pm25"},pm10_value:{cap:"sensor",measurement:"pm10"},co2_value:{cap:"sensor",measurement:"co2"},voc_value:{cap:"sensor",measurement:"voc"},battery_percentage:{cap:"battery",kind:"level"},residual_electricity:{cap:"battery",kind:"level"},va_battery:{cap:"battery",kind:"level"},battery_state:{cap:"battery",kind:"state"}},Y4=20;function Jd(t,e){let n=new Map;for(let a of t)n.set(a.code,a);let o=new Set([...e??[],...t.map(a=>a.code)]),r=[],i=[],s;for(let a of o){let c=J4[a];if(!c)continue;let l=n.get(a),u=typeof l?.time=="number"?l.time:void 0,d=u!==void 0?{reportTs:u}:{};if(c.cap==="binarySensor")r.push({code:a,sensorType:c.sensorType,active:l===void 0?null:c.active(l.value),...d});else if(c.cap==="sensor"){let f=l===void 0?null:KR(l.value);i.push({code:a,measurement:c.measurement,unit:en[c.measurement],value:f===null?null:f/(c.divide??1),...d})}else s??={level:null,low:null},c.kind==="level"?s.level=l===void 0?s.level:KR(l.value):l!==void 0&&(s.low=En(l.value,"low")),u!==void 0&&(s.reportTs=u)}return{binary:r,numeric:i,...s?{battery:s}:{}}}var Yd=t=>t.low!==null?t.low:t.level!==null?t.level<=Y4:null;function GR(t){let e=[];for(let n of t.binary)e.push({type:"binarySensor",instance:n.code,config:{sensorType:n.sensorType},state:{active:n.active,lastChanged:n.reportTs??null}});for(let n of t.numeric)e.push({type:"sensor",instance:n.code,config:{measurement:n.measurement,unit:n.unit},state:{value:n.value,ts:n.reportTs??null}});return t.battery&&e.push({type:"battery",state:{level:t.battery.level,low:Yd(t.battery)}}),e}function WR(t,e){let n=[];for(let o of t.binary)n.push({type:"binarySensor",instance:o.code,state:{active:o.active,lastChanged:o.reportTs??e??null}});for(let o of t.numeric)n.push({type:"sensor",instance:o.code,state:{value:o.value,ts:o.reportTs??e??null}});return t.battery&&n.push({type:"battery",state:{level:t.battery.level,low:Yd(t.battery)}}),n}function X4(t){return t.some(e=>e.type==="binarySensor")?"binarySensor":"sensor"}function ZR(t,e,n){let o=t.mac?T(t.mac):void 0;return{source:{provider:"tuya",providerAccountId:n.accountId,nativeId:t.id,...t.category?{nativeType:t.category}:{},reachability:"cloud",online:n.online??t.online??!0,lastSeen:n.now},fingerprints:o?[`mac:${o}`]:[`tuya:${t.id}`],type:X4(e),name:t.name,manufacturer:"Tuya",model:t.productId??null,capabilities:e}}var qR={eu:"https://openapi.tuyaeu.com","eu-w":"https://openapi-weaz.tuyaeu.com",us:"https://openapi.tuyaus.com","us-e":"https://openapi-ueaz.tuyaus.com",cn:"https://openapi.tuyacn.com",in:"https://openapi.tuyain.com"},Ue=class extends Error{constructor(n,o){super(n);this.code=o;this.name="TuyaCloudError"}code},VR="Your Tuya IoT Core trial has expired. Open iot.tuya.com \u2192 Cloud \u2192 My Services \u2192 'Extend Trial Period' (approved in 1\u20132 workdays). Your already-connected lamps keep working locally \u2014 only fetching NEW keys is blocked.",Q4="Your Tuya IoT Core plan has an overdue bill. Open iot.tuya.com \u2192 Cloud \u2192 My Services and settle it. Your already-connected lamps keep working locally \u2014 only fetching NEW keys is blocked.",e5="Tuya rejected the request timestamp \u2014 this PC's clock is off. Turn on automatic date & time (or sync the system clock) and try again.",t5="Tuya blocked this request by IP allowlist. In iot.tuya.com \u2192 Cloud \u2192 your project \u2192 Overview, add this PC's public IP address to the project's IP allowlist (or clear it), then retry.",JR=new Set([28841002,28841105,1106]),n5=(t,e)=>t!==void 0&&JR.has(t)||/subscription|no permission|not.*authorized|expired|service.*expired/i.test(e),r5=new Set([28841003]),o5=new Set([1013]),i5=new Set([1114]),s5=new Set([1041,1110,1111,1113,1199]),a5=new Set([1010,1011,1012]),YR=t=>(0,ii.createHash)("sha256").update(t).digest("hex"),c5=YR("");function l5(t){let e=`${t.method}
171
+ ${t.body?YR(t.body):c5}
172
+
173
+ ${t.path}`,n=`${t.clientId}${t.accessToken??""}${t.t}${t.nonce}${e}`;return(0,ii.createHmac)("sha256",t.secret).update(n).digest("hex").toUpperCase()}async function oi(t,e){let n=String(e.now()),o=e.nonce(),r=l5({clientId:e.clientId,secret:e.secret,...e.accessToken?{accessToken:e.accessToken}:{},method:e.method,path:e.path,body:"",t:n,nonce:o}),i={client_id:e.clientId,sign:r,t:n,nonce:o,sign_method:"HMAC-SHA256"};e.accessToken&&(i.access_token=e.accessToken);let s=await t(`${e.host}${e.path}`,{method:e.method,headers:i}),a;try{a=JSON.parse(await s.text())}catch{throw new Ue(`Tuya cloud returned a non-JSON response (HTTP ${s.status})`)}if(a.success===!1||a.code!==void 0&&a.code!==0){let c=a.msg??`error ${a.code??"?"}`,l=a.code;throw l!==void 0&&r5.has(l)?new Ue(Q4,l):l!==void 0&&o5.has(l)?new Ue(e5,l):l!==void 0&&i5.has(l)?new Ue(t5,l):n5(l,c)?new Ue(VR,l):new Ue(`Tuya cloud: ${c}`,l)}return a.result}async function XR(t){let e=[],n;for(let o=0;o<100;o++){let r=await t(`size=100${n?`&last_row_key=${encodeURIComponent(n)}`:""}`);if(Array.isArray(r)){e.push(...r);break}if(e.push(...r.devices??[]),r.has_more!==!0||!r.last_row_key||(r.devices??[]).length===0)break;n=r.last_row_key}return e}function QR(t){if(!t||typeof t!="object")return;let e=t.model,n=t;if(typeof e=="string")try{n=JSON.parse(e)}catch{return}let o={},r={},i=!1,s=l=>{if(!l||typeof l!="object")return;let u=l,d=typeof u.code=="string"?u.code:void 0,f=typeof u.abilityId=="number"?u.abilityId:typeof u.dp_id=="number"?u.dp_id:void 0;if(!d||f===void 0)return;o[d]=f,/^(bright_value|temp_value|colour_data)$/.test(d)&&f<10&&(i=!0);let m=u.typeSpec??u.values,g=typeof m=="string"?u5(m):m;if(g&&typeof g=="object"){let h=g.min,y=g.max;typeof h=="number"&&typeof y=="number"&&(r[d]={min:h,max:y})}},a=n.services;if(Array.isArray(a)){for(let l of a)if(l&&typeof l=="object")for(let u of l.properties??[])s(u)}let c=n.properties;if(Array.isArray(c))for(let l of c)s(l);for(let l of["functions","status"]){let u=n[l];if(Array.isArray(u))for(let d of u)s(d)}if(Object.keys(o).length!==0)return{codes:o,...Object.keys(r).length?{ranges:r}:{},...i?{legacy:!0}:{}}}var u5=t=>{try{return JSON.parse(t)}catch{return}};async function rc(t){let e=qR[t.creds.region];if(!e)throw new Ue(`Unknown Tuya region "${t.creds.region}" \u2014 use eu, eu-w, us, us-e, cn, or in.`);let n=t.now??Date.now,o=t.nonce??(()=>(0,ii.randomBytes)(8).toString("hex")),r={host:e,clientId:t.creds.clientId,secret:t.creds.clientSecret,now:n,nonce:o},i=await oi(t.fetch,{...r,method:"GET",path:"/v1.0/token?grant_type=1"});if(!i.access_token)throw new Ue("Tuya cloud did not return an access token \u2014 re-check the Access ID/Secret and region.");let s=await XR(u=>oi(t.fetch,{...r,accessToken:i.access_token,method:"GET",path:`/v1.0/iot-01/associated-users/devices?${u}`})),a={},c=0;for(let u of s){if(!u.id||!u.local_key)continue;let d=u.category??"",f=tk.has(d);f&&c++;let m;try{let g=await oi(t.fetch,{...r,accessToken:i.access_token,method:"GET",path:`/v2.0/cloud/thing/${u.id}/model`});m=QR(g)}catch{}a[u.id]={localKey:u.local_key,name:u.name??d??"Tuya device",category:d,...u.product_id?{productId:u.product_id}:{},...f?{sleepy:!0}:{},...m?{dpModel:m}:{}}}let l=Object.keys(a);if(l.length>0)try{let u=await oi(t.fetch,{...r,accessToken:i.access_token,method:"GET",path:`/v1.0/iot-03/devices/factory-infos?device_ids=${l.join(",")}`});for(let d of Array.isArray(u)?u:[]){let f=typeof d?.id=="string"?a[d.id]:void 0,m=typeof d?.mac=="string"&&d.mac.length>0?T(d.mac):void 0;f&&m&&m.length===17&&(f.mac=m)}}catch{}return{keystore:a,deviceCount:Object.keys(a).length,sleepyCount:c}}function Cn(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!e||typeof e!="object"||Array.isArray(e))return{};let n={};for(let[o,r]of Object.entries(e)){if(!r||typeof r!="object")continue;let i=r;typeof i.localKey!="string"||typeof i.name!="string"||typeof i.category!="string"||(n[o]={localKey:i.localKey,name:i.name,category:i.category,...typeof i.productId=="string"?{productId:i.productId}:{},...i.protoVersion==="3.3"||i.protoVersion==="3.4"||i.protoVersion==="3.5"?{protoVersion:i.protoVersion}:{},...typeof i.mac=="string"?{mac:i.mac}:{},...i.sleepy===!0?{sleepy:!0}:{},...i.dpModel&&typeof i.dpModel=="object"?{dpModel:i.dpModel}:{}})}return n}function oc(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let i=t[o]?.mac;n[o]={...r,...i&&!r.mac?{mac:i}:{}}}return n}function ic(t){return t instanceof Ue&&(t.message===VR||t.code!==void 0&&JR.has(t.code))}function nk(t){return t instanceof Ue&&(t.code!==void 0&&s5.has(t.code)||/too many|rate.?limit|429|frequent/i.test(t.message))}var d5=t=>t instanceof Ue&&t.code!==void 0&&a5.has(t.code);function eA(t){let e=qR[t.creds.region];if(!e)throw new Ue(`Unknown Tuya region "${t.creds.region}" \u2014 use eu, eu-w, us, us-e, cn, or in.`);let n=t.now??Date.now,o=t.nonce??(()=>(0,ii.randomBytes)(8).toString("hex")),r={host:e,clientId:t.creds.clientId,secret:t.creds.clientSecret,now:n,nonce:o},i=null,s=async()=>{let l=await oi(t.fetch,{...r,method:"GET",path:"/v1.0/token?grant_type=1"});if(!l.access_token)throw new Ue("Tuya cloud did not return an access token \u2014 re-check the Access ID/Secret and region.");return i={access:l.access_token,expiresAt:n()+(l.expire_time??7200)*1e3},l.access_token},a=async()=>i&&n()<i.expiresAt-6e4?i.access:s(),c=async l=>{let u=await a();try{return await oi(t.fetch,{...r,accessToken:u,method:"GET",path:l})}catch(d){if(!d5(d))throw d;return i=null,oi(t.fetch,{...r,accessToken:await s(),method:"GET",path:l})}};return{async devices(){return XR(l=>c(`/v1.0/iot-01/associated-users/devices?${l}`))},async model(l){try{return QR(await c(`/v2.0/cloud/thing/${encodeURIComponent(l)}/model`))}catch{return}},async properties(l){let u=await c(`/v2.0/cloud/thing/${encodeURIComponent(l)}/shadow/properties`);return(Array.isArray(u)?u:u.properties??[]).map(f=>({code:String(f.code),value:f.value,...typeof f.time=="number"?{time:f.time}:{},...typeof f.dp_id=="number"?{dpId:f.dp_id}:{}}))}}}function si(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;return typeof n.clientId!="string"||typeof n.clientSecret!="string"||typeof n.region!="string"?null:{clientId:n.clientId,clientSecret:n.clientSecret,region:n.region,...typeof n.uid=="string"?{uid:n.uid}:{},...typeof n.pollSeconds=="number"&&n.pollSeconds>0?{pollSeconds:n.pollSeconds}:{}}}var rk="tuya_cloud",ok="govee_cloud";function p5(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.apiKey=="string"&&e.apiKey.length>0?{apiKey:e.apiKey}:null}catch{return null}}function f5(t){if(!t)return[];try{let e=JSON.parse(t);if(!e||typeof e!="object")return[];let n=[];for(let[o,r]of Object.entries(e))typeof r?.sku=="string"&&n.push({device:o,sku:r.sku,...typeof r.name=="string"?{name:r.name}:{}});return n}catch{return[]}}function tA(t){let e=[];si(t("tuya","cloud"))&&e.push({provider:"tuya",accountId:rk,cfg:{}});let n=p5(t("govee","cloud")),o=f5(t("govee","keystore"));return n&&o.length>0&&e.push({provider:"govee",accountId:ok,cfg:{apiKey:n.apiKey,devices:o}}),e}var An={minKelvin:2e3,maxKelvin:9e3},Rn=t=>typeof t=="number"&&Number.isFinite(t)?t:null,m5=t=>typeof t=="string"&&t?t:void 0,ac=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,sc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function Ss(t,e={}){return JSON.stringify({msg:{cmd:t,data:e}})}var ik=Ss("devStatus",{});function Xd(t,e){let n=ac(ac(t)?.msg);if(!n)throw new Error("govee reply has no msg");if(n.cmd!==e)throw new Error(`govee reply cmd ${String(n.cmd)} != ${e}`);let o=ac(n.data);if(!o)throw new Error("govee reply has no data");return o}function nA(t){let e=Xd(t,"scan"),n=m5(e.sku);return n!==void 0?{model:n}:{}}function Qd(t,e){let n=(t%360+360)%360/60,r=Math.max(0,Math.min(100,e))/100,i=r*(1-Math.abs(n%2-1)),s=1-r,[a,c,l]=n<1?[r,i,0]:n<2?[i,r,0]:n<3?[0,r,i]:n<4?[0,i,r]:n<5?[i,0,r]:[r,0,i];return{r:Math.round((a+s)*255),g:Math.round((c+s)*255),b:Math.round((l+s)*255)}}function sk(t,e,n){let o=t/255,r=e/255,i=n/255,s=Math.max(o,r,i),a=Math.min(o,r,i),c=s-a;if(c===0||s===0)return{hue:0,saturation:0};let l;return s===o?l=(r-i)/c%6:s===r?l=(i-o)/c+2:l=(o-r)/c+4,{hue:Math.round(((l*60+360)%360+360)%360),saturation:Math.round(c/s*100)}}function rA(t){let e=Rn(t.onOff),n=Rn(t.colorTemInKelvin),o=ac(t.color),r=o?Rn(o.r):null,i=o?Rn(o.g):null,s=o?Rn(o.b):null,a=n!==null&&n>0,c=!a&&r!==null&&i!==null&&s!==null?sk(r,i,s):null;return{on:e===null?null:e!==0,level:Rn(t.brightness),kelvin:a?n:null,hue:c?c.hue:null,saturation:c?c.saturation:null}}function ep(t){let e=rA(t);return[{type:"power",state:{on:e.on}},{type:"brightness",state:{level:e.level}},{type:"colorTemperature",state:{kelvin:e.kelvin}},{type:"color",state:{hue:e.hue,saturation:e.saturation}}]}function oA(t,e){let n=rA(t),o=T(e.mac);return{source:{provider:"govee",providerAccountId:e.accountId,nativeId:o,...e.model?{nativeType:e.model}:{},reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${o}`],type:"light",name:e.nameOverride??e.model??"Govee light",manufacturer:"Govee",model:e.model??null,capabilities:[{type:"power",state:{on:n.on}},{type:"brightness",state:{level:n.level}},{type:"colorTemperature",config:An,state:{kelvin:n.kelvin}},{type:"color",config:{modes:["hs"]},state:{hue:n.hue,saturation:n.saturation}}]}}function iA(t,e){return{source:{provider:"govee",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??t.model??"Govee light",manufacturer:"Govee",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function sA(t,e,n,o){let r=ac(n)??{},i=()=>{throw new Error(`govee light does not support ${t}.${e}`)};if(t==="power"&&(e==="turnOn"||e==="turnOff"||e==="toggle")){let s;if(e==="toggle"){if(o.currentOn===void 0)throw new Error("govee toggle needs the current power state (pre-read failed)");s=!o.currentOn}else s=e==="turnOn";return{frame:Ss("turn",{value:s?1:0}),optimistic:{type:"power",state:{on:s}}}}if(t==="brightness"&&(e==="setBrightness"||e==="adjustBrightness")){let s;if(e==="adjustBrightness"){if(o.currentLevel===void 0)throw new Error("govee adjustBrightness needs the current level (pre-read failed)");s=sc(o.currentLevel+(Rn(r.delta)??0),0,100)}else s=sc(Rn(r.level)??0,0,100);if(s===0)return{frame:Ss("turn",{value:0}),optimistic:{type:"brightness",state:{level:0}}};let a=Math.max(1,s);return{frame:Ss("brightness",{value:a}),optimistic:{type:"brightness",state:{level:a}}}}if(t==="colorTemperature"&&e==="setColorTemperature"){let s=sc(Rn(r.kelvin)??An.minKelvin,An.minKelvin,An.maxKelvin);return{frame:Ss("colorwc",{color:{r:0,g:0,b:0},colorTemInKelvin:s}),optimistic:{type:"colorTemperature",state:{kelvin:s}}}}if(t==="color"&&e==="setColor"){let s=sc(Rn(r.hue)??0,0,360),a=sc(Rn(r.saturation)??0,0,100),{r:c,g:l,b:u}=Qd(s,a);return{frame:Ss("colorwc",{color:{r:c,g:l,b:u},colorTemInKelvin:0}),optimistic:{type:"color",state:{hue:s,saturation:a}}}}return i()}function aA(t,e){return ep(t).find(n=>n.type===e)?.state}var ak=4003,g5=1e4,h5=2e3,cA=3,y5=t=>t>0?new Promise(e=>setTimeout(e,t).unref?.()):Promise.resolve(),tp=class{constructor(e,n,o=uA){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="govee";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"Govee devices need no pairing \u2014 enable LAN Control in the Govee app, then connect via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);r?(this.runtime.set(o.key,{ip:r.ip,online:!0,misses:0,...o.model?{model:o.model}:{}}),n.push(oA(r.data,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.model?{model:o.model}:{},...o.name?{nameOverride:o.name}:{}}))):(this.runtime.set(o.key,{ip:o.ip,online:!1,misses:cA,...o.model?{model:o.model}:{}}),n.push(iA(o,{accountId:this.accountId,now:Date.now()})))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshStatus(r);i.online=!0,i.misses=0,o.push({nativeId:r,patch:ep(s),online:!0,ts:Date.now()})}catch{i.misses++,i.misses>=cA&&i.online&&(i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()}))}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown govee device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let u=ep(await this.freshStatus(e)),d=u.find(m=>m.type==="power")?.state,f=u.find(m=>m.type==="brightness")?.state;typeof d?.on=="boolean"&&(a.currentOn=d.on),typeof f?.level=="number"&&(a.currentLevel=f.level)}let{frame:c,optimistic:l}=sA(n,o,r,a);if(await this.need().control(s.ip,c),s.online=!0,s.misses=0,i?.readAfter){await y5(this.cfg.settleMs??h5);let u=aA(await this.freshStatus(e),n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??g5),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}async freshStatus(e){let n=this.runtime.get(e);if(!n)throw new Error(`unknown govee device ${e}`);let o=await he({ip:n.ip,fn:r=>this.need().query(r,ik,ak),rediscover:()=>this.need().rediscover(e),onNewIp:r=>{n.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed});return Xd(o,"devStatus")}async locate(e,n){let o=async r=>({ip:r,data:Xd(await e.query(r,ik,ak),"devStatus")});try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("Govee adapter not initialized");return this.client}};function lA(t=uA){let e=t();return async n=>{try{let{model:o}=nA(await e.query(n,ti,ei)),r=await e.macForIp(n);return{...r?{mac:T(r)}:{},...o?{model:o}:{}}}catch{return null}}}var v5=2e3,uA=()=>{let t=!1,e=new Set;return{async control(n,o){if(t)throw new Error("govee client closed");let r=await import("node:dgram");await new Promise((i,s)=>{let a=r.createSocket("udp4");a.on("error",c=>{try{a.close()}catch{}s(c instanceof Error?c:new Error(String(c)))}),a.send(o,ak,n,c=>{try{a.close()}catch{}c?s(c):i()})})},async query(n,o,r){if(t)throw new Error("govee client closed");let i=await import("node:dgram");return new Promise((s,a)=>{let c=i.createSocket({type:"udp4",reuseAddr:!0}),l=!1,u=f=>{if(!l){l=!0,e.delete(u);try{c.close()}catch{}a(f)}};e.add(u);let d=setTimeout(()=>u(new Error(`govee request timeout (${n}:${r})`)),v5);d.unref?.(),c.on("error",f=>{clearTimeout(d),u(f instanceof Error?f:new Error(String(f)))}),c.on("message",(f,m)=>{if(m.address===n&&!l){l=!0,e.delete(u),clearTimeout(d);try{c.close()}catch{}try{s(JSON.parse(f.toString("utf8")))}catch(g){a(g instanceof Error?g:new Error(String(g)))}}}),c.bind(Nd,()=>{c.send(o,r,n,f=>{f&&(clearTimeout(d),u(f))})})})},macForIp(n){return dt(n)},rediscover(n){return se(n)},close(){t=!0;for(let n of[...e])n(new Error("govee client closed"));e.clear()}}};var b5="https://openapi.api.govee.com/router/api/v1",rp=(t,e)=>fetch(t,e),on=class extends Error{constructor(n,o){super(n);this.code=o;this.name="GoveeCloudError"}code},je={power:{type:"devices.capabilities.on_off",instance:"powerSwitch"},brightness:{type:"devices.capabilities.range",instance:"brightness"},colorRgb:{type:"devices.capabilities.color_setting",instance:"colorRgb"},colorTemp:{type:"devices.capabilities.color_setting",instance:"colorTemperatureK"}},dA={type:"devices.capabilities.dynamic_scene",instance:"lightScene"},cc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t))),Pn=t=>typeof t=="number"&&Number.isFinite(t)?t:null,pA=(t,e,n)=>(t&255)<<16|(e&255)<<8|n&255,w5=t=>({r:t>>16&255,g:t>>8&255,b:t&255});async function ai(t,e,n,o,r){let i;try{i=await t(`${b5}${n}`,{method:"POST",headers:{"Content-Type":"application/json","Govee-API-Key":e},body:JSON.stringify({requestId:r,...o&&typeof o=="object"?o:{}})})}catch(a){throw new on(`Couldn't reach the Govee cloud \u2014 check your internet connection. (${a instanceof Error?a.message:String(a)})`)}if(i.status===401||i.status===403)throw new on("Govee rejected that API key \u2014 copy it again from the Govee Home app (Settings \u2192 Apply for API Key).",i.status);if(i.status===429)throw new on("Govee's daily API limit was hit \u2014 try again later.",429);let s;try{s=JSON.parse(await i.text())}catch{throw new on(`Govee returned an unexpected response (HTTP ${i.status}).`,i.status)}if(i.status<200||i.status>=300||s.code!==void 0&&s.code!==200)throw new on(s.message??s.msg??`Govee API error (HTTP ${i.status}, code ${s.code??"?"}).`,s.code??i.status);return s}var lc=t=>typeof t=="string"&&t?t:void 0;async function k5(t,e,n){let o=await ai(t,e,"/user/devices",{},n),r=Array.isArray(o.data)?o.data:[],i=[];for(let s of r){if(!s||typeof s!="object")continue;let a=s,c=lc(a.sku),l=lc(a.device);if(!c||!l)continue;let u=Array.isArray(a.capabilities)?a.capabilities:[];u.length>0&&!u.some(d=>d?.type===je.power.type)||i.push({sku:c,device:l,name:lc(a.deviceName)??c})}return i}async function op(t,e,n,o){let r=await ai(t,e,"/device/state",{payload:{sku:n.sku,device:n.device}},o),i=r.payload&&typeof r.payload=="object"?r.payload:{},s=Array.isArray(i.capabilities)?i.capabilities:[],a=(h,y)=>{let b=s.find(x=>x?.type===h&&x?.instance===y);return(b&&typeof b.state=="object"?b.state:void 0)?.value},c=Pn(a(je.power.type,je.power.instance)),l=Pn(a(je.brightness.type,je.brightness.instance)),u=Pn(a(je.colorTemp.type,je.colorTemp.instance)),d=Pn(a(je.colorRgb.type,je.colorRgb.instance)),f=u!==null&&u>0,m=d!==null?w5(d):null,g=!f&&m?sk(m.r,m.g,m.b):null;return[{type:"power",state:{on:c===null?null:c!==0}},{type:"brightness",state:{level:l}},{type:"colorTemperature",state:{kelvin:f?u:null}},{type:"color",state:{hue:g?g.hue:null,saturation:g?g.saturation:null}}]}async function fA(t,e,n,o){let r=await ai(t,e,"/device/scenes",{payload:{sku:n.sku,device:n.device}},o),i=r.payload&&typeof r.payload=="object"?r.payload:{},a=(Array.isArray(i.capabilities)?i.capabilities:[]).find(f=>f?.type===dA.type),c=a&&typeof a.parameters=="object"?a.parameters:{},l=Array.isArray(c.options)?c.options:[],u=new Set,d=[];for(let f of l){let m=lc(f?.name);m===void 0||f?.value===void 0||u.has(m)||(u.add(m),d.push({name:m,value:f.value}))}return d}async function mA(t,e,n,o,r){await ai(t,e,"/device/control",{payload:{sku:n.sku,device:n.device,capability:{...dA,value:o}}},r)}var np={type:"devices.capabilities.segment_color_setting",instance:"segmentedColorRgb"},Wt=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;function x5(t){let n=(Array.isArray(t)?t:[]).find(c=>Wt(c)?.type===np.type&&Wt(c)?.instance===np.instance),o=Wt(Wt(n)?.parameters)?.fields,r=(Array.isArray(o)?o:[]).find(c=>Wt(c)?.fieldName==="segment"),i=Wt(Wt(r)?.elementRange)??Wt(Wt(r)?.size),s=Pn(i?.min),a=Pn(i?.max);return s===null||a===null||a<s?null:a-s+1}function S5(t){let e=Array.isArray(t)?t:[];if(e.length===0)return null;let n=r=>e.some(i=>Wt(i)?.type===r),o=(r,i)=>e.some(s=>Wt(s)?.type===r&&Wt(s)?.instance===i);return{power:n(je.power.type),brightness:o(je.brightness.type,je.brightness.instance),color:o(je.colorRgb.type,je.colorRgb.instance),colorTemperature:o(je.colorTemp.type,je.colorTemp.instance),segments:x5(t)}}async function gA(t,e,n){let o=await ai(t,e,"/user/devices",{},n),r=Array.isArray(o.data)?o.data:[],i=new Map;for(let s of r){let a=Wt(s),c=lc(a?.device);if(!c)continue;let l=S5(a?.capabilities);l&&i.set(c,l)}return i}function hA(t){let e=new Map;for(let n of t){let{r:o,g:r,b:i}=Qd(n.hue,n.saturation),s=pA(o,r,i),a=e.get(s);a?a.push(n.index):e.set(s,[n.index])}return[...e.entries()].map(([n,o])=>({rgb:n,segments:o}))}async function yA(t,e,n,o,r,i){await ai(t,e,"/device/control",{payload:{sku:n.sku,device:n.device,capability:{type:np.type,instance:np.instance,value:{segment:o,rgb:r}}}},i)}function vA(t,e,n,o){let r=n&&typeof n=="object"?n:{},i=()=>{throw new on(`Govee cloud light does not support ${t}.${e}`)};if(t==="power"&&(e==="turnOn"||e==="turnOff"||e==="toggle")){let s;if(e==="toggle"){if(o.currentOn===void 0)throw new on("govee toggle needs the current power state (state read failed)");s=!o.currentOn}else s=e==="turnOn";return{capability:{...je.power,value:s?1:0},optimistic:{type:"power",state:{on:s}}}}if(t==="brightness"&&(e==="setBrightness"||e==="adjustBrightness")){let s;if(e==="adjustBrightness"){if(o.currentLevel===void 0)throw new on("govee adjustBrightness needs the current level (state read failed)");s=cc(o.currentLevel+(Pn(r.delta)??0),0,100)}else s=cc(Pn(r.level)??0,0,100);return s===0?{capability:{...je.power,value:0},optimistic:{type:"brightness",state:{level:0}}}:{capability:{...je.brightness,value:s},optimistic:{type:"brightness",state:{level:s}}}}if(t==="colorTemperature"&&e==="setColorTemperature"){let s=cc(Pn(r.kelvin)??An.minKelvin,An.minKelvin,An.maxKelvin);return{capability:{...je.colorTemp,value:s},optimistic:{type:"colorTemperature",state:{kelvin:s}}}}if(t==="color"&&e==="setColor"){let s=cc(Pn(r.hue)??0,0,360),a=cc(Pn(r.saturation)??0,0,100),{r:c,g:l,b:u}=Qd(s,a);return{capability:{...je.colorRgb,value:pA(c,l,u)},optimistic:{type:"color",state:{hue:s,saturation:a}}}}return i()}async function bA(t,e,n,o,r){await ai(t,e,"/device/control",{payload:{sku:n.sku,device:n.device,capability:o}},r)}async function wA(t){let e=t.requestId??(()=>"req"),n=await k5(t.fetch,t.creds.apiKey,e()),o={};for(let r of n)o[r.device]={sku:r.sku,name:r.name};return{keystore:o,deviceCount:n.length}}function _5(t,e,n,o){let r=[];o?(o.power&&r.push({type:"power",state:{on:null}}),o.brightness&&r.push({type:"brightness",state:{level:null}}),o.colorTemperature&&r.push({type:"colorTemperature",config:An,state:{kelvin:null}}),o.color&&r.push({type:"color",config:{modes:["hs"]},state:{hue:null,saturation:null}})):r.push({type:"power",state:{on:null}},{type:"brightness",state:{level:null}},{type:"colorTemperature",config:An,state:{kelvin:null}},{type:"color",config:{modes:["hs"]},state:{hue:null,saturation:null}});let i=o!==void 0&&o.power&&!o.brightness&&!o.color&&!o.colorTemperature;return{source:{provider:"govee",providerAccountId:e,nativeId:t.device,...t.sku?{nativeType:t.sku}:{},reachability:"cloud",online:!0,lastSeen:n},fingerprints:[`fallback:govee:${e}:${t.device}`],type:i?"plug":"light",name:t.name??t.sku??"Govee light",manufacturer:"Govee",model:t.sku??null,capabilities:r}}var ip=class{constructor(e,n,o=rp){this.accountId=e;this.cfg=n;this.fetch=o;for(let r of n.devices)this.byId.set(r.device,r);this.now=n.now??Date.now}accountId;cfg;fetch;provider="govee";reachability="cloud";byId=new Map;scenesById=new Map;segmentsById=new Map;now;seq=0;rid(){return this.cfg.requestId?this.cfg.requestId():`gv-${this.accountId}-${++this.seq}`}async init(e){}async link(e,n){return{ok:!1,error:"Add your Govee API key via the Integrations panel (Govee Home app \u2192 Settings \u2192 Apply for API Key), then rescan.",retryable:!1}}async unlink(e){}async discover(){let e=this.now(),n=[],o=new Map;try{for(let[r,i]of await gA(this.fetch,this.cfg.apiKey,this.rid()))o.set(r,i)}catch{}this.segmentsById.clear();for(let[r,i]of o)i.segments&&this.segmentsById.set(r,i.segments);for(let r of this.byId.values()){let i=_5(r,this.accountId,e,o.get(r.device)),s=this.segmentsById.get(r.device);s&&i.capabilities.push({type:"segmentColor",config:{segments:s},state:{colors:null}});try{let a=await fA(this.fetch,this.cfg.apiKey,{sku:r.sku,device:r.device},this.rid());this.scenesById.set(r.device,a);for(let c of a)i.capabilities.push({type:"scene",instance:c.name,state:{}})}catch{}n.push(i)}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.byId.keys()],o=[];for(let r of n){let i=this.byId.get(r);if(i)try{let s=await op(this.fetch,this.cfg.apiKey,{sku:i.sku,device:i.device},this.rid());o.push({nativeId:r,patch:s,online:!0,ts:this.now()})}catch{o.push({nativeId:r,patch:[],online:!1,ts:this.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.byId.get(e);if(!s)throw new Error(`unknown govee cloud device ${e}`);let a={sku:s.sku,device:s.device};if(n==="scene"){if(o!=="activate")throw new Error(`unsupported govee scene command ${o}`);let d=(this.scenesById.get(e)??[]).find(f=>f.name===i?.instance);if(!d)throw new Error(`unknown govee scene "${i?.instance??""}" on ${e}`);return await mA(this.fetch,this.cfg.apiKey,a,d.value,this.rid()),{state:{lastActivated:this.now()}}}if(n==="segmentColor"){if(o!=="setSegmentColors")throw new Error(`unsupported govee segment command ${o}`);let d=(r&&typeof r=="object"?r.segments:void 0)??[],f=(Array.isArray(d)?d:[]).map(m=>m&&typeof m=="object"?m:{}).filter(m=>typeof m.index=="number").map(m=>({index:m.index,hue:typeof m.hue=="number"?m.hue:0,saturation:typeof m.saturation=="number"?m.saturation:0}));if(f.length===0)throw new Error("govee setSegmentColors needs at least one {index,hue,saturation}");for(let m of hA(f))await yA(this.fetch,this.cfg.apiKey,a,m.segments,m.rgb,this.rid());return{state:{colors:null}}}let c={};if(o==="toggle"||o==="adjustBrightness"){let d=await op(this.fetch,this.cfg.apiKey,a,this.rid()),f=d.find(g=>g.type==="power")?.state,m=d.find(g=>g.type==="brightness")?.state;typeof f?.on=="boolean"&&(c.currentOn=f.on),typeof m?.level=="number"&&(c.currentLevel=m.level)}let{capability:l,optimistic:u}=vA(n,o,r,c);if(await bA(this.fetch,this.cfg.apiKey,a,l,this.rid()),i?.readAfter){let d=(await op(this.fetch,this.cfg.apiKey,a,this.rid())).find(f=>f.type===n)?.state;return{state:d,verifiedState:d}}return{state:u.state}}subscribe(e,n){return()=>{}}async dispose(){}};var Pe=t=>typeof t=="number"&&Number.isFinite(t)?t:null,ke=t=>typeof t=="string"?t:null,ck=t=>typeof t=="boolean"?t:null,uc=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[],kA=t=>{let e=Number(t);return t.trim()!==""&&Number.isFinite(e)?e:null},pt=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e,_s=t=>Math.round(t*10)/10,uk=t=>t.split(".")[0]??"",lo=(t,e)=>typeof t=="number"&&(t&e)!==0,lk=t=>Math.min(12e3,Math.max(1e3,Math.round(t))),uo=t=>t==="on"?!0:t==="off"?!1:null,sp="unavailable",SA=(t,e,n)=>`${t} ${e} ${n??""}`,xA=4,I5=128,T5=2,E5=4,C5=2,R5=4,A5=2048;function _A(t){let e=uk(t.entity_id),n=t.attributes,o=t.state,r=[];switch(e){case"light":{r.push({type:"power",state:{on:uo(o)}});let i=uc(n.supported_color_modes);if(i.some(a=>a!=="onoff")){let a=Pe(n.brightness);r.push({type:"brightness",state:{level:a===null?null:eT(a)}})}if(i.includes("color_temp")){let a=Pe(n.color_temp_kelvin);r.push({type:"colorTemperature",config:{minKelvin:lk(Pe(n.min_color_temp_kelvin)??2e3),maxKelvin:lk(Pe(n.max_color_temp_kelvin)??6535)},state:{kelvin:a===null?null:lk(a)}})}let s=i.filter(a=>["hs","rgb","rgbw","rgbww","xy"].includes(a));if(s.length>0){let a=n.hs_color,c=Array.isArray(a)&&typeof a[0]=="number"?a[0]:null,l=Array.isArray(a)&&typeof a[1]=="number"?a[1]:null,u=[...new Set(s.map(d=>d.startsWith("rgb")?"rgb":d==="xy"?"xy":"hs"))];r.push({type:"color",config:{modes:u},state:{hue:c,saturation:l}})}break}case"switch":r.push({type:"power",state:{on:uo(o)}});break;case"input_boolean":r.push({type:"toggle",state:{on:uo(o)}});break;case"fan":r.push({type:"fan",config:{presets:uc(n.preset_modes),supportsOscillate:lo(n.supported_features,C5)},state:{on:uo(o),level:Pe(n.percentage),preset:ke(n.preset_mode),oscillating:ck(n.oscillating)}});break;case"lock":{let i={locked:"locked",unlocked:"unlocked",jammed:"jammed"};r.push({type:"lock",state:{state:i[o]??"unknown"}});break}case"cover":{let i=ke(n.device_class),s={awning:"awning",blind:"blind",curtain:"curtain",damper:"generic",door:"door",garage:"garage",gate:"door",shade:"shade",shutter:"blind",window:"window"},a={open:"open",closed:"closed",opening:"opening",closing:"closing"};r.push({type:"cover",config:{kind:(i?s[i]:void 0)??"generic",supportsPosition:lo(n.supported_features,xA),supportsTilt:lo(n.supported_features,I5)},state:{position:Pe(n.current_position),tilt:Pe(n.current_tilt_position),state:a[o]??"unknown"}});break}case"climate":{let i=ke(n.temperature_unit)==="\xB0F",s=d=>{let f=Pe(d);return f===null?null:i?_s(ts(f)):f},a={off:"off",heat:"heat",cool:"cool",heat_cool:"auto",auto:"auto",dry:"dry",fan_only:"fanOnly"},c=[...new Set(uc(n.hvac_modes).map(d=>a[d]).filter(d=>!!d))],l={idle:"idle",heating:"heating",cooling:"cooling",fan:"fan",drying:"idle",off:"idle"},u=ke(n.hvac_action);r.push({type:"thermostat",config:{modes:c.length?c:["off"],minC:s(n.min_temp)??7,maxC:s(n.max_temp)??35,supportsRange:lo(n.supported_features,T5)},state:{mode:a[o]??null,currentC:s(n.current_temperature),setpointC:s(n.temperature),heatC:s(n.target_temp_low),coolC:s(n.target_temp_high),action:u?l[u]??null:null}}),lo(n.supported_features,E5)&&r.push({type:"humidity",config:{settable:!0,minPct:Pe(n.min_humidity)??0,maxPct:Pe(n.max_humidity)??100},state:{currentPct:Pe(n.current_humidity),targetPct:Pe(n.humidity)}});break}case"humidifier":r.push({type:"power",state:{on:uo(o)}}),r.push({type:"humidity",config:{settable:!0,minPct:Pe(n.min_humidity)??0,maxPct:Pe(n.max_humidity)??100},state:{currentPct:Pe(n.current_humidity),targetPct:Pe(n.humidity)}});break;case"media_player":{let i={playing:"playing",paused:"paused",idle:"idle",buffering:"buffering",off:"stopped",standby:"stopped",on:"idle"},s=ke(n.media_title),a=ke(n.media_artist),c=ke(n.media_album_name),l=s||a||c?{...s?{title:s}:{},...a?{artist:a}:{},...c?{album:c}:{}}:null,u=ke(n.repeat);if(r.push({type:"mediaTransport",state:{state:i[o]??null,metadata:l,shuffle:ck(n.shuffle),repeat:u==="one"||u==="all"||u==="off"?u:null}}),lo(n.supported_features,R5)){let d=Pe(n.volume_level);r.push({type:"volume",state:{level:d===null?null:Math.round(d*100),muted:ck(n.is_volume_muted)}})}lo(n.supported_features,A5)&&r.push({type:"inputSource",config:{sources:uc(n.source_list)},state:{source:ke(n.source)}});break}case"sensor":{let i=ke(n.device_class),s=kA(o);if(i==="battery")r.push({type:"battery",state:{level:s}});else if(["power","energy","voltage","current","apparent_power","reactive_power"].includes(i??"")){let a=i==="energy"?"energy":i==="voltage"?"voltage":i==="current"?"current":"power";r.push({type:"energyMeter",state:{[a]:s}})}else{let a=P5(i,ke(n.unit_of_measurement),s);r.push({type:"sensor",config:{measurement:a.measurement,unit:en[a.measurement]},state:{value:a.value,ts:null}})}break}case"binary_sensor":{let i=ke(n.device_class);i==="connectivity"?r.push({type:"connectivity",config:{transport:"unknown"},state:{online:uo(o)}}):i==="battery"?r.push({type:"battery",state:{level:null,low:uo(o)}}):r.push({type:"binarySensor",config:{sensorType:D5(i)},state:{active:uo(o)}});break}case"vacuum":{let i={cleaning:"running",returning:"running",paused:"paused",docked:"stopped",idle:"stopped",error:"unknown"};r.push({type:"startStop",config:{supportsPause:!0},state:{state:i[o]??"unknown"}});let s=Pe(n.battery_level);s!==null&&r.push({type:"battery",state:{level:s}});break}case"lawn_mower":{let i={mowing:"running",returning:"running",paused:"paused",docked:"stopped",error:"unknown"};r.push({type:"startStop",config:{supportsPause:!0},state:{state:i[o]??"unknown"}});break}case"number":case"input_number":r.push({type:"range",config:{min:Pe(n.min)??0,max:Pe(n.max)??100,step:Pe(n.step)??void 0,unit:ke(n.unit_of_measurement)??void 0},state:{value:kA(o)}});break;case"select":case"input_select":r.push({type:"mode",config:{options:uc(n.options)},state:{value:o===sp?null:o}});break;case"valve":r.push({type:"cover",config:{kind:"valve",supportsPosition:lo(n.supported_features,xA),supportsTilt:!1},state:{position:Pe(n.current_valve_position),state:o==="open"?"open":o==="closed"?"closed":"unknown"}});break;case"water_heater":{let i=ke(n.temperature_unit)==="\xB0F",s=a=>{let c=Pe(a);return c===null?null:i?_s(ts(c)):c};r.push({type:"thermostat",config:{modes:["heat"],minC:s(n.min_temp)??30,maxC:s(n.max_temp)??80,supportsRange:!1},state:{mode:"heat",currentC:s(n.current_temperature),setpointC:s(n.temperature)}});break}case"scene":case"script":case"button":case"input_button":case"event":r.push({type:"scene",state:{}});break;case"siren":case"remote":r.push({type:"power",state:{on:o==="on"?!0:o==="off"?!1:null}});break;case"alarm_control_panel":r.push({type:"mode",config:{options:["disarmed","armed_home","armed_away","armed_night"]},state:{value:o===sp?null:o}});break;case"camera":r.push({type:"camera",config:{protocols:["hls","snapshot"]},state:{streaming:o==="streaming"||o==="recording"}});break;default:break}return r}function P5(t,e,n){let r=(t?{temperature:"temperature",humidity:"humidity",illuminance:"illuminance",pressure:"pressure",atmospheric_pressure:"pressure",carbon_dioxide:"co2",pm25:"pm25",pm10:"pm10",volatile_organic_compounds:"voc",aqi:"airQuality",sound_pressure:"noise",distance:"distance"}[t]:void 0)??"generic",i=r==="temperature"&&e==="\xB0F"&&n!==null?_s(ts(n)):n;return{measurement:r,value:i}}function D5(t){return(t?{motion:"motion",occupancy:"occupancy",presence:"presence",moving:"motion",door:"contact",window:"contact",opening:"contact",garage_door:"contact",moisture:"moisture",gas:"gas",smoke:"smoke",carbon_monoxide:"co",heat:"smoke",tamper:"tamper",vibration:"vibration",sound:"sound",safety:"generic"}[t]:void 0)??"generic"}function $5(t){let e=r=>t.caps.includes(r),n=r=>t.domains.includes(r),o=r=>t.deviceClasses.includes(r);return e("lock")?"lock":e("camera")?"camera":e("doorbell")?"doorbell":e("cover")?o("garage")?"garageDoor":n("valve")?"valve":"cover":e("thermostat")?n("water_heater")?"waterHeater":"thermostat":e("mediaTransport")?n("media_player")?"mediaPlayer":"speaker":e("fan")?"fan":e("humidity")&&n("humidifier")?"humidifier":n("vacuum")?"vacuum":e("brightness")||e("color")||e("colorTemperature")||n("light")?"light":n("switch")?o("outlet")?"plug":"switch":e("scene")?"scene":e("binarySensor")?"binarySensor":e("sensor")||e("energyMeter")||e("battery")?"sensor":e("toggle")||e("power")?"switch":"other"}function IA(t){let e=new Map(t.states.map(l=>[l.entity_id,l])),n=new Map(t.areas.map(l=>[l.area_id,l.name])),o=new Map(t.devices.map(l=>[l.id,l])),r={},i={},s={},a=new Map;for(let l of t.entities){let u=e.get(l.entity_id)??{entity_id:l.entity_id,state:"unknown",attributes:{}},d=uk(l.entity_id),f=l.device_id?o.get(l.device_id):void 0,m=f?f.id:l.entity_id,g=f?ke(f.name_by_user)??ke(f.name)??l.entity_id:ke(l.name)??ke(l.original_name)??ke(u.attributes.friendly_name)??l.entity_id,h=l.area_id??f?.area_id??null,y=a.get(m);y||(y={nativeId:m,name:g,area:h,online:!1,caps:[],domains:[],deviceClasses:[],device:f},a.set(m,y),i[m]=[]),h&&!y.area&&(y.area=h),u.state!==sp&&(y.online=!0),y.domains.push(d);let b=ke(u.attributes.device_class);b&&y.deviceClasses.push(b);for(let w of _A(u)){let x=SA(m,w.type,w.instance);r[x]||(r[x]={entityId:l.entity_id,domain:d}),y.caps.some(I=>I.type===w.type&&(I.instance??"")===(w.instance??""))||y.caps.push(w)}i[m]=[...i[m]??[],l.entity_id],s[l.entity_id]=m}return{candidates:[...a.values()].map(l=>({source:{provider:"homeassistant",providerAccountId:t.accountId,nativeId:l.nativeId,reachability:"local",online:l.online,credentialRef:null,lastSeen:null},fingerprints:O5(t.accountId,l),type:$5({domains:l.domains,deviceClasses:l.deviceClasses,caps:l.caps.map(u=>u.type)}),name:l.name,areaHint:l.area?{nativeId:l.area,name:n.get(l.area)??l.area}:null,manufacturer:l.device?.manufacturer??null,model:l.device?.model??null,capabilities:l.caps})),rooms:t.areas.map(l=>({nativeId:l.area_id,name:l.name})),index:{byCap:r,byDevice:i,entityToNative:s}}}function O5(t,e){let n=[];for(let o of e.device?.connections??[])Array.isArray(o)&&o[0]==="mac"&&typeof o[1]=="string"&&n.push(`mac:${o[1].toLowerCase()}`);return n.push(e.device?`ha-device:${t}:${e.nativeId}`:`ha-entity:${t}:${e.nativeId}`),n}function TA(t,e,n,o){return t.byCap[SA(e,n,o)]??null}var ne=(t,e,n={})=>({domain:t,service:e,data:n});function EA(t,e,n,o,r){let i=o??{};switch(e){case"power":if(n==="turnOn")return ne(t,"turn_on");if(n==="turnOff")return ne(t,"turn_off");if(n==="toggle")return ne(t,"toggle");break;case"toggle":if(n==="setToggle")return ne(t,i.on?"turn_on":"turn_off");break;case"brightness":if(n==="setBrightness")return ne("light","turn_on",{brightness_pct:pt(i.level,0)});if(n==="adjustBrightness")return ne("light","turn_on",{brightness_step_pct:pt(i.delta,0)});break;case"colorTemperature":if(n==="setColorTemperature")return ne("light","turn_on",{color_temp_kelvin:pt(i.kelvin,3e3)});break;case"color":if(n==="setColor")return ne("light","turn_on",{hs_color:[pt(i.hue,0),pt(i.saturation,0)]});break;case"lock":if(n==="lock")return ne("lock","lock");if(n==="unlock")return ne("lock","unlock");break;case"cover":if(n==="open")return ne(t==="valve"?"valve":"cover",t==="valve"?"open_valve":"open_cover");if(n==="close")return ne(t==="valve"?"valve":"cover",t==="valve"?"close_valve":"close_cover");if(n==="stop")return ne(t==="valve"?"valve":"cover",t==="valve"?"stop_valve":"stop_cover");if(n==="setPosition")return ne(t==="valve"?"valve":"cover",t==="valve"?"set_valve_position":"set_cover_position",{position:pt(i.position,0)});if(n==="setTilt")return ne("cover","set_cover_tilt_position",{tilt_position:pt(i.tilt,0)});break;case"thermostat":if(n==="setSetpoint"){let s=pt(i.celsius,20);return ne(t==="water_heater"?"water_heater":"climate","set_temperature",{temperature:r.imperial?_s(Zu(s)):s})}if(n==="setThermostatMode")return ne("climate","set_hvac_mode",{hvac_mode:L5(ke(i.mode))});if(n==="setRange"){let s=pt(i.heatCelsius,18),a=pt(i.coolCelsius,24);return ne("climate","set_temperature",{target_temp_low:r.imperial?_s(Zu(s)):s,target_temp_high:r.imperial?_s(Zu(a)):a})}break;case"humidity":if(n==="setHumidity")return ne("humidifier","set_humidity",{humidity:pt(i.percent,50)});break;case"fan":if(n==="turnOn")return ne("fan","turn_on");if(n==="turnOff")return ne("fan","turn_off");if(n==="setFanSpeed")return ne("fan","set_percentage",{percentage:pt(i.level,0)});if(n==="setFanPreset")return ne("fan","set_preset_mode",{preset_mode:ke(i.preset)??""});if(n==="setOscillate")return ne("fan","oscillate",{oscillating:!!i.oscillating});break;case"mode":if(n==="setMode"){if(t==="alarm_control_panel"){let s=ke(i.value);return ne("alarm_control_panel",s==="disarmed"?"alarm_disarm":s==="armed_home"?"alarm_arm_home":s==="armed_night"?"alarm_arm_night":"alarm_arm_away")}return ne(t==="input_select"?"input_select":"select","select_option",{option:ke(i.value)??""})}break;case"range":if(n==="setValue")return ne(t==="input_number"?"input_number":"number","set_value",{value:pt(i.value,0)});break;case"mediaTransport":{let a={play:{service:"media_play"},pause:{service:"media_pause"},stop:{service:"media_stop"},next:{service:"media_next_track"},previous:{service:"media_previous_track"},seek:{service:"media_seek",data:{seek_position:pt(i.positionSec,0)}},setShuffle:{service:"shuffle_set",data:{shuffle:!!i.on}},setRepeat:{service:"repeat_set",data:{repeat:ke(i.mode)??"off"}}}[n];if(a)return ne("media_player",a.service,a.data??{});break}case"volume":if(n==="setVolume")return ne("media_player","volume_set",{volume_level:pt(i.level,0)/100});if(n==="adjustVolume")return ne("media_player",pt(i.delta,0)>=0?"volume_up":"volume_down");if(n==="setMute")return ne("media_player","volume_mute",{is_volume_muted:!!i.muted});break;case"inputSource":if(n==="selectInput")return ne("media_player","select_source",{source:ke(i.source)??""});break;case"startStop":{let s=t==="lawn_mower"?"lawn_mower":"vacuum";if(n==="start")return ne(s,s==="vacuum"?"start":"start_mowing");if(n==="stop")return ne(s,s==="vacuum"?"stop":"dock");if(n==="pause")return ne(s,"pause");if(n==="resume")return ne(s,s==="vacuum"?"start":"start_mowing");break}case"scene":if(n==="activate")return t==="button"||t==="input_button"?ne(t,"press"):ne(t==="script"?"script":"scene","turn_on");break;default:break}throw new Error(`no Home Assistant service for ${e}.${n} on ${t}`)}function L5(t){return(t?{off:"off",heat:"heat",cool:"cool",auto:"heat_cool",eco:"auto",fanOnly:"fan_only",dry:"dry"}[t]:void 0)??"auto"}function ap(t){return _A(t).map(e=>({type:e.type,...e.instance?{instance:e.instance}:{},state:e.state}))}function CA(t,e){let n=uk(e.entity_id);if(!(n==="button"||n==="input_button"||n==="event")||e.state===sp||e.state==="unknown"||t&&t.state===e.state)return null;let r=ke(e.attributes.device_class)==="doorbell";return{capability:r?"doorbell":"scene",event:"press"}}var pp=class{constructor(e,n,o=vH){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="homeassistant";reachability="local";client=null;index={byCap:{},byDevice:{},entityToNative:{}};cache=new Map;imperial=!1;unsub=null;disposed=!1;onState=null;onEdge=null;async init(e){let n=await e.localSecrets.read(this.accountId);if(!n)throw new Error(`no Home Assistant token stored for ${this.accountId} \u2014 run \`acbridge link home-assistant\``);this.client=await this.clientFactory({baseUrl:this.cfg.baseUrl,token:n}),this.imperial=this.cfg.unitSystem?this.cfg.unitSystem==="imperial":(await this.client.config()).imperial}async link(e,n){return e.kind!=="token"?{ok:!1,error:"Home Assistant links with a long-lived access token.",retryable:!1}:(await n.localSecrets.write(this.accountId,e.token),{ok:!0,accountId:this.accountId})}async unlink(e){await e.localSecrets.write(this.accountId,"")}async discover(){let e=this.need(),[{devices:n,entities:o,areas:r},i]=await Promise.all([e.registries(),e.states()]);this.ingest(i);let s={accountId:this.accountId,devices:n,entities:o,areas:r,states:i},{candidates:a,rooms:c,index:l}=IA(s);return this.index=l,{devices:a,rooms:c}}async getState(e){let o=await this.need().states();this.ingest(o);let r=e?new Set(this.index.byDevice[e]??[]):null,i=new Map;for(let s of o){if(r&&!r.has(s.entity_id))continue;let a=this.index.entityToNative[s.entity_id];if(!a)continue;let c=i.get(a)??{nativeId:a,patch:[],online:!1,ts:0};c.patch.push(...ap(s)),s.state!=="unavailable"&&(c.online=!0),i.set(a,c)}return[...i.values()]}async sendCommand(e,n,o,r,i){let s=this.need(),a=TA(this.index,e,n,i?.instance);if(!a)throw new Error(`no Home Assistant entity backs ${n} on ${e}`);let c=EA(a.domain,n,o,r,{imperial:this.imperial}),l=await s.callService(c.domain,c.service,c.data,a.entityId);if(i?.readAfter){let u=(await s.states()).find(d=>d.entity_id===a.entityId);if(u){this.cache.set(u.entity_id,u);let d=ap(u).find(f=>f.type===n)?.state;return{state:d,verifiedState:d,result:l}}}return{result:l}}subscribe(e,n){this.onState=e,this.onEdge=n;let o=this.client;return o&&o.subscribe(r=>this.applyLive(r)).then(r=>{this.disposed?r():this.unsub=r}).catch(()=>{}),()=>{this.unsub?.(),this.unsub=null,this.onState=null,this.onEdge=null}}async dispose(){this.disposed=!0,this.unsub?.(),this.unsub=null,await this.client?.close(),this.client=null}applyLive(e){for(let n of e){let o=this.cache.get(n.entity_id);this.cache.set(n.entity_id,n);let r=this.index.entityToNative[n.entity_id];if(!r)continue;let i=CA(o,n);i&&this.onEdge?.({nativeId:r,capability:i.capability,event:i.event,ts:0}),this.onState?.({nativeId:r,patch:ap(n),online:n.state!=="unavailable",ts:0})}}ingest(e){for(let n of e)this.cache.set(n.entity_id,n)}need(){if(!this.client)throw new Error("Home Assistant adapter not initialized");return this.client}},hH={1:"cannot connect \u2014 is the URL reachable from this machine? (.local names don't resolve under WSL; use the IP)",2:"invalid auth \u2014 Home Assistant rejected the token",3:"connection lost during setup",4:"no host in the URL",5:"refused https\u2192http downgrade"};function yH(t){try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.refresh_token=="string"&&typeof e.access_token=="string")return{kind:"oauth",data:e}}catch{}return{kind:"llat",token:t}}var vH=async({baseUrl:t,token:e})=>{let n=await Promise.resolve().then(()=>(aP(),sP)),o=yH(e),r=o.kind==="oauth"?await n.getAuth({hassUrl:o.data.hassUrl||t,...o.data.clientId?{clientId:o.data.clientId}:{},loadTokens:async()=>o.data}):n.createLongLivedTokenAuth(t,e),i=await n.createConnection({auth:r}).catch(c=>{throw new Error(`Home Assistant connect to ${t} failed: ${typeof c=="number"?hH[c]??`code ${c}`:String(c)}`)}),s=c=>i.sendMessagePromise(c),a=c=>({entity_id:c.entity_id,state:c.state,attributes:c.attributes??{}});return{async registries(){let[c,l,u]=await Promise.all([s({type:"config/device_registry/list"}),s({type:"config/entity_registry/list"}),s({type:"config/area_registry/list"})]);return{devices:c,entities:l,areas:u}},async states(){return(await s({type:"get_states"})).map(a)},async config(){return{imperial:((await s({type:"get_config"})).unit_system?.temperature??"").includes("F")}},async callService(c,l,u,d){return s({type:"call_service",domain:c,service:l,service_data:u,target:{entity_id:d}})},async subscribe(c){let l=d=>c(Object.values(d).map(a)),u=n.subscribeEntities(i,l);return()=>u()},async close(){i.close()}}};var Dn=t=>typeof t=="number"&&Number.isFinite(t)?t:null,sn=t=>typeof t=="string"?t:null,yc=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e,xk=t=>Math.min(12e3,Math.max(1e3,Math.round(t))),bH=t=>Math.min(500,Math.max(153,Math.round(t))),fp=(t,e,n)=>`${t} ${e} ${n??""}`,wH=t=>Math.round(10**((t-1)/1e4)),kH={A:{r:{x:.704,y:.296},g:{x:.2151,y:.7106},b:{x:.138,y:.08}},B:{r:{x:.675,y:.322},g:{x:.409,y:.518},b:{x:.167,y:.04}},C:{r:{x:.692,y:.308},g:{x:.17,y:.7},b:{x:.153,y:.048}}},mp="C",cP=t=>Math.round(t*1e4)/1e4,Sk=t=>t>.04045?((t+.055)/1.055)**2.4:t/12.92,_k=t=>t<=.0031308?12.92*t:1.055*t**(1/2.4)-.055;function lP(t,e){let{r:n,g:o,b:r}=kH[e],i={x:o.x-n.x,y:o.y-n.y},s={x:r.x-n.x,y:r.y-n.y},a={x:t.x-n.x,y:t.y-n.y},c=i.x*s.y-i.y*s.x,l=c===0?-1:(a.x*s.y-a.y*s.x)/c,u=c===0?-1:(i.x*a.y-i.y*a.x)/c;if(l>=0&&u>=0&&l+u<=1)return t;let d=(w,x)=>{let I={x:t.x-w.x,y:t.y-w.y},E={x:x.x-w.x,y:x.y-w.y},C=E.x*E.x+E.y*E.y,F=C===0?0:Math.max(0,Math.min(1,(I.x*E.x+I.y*E.y)/C));return{x:w.x+E.x*F,y:w.y+E.y*F}},f=(w,x)=>Math.hypot(w.x-x.x,w.y-x.y),m=d(n,o),g=d(o,r),h=d(r,n),y=m,b=f(t,m);return f(t,g)<b&&(y=g,b=f(t,g)),f(t,h)<b&&(y=h),y}function xH(t,e,n){let o=e/100,r=n/100,i=r*o,s=(t%360+360)%360/60,a=i*(1-Math.abs(s%2-1)),c=0,l=0,u=0;s<1?(c=i,l=a):s<2?(c=a,l=i):s<3?(l=i,u=a):s<4?(l=a,u=i):s<5?(c=a,u=i):(c=i,u=a);let d=r-i;return{r:c+d,g:l+d,b:u+d}}function SH(t,e,n){let o=Math.max(t,e,n),r=Math.min(t,e,n),i=o-r,s=0;return i!==0&&(o===t?s=((e-n)/i%6+6)%6:o===e?s=(n-t)/i+2:s=(t-e)/i+4,s*=60),{h:s,s:o===0?0:i/o*100,v:o*100}}function Tk(t,e,n=mp){let{r:o,g:r,b:i}=xH(t,e,100),s=Sk(o),a=Sk(r),c=Sk(i),l=s*.664511+a*.154324+c*.162028,u=s*.283881+a*.668433+c*.047685,d=s*88e-6+a*.07231+c*.986039,f=l+u+d,m=f===0?{x:0,y:0}:{x:l/f,y:u/f},g=lP(m,n);return{x:cP(g.x),y:cP(g.y)}}function gp(t,e,n=mp){let o=lP({x:t,y:e},n),r=1,i=o.y===0?0:r/o.y*o.x,s=o.y===0?0:r/o.y*(1-o.x-o.y),a=_k(i*1.656492-r*.354851-s*.255038),c=_k(-i*.707196+r*1.655397+s*.036152),l=_k(i*.051713-r*.121364+s*1.01153),u=Math.max(a,c,l,1);a=Math.max(0,a/u),c=Math.max(0,c/u),l=Math.max(0,l/u);let d=SH(a,c,l);return{hue:Math.round((d.h%360+360)%360),saturation:Math.round(d.s)}}var uP=t=>{let e=sn(t.color?.gamut_type);return e==="A"||e==="B"||e==="C"?e:mp};function Ik(t){let e=[];switch(t.type){case"light":case"grouped_light":{if(t.on&&e.push({type:"power",state:{on:typeof t.on.on=="boolean"?t.on.on:null}}),t.dimming){let n=Dn(t.dimming.brightness);e.push({type:"brightness",state:{level:n===null?null:Math.round(n)}})}if(t.color_temperature){let n=Dn(t.color_temperature.mirek),o=t.color_temperature.mirek_schema,r=Dn(o?.mirek_minimum)??153,i=Dn(o?.mirek_maximum)??500;e.push({type:"colorTemperature",config:{minKelvin:xk(Wu(i)),maxKelvin:xk(Wu(r))},state:{kelvin:n===null?null:xk(Wu(n))}})}if(t.color){let n=t.color.xy,o=n&&Dn(n.x)!==null&&Dn(n.y)!==null?gp(n.x,n.y,uP(t)):null;e.push({type:"color",config:{modes:["hs","xy"]},state:{hue:o?o.hue:null,saturation:o?o.saturation:null}})}break}case"motion":{let n=t.motion,o=n?typeof n.motion=="boolean"?n.motion:typeof n.motion_report?.motion=="boolean"?n.motion_report.motion:null:null;e.push({type:"binarySensor",instance:"motion",config:{sensorType:"motion"},state:{active:o}});break}case"temperature":{let n=t.temperature,o=n?Dn(n.temperature)??Dn(n.temperature_report?.temperature):null;e.push({type:"sensor",instance:"temperature",config:{measurement:"temperature",unit:en.temperature},state:{value:o===null?null:Math.round(o*10)/10,ts:null}});break}case"light_level":{let n=t.light,o=n?Dn(n.light_level)??Dn(n.light_level_report?.light_level):null,r="illuminance";e.push({type:"sensor",instance:"illuminance",config:{measurement:r,unit:en[r]},state:{value:o===null?null:wH(o),ts:null}});break}case"device_power":{let n=t.power_state;e.push({type:"battery",state:{level:n?Dn(n.battery_level):null,low:n?n.battery_state==="low"||n.battery_state==="critical":null}});break}default:break}return e}var _H=/bulb|lamp|light|strip|spot|candle|lantern|ceiling|pendant|wall_|floor_/;function IH(t,e){if(e.isGroup)return"group";if(e.isBridge)return"bridge";let n=r=>t.includes(r);return n("brightness")||n("color")||n("colorTemperature")?"light":n("power")?_H.test(e.archetype??"")?"light":"plug":e.hasButton?"remote":n("binarySensor")?"binarySensor":n("sensor")||n("battery")?"sensor":"other"}function dP(t){let e=new Map(t.resources.map(f=>[f.id,f])),n=t.resources.filter(f=>f.type==="room"),o=t.resources.filter(f=>f.type==="zone"),r=new Map;for(let f of n){let m=sn(f.metadata?.name)??f.id;for(let g of f.children??[])g.rtype==="device"&&r.set(g.rid,{id:f.id,name:m})}let i={},s={},a={},c=[];for(let f of t.resources){if(f.type!=="device")continue;let m=f.id,g=[],h=[],y=null,b=!0,w=!1,x=!1;for(let E of f.services??[]){let C=e.get(E.rid);if(!C)continue;if(a[C.id]=m,h.push(C.id),C.type==="zigbee_connectivity"){y=sn(C.mac_address),C.status&&(b=C.status==="connected");continue}if(C.type==="button"){w=!0;continue}C.type==="bridge"&&(x=!0);let F=C.type==="light"?uP(C):void 0;for(let U of Ik(C)){let W=fp(m,U.type,U.instance);i[W]||(i[W]={rid:C.id,rtype:C.type,...F?{gamut:F}:{}}),g.some(N=>N.type===U.type&&(N.instance??"")===(U.instance??""))||g.push(U)}}s[m]=h;let I=r.get(m)??null;c.push({source:{provider:"hue",providerAccountId:t.accountId,nativeId:m,reachability:"local",online:b,credentialRef:null,lastSeen:null},fingerprints:TH(t.bridgeId,m,y),type:IH(g.map(E=>E.type),{hasButton:w,isGroup:!1,archetype:sn(f.metadata?.archetype),isBridge:x}),name:sn(f.metadata?.name)??m,areaHint:I?{nativeId:I.id,name:I.name}:null,manufacturer:sn(f.product_data?.manufacturer_name),model:sn(f.product_data?.model_id),capabilities:g})}let l=new Map;for(let f of[...n,...o]){let m=(f.services??[]).find(x=>x.rtype==="grouped_light");if(!m)continue;let g=e.get(m.rid);if(!g)continue;let h=g.id,y=Ik(g);for(let x of y)i[fp(h,x.type,x.instance)]={rid:g.id,rtype:"grouped_light"};a[g.id]=h,s[h]=[g.id];let b=[...new Set((f.children??[]).map(x=>x.rtype==="device"?x.rid:e.get(x.rid)?.owner?.rid).filter(x=>typeof x=="string"))];l.set(f.id,b);let w=sn(f.metadata?.name)??h;c.push({source:{provider:"hue",providerAccountId:t.accountId,nativeId:h,reachability:"local",online:!0,credentialRef:null,lastSeen:null},fingerprints:[`hue:${t.bridgeId}:group:${h}`],type:"group",name:w,areaHint:{nativeId:f.id,name:w},capabilities:y,memberNativeIds:b})}let u=new Map(c.map(f=>[f.source.nativeId,f]));for(let f of t.resources){if(f.type!=="scene")continue;let m=f.group?.rid;if(!m)continue;let g=sn(f.metadata?.name)??f.id,h=(l.get(m)??[]).filter(y=>u.get(y)?.type==="light");for(let y of h){let b=u.get(y);b&&(b.capabilities.some(w=>w.type==="scene"&&(w.instance??"")===g)||b.capabilities.push({type:"scene",instance:g,state:{}}),i[fp(y,"scene",g)]={rid:f.id,rtype:"scene"},b.memberNativeIds=[...new Set([...b.memberNativeIds??[],...h])])}}let d=[...n,...o].map(f=>({nativeId:f.id,name:sn(f.metadata?.name)??f.id}));return{candidates:c,rooms:d,index:{byCap:i,byDevice:s,ridToNative:a}}}function TH(t,e,n){let o=[];return n&&o.push(`mac:${n.toLowerCase()}`),o.push(`hue:${t}:${e}`),o}function pP(t,e,n,o){return t.byCap[fp(e,n,o)]??null}function fP(t,e,n,o,r){let i=o??{},s=a=>({rtype:t.rtype,rid:t.rid,body:a});switch(e){case"power":if(n==="turnOn")return s({on:{on:!0}});if(n==="turnOff")return s({on:{on:!1}});if(n==="toggle")return s({on:{on:!r?.currentOn}});break;case"brightness":if(n==="setBrightness")return s({dimming:{brightness:Math.max(0,Math.min(100,yc(i.level,0)))}});if(n==="adjustBrightness"){let a=yc(i.delta,0);return s({dimming_delta:{action:a>=0?"up":"down",brightness_delta:Math.abs(a)}})}break;case"colorTemperature":if(n==="setColorTemperature")return s({color_temperature:{mirek:bH(QI(yc(i.kelvin,3e3)))}});break;case"color":if(n==="setColor")return s({color:{xy:Tk(yc(i.hue,0),yc(i.saturation,0),t.gamut??mp)}});break;case"scene":if(n==="activate")return s({recall:{action:"active"}});break;default:break}throw new Error(`no Hue CLIP v2 service for ${e}.${n}`)}function hp(t){return Ik(t).map(e=>({type:e.type,...e.instance?{instance:e.instance}:{},state:e.state}))}function mP(t){if(t.type!=="button"||!t.button)return null;let e=sn(t.button.last_event)??sn(t.button.button_report?.event);return e?{capability:"scene",event:e}:null}function EH(t){try{let e=JSON.parse(t);if(e&&typeof e.appkey=="string")return e.appkey}catch{}return t.trim()?t.trim():null}var yp=class{constructor(e,n,o=RH){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="hue";reachability="local";client=null;index={byCap:{},byDevice:{},ridToNative:{}};cache=new Map;unsub=null;disposed=!1;onState=null;onEdge=null;async init(e){let n=await e.localSecrets.read(this.accountId),o=n?EH(n):null;if(!o)throw new Error(`no Hue app-key stored for ${this.accountId} \u2014 pair the bridge (app \u2192 Integrations, or \`acbridge link hue\`)`);this.client=await this.clientFactory({host:this.cfg.host,bridgeId:this.cfg.bridgeId,appkey:o})}async link(e,n){if(e.kind==="appKey"){let r=e.appkey.trim();if(!r)return{ok:!1,error:"Provide a Hue application key, or press the bridge link button to mint one.",retryable:!1};let i=await this.clientFactory({host:this.cfg.host,bridgeId:this.cfg.bridgeId,appkey:r});try{await i.resources()}catch{return await i.close().catch(()=>{}),{ok:!1,error:"That Hue application key was rejected by the bridge \u2014 check the key, or press the link button to mint a new one.",retryable:!0}}return await n.localSecrets.write(this.accountId,JSON.stringify({appkey:r})),this.client=i,{ok:!0,accountId:this.accountId}}if(e.kind!=="button")return{ok:!1,error:"Philips Hue pairs by pressing the bridge link button.",retryable:!1};let o=this.client??await this.clientFactory({host:this.cfg.host,bridgeId:this.cfg.bridgeId,appkey:null});try{let{appkey:r,clientkey:i}=await o.pair();return await n.localSecrets.write(this.accountId,JSON.stringify({appkey:r,...i?{clientkey:i}:{}})),this.client=await this.clientFactory({host:this.cfg.host,bridgeId:this.cfg.bridgeId,appkey:r}),{ok:!0,accountId:this.accountId}}catch(r){return{ok:!1,error:r instanceof Error?r.message:"pairing failed \u2014 press the link button and retry",retryable:!0}}}async unlink(e){await e.localSecrets.write(this.accountId,"")}async discover(){let n=await this.need().resources();this.ingest(n);let{candidates:o,rooms:r,index:i}=dP({accountId:this.accountId,bridgeId:this.cfg.bridgeId,resources:n});return this.index=i,{devices:o,rooms:r}}async getState(e){let o=await this.need().resources();this.ingest(o);let r=e?new Set(this.index.byDevice[e]??[]):null,i=new Map;for(let s of o){if(r&&!r.has(s.id))continue;let a=this.index.ridToNative[s.id];if(!a)continue;let c=i.get(a)??{nativeId:a,patch:[],online:!0,ts:0};s.type==="zigbee_connectivity"&&typeof s.status=="string"&&(c.online=s.status==="connected"),c.patch.push(...hp(s)),i.set(a,c)}return[...i.values()]}async sendCommand(e,n,o,r,i){let s=this.need(),a=pP(this.index,e,n,i?.instance);if(!a)throw new Error(`no Hue resource backs ${n} on ${e}`);let c=fP(a,n,o,r,{currentOn:this.currentOn(a.rid)}),l=await s.putResource(c.rtype,c.rid,c.body);if(i?.readAfter){let u=(await s.resources()).find(d=>d.id===a.rid);if(u){this.cache.set(u.id,u);let d=hp(u).find(f=>f.type===n)?.state;return{state:d,verifiedState:d,result:l}}}return{result:l}}subscribe(e,n){this.onState=e,this.onEdge=n;let o=this.client;return o&&o.subscribe(r=>this.applyLive(r)).then(r=>{this.disposed?r():this.unsub=r}).catch(()=>{}),()=>{this.unsub?.(),this.unsub=null,this.onState=null,this.onEdge=null}}async dispose(){this.disposed=!0,this.unsub?.(),this.unsub=null,await this.client?.close(),this.client=null}applyLive(e){for(let n of e){let o=this.cache.get(n.id),r=o?{...o,...n}:n;o?.color&&n.color&&(r.color={...o.color,...n.color}),this.cache.set(n.id,r);let i=this.index.ridToNative[n.id];if(!i)continue;let s=mP(n);s&&this.onEdge?.({nativeId:i,capability:s.capability,event:s.event,ts:0});let a=hp(r);a.length>0&&this.onState?.({nativeId:i,patch:a,online:!0,ts:0})}}ingest(e){for(let n of e)this.cache.set(n.id,n)}currentOn(e){let n=this.cache.get(e);return typeof n?.on?.on=="boolean"?n.on.on:void 0}need(){if(!this.client)throw new Error("Hue adapter not initialized");return this.client}},CH="acbridge#hub",Ek=t=>{let e=t?.subject?.CN;return typeof e=="string"?e:Array.isArray(e)?e[0]:void 0},gP=(t,e)=>typeof t=="string"&&t.toLowerCase()===e.toLowerCase(),RH=async({host:t,bridgeId:e,appkey:n})=>{let o=await import("node:https"),r=await import("node:fs"),i=process.env.BRIDGE_HUE_CACERT,s=i?r.readFileSync(i):void 0,a=new o.Agent({keepAlive:!0,...s?{ca:s,rejectUnauthorized:!0,checkServerIdentity:(l,u)=>gP(Ek(u),e)?void 0:new Error(`Hue cert CN ${Ek(u)??"(none)"} != bridgeId ${e}`)}:{rejectUnauthorized:!1}}),c=({method:l,path:u,headers:d,body:f})=>new Promise((m,g)=>{let h=f===void 0?void 0:JSON.stringify(f),y=o.request({host:t,port:443,method:l,path:u,agent:a,headers:{"content-type":"application/json",...n?{"hue-application-key":n}:{},...d}},b=>{if(!s){let x=Ek(b.socket.getPeerCertificate?.());if(!gP(x,e)){b.destroy(),g(new Error(`Hue cert CN ${x??"(none)"} != bridgeId ${e}`));return}}let w="";b.setEncoding("utf8"),b.on("data",x=>w+=x),b.on("end",()=>{try{m(w?JSON.parse(w):{})}catch(x){g(x instanceof Error?x:new Error(String(x)))}})});y.on("error",g),h&&y.write(h),y.end()});return{async pair(){let l=await c({method:"POST",path:"/api",body:{devicetype:CH,generateclientkey:!0}}),u=l.find(f=>f.success)?.success;if(u)return{appkey:u.username,clientkey:u.clientkey};let d=l.find(f=>f.error)?.error;throw new Error(d?.type===101?"press the link button on the Hue Bridge, then retry":d?.description??"Hue pairing failed")},async resources(){return(await c({method:"GET",path:"/clip/v2/resource"})).data??[]},async putResource(l,u,d){return c({method:"PUT",path:`/clip/v2/resource/${l}/${u}`,body:d})},async subscribe(l){let u=o.request({host:t,port:443,method:"GET",path:"/eventstream/clip/v2",agent:a,headers:{accept:"text/event-stream",...n?{"hue-application-key":n}:{}}});return u.on("response",d=>{let f="";d.setEncoding("utf8"),d.on("data",m=>{f+=m;let g;for(;(g=f.indexOf(`
174
+
175
+ `))!==-1;){let h=f.slice(0,g);f=f.slice(g+2);let y=h.split(`
176
+ `).filter(b=>b.startsWith("data:")).map(b=>b.slice(5).trim()).join("");if(y)try{let w=JSON.parse(y).flatMap(x=>x.data??[]);w.length&&l(w)}catch{}}})}),u.on("error",()=>{}),u.end(),()=>u.destroy()},async close(){a.destroy()}}},Yne=15*6e4;function De(t,e){return`${t}#${e}`}function kt(t){let e=t.indexOf("#");return e<=0||e>=t.length-1?null:{parentNativeId:t.slice(0,e),childKey:t.slice(e+1)}}function po(t){return kt(t)!==null}function Ur(t,e,n){return`fallback:${t}:${e}:${n}`}var bp={minKelvin:2500,maxKelvin:9e3},xe=t=>typeof t=="number"&&Number.isFinite(t)?t:null,tt=t=>typeof t=="string"&&t?t:void 0,Zt=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;function Qn(t){let e=Zt(Zt(Zt(t)?.system)?.get_sysinfo);if(!e)throw new Error("kasa reply has no system.get_sysinfo");let n=xe(e.err_code);if(n!==null&&n!==0)throw new Error(`kasa get_sysinfo err_code ${n}`);return e}function Ck(t){return(tt(t.mic_type)??tt(t.type)??"").includes("BULB")?"bulb":xe(t.brightness)!==null?"dimmer":"plug"}function AH(t,e){return e==="bulb"?"light":e==="dimmer"?"dimmer":/^(hs2|ks2|es2)/i.test(tt(t.model)??"")?"switch":"plug"}function hP(t,e){if(e==="bulb"){let o=Zt(t.light_state)??{},r=xe(o.on_off)===null?null:xe(o.on_off)===1,i=r?o:Zt(o.dft_on_state)??o,s=xe(i.color_temp);return{on:r,level:xe(i.brightness),kelvin:s!==null&&s>0?s:null,hue:xe(i.hue),saturation:xe(i.saturation)}}let n=xe(t.relay_state);return{on:n===null?null:n===1,level:xe(t.brightness),kelvin:null,hue:null,saturation:null}}var PH=t=>(tt(t.feature)??"").includes("ENE"),Ts=(t,e)=>xe(t[e])===1;function DH(t,e){let n=hP(t,e),o=[{type:"power",state:{on:n.on}}];return e==="bulb"?(Ts(t,"is_dimmable")&&o.push({type:"brightness",state:{level:n.level}}),Ts(t,"is_variable_color_temp")&&o.push({type:"colorTemperature",config:bp,state:{kelvin:n.kelvin}}),Ts(t,"is_color")&&o.push({type:"color",config:{modes:["hs"]},state:{hue:n.hue,saturation:n.saturation}})):e==="dimmer"&&o.push({type:"brightness",state:{level:n.level}}),PH(t)&&o.push({type:"energyMeter",state:{power:null,energy:null,voltage:null,current:null}}),o}function yP(t,e){let n=hP(t,e),o=[{type:"power",state:{on:n.on}}];return(e==="bulb"&&Ts(t,"is_dimmable")||e==="dimmer")&&o.push({type:"brightness",state:{level:n.level}}),e==="bulb"&&Ts(t,"is_variable_color_temp")&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),e==="bulb"&&Ts(t,"is_color")&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),o}function vP(t,e){let n=Ck(t),o=T(e.mac);return{source:{provider:"kasa",providerAccountId:e.accountId,nativeId:o,nativeType:tt(t.mic_type)??tt(t.type),reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${o}`],type:AH(t,n),name:e.nameOverride??tt(t.alias)??tt(t.model)??"Kasa device",manufacturer:"TP-Link Kasa",model:tt(t.model)??null,capabilities:DH(t,n)}}function bP(t,e){let n=t.model??"",o=/^(kl|lb)/i.test(n)?"light":/^(hs2|ks2|es2)/i.test(n)?"switch":"plug";return{source:{provider:"kasa",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:o,name:t.name??t.model??"Kasa device",manufacturer:"TP-Link Kasa",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function bc(t){let e=t.children;if(!Array.isArray(e)||e.length===0)return null;let n=tt(t.deviceId)??"";return e.map((o,r)=>{let i=Zt(o)??{},s=tt(i.id)??"",a=s.length>2?s:`${n}${String(r).padStart(2,"0")}`,c=xe(i.state);return{childId:a,alias:tt(i.alias)??`Outlet ${r+1}`,on:c===null?null:c===1}})}function wP(t,e,n){let o=T(n.mac),r={source:{provider:"kasa",providerAccountId:n.accountId,nativeId:o,nativeType:tt(t.mic_type)??tt(t.type),reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:"plug",name:n.nameOverride??tt(t.alias)??tt(t.model)??"Kasa power strip",manufacturer:"TP-Link Kasa",model:tt(t.model)??null,capabilities:[]},i=e.map(s=>{let a=De(o,s.childId);return{source:{provider:"kasa",providerAccountId:n.accountId,nativeId:a,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[Ur("kasa",n.accountId,a)],type:"plug",name:s.alias,manufacturer:"TP-Link Kasa",model:tt(t.model)??null,parentNativeId:o,capabilities:[{type:"power",state:{on:s.on}}]}});return[r,...i]}function kP(t,e){let n=bc(t);if(!n)return[];let o=T(e);return n.map(r=>({nativeId:De(o,r.childId),patch:[{type:"power",state:{on:r.on}}]}))}function Rk(t,e){return bc(t)?.find(n=>n.childId===e)?.on??null}var xP=t=>t==="bulb"?"smartlife.iot.common.emeter":"emeter",$H="smartlife.iot.smartbulb.lightingservice";function Ak(t,e){return JSON.stringify({system:{get_sysinfo:{}},...e?{[xP(t)]:{get_realtime:{}}}:{}})}function OH(t){let e=xe(t.power_mw),n=xe(t.voltage_mv),o=xe(t.current_ma),r=xe(t.total_wh);return{power:e!==null?e/1e3:xe(t.power),voltage:n!==null?n/1e3:xe(t.voltage),current:o!==null?o/1e3:xe(t.current),energy:r!==null?r/1e3:xe(t.total)}}function SP(t,e,n){let o=yP(Qn(n),t);if(e){let r=Zt(Zt(Zt(n)?.[xP(t)])?.get_realtime),i=r?xe(r.err_code):null;r&&(i===null||i===0)&&o.push({type:"energyMeter",state:OH(r)})}return o}function _P(t){let e=Zt(t)??{};for(let[n,o]of Object.entries(e))for(let[r,i]of Object.entries(Zt(o)??{})){let s=xe(Zt(i)?.err_code);if(s!==null&&s!==0)throw new Error(`kasa err_code ${s} (${n}.${r})`)}}var vc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t))),vp=t=>JSON.stringify({[$H]:{transition_light_state:{transition_period:0,...t}}}),LH=(t,e)=>JSON.stringify({...e?{context:{child_ids:[e]}}:{},system:{set_relay_state:{state:t?1:0}}});function IP(t,e,n,o,r){let i=Zt(o)??{},s=()=>{throw new Error(`kasa ${t} does not support ${e}.${n}`)};if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){let a;if(n==="toggle"){if(r.currentOn===void 0)throw new Error("kasa toggle needs the current power state (pre-read failed)");a=!r.currentOn}else a=n==="turnOn";return{payload:t==="bulb"?vp({on_off:a?1:0}):LH(a,r.childId),optimistic:{type:"power",state:{on:a}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){t==="plug"&&s();let a;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("kasa adjustBrightness needs the current level (pre-read failed)");a=vc(r.currentLevel+(xe(i.delta)??0),0,100)}else a=vc(xe(i.level)??0,0,100);return{payload:t==="bulb"?vp({on_off:1,ignore_default:1,brightness:a}):JSON.stringify({"smartlife.iot.dimmer":{set_brightness:{brightness:a}}}),optimistic:{type:"brightness",state:{level:a}}}}if(e==="colorTemperature"&&n==="setColorTemperature"&&t==="bulb"){let a=vc(xe(i.kelvin)??bp.minKelvin,bp.minKelvin,bp.maxKelvin);return{payload:vp({on_off:1,ignore_default:1,color_temp:a}),optimistic:{type:"colorTemperature",state:{kelvin:a}}}}if(e==="color"&&n==="setColor"&&t==="bulb"){let a=vc(xe(i.hue)??0,0,360),c=vc(xe(i.saturation)??0,0,100);return{payload:vp({on_off:1,ignore_default:1,hue:a,saturation:c,color_temp:0}),optimistic:{type:"color",state:{hue:a,saturation:c}}}}return s()}function TP(t,e,n){return yP(e,t).find(o=>o.type===n)?.state}var NH=1e4,MH=2e3,UH=2e3,FH=1e3,$n=t=>typeof t=="string"&&t?t:void 0,BH=t=>/^(kl|lb)/i.test(t??"")?"bulb":"plug",wc=class{constructor(e,n,o=CP){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="kasa";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=await this.clientFactory(e)}async link(e,n){return{ok:!1,error:"Kasa devices need no pairing \u2014 connect them via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o.key,o.ip);if(r){let i=r.si,s=bc(i),a={accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{}};s?(this.runtime.set(o.key,{ip:r.ip,kind:"plug",hasEmeter:!1,online:!0,children:s}),n.push(...wP(i,s,a))):(this.runtime.set(o.key,{ip:r.ip,kind:Ck(i),hasEmeter:jH(i),online:!0}),n.push(vP(i,a)))}else this.runtime.set(o.key,{ip:o.ip,kind:BH(o.model),hasEmeter:!1,online:!1}),n.push(bP(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[kt(e)?.parentNativeId??e]:[...this.runtime.keys()],o=e&&po(e)?e:null,r=[];for(let i of n){let s=this.runtime.get(i);if(s)try{let a=await this.withIpRetry(i,c=>this.need().command(c,Ak(s.kind,s.hasEmeter)));if(s.online=!0,s.children){let c=Qn(a);s.children=bc(c)??s.children;for(let l of kP(c,i))o&&l.nativeId!==o||r.push({nativeId:l.nativeId,patch:l.patch,online:!0,ts:Date.now()})}else r.push({nativeId:i,patch:SP(s.kind,s.hasEmeter,a),online:!0,ts:Date.now()})}catch{if(s.online=!1,s.children)for(let a of s.children){let c=De(i,a.childId);o&&c!==o||r.push({nativeId:c,patch:[],online:!1,ts:Date.now()})}else r.push({nativeId:i,patch:[],online:!1,ts:Date.now()})}}return r}async sendCommand(e,n,o,r,i){let s=kt(e),a=s?.parentNativeId??e,c=s?.childKey,l=this.runtime.get(a);if(!l)throw new Error(`unknown kasa device ${e}`);let u=c?{childId:c}:{};if(o==="toggle"||o==="adjustBrightness"){let g=await this.freshSysinfo(a,l),h=c?Rk(g,c):zH(g,l.kind),y=c?null:HH(g,l.kind);h!==null&&(u.currentOn=h),y!==null&&(u.currentLevel=y)}let{payload:d,optimistic:f}=IP(l.kind,n,o,r,u),m=await this.withIpRetry(a,g=>this.need().command(g,d));if(_P(m),l.online=!0,i?.readAfter){let g=await this.freshSysinfo(a,l),h=c?{on:Rk(g,c)}:TP(l.kind,g,n);return{state:h,verifiedState:h,result:m}}return{state:f.state,result:m}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??NH),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown kasa device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async freshSysinfo(e,n){return Qn(await this.withIpRetry(e,o=>this.need().command(o,Ak(n.kind,!1))))}async locate(e,n,o){try{let r=await e.probe(o);if(r)return{ip:o,si:Qn(r)};let i=await e.rediscover(n);if(!i||i===o)return null;let s=await e.probe(i);return s?(this.cfg.onIpChange?.(n,i),{ip:i,si:Qn(s)}):null}catch{return null}}need(){if(!this.client)throw new Error("Kasa adapter not initialized");return this.client}},jH=t=>($n(t.feature)??"").includes("ENE");function zH(t,e){if(e==="bulb"){let n=t.light_state,o=n&&typeof n=="object"?n.on_off:void 0;return typeof o=="number"?o===1:null}return typeof t.relay_state=="number"?t.relay_state===1:null}function HH(t,e){if(e==="bulb"){let n=t.light_state??{},o=typeof n.on_off=="number"&&n.on_off===1?n:n.dft_on_state??n;return typeof o.brightness=="number"?o.brightness:null}return typeof t.brightness=="number"?t.brightness:null}function EP(t=CP){let e;return async n=>{e??=await t();let o=await e.probe(n);if(!o)return null;try{let r=Qn(o),i=we($n(r.mac)??$n(r.mic_mac)),s=$n(r.mic_type)??$n(r.type);return{...i?{mac:i}:{},...$n(r.alias)?{name:$n(r.alias)}:{},...$n(r.model)?{model:$n(r.model)}:{},...s?.includes("CAM")?{expectedType:"camera"}:{}}}catch{return null}}}var CP=()=>{let t=!1,e=new Set;return{probe:async o=>{let r=await import("node:dgram");return new Promise(i=>{let s=r.createSocket("udp4"),a=!1,c=u=>{if(!a){a=!0;try{s.close()}catch{}i(u)}},l=setTimeout(()=>c(null),MH);l.unref?.(),s.on("error",()=>c(null)),s.on("message",(u,d)=>{if(d.address===o){clearTimeout(l);try{c(JSON.parse(so(u)))}catch{c(null)}}}),s.send(Buffer.from(Xn(rn)),Rt,o,u=>{u&&c(null)})})},async command(o,r){if(t)throw new Error("kasa client closed");let i=await import("node:net");return new Promise((s,a)=>{let c=Buffer.from(Xn(r)),l=Buffer.alloc(4);l.writeUInt32BE(c.length);let u=i.connect({host:o,port:Rt}),d=!1,f=Buffer.alloc(0),m=g=>{d||(d=!0,e.delete(m),u.destroy(),a(g))};e.add(m),u.setTimeout(UH,()=>m(new Error(`kasa command timeout (${o}:${Rt})`))),u.on("error",g=>m(g instanceof Error?g:new Error(String(g)))),u.on("close",()=>m(new Error("kasa connection closed before a full reply"))),u.on("data",g=>{if(f=Buffer.concat([f,g]),f.length<4)return;let h=f.readUInt32BE(0);if(!(f.length<4+h)){d=!0,e.delete(m),u.end(),u.destroy();try{s(JSON.parse(so(f.subarray(4,4+h))))}catch(y){a(y instanceof Error?y:new Error(String(y)))}}}),u.write(Buffer.concat([l,c]))})},async rediscover(o){let r=T(o),i=await import("node:dgram"),s=await new Promise(a=>{let c=i.createSocket("udp4"),l=!1,u=f=>{if(!l){l=!0;try{c.close()}catch{}a(f)}},d=setTimeout(()=>u(void 0),FH);d.unref?.(),c.on("error",()=>u(void 0)),c.on("message",(f,m)=>{try{let g=Qn(JSON.parse(so(f))),h=we($n(g.mac)??$n(g.mic_mac));h&&T(h)===r&&(clearTimeout(d),u(m.address))}catch{}}),c.bind(()=>{try{c.setBroadcast(!0),c.send(Buffer.from(Xn(rn)),Rt,"255.255.255.255",f=>{f&&u(void 0)})}catch{u(void 0)}})});return s||se(r)},close(){t=!0;for(let o of[...e])o(new Error("kasa client closed"));e.clear()}}};var jP=require("node:crypto");var qe=require("node:crypto");var Es=class extends Error{constructor(e="tapo authentication rejected"){super(e),this.name="TapoAuthError"}},PP=[{username:"test@tp-link.net",password:"test"},{username:"kasa@tp-link.net",password:"kasaSetup"},{username:"",password:""}],Pk=t=>(0,qe.createHash)("md5").update(t).digest(),wp=t=>(0,qe.createHash)("sha1").update(t).digest(),er=t=>(0,qe.createHash)("sha256").update(t).digest();function KH(t){return er(Buffer.concat([wp(t.username),wp(t.password)]))}function GH(t,e,n){return er(Buffer.concat([t,e,n]))}function WH(t,e,n){return er(Buffer.concat([e,t,n]))}function DP(t){return Pk(Buffer.concat([Pk(t.username),Pk(t.password)]))}function $P(t,e){return er(Buffer.concat([t,e]))}function OP(t,e){return er(Buffer.concat([t,e]))}var kc=t=>{let e=Buffer.alloc(4);return e.writeInt32BE(t|0),e},xc=class{key;ivPrefix;sig;seq;constructor(e,n,o){let r=Buffer.concat([e,n,o]);this.key=er(Buffer.concat([Buffer.from("lsk"),r])).subarray(0,16);let i=er(Buffer.concat([Buffer.from("iv"),r]));this.ivPrefix=i.subarray(0,12),this.seq=i.readInt32BE(i.length-4),this.sig=er(Buffer.concat([Buffer.from("ldk"),r])).subarray(0,28)}encrypt(e){this.seq=this.seq+1|0;let n=Buffer.concat([this.ivPrefix,kc(this.seq)]),o=(0,qe.createCipheriv)("aes-128-cbc",this.key,n),r=Buffer.concat([o.update(Buffer.from(e,"utf8")),o.final()]),i=er(Buffer.concat([this.sig,kc(this.seq),r]));return{body:Buffer.concat([i,r]),seq:this.seq}}decrypt(e,n){let o=Buffer.concat([this.ivPrefix,kc(n)]),r=(0,qe.createDecipheriv)("aes-128-cbc",this.key,o);return Buffer.concat([r.update(e.subarray(32)),r.final()]).toString("utf8")}sealAt(e,n){let o=Buffer.concat([this.ivPrefix,kc(n)]),r=(0,qe.createCipheriv)("aes-128-cbc",this.key,o),i=Buffer.concat([r.update(Buffer.from(e,"utf8")),r.final()]),s=er(Buffer.concat([this.sig,kc(n),i]));return Buffer.concat([s,i])}};function ZH(t,e){let n=Buffer.from(wp(t.username).toString("hex"),"utf8").toString("base64"),o=e?Buffer.from(wp(t.password).toString("hex"),"utf8").toString("base64"):Buffer.from(t.password,"utf8").toString("base64");return e?{username:n,password2:o}:{username:n,password:o}}function qH(t,e,n){let o=(0,qe.createCipheriv)("aes-128-cbc",t,e);return Buffer.concat([o.update(Buffer.from(n,"utf8")),o.final()]).toString("base64")}function VH(t,e,n){let o=(0,qe.createDecipheriv)("aes-128-cbc",t,e),r=Buffer.from(n,"base64");return Buffer.concat([o.update(r),o.final()]).toString("utf8")}function RP(t){if(t.length<=16)return null;let e;try{e=JSON.parse(Buffer.from(t.subarray(16)).toString("utf8"))}catch{return null}if(!e||typeof e!="object")return null;let n=e.result;if(!n||typeof n!="object")return null;let o=n,r=typeof o.device_type=="string"?o.device_type:void 0;if(r===void 0||!r.startsWith("SMART."))return null;let i=o.mgt_encrypt_schm,s=i&&typeof i=="object"?i:{},a=s.encrypt_type==="AES"?"AES":"KLAP",c=typeof s.lv=="number"?s.lv:void 0,l=typeof s.http_port=="number"&&s.http_port>0&&s.http_port<=65535?s.http_port:void 0,u=typeof o.device_model=="string"?o.device_model:void 0,d=typeof o.mac=="string"?o.mac:void 0;return{...d?{mac:T(d)}:{},...u?{model:u}:{},deviceType:r,transport:{encryptType:a,...c!==void 0?{loginVersion:c}:{},...l!==void 0?{httpPort:l}:{}}}}var JH=86400,YH=1200,LP=t=>t.cookies.TP_SESSIONID!==void 0?{TP_SESSIONID:t.cookies.TP_SESSIONID}:{},NP=(t,e)=>{let n=Number(t.cookies.TIMEOUT);return e+(Number.isFinite(n)&&n>0?n:JH)*1e3-YH*1e3};async function XH(t,e,n,o,r){for(let i of[n,...PP]){let s=KH(i),a=(0,qe.randomBytes)(16),c=await t.http(e,{path:"/app/handshake1",body:a,port:r});if(c.status!==200||c.body.length!==48)continue;let l=c.body.subarray(0,16);if(!c.body.subarray(16,48).equals(GH(a,l,s)))continue;let d=LP(c);if((await t.http(e,{path:"/app/handshake2",body:WH(a,l,s),cookies:d,port:r})).status===200)return{kind:"KLAP",cipher:new xc(a,l,s),cookies:d,expiresAt:NP(c,o)}}return"bad-credentials"}async function QH(t,e,n,o,r,i){let{publicKey:s,privateKey:a}=(0,qe.generateKeyPairSync)("rsa",{modulusLength:1024}),c=s.export({type:"spki",format:"pem"}).toString(),l=await t.http(e,{path:"/app",json:!0,body:Buffer.from(JSON.stringify({method:"handshake",params:{key:c}})),port:i});if(l.status!==200)return"bad-credentials";let u=Dk(l.body);if(!u||u.error_code!==0||typeof u.result?.key!="string")return"bad-credentials";let d=(0,qe.privateDecrypt)({key:a,padding:qe.constants.RSA_PKCS1_PADDING},Buffer.from(u.result.key,"base64")),f=d.subarray(0,16),m=d.subarray(16,32),g=LP(l);for(let h of[n,...PP]){let y=ZH(h,o),b=await MP(t,e,f,m,void 0,g,JSON.stringify({method:"login_device",params:y}),i);if(b.error_code===0&&typeof b.result?.token=="string")return{kind:"AES",key:f,iv:m,cookies:g,token:b.result.token,expiresAt:NP(l,r)}}return"bad-credentials"}async function MP(t,e,n,o,r,i,s,a){let c=JSON.stringify({method:"securePassthrough",params:{request:qH(n,o,s)}}),l=await t.http(e,{path:"/app",json:!0,body:Buffer.from(c),cookies:i,...r?{query:{token:r}}:{},port:a}),u=Dk(l.body);if(!u||u.error_code!==0||typeof u.result?.response!="string")return{error_code:u?.error_code??9999};try{return JSON.parse(VH(n,o,u.result.response))}catch{return{error_code:9999}}}function Dk(t){try{return JSON.parse(t.toString("utf8"))}catch{return null}}async function AP(t,e,n,o,r,i){let s=JSON.stringify({method:o,...r!==void 0?{params:r}:{}});if(e.kind==="KLAP"){let{body:c,seq:l}=e.cipher.encrypt(s),u=await t.http(n,{path:"/app/request",query:{seq:l},body:c,cookies:e.cookies,port:i});if(u.status===403)return{invalid:!0};if(u.status!==200)throw new Error(`tapo request http ${u.status}`);let d=Dk(Buffer.from(e.cipher.decrypt(u.body,l),"utf8"));if(!d)throw new Error("tapo response decode failed");if(d.error_code!==void 0&&d.error_code!==0)throw new Error(`tapo ${o} error_code ${d.error_code}`);return{invalid:!1,result:d.result??{}}}let a=await MP(t,n,e.key,e.iv,e.token,e.cookies,s,i);if(a.error_code===9999)return{invalid:!0};if(a.error_code!==0)throw new Error(`tapo ${o} error_code ${a.error_code}`);return{invalid:!1,result:a.result??{}}}function $k(t=Sc(),e={}){let n=e.now??Date.now,o=e.resolveNeighborIp??(c=>se(c)),r=new Map,i=new Map,s=(c,l)=>{let d=(i.get(c)??Promise.resolve()).then(l,l);return i.set(c,d.then(()=>{},()=>{})),d};async function a(c,l,u,d){let f=r.get(c);if(!d&&f&&n()<f.expiresAt)return f;r.delete(c);let m=l.encryptType==="AES"?await QH(t,c,u,l.loginVersion===2,n(),l.httpPort):await XH(t,c,u,n(),l.httpPort);if(m==="bad-credentials")throw new Es;return r.set(c,m),m}return{probe:c=>s(c,async()=>{let l=await t.tdp(c).catch(()=>null);return l?RP(l):null}),login:(c,l,u)=>s(c,async()=>{await a(c,l,u,!1)}),call:(c,l,u,d,f)=>s(c,async()=>{let m=await a(c,l,u,!1),g=await AP(t,m,c,d,f,l.httpPort);if(g.invalid&&(m=await a(c,l,u,!0),g=await AP(t,m,c,d,f,l.httpPort),g.invalid))throw new Error("tapo session repeatedly invalid");return g.result??{}}),rediscover:async(c,l)=>{let u=T(c);for(let d of l){let f=await t.tdp(d).then(m=>m?RP(m):null).catch(()=>null);if(f?.mac!==void 0&&f.mac===u)return d}return o(u)},close:()=>{r.clear(),i.clear(),t.close()}}}var eK=2e3,tK=5e3;function nK(t){let e={};for(let n of t??[]){let o=n.split(";",1)[0]??"",r=o.indexOf("=");r>0&&(e[o.slice(0,r).trim()]=o.slice(r+1).trim())}return e}var Sc=()=>{let t=!1;return{async tdp(e){if(t)return null;let n=await import("node:dgram");return new Promise(o=>{let r=n.createSocket("udp4"),i=!1,s=c=>{if(!i){i=!0;try{r.close()}catch{}o(c)}},a=setTimeout(()=>s(null),eK);a.unref?.(),r.on("error",()=>s(null)),r.on("message",(c,l)=>{l.address===e&&(clearTimeout(a),s(new Uint8Array(c)))}),r.send(Buffer.from(ws),Nr,e,c=>{c&&s(null)})})},async http(e,n){if(t)throw new Error("tapo client closed");let o=await import("node:http");return new Promise((r,i)=>{let s=n.query?`?${new URLSearchParams(Object.entries(n.query).map(([l,u])=>[l,String(u)])).toString()}`:"",a={"content-type":n.json?"application/json":"application/octet-stream","content-length":String(n.body.length)};n.cookies&&Object.keys(n.cookies).length>0&&(a.cookie=Object.entries(n.cookies).map(([l,u])=>`${l}=${u}`).join("; "));let c=o.request({host:e,port:n.port??80,method:"POST",path:`${n.path}${s}`,headers:a,timeout:tK},l=>{let u=[];l.on("data",d=>u.push(d)),l.on("end",()=>r({status:l.statusCode??0,body:Buffer.concat(u),cookies:nK(l.headers["set-cookie"])}))});c.on("timeout",()=>c.destroy(new Error(`tapo http timeout (${e})`))),c.on("error",i),c.write(n.body),c.end()})},close(){t=!0}}};var rK=86400,oK=1200,UP={username:"",password:""},iK=t=>t.cookies.TP_SESSIONID!==void 0?{TP_SESSIONID:t.cookies.TP_SESSIONID}:{},sK=(t,e)=>{let n=Number(t.cookies.TIMEOUT);return e+(Number.isFinite(n)&&n>0?n:rK)*1e3-oK*1e3};async function aK(t,e,n,o){for(let r of n){let i=DP(r),s=(0,jP.randomBytes)(16),a=await t.http(e,{path:"/app/handshake1",body:s});if(a.status!==200||a.body.length!==48)continue;let c=a.body.subarray(0,16);if(!a.body.subarray(16,48).equals($P(s,i)))continue;let u=iK(a);if((await t.http(e,{path:"/app/handshake2",body:OP(c,i),cookies:u})).status===200)return{cipher:new xc(s,c,i),cookies:u,expiresAt:sK(a,o)}}return"bad-credentials"}async function FP(t,e,n,o){let{body:r,seq:i}=e.cipher.encrypt(o),s=await t.http(n,{path:"/app/request",query:{seq:i},body:r,cookies:e.cookies});if(s.status===403)return{invalid:!0};if(s.status!==200)throw new Error(`kasa-klap request http ${s.status}`);try{return{invalid:!1,reply:JSON.parse(e.cipher.decrypt(s.body,i))}}catch{throw new Error("kasa-klap response decode failed")}}function Ok(t,e,n={}){let o=n.now??Date.now,r=n.resolveNeighborIp??(d=>se(d)),i=e.username===""&&e.password===""?[UP]:[e,UP],s=new Map,a=new Map,c=(d,f)=>{let g=(a.get(d)??Promise.resolve()).then(f,f);return a.set(d,g.then(()=>{},()=>{})),g};async function l(d,f){let m=s.get(d);if(!f&&m&&o()<m.expiresAt)return m;s.delete(d);let g=await aK(t,d,i,o());if(g==="bad-credentials")throw new Es("kasa-klap authentication rejected");return s.set(d,g),g}async function u(d,f){let m=await l(d,!1),g=await FP(t,m,d,f);if(g.invalid&&(m=await l(d,!0),g=await FP(t,m,d,f),g.invalid))throw new Error("kasa-klap session repeatedly invalid");return g.reply}return{probe:d=>c(d,async()=>{try{let f=await u(d,rn);return f!==null&&typeof f=="object"?f:null}catch{return null}}),command:(d,f)=>c(d,()=>u(d,f)),rediscover:d=>r(T(d)),close:()=>{s.clear(),a.clear(),n.ownsSeam!==!1&&t.close()}}}var fo=t=>typeof t=="string"&&t?t:void 0,BP="check the TP-Link/Kasa email and password (or leave both blank if the device was never linked to the cloud)",cK="TP-Link cameras are not controllable over this protocol";function zP(t){if(!t)return{username:"",password:""};try{let e=JSON.parse(t);return{username:typeof e.username=="string"?e.username:"",password:typeof e.password=="string"?e.password:""}}catch{return{username:"",password:""}}}function HP(t=Sc){let e=t();return async(n,o)=>{if(!o||typeof o.username!="string"||typeof o.password!="string")return{badCredentials:BP};let r=Ok(e,{username:o.username,password:o.password},{ownsSeam:!1});try{let i=Qn(await r.command(n,rn));if((fo(i.mic_type)??fo(i.type))?.includes("CAM"))return{veto:cK};let s=we(fo(i.mac)??fo(i.mic_mac));return{...s?{mac:s}:{},...fo(i.alias)?{name:fo(i.alias)}:{},...fo(i.model)?{model:fo(i.model)}:{}}}catch(i){return i instanceof Es?{badCredentials:BP}:null}}}var $e={GET_SERVICE:2,STATE_SERVICE:3,GET_LABEL:23,STATE_LABEL:25,GET_VERSION:32,STATE_VERSION:33,GET_COLOR:101,SET_COLOR:102,LIGHT_STATE:107,SET_POWER:117,STATE_POWER:118,SET_EXTENDED_COLOR_ZONES:510,GET_EXTENDED_COLOR_ZONES:511,STATE_EXTENDED_COLOR_ZONES:512},Lk=82,WP=3500,mo=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t))),lK=t=>Math.round((t%360+360)%360/360*65535),KP=t=>Math.round(mo(t,0,100)/100*65535),uK=t=>Math.round(t/65535*360),GP=t=>Math.round(t/65535*100),Cs=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function ZP(t,e,n){t.setUint16(e,lK(n.hue),!0),t.setUint16(e+2,KP(n.saturation),!0),t.setUint16(e+4,KP(n.brightness),!0),t.setUint16(e+6,Math.round(n.kelvin),!0)}function qP(t,e){return{hue:uK(t.getUint16(e,!0)),saturation:GP(t.getUint16(e+2,!0)),brightness:GP(t.getUint16(e+4,!0)),kelvin:t.getUint16(e+6,!0)}}var kp=()=>new Uint8Array(0);function dK(t,e=0){let n=new Uint8Array(13),o=Cs(n);return ZP(o,1,t),o.setUint32(9,e,!0),n}function pK(t,e=0){let n=new Uint8Array(6),o=Cs(n);return o.setUint16(0,t?65535:0,!0),o.setUint32(2,e,!0),n}function xp(t){if(t.length<44)throw new Error(`LightState payload too short (${t.length})`);let e=Cs(t),n=new TextDecoder().decode(t.subarray(12,44)).replace(/\0+$/,"").trim();return{...qP(e,0),power:e.getUint16(10,!0)>0,label:n}}function Nk(t){if(t.length<8)throw new Error("StateVersion payload too short");let e=Cs(t);return{vendor:e.getUint32(0,!0),product:e.getUint32(4,!0)}}var VP=()=>new Uint8Array(0);function JP(t,e={}){let n=new Uint8Array(8+Lk*8),o=Cs(n);o.setUint32(0,e.durationMs??0,!0),o.setUint8(4,e.apply??1),o.setUint16(5,e.zoneIndex??0,!0);let r=Math.min(t.length,Lk);o.setUint8(7,r);for(let i=0;i<r;i++)ZP(o,8+i*8,t[i]);return n}function YP(t){if(t.length<5)throw new Error(`StateExtendedColorZones payload too short (${t.length})`);let e=Cs(t),n=e.getUint16(0,!0),o=e.getUint16(2,!0),r=Math.min(e.getUint8(4),Lk),i=[];for(let s=0;s<r;s++)i.push(qP(e,5+s*8));return{count:n,zoneIndex:o,colors:i}}function XP(t,e,n){let o=[];for(let r=0;r<e;r++)o.push(t[r]??{hue:0,saturation:0,brightness:100,kelvin:WP});for(let r of n){if(!Number.isInteger(r.index)||r.index<0||r.index>=e)continue;let i=o[r.index];o[r.index]={hue:mo(r.hue,0,360),saturation:mo(r.saturation,0,100),brightness:i.brightness,kelvin:i.kelvin}}return o}function Sp(t){return{colors:t.map(e=>({hue:e.hue,saturation:e.saturation}))}}function Rs(t){let e=ks[t];return e?{color:e.color,...e.ctRange?{ctRange:e.ctRange}:{},...e.extendedMultizone?{extendedMultizone:!0}:{},...e.relay?{relay:!0}:{}}:{color:!1}}var Mk=t=>t.ctRange!==void 0&&t.ctRange[0]!==t.ctRange[1];function Uk(t,e){let n=[{type:"power",state:{on:e.power}},{type:"brightness",state:{level:e.brightness}}];return Mk(t)&&n.push({type:"colorTemperature",state:{kelvin:e.kelvin}}),t.color&&n.push({type:"color",state:{hue:e.hue,saturation:e.saturation}}),n}function QP(t){let e=Rs(t.pid),n=T(t.mac),o=[{type:"power",state:{on:t.light.power}},{type:"brightness",state:{level:t.light.brightness}}];Mk(e)&&o.push({type:"colorTemperature",config:{minKelvin:e.ctRange[0],maxKelvin:e.ctRange[1]},state:{kelvin:t.light.kelvin}}),e.color&&o.push({type:"color",config:{modes:["hs"]},state:{hue:t.light.hue,saturation:t.light.saturation}}),e.extendedMultizone&&t.zones&&t.zones.count>0&&o.push({type:"segmentColor",config:{segments:t.zones.count},state:Sp(t.zones.colors)});let r=ni(t.pid).model;return{source:{provider:"lifx",providerAccountId:t.accountId,nativeId:n,nativeType:`product:${t.pid}`,reachability:"local",online:!0,lastSeen:t.now},fingerprints:[`mac:${n}`],type:"light",name:t.nameOverride??(t.light.label||r),manufacturer:"LIFX",model:r,capabilities:o}}function eD(t,e){return{source:{provider:"lifx",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??t.model??"LIFX light",manufacturer:"LIFX",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function tD(t,e,n,o,r){let i=o&&typeof o=="object"?o:{},s=u=>typeof u=="number"&&Number.isFinite(u)?u:null,a=()=>{throw new Error(`lifx product does not support ${e}.${n}`)},c=()=>{if(!r.current)throw new Error(`lifx ${n} needs the current light state (pre-read failed)`);return r.current},l=(u,d)=>({type:$e.SET_COLOR,payload:dK(u),expectType:$e.LIGHT_STATE,optimistic:d});if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){let u=n==="toggle"?!c().power:n==="turnOn";return{type:$e.SET_POWER,payload:pK(u),expectType:$e.STATE_POWER,optimistic:{type:"power",state:{on:u}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){let u=c(),d=mo(n==="adjustBrightness"?u.brightness+(s(i.delta)??0):s(i.level)??0,0,100);return l({...u,brightness:d},{type:"brightness",state:{level:d}})}if(e==="colorTemperature"&&n==="setColorTemperature"){Mk(t)||a();let u=t.ctRange,d=c(),f=mo(s(i.kelvin)??u[0],u[0],u[1]);return l({hue:0,saturation:0,brightness:d.brightness,kelvin:f},{type:"colorTemperature",state:{kelvin:f}})}if(e==="color"&&n==="setColor"){t.color||a();let u=c(),d=mo(s(i.hue)??0,0,360),f=mo(s(i.saturation)??0,0,100),m=u.kelvin>0?u.kelvin:WP;return l({hue:d,saturation:f,brightness:u.brightness,kelvin:m},{type:"color",state:{hue:d,saturation:f}})}return a()}function nD(t,e,n){return Uk(t,e).find(o=>o.type===n)?.state}var fK=1e4,rD=2e3,mK=1e3,gK=(t,e)=>e==="toggle"||t==="brightness"||t==="colorTemperature"||t==="color",_p=class{constructor(e,n,o=iD){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="lifx";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"LIFX devices need no pairing \u2014 connect them via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);if(!(r&&"relay"in r))if(r){let i=Rs(r.pid);this.runtime.set(o.key,{ip:r.ip,pid:r.pid,features:i,online:!0});let s;i.extendedMultizone&&(s=await this.freshZones(o.key).catch(()=>{})),n.push(QP({accountId:this.accountId,mac:o.key,pid:r.pid,light:r.light,now:Date.now(),...s?{zones:s}:{},...o.name?{nameOverride:o.name}:{}}))}else this.runtime.set(o.key,{ip:o.ip,pid:0,features:Rs(0),online:!1}),n.push(eD(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshLight(r);i.online=!0,o.push({nativeId:r,patch:Uk(i.features,s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown lifx device ${e}`);if(n==="segmentColor")return this.sendSegmentColors(e,o,r,i);let a={};gK(n,o)&&(a.current=await this.freshLight(e));let c=tD(s.features,n,o,r,a);if(await this.withIpRetry(e,l=>this.need().request(l,e,c.type,c.payload,c.expectType)),s.online=!0,i?.readAfter){let l=await this.freshLight(e),u=nD(s.features,l,n);return{state:u,verifiedState:u}}return{state:c.optimistic.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??fK),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown lifx device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async freshLight(e){let n=await this.withIpRetry(e,o=>this.need().request(o,e,$e.GET_COLOR,kp(),$e.LIGHT_STATE));return xp(n.payload)}async freshZones(e){let n=await this.withIpRetry(e,o=>this.need().request(o,e,$e.GET_EXTENDED_COLOR_ZONES,VP(),$e.STATE_EXTENDED_COLOR_ZONES));return YP(n.payload)}async sendSegmentColors(e,n,o,r){if(n!=="setSegmentColors")throw new Error(`unsupported lifx segmentColor command ${n}`);let i=o&&typeof o=="object"?o.segments:void 0;if(!Array.isArray(i))throw new Error("lifx setSegmentColors needs a segments array");let s=await this.freshZones(e),a=XP(s.colors,s.count,i);await this.withIpRetry(e,l=>this.need().request(l,e,$e.SET_EXTENDED_COLOR_ZONES,JP(a,{apply:1}),$e.STATE_EXTENDED_COLOR_ZONES));let c=this.runtime.get(e);if(c&&(c.online=!0),r?.readAfter){let l=await this.freshZones(e),u=Sp(l.colors);return{state:u,verifiedState:u}}return{state:Sp(a)}}async locate(e,n){let o=async r=>{let s=Nk((await e.request(r,n.key,$e.GET_VERSION,new Uint8Array(0),$e.STATE_VERSION)).payload).product;if(Rs(s).relay)return{ip:r,pid:s,relay:!0};let a=xp((await e.request(r,n.key,$e.GET_COLOR,kp(),$e.LIGHT_STATE)).payload);return{ip:r,pid:s,light:a}};try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("LIFX adapter not initialized");return this.client}},hK="this LIFX Switch is a wall relay \u2014 no local control adapter for it in v1";function oD(t=iD){let e=t();return async n=>{try{let o=await e.probe(n);if(!o)return null;let r;try{r=Nk((await e.request(n,o.mac,$e.GET_VERSION,new Uint8Array(0),$e.STATE_VERSION)).payload).product}catch{}if(r!==void 0&&Rs(r).relay)return{veto:hK};let i={mac:o.mac};r!==void 0&&(i.model=ni(r).model);try{let s=xp((await e.request(n,o.mac,$e.GET_COLOR,kp(),$e.LIGHT_STATE)).payload);s.label&&(i.name=s.label)}catch{}return i}catch{return null}}}var iD=()=>{let t=!1,e=0,n=new Set,o=()=>e=(e+1)%256,r=async(i,s,a,c)=>{let l=await import("node:dgram");return new Promise((u,d)=>{let f=l.createSocket("udp4"),m=!1,g=C=>{if(!m){m=!0,n.delete(h),clearTimeout(y);try{f.close()}catch{}C()}},h=C=>g(()=>d(C));n.add(h);let y=setTimeout(()=>g(()=>c(u,d)),a);y.unref?.(),f.on("error",C=>h(C instanceof Error?C:new Error(String(C)))),f.on("message",(C,F)=>{let U=xs(C);if(!U||U.source!==Qa)return;let W=s(U,F);W!==void 0&&g(()=>u(W))});let{packet:b,port:w,address:x,broadcast:I}=i(),E=()=>f.send(b,w,x,C=>{C&&h(C)});I?f.bind(()=>{try{f.setBroadcast(!0),E()}catch(C){h(C instanceof Error?C:new Error(String(C)))}}):E()})};return{async probe(i){if(t)throw new Error("lifx client closed");return r(()=>({packet:_n({type:$e.GET_SERVICE,tagged:!0,resRequired:!0,sequence:o()}),port:At,address:i}),(s,a)=>{if(s.type!==$e.STATE_SERVICE||a.address!==i||s.targetMac===void 0)return;let c=new DataView(s.payload.buffer,s.payload.byteOffset,s.payload.byteLength);if(!(s.payload.length<5||s.payload[0]!==1))return{mac:s.targetMac,port:c.getUint32(1,!0)||At}},rD,s=>s(null))},async request(i,s,a,c,l){if(t)throw new Error("lifx client closed");let u=T(s);return r(()=>({packet:_n({type:a,targetMac:u,resRequired:!0,sequence:o(),payload:c}),port:At,address:i}),d=>d.type===l&&d.targetMac===u?d:void 0,rD,(d,f)=>f(new Error(`lifx request timeout (${i}:${At} type=${a})`)))},async rediscover(i){let s=T(i),a=await r(()=>({packet:_n({type:$e.GET_SERVICE,tagged:!0,resRequired:!0,sequence:o()}),port:At,address:"255.255.255.255",broadcast:!0}),(c,l)=>c.type===$e.STATE_SERVICE&&c.targetMac===s?l.address:void 0,mK,c=>c(void 0)).catch(()=>{});return a||se(s)},close(){t=!0;for(let i of[...n])i(new Error("lifx client closed"));n.clear()}}};var SD=require("node:crypto");var sD=require("node:crypto");var q=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Ps=t=>typeof t=="string"&&t?t:void 0,ce=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,Fk=t=>(0,sD.createHash)("sha256").update(t,"utf8").digest("hex"),yK="admin",vK=Fk("dummy_method:dummy_uri");function bK(t){try{return ce(JSON.parse(t))}catch{return}}function aD(t){let e=typeof t=="string"?bK(t):ce(t);if(!e||e.auth_type!=="digest")return null;let n=Ps(e.realm),o=Ps(e.algorithm)??"SHA-256",r=typeof e.nonce=="number"?e.nonce:Ps(e.nonce);return!n||r===void 0?null:{realm:n,nonce:r,algorithm:o}}function cD(t){let e=Ps(t);if(!e||!/^digest\b/i.test(e.trim()))return null;let n={};for(let i of e.replace(/^digest\s+/i,"").matchAll(/([a-z]+)\s*=\s*(?:"([^"]*)"|([^,\s]+))/gi))n[i[1].toLowerCase()]=i[2]??i[3]??"";let o=n.realm,r=n.nonce;return!o||r===void 0?null:{realm:o,nonce:r,algorithm:n.algorithm??"SHA-256"}}function lD(t,e){let n=e.username??yK,o=Fk(`${n}:${t.realm}:${e.password}`),r=Fk(`${o}:${t.nonce}:${e.nc}:${e.cnonce}:auth:${vK}`);return{realm:t.realm,username:n,nonce:t.nonce,cnonce:e.cnonce,response:r,algorithm:t.algorithm,nc:e.nc}}var Ip=t=>t==="rgbw"?"RGBW":t==="rgb"?"RGB":"Light";function Bk(t){let e=ce(t["switch:0"]),n=[],o=[];for(let i of Object.keys(t)){let s=/^input:(\d+)$/.exec(i);s&&n.push(Number(s[1]));let a=/^switch:(\d+)$/.exec(i);a&&o.push(Number(a[1]))}let r=ce(t["rgbw:0"])?"rgbw":ce(t["rgb:0"])?"rgb":ce(t["light:0"])?"light":null;return{switch0:e!==void 0,switch0Emeter:e!==void 0&&(q(e.apower)!==null||ce(e.aenergy)!==void 0),cover0:ce(t["cover:0"])!==void 0,inputs:n.sort((i,s)=>i-s),switches:o.sort((i,s)=>i-s),lightKind:r}}function uD(t,e){return t.cover0?"cover":t.lightKind?"light":/plug/i.test(e)?"plug":"switch"}function wK(t,e){let n=(t%360+360)%360/60,r=Math.max(0,Math.min(100,e))/100,i=r*(1-Math.abs(n%2-1)),s=1-r,[a,c,l]=n<1?[r,i,0]:n<2?[i,r,0]:n<3?[0,r,i]:n<4?[0,i,r]:n<5?[i,0,r]:[r,0,i];return{r:Math.round((a+s)*255),g:Math.round((c+s)*255),b:Math.round((l+s)*255)}}function jk(t,e,n){let o=t/255,r=e/255,i=n/255,s=Math.max(o,r,i),a=Math.min(o,r,i),c=s-a;if(c===0||s===0)return{hue:0,saturation:0};let l;return s===o?l=(r-i)/c%6:s===r?l=(i-o)/c+2:l=(o-r)/c+4,{hue:Math.round(((l*60+360)%360+360)%360),saturation:Math.round(c/s*100)}}function kK(t,e){let n=[{type:"power",state:{on:typeof e.output=="boolean"?e.output:null}},{type:"brightness",state:{level:q(e.brightness)}}];if(t==="rgb"||t==="rgbw"){let o=Array.isArray(e.rgb)?e.rgb.map(q):[],r=o.length===3&&o.every(i=>i!==null)?jk(o[0],o[1],o[2]):null;n.push({type:"color",config:{modes:["hs"]},state:{hue:r?.hue??null,saturation:r?.saturation??null}})}return t==="rgbw"&&n.push({type:"range",instance:"white",config:{min:0,max:100,step:1,unit:"%"},state:{value:q(e.white)}}),n}function zk(t){let e=Ps(t);return e==="open"||e==="closed"||e==="opening"||e==="closing"||e==="stopped"?e:"unknown"}function xK(t){return{position:q(t.current_pos),state:zk(t.state)}}function dD(t,e){let n=[],o=ce(e["switch:0"]);if(t.switch0&&o&&(n.push({type:"power",state:{on:typeof o.output=="boolean"?o.output:null}}),t.switch0Emeter)){let i=q(ce(o.aenergy)?.total);n.push({type:"energyMeter",state:{power:q(o.apower),voltage:q(o.voltage),current:q(o.current),energy:i!==null?i/1e3:null}})}let r=ce(e["cover:0"]);if(t.cover0&&r&&n.push({type:"cover",config:{kind:"generic",supportsPosition:q(r.current_pos)!==null,supportsTilt:!1},state:{position:q(r.current_pos),state:zk(r.state)}}),t.lightKind){let i=ce(e[`${t.lightKind}:0`]);i&&n.push(...kK(t.lightKind,i))}for(let i of t.inputs){let s=ce(e[`input:${i}`]);n.push({type:"binarySensor",instance:String(i),config:{sensorType:"generic"},state:{active:typeof s?.state=="boolean"?s.state:null}})}return n}function pD(t,e){let n=Bk(t),o=T(e.mac);return{source:{provider:"shelly",providerAccountId:e.accountId,nativeId:o,nativeType:e.app,reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${o}`],type:uD(n,e.app),name:e.nameOverride??e.deviceName??e.app,manufacturer:"Shelly",model:e.app,capabilities:dD(n,t)}}function SK(t,e){let n=ce(t[`switch:${e}`]);if(!n)return[];let o=[{type:"power",state:{on:typeof n.output=="boolean"?n.output:null}}];if(q(n.apower)!==null||ce(n.aenergy)!==void 0){let r=q(ce(n.aenergy)?.total);o.push({type:"energyMeter",state:{power:q(n.apower),voltage:q(n.voltage),current:q(n.current),energy:r!==null?r/1e3:null}})}return o}function _K(t,e){return t.inputs.map(n=>{let o=ce(e[`input:${n}`]);return{type:"binarySensor",instance:String(n),config:{sensorType:"generic"},state:{active:typeof o?.state=="boolean"?o.state:null}}})}function fD(t,e,n){let o=T(n.mac),r={source:{provider:"shelly",providerAccountId:n.accountId,nativeId:o,nativeType:n.app,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:uD(e,n.app),name:n.nameOverride??n.deviceName??n.app,manufacturer:"Shelly",model:n.app,capabilities:_K(e,t)},i=e.switches.map(s=>{let a=De(o,String(s)),c=ce(t[`switch:${s}`]),l=Ps(c?.name)??`Switch ${s+1}`;return{source:{provider:"shelly",providerAccountId:n.accountId,nativeId:a,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[Ur("shelly",n.accountId,a)],type:"switch",name:n.nameOverride?`${n.nameOverride} ${s+1}`:l,manufacturer:"Shelly",model:n.app,parentNativeId:o,capabilities:SK(t,s)}});return[r,...i]}function Hk(t,e,n){let o=T(e),r=[];for(let i of n){let s=ce(t[`switch:${i}`]);if(!s)continue;let a=[];if(typeof s.output=="boolean"&&a.push({type:"power",state:{on:s.output}}),q(s.apower)!==null||ce(s.aenergy)!==void 0){let c={};q(s.apower)!==null&&(c.power=q(s.apower)),q(s.voltage)!==null&&(c.voltage=q(s.voltage)),q(s.current)!==null&&(c.current=q(s.current));let l=q(ce(s.aenergy)?.total);l!==null&&(c.energy=l/1e3),a.push({type:"energyMeter",state:c})}a.length>0&&r.push({nativeId:De(o,String(i)),patch:a})}return r}function mD(t,e){return{source:{provider:"shelly",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:/plug/i.test(t.model??"")?"plug":"switch",name:t.name??t.model??"Shelly device",manufacturer:"Shelly",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function gD(t,e){return dD(t,e).map(n=>({type:n.type,...n.instance!==void 0?{instance:n.instance}:{},state:n.state}))}function hD(t,e){let n=[],o=ce(e["switch:0"]);if(t.switch0&&o&&(typeof o.output=="boolean"&&n.push({type:"power",state:{on:o.output}}),t.switch0Emeter&&(q(o.apower)!==null||ce(o.aenergy)!==void 0))){let i={};q(o.apower)!==null&&(i.power=q(o.apower)),q(o.voltage)!==null&&(i.voltage=q(o.voltage)),q(o.current)!==null&&(i.current=q(o.current));let s=q(ce(o.aenergy)?.total);s!==null&&(i.energy=s/1e3),n.push({type:"energyMeter",state:i})}let r=ce(e["cover:0"]);if(t.cover0&&r){let i={};r.state!==void 0&&(i.state=zk(r.state)),q(r.current_pos)!==null&&(i.position=q(r.current_pos)),Object.keys(i).length>0&&n.push({type:"cover",state:i})}if(t.lightKind){let i=ce(e[`${t.lightKind}:0`]);if(i){if(typeof i.output=="boolean"&&n.push({type:"power",state:{on:i.output}}),q(i.brightness)!==null&&n.push({type:"brightness",state:{level:q(i.brightness)}}),(t.lightKind==="rgb"||t.lightKind==="rgbw")&&Array.isArray(i.rgb)){let s=i.rgb.map(q);s.length===3&&s.every(a=>a!==null)&&n.push({type:"color",state:jk(s[0],s[1],s[2])})}t.lightKind==="rgbw"&&q(i.white)!==null&&n.push({type:"range",instance:"white",state:{value:q(i.white)}})}}for(let i of t.inputs){let s=ce(e[`input:${i}`]);s&&typeof s.state=="boolean"&&n.push({type:"binarySensor",instance:String(i),state:{active:s.state}})}return n}var As=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function yD(t,e,n,o,r=0,i={}){let s=ce(o)??{},a=()=>{throw new Error(`shelly device does not support ${e}.${n}`)};if(t.lightKind){let c=Ip(t.lightKind);if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){if(n==="toggle")return{method:`${c}.Toggle`,params:{id:0},optimistic:u=>{let d=ce(u)?.was_on;return{type:"power",state:{on:typeof d=="boolean"?!d:null}}}};let l=n==="turnOn";return{method:`${c}.Set`,params:{id:0,on:l},optimistic:()=>({type:"power",state:{on:l}})}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){let l;if(n==="adjustBrightness"){if(i.currentLevel===void 0)throw new Error("shelly adjustBrightness needs the current level (pre-read failed)");l=As(i.currentLevel+(q(s.delta)??0),0,100)}else l=As(q(s.level)??0,0,100);return l===0?{method:`${c}.Set`,params:{id:0,on:!1},optimistic:()=>({type:"brightness",state:{level:0}})}:{method:`${c}.Set`,params:{id:0,on:!0,brightness:l},optimistic:()=>({type:"brightness",state:{level:l}})}}if(e==="color"&&n==="setColor"&&(t.lightKind==="rgb"||t.lightKind==="rgbw")){let l=As(q(s.hue)??0,0,360),u=As(q(s.saturation)??0,0,100),{r:d,g:f,b:m}=wK(l,u);return{method:`${c}.Set`,params:{id:0,on:!0,rgb:[d,f,m]},optimistic:()=>({type:"color",state:{hue:l,saturation:u}})}}if(e==="range"&&n==="setRange"&&t.lightKind==="rgbw"){let l=As(q(s.value)??0,0,100);return{method:"RGBW.Set",params:{id:0,white:l},optimistic:()=>({type:"range",state:{value:l}})}}return a()}if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){if(!t.switch0&&!t.switches.includes(r)&&a(),n==="toggle")return{method:"Switch.Toggle",params:{id:r},optimistic:l=>{let u=ce(l)?.was_on;return{type:"power",state:{on:typeof u=="boolean"?!u:null}}}};let c=n==="turnOn";return{method:"Switch.Set",params:{id:r,on:c},optimistic:()=>({type:"power",state:{on:c}})}}if(e==="cover"){if(t.cover0||a(),n==="open")return{method:"Cover.Open",params:{id:0},optimistic:()=>({type:"cover",state:{state:"opening"}})};if(n==="close")return{method:"Cover.Close",params:{id:0},optimistic:()=>({type:"cover",state:{state:"closing"}})};if(n==="stop")return{method:"Cover.Stop",params:{id:0},optimistic:()=>({type:"cover",state:{state:"stopped"}})};if(n==="setPosition"){let c=As(q(s.position)??0,0,100);return{method:"Cover.GoToPosition",params:{id:0,pos:c},optimistic:()=>({type:"cover",state:{position:c}})}}}return a()}function vD(t,e=0,n=null){return n&&(t==="power"||t==="brightness"||t==="color"||t==="range")?{method:`${Ip(n)}.GetStatus`,params:{id:0}}:t==="power"?{method:"Switch.GetStatus",params:{id:e}}:t==="cover"?{method:"Cover.GetStatus",params:{id:0}}:null}function bD(t,e){let n=ce(e);if(n){if(t==="power")return{on:typeof n.output=="boolean"?n.output:null};if(t==="cover")return xK(n);if(t==="brightness")return{level:q(n.brightness)};if(t==="color"){let o=Array.isArray(n.rgb)?n.rgb.map(q):[];return o.length===3&&o.every(r=>r!==null)?jk(o[0],o[1],o[2]):void 0}if(t==="range")return{value:q(n.white)}}}var wD=6e4,IK=2500,TK="gen1 Shelly (REST/CoIoT) \u2014 not yet supported natively; control it via a linked Home Assistant",EK="this Shelly has a password set \u2014 enter it to connect",CK="wrong password \u2014 check it and reconnect",go=class extends Error{constructor(e){super(e),this.name="ShellyAuthError"}};function RK(t){if(t)try{let e=JSON.parse(t);return typeof e.password=="string"&&e.password?e.password:void 0}catch{return}}var an=t=>typeof t=="string"&&t?t:void 0,AK=t=>typeof t=="number"&&Number.isFinite(t)?t:null,On=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,Tp=class{constructor(e,n,o=ID){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="shelly";reachability="local";client=null;runtime=new Map;wsSubs=new Map;reconnectTimers=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){let n=RK(await e.localSecrets.read(this.accountId));this.client=this.clientFactory(n?{password:n}:void 0)}async link(e,n){return{ok:!1,error:"Shelly devices need no pairing \u2014 connect them via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);if(r&&"status"in r){let i=Bk(r.status);this.runtime.set(o.key,{ip:r.ip,app:r.app,components:i,online:!0});let s={accountId:this.accountId,mac:o.key,app:r.app,now:Date.now(),...r.deviceName?{deviceName:r.deviceName}:{},...o.name?{nameOverride:o.name}:{}};i.switches.length>1?n.push(...fD(r.status,i,s)):n.push(pD(r.status,s))}else{this.runtime.set(o.key,{ip:o.ip,app:o.model??"",components:{switch0:!0,switch0Emeter:!1,cover0:!1,inputs:[],switches:[],lightKind:null},online:!1});let i=mD(o,{accountId:this.accountId,now:Date.now()});r?.authFailed&&(i.source.attention="needs-password"),n.push(i)}}return{devices:n,rooms:[]}}async getState(e){let n=e?[kt(e)?.parentNativeId??e]:[...this.runtime.keys()],o=e&&po(e)?e:null,r=[];for(let i of n){let s=this.runtime.get(i);if(s)try{let a=On(await this.withIpRetry(i,c=>this.need().rpc(c,"Shelly.GetStatus")))??{};if(s.online=!0,s.components.switches.length>1)for(let c of Hk(a,i,s.components.switches))o&&c.nativeId!==o||r.push({nativeId:c.nativeId,patch:c.patch,online:!0,attention:null,ts:Date.now()});else r.push({nativeId:i,patch:gD(s.components,a),online:!0,attention:null,ts:Date.now()})}catch(a){s.online=!1;let c=a instanceof go?"needs-password":null;if(s.components.switches.length>1)for(let l of s.components.switches){let u=De(i,String(l));o&&u!==o||r.push({nativeId:u,patch:[],online:!1,attention:c,ts:Date.now()})}else r.push({nativeId:i,patch:[],online:!1,attention:c,ts:Date.now()})}}return r}async sendCommand(e,n,o,r,i){let s=kt(e),a=s?.parentNativeId??e,c=s?Number(s.childKey):0,l=this.runtime.get(a);if(!l)throw new Error(`unknown shelly device ${e}`);let u={};if(n==="brightness"&&o==="adjustBrightness"&&l.components.lightKind){let g=On(await this.withIpRetry(a,y=>this.need().rpc(y,`${Ip(l.components.lightKind)}.GetStatus`,{id:0}))),h=AK(g?.brightness);h!==null&&(u.currentLevel=h)}let d=yD(l.components,n,o,r,c,u),f=await this.withIpRetry(a,g=>this.need().rpc(g,d.method,d.params));l.online=!0;let m=d.optimistic(f);if(i?.readAfter){let g=vD(n,c,l.components.lightKind);if(g){let h=await this.withIpRetry(a,b=>this.need().rpc(b,g.method,g.params)),y=bD(n,h);return{state:y,verifiedState:y,result:f}}}return{state:m.state,result:f}}subscribe(e,n){this.onState=e;for(let o of this.runtime.keys())this.openWs(o);return this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??wD),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null);for(let o of this.wsSubs.values())o();this.wsSubs.clear();for(let o of this.reconnectTimers.values())clearTimeout(o);this.reconnectTimers.clear(),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null);for(let e of this.wsSubs.values())e();this.wsSubs.clear();for(let e of this.reconnectTimers.values())clearTimeout(e);this.reconnectTimers.clear(),this.client?.close(),this.client=null}openWs(e){if(this.disposed||!this.onState||this.wsSubs.has(e))return;let n=this.runtime.get(e);if(!n||!this.client)return;let o=this.client.subscribe(n.ip,{onNotify:r=>this.handleNotify(e,r),onDown:()=>{this.wsSubs.delete(e),this.scheduleReconnect(e)}});this.wsSubs.set(e,o)}handleNotify(e,n){if(this.disposed||!this.onState)return;let o=this.runtime.get(e),r=On(n),i=an(r?.method),s=On(r?.params);if(!o||!i?.startsWith("Notify")||!s)return;if(o.components.switches.length>1){let c=!1;for(let l of Hk(s,e,o.components.switches))c=!0,this.onState?.({nativeId:l.nativeId,patch:l.patch,online:!0,ts:Date.now()});c&&(o.online=!0);return}let a=hD(o.components,s);a.length>0&&(o.online=!0,this.onState?.({nativeId:e,patch:a,online:!0,ts:Date.now()}))}scheduleReconnect(e){if(this.disposed||!this.onState||this.reconnectTimers.has(e))return;let n=setTimeout(()=>{this.reconnectTimers.delete(e),this.openWs(e)},this.cfg.pollMs??wD);n.unref?.(),this.reconnectTimers.set(e,n)}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown shelly device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async locate(e,n){let o=async r=>{let i=On(await e.rpc(r,"Shelly.GetDeviceInfo"))??{},s=we(an(i.mac));if(s&&T(s)!==n.key)throw new Error("mac mismatch \u2014 a different device answered");let a=On(await e.rpc(r,"Shelly.GetStatus"))??{},c=an(i.name)??an(i.id);return{ip:r,app:an(i.app)??n.model??"Shelly",...c?{deviceName:c}:{},status:a}};try{return await o(n.ip)}catch(r){if(r instanceof go)return{authFailed:!0};try{let i=await e.rediscover(n.key);if(!i||i===n.ip)return null;let s=await o(i);return this.cfg.onIpChange?.(n.key,i),s}catch(i){return i instanceof go?{authFailed:!0}:null}}}need(){if(!this.client)throw new Error("Shelly adapter not initialized");return this.client}};function _D(t=ID){return async(e,n)=>{let o=n?.password,r=t(o?{password:o}:void 0),i=await r.info(e).catch(()=>null);if(!i)return null;let s={...i.mac?{mac:i.mac}:{},...i.name?{name:i.name}:{},...i.model?{model:i.model}:{},...i.profile==="cover"?{expectedType:"cover"}:{}};if(i.gen<2)return{...s,veto:TK};if(i.auth){if(!o)return{...s,badCredentials:EK};try{await r.rpc(e,"Shelly.GetDeviceInfo")}catch(a){return a instanceof go?{...s,badCredentials:CK}:null}}return s}}var kD="acbridge-hub",xD=t=>t.status===401||On(t.body?.error)?.code===401,PK=t=>aD(On(t.body?.error)?.message)??cD(t.wwwAuth);function DK(t){let e=t?.fetchImpl??fetch,n=t?.password,o=!1,r=new Set,i=new Set,s=async(l,u)=>{if(o)throw new Error("shelly client closed");let d=new AbortController;r.add(d);let f=setTimeout(()=>d.abort(),IK);f.unref?.();try{return await e(l,{...u,signal:d.signal})}finally{clearTimeout(f),r.delete(d)}},a=async l=>{let u=await s(l);if(!(u.ok??(u.status>=200&&u.status<300)))throw new Error(`shelly http ${u.status} (${l})`);return await u.json()},c=async(l,u)=>{let d=await s(`http://${l}/rpc`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(u)}),f;try{f=await d.json()}catch{f=void 0}return{status:d.status,wwwAuth:d.headers.get("www-authenticate"),body:On(f)}};return{async info(l){try{let u=On(await a(`http://${l}/shelly`))??{},d=typeof u.gen=="number"?u.gen:1,f=u.auth===!0||u.auth_en===!0,m=we(an(u.mac)),g=an(u.app)??an(u.type),h=an(u.name)??an(u.id),y=an(u.profile);return!m&&!g?null:{...m?{mac:m}:{},gen:d,auth:f,...g?{model:g}:{},...h?{name:h}:{},...y?{profile:y}:{}}}catch{return null}},async rpc(l,u,d){let f={id:1,src:kD,method:u,...d?{params:d}:{}},m=await c(l,f);if(xD(m)){let h=PK(m);if(!n||!h)throw new go("shelly device requires a password");let y=lD(h,{password:n,cnonce:(0,SD.randomBytes)(16).toString("base64"),nc:1});if(m=await c(l,{...f,auth:y}),xD(m))throw new go("shelly authentication rejected (wrong password)")}let g=On(m.body?.error);if(g)throw new Error(`shelly rpc ${g.code??"?"}: ${an(g.message)??u}`);if(!m.body)throw new Error(`shelly rpc ${m.status} (http://${l}/rpc)`);return m.body.result},subscribe(l,u){let d=!1,f=null,m=!1,g=()=>{d||(d=!0,m||u.onDown())};return Promise.resolve().then(()=>(hd(),BE)).then(({WebSocket:h})=>{if(m||o)return;f=new h(`ws://${l}/rpc`);let y={terminate:()=>f?.terminate()};i.add(y),f.on("open",()=>f?.send(JSON.stringify({id:1,src:kD,method:"Shelly.GetStatus"}))),f.on("message",b=>{try{u.onNotify(JSON.parse(String(b)))}catch{}}),f.on("error",()=>{}),f.on("close",()=>{i.delete(y),g()})}).catch(g),()=>{m=!0,f?.terminate(),f=null}},async rediscover(l){return se(l)},close(){o=!0;for(let l of[...r])l.abort();r.clear();for(let l of[...i])l.terminate();i.clear()}}}var ID=t=>DK(t);var Cp="main",$K=2200,OK=6500,LK=(t,e,n,o=Cp)=>t?.components?.[o]?.[e]?.[n],tr=(t,e)=>typeof t=="number"?t:e,Ep=t=>t&&typeof t.value=="number"?t.unit==="F"?Math.round(ts(t.value)*10)/10:t.value:null;function NK(t){return((t.components?.find(n=>n.id===Cp)??t.components?.[0])?.capabilities??[]).map(n=>n.id)}function MK(t,e,n){return e?n:n?`${t}:${n}`:t}function UK(t,e,n,o){let r=[],i=[],s=(c,l)=>LK(n,c,l,t),a=(c,l,u)=>{let d=MK(t,o,u);r.push(d!==void 0?{...c,instance:d}:c),i.push({component:t,stCapability:l,capType:c.type,...d!==void 0?{instance:d}:{}})};if(e.has("switch")&&a({type:"power",state:{on:s("switch","switch")?.value==="on"}},"switch"),e.has("switchLevel")&&a({type:"brightness",state:{level:tr(s("switchLevel","level")?.value,null)}},"switchLevel"),e.has("colorControl")){let c=tr(s("colorControl","hue")?.value,null);a({type:"color",config:{modes:["hs"]},state:{hue:c==null?null:Math.round(c*3.6),saturation:tr(s("colorControl","saturation")?.value,null)}},"colorControl")}if(e.has("colorTemperature")&&a({type:"colorTemperature",config:{minKelvin:$K,maxKelvin:OK},state:{kelvin:tr(s("colorTemperature","colorTemperature")?.value,null)}},"colorTemperature"),e.has("lock")){let c=s("lock","lock")?.value;a({type:"lock",state:{state:c==="locked"?"locked":c==="unlocked"?"unlocked":"unknown"}},"lock")}if(e.has("windowShade")){let c=s("windowShade","windowShade")?.value,l=c==="open"?"open":c==="closed"?"closed":c==="opening"?"opening":c==="closing"?"closing":c==="partially open"?"partial":"unknown";a({type:"cover",config:{kind:"shade",supportsPosition:e.has("windowShadeLevel"),supportsTilt:!1},state:{state:l,position:tr(s("windowShadeLevel","shadeLevel")?.value,null)}},"windowShade")}if(e.has("doorControl")){let c=s("doorControl","door")?.value;a({type:"cover",config:{kind:"garage",supportsPosition:!1,supportsTilt:!1},state:{state:c==="open"?"open":c==="closed"?"closed":c==="opening"?"opening":c==="closing"?"closing":"unknown"}},"doorControl")}if(e.has("fanSpeed")&&a({type:"fan",config:{presets:[],supportsOscillate:!1},state:{on:(tr(s("fanSpeed","fanSpeed")?.value,0)??0)>0,level:null}},"fanSpeed"),e.has("thermostatMode")){let c=s("thermostatMode","thermostatMode")?.value,l=["off","heat","cool","auto","eco","fanOnly","dry"];a({type:"thermostat",config:{modes:["off","heat","cool","auto"],minC:7,maxC:35,supportsRange:e.has("thermostatCoolingSetpoint")&&e.has("thermostatHeatingSetpoint")},state:{mode:typeof c=="string"&&l.includes(c)?c:null,currentC:Ep(s("temperatureMeasurement","temperature")),heatC:Ep(s("thermostatHeatingSetpoint","heatingSetpoint")),coolC:Ep(s("thermostatCoolingSetpoint","coolingSetpoint"))}},"thermostatMode")}return e.has("contactSensor")&&a({type:"binarySensor",config:{sensorType:"contact"},state:{active:s("contactSensor","contact")?.value==="open"}},"contactSensor","contact"),e.has("motionSensor")&&a({type:"binarySensor",config:{sensorType:"motion"},state:{active:s("motionSensor","motion")?.value==="active"}},"motionSensor","motion"),e.has("presenceSensor")&&a({type:"binarySensor",config:{sensorType:"presence"},state:{active:s("presenceSensor","presence")?.value==="present"}},"presenceSensor","presence"),e.has("temperatureMeasurement")&&!e.has("thermostatMode")&&a({type:"sensor",config:{measurement:"temperature",unit:"Cel"},state:{value:Ep(s("temperatureMeasurement","temperature"))}},"temperatureMeasurement","temperature"),e.has("relativeHumidityMeasurement")&&a({type:"sensor",config:{measurement:"humidity",unit:"%"},state:{value:tr(s("relativeHumidityMeasurement","humidity")?.value,null)}},"relativeHumidityMeasurement","humidity"),e.has("battery")&&a({type:"battery",state:{level:tr(s("battery","battery")?.value,null)}},"battery"),(e.has("powerMeter")||e.has("energyMeter"))&&a({type:"energyMeter",state:{power:tr(s("powerMeter","power")?.value,null),energy:tr(s("energyMeter","energy")?.value,null)}},e.has("powerMeter")?"powerMeter":"energyMeter"),{capabilities:r,index:i}}function TD(t,e){let n=t.components??[],o=n.find(s=>s.id===Cp)?.id??n[0]?.id??Cp,r=[],i=[];for(let s of n){let a=new Set((s.capabilities??[]).map(l=>l.id)),c=UK(s.id,a,e,s.id===o);r.push(...c.capabilities),i.push(...c.index)}return{capabilities:r,index:i}}function FK(t){return t.has("lock")?"lock":t.has("doorControl")?"garageDoor":t.has("thermostatMode")?"thermostat":t.has("windowShade")?"cover":t.has("fanSpeed")&&!t.has("switchLevel")?"fan":t.has("switch")?t.has("colorControl")||t.has("colorTemperature")||t.has("switchLevel")?"light":"switch":t.has("contactSensor")||t.has("motionSensor")||t.has("presenceSensor")?"binarySensor":t.has("temperatureMeasurement")||t.has("relativeHumidityMeasurement")?"sensor":"other"}function ED(t){let e=new Map((t.rooms??[]).map(i=>[i.roomId,i.name])),n=[],o={byDevice:{}};for(let i of t.devices){let s=t.statuses[i.deviceId],{capabilities:a,index:c}=TD(i,s);o.byDevice[i.deviceId]=c;let l=new Set(NK(i));n.push({source:{provider:"smartthings",providerAccountId:t.accountId,nativeId:i.deviceId,reachability:"cloud",online:t.health?.[i.deviceId]??!0,credentialRef:`relay:smartthings:${t.locationId}`,lastSeen:null},fingerprints:[`st:${t.locationId}:${i.deviceId}`],type:FK(l),name:i.label||i.name||i.deviceId,areaHint:i.roomId?{nativeId:i.roomId,name:e.get(i.roomId)??i.roomId}:null,manufacturer:i.manufacturerName??null,model:null,capabilities:a})}let r=(t.rooms??[]).map(i=>({nativeId:i.roomId,name:i.name}));return{candidates:n,rooms:r,index:o}}var Kk="scene:",BK=t=>`${Kk}${t}`;function CD(t){return t.startsWith(Kk)?t.slice(Kk.length):null}function RD(t,e){return t.map(n=>({source:{provider:"smartthings",providerAccountId:e.accountId,nativeId:BK(n.sceneId),reachability:"cloud",online:!0,credentialRef:`relay:smartthings:${e.locationId}`,lastSeen:null},fingerprints:[`st:${e.locationId}:scene:${n.sceneId}`],type:"scene",name:n.sceneName||n.sceneId,areaHint:null,manufacturer:null,model:null,capabilities:[{type:"scene",state:{}}]}))}function Gk(t,e){let{capabilities:n}=TD(t,e);return{nativeId:t.deviceId,patch:n.map(o=>({type:o.type,...o.instance?{instance:o.instance}:{},state:o.state})),online:!0,ts:0}}function AD(t,e,n,o){let r=(t.byDevice[e]??[]).filter(i=>i.capType===n);return o!==void 0?r.find(i=>i.instance===o):r.find(i=>i.instance===void 0)??r[0]}function PD(t,e,n,o,r){let i=o??{},s=c=>typeof c=="number"?c:0,a=t.component;switch(e){case"power":return n==="turnOn"?{component:a,capability:"switch",command:"on",arguments:[]}:n==="turnOff"?{component:a,capability:"switch",command:"off",arguments:[]}:n==="toggle"?{component:a,capability:"switch",command:r?.currentOn?"off":"on",arguments:[]}:null;case"brightness":if(n==="setBrightness")return{component:a,capability:"switchLevel",command:"setLevel",arguments:[Math.max(0,Math.min(100,s(i.level)))]};if(n==="adjustBrightness"){let c=Math.max(0,Math.min(100,(r?.currentLevel??0)+s(i.delta)));return{component:a,capability:"switchLevel",command:"setLevel",arguments:[c]}}return null;case"colorTemperature":return n==="setColorTemperature"?{component:a,capability:"colorTemperature",command:"setColorTemperature",arguments:[Math.round(s(i.kelvin))]}:null;case"color":return n==="setColor"?{component:a,capability:"colorControl",command:"setColor",arguments:[{hue:Math.round(s(i.hue)/3.6*100)/100,saturation:s(i.saturation)}]}:null;case"lock":return n==="lock"?{component:a,capability:"lock",command:"lock",arguments:[]}:n==="unlock"?{component:a,capability:"lock",command:"unlock",arguments:[]}:null;case"cover":return t.stCapability==="doorControl"?n==="open"?{component:a,capability:"doorControl",command:"open",arguments:[]}:n==="close"?{component:a,capability:"doorControl",command:"close",arguments:[]}:null:n==="open"?{component:a,capability:"windowShade",command:"open",arguments:[]}:n==="close"?{component:a,capability:"windowShade",command:"close",arguments:[]}:n==="stop"?{component:a,capability:"windowShade",command:"pause",arguments:[]}:n==="setPosition"?{component:a,capability:"windowShadeLevel",command:"setShadeLevel",arguments:[Math.max(0,Math.min(100,s(i.position)))]}:null;case"fan":return n==="turnOn"?{component:a,capability:"switch",command:"on",arguments:[]}:n==="turnOff"?{component:a,capability:"switch",command:"off",arguments:[]}:n==="setFanSpeed"?{component:a,capability:"fanSpeed",command:"setFanSpeed",arguments:[Math.round(s(i.level))]}:null;case"thermostat":return n==="setThermostatMode"?{component:a,capability:"thermostatMode",command:"setThermostatMode",arguments:[String(i.mode)]}:n==="setSetpoint"?{component:a,capability:"thermostatCoolingSetpoint",command:"setCoolingSetpoint",arguments:[s(i.celsius)]}:null;default:return null}}var jK=40,zK=new Set(["healthCheck","refresh","execute","ocf","firmwareUpdate","configuration","actuator","sensor"]),HK=new Set(["switch","switchLevel","colorControl","colorTemperature","lock","doorControl","windowShade","windowShadeLevel","thermostatMode","thermostatCoolingSetpoint","thermostatHeatingSetpoint","fanSpeed","fanOscillationMode","mediaPlayback","audioVolume"]);function DD(t,e=jK){let n=[],o=[],r=new Set;for(let i of t)for(let s of i.components??[])for(let a of s.capabilities??[]){let c=a.id;!c||r.has(c)||zK.has(c)||(r.add(c),(HK.has(c)?n:o).push(c))}return[...n,...o].slice(0,Math.max(0,e))}var KK=300*1e3,Rp=class{constructor(e,n,o=GK){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="smartthings";reachability="cloud";client=null;index={byDevice:{}};deviceById=new Map;statusById=new Map;onState=null;pollTimer=null;disposed=!1;async init(e){this.client=await this.clientFactory({getToken:()=>e.cloudTokens.accessToken(this.accountId),getInstalledAppId:()=>e.cloudTokens.installedAppId?.(this.accountId)??Promise.resolve(null),locationId:this.cfg.locationId})}async link(e){return e.kind!=="cloudLinked"?{ok:!1,error:"SmartThings links via the cloud sign-in (app \u2192 Integrations \u2192 SmartThings).",retryable:!1}:{ok:!0,accountId:this.accountId}}async unlink(){}async discover(){let e=this.need(),[n,o,r]=await Promise.all([e.devices(),e.rooms().catch(()=>[]),e.scenes().catch(()=>[])]),i={},s={};await Promise.all(n.map(async l=>{i[l.deviceId]=await e.deviceStatus(l.deviceId).catch(()=>({})),await e.deviceHealth(l.deviceId).then(u=>{s[l.deviceId]=u}).catch(()=>{})})),this.deviceById.clear();for(let l of n)this.deviceById.set(l.deviceId,l);for(let[l,u]of Object.entries(i))this.statusById.set(l,u);let a=ED({accountId:this.accountId,locationId:this.cfg.locationId,devices:n,statuses:i,rooms:o,health:s});this.index=a.index,e.createSubscriptions(DD([...this.deviceById.values()])).catch(()=>{});let c=RD(r,{accountId:this.accountId,locationId:this.cfg.locationId});return{devices:[...a.candidates,...c],rooms:a.rooms}}async getState(e){let n=this.need(),o=e?[e]:[...this.deviceById.keys()],r=[];for(let i of o){let s=this.deviceById.get(i);if(!s)continue;let a=await n.deviceStatus(i).catch(()=>{});a&&this.statusById.set(i,a),r.push(Gk(s,a??this.statusById.get(i)))}return r}async sendCommand(e,n,o,r,i){let s=this.need();if(n==="scene"){let u=CD(e);if(!u)throw new Error(`not a SmartThings scene: ${e}`);if(o!=="activate")throw new Error(`unsupported SmartThings scene command ${o}`);let d=await s.executeScene(u);return{state:{lastActivated:Date.now()},result:d}}let a=AD(this.index,e,n,i?.instance);if(!a)throw new Error(`no SmartThings capability backs ${n}${i?.instance?`[${i.instance}]`:""} on ${e}`);let c=PD(a,n,o,r,{currentOn:this.currentOn(e,a.component),currentLevel:this.currentLevel(e,a.component)});if(!c)throw new Error(`unsupported SmartThings command ${n}.${o}`);let l=await s.command(e,[c]);if(i?.readAfter){let u=await s.deviceStatus(e).catch(()=>{}),d=this.deviceById.get(e);if(u&&d){this.statusById.set(e,u);let f=Gk(d,u).patch.find(m=>m.type===n&&(i.instance?m.instance===i.instance:!0))?.state;return{state:f,verifiedState:f,result:l}}}return{result:l}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},KK),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),await this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}currentOn(e,n="main"){let o=this.statusById.get(e)?.components?.[n]?.switch?.switch?.value;return typeof o=="string"?o==="on":void 0}currentLevel(e,n="main"){let o=this.statusById.get(e)?.components?.[n]?.switchLevel?.level?.value;return typeof o=="number"?o:null}need(){if(!this.client)throw new Error("SmartThings adapter not initialized");return this.client}},GK=async({getToken:t,getInstalledAppId:e,locationId:n})=>{let o="https://api.smartthings.com",r=async(i,s,a)=>{let c=await t();if(!c)throw new Error("no SmartThings access token (link the account, or it needs re-auth)");let l=await fetch(`${o}${s}`,{method:i,headers:{authorization:`Bearer ${c}`,...a!==void 0?{"content-type":"application/json"}:{}},body:a!==void 0?JSON.stringify(a):void 0});if(!l.ok)throw new Error(`SmartThings ${i} ${s} \u2192 ${l.status}`);return await l.json().catch(()=>({}))};return{async devices(){return(await r("GET",`/v1/devices?locationId=${encodeURIComponent(n)}`)).items??[]},async deviceStatus(i){return r("GET",`/v1/devices/${encodeURIComponent(i)}/status`)},async rooms(){return(await r("GET",`/v1/locations/${encodeURIComponent(n)}/rooms`)).items??[]},async scenes(){return(await r("GET",`/v1/scenes?locationId=${encodeURIComponent(n)}`)).items??[]},async executeScene(i){return r("POST",`/v1/scenes/${encodeURIComponent(i)}/execute`)},async deviceHealth(i){return(await r("GET",`/v1/devices/${encodeURIComponent(i)}/health`)).state!=="OFFLINE"},async command(i,s){return r("POST",`/v1/devices/${encodeURIComponent(i)}/commands`,{commands:s})},async createSubscriptions(i){let s=await e();if(!s||i.length===0)return;let a=`/v1/installedapps/${encodeURIComponent(s)}/subscriptions`;await r("DELETE",a).catch(()=>{});for(let c of i)await r("POST",a,{sourceType:"CAPABILITY",capability:{locationId:n,capability:c,attribute:"*",value:"*",stateChangeOnly:!0,subscriptionName:`acb${c}`.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,36)}}).catch(()=>{})},async close(){}}};var Ap={minKelvin:2500,maxKelvin:6500},Ve=t=>typeof t=="number"&&Number.isFinite(t)?t:null,ft=t=>typeof t=="string"&&t?t:void 0,_c=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function Ic(t){let e=ft(t);if(e)try{let n=Buffer.from(e,"base64").toString("utf8");if(n.length===0)return;for(let o=0;o<n.length;o++){let r=n.charCodeAt(o);if(r<32||r===127)return}return n}catch{return}}function Pp(t,e){let n=t?.slice(t.indexOf(".")+1)??"";if(/BULB/.test(n))return"light";if(/SWITCH/.test(n))return"switch";if(/PLUG/.test(n))return"plug";let o=(e??"").toUpperCase();return o.startsWith("L")?"light":o.startsWith("S")?"switch":"plug"}var $D={plug:"plug",light:"light",switch:"switch"},OD=t=>/^(P11[05]|KP125)/i.test(t??"");function LD(t){let e=Ve(t.color_temp);return{on:typeof t.device_on=="boolean"?t.device_on:null,level:Ve(t.brightness),kelvin:e!==null&&e>0?e:null,hue:Ve(t.hue),saturation:Ve(t.saturation)}}var ND=t=>Ve(t.brightness)!==null,Wk=t=>Ve(t.hue)!==null&&Ve(t.saturation)!==null,MD=t=>Array.isArray(t.color_temp_range)||Wk(t)||(Ve(t.color_temp)??0)>0;function WK(t,e,n){let o=LD(t),r=[{type:"power",state:{on:o.on}}];return(e==="light"||e==="switch")&&(ND(t)&&r.push({type:"brightness",state:{level:o.level}}),e==="light"&&MD(t)&&r.push({type:"colorTemperature",config:Ap,state:{kelvin:o.kelvin}}),e==="light"&&Wk(t)&&r.push({type:"color",config:{modes:["hs"]},state:{hue:o.hue,saturation:o.saturation}})),n&&r.push({type:"energyMeter",state:{power:null,energy:null,voltage:null,current:null}}),r}function Zk(t,e){let n=LD(t),o=[{type:"power",state:{on:n.on}}];return(e==="light"||e==="switch")&&ND(t)&&o.push({type:"brightness",state:{level:n.level}}),e==="light"&&MD(t)&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),e==="light"&&Wk(t)&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),o}function UD(t){let e=Ve(t.current_power),n=Ve(t.today_energy);return{type:"energyMeter",state:{power:e!==null?e/1e3:null,energy:n!==null?n/1e3:null,voltage:null,current:null}}}function FD(t,e){let n=e.model??ft(t.model),o=Pp(e.deviceType??ft(t.type),n),r=T(e.mac);return{source:{provider:"tapo",providerAccountId:e.accountId,nativeId:r,...e.deviceType??ft(t.type)?{nativeType:e.deviceType??ft(t.type)}:{},reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${r}`],type:$D[o],name:e.nameOverride??Ic(t.nickname)??n??"Tapo device",manufacturer:"TP-Link",model:n??null,capabilities:WK(t,o,e.energy)}}function BD(t,e){let n=Pp(void 0,t.model);return{source:{provider:"tapo",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:$D[n],name:t.name??t.model??"Tapo device",manufacturer:"TP-Link",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function jD(t,e,n,o,r){let i=o&&typeof o=="object"?o:{},s=()=>{throw new Error(`tapo ${t} does not support ${e}.${n}`)};if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){let a;if(n==="toggle"){if(r.currentOn===void 0)throw new Error("tapo toggle needs the current power state (pre-read failed)");a=!r.currentOn}else a=n==="turnOn";return{params:{device_on:a},optimistic:{type:"power",state:{on:a}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){t==="plug"&&s();let a;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("tapo adjustBrightness needs the current level (pre-read failed)");a=_c(r.currentLevel+(Ve(i.delta)??0),1,100)}else a=_c(Ve(i.level)??1,1,100);return{params:{brightness:a},optimistic:{type:"brightness",state:{level:a}}}}if(e==="colorTemperature"&&n==="setColorTemperature"&&t==="light"){let a=_c(Ve(i.kelvin)??Ap.minKelvin,Ap.minKelvin,Ap.maxKelvin);return{params:{color_temp:a},optimistic:{type:"colorTemperature",state:{kelvin:a}}}}if(e==="color"&&n==="setColor"&&t==="light"){let a=_c(Ve(i.hue)??0,0,360),c=_c(Ve(i.saturation)??0,0,100);return{params:{hue:a,saturation:c,color_temp:0},optimistic:{type:"color",state:{hue:a,saturation:c}}}}return s()}function zD(t,e,n){return Zk(t,e).find(o=>o.type===n)?.state}function HD(t){return(Ve(t.child_num)??0)>0}function Tc(t){let e=t.child_device_list;if(!Array.isArray(e)||e.length===0)return null;let n=[];return e.forEach((o,r)=>{let i=o&&typeof o=="object"?o:{},s=ft(i.device_id);if(!s)return;let a=typeof i.device_on=="boolean"?i.device_on:null;n.push({childId:s,alias:Ic(i.nickname)??`Outlet ${r+1}`,on:a})}),n.length>0?n:null}function KD(t,e,n){let o=T(n.mac),r=n.model??ft(t.model),i=n.deviceType??ft(t.type),s={source:{provider:"tapo",providerAccountId:n.accountId,nativeId:o,...i?{nativeType:i}:{},reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:"plug",name:n.nameOverride??Ic(t.nickname)??r??"Tapo power strip",manufacturer:"TP-Link",model:r??null,capabilities:[]},a=e.map(c=>{let l=De(o,c.childId);return{source:{provider:"tapo",providerAccountId:n.accountId,nativeId:l,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[Ur("tapo",n.accountId,l)],type:"plug",name:c.alias,manufacturer:"TP-Link",model:r??null,parentNativeId:o,capabilities:[{type:"power",state:{on:c.on}}]}});return[s,...a]}function GD(t,e,n){return{device_id:t,requestData:{method:e,params:n}}}function WD(t,e){let n=Tc(t);if(!n)return[];let o=T(e);return n.map(r=>({nativeId:De(o,r.childId),patch:[{type:"power",state:{on:r.on}}]}))}function qk(t,e){return Tc(t)?.find(n=>n.childId===e)?.on??null}function Vk(t){return/HUB/.test((t??"").toUpperCase())}var ZK=t=>Math.round((t-32)*5/9);function qK(t,e){let n=t&&typeof t=="object"?t:{},o=ft(n.device_id);if(!o)return null;let r=ft(n.model)??null,i=(ft(n.category)??"").toLowerCase(),s=ft(n.status)===void 0?!0:ft(n.status)==="online",a=[];if((i.includes("contact")||typeof n.open=="boolean")&&a.push({type:"binarySensor",config:{sensorType:"contact"},state:{active:typeof n.open=="boolean"?n.open:null}}),(i.includes("motion")||typeof n.detected=="boolean")&&a.push({type:"binarySensor",config:{sensorType:"motion"},state:{active:typeof n.detected=="boolean"?n.detected:null}}),i.includes("water")||i.includes("leak")||n.water_leak_status!==void 0||typeof n.in_alarm=="boolean"){let f=n.water_leak_status!==void 0?n.water_leak_status==="water_leak"||n.water_leak_status==="leak":typeof n.in_alarm=="boolean"?n.in_alarm:null;a.push({type:"binarySensor",config:{sensorType:"leak"},state:{active:f}})}i.includes("button")&&a.push({type:"binarySensor",config:{sensorType:"button"},state:{active:null}});let c=Ve(n.current_temp);if(c!==null){let f=(ft(n.temp_unit)??"celsius").toLowerCase();a.push({type:"sensor",config:{measurement:"temperature",unit:"Cel"},state:{value:f.startsWith("f")?ZK(c):Math.round(c)}})}let l=Ve(n.current_humidity);l!==null&&a.push({type:"sensor",config:{measurement:"humidity",unit:"%"},state:{value:l}});let u=Ve(n.battery_percentage);(u!==null||typeof n.at_low_battery=="boolean")&&a.push({type:"battery",state:{level:u,...typeof n.at_low_battery=="boolean"?{low:n.at_low_battery}:{}}});let d=a.some(f=>f.type==="sensor");return{childId:o,name:Ic(n.nickname)??r??`Sensor ${e+1}`,model:r,type:d?"sensor":a.some(f=>f.type==="binarySensor")?"binarySensor":"sensor",capabilities:a,online:s}}function Dp(t){let e=t.child_device_list;if(!Array.isArray(e))return null;let n=[];return e.forEach((o,r)=>{let i=qK(o,r);i&&n.push(i)}),n.length>0?n:null}function ZD(t,e,n){let o=T(n.mac),r=n.model??ft(t.model),i=n.deviceType??ft(t.type),s={source:{provider:"tapo",providerAccountId:n.accountId,nativeId:o,...i?{nativeType:i}:{},reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:"bridge",name:n.nameOverride??Ic(t.nickname)??r??"Tapo hub",manufacturer:"TP-Link",model:r??null,capabilities:[]},a=e.map(c=>{let l=De(o,c.childId);return{source:{provider:"tapo",providerAccountId:n.accountId,nativeId:l,reachability:"local",online:c.online,lastSeen:n.now},fingerprints:[Ur("tapo",n.accountId,l)],type:c.type,name:c.name,manufacturer:"TP-Link",model:c.model,parentNativeId:o,capabilities:c.capabilities}});return[s,...a]}function qD(t,e){let n=Dp(t);if(!n)return[];let o=T(e);return n.map(r=>({nativeId:De(o,r.childId),patch:r.capabilities.map(i=>({type:i.type,state:i.state})),online:r.online}))}var VK=1e4,JK="this TP-Link device isn't a plug, bulb, or switch \u2014 no local adapter for it in v1",VD="check the TP-Link ID and password (and the Tapo app's Third-Party Compatibility toggle)";function YK(t){let e=t.toUpperCase();return/CAM|DOORBELL|HUB|SENSOR|BUTTON/.test(e)?!1:/PLUG|BULB|SWITCH/.test(e)}function XK(t){let e=t.toUpperCase();if(/BULB/.test(e))return"light";if(/SWITCH/.test(e))return"switch";if(/PLUG/.test(e))return"plug"}function QK(t){if(!t)return null;try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.username!="string"||typeof n.password!="string"?null:{username:n.username,password:n.password}}catch{return null}}var e3=t=>t>0?new Promise(e=>setTimeout(e,t).unref?.()):Promise.resolve(),$p=class{constructor(e,n,o=$k){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="tapo";reachability="local";client=null;creds=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory(),this.creds=QK(await e.localSecrets.read(this.accountId))}async link(e,n){return{ok:!1,error:"Tapo devices connect with your TP-Link account via the local Connect flow (POST /local/connect) \u2014 no separate pairing.",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=this.creds?await this.locate(e,o.key,o.ip,this.creds):null;if(r){let i=o.model??r.id.model,s={accountId:this.accountId,mac:o.key,deviceType:r.id.deviceType,...i?{model:i}:{},...o.name?{nameOverride:o.name}:{},now:Date.now()};if(Vk(r.id.deviceType)){let c=await e.call(r.ip,r.id.transport,this.creds,"get_child_device_list").then(Dp).catch(()=>null)??[];this.runtime.set(o.key,{ip:r.ip,transport:r.id.transport,kind:"plug",energy:!1,online:!0,hubChildren:c}),n.push(...ZD(r.info,c,s));continue}let a=HD(r.info)?await e.call(r.ip,r.id.transport,this.creds,"get_child_device_list").then(Tc).catch(()=>null):null;if(a)this.runtime.set(o.key,{ip:r.ip,transport:r.id.transport,kind:"plug",energy:!1,online:!0,children:a}),n.push(...KD(r.info,a,s));else{let c=Pp(r.id.deviceType,i),l=await this.probeEnergy(r.ip,r.id.transport,c,i),u=FD(r.info,{...s,energy:l});this.runtime.set(o.key,{ip:r.ip,transport:r.id.transport,kind:c,energy:l,online:!0}),n.push(u)}}else n.push(BD(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[kt(e)?.parentNativeId??e]:[...this.runtime.keys()],o=e&&po(e)?e:null,r=[];for(let i of n){let s=this.runtime.get(i);if(s)try{if(s.hubChildren){let a=await this.call(i,s,"get_child_device_list");s.hubChildren=Dp(a)??s.hubChildren,s.online=!0;for(let c of qD(a,i))o&&c.nativeId!==o||r.push({nativeId:c.nativeId,patch:c.patch,online:c.online,ts:Date.now()})}else if(s.children){let a=await this.call(i,s,"get_child_device_list");s.children=Tc(a)??s.children,s.online=!0;for(let c of WD(a,i))o&&c.nativeId!==o||r.push({nativeId:c.nativeId,patch:c.patch,online:!0,ts:Date.now()})}else{let a=await this.freshInfo(i,s),c=Zk(a,s.kind);if(s.energy)try{c.push(UD(await this.call(i,s,"get_energy_usage")))}catch{}s.online=!0,r.push({nativeId:i,patch:c,online:!0,ts:Date.now()})}}catch{if(s.online=!1,s.hubChildren)for(let a of s.hubChildren){let c=De(i,a.childId);o&&c!==o||r.push({nativeId:c,patch:[],online:!1,ts:Date.now()})}else if(s.children)for(let a of s.children){let c=De(i,a.childId);o&&c!==o||r.push({nativeId:c,patch:[],online:!1,ts:Date.now()})}else r.push({nativeId:i,patch:[],online:!1,ts:Date.now()})}}return r}async sendCommand(e,n,o,r,i){let s=kt(e),a=s?.parentNativeId??e,c=s?.childKey,l=this.runtime.get(a);if(!l)throw new Error(`unknown tapo device ${e}`);if(l.hubChildren)throw new Error(`tapo hub device is read-only (${e})`);let u={};if(o==="toggle"||o==="adjustBrightness")if(c){let m=qk(await this.call(a,l,"get_child_device_list"),c);m!==null&&(u.currentOn=m)}else{let m=await this.freshInfo(a,l);typeof m.device_on=="boolean"&&(u.currentOn=m.device_on),typeof m.brightness=="number"&&(u.currentLevel=m.brightness)}let{params:d,optimistic:f}=jD(c?"plug":l.kind,n,o,r,u);if(c?await this.call(a,l,"control_child",GD(c,"set_device_info",d)):await this.call(a,l,"set_device_info",d),l.online=!0,i?.readAfter){if(c){let g=qk(await this.call(a,l,"get_child_device_list"),c);return{state:{on:g},verifiedState:{on:g}}}await e3(this.cfg.settleMs??0);let m=zD(await this.freshInfo(a,l),l.kind,n);return{state:m,verifiedState:m}}return{state:f.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??VK),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}async freshInfo(e,n){return this.call(e,n,"get_device_info")}async probeEnergy(e,n,o,r){if(o!=="plug")return!1;if(OD(r))return!0;try{return await this.need().call(e,n,this.credsOrThrow(),"get_energy_usage"),!0}catch{return!1}}call(e,n,o,r){return he({ip:n.ip,fn:i=>this.need().call(i,n.transport,this.credsOrThrow(),o,r),rediscover:()=>this.need().rediscover(e,this.knownIps()),onNewIp:i=>{n.ip=i,this.cfg.onIpChange?.(e,i)},bail:()=>this.disposed})}async locate(e,n,o,r){let i=async s=>{let a=await e.probe(s);if(!a)return null;let c=await e.call(s,a.transport,r,"get_device_info");return{ip:s,id:a,info:c}};try{let s=await i(o);if(s)return s;let a=await e.rediscover(n,this.knownIps(o));if(!a||a===o)return null;let c=await i(a);return c&&this.cfg.onIpChange?.(n,a),c}catch{return null}}knownIps(e){let n=new Set;e&&n.add(e);for(let o of this.runtime.values())n.add(o.ip);for(let o of this.cfg.devices)n.add(o.ip);return[...n]}credsOrThrow(){if(!this.creds)throw new Error("tapo adapter has no stored credentials (re-connect to re-store the TP-Link account)");return this.creds}need(){if(!this.client)throw new Error("Tapo adapter not initialized");return this.client}};function JD(t=$k){let e=t();return async(n,o)=>{let r=await e.probe(n).catch(()=>null);if(!r)return null;if(!YK(r.deviceType)&&!Vk(r.deviceType))return{veto:JK};if(!o||typeof o.username!="string"||typeof o.password!="string")return{badCredentials:VD};try{await e.login(n,r.transport,{username:o.username,password:o.password})}catch{return{badCredentials:VD}}let i=XK(r.deviceType);return{...r.mac?{mac:r.mac}:{},...r.model?{model:r.model}:{},...i?{expectedType:i}:{}}}}var sx=require("node:crypto");var Ln=require("node:crypto"),tx=21930,YD=43605,Ec=26265,XD=39270,Ae={SESS_KEY_NEG_START:3,SESS_KEY_NEG_RESP:4,SESS_KEY_NEG_FINISH:5,CONTROL:7,STATUS:8,HEART_BEAT:9,DP_QUERY:10,CONTROL_NEW:13,DP_QUERY_NEW:16,UPDATEDPS:18},QD=new Set([Ae.SESS_KEY_NEG_START,Ae.SESS_KEY_NEG_RESP,Ae.SESS_KEY_NEG_FINISH,Ae.STATUS,Ae.HEART_BEAT,Ae.DP_QUERY,Ae.DP_QUERY_NEW,Ae.UPDATEDPS]),t3=t=>Buffer.concat([Buffer.from(t,"ascii"),Buffer.alloc(12)]),Yk=["3.1","3.2","3.3","3.4","3.5"].map(t=>Buffer.from(t,"ascii")),n3=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let o=0;o<8;o++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function e$(t){let e=4294967295;for(let n=0;n<t.length;n++)e=n3[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function Xk(t,e){let n=(0,Ln.createCipheriv)("aes-128-ecb",t,null);return Buffer.concat([n.update(e),n.final()])}function Qk(t,e){let n=(0,Ln.createDecipheriv)("aes-128-ecb",t,null);return Buffer.concat([n.update(e),n.final()])}function r3(t,e){let n=(0,Ln.createCipheriv)("aes-128-ecb",t,null);return n.setAutoPadding(!1),Buffer.concat([n.update(e),n.final()])}function t$(t,e,n,o){let r=(0,Ln.createCipheriv)("aes-128-gcm",t,e);return r.setAAD(o),{ct:Buffer.concat([r.update(n),r.final()]),tag:r.getAuthTag()}}function o3(t,e,n,o,r){let i=(0,Ln.createDecipheriv)("aes-128-gcm",t,e);return i.setAAD(r),i.setAuthTag(o),Buffer.concat([i.update(n),i.final()])}function n$(t,e,n,o){let r=Buffer.alloc(16);for(let i=0;i<16;i++)r[i]=e[i]^n[i];return o==="3.5"?t$(t,e.subarray(0,12),r,Buffer.alloc(0)).ct:r3(t,r)}var nx=(t,e)=>(0,Ln.createHmac)("sha256",t).update(e).digest();function ex(t,e,n,o){let r=o?32:4,i=Buffer.alloc(16);i.writeUInt32BE(tx,0),i.writeUInt32BE(t>>>0,4),i.writeUInt32BE(e>>>0,8),i.writeUInt32BE(n.length+r+4,12);let s=Buffer.concat([i,n]),a=o?(0,Ln.createHmac)("sha256",o).update(s).digest():r$(e$(s)),c=Buffer.alloc(4);return c.writeUInt32BE(YD,0),Buffer.concat([s,a,c])}var r$=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t>>>0,0),e};function o$(t,e){if(t.length<24||t.readUInt32BE(0)!==tx)return null;let n=t.readUInt32BE(4),o=t.readUInt32BE(8);if(16+t.readUInt32BE(12)!==t.length)return null;let i=e?32:4,s=t.length-4-i;if(s<16||t.readUInt32BE(t.length-4)!==YD)return null;let a=t.subarray(0,s),c=t.subarray(s,s+i),l=e?(0,Ln.createHmac)("sha256",e).update(a).digest():r$(e$(a));return c.equals(l)?{seq:n,cmd:o,payload:t.subarray(16,s)}:null}function i$(t,e,n,o,r){let i=Buffer.alloc(18);i.writeUInt32BE(Ec,0),i.writeUInt16BE(0,4),i.writeUInt32BE(t>>>0,6),i.writeUInt32BE(e>>>0,10),i.writeUInt32BE(12+n.length+16,14);let{ct:s,tag:a}=t$(o,r,n,i.subarray(4,18)),c=Buffer.alloc(4);return c.writeUInt32BE(XD,0),Buffer.concat([i,r,s,a,c])}function s$(t,e){if(t.length<50||t.readUInt32BE(0)!==Ec)return null;let n=t.readUInt32BE(6),o=t.readUInt32BE(10);if(18+t.readUInt32BE(14)+4!==t.length||t.readUInt32BE(t.length-4)!==XD)return null;let i=t.subarray(18,30),s=t.subarray(30,t.length-4),a=s.subarray(0,s.length-16),c=s.subarray(s.length-16);try{return{seq:n,cmd:o,plaintext:o3(e,i,a,c,t.subarray(4,18))}}catch{return null}}function i3(t,e,n,o){let r=n===null?Buffer.alloc(0):Buffer.from(JSON.stringify(n),"utf8"),i=QD.has(e)?Buffer.alloc(0):t3(t),s=o===void 0?Buffer.alloc(0):(()=>{let a=Buffer.alloc(4);return a.writeUInt32BE(o>>>0,0),a})();return Buffer.concat([s,i,r])}function Jk(t){let e=t,n=0;e.length>=4&&(e.readUInt32BE(0)&4294967040)===0&&(n=e.readUInt32BE(0),e=e.subarray(4)),e.length>=15&&Yk.some(r=>e.subarray(0,3).equals(r))&&(e=e.subarray(15));let o=e.toString("utf8").replace(/\0+$/,"").trim();if(o.length===0)return{retcode:n,data:null};try{let r=JSON.parse(o);return{retcode:n,data:r!==null&&typeof r=="object"?r:null}}catch{return{retcode:n,data:null}}}function rx(t,e,n,o){let r=i3(t,e.cmd,e.data,e.retcode);if(t==="3.5"){if(!o||o.length!==12)throw new Error("tuya 3.5 frame needs a 12-byte iv");return i$(e.seq,e.cmd,r,n.sessionKey??n.localKey,o)}if(t==="3.4"){let u=n.sessionKey??n.localKey,d=e.retcode===void 0?0:4,f=r.subarray(0,d);return ex(e.seq,e.cmd,Buffer.concat([f,Xk(u,r.subarray(d))]),u)}let i=e.retcode===void 0?0:4,s=QD.has(e.cmd)?0:15,a=r.subarray(0,i+s),c=r.subarray(i+s),l=c.length?Xk(n.localKey,c):Buffer.alloc(0);return ex(e.seq,e.cmd,Buffer.concat([a,l]),null)}function a$(t,e,n){if(t==="3.5"){let c=s$(e,n.sessionKey??n.localKey);if(!c)return null;let{retcode:l,data:u}=Jk(c.plaintext);return{seq:c.seq,cmd:c.cmd,data:u,retcode:l}}let o=o$(e,t==="3.4"?n.sessionKey??n.localKey:null);if(!o)return null;if(t==="3.4"){let c=o.payload,l=0;if(c.length>=4&&(c.readUInt32BE(0)&4294967040)===0&&(c.length-4)%16===0&&(l=c.readUInt32BE(0),c=c.subarray(4)),c.length===0||c.length%16!==0)return{seq:o.seq,cmd:o.cmd,data:null,retcode:l};let u;try{u=Qk(n.sessionKey??n.localKey,c)}catch{return null}let d=Jk(u);return{seq:o.seq,cmd:o.cmd,data:d.data,retcode:l}}let r=o.payload,i=0;if(r.length>=4&&(r.readUInt32BE(0)&4294967040)===0){let c=r.subarray(4);(c.length>=15&&Yk.some(u=>c.subarray(0,3).equals(u))||c.length%16===0)&&(i=r.readUInt32BE(0),r=c)}if(r.length>=15&&Yk.some(c=>r.subarray(0,3).equals(c))&&(r=r.subarray(15)),r.length===0||r.length%16!==0)return{seq:o.seq,cmd:o.cmd,data:null,retcode:i};let s;try{s=Qk(n.localKey,r)}catch{return null}let a=Jk(s);return{seq:o.seq,cmd:o.cmd,data:a.data,retcode:i}}var s3=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t>>>0,0),e};function ox(t,e,n,o,r,i,s){let a=s===void 0?Buffer.alloc(0):s3(s);if(t==="3.5"){if(!i||i.length!==12)throw new Error("tuya 3.5 raw frame needs a 12-byte iv");return i$(e,n,Buffer.concat([a,o]),r,i)}return ex(e,n,Buffer.concat([a,Xk(r,o)]),r)}function c$(t,e,n,o=!1){if(t==="3.5"){let s=s$(e,n);if(!s)return null;let a=o&&s.plaintext.length>=4?s.plaintext.subarray(4):s.plaintext;return{seq:s.seq,cmd:s.cmd,payload:a}}let r=o$(e,n);if(!r)return null;let i=o&&r.payload.length>=4?r.payload.subarray(4):r.payload;try{return{seq:r.seq,cmd:r.cmd,payload:Qk(n,i)}}catch{return null}}function l$(t){let e=[],n=0;for(;n+16<=t.length;){let o=t.readUInt32BE(n);if(o===tx){let i=16+t.readUInt32BE(n+12);if(n+i>t.length)break;e.push(t.subarray(n,n+i)),n+=i}else if(o===Ec){if(n+18>t.length)break;let i=18+t.readUInt32BE(n+14)+4;if(n+i>t.length)break;e.push(t.subarray(n,n+i)),n+=i}else n++}return{frames:e,rest:t.subarray(n)}}var a3=6668,c3=["3.3","3.4","3.5"],l3=5e3,u3=9e3,d3=t=>t.readUInt32BE(0)===Ec?t.readUInt32BE(10):t.readUInt32BE(8),p3=new Set([Ae.SESS_KEY_NEG_START,Ae.SESS_KEY_NEG_RESP,Ae.SESS_KEY_NEG_FINISH]);function ix(t){if(!t)return{};if(t.dps&&typeof t.dps=="object")return t.dps;let e=t.data;return e&&typeof e=="object"&&e.dps?e.dps:{}}var ax=class{constructor(e,n,o,r){this.ip=e;this.version=n;this.socket=o;this.params=r;o.onData(i=>this.onData(i)),o.onClose(()=>this.onDrop(new Error("tuya socket closed"))),o.onError(i=>this.onDrop(i))}ip;version;socket;params;seq=0;buf=Buffer.alloc(0);sessionKey;pending=new Map;pushCb=null;hbTimer=null;closed=!1;goneCb=null;onPush(e){this.pushCb=e}onGone(e){this.goneCb=e}startHeartbeat(){this.hbTimer||this.version===void 0||(this.hbTimer=setInterval(()=>{if(!this.closed)try{this.socket.write(this.encode(Ae.HEART_BEAT,null))}catch{}},u3),this.hbTimer.unref?.())}async negotiate(){if(this.version==="3.3")return;let e=(0,sx.randomBytes)(16),n=await this.requestRaw(Ae.SESS_KEY_NEG_START,e);if(n.length<48)throw new Error("tuya session neg: short response");let o=n.subarray(0,16);if(!n.subarray(16,48).equals(nx(this.params.localKey,e)))throw new Error("tuya session neg: hmac mismatch");this.socket.write(ox(this.version,this.nextSeq(),Ae.SESS_KEY_NEG_FINISH,nx(this.params.localKey,o),this.params.localKey,this.iv())),this.sessionKey=n$(this.params.localKey,e,o,this.version)}async query(){let e=this.version==="3.3"?Ae.DP_QUERY:Ae.DP_QUERY_NEW,n=this.version==="3.3"?Ae.DP_QUERY_NEW:Ae.DP_QUERY,o=i=>i===Ae.DP_QUERY?{gwId:this.params.gwId,devId:this.params.gwId}:{},r=!1;try{let i=ix(await this.request(e,o(e)));if(r=!0,Object.keys(i).length>0)return i}catch{}try{let i=ix(await this.request(n,o(n)));if(Object.keys(i).length>0)return i}catch(i){if(!r)throw i}if(r)return{};throw new Error("tuya query: unanswered by DP_QUERY and its alternate")}async set(e){let n=this.version==="3.3"?Ae.CONTROL:Ae.CONTROL_NEW,o=Math.floor(Date.now()/1e3),r=this.version==="3.3"?{gwId:this.params.gwId,devId:this.params.gwId,uid:this.params.gwId,t:String(o),dps:e}:{protocol:5,t:o,data:{dps:e}};await this.request(n,r)}close(){if(!this.closed){this.closed=!0,this.goneCb=null,this.hbTimer&&clearInterval(this.hbTimer),this.hbTimer=null,this.fail(new Error("tuya session closed"));try{this.socket.end()}catch{}}}nextSeq(){return this.seq=this.seq+1&4294967295,this.seq}iv(){return this.version==="3.5"?(0,sx.randomBytes)(12):void 0}encode(e,n){return rx(this.version,{seq:this.nextSeq(),cmd:e,data:n},{localKey:this.params.localKey,...this.sessionKey?{sessionKey:this.sessionKey}:{}},this.iv())}request(e,n){let o=this.nextSeq(),r=rx(this.version,{seq:o,cmd:e,data:n},{localKey:this.params.localKey,...this.sessionKey?{sessionKey:this.sessionKey}:{}},this.iv());return this.awaitSeq(o,r)}async requestRaw(e,n){let o=this.nextSeq(),r=ox(this.version,o,e,n,this.params.localKey,this.iv()),i=await this.awaitSeq(o,r);return i&&i.__raw instanceof Buffer?i.__raw:Buffer.alloc(0)}awaitSeq(e,n){return this.closed?Promise.reject(new Error("tuya session closed")):new Promise((o,r)=>{let i=setTimeout(()=>{this.pending.delete(e),r(new Error(`tuya request timeout (${this.ip})`))},l3);i.unref?.(),this.pending.set(e,{resolve:o,reject:r,timer:i});try{this.socket.write(n)}catch(s){clearTimeout(i),this.pending.delete(e),r(s instanceof Error?s:new Error(String(s)))}})}onData(e){this.buf=this.buf.length?Buffer.concat([this.buf,e]):e;let{frames:n,rest:o}=l$(this.buf);this.buf=o;for(let r of n)this.onFrame(r)}settleNext(e,n){let o=this.pending.keys().next().value;if(o===void 0)return;let r=this.pending.get(o);clearTimeout(r.timer),this.pending.delete(o),n?r.reject(n):r.resolve(e)}onFrame(e){let n=d3(e);if(p3.has(n)){let r=c$(this.version,e,this.params.localKey,!0);this.settleNext(r?{__raw:r.payload}:null,r?void 0:new Error("tuya neg frame decode failed"));return}let o=a$(this.version,e,{localKey:this.params.localKey,...this.sessionKey?{sessionKey:this.sessionKey}:{}});if(!o){this.settleNext(null,new Error("tuya frame decode failed"));return}if(n===Ae.STATUS){let r=ix(o.data);Object.keys(r).length&&this.pushCb&&this.pushCb(r);return}n!==Ae.HEART_BEAT&&this.settleNext(o.data)}onDrop(e){if(this.closed)return;this.closed=!0,this.hbTimer&&clearInterval(this.hbTimer),this.hbTimer=null,this.fail(e);let n=this.goneCb;this.goneCb=null,n?.()}fail(e){for(let{reject:n,timer:o}of this.pending.values())clearTimeout(o),n(e);this.pending.clear()}};function cx(t=m3(),e={}){let n=e.resolveNeighborIp??(i=>se(i));async function o(i,s,a){let c=await t.connect(i,a3),l=new ax(i,a,c,{...s,version:a});try{return await l.negotiate(),l}catch(u){throw l.close(),u}}async function r(i,s){let a=[s.version,...c3.filter(l=>l!==s.version)],c=!1;for(let l of a){let u;try{u=await o(i,s,l)}catch(d){if(!c&&/ECONNREFUSED|ETIMEDOUT|timeout|unreachable|refused/i.test(d.message))return{ok:!1,reason:"unreachable"};c=!0;continue}c=!0;try{let d=await u.query();return{ok:!0,session:u,version:l,dps:d}}catch{u.close()}}return{ok:!1,reason:c?"bad-key":"unreachable"}}return{async probe(i,s){let a=await r(i,s);return a.ok?(a.session.close(),{ok:!0,version:a.version,dps:a.dps}):{ok:!1,reason:a.reason}},async open(i,s){let a=await r(i,s);if(!a.ok)throw new Error(a.reason==="unreachable"?`tuya device unreachable (${i})`:"tuya local key mismatch");return a.session.startHeartbeat(),{ip:i,version:a.version,query:()=>a.session.query(),set:c=>a.session.set(c),onPush:c=>a.session.onPush(c),onGone:c=>a.session.onGone(c),close:()=>a.session.close()}},async rediscover(i,s){return n(T(i))},close:()=>t.close()}}var f3=4e3,m3=()=>{let t=!1;return{async connect(e,n){if(t)throw new Error("tuya client closed");let o=await import("node:net");return new Promise((r,i)=>{let s=o.createConnection({host:e,port:n}),a=!1,c=setTimeout(()=>{a||(a=!0,s.destroy(),i(new Error(`tuya connect timeout (${e}:${n})`)))},f3);c.unref?.(),s.once("connect",()=>{a||(a=!0,clearTimeout(c),r({write:l=>s.write(l),onData:l=>s.on("data",l),onClose:l=>s.on("close",l),onError:l=>s.on("error",l),end:()=>s.destroy()}))}),s.once("error",l=>{a||(a=!0,clearTimeout(c),i(l))})})},close(){t=!0}}};var qt={minKelvin:2700,maxKelvin:6500},Pt=t=>typeof t=="number"&&Number.isFinite(t)?t:null,d$=t=>typeof t=="boolean"?t:null,p$=t=>typeof t=="string"&&t?t:void 0,nt=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function ho(t){return t==="dj"||t==="dd"||t==="xdd"||t==="fwd"?"light":t==="kg"||t==="tgkg"?"switch":"plug"}var f$={light:"light",plug:"plug",switch:"switch"},Cc={light:{power:"20",brightness:"22",colorTemp:"23",color:"24"},plug:{power:"1"},switch:{power:"1"}};function lx(t,e){let n=ho(t),o={kind:n},r=e?.codes??{},i=(...d)=>{for(let f of d)if(typeof r[f]=="number")return String(r[f])},s=(d,f)=>e?.ranges?.[d]??f,a=r.switch_led??r.switch_1??r.switch,c=typeof a=="number"&&a>=10||Number(r.bright_value??0)>=10||Number(r.colour_data??0)>=10;if(e?.legacy===!0&&!c)return o.power={dp:"1"},n!=="plug"&&(o.brightness={dp:"3",min:25,max:255}),n==="light"&&(o.color={dp:"5",encoding:"hex-v1"},o.mode={dp:"2",colour:"colour",white:"white"}),o;let u=i("switch_led","switch_1","switch")??Cc[n].power;if(o.power={dp:u},n==="light"||n==="switch"){let d=i("bright_value_v2","bright_value")??Cc[n].brightness;if(d){let f=r.bright_value_v2!==void 0||d===Cc[n].brightness;o.brightness={dp:d,...s("bright_value_v2",f?{min:10,max:1e3}:{min:25,max:255})}}}if(n==="light"){let d=i("temp_value_v2","temp_value")??Cc.light.colorTemp;d&&(o.colorTemperature={dp:d,maxVal:s("temp_value_v2",{min:0,max:1e3}).max});let f=i("colour_data_v2","colour_data"),m=f??Cc.light.color;m&&(o.color={dp:m,encoding:"hex-v1"}),(f!==void 0||!e)&&(o.mode={dp:i("work_mode")??"21",colour:"colour",white:"white"})}if(n==="plug"){let d=i("cur_power"),f=i("cur_current"),m=i("cur_voltage");(d||f||m)&&(o.energy={...d?{powerDp:d}:{},...f?{currentDp:f}:{},...m?{voltageDp:m}:{}})}return o}function Op(t,e){let n=p$(t);if(!n)return null;if(n.trimStart().startsWith("{")||e==="hsv-json"&&!/^[0-9a-f]+$/i.test(n))try{let i=JSON.parse(n),s=Pt(i.h),a=Pt(i.s);return s===null||a===null?null:{hue:nt(s,0,360),saturation:nt(a/10,0,100)}}catch{return null}if(n.length<12||!/^[0-9a-f]+$/i.test(n))return null;let o=parseInt(n.slice(0,4),16),r=parseInt(n.slice(4,8),16);return{hue:nt(o,0,360),saturation:nt(r/10,0,100)}}function u$(t,e,n,o=1e3){let r=nt(t,0,360),i=nt(e*10,0,1e3);if(n==="hsv-json")return JSON.stringify({h:r,s:i,v:o});let s=(a,c)=>a.toString(16).padStart(c,"0");return`${s(r,4)}${s(i,4)}${s(o,4)}`}function g3(t,e){let n=p$(t);if(!n)return null;if(n.trimStart().startsWith("{")||e==="hsv-json"&&!/^[0-9a-f]+$/i.test(n))try{let o=Pt(JSON.parse(n).v);return o===null?null:nt(o/10,0,100)}catch{return null}return n.length<12||!/^[0-9a-f]+$/i.test(n)?null:nt(parseInt(n.slice(8,12),16)/10,0,100)}var h3=(t,e,n)=>nt(1+(t-e)/(n-e)*99,1,100),y3=(t,e,n)=>nt(e+(t-1)/99*(n-e),e,n);function m$(t,e){if(e.mode&&e.color&&t[e.mode.dp]===e.mode.colour){let o=g3(t[e.color.dp],e.color.encoding);if(o!==null)return o}if(!e.brightness)return null;let n=Pt(t[e.brightness.dp]);return n!==null?h3(n,e.brightness.min,e.brightness.max):null}var g$=(t,e)=>nt(qt.minKelvin+t/e*(qt.maxKelvin-qt.minKelvin),qt.minKelvin,qt.maxKelvin),v3=(t,e)=>nt((t-qt.minKelvin)/(qt.maxKelvin-qt.minKelvin)*e,0,e);function b3(t,e){let n=[{type:"power",state:{on:e.power?d$(t[e.power.dp]):null}}];if(e.brightness&&n.push({type:"brightness",state:{level:m$(t,e)}}),e.colorTemperature){let o=Pt(t[e.colorTemperature.dp]);n.push({type:"colorTemperature",config:{minKelvin:qt.minKelvin,maxKelvin:qt.maxKelvin},state:{kelvin:o!==null&&o>0?g$(o,e.colorTemperature.maxVal):null}})}if(e.color){let o=Op(t[e.color.dp],e.color.encoding);n.push({type:"color",config:{modes:["hs"]},state:{hue:o?.hue??null,saturation:o?.saturation??null}})}return e.energy&&(e.energy.powerDp||e.energy.currentDp||e.energy.voltageDp)&&n.push({type:"energyMeter",state:{power:null,energy:null,voltage:null,current:null}}),n}function Rc(t,e){let n=[];e.power&&t[e.power.dp]!==void 0&&n.push({type:"power",state:{on:d$(t[e.power.dp])}});let o=!!(e.mode&&e.color&&t[e.mode.dp]===e.mode.colour);if(e.brightness&&(t[e.brightness.dp]!==void 0||o&&t[e.color.dp]!==void 0)&&n.push({type:"brightness",state:{level:m$(t,e)}}),e.colorTemperature&&t[e.colorTemperature.dp]!==void 0){let r=Pt(t[e.colorTemperature.dp]);n.push({type:"colorTemperature",state:{kelvin:r!==null&&r>0?g$(r,e.colorTemperature.maxVal):null}})}if(e.color&&t[e.color.dp]!==void 0){let r=Op(t[e.color.dp],e.color.encoding);n.push({type:"color",state:{hue:r?.hue??null,saturation:r?.saturation??null}})}if(e.energy){let r=e.energy.powerDp?Pt(t[e.energy.powerDp]):null,i=e.energy.currentDp?Pt(t[e.energy.currentDp]):null,s=e.energy.voltageDp?Pt(t[e.energy.voltageDp]):null;(r!==null||i!==null||s!==null)&&n.push({type:"energyMeter",state:{power:r!==null?r/10:null,energy:null,current:i!==null?i/1e3:null,voltage:s!==null?s/10:null}})}return n}function h$(t,e,n){let o=T(n.mac);return{source:{provider:"tuya",providerAccountId:n.accountId,nativeId:o,...n.category?{nativeType:n.category}:{},reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:f$[e.kind],name:n.name,manufacturer:"Tuya",model:n.model??null,capabilities:b3(t,e)}}function ux(t,e,n){return{source:{provider:"tuya",providerAccountId:n.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:n.now},fingerprints:[`mac:${t.key}`],type:f$[e.kind],name:n.name,manufacturer:"Tuya",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function y$(t,e,n,o,r){let i=o&&typeof o=="object"?o:{},s=()=>{throw new Error(`tuya ${t.kind} does not support ${e}.${n}`)};if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){t.power||s();let a;if(n==="toggle"){if(r.currentOn===void 0)throw new Error("tuya toggle needs the current power state (pre-read failed)");a=!r.currentOn}else a=n==="turnOn";return{dps:{[t.power.dp]:a},optimistic:{type:"power",state:{on:a}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){t.brightness||s();let a=t.brightness,c;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("tuya adjustBrightness needs the current level (pre-read failed)");c=nt(r.currentLevel+(Pt(i.delta)??0),1,100)}else c=nt(Pt(i.level)??1,1,100);if(t.mode&&t.color&&r.currentMode===t.mode.colour&&r.currentColor){let l=nt(Math.round(c*10),10,1e3);return{dps:{[t.mode.dp]:t.mode.colour,[t.color.dp]:u$(r.currentColor.hue,r.currentColor.saturation,t.color.encoding,l)},optimistic:{type:"brightness",state:{level:c}}}}return{dps:{[a.dp]:y3(c,a.min,a.max)},optimistic:{type:"brightness",state:{level:c}}}}if(e==="colorTemperature"&&n==="setColorTemperature"){t.colorTemperature||s();let a=t.colorTemperature,c=nt(Pt(i.kelvin)??qt.minKelvin,qt.minKelvin,qt.maxKelvin),l={};return t.mode&&(l[t.mode.dp]=t.mode.white),l[a.dp]=v3(c,a.maxVal),{dps:l,optimistic:{type:"colorTemperature",state:{kelvin:c}}}}if(e==="color"&&n==="setColor"){t.color||s();let a=t.color,c=nt(Pt(i.hue)??0,0,360),l=nt(Pt(i.saturation)??0,0,100),u={};return t.mode&&(u[t.mode.dp]=t.mode.colour),u[a.dp]=u$(c,l,a.encoding),{dps:u,optimistic:{type:"color",state:{hue:c,saturation:l}}}}return s()}function v$(t,e,n){return Rc(t,e).find(o=>o.type===n)?.state}function b$(t,e){let n=e&&typeof e=="object"?e:{},o={},r=i=>{i&&n[i]!==void 0&&(o[i]=n[i])};return r(t.power?.dp),r(t.mode?.dp),r(t.brightness?.dp),r(t.colorTemperature?.dp),r(t.color?.dp),o}var w3=15e3,dx="no local key for this device \u2014 run the Tuya key wizard (acbridge link tuya)",px="local key mismatch \u2014 re-pairing rotates the key; re-run the Tuya key wizard",k3=async(t,e)=>{let n=await fetch(t,{method:e.method,headers:e.headers,...e.body!==void 0?{body:e.body}:{}});return{status:n.status,text:()=>n.text()}};function Ac(t){return t==="light"?"light":t==="switch"?"switch":"plug"}var x3=t=>t>0?new Promise(e=>setTimeout(e,t).unref?.()):Promise.resolve(),Lp=class{constructor(e,n,o=cx,r=k3){this.accountId=e;this.cfg=n;this.clientFactory=o;this.cloudFetch=r}accountId;cfg;clientFactory;cloudFetch;provider="tuya";reachability="local";client=null;keystore={};runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory(),this.keystore=Cn(await e.localSecrets.read("keystore"))}async link(e,n){if(e.kind!=="cloudCredentials")return{ok:!1,error:"Tuya devices link via the key wizard (`acbridge link tuya`) \u2014 paste your iot.tuya.com project's Access ID/Secret + region.",retryable:!1};let o={clientId:e.clientId,clientSecret:e.clientSecret,region:e.region};try{let{keystore:r}=await rc({creds:o,fetch:this.cloudFetch}),i=oc(Cn(await n.localSecrets.read("keystore")),r);return await n.localSecrets.write("keystore",JSON.stringify(i)),await n.localSecrets.write("cloud",JSON.stringify(o)),this.keystore=i,{ok:!0,accountId:this.accountId}}catch(r){return{ok:!1,error:r instanceof Ue?r.message:`Tuya key wizard failed: ${r.message}`,retryable:!1}}}async unlink(e){}async discover(){let e=[];for(let n of this.cfg.devices){let o=T(n.key),r=this.entryForMac(o);if(!r){e.push(this.offlineFor(n,void 0));continue}let i=lx(r.entry.category,r.entry.dpModel),s=n.name??r.entry.name,a={ip:n.ip,gwId:r.gwId,params:{gwId:r.gwId,localKey:Buffer.from(r.entry.localKey,"utf8"),version:r.entry.protoVersion??"3.3"},dpMap:i,name:s,...n.model?{model:n.model}:{},category:r.entry.category,handle:null,online:!1};this.runtime.set(o,a);let c=await this.ensureAndQuery(o).catch(()=>null);c?(a.online=!0,e.push(h$(c,i,{accountId:this.accountId,mac:o,name:s,category:r.entry.category,...a.model?{model:a.model}:{},now:Date.now()})),this.attachPush(o,a)):e.push(ux(n,i,{accountId:this.accountId,name:s,now:Date.now()}))}return{devices:e,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.ensureAndQuery(r);i.online=!0,o.push({nativeId:r,patch:Rc(s,i.dpMap),online:!0,ts:Date.now()})}catch{i.online=!1,this.dropHandle(i),o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown tuya device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let u=await this.ensureAndQuery(e),d=Rc(u,s.dpMap),f=d.find(g=>g.type==="power")?.state,m=d.find(g=>g.type==="brightness")?.state;typeof f?.on=="boolean"&&(a.currentOn=f.on),typeof m?.level=="number"&&(a.currentLevel=m.level)}if((o==="setBrightness"||o==="adjustBrightness")&&s.dpMap.mode&&s.dpMap.color){let u=s.lastDps??{};if(u[s.dpMap.mode.dp]===s.dpMap.mode.colour){a.currentMode=s.dpMap.mode.colour;let d=Op(u[s.dpMap.color.dp],s.dpMap.color.encoding);d&&(a.currentColor=d)}}let{dps:c,optimistic:l}=y$(s.dpMap,n,o,r,a);if(await this.withHandle(e,u=>u.set(c)),this.recordDps(e,c),s.online=!0,i?.readAfter){await x3(this.cfg.settleMs??0);let u=v$(await this.ensureAndQuery(e),s.dpMap,n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){this.onState=e;for(let[o,r]of this.runtime)r.handle&&this.attachPush(o,r);return this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??w3),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null);for(let e of this.runtime.values())this.dropHandle(e);this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}attachPush(e,n){n.handle?.onPush(o=>{this.disposed||(this.recordDps(e,o),this.onState?.({nativeId:e,patch:Rc(o,n.dpMap),online:!0,ts:Date.now()}))})}recordDps(e,n){let o=this.runtime.get(e);o&&n&&Object.keys(n).length&&(o.lastDps={...o.lastDps??{},...n})}async ensureAndQuery(e){let n=await this.withHandle(e,o=>o.query());return this.recordDps(e,n),n}async captureNative(e){let n=this.runtime.get(e);if(n){if(!n.lastDps||Object.keys(n.lastDps).length===0)try{await this.ensureAndQuery(e)}catch{return}return n.lastDps?{...n.lastDps}:void 0}}async restoreNative(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown tuya device ${e}`);let r=b$(o.dpMap,n);Object.keys(r).length!==0&&(await this.withHandle(e,i=>i.set(r)),this.recordDps(e,r),o.online=!0)}withHandle(e,n){let o=this.runtime.get(e);if(!o)return Promise.reject(new Error(`unknown tuya device ${e}`));let r=(o.opChain??Promise.resolve()).then(()=>this.runOp(e,o,n));return o.opChain=r.catch(()=>{}),r}async runOp(e,n,o){let r=this.need();try{return await o(await this.ensureHandle(e,n,r))}catch(i){if(this.disposed)throw i;this.dropHandle(n);let s=await r.rediscover(e,[n.ip]);if(!s||s===n.ip)throw i;n.ip=s,this.cfg.onIpChange?.(e,s);let a=await this.ensureHandle(e,n,r);return o(a)}}async ensureHandle(e,n,o){if(n.handle)return n.handle;let r=await o.open(n.ip,n.params);return n.handle=r,r.onGone(()=>{n.handle===r&&(n.handle=null,n.online=!1,this.disposed||this.onState?.({nativeId:e,patch:[],online:!1,ts:Date.now()}))}),this.onState&&this.attachPush(e,n),r}dropHandle(e){try{e.handle?.close()}catch{}e.handle=null}entryForMac(e){for(let[n,o]of Object.entries(this.keystore))if(o.mac&&T(o.mac)===e)return{gwId:n,entry:o}}offlineFor(e,n){let o=lx(n?.category,n?.dpModel);return ux(e,o,{accountId:this.accountId,name:e.name??n?.name??"Tuya device",now:Date.now()})}need(){if(!this.client)throw new Error("Tuya adapter not initialized");return this.client}};function S3(){let t={};return{read:async()=>t,write:async e=>{t=e}}}function w$(t=cx,e={}){let n=t(),o=e.keystore??S3(),r=e.resolveMac??(i=>dt(i));return async(i,s,a)=>{let c=await o.read(),l=a?.vendorId,u=l?c[l]:void 0;if(!l||!u)return{veto:dx};let d={gwId:l,localKey:Buffer.from(u.localKey,"utf8"),version:u.protoVersion??"3.3"},f=await n.probe(i,d).catch(()=>null);if(!f)return null;if(!f.ok)return f.reason==="unreachable"?null:{veto:px};let m=a?.mac?T(a.mac):await r(i);if(m){c[l]={...u,mac:T(m),protoVersion:f.version};try{await o.write(c)}catch{}}let g=ho(u.category);return{...m?{mac:T(m)}:{},name:u.name,...u.productId?{model:u.productId}:{},expectedType:Ac(g)}}}function k$(t){let e=ho(t);return e==="light"?["power","brightness","colorTemperature","color"]:e==="switch"?["power","brightness"]:["power"]}var x$=6e4,_3=5*6e4,I3=15*6e4,T3=5*6e4,E3=async(t,e)=>{let n=await fetch(t,{method:e.method,headers:e.headers,...e.body!==void 0?{body:e.body}:{}});return{status:n.status,text:()=>n.text()}};function C3(t){let e=new Map;for(let[n,o]of Object.entries(Cn(t)))o.mac&&e.set(n,o.mac);return e}var Np=class{constructor(e,n={},o=eA,r=E3,i=Date.now){this.accountId=e;this.cfg=n;this.clientFactory=o;this.fetchLike=r;this.now=i}accountId;cfg;clientFactory;fetchLike;now;provider="tuya";reachability="cloud";client=null;creds=null;runtime=new Map;macs=new Map;lastOnlineRefreshAt=Number.NEGATIVE_INFINITY;onState=null;onEdge=null;pollTimer=null;nextDelayMs=x$;log=()=>{};disposed=!1;get stalenessMs(){return this.cfg.stalenessMs??_3}get maxBackoffMs(){return this.cfg.maxBackoffMs??I3}get basePollMs(){return this.cfg.pollMs??(this.creds?.pollSeconds?this.creds.pollSeconds*1e3:x$)}get onlineRefreshMs(){return this.cfg.onlineRefreshMs??T3}get nextPollDelayMs(){return this.nextDelayMs}async init(e){this.log=e.log,this.creds=si(await e.localSecrets.read("cloud")),this.creds&&(this.client=this.buildClient(this.creds)),this.nextDelayMs=this.basePollMs,this.macs=C3(await e.localSecrets.read("keystore"))}async link(e,n){let o=si(await n.localSecrets.read("cloud")),r;if(e.kind==="cloudCredentials"&&e.clientId&&e.clientSecret)r={clientId:e.clientId,clientSecret:e.clientSecret,region:e.region||o?.region||"eu",...o?.pollSeconds?{pollSeconds:o.pollSeconds}:{}};else if(o)r=o;else return{ok:!1,error:"Set up Tuya first: run the key wizard (`acbridge link tuya`) with your iot.tuya.com project's Access ID/Secret.",retryable:!1};try{let i=this.buildClient(r);return await i.devices(),await n.localSecrets.write("cloud",JSON.stringify(r)),this.creds=r,this.client=i,this.nextDelayMs=this.basePollMs,{ok:!0,accountId:this.accountId}}catch(i){return{ok:!1,error:i instanceof Ue?i.message:`Tuya cloud link failed: ${i.message}`,retryable:!ic(i)&&!(i instanceof Ue)}}}async unlink(e){}async discover(){if(!this.client)return{devices:[],rooms:[]};let e;try{e=await this.client.devices()}catch(o){return this.noteCloudError(o,"discover"),{devices:[],rooms:[]}}let n=[];for(let o of e){if(!o.id||!Vd(o.category))continue;let r=this.macs.get(o.id),i={id:o.id,name:o.name??o.category??"Tuya sensor",category:o.category??"",...o.product_id?{productId:o.product_id}:{},...r?{mac:r}:{},...o.online!==void 0?{online:o.online}:{}},s=await this.client.model(o.id).catch(()=>{}),a=new Set(Object.keys(s?.codes??{}));a.size===0&&this.log(`[tuya-cloud] no data model for ${o.id} (${o.category??"?"}) \u2014 capabilities fall back to whatever the shadow reports`);let c=await this.client.properties(o.id).catch(()=>[]),l=Jd(c,a),u={row:i,codes:a,lastBinaryTs:new Map,motionUntil:new Map,lastEmittedActive:new Map,lastEmittedOnline:i.online??!0},d=this.seed(u,l);this.runtime.set(o.id,u),n.push(ZR(i,d,{accountId:this.accountId,now:this.now()}))}return this.lastOnlineRefreshAt=this.now(),{devices:n,rooms:[]}}async getState(e){if(!this.client)return[];let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=Jd(await this.client.properties(r),i.codes);o.push({nativeId:r,patch:WR(s,this.now()),online:this.onlineOf(i),ts:this.now()})}catch(s){this.noteCloudError(s,"getState"),o.push({nativeId:r,patch:[],online:!1,ts:this.now()})}}return o}async sendCommand(){throw new Error("Tuya cloud sensors are read-only (no commands).")}subscribe(e,n){return this.onState=e,this.onEdge=n,this.arm(this.basePollMs),()=>{this.stopTimer(),this.onState=null,this.onEdge=null}}async dispose(){this.disposed=!0,this.stopTimer(),this.client=null}async poll(){if(!(this.disposed||!this.client))try{await this.refreshOnlineFlags();for(let e of[...this.runtime.values()]){let{patches:n,edges:o}=await this.pollDevice(e),r=this.onlineOf(e);(n.length||r!==e.lastEmittedOnline)&&(e.lastEmittedOnline=r,this.onState?.({nativeId:e.row.id,patch:n,online:r,ts:this.now()}));for(let i of o)this.onEdge?.({nativeId:e.row.id,capability:"binarySensor",instance:i.code,event:i.event,ts:i.ts})}this.nextDelayMs=this.basePollMs}catch(e){if(ic(e)||nk(e)){for(let n of this.runtime.values())this.onState?.({nativeId:n.row.id,patch:[],online:!1,ts:this.now()});this.nextDelayMs=Math.min(this.maxBackoffMs,Math.max(this.basePollMs,this.nextDelayMs)*2),this.log(ic(e)?`tuya cloud: reads paused \u2014 ${e.message}`:"tuya cloud: rate-limited, backing off")}else this.nextDelayMs=this.basePollMs}}buildClient(e){return this.clientFactory({creds:e,fetch:this.fetchLike,now:this.now})}onlineOf(e){return e.row.online??!0}async refreshOnlineFlags(){if(!this.client||this.runtime.size===0)return;let e=this.now();if(e-this.lastOnlineRefreshAt<this.onlineRefreshMs)return;this.lastOnlineRefreshAt=e;let n=await this.client.devices();for(let o of n){let r=this.runtime.get(o.id);r&&o.online!==void 0&&(r.row.online=o.online)}}seed(e,n){let o=this.now(),r=GR(n);for(let i of n.binary){i.active===!0&&i.reportTs!==void 0&&(e.lastBinaryTs.set(i.code,i.reportTs),e.motionUntil.set(i.code,i.reportTs+this.stalenessMs));let s=this.effectiveActive(e,i,o);e.lastEmittedActive.set(i.code,s);let a=r.find(c=>c.type==="binarySensor"&&c.instance===i.code);a&&a.type==="binarySensor"&&(a.state={active:s,lastChanged:e.lastBinaryTs.get(i.code)??i.reportTs??null})}return r}effectiveActive(e,n,o){let r=e.motionUntil.get(n.code);return r!==void 0?o<r:n.active}async pollDevice(e){let n=Jd(await this.client.properties(e.row.id),e.codes),o=this.now(),r=[],i=[];for(let s of n.binary){s.active===!0&&s.reportTs!==void 0&&s.reportTs>(e.lastBinaryTs.get(s.code)??0)&&(e.lastBinaryTs.set(s.code,s.reportTs),e.motionUntil.set(s.code,s.reportTs+this.stalenessMs),i.push({code:s.code,event:s.sensorType==="motion"?"motion":s.sensorType,ts:s.reportTs}));let a=this.effectiveActive(e,s,o);e.lastEmittedActive.get(s.code)!==a&&(e.lastEmittedActive.set(s.code,a),r.push({type:"binarySensor",instance:s.code,state:{active:a,lastChanged:e.lastBinaryTs.get(s.code)??s.reportTs??null}}))}for(let s of n.numeric)r.push({type:"sensor",instance:s.code,state:{value:s.value,ts:s.reportTs??o}});return n.battery&&r.push({type:"battery",state:{level:n.battery.level,low:Yd(n.battery)}}),{patches:r,edges:i}}noteCloudError(e,n){ic(e)?this.log(`tuya cloud (${n}): reads paused \u2014 ${e.message}`):nk(e)&&this.log(`tuya cloud (${n}): rate-limited`)}arm(e){this.disposed||(this.stopTimer(),this.pollTimer=setTimeout(()=>{this.poll().finally(()=>{!this.disposed&&this.onState&&this.arm(this.nextDelayMs)})},e),this.pollTimer.unref?.())}stopTimer(){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null)}};var $s=require("node:crypto");var ci=t=>typeof t=="number"&&Number.isFinite(t)?t:null,yo=t=>typeof t=="string"&&t?t:void 0,Ds=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,R3=t=>Array.isArray(t)?t:[],S$=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t))),_$=t=>(0,$s.createHash)("md5").update(t,"utf8").digest();function A3(t,e,n){let o=(0,$s.createCipheriv)("aes-128-cbc",_$(e),n);return Buffer.concat([o.update(Buffer.from(t,"utf8")),o.final()]).toString("base64")}function P3(t,e,n){let o=(0,$s.createDecipheriv)("aes-128-cbc",_$(e),Buffer.from(n,"base64"));return Buffer.concat([o.update(Buffer.from(t,"base64")),o.final()]).toString("utf8")}function I$(t,e,n){let o={sequence:n.sequence,deviceid:e.deviceid,selfApikey:"123"};return e.devicekey?(o.encrypt=!0,o.iv=n.iv.toString("base64"),o.data=A3(JSON.stringify(t),e.devicekey,n.iv)):o.data=t,o}function T$(t,e){let n=ci(t.error);if(n!==null&&n!==0)throw new Error(`ewelink error ${n}`);let o=t.data;if(typeof o=="string"){let r=yo(t.iv);if(!e.devicekey||!r)throw new Error("ewelink encrypted reply without a devicekey/iv");return Ds(JSON.parse(P3(o,e.devicekey,r)))??{}}return Ds(o)??{}}var vo=t=>typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&t.trim()!==""&&Number.isFinite(Number(t))?Number(t):null;function E$(t){return{power:vo(t.power),energy:null,voltage:vo(t.voltage),current:vo(t.current)}}var C$=t=>{let e=vo(t.temperature);return{value:e!==null&&e>-270&&e<270?Math.round(e*10)/10:null}},R$=t=>({value:vo(t.humidity)});function A$(t){let e=Array.isArray(t.switches),n=ci(t.bright)!==null;return{type:n?"light":"plug",multi:e,hasBrightness:n,hasEnergy:vo(t.power)!==null,hasTemp:vo(t.temperature)!==null,hasHumidity:vo(t.humidity)!==null}}function P$(t){let e=yo(t.switch);if(e)return e==="on";for(let n of R3(t.switches)){let o=Ds(n);if(o&&(ci(o.outlet)??0)===0)return yo(o.switch)==="on"}return null}function Mp(t,e){let n=[{type:"power",state:{on:P$(e)}}];return t.hasBrightness&&n.push({type:"brightness",state:{level:ci(e.bright)}}),t.hasEnergy&&n.push({type:"energyMeter",state:E$(e)}),t.hasTemp&&n.push({type:"sensor",instance:"temperature",state:C$(e)}),t.hasHumidity&&n.push({type:"sensor",instance:"humidity",state:R$(e)}),n}function D$(t,e,n){let o=T(n.mac),r=[{type:"power",state:{on:P$(e)}}];return t.hasBrightness&&r.push({type:"brightness",state:{level:ci(e.bright)}}),t.hasEnergy&&r.push({type:"energyMeter",state:E$(e)}),t.hasTemp&&r.push({type:"sensor",instance:"temperature",config:{measurement:"temperature",unit:"Cel"},state:C$(e)}),t.hasHumidity&&r.push({type:"sensor",instance:"humidity",config:{measurement:"humidity",unit:"%"},state:R$(e)}),{source:{provider:"ewelink",providerAccountId:n.accountId,nativeId:o,nativeType:n.deviceid,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:t.type,name:n.nameOverride??"SONOFF device",manufacturer:"SONOFF (ITEAD)",model:null,capabilities:r}}function $$(t,e){return{source:{provider:"ewelink",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"plug",name:t.name??"SONOFF device",manufacturer:"SONOFF (ITEAD)",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function O$(t,e,n,o,r){let i=Ds(o)??{},s=()=>{throw new Error(`ewelink ${t.type} does not support ${e}.${n}`)},a=c=>t.multi?{action:"switches",payload:{switches:[{switch:c?"on":"off",outlet:0}]}}:{action:"switch",payload:{switch:c?"on":"off"}};if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){let c;if(n==="toggle"){if(r.currentOn===void 0)throw new Error("ewelink toggle needs the current power state (pre-read failed)");c=!r.currentOn}else c=n==="turnOn";return{command:a(c),optimistic:{type:"power",state:{on:c}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){t.hasBrightness||s();let c;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("ewelink adjustBrightness needs the current level (pre-read failed)");c=S$(r.currentLevel+(ci(i.delta)??0),0,100)}else c=S$(ci(i.level)??0,0,100);return c===0?{command:a(!1),optimistic:{type:"brightness",state:{level:0}}}:{command:{action:"dimmable",payload:{switch:"on",bright:Math.max(1,c)}},optimistic:{type:"brightness",state:{level:Math.max(1,c)}}}}return s()}function L$(t,e,n){return Mp(t,e).find(o=>o.type===n)?.state}function Pc(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}let n=Ds(e);if(!n)return{};let o={};for(let[r,i]of Object.entries(n)){let s=Ds(i),a=s?yo(s.devicekey):void 0;a&&(o[r]={devicekey:a,...s&&yo(s.name)?{name:yo(s.name)}:{},...s&&yo(s.mac)?{mac:T(yo(s.mac))}:{}})}return o}var N$=8081,D3="no eWeLink key for this device \u2014 run the eWeLink wizard (acbridge link ewelink)",$3=15e3;function M$(t){let e=new Map;for(let[n,o]of Object.entries(t))o.mac&&e.set(T(o.mac),{deviceid:n,devicekey:o.devicekey});return e}var Up=class{constructor(e,n,o=F$){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="ewelink";reachability="local";client=null;byMac=new Map;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory(),this.byMac=M$(Pc(await e.localSecrets.read("keystore")))}async link(e,n){return{ok:!1,error:"SONOFF/eWeLink links via the wizard (`acbridge link ewelink`) \u2014 sign in once so the hub caches each device's LAN key.",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=this.byMac.get(o.key),i=r?{deviceid:r.deviceid,devicekey:r.devicekey}:o.providerDeviceId?{deviceid:o.providerDeviceId}:null,s=i?await this.locate(e,o,i):null;s&&i?(this.runtime.set(o.key,{ip:s.ip,dev:i,profile:s.profile,online:!0}),n.push(D$(s.profile,s.state,{accountId:this.accountId,mac:o.key,deviceid:i.deviceid,now:Date.now(),...o.name?{nameOverride:o.name}:{}}))):n.push($$(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshState(r);i.online=!0,o.push({nativeId:r,patch:Mp(i.profile,s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown ewelink device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let u=Mp(s.profile,await this.freshState(e)),d=u.find(m=>m.type==="power")?.state,f=u.find(m=>m.type==="brightness")?.state;typeof d?.on=="boolean"&&(a.currentOn=d.on),typeof f?.level=="number"&&(a.currentLevel=f.level)}let{command:c,optimistic:l}=O$(s.profile,n,o,r,a);if(await this.call(e,c.action,c.payload),s.online=!0,i?.readAfter){let u=L$(s.profile,await this.freshState(e),n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??$3),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}call(e,n,o){let r=this.runtime.get(e);if(!r)throw new Error(`unknown ewelink device ${e}`);return he({ip:r.ip,fn:i=>this.need().request(i,n,o,r.dev),rediscover:()=>this.need().rediscover(e),onNewIp:i=>{r.ip=i,this.cfg.onIpChange?.(e,i)},bail:()=>this.disposed})}async freshState(e){return this.call(e,"info",{})}async locate(e,n,o){let r=async i=>{let s=await e.request(i,"info",{},o);return{ip:i,state:s,profile:A$(s)}};try{return await r(n.ip)}catch{try{let i=await e.rediscover(n.key);if(!i||i===n.ip)return null;let s=await r(i);return this.cfg.onIpChange?.(n.key,i),s}catch{return null}}}need(){if(!this.client)throw new Error("eWeLink adapter not initialized");return this.client}};function U$(t,e=F$){let n=e();return async(o,r,i)=>{let s=i?.mac?T(i.mac):await n.macForIp(o).then(l=>l?T(l):void 0).catch(()=>{});if(!s)return null;let a=M$(t()).get(s);if(a)try{await n.request(o,"info",{},{deviceid:a.deviceid,devicekey:a.devicekey});let l=t()[a.deviceid]?.name;return{mac:s,providerDeviceId:a.deviceid,...l?{name:l}:{}}}catch{return null}let c=i?.vendorId;if(!c)return{veto:D3};try{return await n.request(o,"info",{},{deviceid:c}),{mac:s,providerDeviceId:c}}catch{return null}}}var O3=4e3,F$=()=>{let t=!1,e=0;return{async request(n,o,r,i){if(t)throw new Error("ewelink client closed");let[s,a]=await Promise.all([import("node:http"),import("node:crypto")]),c=Math.max(e+1,Date.now());e=c;let l=JSON.stringify(I$(r,i,{sequence:String(c),iv:a.randomBytes(16)})),u=await new Promise((d,f)=>{let m=s.request({host:n,port:N$,method:"POST",path:`/zeroconf/${o}`,headers:{"content-type":"application/json","content-length":Buffer.byteLength(l)}},h=>{let y="";h.setEncoding("utf8"),h.on("data",b=>y+=b),h.on("end",()=>h.statusCode&&h.statusCode>=200&&h.statusCode<300?d(y):f(new Error(`ewelink HTTP ${h.statusCode}`)))}),g=setTimeout(()=>m.destroy(new Error(`ewelink request timeout (${n}:${N$})`)),O3);g.unref?.(),m.on("error",h=>{clearTimeout(g),f(h instanceof Error?h:new Error(String(h)))}),m.on("close",()=>clearTimeout(g)),m.write(l),m.end()});return T$(JSON.parse(u),i)},macForIp(n){return dt(n)},rediscover(n){return se(n)},close(){t=!0}}};var B$=require("node:crypto");var Dt={minKelvin:2700,maxKelvin:6500},bo={rgb:1,temperature:2,luminance:4},rt=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Fp=t=>typeof t=="string"&&t?t:void 0,ze=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,Bp=t=>Array.isArray(t)?t:[],Fr=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function L3(t,e,n){return(0,B$.createHash)("md5").update(`${t}${e}${n}`,"utf8").digest("hex")}function j$(t,e,n,o,r){return{header:{messageId:r.messageId,namespace:t,method:e,payloadVersion:1,triggerSrc:"MerossClient",from:"MerossClient",timestamp:r.timestamp,timestampMs:0,sign:L3(r.messageId,o,r.timestamp)},payload:n}}function Os(t){let e=ze(t),n=ze(e?.payload);if(!n)throw new Error("meross reply has no payload");return n}var N3=t=>Fr((Fr(t,Dt.minKelvin,Dt.maxKelvin)-Dt.minKelvin)/(Dt.maxKelvin-Dt.minKelvin)*100,0,100),M3=t=>Fr(Dt.minKelvin+Fr(t,0,100)/100*(Dt.maxKelvin-Dt.minKelvin),Dt.minKelvin,Dt.maxKelvin);function U3(t,e){let n=(t%360+360)%360/60,r=Math.max(0,Math.min(100,e))/100,i=r*(1-Math.abs(n%2-1)),s=1-r,[a,c,l]=n<1?[r,i,0]:n<2?[i,r,0]:n<3?[0,r,i]:n<4?[0,i,r]:n<5?[i,0,r]:[r,0,i],u=Math.round((a+s)*255),d=Math.round((c+s)*255),f=Math.round((l+s)*255);return u*65536+d*256+f}function F3(t){let e=(t>>16&255)/255,n=(t>>8&255)/255,o=(t&255)/255,r=Math.max(e,n,o),i=Math.min(e,n,o),s=r-i;if(s===0||r===0)return{hue:0,saturation:0};let a;return r===e?a=(n-o)/s%6:r===n?a=(o-e)/s+2:a=(e-n)/s+4,{hue:Math.round(((a*60+360)%360+360)%360),saturation:Math.round(s/r*100)}}function z$(t){let e=s=>s in t,n=ze(t["Appliance.Control.Light"]),o=n?rt(n.capacity)??0:0,r=e("Appliance.Control.Light"),i=e("Appliance.GarageDoor.State");return{type:i?"garageDoor":r?"light":"plug",hasBrightness:r&&(o&bo.luminance)!==0,hasCt:r&&(o&bo.temperature)!==0,hasColor:r&&(o&bo.rgb)!==0,hasEnergy:e("Appliance.Control.Electricity"),garage:i}}function B3(t){for(let e of Bp(t.garageDoor)){let n=ze(e);if(n&&(rt(n.channel)??0)===0)return rt(n.open)===1}return null}function H$(t){let e=ze(ze(t.all)?.digest)??{},n=B3(e);return{state:n===null?"unknown":n?"open":"closed"}}function j3(t){let e=Bp(t.togglex);for(let o of e){let r=ze(o);if(r&&(rt(r.channel)??0)===0)return rt(r.onoff)===1}let n=ze(t.toggle);return n?rt(n.onoff)===1:null}function K$(t,e){let n=ze(e.all)??{},o=ze(n.digest)??{},r=j3(o),i=ze(o.light),s=null,a=null,c=null,l=null;if(i){let u=rt(i.capacity)??0;if(t.hasBrightness&&(s=rt(i.luminance)),t.hasCt&&(u&bo.temperature)!==0&&(a=M3(rt(i.temperature)??0)),t.hasColor&&(u&bo.rgb)!==0){let d=F3(rt(i.rgb)??0);c=d.hue,l=d.saturation}}return{on:r,level:s,kelvin:a,hue:c,saturation:l}}function jp(t,e){if(t.garage)return[{type:"cover",state:H$(e)}];let n=K$(t,e),o=[{type:"power",state:{on:n.on}}];return t.hasBrightness&&o.push({type:"brightness",state:{level:n.level}}),t.hasCt&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),t.hasColor&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),o}function G$(t){let e=ze(t.electricity)??{},n=rt(e.power);return{type:"energyMeter",state:{power:n!==null?Math.round(n/10)/100:null}}}function fx(t){let e=ze(ze(ze(t.all)?.system)?.hardware)??{},n=Fp(e.macAddress),o=Fp(e.type);return{...n?{mac:T(n)}:{},...o?{model:o}:{}}}function W$(t,e,n){let o=T(n.mac);if(t.garage)return{source:{provider:"meross",providerAccountId:n.accountId,nativeId:o,...n.model?{nativeType:n.model}:{},reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:"garageDoor",name:n.nameOverride??"Meross garage",manufacturer:"Meross",model:n.model??null,capabilities:[{type:"cover",config:{kind:"garage",supportsPosition:!1,supportsTilt:!1},state:H$(e)}]};let r=K$(t,e),i=[{type:"power",state:{on:r.on}}];return t.hasBrightness&&i.push({type:"brightness",state:{level:r.level}}),t.hasCt&&i.push({type:"colorTemperature",config:Dt,state:{kelvin:r.kelvin}}),t.hasColor&&i.push({type:"color",config:{modes:["hs"]},state:{hue:r.hue,saturation:r.saturation}}),t.hasEnergy&&i.push({type:"energyMeter",state:{power:null}}),{source:{provider:"meross",providerAccountId:n.accountId,nativeId:o,...n.model?{nativeType:n.model}:{},reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${o}`],type:t.type,name:n.nameOverride??"Meross device",manufacturer:"Meross",model:n.model??null,capabilities:i}}function Z$(t,e){return{source:{provider:"meross",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"plug",name:t.name??"Meross device",manufacturer:"Meross",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function Dc(t){let e=ze(ze(t.all)?.digest)??{},n=[];for(let o of Bp(e.togglex)){let r=ze(o),i=r?rt(r.channel):null;r&&i!==null&&i>=1&&n.push({channel:i,on:rt(r.onoff)===1})}return n.length>0?n.sort((o,r)=>o.channel-r.channel):null}function q$(t,e){let n=T(e.mac);return t.map(o=>{let r=De(n,String(o.channel));return{source:{provider:"meross",providerAccountId:e.accountId,nativeId:r,reachability:"local",online:!0,lastSeen:e.now},fingerprints:[Ur("meross",e.accountId,r)],type:"plug",name:`Outlet ${o.channel}`,manufacturer:"Meross",model:e.model??null,parentNativeId:n,capabilities:[{type:"power",state:{on:o.on}}]}})}function V$(t,e){let n=Dc(t);if(!n)return[];let o=T(e);return n.map(r=>({nativeId:De(o,String(r.channel)),patch:[{type:"power",state:{on:r.on}}]}))}function mx(t,e){return Dc(t)?.find(n=>n.channel===e)?.on??null}function J$(t,e){return{namespace:"Appliance.Control.ToggleX",payload:{togglex:{channel:t,onoff:e?1:0}}}}function Y$(t,e,n,o,r){let i=ze(o)??{},s=()=>{throw new Error(`meross ${t.type} does not support ${e}.${n}`)},a=(c,l)=>({namespace:"Appliance.Control.Light",payload:{light:{channel:0,capacity:l,...c}}});if(e==="cover"&&(n==="open"||n==="close")){t.garage||s();let c=n==="open";return{command:{namespace:"Appliance.GarageDoor.State",payload:{state:{channel:0,open:c?1:0}}},optimistic:{type:"cover",state:{state:c?"opening":"closing"}}}}if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){let c;if(n==="toggle"){if(r.currentOn===void 0)throw new Error("meross toggle needs the current power state (pre-read failed)");c=!r.currentOn}else c=n==="turnOn";return{command:{namespace:"Appliance.Control.ToggleX",payload:{togglex:{channel:0,onoff:c?1:0}}},optimistic:{type:"power",state:{on:c}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){t.hasBrightness||s();let c;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("meross adjustBrightness needs the current level (pre-read failed)");c=Fr(r.currentLevel+(rt(i.delta)??0),0,100)}else c=Fr(rt(i.level)??0,0,100);return c===0?{command:{namespace:"Appliance.Control.ToggleX",payload:{togglex:{channel:0,onoff:0}}},optimistic:{type:"brightness",state:{level:0}}}:{command:a({luminance:c},bo.luminance),optimistic:{type:"brightness",state:{level:c}}}}if(e==="colorTemperature"&&n==="setColorTemperature"){t.hasCt||s();let c=Fr(rt(i.kelvin)??Dt.minKelvin,Dt.minKelvin,Dt.maxKelvin);return{command:a({temperature:N3(c)},bo.temperature),optimistic:{type:"colorTemperature",state:{kelvin:c}}}}if(e==="color"&&n==="setColor"){t.hasColor||s();let c=Fr(rt(i.hue)??0,0,360),l=Fr(rt(i.saturation)??0,0,100);return{command:a({rgb:U3(c,l)},bo.rgb),optimistic:{type:"color",state:{hue:c,saturation:l}}}}return s()}function X$(t,e,n){return jp(t,e).find(o=>o.type===n)?.state}function $c(t){if(!t)return null;try{let e=ze(JSON.parse(t));if(e&&typeof e.key=="string"){let n=Bp(e.devices).map(o=>ze(o)).filter(o=>!!o&&typeof o.mac=="string").map(o=>({mac:T(String(o.mac)),...Fp(o.name)?{name:Fp(o.name)}:{}}));return{key:e.key,...n.length?{devices:n}:{}}}}catch{}return null}var Q$=80,z3="no Meross account key on this PC \u2014 run the Meross wizard (acbridge link meross)",H3=15e3,zp=class{constructor(e,n,o=t1){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="meross";reachability="local";client=null;key="";hasKey=!1;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory();let n=$c(await e.localSecrets.read("keystore"));n&&(this.key=n.key,this.hasKey=!0)}async link(e,n){return{ok:!1,error:"Meross links via the account wizard (`acbridge link meross`) \u2014 sign in once so the hub can sign local requests.",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=this.hasKey?await this.locate(e,o):null;if(r){let i=Dc(r.all);this.runtime.set(o.key,{ip:r.ip,profile:r.profile,...r.model?{model:r.model}:{},online:!0,...i?{outlets:i}:{}}),n.push(W$(r.profile,r.all,{accountId:this.accountId,mac:o.key,now:Date.now(),...r.model?{model:r.model}:{},...o.name?{nameOverride:o.name}:{}})),i&&n.push(...q$(i,{accountId:this.accountId,mac:o.key,now:Date.now(),...r.model?{model:r.model}:{}}))}else n.push(Z$(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[kt(e)?.parentNativeId??e]:[...this.runtime.keys()],o=e&&po(e)?e:null,r=[];for(let i of n){let s=this.runtime.get(i);if(s)try{let a=await this.freshAll(i);if(s.online=!0,!o){let c=jp(s.profile,a);if(s.profile.hasEnergy)try{c.push(G$(Os(await this.call(i,"Appliance.Control.Electricity","GET",{electricity:{channel:0}}))))}catch{}r.push({nativeId:i,patch:c,online:!0,ts:Date.now()})}if(s.outlets){s.outlets=Dc(a)??s.outlets;for(let c of V$(a,i))o&&c.nativeId!==o||r.push({nativeId:c.nativeId,patch:c.patch,online:!0,ts:Date.now()})}}catch{if(s.online=!1,s.outlets)for(let a of s.outlets){let c=De(i,String(a.channel));o&&c!==o||r.push({nativeId:c,patch:[],online:!1,ts:Date.now()})}o||r.push({nativeId:i,patch:[],online:!1,ts:Date.now()})}}return r}async sendCommand(e,n,o,r,i){let s=kt(e),a=s?.parentNativeId??e,c=s?Number(s.childKey):null,l=this.runtime.get(a);if(!l)throw new Error(`unknown meross device ${e}`);if(c!==null&&Number.isFinite(c)){if(n!=="power")throw new Error(`meross outlet ${c} does not support ${n}.${o}`);let m;if(o==="toggle"){let h=mx(await this.freshAll(a),c);if(h===null)throw new Error("meross outlet toggle needs the current power state (pre-read failed)");m=!h}else if(o==="turnOn"||o==="turnOff")m=o==="turnOn";else throw new Error(`meross outlet does not support power.${o}`);let g=J$(c,m);if(await this.call(a,g.namespace,"SET",g.payload),l.online=!0,i?.readAfter){let h={on:mx(await this.freshAll(a),c)};return{state:h,verifiedState:h}}return{state:{on:m}}}let u={};if(o==="toggle"||o==="adjustBrightness"){let m=jp(l.profile,await this.freshAll(a)),g=m.find(y=>y.type==="power")?.state,h=m.find(y=>y.type==="brightness")?.state;typeof g?.on=="boolean"&&(u.currentOn=g.on),typeof h?.level=="number"&&(u.currentLevel=h.level)}let{command:d,optimistic:f}=Y$(l.profile,n,o,r,u);if(await this.call(a,d.namespace,"SET",d.payload),l.online=!0,i?.readAfter){let m=X$(l.profile,await this.freshAll(a),n);return{state:m,verifiedState:m}}return{state:f.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??H3),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}call(e,n,o,r){let i=this.runtime.get(e);if(!i)throw new Error(`unknown meross device ${e}`);return he({ip:i.ip,fn:s=>this.need().call(s,n,o,r,this.key),rediscover:()=>this.need().rediscover(e),onNewIp:s=>{i.ip=s,this.cfg.onIpChange?.(e,s)},bail:()=>this.disposed})}async freshAll(e){return Os(await this.call(e,"Appliance.System.All","GET",{all:{}}))}async locate(e,n){let o=async r=>{let i=Os(await e.call(r,"Appliance.System.Ability","GET",{ability:{}},this.key)),s=i.ability??i,a=z$(s),c=Os(await e.call(r,"Appliance.System.All","GET",{all:{}},this.key)),l=fx(c);return{ip:r,profile:a,all:c,...l.model?{model:l.model}:{}}};try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("Meross adapter not initialized");return this.client}};function e1(t,e=t1){let n=e();return async(o,r,i)=>{let s=t();if(s===null)return{veto:z3};try{let a=Os(await n.call(o,"Appliance.System.All","GET",{all:{}},s)),c=fx(a),l=c.mac??(i?.mac?T(i.mac):await n.macForIp(o).then(u=>u?T(u):void 0).catch(()=>{}));return{...l?{mac:l}:{},...c.model?{model:c.model}:{}}}catch{return null}}}var K3=4e3,t1=()=>{let t=!1;return{async call(e,n,o,r,i){if(t)throw new Error("meross client closed");let[s,a]=await Promise.all([import("node:http"),import("node:crypto")]),c=a.randomBytes(16).toString("hex"),l=Math.floor(Date.now()/1e3),u=JSON.stringify(j$(n,o,r,i,{messageId:c,timestamp:l})),d=await new Promise((f,m)=>{let g=s.request({host:e,port:Q$,method:"POST",path:"/config",headers:{"content-type":"application/json","content-length":Buffer.byteLength(u)}},y=>{let b="";y.setEncoding("utf8"),y.on("data",w=>b+=w),y.on("end",()=>y.statusCode&&y.statusCode>=200&&y.statusCode<300?f(b):m(new Error(`meross HTTP ${y.statusCode}`)))}),h=setTimeout(()=>g.destroy(new Error(`meross request timeout (${e}:${Q$})`)),K3);h.unref?.(),g.on("error",y=>{clearTimeout(h),m(y instanceof Error?y:new Error(String(y)))}),g.on("close",()=>clearTimeout(h)),g.write(u),g.end()});return JSON.parse(d)},macForIp(e){return dt(e)},rediscover(e){return se(e)},close(){t=!0}}};var Oc={avty:"availability",avty_mode:"availability_mode",avty_t:"availability_topic",avty_tpl:"availability_template",cmps:"components",dev:"device",dev_cla:"device_class",dsp_prc:"display_precision",e:"encoding",en:"enabled_by_default",ent_cat:"entity_category",ent_pic:"entity_picture",ic:"icon",json_attr_t:"json_attributes_topic",json_attr_tpl:"json_attributes_template",o:"origin",obj_id:"object_id",opt:"optimistic",p:"platform",qos:"qos",ret:"retain",stat_cla:"state_class",sup_feat:"supported_features",uniq_id:"unique_id",unit_of_meas:"unit_of_measurement",cmd_t:"command_topic",cmd_tpl:"command_template",stat_t:"state_topic",stat_tpl:"state_template",stat_val_tpl:"state_value_template",val_tpl:"value_template",t:"topic",pl:"payload",pl_avail:"payload_available",pl_cls:"payload_close",pl_lock:"payload_lock",pl_not_avail:"payload_not_available",pl_off:"payload_off",pl_on:"payload_on",pl_open:"payload_open",pl_osc_off:"payload_oscillation_off",pl_osc_on:"payload_oscillation_on",pl_stop:"payload_stop",pl_unlk:"payload_unlock",stat_off:"state_off",stat_on:"state_on",bri_cmd_t:"brightness_command_topic",bri_cmd_tpl:"brightness_command_template",bri_scl:"brightness_scale",bri_stat_t:"brightness_state_topic",bri_val_tpl:"brightness_value_template",clr_mode_stat_t:"color_mode_state_topic",clr_mode_val_tpl:"color_mode_value_template",clr_temp_cmd_t:"color_temp_command_topic",clr_temp_cmd_tpl:"color_temp_command_template",clr_temp_stat_t:"color_temp_state_topic",clr_temp_val_tpl:"color_temp_value_template",clrm:"color_mode",fx_cmd_t:"effect_command_topic",fx_list:"effect_list",fx_stat_t:"effect_state_topic",fx_val_tpl:"effect_value_template",hs_cmd_t:"hs_command_topic",hs_stat_t:"hs_state_topic",hs_val_tpl:"hs_value_template",max_kelvin:"max_kelvin",max_mirs:"max_mireds",min_kelvin:"min_kelvin",min_mirs:"min_mireds",on_cmd_type:"on_command_type",rgb_cmd_t:"rgb_command_topic",rgb_stat_t:"rgb_state_topic",rgb_val_tpl:"rgb_value_template",schema:"schema",sup_clrm:"supported_color_modes",whit_cmd_t:"white_command_topic",whit_scl:"white_scale",xy_cmd_t:"xy_command_topic",xy_stat_t:"xy_state_topic",xy_val_tpl:"xy_value_template",pos_clsd:"position_closed",pos_open:"position_open",pos_t:"position_topic",pos_tpl:"position_template",set_pos_t:"set_position_topic",set_pos_tpl:"set_position_template",stat_clsd:"state_closed",stat_closing:"state_closing",stat_open:"state_open",stat_opening:"state_opening",stat_stopped:"state_stopped",tilt_cmd_t:"tilt_command_topic",tilt_status_t:"tilt_status_topic",tilt_status_tpl:"tilt_status_template",osc_cmd_t:"oscillation_command_topic",osc_stat_t:"oscillation_state_topic",osc_val_tpl:"oscillation_value_template",pct_cmd_t:"percentage_command_topic",pct_stat_t:"percentage_state_topic",pct_val_tpl:"percentage_value_template",pr_mode_cmd_t:"preset_mode_command_topic",pr_mode_stat_t:"preset_mode_state_topic",pr_mode_val_tpl:"preset_mode_value_template",pr_modes:"preset_modes",spd_rng_max:"speed_range_max",spd_rng_min:"speed_range_min",act_t:"action_topic",act_tpl:"action_template",curr_temp_t:"current_temperature_topic",curr_temp_tpl:"current_temperature_template",max_temp:"max_temp",min_temp:"min_temp",mode_cmd_t:"mode_command_topic",mode_stat_t:"mode_state_topic",mode_stat_tpl:"mode_state_template",modes:"modes",temp_cmd_t:"temperature_command_topic",temp_stat_t:"temperature_state_topic",temp_stat_tpl:"temperature_state_template",temp_step:"temp_step",temp_unit:"temperature_unit",stat_jam:"state_jammed",stat_locked:"state_locked",stat_unlocked:"state_unlocked",max:"max",min:"min",ops:"options",step:"step"},gx={cns:"connections",cu:"configuration_url",hw:"hw_version",ids:"identifiers",mdl:"model",mdl_id:"model_id",mf:"manufacturer",name:"name",sa:"suggested_area",sn:"serial_number",sw:"sw_version",via_device:"via_device"},hx={name:"name",sw:"sw_version",url:"support_url"};var wo=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Hp=t=>typeof t=="string"&&t?t:void 0,n1=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,Ls=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function yx(t,e){let n=(t%360+360)%360/60,r=Math.max(0,Math.min(100,e))/100,i=r*(1-Math.abs(n%2-1)),s=1-r,[a,c,l]=n<1?[r,i,0]:n<2?[i,r,0]:n<3?[0,r,i]:n<4?[0,i,r]:n<5?[i,0,r]:[r,0,i];return{r:Math.round((a+s)*255),g:Math.round((c+s)*255),b:Math.round((l+s)*255)}}function Kp(t,e,n){let o=t/255,r=e/255,i=n/255,s=Math.max(o,r,i),a=Math.min(o,r,i),c=s-a;if(c===0||s===0)return{hue:0,saturation:0};let l;return s===o?l=(r-i)/c%6:s===r?l=(i-o)/c+2:l=(o-r)/c+4,{hue:Math.round((l*60%360+360)%360),saturation:Math.round(c/s*100)}}function G3(t){let e=Array.isArray(t.seg)?t.seg:[],n=n1(e[0])?.col,o=Array.isArray(n)?n[0]:void 0;if(!Array.isArray(o))return null;let r=wo(o[0]),i=wo(o[1]),s=wo(o[2]);return r!==null&&i!==null&&s!==null?{r,g:i,b:s}:null}function r1(t){let e=wo(t.bri),n=G3(t),o=n?Kp(n.r,n.g,n.b):null;return{on:typeof t.on=="boolean"?t.on:null,level:e!==null?Ls(e/255*100,0,100):null,hue:o?o.hue:null,saturation:o?o.saturation:null}}function Gp(t){let e=r1(t);return[{type:"power",state:{on:e.on}},{type:"brightness",state:{level:e.level}},{type:"color",state:{hue:e.hue,saturation:e.saturation}}]}function o1(t,e,n){let o=r1(t),r=T(n.mac),i=[{type:"power",state:{on:o.on}},{type:"brightness",state:{level:o.level}},{type:"color",config:{modes:["hs"]},state:{hue:o.hue,saturation:o.saturation}}];return{source:{provider:"wled",providerAccountId:n.accountId,nativeId:r,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${r}`],type:"light",name:n.nameOverride??Hp(e.name)??"WLED",manufacturer:"WLED",model:Hp(e.arch)?`WLED (${Hp(e.arch)})`:"WLED",capabilities:i}}function i1(t,e){return{source:{provider:"wled",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??"WLED",manufacturer:"WLED",model:t.model??"WLED",capabilities:[{type:"power",state:{on:null}}]}}function s1(t){let e=Hp(t.mac);return e&&/^[0-9a-f]{12}$/i.test(e)?T(e):void 0}function a1(t,e,n,o){let r=n1(n)??{},i=()=>{throw new Error(`wled does not support ${t}.${e}`)};if(t==="power"&&(e==="turnOn"||e==="turnOff"||e==="toggle")){let s;if(e==="toggle"){if(o.currentOn===void 0)throw new Error("wled toggle needs the current power state (pre-read failed)");s=!o.currentOn}else s=e==="turnOn";return{body:{on:s},optimistic:{type:"power",state:{on:s}}}}if(t==="brightness"&&(e==="setBrightness"||e==="adjustBrightness")){let s;if(e==="adjustBrightness"){if(o.currentLevel===void 0)throw new Error("wled adjustBrightness needs the current level (pre-read failed)");s=Ls(o.currentLevel+(wo(r.delta)??0),0,100)}else s=Ls(wo(r.level)??0,0,100);return s===0?{body:{on:!1},optimistic:{type:"brightness",state:{level:0}}}:{body:{on:!0,bri:Ls(s/100*255,1,255)},optimistic:{type:"brightness",state:{level:s}}}}if(t==="color"&&e==="setColor"){let s=Ls(wo(r.hue)??0,0,360),a=Ls(wo(r.saturation)??0,0,100),{r:c,g:l,b:u}=yx(s,a);return{body:{on:!0,seg:[{col:[[c,l,u]]}]},optimistic:{type:"color",state:{hue:s,saturation:a}}}}return i()}function c1(t,e){return Gp(t).find(n=>n.type===e)?.state}var Vt=t=>Math.round(t*10)/10,l1={"temperature|\xB0c":t=>t,"temperature|c":t=>t,"temperature|\xB0f":t=>Vt((t-32)*5/9),"temperature|f":t=>Vt((t-32)*5/9),"temperature|k":t=>Vt(t-273.15),"humidity|%":t=>t,"illuminance|lx":t=>t,"illuminance|lux":t=>t,"pressure|hpa":t=>t,"pressure|mbar":t=>t,"pressure|pa":t=>Vt(t/100),"pressure|kpa":t=>Vt(t*10),"pressure|bar":t=>Vt(t*1e3),"pressure|inhg":t=>Vt(t*33.8639),"pressure|psi":t=>Vt(t*68.9476),"co2|ppm":t=>t,"pm25|\xB5g/m\xB3":t=>t,"pm25|ug/m3":t=>t,"pm10|\xB5g/m\xB3":t=>t,"pm10|ug/m3":t=>t,"voc|ppb":t=>t,"voc|ppm":t=>t*1e3,"airQuality|":t=>t,"airQuality|index":t=>t,"noise|db":t=>t,"noise|dba":t=>t,"noise|db(a)":t=>t,"distance|m":t=>t,"distance|cm":t=>t/100,"distance|mm":t=>t/1e3,"distance|km":t=>t*1e3,"distance|ft":t=>Vt(t*.3048),"distance|in":t=>Vt(t*.0254),"windSpeed|m/s":t=>t,"windSpeed|km/h":t=>Vt(t/3.6),"windSpeed|mph":t=>Vt(t*.44704),"windSpeed|kn":t=>Vt(t*.514444)},u1=(t,e)=>`${t}|${(e??"").toLowerCase()}`;function Wp(t,e){return t==="generic"?"generic":l1[u1(t,e)]!==void 0?t:"generic"}function Zp(t,e,n){let o=l1[u1(t??"generic",e)];return o?o(n):n}var Xp="homeassistant",un=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),S=t=>typeof t=="string"&&t!==""?t:void 0,li="~";function W3(t,e=Xp){if(t.includes("+")||t.includes("#"))return null;let n=t.split("/");if(n.length<4||n.length>5||n[0]!==e||n[n.length-1]!=="config")return null;let o=n.slice(1,-1),r=o[0];if(!r)return null;let i=o.length===3?o[1]??null:null,s=o[o.length-1];return!s||o.length===3&&!i?null:r==="device"?{kind:"device",nodeId:i,objectId:s}:{kind:"entity",component:r,nodeId:i,objectId:s}}function Lc(t,e){let n={};for(let[o,r]of Object.entries(t)){let i=e[o]??o;i!==o&&Object.prototype.hasOwnProperty.call(t,i)||(n[i]=r)}return n}function bx(t,e){for(let[n,o]of Object.entries(t)){if(!n.endsWith("topic")||typeof o!="string"||o==="")continue;let r=o;r.startsWith(li)&&(r=`${e}${r.slice(1)}`),r.endsWith(li)&&(r=`${r.slice(0,-1)}${e}`),t[n]=r}}function m1(t,e){return Array.isArray(t)?t.map(n=>{if(!un(n))return n;let o=Lc(n,Oc);return bx(o,e),o}):t}function Z3(t){if(!un(t)||Object.keys(t).length===0)return null;let e=Lc(t,Oc),n=S(e[li])??"";return delete e[li],un(e.device)&&(e.device=Lc(e.device,gx)),un(e.origin)&&(e.origin=Lc(e.origin,hx)),n&&bx(e,n),e.availability!==void 0&&(e.availability=m1(e.availability,n)),e}var q3=/^\{\{\s*value\s*\}\}$/,V3=/^\{\{\s*value_json((?:\.[A-Za-z_$][\w$]*|\[\s*'[^']*'\s*\]|\[\s*"[^"]*"\s*\])+)\s*\}\}$/,J3=/\.([A-Za-z_$][\w$]*)|\[\s*'([^']*)'\s*\]|\[\s*"([^"]*)"\s*\]/g;function g1(t,e){if(t===void 0||t==="")return{ok:!0,value:e};if(q3.test(t))return{ok:!0,value:e};let n=V3.exec(t);if(!n)return{ok:!1};let o;try{o=JSON.parse(e)}catch{return{ok:!1}}let r=o;for(let i of n[1].matchAll(J3)){let s=i[1]??i[2]??i[3];if(!un(r))return{ok:!0,value:null};r=r[s]}return r==null?{ok:!0,value:null}:typeof r=="string"?{ok:!0,value:r}:typeof r=="number"||typeof r=="boolean"?{ok:!0,value:String(r)}:{ok:!1}}function Y3(t,e){let n=t?.connections;if(Array.isArray(n)){let i=n.filter(c=>Array.isArray(c)&&typeof c[0]=="string"&&typeof c[1]=="string"),s=i.find(([c])=>c.toLowerCase()==="mac");if(s)return`mac:${T(s[1])}`;let a=i[0];if(a)return`${a[0].toLowerCase()}:${a[1].toLowerCase()}`}let o=t?.identifiers,r=typeof o=="string"?[o]:Array.isArray(o)?o.filter(i=>typeof i=="string"):[];return r.length>0?`id:${[...r].sort().join(",")}`:`topic:${e}`}function h1(t,e,n=Xp){let o=W3(e,n);if(!o)return[];let r=Z3(t);if(!r)return[];if(o.kind==="entity")return[{configTopic:e,component:o.component,nodeId:o.nodeId,objectId:o.objectId,cfg:r}];let i=r.components;if(!un(i))return[];let s=S(un(t)?t[li]:void 0)??"",a=[];for(let[c,l]of Object.entries(i)){if(!un(l)||Object.keys(l).length===0)continue;let u=Lc(l,Oc),d=S(u.platform);if(!d)continue;let f=S(u[li]);delete u[li],bx(u,f??s),u.availability!==void 0&&(u.availability=m1(u.availability,f??s)),r.device!==void 0&&u.device===void 0&&(u.device=r.device),r.origin!==void 0&&u.origin===void 0&&(u.origin=r.origin),a.push({configTopic:`${e}#${c}`,component:d,nodeId:o.nodeId,objectId:c,cfg:u})}return a}var Y=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ui=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[],X3=t=>Math.round(t*10)/10,ln=(t,e,n)=>Math.max(e,Math.min(n,t)),cn=t=>ln(Math.round(t),0,100),Q3=new Set(["update","text","event","device_automation","tag","image","camera","vacuum","siren","alarm_control_panel","humidifier","water_heater","valve","lawn_mower","scene","device_tracker","button","notify"]),eG={temperature:"temperature",humidity:"humidity",illuminance:"illuminance",pressure:"pressure",atmospheric_pressure:"pressure",carbon_dioxide:"co2",pm25:"pm25",pm10:"pm10",volatile_organic_compounds_parts:"voc",aqi:"airQuality",sound_pressure:"noise",distance:"distance",wind_speed:"windSpeed"},tG={motion:"motion",occupancy:"occupancy",presence:"presence",door:"contact",window:"contact",garage_door:"contact",opening:"contact",moisture:"leak",smoke:"smoke",carbon_monoxide:"co",gas:"gas",tamper:"tamper",vibration:"vibration",moving:"vibration",sound:"sound"},nG={blind:"blind",shutter:"blind",shade:"shade",curtain:"curtain",awning:"awning",garage:"garage",gate:"garage",door:"door",window:"window",damper:"valve"},wx={off:"off",heat:"heat",cool:"cool",auto:"auto",heat_cool:"auto",dry:"dry",fan_only:"fanOnly"},rG={heating:"heating",cooling:"cooling",fan:"fan",idle:"idle",off:"idle",drying:"idle"},Ie=(t,e,n)=>t?[{topic:t,field:e,...n?{template:n}:{}}]:[];function y1(t){let{cfg:e,component:n}=t;if(e.enabled_by_default===!1)return null;let o=S(e.entity_category),r=S(e.device_class)==="battery";if(o==="config"||o!==void 0&&o!=="config"&&!r||Q3.has(n))return null;let i=oG(n,e);if(!i)return null;let s=un(e.device)?e.device:void 0,a=dG(e),c=[...new Set(i.reads.map(l=>l.topic))];return{configTopic:t.configTopic,component:n,deviceKey:Y3(s,t.objectId),uniqueId:S(e.unique_id)??null,name:S(e.name)??S(s?.name)??t.objectId,device:s,capability:i.capability,extraCapabilities:i.extras,stateTopics:c,availabilityTopics:a,reads:i.reads,cfg:e}}function oG(t,e){switch(t){case"switch":case"input_boolean":return{capability:{type:"power",state:{on:null}},extras:[],reads:Ie(S(e.state_topic),"power",S(e.value_template))};case"light":return iG(e);case"sensor":return sG(e);case"binary_sensor":return{capability:{type:"binarySensor",config:{sensorType:tG[S(e.device_class)??""]??"generic"},state:{active:null}},extras:[],reads:Ie(S(e.state_topic),"binary",S(e.value_template))};case"cover":return aG(e);case"fan":return cG(e);case"lock":return{capability:{type:"lock",state:{state:"unknown"}},extras:[],reads:Ie(S(e.state_topic),"lock",S(e.value_template))};case"climate":return uG(e);case"number":return{capability:{type:"range",config:{min:Y(e.min)??1,max:Y(e.max)??100,...Y(e.step)!==void 0?{step:Y(e.step)}:{},...S(e.unit_of_measurement)?{unit:S(e.unit_of_measurement)}:{}},state:{value:null}},extras:[],reads:Ie(S(e.state_topic),"range",S(e.value_template))};case"select":return{capability:{type:"mode",config:{options:ui(e.options)},state:{value:null}},extras:[],reads:Ie(S(e.state_topic),"mode",S(e.value_template))};default:return null}}var v1=t=>ln(Math.round(1e6/t),1e3,12e3),b1=t=>Math.round(1e6/t);function d1(t){let e=Y(t.min_kelvin),n=Y(t.max_kelvin);if(e!==void 0&&n!==void 0)return{minKelvin:ln(e,1e3,12e3),maxKelvin:ln(n,1e3,12e3)};let o=Y(t.min_mireds)??153,r=Y(t.max_mireds)??500;return{minKelvin:ln(Math.ceil(1e6/r),1e3,12e3),maxKelvin:ln(Math.floor(1e6/o),1e3,12e3)}}function iG(t){let e={type:"power",state:{on:null}},n=S(t.schema)??"default";if(n==="template")return{capability:e,extras:[],reads:[]};let o=[],r=[],i=ui(t.supported_color_modes).map(d=>d.toLowerCase()),s=i.some(d=>["hs","rgb","rgbw","rgbww","xy"].includes(d)),a=i.includes("color_temp");if(n==="json")return r.push(...Ie(S(t.state_topic),"lightJson")),(t.brightness===!0||i.some(d=>d!=="onoff"))&&o.push({type:"brightness",state:{level:null}}),s&&o.push({type:"color",config:{modes:["hs"]},state:{hue:null,saturation:null}}),a&&o.push({type:"colorTemperature",config:d1(t),state:{kelvin:null}}),{capability:e,extras:o,reads:r};r.push(...Ie(S(t.state_topic),"power",S(t.state_value_template)??S(t.value_template))),(S(t.brightness_state_topic)??S(t.brightness_command_topic))&&(o.push({type:"brightness",state:{level:null}}),r.push(...Ie(S(t.brightness_state_topic),"brightness",S(t.brightness_value_template)))),(S(t.color_temp_state_topic)??S(t.color_temp_command_topic))&&(o.push({type:"colorTemperature",config:d1(t),state:{kelvin:null}}),r.push(...Ie(S(t.color_temp_state_topic),"colorTemp",S(t.color_temp_value_template))));let c=S(t.hs_state_topic)??S(t.hs_command_topic),l=S(t.xy_state_topic)??S(t.xy_command_topic),u=S(t.rgb_state_topic)??S(t.rgb_command_topic);return(c??l??u)&&(o.push({type:"color",config:{modes:["hs"]},state:{hue:null,saturation:null}}),c?r.push(...Ie(S(t.hs_state_topic),"hs",S(t.hs_value_template))):l?r.push(...Ie(S(t.xy_state_topic),"xy",S(t.xy_value_template))):r.push(...Ie(S(t.rgb_state_topic),"rgb",S(t.rgb_value_template)))),{capability:e,extras:o,reads:r}}function sG(t){let e=S(t.device_class)??"",n=S(t.value_template),o=S(t.state_topic);if(e==="battery")return{capability:{type:"battery",state:{level:null}},extras:[],reads:Ie(o,"battery",n)};let i={power:"energyPower",energy:"energyEnergy",voltage:"energyVoltage",current:"energyCurrent"}[e];if(i)return{capability:{type:"energyMeter",state:{}},extras:[],reads:Ie(o,i,n)};let s=eG[e]??"generic",a=Wp(s,S(t.unit_of_measurement));return{capability:{type:"sensor",config:{measurement:a,unit:en[a]},state:{value:null}},extras:[],reads:Ie(o,"sensor",n)}}var w1=t=>({open:Y(t.position_open)??100,closed:Y(t.position_closed)??0});function aG(t){let e=!!(S(t.position_topic)??S(t.set_position_topic)),n=!!(S(t.tilt_command_topic)??S(t.tilt_status_topic));return{capability:{type:"cover",config:{kind:nG[S(t.device_class)??""]??"generic",supportsPosition:e,supportsTilt:n},state:{state:"unknown"}},extras:[],reads:[...Ie(S(t.state_topic),"coverState",S(t.value_template)),...Ie(S(t.position_topic),"coverPosition",S(t.position_template)),...Ie(S(t.tilt_status_topic),"coverTilt",S(t.tilt_status_template))]}}var k1=t=>{let e=Y(t.speed_range_min)??1,n=Y(t.speed_range_max)??100;return{min:e,span:Math.max(1,n-e+1)}};function cG(t){let e=ui(t.preset_modes),n=!!(S(t.oscillation_command_topic)??S(t.oscillation_state_topic));return{capability:{type:"fan",config:{presets:e,supportsOscillate:n},state:{on:null}},extras:[],reads:[...Ie(S(t.state_topic),"fanOn",S(t.state_value_template)??S(t.value_template)),...Ie(S(t.percentage_state_topic),"fanPercent",S(t.percentage_value_template)),...Ie(S(t.preset_mode_state_topic),"fanPreset",S(t.preset_mode_value_template)),...Ie(S(t.oscillation_state_topic),"fanOscillate",S(t.oscillation_value_template))]}}var Jp=t=>(S(t.temperature_unit)??"C").toUpperCase().includes("F"),Yp=(t,e)=>e?X3((t-32)*5/9):t,lG=(t,e)=>e?Math.round(t*9/5+32):t;function uG(t){let e=Jp(t),n=ui(t.modes).length>0?ui(t.modes):["off","heat","cool","auto","dry","fan_only"];return{capability:{type:"thermostat",config:{modes:[...new Set(n.map(r=>wx[r.toLowerCase()]).filter(r=>r!==void 0))],minC:Yp(Y(t.min_temp)??(e?45:7),e),maxC:Yp(Y(t.max_temp)??(e?95:35),e),supportsRange:!1},state:{mode:null,currentC:null}},extras:[],reads:[...Ie(S(t.mode_state_topic),"climateMode",S(t.mode_state_template)),...Ie(S(t.temperature_state_topic),"climateSetpoint",S(t.temperature_state_template)),...Ie(S(t.current_temperature_topic),"climateCurrent",S(t.current_temperature_template)),...Ie(S(t.action_topic),"climateAction",S(t.action_template))]}}function x1(t){let e=S(t.availability_topic),n=e?[{topic:e,online:S(t.payload_available)??"online",offline:S(t.payload_not_available)??"offline",...S(t.availability_template)?{template:S(t.availability_template)}:{}}]:[],o=t.availability;if(Array.isArray(o))for(let r of o){if(!un(r))continue;let i=S(r.topic);i&&n.push({topic:i,online:S(r.payload_available)??"online",offline:S(r.payload_not_available)??"offline",...S(r.value_template)?{template:S(r.value_template)}:{}})}return n}var dG=t=>[...new Set(x1(t).map(e=>e.topic))];function S1(t,e,n){for(let o of x1(t.cfg)){if(o.topic!==e)continue;let r=g1(o.template,n),i=r.ok?r.value:null;if(i===o.online)return!0;if(i===o.offline)return!1}return null}var Vp=(t,e)=>{let n=S(t.state_on)??S(t.payload_on)??"ON",o=S(t.state_off)??S(t.payload_off)??"OFF";return e===n?!0:e===o?!1:null},xt=t=>{if(t===null)return null;let e=Number(t);return Number.isFinite(e)?e:null},p1=t=>{let e=(t??"").split(",").map(n=>Number(n.trim()));return e.length>=2&&e.every(n=>Number.isFinite(n))?[e[0],e[1]]:null},pG=t=>{let e=(t??"").split(",").map(n=>Number(n.trim()));return e.length>=3&&e.slice(0,3).every(n=>Number.isFinite(n))?[e[0],e[1],e[2]]:null};function _1(t,e,n){let o=t.reads.filter(s=>s.topic===e);if(o.length===0)return null;let r=new Map,i=(s,a)=>{r.set(s,{...r.get(s)??{},...a})};for(let s of o){let a=g1(s.template,n),c=a.ok?a.value:null;fG(t,s.field,c,n,i)}return[...r.entries()].map(([s,a])=>({type:s,...t.instance?{instance:t.instance}:{},state:a}))}function fG(t,e,n,o,r){let i=t.cfg;switch(e){case"power":return r("power",{on:Vp(i,n)});case"fanOn":return r("fan",{on:Vp(i,n)});case"binary":return r("binarySensor",{active:Vp(i,n)});case"brightness":{let s=xt(n),a=Y(i.brightness_scale)??255;return r("brightness",{level:s===null?null:cn(s/a*100)})}case"colorTemp":{let s=xt(n),a=s===null?null:i.color_temp_kelvin===!0?ln(Math.round(s),1e3,12e3):v1(s);return r("colorTemperature",{kelvin:a})}case"hs":{let s=p1(n);return r("color",s?{hue:ln(Math.round(s[0]),0,360),saturation:cn(s[1])}:{hue:null,saturation:null})}case"rgb":{let s=pG(n);if(!s)return r("color",{hue:null,saturation:null});let a=Kp(s[0],s[1],s[2]);return r("color",a)}case"xy":{let s=p1(n);return r("color",s?gp(s[0],s[1]):{hue:null,saturation:null})}case"lightJson":return gG(t,o,r);case"sensor":{let s=xt(n);return r("sensor",{value:s===null?null:mG(t,s)})}case"battery":return r("battery",{level:xt(n)===null?null:cn(xt(n))});case"energyPower":return r("energyMeter",{power:xt(n)});case"energyEnergy":return r("energyMeter",{energy:xt(n)});case"energyVoltage":return r("energyMeter",{voltage:xt(n)});case"energyCurrent":return r("energyMeter",{current:xt(n)});case"coverState":{let s={[S(i.state_open)??"open"]:"open",[S(i.state_closed)??"closed"]:"closed",[S(i.state_opening)??"opening"]:"opening",[S(i.state_closing)??"closing"]:"closing",[S(i.state_stopped)??"stopped"]:"stopped"};return r("cover",{state:s[n??""]??"unknown"})}case"coverPosition":{let s=xt(n),{open:a,closed:c}=w1(i);return r("cover",{position:s===null||a===c?null:cn((s-c)/(a-c)*100)})}case"coverTilt":{let s=xt(n);return r("cover",{tilt:s===null?null:cn(s)})}case"fanPercent":{let s=xt(n),{min:a,span:c}=k1(i);return r("fan",{level:s===null?null:cn((s-a+1)*100/c)})}case"fanPreset":return r("fan",{preset:n});case"fanOscillate":{let s=S(i.payload_oscillation_on)??"oscillate_on",a=S(i.payload_oscillation_off)??"oscillate_off";return r("fan",{oscillating:n===s?!0:n===a?!1:null})}case"lock":{let s={[S(i.state_locked)??"LOCKED"]:"locked",[S(i.state_unlocked)??"UNLOCKED"]:"unlocked",[S(i.state_jammed)??"JAMMED"]:"jammed"};return r("lock",{state:s[n??""]??"unknown"})}case"climateMode":return r("thermostat",{mode:wx[(n??"").toLowerCase()]??null});case"climateSetpoint":{let s=xt(n);return r("thermostat",{setpointC:s===null?null:Yp(s,Jp(i))})}case"climateCurrent":{let s=xt(n);return r("thermostat",{currentC:s===null?null:Yp(s,Jp(i))})}case"climateAction":return r("thermostat",{action:rG[(n??"").toLowerCase()]??null});case"range":return r("range",{value:xt(n)});case"mode":return r("mode",{value:n})}}function mG(t,e){let n=t.capability;return Zp(n.config?.measurement,S(t.cfg.unit_of_measurement),e)}function gG(t,e,n){let o;try{o=JSON.parse(e)}catch{return n("power",{on:null})}if(!un(o))return n("power",{on:null});let r=t.cfg;o.state!==void 0&&n("power",{on:Vp(r,typeof o.state=="string"?o.state:String(o.state))});let i=s=>t.extraCapabilities.some(a=>a.type===s);if(i("brightness")&&o.brightness!==void 0){let s=Y(o.brightness),a=Y(r.brightness_scale)??255;n("brightness",{level:s===void 0?null:cn(s/a*100)})}if(i("colorTemperature")&&o.color_temp!==void 0){let s=Y(o.color_temp);n("colorTemperature",{kelvin:s===void 0?null:r.color_temp_kelvin===!0?ln(Math.round(s),1e3,12e3):v1(s)})}if(i("color")&&un(o.color)){let s=o.color,a=Y(s.h)??Y(s.hue),c=Y(s.s)??Y(s.saturation),l=Y(s.x),u=Y(s.y),d=Y(s.r),f=Y(s.g),m=Y(s.b);a!==void 0&&c!==void 0?n("color",{hue:ln(Math.round(a),0,360),saturation:cn(c)}):l!==void 0&&u!==void 0?n("color",gp(l,u)):d!==void 0&&f!==void 0&&m!==void 0?n("color",Kp(d,f,m)):n("color",{hue:null,saturation:null})}}var Oe=(t,e,n)=>e?[{topic:e,payload:n,...t.retain===!0?{retain:!0}:{}}]:null;function I1(t,e,n,o){if(!(t.capability.type===e||t.extraCapabilities.some(c=>c.type===e)))return null;let i=o??{},s=t.cfg;if(t.component==="light"&&S(s.schema)==="json")return hG(t,e,n,i);switch(e){case"power":return n==="turnOn"?Oe(s,S(s.command_topic),S(s.payload_on)??"ON"):n==="turnOff"?Oe(s,S(s.command_topic),S(s.payload_off)??"OFF"):null;case"brightness":{if(n!=="setBrightness")return null;let c=Y(s.brightness_scale)??255;return Oe(s,S(s.brightness_command_topic),String(Math.round((Y(i.level)??0)*c/100)))}case"colorTemperature":{if(n!=="setColorTemperature")return null;let c=Y(i.kelvin)??2700;return Oe(s,S(s.color_temp_command_topic),String(s.color_temp_kelvin===!0?Math.round(c):b1(c)))}case"color":{if(n!=="setColor")return null;let c=ln(Y(i.hue)??0,0,360),l=cn(Y(i.saturation)??0);if(S(s.hs_command_topic))return Oe(s,S(s.hs_command_topic),`${Math.round(c)},${l}`);if(S(s.xy_command_topic)){let d=Tk(c,l);return Oe(s,S(s.xy_command_topic),`${d.x},${d.y}`)}let u=yx(c,l);return Oe(s,S(s.rgb_command_topic),`${u.r},${u.g},${u.b}`)}case"cover":{if(n==="open")return Oe(s,S(s.command_topic),S(s.payload_open)??"OPEN");if(n==="close")return Oe(s,S(s.command_topic),S(s.payload_close)??"CLOSE");if(n==="stop")return Oe(s,S(s.command_topic),S(s.payload_stop)??"STOP");if(n==="setPosition"){let{open:c,closed:l}=w1(s);return Oe(s,S(s.set_position_topic),String(Math.round(l+(Y(i.position)??0)/100*(c-l))))}return n==="setTilt"?Oe(s,S(s.tilt_command_topic),String(cn(Y(i.tilt)??0))):null}case"fan":{if(n==="turnOn")return Oe(s,S(s.command_topic),S(s.payload_on)??"ON");if(n==="turnOff")return Oe(s,S(s.command_topic),S(s.payload_off)??"OFF");if(n==="setFanSpeed"){let{min:c,span:l}=k1(s),u=cn(Y(i.level)??0),d=u===0?0:Math.max(c,Math.round(u*l/100)+c-1);return Oe(s,S(s.percentage_command_topic),String(d))}if(n==="setFanPreset"){let c=S(i.preset);return!c||!ui(s.preset_modes).includes(c)?null:Oe(s,S(s.preset_mode_command_topic),c)}if(n==="setOscillate"){let c=i.oscillating===!0;return Oe(s,S(s.oscillation_command_topic),c?S(s.payload_oscillation_on)??"oscillate_on":S(s.payload_oscillation_off)??"oscillate_off")}return null}case"lock":return n==="lock"?Oe(s,S(s.command_topic),S(s.payload_lock)??"LOCK"):n==="unlock"?Oe(s,S(s.command_topic),S(s.payload_unlock)??"UNLOCK"):null;case"thermostat":{let c=Jp(s);if(n==="setSetpoint")return Oe(s,S(s.temperature_command_topic),String(lG(Y(i.celsius)??20,c)));if(n==="setThermostatMode"){let l=S(i.mode),u=Object.entries(wx).find(([,d])=>d===l)?.[0];return u?Oe(s,S(s.mode_command_topic),u):null}return null}case"range":return n!=="setRange"?null:Oe(s,S(s.command_topic),String(Y(i.value)??0));case"mode":{if(n!=="setMode")return null;let c=S(i.value);return!c||!ui(s.options).includes(c)?null:Oe(s,S(s.command_topic),c)}default:return null}}function hG(t,e,n,o){let r=t.cfg,i=S(r.command_topic);if(!i)return null;let s=S(r.payload_on)??"ON",a=S(r.payload_off)??"OFF",c=u=>[{topic:i,payload:JSON.stringify(u),...r.retain===!0?{retain:!0}:{}}],l=u=>t.extraCapabilities.some(d=>d.type===u);if(e==="power")return n==="turnOn"?c({state:s}):n==="turnOff"?c({state:a}):null;if(e==="brightness"&&n==="setBrightness"&&l("brightness")){let u=Y(r.brightness_scale)??255;return c({state:s,brightness:Math.round((Y(o.level)??0)*u/100)})}if(e==="color"&&n==="setColor"&&l("color"))return c({state:s,color:{h:Math.round(ln(Y(o.hue)??0,0,360)),s:cn(Y(o.saturation)??0)}});if(e==="colorTemperature"&&n==="setColorTemperature"&&l("colorTemperature")){let u=Y(o.kelvin)??2700;return c({state:s,color_temp:r.color_temp_kelvin===!0?Math.round(u):b1(u)})}return null}var vx=[{component:"light",type:"light"},{component:"lock",type:"lock"},{component:"climate",type:"thermostat"},{component:"fan",type:"fan"},{component:"cover",type:"cover"},{component:"switch",type:"switch"},{component:"select",type:"other"},{component:"number",type:"other"},{component:"binary_sensor",type:"binarySensor"},{component:"sensor",type:"sensor"}],f1=t=>{let e=vx.findIndex(n=>n.component===t);return e===-1?vx.length:e},qp=t=>t.uniqueId??t.configTopic;function yG(t){for(let{component:e,type:n}of vx){let o=t.find(r=>r.component===e);if(o)return e==="switch"?S(o.cfg.device_class)==="outlet"?"plug":"switch":e==="cover"?S(o.cfg.device_class)==="garage"?"garageDoor":"cover":n}return"other"}function T1(t,e){let n=new Map;for(let i of t){let s=n.get(i.deviceKey);s?s.push(i):n.set(i.deviceKey,[i])}let o=new Map,r=[];for(let[i,s]of[...n.entries()].sort(([a],[c])=>a<c?-1:1)){let a=s.find(m=>m.device!==void 0)?.device,c=S(a?.suggested_area);c&&o.set(c,c);let l=[],u=new Set;for(let m of[...s].sort((g,h)=>f1(g.component)-f1(h.component)||(qp(g)<qp(h)?-1:qp(g)>qp(h)?1:0))){let g=[m.capability,...m.extraCapabilities],h=g.some(y=>u.has(y.type));m.instance=h?m.uniqueId??m.configTopic:void 0;for(let y of g)u.add(y.type),l.push(m.instance?{...y,instance:m.instance}:y)}let d=S(a?.serial_number),f=[...i.startsWith("mac:")?[i]:[],...d?[`serial:${d}`]:[]];r.push({source:{provider:"mqtt",providerAccountId:e.accountId,nativeId:i,reachability:"local",online:e.online?e.online(i):!0,credentialRef:null,lastSeen:e.now},fingerprints:f.length>0?f:[`fallback:mqtt:${e.accountId}:${i}`],type:yG(s),name:S(a?.name)??s[0].name,areaHint:c?{nativeId:c,name:c}:null,manufacturer:S(a?.manufacturer)??null,model:S(a?.model)??S(a?.model_id)??null,capabilities:l})}return{devices:r,rooms:[...o.keys()].sort().map(i=>({nativeId:i,name:i}))}}var kG={settleQuietMs:400,settleMaxMs:5e3,batchMs:150,reconnectMs:5e3,verifyWaitMs:1500},kx=(t,e)=>`${t}|${e}`,tf=class{constructor(e,n,o=xG){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="mqtt";reachability="local";client=null;password;disposed=!1;discovered=!1;bindings=new Map;rawConfigs=new Map;topicIndex=new Map;subscribed=new Set;cache=new Map;pending=new Set;batchTimer=null;notifyTimer=null;reconnectTimer=null;settleBump=null;onState=null;devicesChanged;log=()=>{};opt(e){return this.cfg[e]??kG[e]}get prefix(){return this.cfg.discoveryPrefix??Xp}async init(e){this.log=e.log,this.devicesChanged=e.devicesChanged,this.password=await e.localSecrets.read(this.accountId)??void 0,await this.connect(),await this.settle()}async link(e,n){return{ok:!1,error:"MQTT links to a broker you already run \u2014 add it with `acbridge link mqtt` (host, optional username/password).",retryable:!1}}async unlink(e){await e.localSecrets.write(this.accountId,"")}async discover(){this.discovered=!0;let{devices:e,rooms:n}=T1([...this.bindings.values()],{accountId:this.accountId,now:Date.now(),online:o=>this.cache.get(o)?.online??!0});for(let o of e){let r=this.cache.get(o.source.nativeId);if(r)for(let i of r.patch.values()){let s=this.bindings.get(i.configTopic)?.instance,a=o.capabilities.find(c=>c.type===i.type&&(c.instance??"")===(s??""));a&&i.state&&typeof i.state=="object"&&(a.state={...a.state,...i.state})}}return{devices:e,rooms:n}}async getState(e){let n=[];for(let[o,r]of this.cache)e!==void 0&&o!==e||n.push(this.eventFor(o,r));return n}async sendCommand(e,n,o,r,i){let s=this.need(),a=this.targetFor(e,n,i?.instance),c=a?I1(a,n,o,r):null;if(!a||!c)throw new Error(`no MQTT entity backs ${n}.${o} on ${e}`);let l=this.snapshot(e,a.configTopic,n);for(let d of c)await s.publish(d.topic,d.payload,d.retain?{retain:!0}:void 0);if(!i?.readAfter)return{result:{published:c.length}};let u=await this.awaitEcho(e,a.configTopic,n,l);return u===void 0?{result:{published:c.length}}:{state:u,verifiedState:u,result:{published:c.length}}}subscribe(e,n){return this.onState=e,()=>{this.onState=null}}async dispose(){this.disposed=!0;for(let e of[this.batchTimer,this.notifyTimer,this.reconnectTimer])e&&clearTimeout(e);this.batchTimer=this.notifyTimer=this.reconnectTimer=null,this.onState=null,await this.client?.close().catch(()=>{}),this.client=null}async connect(){let e=this.cfg.tls===!0;this.client=await this.clientFactory({host:this.cfg.host,port:this.cfg.port??(e?8883:1883),tls:e,clientId:this.cfg.clientId??`acbridge-${this.accountId}`,...this.cfg.username?{username:this.cfg.username}:{},...this.password?{password:this.password}:{}},{onMessage:(o,r)=>this.onMessage(o,r),onClose:()=>this.onClose()});let n=[`${this.prefix}/#`,...this.subscribed];this.subscribed.clear();for(let o of n)await this.ensureSubscribed(o)}async ensureSubscribed(e){this.subscribed.has(e)||(this.subscribed.add(e),await this.client?.subscribe(e).catch(n=>this.log(`[mqtt] subscribe ${e} failed: ${String(n)}`)))}settle(){return new Promise(e=>{let n,o=()=>{clearTimeout(n),clearTimeout(r),this.settleBump=null,e()};n=setTimeout(o,this.opt("settleQuietMs"));let r=setTimeout(o,this.opt("settleMaxMs"));this.settleBump=()=>{clearTimeout(n),n=setTimeout(o,this.opt("settleQuietMs"))}})}onClose(){if(this.client=null,!this.disposed){for(let e of this.bindings.values())this.ensureCache(e.deviceKey).online=!1,this.pending.add(e.deviceKey);this.scheduleFlush(),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.disposed&&this.connect().catch(e=>{this.log(`[mqtt] reconnect to ${this.cfg.host} failed: ${String(e)}`),this.onClose()})},this.opt("reconnectMs"))}}onMessage(e,n){if(this.settleBump?.(),e.startsWith(`${this.prefix}/`)&&e.endsWith("/config")){this.onConfig(e,n);return}let o=this.topicIndex.get(e);if(o){for(let r of o){let i=this.ensureCache(r.deviceKey),s=S1(r,e,n);s!==null&&(i.online=s);let a=_1(r,e,n);if(a)for(let c of a)i.patch.set(kx(r.configTopic,c.type),{configTopic:r.configTopic,type:c.type,state:c.state});(s!==null||a)&&this.pending.add(r.deviceKey)}this.scheduleFlush()}}onConfig(e,n){if(this.rawConfigs.get(e)===n)return;n===""?this.rawConfigs.delete(e):this.rawConfigs.set(e,n);for(let r of[...this.bindings.keys()])(r===e||r.startsWith(`${e}#`))&&this.bindings.delete(r);let o=null;if(n!=="")try{o=JSON.parse(n)}catch{this.log(`[mqtt] ignoring malformed discovery config on ${e}`);return}for(let r of h1(o,e,this.prefix)){let i=y1(r);i&&this.bindings.set(i.configTopic,i)}this.reindex(),this.scheduleNotify()}reindex(){let e=new Map;for(let n of this.bindings.values())for(let o of[...n.stateTopics,...n.availabilityTopics]){let r=e.get(o);r?r.push(n):e.set(o,[n])}this.topicIndex=e;for(let n of e.keys())this.ensureSubscribed(n)}scheduleFlush(){this.batchTimer||this.pending.size===0||(this.batchTimer=setTimeout(()=>{this.batchTimer=null;let e=[...this.pending];this.pending.clear();for(let n of e){let o=this.cache.get(n);o&&this.onState?.(this.eventFor(n,o))}},this.opt("batchMs")))}scheduleNotify(){!this.discovered||!this.devicesChanged||this.notifyTimer||(this.notifyTimer=setTimeout(()=>{this.notifyTimer=null,this.disposed||this.devicesChanged?.()},this.opt("batchMs")))}ensureCache(e){let n=this.cache.get(e);if(n)return n;let o={patch:new Map,online:void 0};return this.cache.set(e,o),o}eventFor(e,n){return{nativeId:e,patch:[...n.patch.values()].map(o=>{let r=this.bindings.get(o.configTopic)?.instance;return{type:o.type,...r?{instance:r}:{},state:o.state}}),...n.online!==void 0?{online:n.online}:{},ts:Date.now()}}targetFor(e,n,o){let r=[...this.bindings.values()].filter(i=>i.deviceKey===e&&(i.capability.type===n||i.extraCapabilities.some(s=>s.type===n)));return o!==void 0?r.find(i=>i.instance===o):r.find(i=>i.instance===void 0)??r[0]}snapshot(e,n,o){return JSON.stringify(this.cache.get(e)?.patch.get(kx(n,o))?.state??null)}async awaitEcho(e,n,o,r){let i=Date.now()+this.opt("verifyWaitMs");for(;Date.now()<i;){await new Promise(a=>setTimeout(a,5));let s=this.cache.get(e)?.patch.get(kx(n,o))?.state;if(s!==void 0&&JSON.stringify(s)!==r)return s}}need(){if(!this.client)throw new Error(`MQTT broker ${this.cfg.host} is not connected`);return this.client}},xG=async(t,e)=>{let{connectMqtt:n}=await Promise.resolve().then(()=>(j1(),B1));return n(t,e)};function Ms(t){if(!t)return{devices:{}};try{let n=JSON.parse(t)?.devices;if(!n||typeof n!="object"||Array.isArray(n))return{devices:{}};let o={};for(let[r,i]of Object.entries(n))typeof i=="string"&&i&&(o[T(r)]=i);return{devices:o}}catch{return{devices:{}}}}function z1(t,e,n){return n?{devices:{...t.devices,[T(e)]:n}}:t}function xx(t,e){return t.devices[T(e)]}var nr=G(require("node:crypto"),1);var B={HelloRequest:1,HelloResponse:2,AuthenticationRequest:3,AuthenticationResponse:4,DisconnectRequest:5,DisconnectResponse:6,PingRequest:7,PingResponse:8,DeviceInfoRequest:9,DeviceInfoResponse:10,ListEntitiesRequest:11,ListEntitiesBinarySensorResponse:12,ListEntitiesCoverResponse:13,ListEntitiesFanResponse:14,ListEntitiesLightResponse:15,ListEntitiesSensorResponse:16,ListEntitiesSwitchResponse:17,ListEntitiesTextSensorResponse:18,ListEntitiesDoneResponse:19,SubscribeStatesRequest:20,BinarySensorStateResponse:21,CoverStateResponse:22,FanStateResponse:23,LightStateResponse:24,SensorStateResponse:25,SwitchStateResponse:26,TextSensorStateResponse:27,CoverCommandRequest:30,FanCommandRequest:31,LightCommandRequest:32,SwitchCommandRequest:33,ListEntitiesClimateResponse:46,ClimateStateResponse:47,ClimateCommandRequest:48,ListEntitiesNumberResponse:49,NumberStateResponse:50,NumberCommandRequest:51,ListEntitiesSelectResponse:52,SelectStateResponse:53,SelectCommandRequest:54,ListEntitiesLockResponse:58,LockStateResponse:59,LockCommandRequest:60};function Mc(t){if(t<0||!Number.isFinite(t))throw new Error(`esphome: cannot varint-encode ${t}`);let e=[],n=t;do{let o=n%128;n=Math.floor(n/128),n>0&&(o|=128),e.push(o)}while(n>0);return Buffer.from(e)}function di(t,e){let n=0,o=1;for(let r=0;r<5;r+=1){let i=t[e+r];if(i===void 0)return null;if(n+=(i&127)*o,(i&128)===0)return{value:n,next:e+r+1};o*=128}throw new Error("esphome: varint longer than 5 bytes")}function W1(t){let e=Buffer.alloc(4);return e.writeFloatLE(t,0),e}function Ke(t){let e=[];for(let n of t)if(e.push(Mc(n.n<<3|n.wire)),n.wire===0)e.push(Mc(typeof n.value=="boolean"?n.value?1:0:Number(n.value)));else if(n.wire===2){let o=Buffer.isBuffer(n.value)?n.value:Buffer.from(String(n.value),"utf8");e.push(Mc(o.length),o)}else if(Buffer.isBuffer(n.value))e.push(n.value);else{let o=Buffer.alloc(4);o.writeUInt32LE(Number(n.value)>>>0,0),e.push(o)}return Buffer.concat(e)}function pi(t){let e=new Map,n=(r,i)=>{let s=e.get(r);s?s.push(i):e.set(r,[i])},o=0;for(;o<t.length;){let r=di(t,o);if(!r)break;o=r.next;let i=r.value>>>3,s=r.value&7;if(s===0){let a=di(t,o);if(!a)break;n(i,a.value),o=a.next}else if(s===2){let a=di(t,o);if(!a)break;let c=a.next+a.value;if(c>t.length)break;n(i,t.subarray(a.next,c)),o=c}else if(s===5){if(o+4>t.length)break;n(i,t.subarray(o,o+4)),o+=4}else if(s===1)o+=8;else break}return e}var sf=(t,e)=>t.get(e)?.[0];function xo(t,e){let n=sf(t,e);return typeof n=="number"?n:void 0}function Nn(t,e){let n=xo(t,e);return n===void 0?void 0:n!==0}function af(t,e){let n=sf(t,e);return Buffer.isBuffer(n)&&n.length===4?n.readUInt32LE(0):void 0}function Je(t,e){let n=sf(t,e);return Buffer.isBuffer(n)&&n.length===4?n.readFloatLE(0):void 0}function He(t,e){let n=sf(t,e);return Buffer.isBuffer(n)?n.toString("utf8"):void 0}function cf(t,e){return(t.get(e)??[]).filter(n=>Buffer.isBuffer(n)).map(n=>n.toString("utf8"))}function Ix(t,e){let n=[];for(let o of t.get(e)??[]){if(typeof o=="number"){n.push(o);continue}let r=0;for(;r<o.length;){let i=di(o,r);if(!i)break;n.push(i.value),r=i.next}}return n}var of=class extends Error{preamble;offset;constructor(e,n,o){super(e),this.preamble=n,this.offset=o}};function SG(t,e){return Buffer.concat([Buffer.from([0]),Mc(e.length),Mc(t),e])}function _G(t){let e=[],n=0;for(;!(n>=t.length);){if(t[n]!==0)throw new of(`esphome: bad plaintext preamble 0x${(t[n]??0).toString(16)}`,t[n]??0,n);let o=di(t,n+1);if(!o)break;let r=di(t,o.next);if(!r)break;let i=r.next+o.value;if(i>t.length)break;e.push({type:r.value,payload:t.subarray(r.next,i)}),n=i}return{frames:e,rest:t.subarray(n)}}var ko=class extends Error{},Us=class extends Error{},IG="Noise_NNpsk0_25519_ChaChaPoly_SHA256",TG=Buffer.from("NoiseAPIInit\0\0","binary"),EG=Buffer.from("302a300506032b656e032100","hex");function CG(t){let e=Buffer.from(t.trim(),"base64");if(e.length!==32)throw new ko(`esphome: the encryption key must decode to 32 bytes (got ${e.length})`);return e}var H1=t=>nr.default.createHash("sha256").update(t).digest(),Sx=(t,e,n)=>{let o=Buffer.from(nr.default.hkdfSync("sha256",e,t,Buffer.alloc(0),32*n));return Array.from({length:n},(r,i)=>o.subarray(i*32,(i+1)*32))},RG=t=>t.export({type:"spki",format:"der"}).subarray(-32),AG=t=>nr.default.createPublicKey({key:Buffer.concat([EG,t]),format:"der",type:"spki"}),nf=t=>{let e=Buffer.alloc(12);return e.writeUInt32LE(t,4),e};function PG(t,e){let n=H1(Buffer.from(IG,"utf8")),o=n,r=null,i=0,s=null,a=null,c=0,l=0,u=e??nr.default.generateKeyPairSync("x25519"),d=I=>{n=H1(Buffer.concat([n,I]))},f=I=>{let[E,C]=Sx(o,I,2);o=E,r=C,i=0},m=I=>{if(!r)throw new Error("esphome: noise key not established");let E=nr.default.createCipheriv("chacha20-poly1305",r,nf(i),{authTagLength:16});E.setAAD(n);let C=Buffer.concat([E.update(I),E.final(),E.getAuthTag()]);return i+=1,d(C),C},g=I=>{if(!r)throw new Error("esphome: noise key not established");let E=nr.default.createDecipheriv("chacha20-poly1305",r,nf(i),{authTagLength:16});E.setAAD(n),E.setAuthTag(I.subarray(I.length-16));let C;try{C=Buffer.concat([E.update(I.subarray(0,I.length-16)),E.final()])}catch{throw new ko("esphome: handshake MAC failure \u2014 the encryption key is wrong")}return i+=1,d(I),C};d(TG);let[h,y,b]=Sx(o,t,3);o=h,d(y),r=b,i=0;let w=Buffer.alloc(0),x=I=>{let E=Buffer.alloc(3);return E[0]=1,E.writeUInt16BE(I.length,1),Buffer.concat([E,I])};return{hello:()=>Buffer.from([1,0,0]),handshakeFrame(){let I=RG(u.publicKey);d(I),f(I);let E=m(Buffer.alloc(0));return x(Buffer.concat([Buffer.from([0]),I,E]))},readServerHello(I){if(I.length<4||I[0]!==1)throw new Error("esphome: bad noise frame");let E=I.subarray(3,3+I.readUInt16BE(1));if(E[0]!==1)throw new Error(`esphome: unexpected noise hello protocol byte 0x${(E[0]??0).toString(16)}`);let C=E.subarray(1).toString("utf8").split("\0"),F=C[0]??"",U=C[1]&&C[1].length>0?C[1]:void 0;return{name:F,mac:U}},readHandshakeReply(I){if(I.length<4||I[0]!==1)throw new Error("esphome: bad noise frame");let E=I.subarray(3,3+I.readUInt16BE(1));if(E[0]!==0){let W=E.subarray(1).toString("utf8");throw/^bad /i.test(W)?new Error(`esphome: the device rejected the handshake \u2014 ${W}`):new ko(`esphome: ${W||"handshake rejected"}`)}let C=E.subarray(1,33);d(C),f(C),f(nr.default.diffieHellman({privateKey:u.privateKey,publicKey:AG(C)})),g(E.subarray(33));let[F,U]=Sx(o,Buffer.alloc(0),2);s=F,a=U,c=0,l=0},encodeFrame(I,E){if(!s)throw new Error("esphome: noise channel not established");let C=Buffer.alloc(4+E.length);C.writeUInt16BE(I,0),C.writeUInt16BE(E.length,2),E.copy(C,4);let F=nr.default.createCipheriv("chacha20-poly1305",s,nf(c),{authTagLength:16});F.setAAD(Buffer.alloc(0));let U=Buffer.concat([F.update(C),F.final(),F.getAuthTag()]);return c+=1,x(U)},decodeFrames(I){if(!a)throw new Error("esphome: noise channel not established");let E=Buffer.concat([w,I]),C=[],F=0;for(;!(F+3>E.length);){if(E[F]!==1)throw new Error(`esphome: bad noise preamble 0x${(E[F]??0).toString(16)}`);let U=E.readUInt16BE(F+1),W=F+3+U;if(W>E.length)break;let N=nr.default.createDecipheriv("chacha20-poly1305",a,nf(l),{authTagLength:16});N.setAAD(Buffer.alloc(0));let M=E.subarray(F+3,W);N.setAuthTag(M.subarray(M.length-16));let ue=Buffer.concat([N.update(M.subarray(0,M.length-16)),N.final()]);l+=1,C.push({type:ue.readUInt16BE(0),payload:ue.subarray(4,4+ue.readUInt16BE(2))}),F=W}return w=E.subarray(F),{frames:C,rest:Buffer.alloc(0)}}}}var DG=6e3,_x=4e3,rf=Buffer.alloc(0),$G=new Set([B.ListEntitiesBinarySensorResponse,B.ListEntitiesCoverResponse,B.ListEntitiesFanResponse,B.ListEntitiesLightResponse,B.ListEntitiesSensorResponse,B.ListEntitiesSwitchResponse,B.ListEntitiesTextSensorResponse,B.ListEntitiesClimateResponse,B.ListEntitiesNumberResponse,B.ListEntitiesSelectResponse,B.ListEntitiesLockResponse]),K1=256*1024;function OG(t){let e=pi(t),n=He(e,13)||He(e,2);return{...n?{name:n}:{},...He(e,3)?{mac:He(e,3)}:{},...He(e,6)?{model:He(e,6)}:{},...He(e,12)?{manufacturer:He(e,12)}:{}}}function LG(t,e,n){return new Promise((o,r)=>{let i=!1,s=setTimeout(()=>a(new Error(`esphome: bring-up timed out after ${n}ms`)),n);s.unref?.();function a(K){i||(i=!0,clearTimeout(s),t.destroy(),r(K))}function c(K){i||(i=!0,clearTimeout(s),o(K))}let l=!1;t.onClose(()=>{l=!0,a(new Error("esphome: connection closed before bring-up completed"))});let u;try{u=e.psk?PG(CG(e.psk)):null}catch(K){a(K instanceof Error?K:new Error(String(K)));return}let d=(K,L)=>{t.write(u?u.encodeFrame(K,L):SG(K,L))},f=null,m=K=>new Promise((L,ye)=>{f=ot=>{if(ot.type!==K){ye(new Error(`esphome: expected message type ${K} during bring-up, got ${ot.type}`));return}L(ot)}}),g=(K,L,ye)=>{let ot=m(ye);return d(K,L),ot},h="bringup",y=null,b=[],w=[],x=[],I=!1;function E(K,L){if(K===B.PingRequest){d(B.PingResponse,rf);return}if(h==="established"){if(!I)x.push({type:K,payload:L});else for(let ye of w)ye(K,L);return}if(h==="listing"){if(K===B.ListEntitiesDoneResponse){let ye=y;y=null,ye?.();return}$G.has(K)&&b.push({type:K,payload:L});return}if(f){let ye=f;f=null,ye({type:K,payload:L})}}let C=Buffer.alloc(0),F=0;function U(K){try{C=Buffer.concat([C,K]);let L=_G(C);if(C=L.rest,C.length>=1&&C[0]===0){let ye=di(C,1);if(ye&&ye.value>K1)throw new Error(`esphome: claimed frame length ${ye.value} exceeds the ${K1}-byte cap`)}for(let ye of L.frames)F+=1,E(ye.type,ye.payload)}catch(L){if(L instanceof of&&L.preamble===1&&L.offset===0&&F===0){a(new ko("esphome: this device has API encryption enabled \u2014 enter its `api: encryption: key`"));return}a(L instanceof Error?L:new Error(String(L)))}}let W=Buffer.alloc(0),N=!1,M=!1;function ue(K){if(u)try{if(M){let{frames:L}=u.decodeFrames(K);for(let ye of L)E(ye.type,ye.payload);return}for(W=Buffer.concat([W,K]);!(W.length<3);){if(W[0]!==1)throw new Error(`esphome: bad noise preamble 0x${(W[0]??0).toString(16)}`);let ye=3+W.readUInt16BE(1);if(ye>W.length)break;let ot=W.subarray(0,ye);if(W=W.subarray(ye),!N){u.readServerHello(ot),N=!0;continue}u.readHandshakeReply(ot),M=!0;let cr=W;if(W=Buffer.alloc(0),cr.length){let{frames:fn}=u.decodeFrames(cr);for(let v of fn)E(v.type,v.payload)}de().catch(fn=>a(fn instanceof Error?fn:new Error(String(fn))));break}}catch(L){a(L instanceof Error?L:new Error(String(L)))}}async function de(){try{await g(B.HelloRequest,Ke([{n:1,wire:2,value:"ac-bridge"}]),B.HelloResponse);let K=await g(B.DeviceInfoRequest,rf,B.DeviceInfoResponse),L=OG(K.payload);h="listing";let ye=new Promise(ot=>{y=ot});d(B.ListEntitiesRequest,rf),await ye,h="established",d(B.SubscribeStatesRequest,rf),c({deviceInfo:L,entities:b,async send(ot,cr){if(l)throw new Error("esphome: session is closed");d(ot,cr)},onState(ot){if(w.push(ot),!I){I=!0;let cr=x.splice(0,x.length);for(let fn of cr)ot(fn.type,fn.payload)}},close(){l||(l=!0,t.destroy())}})}catch(K){a(K instanceof Error?K:new Error(String(K)))}}t.onData(u?ue:U),u?(t.write(u.hello()),t.write(u.handshakeFrame())):de().catch(K=>a(K instanceof Error?K:new Error(String(K))))})}function NG(t,e,n){return new Promise((o,r)=>{let i=!1,s=setTimeout(()=>{i||(i=!0,r(new Us(`esphome: connect timed out (${t})`)))},n);s.unref?.(),Promise.resolve(e).then(a=>{if(i){a.destroy();return}i=!0,clearTimeout(s),o(a)},a=>{i||(i=!0,clearTimeout(s),r(new Us(a instanceof Error?a.message:String(a),{cause:a})))})})}function MG(t,e={}){let n=e.rediscover??(async()=>{}),o=e.bringUpTimeoutMs??DG,r=e.connectTimeoutMs??_x,i=!1;return{async connect(s,a){if(i)throw new Error("esphome: client is closed");let c=await NG(s,t(s),r);return LG(c,a,o)},rediscover:n,close(){i=!0}}}var G1=6053;function UG(t){return e=>FG(e,t)}async function FG(t,e){let n=await import("node:net");return new Promise((o,r)=>{let i=n.createConnection({host:t,port:G1}),s=!1,a=setTimeout(()=>{s||(s=!0,i.destroy(),r(new Error(`esphome: connect timeout (${t}:${G1})`)))},e);a.unref?.(),i.on("error",c=>{s||(s=!0,clearTimeout(a),r(c instanceof Error?c:new Error(String(c))))}),i.once("connect",()=>{s||(s=!0,clearTimeout(a),o({write:c=>{i.write(c)},onData:c=>{i.on("data",c)},onClose:c=>{i.on("close",c)},destroy:()=>{i.destroy()}}))})})}var Tx=()=>MG(UG(_x),{rediscover:t=>se(t),connectTimeoutMs:_x});var BG={motion:"motion",occupancy:"occupancy",presence:"presence",door:"contact",window:"contact",garage_door:"contact",opening:"contact",moisture:"leak",smoke:"smoke",carbon_monoxide:"co",gas:"gas",tamper:"tamper",vibration:"vibration",sound:"sound",problem:"generic",safety:"generic",lock:"contact"},jG={temperature:"temperature",humidity:"humidity",illuminance:"illuminance",pressure:"pressure",atmospheric_pressure:"pressure",carbon_dioxide:"co2",pm25:"pm25",pm10:"pm10",volatile_organic_compounds_parts:"voc",aqi:"airQuality",sound_pressure:"noise",distance:"distance",wind_speed:"windSpeed"},zG=new Set(["power","energy","voltage","current","apparent_power","reactive_power"]),Ye={ON_OFF:1,LEGACY_BRIGHTNESS:2,BRIGHTNESS:3,WHITE:7,COLOR_TEMPERATURE:11,COLD_WARM_WHITE:19,RGB:35,RGB_WHITE:39,RGB_COLOR_TEMPERATURE:47,RGB_COLD_WARM_WHITE:51},HG=new Set([Ye.LEGACY_BRIGHTNESS,Ye.BRIGHTNESS,Ye.WHITE,Ye.COLOR_TEMPERATURE,Ye.COLD_WARM_WHITE,Ye.RGB,Ye.RGB_WHITE,Ye.RGB_COLOR_TEMPERATURE,Ye.RGB_COLD_WARM_WHITE]),KG=new Set([Ye.COLOR_TEMPERATURE,Ye.COLD_WARM_WHITE,Ye.RGB_COLOR_TEMPERATURE,Ye.RGB_COLD_WARM_WHITE]),GG=new Set([Ye.RGB,Ye.RGB_WHITE,Ye.RGB_COLOR_TEMPERATURE,Ye.RGB_COLD_WARM_WHITE]),Cx=t=>Math.floor(1e6/t),WG={awning:"awning",blind:"blind",curtain:"curtain",door:"door",garage:"garage",gate:"door",shade:"shade",shutter:"blind",window:"window"},Rx={0:"off",1:"auto",2:"cool",3:"heat",4:"fanOnly",5:"dry",6:"auto"},ZG=t=>{let e=pi(t),n=af(e,2);if(n===void 0)return null;let o=He(e,1)??String(n);return{key:n,objectId:o,name:He(e,3)||o}};function Ax(t,e){let n=ZG(e);if(!n)return null;let o=pi(e),r=(s,a)=>({...n,kind:s,capability:a}),i=n.objectId;if(t===B.ListEntitiesSwitchResponse){let s=He(o,9);return{...r("switch",{type:"power",instance:i,state:{on:null}}),...s?{deviceClass:s}:{}}}if(t===B.ListEntitiesBinarySensorResponse){let s=BG[He(o,5)??""]??"generic";return r("binary_sensor",{type:"binarySensor",instance:i,config:{sensorType:s},state:{active:null}})}if(t===B.ListEntitiesSensorResponse){let s=He(o,9)??"";if(s==="battery")return r("sensor",{type:"battery",instance:i,state:{level:null}});if(zG.has(s))return{...r("sensor",{type:"energyMeter",instance:i,state:{}}),deviceClass:s};let a=He(o,6),c=Wp(jG[s]??"generic",a);return{...r("sensor",{type:"sensor",instance:i,config:{measurement:c,unit:en[c]},state:{value:null}}),...a?{declaredUnit:a}:{}}}if(t===B.ListEntitiesTextSensorResponse)return r("text_sensor",{type:"sensor",instance:i,config:{measurement:"generic",unit:en.generic},state:{value:null}});if(t===B.ListEntitiesLightResponse){let s=Ix(o,12),a=cf(o,11),c=[];if(s.some(l=>HG.has(l))&&c.push({type:"brightness",instance:i,state:{level:null}}),s.some(l=>KG.has(l))){let l=Je(o,9),u=Je(o,10);l&&u&&c.push({type:"colorTemperature",instance:i,config:{minKelvin:Cx(u),maxKelvin:Cx(l)},state:{kelvin:null}})}return s.some(l=>GG.has(l))&&c.push({type:"color",instance:i,config:{modes:["hs"]},state:{hue:null,saturation:null}}),{...n,kind:"light",capability:{type:"power",instance:i,state:{on:null}},extras:c,colorModes:s,...a.length?{effects:a}:{}}}if(t===B.ListEntitiesCoverResponse){let s=WG[He(o,8)??""]??"generic";return r("cover",{type:"cover",instance:i,config:{kind:s,supportsPosition:Nn(o,6)??!1,supportsTilt:Nn(o,7)??!1},state:{state:"unknown"}})}if(t===B.ListEntitiesFanResponse){let s=xo(o,8);return{...r("fan",{type:"fan",instance:i,config:{presets:cf(o,12),supportsOscillate:Nn(o,5)??!1},state:{on:null}}),...s?{speedCount:s}:{}}}if(t===B.ListEntitiesLockResponse)return r("lock",{type:"lock",instance:i,state:{state:"unknown"}});if(t===B.ListEntitiesClimateResponse){let s=Ix(o,7),a=s.map(c=>Rx[c]).filter(c=>c!==void 0);return{...r("climate",{type:"thermostat",instance:i,config:{modes:[...new Set(a)],minC:Je(o,8)??7,maxC:Je(o,9)??35,supportsRange:Nn(o,6)??!1},state:{mode:null,currentC:null}}),...s.length?{climateModeIds:s}:{}}}if(t===B.ListEntitiesNumberResponse){let s=Je(o,8),a=He(o,11);return r("number",{type:"range",instance:i,config:{min:Je(o,6)??0,max:Je(o,7)??100,...s!==void 0?{step:s}:{},...a?{unit:a}:{}},state:{value:null}})}return t===B.ListEntitiesSelectResponse?r("select",{type:"mode",instance:i,config:{options:cf(o,6)},state:{value:null}}):null}function Z1(t){return t.extras??[]}var Ex=t=>t===void 0?null:Math.round(t*100),qG=(t,e,n)=>{let o=Math.max(t,e,n),r=Math.min(t,e,n),i=o-r,s=0;return i!==0&&(o===t?s=(e-n)/i%6:o===e?s=(n-t)/i+2:s=(t-e)/i+4,s*=60,s<0&&(s+=360)),{hue:Math.round(s),saturation:o===0?0:Math.round(i/o*100)}},VG={0:"unknown",1:"locked",2:"unlocked",3:"jammed",4:"unknown",5:"unknown"},JG={0:"idle",2:"cooling",3:"heating",4:"idle",5:"idle",6:"fan"};function q1(t,e,n){let o=pi(e),r=n.objectId,i=Nn(o,3)===!0;if(t===B.SwitchStateResponse)return[{type:"power",instance:r,state:{on:Nn(o,2)??null}}];if(t===B.BinarySensorStateResponse)return[{type:"binarySensor",instance:r,state:{active:i?null:Nn(o,2)??null}}];if(t===B.SensorStateResponse){let s=i?null:Je(o,2)??null;if(n.capability.type==="battery")return[{type:"battery",instance:r,state:{level:s}}];if(n.capability.type==="energyMeter"){let c=n.deviceClass??"",l={};return c==="voltage"?l.voltage=s:c==="current"?l.current=s:c==="energy"?l.energy=s:l.power=s,[{type:"energyMeter",instance:r,state:l}]}let a=n.capability.type==="sensor"?n.capability.config?.measurement:void 0;return[{type:"sensor",instance:r,state:{value:s===null?null:Zp(a,n.declaredUnit,s)}}]}if(t===B.TextSensorStateResponse)return[{type:"sensor",instance:r,state:{value:null}}];if(t===B.NumberStateResponse)return[{type:"range",instance:r,state:{value:i?null:Je(o,2)??null}}];if(t===B.SelectStateResponse)return[{type:"mode",instance:r,state:{value:i?null:He(o,2)??null}}];if(t===B.LightStateResponse){let s=[{type:"power",instance:r,state:{on:Nn(o,2)??null}}];(n.extras??[]).some(g=>g.type==="brightness")&&s.push({type:"brightness",instance:r,state:{level:Ex(Je(o,3))}});let c=(n.extras??[]).some(g=>g.type==="color"),l=Je(o,4),u=Je(o,5),d=Je(o,6);c&&l!==void 0&&u!==void 0&&d!==void 0&&s.push({type:"color",instance:r,state:qG(l,u,d)});let f=(n.extras??[]).some(g=>g.type==="colorTemperature"),m=Je(o,8);return f&&m&&s.push({type:"colorTemperature",instance:r,state:{kelvin:Cx(m)}}),s}if(t===B.CoverStateResponse){let s=Ex(Je(o,3)),a=Ex(Je(o,4)),c=xo(o,5)??0,l=c===1?"opening":c===2?"closing":s===null?"unknown":s>=100?"open":s<=0?"closed":"partial";return[{type:"cover",instance:r,state:{position:s,...a!==null?{tilt:a}:{},state:l}}]}if(t===B.FanStateResponse){let s=xo(o,6),a=s!==void 0&&n.speedCount&&n.speedCount>0?Math.round(s/n.speedCount*100):void 0;return[{type:"fan",instance:r,state:{on:Nn(o,2)??null,...a!==void 0?{level:a}:{},...He(o,7)?{preset:He(o,7)}:{},oscillating:Nn(o,3)??null}}]}if(t===B.LockStateResponse)return[{type:"lock",instance:r,state:{state:VG[xo(o,2)??0]??"unknown"}}];if(t===B.ClimateStateResponse){let s=xo(o,8);return[{type:"thermostat",instance:r,state:{mode:Rx[xo(o,2)??0]??null,currentC:Je(o,3)??null,setpointC:Je(o,4)??null,...s===void 0?{}:{action:JG[s]??"idle"}}}]}return[]}var rr=(t,e)=>({n:t,wire:5,value:W1(e)}),Se=(t,e)=>({n:t,wire:0,value:e}),St=t=>({n:1,wire:5,value:t}),lf=t=>Math.min(1,Math.max(0,t/100)),YG=(t,e)=>{let n=t;return typeof e?.min=="number"&&(n=Math.max(e.min,n)),typeof e?.max=="number"&&(n=Math.min(e.max,n)),n},XG=(t,e)=>{let o=e/100,r=o*(1-Math.abs(t/60%2-1)),i=1-o,[s,a,c]=t<60?[o,r,0]:t<120?[r,o,0]:t<180?[0,o,r]:t<240?[0,r,o]:t<300?[r,0,o]:[o,0,r];return[s+i,a+i,c+i]};function V1(t,e,n,o,r){let i=o&&typeof o=="object"?o:{},s=t.key,a=()=>{throw new Error(`esphome does not support ${e}.${n}`)};if(t.kind==="switch"&&e==="power"){let c=n==="toggle"?!(r.currentOn??!1):n==="turnOn";return n!=="toggle"&&n!=="turnOn"&&n!=="turnOff"&&a(),{type:B.SwitchCommandRequest,payload:Ke([St(s),Se(2,c)]),optimistic:{type:"power",state:{on:c}}}}if(t.kind==="light"){let c=[St(s)];if(e==="power"){let l=n==="toggle"?!(r.currentOn??!1):n==="turnOn";return n!=="toggle"&&n!=="turnOn"&&n!=="turnOff"&&a(),c.push(Se(2,!0),Se(3,l)),{type:B.LightCommandRequest,payload:Ke(c),optimistic:{type:"power",state:{on:l}}}}if(e==="brightness"){let l=n==="setBrightness"?Number(i.level):Math.min(100,Math.max(0,(r.currentLevel??0)+Number(i.delta)));return n!=="setBrightness"&&n!=="adjustBrightness"&&a(),c.push(Se(2,!0),Se(3,l>0),Se(4,!0),rr(5,lf(l))),{type:B.LightCommandRequest,payload:Ke(c),optimistic:{type:"brightness",state:{level:l}}}}if(e==="color"&&n==="setColor"){let l=Number(i.hue),u=Number(i.saturation),[d,f,m]=XG(l,u);return c.push(Se(2,!0),Se(3,!0),Se(6,!0),rr(7,d),rr(8,f),rr(9,m)),t.colorModes?.includes(Ye.RGB)&&c.push(Se(22,!0),{n:23,wire:0,value:Ye.RGB}),{type:B.LightCommandRequest,payload:Ke(c),optimistic:{type:"color",state:{hue:l,saturation:u}}}}if(e==="colorTemperature"&&n==="setColorTemperature"){let l=Number(i.kelvin);return c.push(Se(2,!0),Se(3,!0),Se(12,!0),rr(13,1e6/l)),{type:B.LightCommandRequest,payload:Ke(c),optimistic:{type:"colorTemperature",state:{kelvin:l}}}}a()}if(t.kind==="cover"&&e==="cover"){if(n==="stop")return{type:B.CoverCommandRequest,payload:Ke([St(s),Se(8,!0)]),optimistic:{type:"cover",state:{state:"stopped"}}};if(n==="open"||n==="close"){let c=n==="open"?100:0;return{type:B.CoverCommandRequest,payload:Ke([St(s),Se(4,!0),rr(5,lf(c))]),optimistic:{type:"cover",state:{position:c,state:n==="open"?"opening":"closing"}}}}if(n==="setPosition"){let c=Number(i.position);return{type:B.CoverCommandRequest,payload:Ke([St(s),Se(4,!0),rr(5,lf(c))]),optimistic:{type:"cover",state:{position:c,state:"partial"}}}}if(n==="setTilt"){let c=Number(i.tilt);return{type:B.CoverCommandRequest,payload:Ke([St(s),Se(6,!0),rr(7,lf(c))]),optimistic:{type:"cover",state:{tilt:c,state:"partial"}}}}a()}if(t.kind==="fan"&&e==="fan"){if(n==="turnOn"||n==="turnOff"){let c=n==="turnOn";return{type:B.FanCommandRequest,payload:Ke([St(s),Se(2,!0),Se(3,c)]),optimistic:{type:"fan",state:{on:c}}}}if(n==="setFanSpeed"){let c=Number(i.level);(typeof t.speedCount!="number"||t.speedCount<=0)&&a();let l=Math.round(c/100*t.speedCount),u=Math.min(t.speedCount,Math.max(0,l));return{type:B.FanCommandRequest,payload:Ke([St(s),Se(2,!0),Se(3,c>0),Se(10,!0),{n:11,wire:0,value:u}]),optimistic:{type:"fan",state:{on:c>0,level:c}}}}if(n==="setFanPreset"){let c=String(i.preset);return{type:B.FanCommandRequest,payload:Ke([St(s),Se(12,!0),{n:13,wire:2,value:c}]),optimistic:{type:"fan",state:{preset:c}}}}if(n==="setOscillate"){let c=!!i.oscillating;return{type:B.FanCommandRequest,payload:Ke([St(s),Se(6,!0),Se(7,c)]),optimistic:{type:"fan",state:{oscillating:c}}}}a()}if(t.kind==="lock"&&e==="lock"){n!=="lock"&&n!=="unlock"&&a();let c=n==="lock";return{type:B.LockCommandRequest,payload:Ke([St(s),{n:2,wire:0,value:c?1:0}]),optimistic:{type:"lock",state:{state:c?"locked":"unlocked"}}}}if(t.kind==="climate"&&e==="thermostat"){if(n==="setThermostatMode"){let c=String(i.mode),l=0;if(c==="auto"){let u=t.climateModeIds??[];u.includes(1)?l=1:u.includes(6)?l=6:a()}else{let u=Object.entries(Rx).find(([,d])=>d===c);u||a(),l=Number(u?.[0])}return{type:B.ClimateCommandRequest,payload:Ke([St(s),Se(2,!0),{n:3,wire:0,value:l}]),optimistic:{type:"thermostat",state:{mode:c}}}}if(n==="setSetpoint"){let c=Number(i.celsius);return{type:B.ClimateCommandRequest,payload:Ke([St(s),Se(4,!0),rr(5,c)]),optimistic:{type:"thermostat",state:{setpointC:c}}}}a()}if(t.kind==="number"&&e==="range"){n!=="setRange"&&n!=="adjustRange"&&a();let c=t.capability.type==="range"?t.capability.config:void 0,l=n==="setRange"?Number(i.value):YG((r.currentValue??0)+Number(i.delta),c);return{type:B.NumberCommandRequest,payload:Ke([St(s),rr(2,l)]),optimistic:{type:"range",state:{value:l}}}}if(t.kind==="select"&&e==="mode"&&n==="setMode"){let c=String(i.value);return{type:B.SelectCommandRequest,payload:Ke([St(s),{n:2,wire:2,value:c}]),optimistic:{type:"mode",state:{value:c}}}}return a()}var QG=new Set(["switch","light","cover","fan","lock","climate","number","select"]),e8=new Set(["sensor","binary_sensor"]);function X1(t){if(t.some(o=>o.kind==="light"))return"light";if(t.some(o=>o.kind==="climate"))return"thermostat";if(t.some(o=>o.kind==="lock"))return"lock";if(t.some(o=>o.kind==="cover"))return"cover";if(t.some(o=>o.kind==="fan"))return"fan";if(t.some(o=>o.kind==="switch"&&o.deviceClass==="outlet"))return"plug";if(t.some(o=>o.kind==="switch"))return"switch";let e=t.some(o=>e8.has(o.kind)),n=t.some(o=>QG.has(o.kind));return e&&!n?"sensor":"other"}var J1=[5e3,3e4,12e4],Uc=(t,e)=>`${t}|${e??""}`;function Y1(t,e){for(let n of e)t.state.set(Uc(n.type,n.instance),n)}var uf=class{constructor(e,n,o=Tx){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="esphome";reachability="local";client=null;keystore={devices:{}};runtime=new Map;onState=null;devicesChanged;retryTimers=new Map;disposed=!1;async init(e){this.client=this.clientFactory(),this.devicesChanged=e.devicesChanged,this.keystore=Ms(await e.localSecrets.read("keystore"))}async link(e,n){return{ok:!1,error:"ESPHome needs no pairing \u2014 connect it via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=[];for(let n of this.cfg.devices)e.push(await this.discoverRow(n));return{devices:e,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);i&&o.push({nativeId:r,patch:i.session?[...i.state.values()]:[],online:i.online,ts:Date.now()})}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown esphome device ${e}`);if(!s.session)throw new Error(`esphome device ${e} is offline`);let a=this.entityFor(s,n,i?.instance);if(!a)throw new Error(`no esphome entity backs ${n}${i?.instance?` (instance "${i.instance}")`:""} on ${e}`);let{type:c,payload:l,optimistic:u}=V1(a,n,o,r,this.ctxFor(s,a));try{await s.session.send(c,l)}catch(d){throw s.session=null,s.online=!1,this.devicesChanged?.(),d}return s.online=!0,Y1(s,[{type:u.type,instance:a.objectId,state:u.state}]),{state:u.state}}subscribe(e,n){return this.onState=e,()=>{this.onState=null}}async dispose(){this.disposed=!0,this.onState=null;for(let e of[...this.retryTimers.keys()])this.cancelReconnect(e);for(let e of this.runtime.values())e.session?.close();this.client?.close(),this.client=null}async discoverRow(e){let n=this.runtime.get(e.key);return n?.session||(n=await this.connectRow(e),this.runtime.set(e.key,n)),this.candidateFrom(e,n)}async connectRow(e){let n=this.need(),o=this.runtime.get(e.key),r=xx(this.keystore,e.key),i=r?{psk:r}:{},s=e.ip;try{let a=await he({ip:e.ip,fn:u=>n.connect(u,i),rediscover:()=>n.rediscover(e.key),onNewIp:u=>{s=u,this.cfg.onIpChange?.(e.key,u)},bail:()=>this.disposed});if(this.disposed)return a.close(),{ip:e.ip,online:!1,session:null,entities:o?.entities??[],state:new Map,failures:o?.failures??0};let c=a.entities.map(u=>Ax(u.type,u.payload)).filter(u=>u!==null);this.cancelReconnect(e.key);let l={ip:s,online:!0,session:a,entities:c,state:new Map,failures:0};return this.attach(e.key,l),l}catch{let a=(o?.failures??0)+1;return this.disposed||this.scheduleReconnect(e.key,a),{ip:e.ip,online:!1,session:null,entities:o?.entities??[],state:new Map,failures:a}}}scheduleReconnect(e,n){if(this.retryTimers.has(e))return;let o=J1[Math.min(n-1,J1.length-1)]??0,r=setTimeout(()=>{this.retryTimers.delete(e),this.disposed||this.devicesChanged?.()},o);r.unref?.(),this.retryTimers.set(e,r)}cancelReconnect(e){let n=this.retryTimers.get(e);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(e))}attach(e,n){let o=n.session;o&&o.onState((r,i)=>{if(this.disposed)return;let s=af(pi(i),1);if(s===void 0)return;let a=n.entities.find(l=>l.key===s);if(!a)return;let c=q1(r,i,a);c.length!==0&&(Y1(n,c),n.online=!0,this.onState?.({nativeId:e,patch:c,online:!0,ts:Date.now()}))})}candidateFrom(e,n){let o=n.session?.deviceInfo,r=n.entities.flatMap(i=>[i.capability,...Z1(i)]).map(i=>this.withCachedState(i,n));return{source:{provider:"esphome",providerAccountId:this.accountId,nativeId:e.key,reachability:"local",online:n.online,lastSeen:Date.now()},fingerprints:[`mac:${e.key}`],type:X1(n.entities),name:e.name??o?.name??"ESPHome device",manufacturer:o?.manufacturer??"ESPHome",model:e.model??o?.model??"ESPHome",capabilities:r}}withCachedState(e,n){let o=n.state.get(Uc(e.type,e.instance));if(!o||typeof o.state!="object"||o.state===null)return e;let r={...e};return typeof r.state=="object"&&r.state!==null&&(r.state={...r.state,...o.state}),r}entityFor(e,n,o){let r=e.entities.filter(i=>i.capability.type===n||(i.extras??[]).some(s=>s.type===n));return o!==void 0?r.find(i=>i.objectId===o):r[0]}ctxFor(e,n){let o={},r=e.state.get(Uc("power",n.objectId))?.state;typeof r?.on=="boolean"&&(o.currentOn=r.on);let i=e.state.get(Uc("brightness",n.objectId))?.state;typeof i?.level=="number"&&(o.currentLevel=i.level);let s=e.state.get(Uc("range",n.objectId))?.state;return typeof s?.value=="number"&&(o.currentValue=s.value),o}need(){if(!this.client)throw new Error("ESPHome adapter not initialized");return this.client}};function Q1(t,e=Tx){let n=e();return async(o,r,i)=>{let s=r?.encryptionKey??(i?.mac?xx(t(),i.mac):void 0);try{let a=await n.connect(o,s?{psk:s}:{}),{mac:c,name:l,model:u}=a.deviceInfo,d=a.entities.map(m=>Ax(m.type,m.payload)).filter(m=>m!==null);a.close();let f=X1(d);return{...c?{mac:c}:{},...l?{name:l}:{},...u?{model:u}:{},expectedType:f}}catch(a){return a instanceof ko?{badCredentials:"check the device's api encryption key"}:!s&&!(a instanceof Us)?{badCredentials:"this device refused an unencrypted connection \u2014 enter its api encryption key"}:null}}}var Px={minKelvin:1200,maxKelvin:6500},So=t=>typeof t=="number"&&Number.isFinite(t)?t:null,fi=t=>typeof t=="string"&&t?t:void 0,dn=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,Fc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function pf(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}let n=dn(e);if(!n)return{};let o={};for(let[r,i]of Object.entries(n)){let s=dn(i),a=s?fi(s.token):void 0;a&&(o[T(r)]={token:a})}return o}var df=(t,e)=>{let n=dn(t[e]);return n?So(n.value):null},t8=(t,e)=>{let n=dn(t[e]);if(!n)return null;let o=So(n.min),r=So(n.max);return o!==null&&r!==null?{min:o,max:r}:null};function Bc(t){let e=dn(t.state)??{},n=dn(e.ct)!==void 0,o=dn(e.hue)!==void 0&&dn(e.sat)!==void 0,r=t8(e,"ct");return{profile:{hasBrightness:!0,hasCt:n,hasColor:o},ctRange:r?{minKelvin:r.min,maxKelvin:r.max}:Px,...fi(t.name)?{name:fi(t.name)}:{},...fi(t.model)?{model:fi(t.model)}:{}}}function n8(t){let e=dn(t.effects),n=e?fi(e.select)??null:null,o=e?.effectsList,r=Array.isArray(o)?o.filter(i=>typeof i=="string"&&i.length>0):[];return{select:n,list:r}}function r8(t){let e=new Set,n=[];for(let o of n8(t).list)e.has(o)||(e.add(o),n.push({type:"scene",instance:o,state:{}}));return n}function eO(t){let e=dn(t.state)??{},n=dn(e.on),o=n&&typeof n.value=="boolean"?n.value:null,r=fi(e.colorMode);return{on:o,level:df(e,"brightness"),kelvin:r==="ct"?df(e,"ct"):null,hue:r==="hs"?df(e,"hue"):null,saturation:r==="hs"?df(e,"sat"):null}}function ff(t,e){let n=eO(e),o=[{type:"power",state:{on:n.on}}];return t.hasBrightness&&o.push({type:"brightness",state:{level:n.level}}),t.hasCt&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),t.hasColor&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),o}function tO(t,e){let n=Bc(t),o=eO(t),r=T(e.mac),i=[{type:"power",state:{on:o.on}}];return n.profile.hasBrightness&&i.push({type:"brightness",state:{level:o.level}}),n.profile.hasCt&&i.push({type:"colorTemperature",config:n.ctRange,state:{kelvin:o.kelvin}}),n.profile.hasColor&&i.push({type:"color",config:{modes:["hs"]},state:{hue:o.hue,saturation:o.saturation}}),i.push(...r8(t)),{source:{provider:"nanoleaf",providerAccountId:e.accountId,nativeId:r,...n.model?{nativeType:n.model}:{},reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${r}`],type:"light",name:e.nameOverride??n.name??"Nanoleaf",manufacturer:"Nanoleaf",model:n.model??null,capabilities:i}}function nO(t,e){return{source:{provider:"nanoleaf",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??"Nanoleaf",manufacturer:"Nanoleaf",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function rO(t,e,n,o,r,i){let s=dn(r)??{},a=()=>{throw new Error(`nanoleaf light does not support ${n}.${o}`)};if(n==="power"&&(o==="turnOn"||o==="turnOff"||o==="toggle")){let c;if(o==="toggle"){if(i.currentOn===void 0)throw new Error("nanoleaf toggle needs the current power state (pre-read failed)");c=!i.currentOn}else c=o==="turnOn";return{body:{on:{value:c}},optimistic:{type:"power",state:{on:c}}}}if(n==="brightness"&&(o==="setBrightness"||o==="adjustBrightness")){t.hasBrightness||a();let c;if(o==="adjustBrightness"){if(i.currentLevel===void 0)throw new Error("nanoleaf adjustBrightness needs the current level (pre-read failed)");c=Fc(i.currentLevel+(So(s.delta)??0),0,100)}else c=Fc(So(s.level)??0,0,100);return c===0?{body:{on:{value:!1}},optimistic:{type:"brightness",state:{level:0}}}:{body:{on:{value:!0},brightness:{value:c}},optimistic:{type:"brightness",state:{level:c}}}}if(n==="colorTemperature"&&o==="setColorTemperature"){t.hasCt||a();let c=Fc(So(s.kelvin)??e.minKelvin,e.minKelvin,e.maxKelvin);return{body:{on:{value:!0},ct:{value:c}},optimistic:{type:"colorTemperature",state:{kelvin:c}}}}if(n==="color"&&o==="setColor"){t.hasColor||a();let c=Fc(So(s.hue)??0,0,360),l=Fc(So(s.saturation)??0,0,100);return{body:{on:{value:!0},hue:{value:c},sat:{value:l}},optimistic:{type:"color",state:{hue:c,saturation:l}}}}return a()}function oO(t,e,n){return ff(t,e).find(o=>o.type===n)?.state}var iO=16021,o8="Hold the Nanoleaf power/on-off button for 5\u20137 seconds until the LEDs flash, then Connect again. On newer Nanoleaf (Matter/Essentials) with no button, open the pairing window in the Nanoleaf app (Device settings \u2192 Connect to API), then Connect.",i8=1e4,mf=class{constructor(e,n,o=aO){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="nanoleaf";reachability="local";client=null;keystore={};runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory(),this.keystore=pf(await e.localSecrets.read("keystore"))}async link(e,n){return{ok:!1,error:"Nanoleaf pairs from the local Connect flow \u2014 hold the panel's button until it flashes, then Connect (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=this.keystore[o.key]?.token,i=r?await this.locate(e,o,r):null;if(i){let s=Bc(i.raw);this.runtime.set(o.key,{ip:i.ip,token:r,profile:s.profile,ctRange:s.ctRange,online:!0}),n.push(tO(i.raw,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{}}))}else r&&this.runtime.set(o.key,{ip:o.ip,token:r,profile:{hasBrightness:!0,hasCt:!1,hasColor:!1},ctRange:Px,online:!1}),n.push(nO(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshState(r);i.online=!0,o.push({nativeId:r,patch:ff(i.profile,s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown nanoleaf device ${e}`);if(n==="scene"){if(o!=="activate")throw new Error(`unsupported nanoleaf scene command ${o}`);let u=i?.instance;if(!u)throw new Error("nanoleaf scene.activate needs the effect name (instance)");return await this.withIpRetry(e,d=>this.need().putEffect(d,s.token,u)),s.online=!0,{state:{lastActivated:Date.now()}}}let a={};if(o==="toggle"||o==="adjustBrightness"){let u=ff(s.profile,await this.freshState(e)),d=u.find(m=>m.type==="power")?.state,f=u.find(m=>m.type==="brightness")?.state;typeof d?.on=="boolean"&&(a.currentOn=d.on),typeof f?.level=="number"&&(a.currentLevel=f.level)}let{body:c,optimistic:l}=rO(s.profile,s.ctRange,n,o,r,a);if(await this.withIpRetry(e,u=>this.need().putState(u,s.token,c)),s.online=!0,i?.readAfter){let u=oO(s.profile,await this.freshState(e),n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??i8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown nanoleaf device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async freshState(e){let n=this.runtime.get(e);if(!n)throw new Error(`unknown nanoleaf device ${e}`);return this.withIpRetry(e,o=>this.need().getState(o,n.token))}async locate(e,n,o){let r=async i=>({ip:i,raw:await e.getState(i,o)});try{return await r(n.ip)}catch{try{let i=await e.rediscover(n.key);if(!i||i===n.ip)return null;let s=await r(i);return this.cfg.onIpChange?.(n.key,i),s}catch{return null}}}need(){if(!this.client)throw new Error("Nanoleaf adapter not initialized");return this.client}};function sO(t,e=aO){let n=e();return async(o,r,i)=>{let s=i?.mac?T(i.mac):void 0;if(s){let u=t.read()[s]?.token;if(u)try{let d=Bc(await n.getState(o,u));return{mac:s,...d.name?{name:d.name}:{},...d.model?{model:d.model}:{}}}catch{}}let a;try{a=await n.pairNew(o)}catch{return null}if(a===null)return{pairingRequired:o8};let c=s??await n.macForIp(o).then(u=>u?T(u):void 0).catch(()=>{});if(c){let u=t.read();u[c]={token:a},t.write(u)}let l={};try{l=Bc(await n.getState(o,a))}catch{}return{...c?{mac:c}:{},...l.name?{name:l.name}:{},...l.model?{model:l.model}:{}}}}var s8=4e3,aO=()=>{let t=!1,e=async(n,o,r,i)=>{if(t)throw new Error("nanoleaf client closed");let s=await import("node:http"),a=i===void 0?void 0:JSON.stringify(i);return new Promise((c,l)=>{let u=s.request({host:n,port:iO,method:o,path:r,headers:a!==void 0?{"content-type":"application/json","content-length":Buffer.byteLength(a)}:{}},f=>{let m="";f.setEncoding("utf8"),f.on("data",g=>m+=g),f.on("end",()=>c({status:f.statusCode??0,text:m}))}),d=setTimeout(()=>{u.destroy(new Error(`nanoleaf request timeout (${n}:${iO})`))},s8);d.unref?.(),u.on("error",f=>{clearTimeout(d),l(f instanceof Error?f:new Error(String(f)))}),u.on("close",()=>clearTimeout(d)),a!==void 0&&u.write(a),u.end()})};return{async pairNew(n){let{status:o,text:r}=await e(n,"POST","/api/v1/new",{});if(o===403||o===401)return null;if(o<200||o>=300)throw new Error(`nanoleaf pair failed (HTTP ${o})`);let i=JSON.parse(r).auth_token;if(typeof i!="string"||!i)throw new Error("nanoleaf pair: no auth_token in response");return i},async getState(n,o){let{status:r,text:i}=await e(n,"GET",`/api/v1/${o}/`);if(r<200||r>=300)throw new Error(`nanoleaf getState failed (HTTP ${r})`);return JSON.parse(i)},async putState(n,o,r){let{status:i}=await e(n,"PUT",`/api/v1/${o}/state`,r);if(i<200||i>=300)throw new Error(`nanoleaf putState failed (HTTP ${i})`)},async putEffect(n,o,r){let{status:i}=await e(n,"PUT",`/api/v1/${o}/effects`,{select:r});if(i<200||i>=300)throw new Error(`nanoleaf putEffect failed (HTTP ${i})`)},macForIp(n){return dt(n)},rediscover(n){return se(n)},close(){t=!0}}};var hf={minKelvin:2200,maxKelvin:6500};function Fs(t){let e=zd(t);return e.expectedCapabilities.includes("fan")?{type:"fan",hasBrightness:!0,hasCt:e.expectedCapabilities.includes("colorTemperature"),hasColor:!1}:{type:e.expectedType,hasBrightness:e.expectedCapabilities.includes("brightness"),hasCt:e.expectedCapabilities.includes("colorTemperature"),hasColor:e.expectedCapabilities.includes("color")}}var pn=t=>typeof t=="number"&&Number.isFinite(t)?t:null,a8=t=>typeof t=="string"&&t?t:void 0,gf=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;function mi(t,e={}){return JSON.stringify({method:t,params:e})}function _o(t){let e=gf(t),n=gf(e?.error);if(n)throw new Error(`wiz error ${pn(n.code)??"?"}: ${a8(n.message)??"request failed"}`);let o=gf(e?.result);if(!o)throw new Error("wiz reply has no result");return o}function cO(t){if(_o(t).success!==!0)throw new Error("wiz setPilot refused (success!=true)")}function lO(t){try{let e=_o(t).cctRange;if(Array.isArray(e)){let n=e.filter(o=>typeof o=="number"&&Number.isFinite(o)&&o>0);if(n.length>=2)return{minKelvin:Math.min(...n),maxKelvin:Math.max(...n)}}}catch{}return hf}function c8(t,e){let n=(t%360+360)%360/60,r=Math.max(0,Math.min(100,e))/100,i=r*(1-Math.abs(n%2-1)),s=1-r,[a,c,l]=n<1?[r,i,0]:n<2?[i,r,0]:n<3?[0,r,i]:n<4?[0,i,r]:n<5?[i,0,r]:[r,0,i];return{r:Math.round((a+s)*255),g:Math.round((c+s)*255),b:Math.round((l+s)*255)}}function l8(t,e,n){let o=t/255,r=e/255,i=n/255,s=Math.max(o,r,i),a=Math.min(o,r,i),c=s-a;if(c===0||s===0)return{hue:0,saturation:0};let l;return s===o?l=(r-i)/c%6:s===r?l=(i-o)/c+2:l=(o-r)/c+4,{hue:Math.round(((l*60+360)%360+360)%360),saturation:Math.round(c/s*100)}}function uO(t){let e=typeof t.state=="boolean"?t.state:null,n=pn(t.temp),o=pn(t.r),r=pn(t.g),i=pn(t.b),s=o!==null&&r!==null&&i!==null?l8(o,r,i):null;return{on:e,level:pn(t.dimming),kelvin:n!==null&&n>0?n:null,hue:s?s.hue:null,saturation:s?s.saturation:null}}function Dx(t,e){let n=uO(e),o=[{type:"power",state:{on:n.on}}];return t.hasBrightness&&o.push({type:"brightness",state:{level:n.level}}),t.hasCt&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),t.hasColor&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),o}function dO(t,e){let n=Fs(e.moduleName),o=uO(t),r=T(e.mac),i=[{type:"power",state:{on:o.on}}];return n.hasBrightness&&i.push({type:"brightness",state:{level:o.level}}),n.hasCt&&i.push({type:"colorTemperature",config:e.ctRange,state:{kelvin:o.kelvin}}),n.hasColor&&i.push({type:"color",config:{modes:["hs"]},state:{hue:o.hue,saturation:o.saturation}}),i.push(...d8(n)),{source:{provider:"wiz",providerAccountId:e.accountId,nativeId:r,nativeType:e.moduleName,reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${r}`],type:n.type,name:e.nameOverride??e.moduleName,manufacturer:"WiZ",model:e.moduleName,capabilities:i}}function pO(t,e){let n=Fs(t.model??"");return{source:{provider:"wiz",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:n.type,name:t.name??t.model??"WiZ device",manufacturer:"WiZ",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}var fO=[{id:1,name:"Ocean"},{id:2,name:"Romance"},{id:3,name:"Sunset"},{id:4,name:"Party"},{id:5,name:"Fireplace"},{id:6,name:"Cozy"},{id:7,name:"Forest"},{id:8,name:"Pastel Colors"},{id:9,name:"Wake up"},{id:10,name:"Bedtime"},{id:11,name:"Warm White"},{id:12,name:"Daylight"},{id:13,name:"Cool White"},{id:14,name:"Night Light"},{id:15,name:"Focus"},{id:16,name:"Relax"},{id:17,name:"True Colors"},{id:18,name:"TV Time"},{id:19,name:"Plant Growth"},{id:20,name:"Spring"},{id:21,name:"Summer"},{id:22,name:"Fall"},{id:23,name:"Deep Dive"},{id:24,name:"Jungle"},{id:25,name:"Mojito"},{id:26,name:"Club"},{id:27,name:"Christmas"},{id:28,name:"Halloween"},{id:29,name:"Candlelight"},{id:30,name:"Golden White"},{id:31,name:"Pulse"},{id:32,name:"Steampunk"}],u8=new Map(fO.map(t=>[t.name,t.id]));function d8(t){return t.hasColor?fO.map(e=>({type:"scene",instance:e.name,state:{}})):[]}var jc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function mO(t,e,n,o,r,i,s){let a=gf(r)??{},c=()=>{throw new Error(`wiz ${t.type} does not support ${n}.${o}`)};if(n==="scene"&&o==="activate"){let l=s!==void 0?u8.get(s):void 0;if(l===void 0)throw new Error(`wiz: unknown scene ${s??"(none given)"}`);return{params:{state:!0,sceneId:l},optimistic:{type:"scene",state:{}}}}if(n==="power"&&(o==="turnOn"||o==="turnOff"||o==="toggle")){let l;if(o==="toggle"){if(i.currentOn===void 0)throw new Error("wiz toggle needs the current power state (pre-read failed)");l=!i.currentOn}else l=o==="turnOn";return{params:{state:l},optimistic:{type:"power",state:{on:l}}}}if(n==="brightness"&&(o==="setBrightness"||o==="adjustBrightness")){t.hasBrightness||c();let l;if(o==="adjustBrightness"){if(i.currentLevel===void 0)throw new Error("wiz adjustBrightness needs the current level (pre-read failed)");l=jc(i.currentLevel+(pn(a.delta)??0),0,100)}else l=jc(pn(a.level)??0,0,100);if(l===0)return{params:{state:!1},optimistic:{type:"brightness",state:{level:0}}};let u=Math.max(10,l);return{params:{state:!0,dimming:u},optimistic:{type:"brightness",state:{level:u}}}}if(n==="colorTemperature"&&o==="setColorTemperature"){t.hasCt||c();let l=jc(pn(a.kelvin)??e.minKelvin,e.minKelvin,e.maxKelvin);return{params:{state:!0,temp:l},optimistic:{type:"colorTemperature",state:{kelvin:l}}}}if(n==="color"&&o==="setColor"){t.hasColor||c();let l=jc(pn(a.hue)??0,0,360),u=jc(pn(a.saturation)??0,0,100);if(u===0)return{params:{state:!0,c:255,w:255},optimistic:{type:"color",state:{hue:l,saturation:0}}};let{r:d,g:f,b:m}=c8(l,u);return{params:{state:!0,r:d,g:f,b:m},optimistic:{type:"color",state:{hue:l,saturation:u}}}}return c()}function $x(t){let e;try{e=_o(t)}catch{return null}let n=pn(e.power);return n===null?null:{type:"energyMeter",state:{power:n/1e3,energy:null,voltage:null,current:null}}}function gO(t,e,n){return Dx(t,e).find(o=>o.type===n)?.state}var p8=1e4,f8=2e3,m8=1e3,Ox=t=>typeof t=="string"&&t?t:void 0,yf=class{constructor(e,n,o=yO){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="wiz";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"WiZ devices need no pairing \u2014 connect them via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);if(r){let i=Fs(r.moduleName),s=i.type==="plug"?await e.request(r.ip,mi("getPower")).then($x).catch(()=>null):null;this.runtime.set(o.key,{ip:r.ip,profile:i,ctRange:r.ctRange,moduleName:r.moduleName,online:!0,hasEnergy:s!==null});let a=dO(r.pilot,{accountId:this.accountId,mac:o.key,moduleName:r.moduleName,ctRange:r.ctRange,now:Date.now(),...o.name?{nameOverride:o.name}:{}});s&&a.capabilities.push({type:"energyMeter",state:{power:null,energy:null,voltage:null,current:null}}),n.push(a)}else this.runtime.set(o.key,{ip:o.ip,profile:Fs(o.model??""),ctRange:hf,moduleName:o.model??"",online:!1,hasEnergy:!1}),n.push(pO(o,{accountId:this.accountId,now:Date.now()}))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshPilot(r),a=Dx(i.profile,s);if(i.hasEnergy)try{let c=$x(await this.withIpRetry(r,l=>this.need().request(l,mi("getPower"))));c&&a.push(c)}catch{}i.online=!0,o.push({nativeId:r,patch:a,online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown wiz device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let d=await this.freshPilot(e);typeof d.state=="boolean"&&(a.currentOn=d.state),typeof d.dimming=="number"&&(a.currentLevel=d.dimming)}let{params:c,optimistic:l}=mO(s.profile,s.ctRange,n,o,r,a,i?.instance),u=await this.withIpRetry(e,d=>this.need().request(d,mi("setPilot",c)));if(cO(u),s.online=!0,i?.readAfter){let d=await this.freshPilot(e),f=gO(s.profile,d,n);return{state:f,verifiedState:f,result:u}}return{state:l.state,result:u}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??p8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown wiz device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async freshPilot(e){return _o(await this.withIpRetry(e,n=>this.need().request(n,mi("getPilot"))))}async locate(e,n){let o=async r=>{let i=_o(await e.request(r,ri)),s=Ox(i.moduleName)??"",c=Fs(s).hasCt?lO(await e.request(r,mi("getModelConfig")).catch(()=>null)):hf,l=_o(await e.request(r,mi("getPilot")));return{ip:r,moduleName:s,ctRange:c,pilot:l}};try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("WiZ adapter not initialized");return this.client}};function hO(t=yO){let e=t();return async n=>{try{let o=_o(await e.request(n,ri)),r=we(Ox(o.mac)),i=Ox(o.moduleName);return{...r?{mac:r}:{},...i?{model:i}:{}}}catch{return null}}}var yO=()=>{let t=!1,e=new Set;return{async request(n,o){if(t)throw new Error("wiz client closed");let r=await import("node:dgram");return new Promise((i,s)=>{let a=r.createSocket("udp4"),c=!1,l=d=>{if(!c){c=!0,e.delete(l);try{a.close()}catch{}s(d)}};e.add(l);let u=setTimeout(()=>l(new Error(`wiz request timeout (${n}:${In})`)),f8);u.unref?.(),a.on("error",d=>{clearTimeout(u),l(d instanceof Error?d:new Error(String(d)))}),a.on("message",(d,f)=>{if(f.address===n&&!c){c=!0,e.delete(l),clearTimeout(u);try{a.close()}catch{}try{i(JSON.parse(d.toString("utf8")))}catch(m){s(m instanceof Error?m:new Error(String(m)))}}}),a.send(o,In,n,d=>{d&&(clearTimeout(u),l(d))})})},async rediscover(n){let o=T(n),r=await import("node:dgram"),i=await new Promise(s=>{let a=r.createSocket("udp4"),c=!1,l=d=>{if(!c){c=!0;try{a.close()}catch{}s(d)}},u=setTimeout(()=>l(void 0),m8);u.unref?.(),a.on("error",()=>l(void 0)),a.on("message",(d,f)=>{try{let g=JSON.parse(d.toString("utf8")).result,h=g&&typeof g=="object"?g.mac:void 0,y=we(typeof h=="string"?h:void 0);y&&y===o&&(clearTimeout(u),l(f.address))}catch{}}),a.bind(()=>{try{a.setBroadcast(!0),a.send(jd,In,"255.255.255.255",d=>{d&&l(void 0)})}catch{l(void 0)}})});return i||se(o)},close(){t=!0;for(let n of[...e])n(new Error("wiz client closed"));e.clear()}}};var vO=80,g8=1e4,h8=4e3,vf=class{constructor(e,n,o=wO){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="wled";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"WLED needs no pairing \u2014 connect it via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);r?(this.runtime.set(o.key,{ip:r.ip,online:!0}),n.push(o1(r.state,r.info,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{}}))):(this.runtime.set(o.key,{ip:o.ip,online:!1}),n.push(i1(o,{accountId:this.accountId,now:Date.now()})))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let{state:s}=await this.fresh(r);i.online=!0,o.push({nativeId:r,patch:Gp(s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown wled device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let u=Gp((await this.fresh(e)).state),d=u.find(m=>m.type==="power")?.state,f=u.find(m=>m.type==="brightness")?.state;typeof d?.on=="boolean"&&(a.currentOn=d.on),typeof f?.level=="number"&&(a.currentLevel=f.level)}let{body:c,optimistic:l}=a1(n,o,r,a);if(await this.withIpRetry(e,u=>this.need().setState(u,c)),s.online=!0,i?.readAfter){let u=c1((await this.fresh(e)).state,n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??g8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown wled device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}fresh(e){return this.withIpRetry(e,n=>this.need().get(n))}async locate(e,n){let o=async r=>({ip:r,...await e.get(r)});try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("WLED adapter not initialized");return this.client}};function bO(t=wO){let e=t();return async n=>{try{let{info:o}=await e.get(n),r=s1(o),i=typeof o.name=="string"&&o.name?o.name:void 0;return{...r?{mac:r}:{},...i?{name:i}:{},model:"WLED"}}catch{return null}}}var wO=()=>{let t=!1,e=async(n,o,r,i)=>{if(t)throw new Error("wled client closed");let s=await import("node:http"),a=i===void 0?void 0:JSON.stringify(i);return new Promise((c,l)=>{let u=s.request({host:n,port:vO,method:o,path:r,headers:a!==void 0?{"content-type":"application/json","content-length":Buffer.byteLength(a)}:{}},f=>{let m="";f.setEncoding("utf8"),f.on("data",g=>m+=g),f.on("end",()=>c({status:f.statusCode??0,text:m}))}),d=setTimeout(()=>u.destroy(new Error(`wled request timeout (${n}:${vO})`)),h8);d.unref?.(),u.on("error",f=>{clearTimeout(d),l(f instanceof Error?f:new Error(String(f)))}),u.on("close",()=>clearTimeout(d)),a!==void 0&&u.write(a),u.end()})};return{async get(n){let{status:o,text:r}=await e(n,"GET","/json");if(o<200||o>=300)throw new Error(`wled get failed (HTTP ${o})`);let i=JSON.parse(r),s=i.state&&typeof i.state=="object"?i.state:{},a=i.info&&typeof i.info=="object"?i.info:{};return{state:s,info:a}},async setState(n,o){let{status:r}=await e(n,"POST","/json/state",o);if(r<200||r>=300)throw new Error(`wled setState failed (HTTP ${r})`)},rediscover(n){return se(n)},close(){t=!0}}};var Bs=t=>typeof t=="number"&&Number.isFinite(t)?t:null,Lx=t=>typeof t=="string"&&t?t:void 0,kO=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,bf=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t))),xO=143,SO=344,wf={minKelvin:Math.round(1e6/SO),maxKelvin:Math.round(1e6/xO)},y8=t=>bf(Math.round(1e6/t),xO,SO),_O=t=>Math.round(1e6/t);function v8(t){let e=Array.isArray(t.lights)?t.lights:[];return kO(e[0])}function IO(t){let e=v8(t)??{},n=Bs(e.on),o=Bs(e.temperature);return{on:n===null?null:n!==0,level:Bs(e.brightness),kelvin:o!==null&&o>0?_O(o):null}}function kf(t){let e=IO(t);return[{type:"power",state:{on:e.on}},{type:"brightness",state:{level:e.level}},{type:"colorTemperature",state:{kelvin:e.kelvin}}]}function TO(t,e,n){let o=IO(t),r=T(n.mac),i=[{type:"power",state:{on:o.on}},{type:"brightness",state:{level:o.level}},{type:"colorTemperature",config:wf,state:{kelvin:o.kelvin}}];return{source:{provider:"elgato",providerAccountId:n.accountId,nativeId:r,reachability:"local",online:!0,lastSeen:n.now},fingerprints:[`mac:${r}`],type:"light",name:n.nameOverride??Lx(e.displayName)??Lx(e.productName)??"Elgato Key Light",manufacturer:"Elgato",model:Lx(e.productName)??"Key Light",capabilities:i}}function EO(t,e){return{source:{provider:"elgato",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??"Elgato Key Light",manufacturer:"Elgato",model:t.model??"Key Light",capabilities:[{type:"power",state:{on:null}}]}}function CO(t,e,n,o){let r=kO(n)??{},i=a=>({lights:[a]}),s=()=>{throw new Error(`elgato does not support ${t}.${e}`)};if(t==="power"&&(e==="turnOn"||e==="turnOff"||e==="toggle")){let a;if(e==="toggle"){if(o.currentOn===void 0)throw new Error("elgato toggle needs the current power state (pre-read failed)");a=!o.currentOn}else a=e==="turnOn";return{body:i({on:a?1:0}),optimistic:{type:"power",state:{on:a}}}}if(t==="brightness"&&(e==="setBrightness"||e==="adjustBrightness")){let a;if(e==="adjustBrightness"){if(o.currentLevel===void 0)throw new Error("elgato adjustBrightness needs the current level (pre-read failed)");a=bf(o.currentLevel+(Bs(r.delta)??0),0,100)}else a=bf(Bs(r.level)??0,0,100);return a===0?{body:i({on:0}),optimistic:{type:"brightness",state:{level:0}}}:{body:i({on:1,brightness:a}),optimistic:{type:"brightness",state:{level:a}}}}if(t==="colorTemperature"&&e==="setColorTemperature"){let a=bf(Bs(r.kelvin)??wf.minKelvin,wf.minKelvin,wf.maxKelvin),c=y8(a);return{body:i({on:1,temperature:c}),optimistic:{type:"colorTemperature",state:{kelvin:_O(c)}}}}return s()}function RO(t,e){return kf(t).find(n=>n.type===e)?.state}var AO=9123,b8=1e4,w8=4e3,xf=class{constructor(e,n,o=DO){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="elgato";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"Elgato Key Light needs no pairing \u2014 connect it via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);r?(this.runtime.set(o.key,{ip:r.ip,online:!0}),n.push(TO(r.lights,r.info,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{}}))):(this.runtime.set(o.key,{ip:o.ip,online:!1}),n.push(EO(o,{accountId:this.accountId,now:Date.now()})))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let{lights:s}=await this.fresh(r);i.online=!0,o.push({nativeId:r,patch:kf(s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown elgato device ${e}`);let a={};if(o==="toggle"||o==="adjustBrightness"){let u=kf((await this.fresh(e)).lights),d=u.find(m=>m.type==="power")?.state,f=u.find(m=>m.type==="brightness")?.state;typeof d?.on=="boolean"&&(a.currentOn=d.on),typeof f?.level=="number"&&(a.currentLevel=f.level)}let{body:c,optimistic:l}=CO(n,o,r,a);if(await this.withIpRetry(e,u=>this.need().setState(u,c)),s.online=!0,i?.readAfter){let u=RO((await this.fresh(e)).lights,n);return{state:u,verifiedState:u}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??b8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown elgato device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}fresh(e){return this.withIpRetry(e,n=>this.need().get(n))}async locate(e,n){let o=async r=>({ip:r,...await e.get(r)});try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("Elgato adapter not initialized");return this.client}};function PO(t=DO){let e=t();return async n=>{try{let{info:o}=await e.get(n),r=await e.macForIp(n).then(a=>a?T(a):void 0).catch(()=>{}),i=typeof o.displayName=="string"&&o.displayName?o.displayName:void 0,s=typeof o.productName=="string"&&o.productName?o.productName:"Key Light";return{...r?{mac:r}:{},...i?{name:i}:{},model:s}}catch{return null}}}var DO=()=>{let t=!1,e=async(o,r,i,s)=>{if(t)throw new Error("elgato client closed");let a=await import("node:http"),c=s===void 0?void 0:JSON.stringify(s);return new Promise((l,u)=>{let d=a.request({host:o,port:AO,method:r,path:i,headers:c!==void 0?{"content-type":"application/json","content-length":Buffer.byteLength(c)}:{}},m=>{let g="";m.setEncoding("utf8"),m.on("data",h=>g+=h),m.on("end",()=>l({status:m.statusCode??0,text:g}))}),f=setTimeout(()=>d.destroy(new Error(`elgato request timeout (${o}:${AO})`)),w8);f.unref?.(),d.on("error",m=>{clearTimeout(f),u(m instanceof Error?m:new Error(String(m)))}),d.on("close",()=>clearTimeout(f)),c!==void 0&&d.write(c),d.end()})},n=async(o,r)=>{let{status:i,text:s}=await e(o,"GET",r);if(i<200||i>=300)throw new Error(`elgato GET ${r} failed (HTTP ${i})`);return JSON.parse(s)};return{async get(o){let r=await n(o,"/elgato/lights"),i=await n(o,"/elgato/accessory-info").catch(()=>({}));return{lights:r,info:i}},async setState(o,r){let{status:i}=await e(o,"PUT","/elgato/lights",r);if(i<200||i>=300)throw new Error(`elgato setState failed (HTTP ${i})`)},macForIp(o){return dt(o)},rediscover(o){return se(o)},close(){t=!0}}};var Io=(t,e)=>{let o=new RegExp(`<${e}[^>]*>([^<]*)</${e}>`,"i").exec(t)?.[1]?.trim();return o||void 0};function $O(t){let e=Io(t,"user-device-name")??Io(t,"friendly-device-name")??Io(t,"default-device-name"),n=Io(t,"model-name")??Io(t,"vendor-name"),o=Io(t,"power-mode"),r=Io(t,"wifi-mac")??Io(t,"ethernet-mac"),i=r&&/^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/i.test(r)?T(r):void 0;return{...e?{name:e}:{},...n?{model:n}:{},powerOn:o===void 0?null:o==="PowerOn",...i?{mac:i}:{}}}function OO(t,e){let n=T(e.mac),o=[{type:"power",state:{on:t.powerOn}},{type:"mediaTransport",state:{state:null}},{type:"volume",state:{level:null,muted:null}}];return{source:{provider:"roku",providerAccountId:e.accountId,nativeId:n,reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${n}`],type:"tv",name:e.nameOverride??t.name??"Roku",manufacturer:"Roku",model:t.model??"Roku",capabilities:o}}function LO(t,e){return{source:{provider:"roku",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"tv",name:t.name??"Roku",manufacturer:"Roku",model:t.model??"Roku",capabilities:[{type:"power",state:{on:null}}]}}function NO(t){return[{type:"power",state:{on:t.powerOn}}]}function MO(t,e,n,o){let r=n&&typeof n=="object"?n:{},i=()=>{throw new Error(`roku does not support ${t}.${e}`)};if(t==="power"){if(e==="turnOn")return{key:"PowerOn",optimistic:{type:"power",state:{on:!0}}};if(e==="turnOff")return{key:"PowerOff",optimistic:{type:"power",state:{on:!1}}};if(e==="toggle"){if(o.currentOn===void 0)throw new Error("roku toggle needs the current power state (pre-read failed)");let s=!o.currentOn;return{key:s?"PowerOn":"PowerOff",optimistic:{type:"power",state:{on:s}}}}}if(t==="mediaTransport"){if(e==="play")return{key:"Play",optimistic:{type:"mediaTransport",state:{state:"playing"}}};if(e==="pause")return{key:"Play",optimistic:{type:"mediaTransport",state:{state:"paused"}}};if(e==="next")return{key:"Fwd",optimistic:{type:"mediaTransport",state:{state:null}}};if(e==="previous")return{key:"Rev",optimistic:{type:"mediaTransport",state:{state:null}}}}if(t==="volume"){if(e==="adjustVolume"){let s=typeof r.delta=="number"?r.delta:0;return s===0&&i(),{key:s>0?"VolumeUp":"VolumeDown",optimistic:{type:"volume",state:{}}}}if(e==="setMute")return{key:"VolumeMute",optimistic:{type:"volume",state:{muted:typeof r.muted=="boolean"?r.muted:!1}}}}return i()}var UO=8060,k8=15e3,x8=4e3,Sf=class{constructor(e,n,o=BO){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="roku";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"Roku needs no pairing \u2014 connect it via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);r?(this.runtime.set(o.key,{ip:r.ip,online:!0}),n.push(OO(r.info,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{}}))):(this.runtime.set(o.key,{ip:o.ip,online:!1}),n.push(LO(o,{accountId:this.accountId,now:Date.now()})))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.fresh(r);i.online=!0,o.push({nativeId:r,patch:NO(s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown roku device ${e}`);let a={};if(n==="power"&&o==="toggle"){let u=await this.fresh(e);typeof u.powerOn=="boolean"&&(a.currentOn=u.powerOn)}let{key:c,optimistic:l}=MO(n,o,r,a);if(await this.withIpRetry(e,u=>this.need().keypress(u,c)),s.online=!0,i?.readAfter&&n==="power"){let u=await this.fresh(e);return{state:{on:u.powerOn},verifiedState:{on:u.powerOn}}}return{state:l.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??k8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown roku device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}fresh(e){return this.withIpRetry(e,n=>this.need().deviceInfo(n))}async locate(e,n){let o=async r=>({ip:r,info:await e.deviceInfo(r)});try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("Roku adapter not initialized");return this.client}};function FO(t=BO){let e=t();return async n=>{try{let o=await e.deviceInfo(n),r=o.mac??await e.macForIp(n).then(i=>i?T(i):void 0).catch(()=>{});return{...r?{mac:r}:{},...o.name?{name:o.name}:{},model:o.model??"Roku"}}catch{return null}}}var BO=()=>{let t=!1,e=async(n,o,r)=>{if(t)throw new Error("roku client closed");let i=await import("node:http");return new Promise((s,a)=>{let c=i.request({host:n,port:UO,method:o,path:r},u=>{let d="";u.setEncoding("utf8"),u.on("data",f=>d+=f),u.on("end",()=>s({status:u.statusCode??0,text:d}))}),l=setTimeout(()=>c.destroy(new Error(`roku request timeout (${n}:${UO})`)),x8);l.unref?.(),c.on("error",u=>{clearTimeout(l),a(u instanceof Error?u:new Error(String(u)))}),c.on("close",()=>clearTimeout(l)),c.end()})};return{async deviceInfo(n){let{status:o,text:r}=await e(n,"GET","/query/device-info");if(o<200||o>=300)throw new Error(`roku device-info failed (HTTP ${o})`);return $O(r)},async keypress(n,o){let{status:r}=await e(n,"POST",`/keypress/${encodeURIComponent(o)}`);if(r<200||r>=300)throw new Error(`roku keypress ${o} failed (HTTP ${r})`)},macForIp(n){return dt(n)},rediscover(n){return se(n)},close(){t=!0}}};var Nx=1700,zO=6500,jO={minKelvin:Nx,maxKelvin:zO},S8={color:{minKelvin:1700,maxKelvin:6500},color1:{minKelvin:1700,maxKelvin:6500},color2:{minKelvin:2700,maxKelvin:6500},strip1:{minKelvin:1700,maxKelvin:6500},bslamp1:{minKelvin:1700,maxKelvin:6500},ceiling1:{minKelvin:2700,maxKelvin:6500},ceiling2:{minKelvin:2700,maxKelvin:6500},ceiling3:{minKelvin:2700,maxKelvin:6e3},ceiling4:{minKelvin:2700,maxKelvin:6500}},_8={ceiling:{minKelvin:2700,maxKelvin:6500},color:{minKelvin:1700,maxKelvin:6500},strip:{minKelvin:1700,maxKelvin:6500},stripe:{minKelvin:1700,maxKelvin:6500},bslamp:{minKelvin:1700,maxKelvin:6500}};function I8(t){if(!t)return jO;let e=S8[t];if(e)return e;for(let[n,o]of Object.entries(_8))if(t.startsWith(n))return o;return jO}var js=["smooth",300],_f=["power","bright","ct","rgb","hue","sat","color_mode","name","bg_power","bg_bright","bg_ct","bg_rgb","bg_hue","bg_sat"],Br="bg",Xe=t=>typeof t=="number"&&Number.isFinite(t)?t:typeof t=="string"&&t.trim()!==""&&Number.isFinite(Number(t))?Number(t):null,HO=t=>typeof t=="string"&&t?t:void 0,T8=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,zc=(t,e,n)=>Math.max(e,Math.min(n,Math.round(t)));function Mx(t){let e={};return _f.forEach((n,o)=>{let r=t[o];e[n]=typeof r=="string"?r:r==null?"":String(r)}),e}function Ux(t){let e=HO(t.bg_power)!==void 0;return{hasBrightness:!0,hasCt:Xe(t.ct)!==null,hasColor:Xe(t.rgb)!==null,hasBg:e,hasBgCt:e&&Xe(t.bg_ct)!==null,hasBgColor:e&&Xe(t.bg_rgb)!==null}}function KO(t,e,n){let o=t/255,r=e/255,i=n/255,s=Math.max(o,r,i),a=Math.min(o,r,i),c=s-a;if(c===0||s===0)return{hue:0,saturation:0};let l;return s===o?l=(r-i)/c%6:s===r?l=(i-o)/c+2:l=(o-r)/c+4,{hue:Math.round(((l*60+360)%360+360)%360),saturation:Math.round(c/s*100)}}var GO=t=>({r:t>>16&255,g:t>>8&255,b:t&255});function WO(t){let e=t.power,n=e==="on"?!0:e==="off"?!1:null,o=t.color_mode,r=o==="2"?Xe(t.ct):null,i=null,s=null;if(o==="3")i=Xe(t.hue),s=Xe(t.sat);else if(o==="1"){let a=Xe(t.rgb);if(a!==null){let{r:c,g:l,b:u}=GO(a),d=KO(c,l,u);i=d.hue,s=d.saturation}}return{on:n,level:Xe(t.bright),kelvin:r,hue:i,saturation:s}}function ZO(t){let e=t.bg_power,n=e==="on"?!0:e==="off"?!1:null,o=Xe(t.bg_hue),r=Xe(t.bg_sat);if(o===null||r===null){let i=Xe(t.bg_rgb);if(i!==null){let{r:s,g:a,b:c}=GO(i),l=KO(s,a,c);o=l.hue,r=l.saturation}}return{on:n,level:Xe(t.bg_bright),kelvin:Xe(t.bg_ct),hue:o,saturation:r}}function If(t,e){let n=WO(e),o=[{type:"power",state:{on:n.on}}];if(t.hasBrightness&&o.push({type:"brightness",state:{level:n.level}}),t.hasCt&&o.push({type:"colorTemperature",state:{kelvin:n.kelvin}}),t.hasColor&&o.push({type:"color",state:{hue:n.hue,saturation:n.saturation}}),t.hasBg){let r=ZO(e);o.push({type:"power",instance:Br,state:{on:r.on}}),o.push({type:"brightness",instance:Br,state:{level:r.level}}),t.hasBgCt&&o.push({type:"colorTemperature",instance:Br,state:{kelvin:r.kelvin}}),t.hasBgColor&&o.push({type:"color",instance:Br,state:{hue:r.hue,saturation:r.saturation}})}return o}function qO(t,e){let n=Ux(t),o=WO(t),r=T(e.mac),i=I8(e.model),s=[{type:"power",state:{on:o.on}}];if(n.hasBrightness&&s.push({type:"brightness",state:{level:o.level}}),n.hasCt&&s.push({type:"colorTemperature",config:i,state:{kelvin:o.kelvin}}),n.hasColor&&s.push({type:"color",config:{modes:["hs"]},state:{hue:o.hue,saturation:o.saturation}}),n.hasBg){let a=ZO(t);s.push({type:"power",instance:Br,state:{on:a.on}}),s.push({type:"brightness",instance:Br,state:{level:a.level}}),n.hasBgCt&&s.push({type:"colorTemperature",instance:Br,config:i,state:{kelvin:a.kelvin}}),n.hasBgColor&&s.push({type:"color",instance:Br,config:{modes:["hs"]},state:{hue:a.hue,saturation:a.saturation}})}return{source:{provider:"yeelight",providerAccountId:e.accountId,nativeId:r,reachability:"local",online:!0,lastSeen:e.now},fingerprints:[`mac:${r}`],type:"light",name:e.nameOverride??HO(t.name)??"Yeelight light",manufacturer:"Yeelight",model:e.model??null,capabilities:s}}function VO(t,e){return{source:{provider:"yeelight",providerAccountId:e.accountId,nativeId:t.key,reachability:"local",online:!1,lastSeen:e.now},fingerprints:[`mac:${t.key}`],type:"light",name:t.name??"Yeelight light",manufacturer:"Yeelight",model:t.model??null,capabilities:[{type:"power",state:{on:null}}]}}function JO(t,e,n,o,r,i){let s=T8(o)??{},a=i===Br,c=m=>a?`bg_${m}`:m,l=a?t.hasBgCt:t.hasCt,u=a?t.hasBgColor:t.hasColor,d=()=>{throw new Error(`yeelight light does not support ${e}.${n}${a?" (bg)":""}`)},f={method:c("set_power"),params:["on",...js]};if(e==="power"&&(n==="turnOn"||n==="turnOff"||n==="toggle")){if(n==="toggle"){if(r.currentOn===void 0)throw new Error("yeelight toggle needs the current power state (pre-read failed)");let g=!r.currentOn;return{commands:[{method:c("toggle"),params:[]}],optimistic:{type:"power",state:{on:g}}}}let m=n==="turnOn";return{commands:[{method:c("set_power"),params:[m?"on":"off",...js]}],optimistic:{type:"power",state:{on:m}}}}if(e==="brightness"&&(n==="setBrightness"||n==="adjustBrightness")){let m;if(n==="adjustBrightness"){if(r.currentLevel===void 0)throw new Error("yeelight adjustBrightness needs the current level (pre-read failed)");m=zc(r.currentLevel+(Xe(s.delta)??0),0,100)}else m=zc(Xe(s.level)??0,0,100);if(m===0)return{commands:[{method:c("set_power"),params:["off",...js]}],optimistic:{type:"brightness",state:{level:0}}};let g=Math.max(1,m);return{commands:[f,{method:c("set_bright"),params:[g,...js]}],optimistic:{type:"brightness",state:{level:g}}}}if(e==="colorTemperature"&&n==="setColorTemperature"){l||d();let m=zc(Xe(s.kelvin)??Nx,Nx,zO);return{commands:[f,{method:c("set_ct_abx"),params:[m,...js]}],optimistic:{type:"colorTemperature",state:{kelvin:m}}}}if(e==="color"&&n==="setColor"){u||d();let m=Math.min(359,zc(Xe(s.hue)??0,0,360)%360),g=zc(Xe(s.saturation)??0,0,100);return{commands:[f,{method:c("set_hsv"),params:[m,g,...js]}],optimistic:{type:"color",state:{hue:m,saturation:g}}}}return d()}function YO(t){if(t[0]!=="ok")throw new Error("yeelight command refused (result != ok)")}function XO(t,e,n,o){return If(t,e).find(r=>r.type===n&&(o?r.instance===o:r.instance===void 0))?.state}var QO=55443,E8=1e4,eL=2e3,Tf=class{constructor(e,n,o=nL){this.accountId=e;this.cfg=n;this.clientFactory=o}accountId;cfg;clientFactory;provider="yeelight";reachability="local";client=null;runtime=new Map;pollTimer=null;onState=null;disposed=!1;async init(e){this.client=this.clientFactory()}async link(e,n){return{ok:!1,error:"Yeelight devices need no pairing \u2014 enable LAN Control in the Yeelight app, then connect via the local Connect flow (POST /local/connect).",retryable:!1}}async unlink(e){}async discover(){let e=this.need(),n=[];for(let o of this.cfg.devices){let r=await this.locate(e,o);r?(this.runtime.set(o.key,{ip:r.ip,profile:Ux(r.props),online:!0}),n.push(qO(r.props,{accountId:this.accountId,mac:o.key,now:Date.now(),...o.name?{nameOverride:o.name}:{},...o.model?{model:o.model}:{}}))):(this.runtime.set(o.key,{ip:o.ip,profile:{hasBrightness:!0,hasCt:!1,hasColor:!1,hasBg:!1,hasBgCt:!1,hasBgColor:!1},online:!1}),n.push(VO(o,{accountId:this.accountId,now:Date.now()})))}return{devices:n,rooms:[]}}async getState(e){let n=e?[e]:[...this.runtime.keys()],o=[];for(let r of n){let i=this.runtime.get(r);if(i)try{let s=await this.freshProps(r);i.online=!0,o.push({nativeId:r,patch:If(i.profile,s),online:!0,ts:Date.now()})}catch{i.online=!1,o.push({nativeId:r,patch:[],online:!1,ts:Date.now()})}}return o}async sendCommand(e,n,o,r,i){let s=this.runtime.get(e);if(!s)throw new Error(`unknown yeelight device ${e}`);let a=i?.instance,c={};if(o==="toggle"||o==="adjustBrightness"){let d=If(s.profile,await this.freshProps(e)),f=h=>d.find(y=>y.type===h&&(a?y.instance===a:y.instance===void 0))?.state,m=f("power"),g=f("brightness");typeof m?.on=="boolean"&&(c.currentOn=m.on),typeof g?.level=="number"&&(c.currentLevel=g.level)}let{commands:l,optimistic:u}=JO(s.profile,n,o,r,c,a);for(let d of l){let f=await this.withIpRetry(e,m=>this.need().command(m,d.method,d.params));YO(f)}if(s.online=!0,i?.readAfter){let d=XO(s.profile,await this.freshProps(e),n,a);return{state:d,verifiedState:d}}return{state:u.state}}subscribe(e,n){return this.onState=e,this.pollTimer||(this.pollTimer=setInterval(()=>{this.reconcile()},this.cfg.pollMs??E8),this.pollTimer.unref?.()),()=>{this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.onState=null}}async dispose(){this.disposed=!0,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.client?.close(),this.client=null}async reconcile(){if(!(this.disposed||!this.onState))try{for(let e of await this.getState())this.onState?.(e)}catch{}}withIpRetry(e,n){let o=this.runtime.get(e);if(!o)throw new Error(`unknown yeelight device ${e}`);return he({ip:o.ip,fn:n,rediscover:()=>this.need().rediscover(e),onNewIp:r=>{o.ip=r,this.cfg.onIpChange?.(e,r)},bail:()=>this.disposed})}async freshProps(e){return Mx(await this.withIpRetry(e,n=>this.need().command(n,"get_prop",[..._f])))}async locate(e,n){let o=async r=>({ip:r,props:Mx(await e.command(r,"get_prop",[..._f]))});try{return await o(n.ip)}catch{try{let r=await e.rediscover(n.key);if(!r||r===n.ip)return null;let i=await o(r);return this.cfg.onIpChange?.(n.key,r),i}catch{return null}}}need(){if(!this.client)throw new Error("Yeelight adapter not initialized");return this.client}};function tL(t=nL){let e=t();return async n=>{try{let o=await e.command(n,"get_prop",["power","name"]),r=await e.macForIp(n),i=typeof o[1]=="string"&&o[1]?o[1]:void 0;return{...r?{mac:T(r)}:{},...i?{name:i}:{}}}catch{return null}}}var C8=3e4,nL=(t=R8())=>{let e=!1,n=0,o=new Map,r=null,i=new Map,s=new Map,a=(f,m)=>{let g=o.get(f);if(g){o.delete(f),g.idle&&clearTimeout(g.idle);for(let h of g.pending.values())clearTimeout(h.timer),h.reject(m);g.pending.clear();try{g.conn.destroy()}catch{}}},c=f=>{let m=o.get(f);m&&(m.idle&&clearTimeout(m.idle),!(m.pending.size>0)&&(m.idle=setTimeout(()=>{o.get(f)?.pending.size===0&&a(f,new Error("yeelight idle-closed"))},C8),m.idle.unref?.()))},l=(f,m)=>{let g=o.get(f);if(!g)return;g.buf+=m;let h;for(;(h=g.buf.indexOf(`\r
177
+ `))>=0;){let y=g.buf.slice(0,h);if(g.buf=g.buf.slice(h+2),!y)continue;let b;try{b=JSON.parse(y)}catch{continue}let w=b.id;if(typeof w!="number")continue;let x=g.pending.get(w);if(!x)continue;g.pending.delete(w),clearTimeout(x.timer);let I=b.error;if(I&&typeof I=="object"){let E=I;x.reject(new Error(`yeelight error ${typeof E.code=="number"?E.code:"?"}: ${typeof E.message=="string"?E.message:"request failed"}`))}else{let E=b.result;x.resolve(Array.isArray(E)?E.map(C=>typeof C=="string"?C:C==null?"":String(C)):[])}c(f)}},u=async f=>{let m=o.get(f);if(m)return m;let g=await t.connect(f,QO),h={conn:g,buf:"",pending:new Map,idle:null};return o.set(f,h),g.onData(y=>l(f,y)),g.onClose(()=>a(f,new Error("yeelight connection closed"))),h},d=async(f,m,g)=>{if(e)throw new Error("yeelight client closed");let h=await u(f),y=++n;return new Promise((b,w)=>{let x=setTimeout(()=>{h.pending.delete(y),c(f),w(new Error(`yeelight request timeout (${f}:${QO})`))},eL);x.unref?.(),h.pending.set(y,{resolve:b,reject:w,timer:x});try{h.conn.write(`${JSON.stringify({id:y,method:m,params:g})}\r
178
+ `)}catch(I){h.pending.delete(y),clearTimeout(x),w(I instanceof Error?I:new Error(String(I)))}})};return{command:d,macForIp:f=>dt(f),rediscover:f=>se(f),async openMusic(f){if(e)throw new Error("yeelight client closed");r||(r=await t.listen((h,y)=>{let b=i.get(h);b?(i.delete(h),b(y)):y.destroy()}));let m=new Promise((h,y)=>{i.set(f,h),setTimeout(()=>{i.delete(f),y(new Error(`yeelight music-mode connect timeout (${f})`))},eL).unref?.()});await d(f,"set_music",[1,r.host,r.port]);let g=await m;return s.set(f,g),{send:(h,y)=>g.write(`${JSON.stringify({id:++n,method:h,params:y})}\r
179
+ `),close:async()=>{s.delete(f);try{g.destroy()}catch{}try{await d(f,"set_music",[0])}catch{}}}},close(){e=!0;for(let f of[...o.keys()])a(f,new Error("yeelight client closed"));for(let f of s.values())try{f.destroy()}catch{}s.clear(),r?.close(),r=null}}},R8=()=>{let t=e=>({write:n=>{e.write(n)},onData:n=>{e.on("data",o=>n(typeof o=="string"?o:o.toString("utf8")))},onClose:n=>{e.on("close",()=>n()),e.on("error",()=>{})},destroy:()=>e.destroy()});return{async connect(e,n){let o=await import("node:net");return new Promise((r,i)=>{let s=o.createConnection({host:e,port:n});s.setEncoding("utf8");let a=!1;s.once("connect",()=>{a=!0,r(t(s))}),s.once("error",c=>{a||i(c instanceof Error?c:new Error(String(c)))})})},async listen(e){let n=await import("node:net"),o=await import("node:os"),r=n.createServer(c=>{c.setEncoding("utf8");let l=(c.remoteAddress??"").replace(/^::ffff:/,"");e(l,t(c))});await new Promise(c=>r.listen(0,c));let i=r.address(),s=i&&typeof i=="object"?i.port:0;return{host:Object.values(o.networkInterfaces()).flat().find(c=>c&&c.family==="IPv4"&&!c.internal)?.address??"127.0.0.1",port:s,close:()=>r.close()}}}};var Fx={nativeId:"room-living",name:"Living Room"},rL={nativeId:"room-entry",name:"Entryway"},Ef=class{constructor(e){this.accountId=e;this.devices=[{nativeId:"light-1",type:"light",name:"Living Room Lamp",room:Fx,capabilities:[{type:"power",state:{on:!1}},{type:"brightness",state:{level:0}},{type:"colorTemperature",config:{minKelvin:2200,maxKelvin:6500},state:{kelvin:null}}]},{nativeId:"lock-1",type:"lock",name:"Front Door",room:rL,capabilities:[{type:"lock",state:{state:"locked"}}]},{nativeId:"sensor-1",type:"sensor",name:"Living Room Temperature",room:Fx,capabilities:[{type:"sensor",config:{measurement:"temperature",unit:"Cel"},state:{value:21,ts:0}}]}]}accountId;provider="mock";reachability="local";onState=null;onEdge=null;devices;async init(e){}async link(e,n){return{ok:!0,accountId:this.accountId}}async unlink(e){}async discover(){return{devices:this.devices.map(n=>({source:{provider:"mock",providerAccountId:this.accountId,nativeId:n.nativeId,reachability:"local",online:!0,credentialRef:null,lastSeen:null},fingerprints:[`mock:${this.accountId}:${n.nativeId}`],type:n.type,name:n.name,areaHint:n.room,capabilities:n.capabilities.map(o=>structuredClone(o))})),rooms:[Fx,rL]}}async getState(e){return this.devices.filter(n=>!e||n.nativeId===e).map(n=>({nativeId:n.nativeId,patch:n.capabilities.map(o=>({type:o.type,instance:o.instance,state:o.state})),online:!0,ts:0}))}async sendCommand(e,n,o,r,i){let a=this.devices.find(l=>l.nativeId===e)?.capabilities.find(l=>l.type===n),c=a?A8(a,o,r):void 0;return{state:c,verifiedState:i?.readAfter?c:void 0}}subscribe(e,n){return this.onState=e,this.onEdge=n,()=>{this.onState=null,this.onEdge=null}}async dispose(){}emitTestState(e){this.onState?.(e)}emitTestEdge(e){this.onEdge?.(e)}};function A8(t,e,n){let o=n??{};switch(t.type){case"power":return t.state.on=e==="turnOn"?!0:e==="turnOff"?!1:!t.state.on,{on:t.state.on};case"brightness":return e==="setBrightness"&&typeof o.level=="number"&&(t.state.level=o.level),{level:t.state.level};case"colorTemperature":return e==="setColorTemperature"&&typeof o.kelvin=="number"&&(t.state.kelvin=o.kelvin),{kelvin:t.state.kelvin};case"lock":return e==="lock"?t.state.state="locked":e==="unlock"&&(t.state.state="unlocked"),{state:t.state.state};default:return t.state}}var Hc=t=>{throw new Error(`provider has no ingest adapter yet (accountId: ${t})`)},oL={mock:t=>new Ef(t),hue:(t,e)=>new yp(t,e),matter:Hc,smartthings:(t,e)=>new Rp(t,e),homeassistant:(t,e)=>new pp(t,e),nest:Hc,alexa:Hc,google:Hc,kasa:(t,e)=>t===Tn("kasa-klap")?new wc(t,e,async n=>Ok(Sc(),zP(n?await n.localSecrets.read(t):null))):new wc(t,e),wiz:(t,e)=>new yf(t,e),lifx:(t,e)=>new _p(t,e),shelly:(t,e)=>new Tp(t,e),govee:(t,e)=>t===ok?new ip(t,e):new tp(t,e),tapo:(t,e)=>new $p(t,e),tuya:(t,e)=>t===rk?new Np(t,e):new Lp(t,e),yeelight:(t,e)=>new Tf(t,e),nanoleaf:(t,e)=>new mf(t,e),meross:(t,e)=>new zp(t,e),ewelink:(t,e)=>new Up(t,e),wled:(t,e)=>new vf(t,e),elgato:(t,e)=>new xf(t,e),roku:(t,e)=>new Sf(t,e),mqtt:(t,e)=>new tf(t,e),esphome:(t,e)=>new uf(t,e),other:Hc};function Kc(t){return t==="kasa-klap"?"kasa":t}function iL(t){let e=t.log??(()=>{}),n=[];for(let{accountId:r,config:i}of jR(t.paths))n.push(t.addHomeAssistant(r,i));for(let{accountId:r,config:i}of zR(t.paths))n.push(t.addHue(r,i));let o=t.addMqtt;if(o)for(let{accountId:r,config:i}of HR(t.paths))n.push(o(r,i).catch(s=>e(`[hub] mqtt ${r} bring-up failed (will retry at next start): ${String(s)}`)));for(let{provider:r,accountId:i,devices:s}of UR(t.roster)){let a={devices:s,onIpChange:(c,l)=>t.onIpChange(r,c,l)};n.push(t.addRosterAdapter(Kc(r),i,a).catch(c=>e(`[hub] ${r} roster bring-up failed (will retry at next start): ${String(c)}`)))}if(t.loadCloudAccounts&&t.addCloudAdapter){let r=t.addCloudAdapter;for(let{provider:i,accountId:s,cfg:a}of t.loadCloudAccounts())n.push(r(i,s,a).catch(c=>e(`[hub] ${i} cloud-lane bring-up failed (will retry at next start): ${String(c)}`)))}return Promise.allSettled(n).then(()=>{})}var gi=async({method:t,url:e,token:n,body:o})=>{try{let r=await fetch(e,{method:t,headers:{authorization:`Bearer ${n}`,...o!==void 0?{"content-type":"application/json"}:{}},body:o!==void 0?JSON.stringify(o):void 0}),i=await r.json().catch(()=>null);return{status:r.status,json:i}}catch{return{status:0,json:null}}},Bx=t=>t.replace(/^ws/,"http").replace(/\/+$/,""),P8=6e4;function sL(t){let e=t.http??gi,n=t.now??Date.now,o=new Map,r=async(i,s)=>{let a=o.get(i);if(a&&n()<a.expiresAt-P8)return s==="access_token"?a.accessToken:a.installedAppId;let c=t.readNodeToken?.()??"";if(!t.relayUrl||!c)return null;let{status:l,json:u}=await e({method:"POST",url:`${Bx(t.relayUrl)}/connected-accounts/${encodeURIComponent(i)}/access-token`,token:c,body:{}});if(l===200&&u&&typeof u=="object"){let d=u,f=typeof d.access_token=="string"?d.access_token:null,m=typeof d.expires_at=="number"?d.expires_at:0;f&&m>0&&o.set(i,{accessToken:f,installedAppId:typeof d.installed_app_id=="string"?d.installed_app_id:null,expiresAt:m});let g=d[s];if(typeof g=="string"&&g)return g}return o.delete(i),null};return{accessToken:i=>r(i,"access_token"),installedAppId:i=>r(i,"installed_app_id")}}async function aL(t){let e=t.http??gi,n=t.readNodeToken?.()??"";if(!t.relayUrl||!n)return[];let{status:o,json:r}=await e({method:"GET",url:`${Bx(t.relayUrl)}/connected-accounts`,token:n});if(o===200&&r&&typeof r=="object"){let i=r.accounts;if(Array.isArray(i))return i}return[]}async function cL(t){let e=t.http??gi,n=t.readNodeToken?.()??"";if(!t.relayUrl||!n)return!1;let o=Qf(n);if(!o)return!1;let{status:r}=await e({method:"PATCH",url:`${Bx(t.relayUrl)}/node/${encodeURIComponent(o)}`,token:n,body:{name:t.name,platform:t.platform}});return r>=200&&r<300}function D8(t){let e=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n;o.provider==="smartthings"&&o.credentialLocation==="relay-do-sealed"&&o.status!=="revoked"&&(typeof o.accountId!="string"||typeof o.providerAccountId!="string"||e.push({accountId:o.accountId,config:{locationId:o.providerAccountId,...typeof o.displayName=="string"?{name:o.displayName}:{}}}))}return e}async function lL(t){return D8(await aL(t))}async function uL(t){let e=t.log??(()=>{});if(!t.paths){e("[hub] no account scope pinned \u2014 SmartThings cloud accounts stay off (null scope, never the relay's ambiguous graph)");return}try{for(let{accountId:n,config:o}of await lL({relayUrl:t.relayUrl,readNodeToken:t.readNodeToken,http:t.http}))t.addSmartThings(n,o)}catch(n){e(`[hub] smartthings account load failed: ${String(n)}`)}}var Gc=require("node:path");function dL(t,e){t.providerSecretFile(e,"probe");let n=am(),o=(0,Gc.join)((0,Gc.dirname)((0,Gc.dirname)(t.providerSecretFile(e,"probe"))),".keyring-index"),r=i=>im({keyring:n,file:t.providerSecretFile(e,i),account:`${e}/${i}`,index:Yc(o)});return{async read(i){return r(i).read()},async write(i,s){r(i).write(s)},async delete(i){r(i).delete()}}}var _se=p.enum(["telemetry","transcripts","sale"]),jx=p.object({plan:p.enum(["free","paid"]),planStatus:p.enum(["active","past_due","canceled"]).optional(),serviceOk:p.boolean().optional(),capture:p.object({telemetry:p.boolean(),transcripts:p.boolean()}),sellOk:p.boolean(),policyVersion:p.string(),consentRequired:p.boolean()});var $8=1440*60*1e3,O8=360*60*1e3,L8=jx.partial({sellOk:!0,consentRequired:!0}).extend({fetchedAt:p.number().int().nonnegative()});function zx(t,e){pe(e,`${JSON.stringify(t,null,2)}
180
+ `,384)}function Hx(t){let e=X(t);if(!e)return null;try{let n=L8.safeParse(JSON.parse(e));return n.success?n.data:null}catch{return null}}function pL(t,e=Date.now(),n=$8){return t!==null&&e-t.fetchedAt<=n}var N8=336*60*60*1e3;function fL({entitlement:t,paired:e,now:n}){return e?t===null||t.serviceOk===!1||t.plan==="free"&&t.serviceOk!==!0?!0:n-t.fetchedAt>N8:!1}function mL(t){let e=t.http??gi,n=t.file,o=t.now??Date.now,r=async()=>{let s=t.readNodeToken();if(!s)return;let{status:a,json:c}=await e({method:"GET",url:`${t.relayUrl.replace(/\/+$/,"")}/entitlement`,token:s});if(a!==200)return;let l=jx.safeParse(c);if(l.success)try{zx({...l.data,fetchedAt:o()},n)}catch(u){console.error(`[hub] entitlement file write failed: ${String(u)}`)}};r();let i=setInterval(()=>{r()},O8);return i.unref(),{refreshNow:r,stop:()=>clearInterval(i)}}var or=require("node:fs"),gL=G(require("node:path"),1),M8=4320*60*1e3,U8=336*60*60*1e3,F8=1440*60*1e3,hL=3600*1e3,yL=t=>/\.tmp-/.test(t);function B8(t,e){let n=e.now-t.mtimeMs;if(n<0)return"keep";if(yL(t.name))return n>e.tmpTtlMs?"sweep":"keep";if((t.sessionId||t.claudeSessionId)&&e.isLive(t))return"keep";let o=t.selfWritten?e.selfWrittenTtlMs:e.ownedTtlMs;return n>o?"sweep":"keep"}function vL(t,e){if(!(0,or.existsSync)(t))return{swept:0,kept:0};let n;try{n=(0,or.readdirSync)(t)}catch{return{swept:0,kept:0}}let o={now:(e?.now??Date.now)(),isLive:e?.isLive??(()=>!1),selfWrittenTtlMs:e?.selfWrittenTtlMs??M8,ownedTtlMs:e?.ownedTtlMs??U8,tmpTtlMs:e?.tmpTtlMs??F8},r=0,i=0;for(let s of n){if(!s.endsWith(".json")&&!yL(s))continue;let a=gL.default.join(t,s),c;try{let l=(0,or.statSync)(a);if(!l.isFile())continue;let u=!1,d,f;try{let m=JSON.parse((0,or.readFileSync)(a,"utf8"));u=m?.selfWritten===!0,d=typeof m?.claudeSessionId=="string"?m.claudeSessionId:void 0,f=typeof m?.id=="string"?m.id:void 0}catch{}c={name:s,mtimeMs:l.mtimeMs,selfWritten:u,claudeSessionId:d,sessionId:f}}catch{continue}if(B8(c,o)==="keep"){i++;continue}try{(0,or.rmSync)(a,{force:!0}),r++}catch{i++}}return{swept:r,kept:i}}var Jt=require("node:fs"),ir=G(require("node:path"),1);var qx=G(require("node:os"),1);function Kx(t,e){return pL(t,e)&&t.capture.transcripts===!0}function bL(t){let e=t.read,n=t.now??Date.now,o=Kx(e(),n());return{on(r=n()){return Kx(e(),r)},refresh(r=n()){let i=Kx(e(),r);return o&&!i&&t.onOff(),o=i,i}}}var Ge=require("node:fs"),Gx=G(require("node:path"),1);var j8=/<channel source="alexa" requestId="([^"]+)">/;function Wx(t){return Buffer.byteLength(t,"utf8")}function z8(t){let e=t.content,n=[];if(typeof e=="string")n.push(e);else if(Array.isArray(e))for(let o of e)o&&typeof o=="object"&&typeof o.text=="string"&&n.push(o.text);for(let o of n){let r=j8.exec(o);if(r)return r[1]}return null}var H8=()=>({pending:new Map});function K8(t,e,n){let o=typeof t.uuid=="string"?t.uuid:null,r=typeof t.timestamp=="string"?Date.parse(t.timestamp):NaN;if(!o||Number.isNaN(r))return[];let i=[],s=typeof t.type=="string"?t.type:"unknown",a=t.message&&typeof t.message=="object"?t.message:{},c=a.usage&&typeof a.usage=="object"?a.usage:{},l=f=>typeof f=="number"?f:void 0,u=f=>typeof f=="string"?f:void 0;i.push({id:o,ts:r,seq:e,type:s,line:{parentUuid:u(t.parentUuid),apiRequestId:u(t.requestId),bridgeRequestId:z8(a)??void 0,model:u(a.model),stopReason:u(a.stop_reason),isSidechain:t.isSidechain===!0?!0:void 0,inputTokens:l(c.input_tokens),outputTokens:l(c.output_tokens),cacheReadTokens:l(c.cache_read_input_tokens),cacheCreationTokens:l(c.cache_creation_input_tokens),cwd:u(t.cwd),gitBranch:u(t.gitBranch),cliVersion:u(t.version)}});let d=Array.isArray(a.content)?a.content:[];for(let f of d){if(!f||typeof f!="object")continue;let m=f;if(m.type==="tool_use"&&typeof m.id=="string")n.pending.set(m.id,{entryUuid:o,toolName:u(m.name)??"unknown",inputBytes:Wx(JSON.stringify(m.input??null)),ts:r});else if(m.type==="tool_result"&&typeof m.tool_use_id=="string"){let g=n.pending.get(m.tool_use_id);if(!g)continue;n.pending.delete(m.tool_use_id),i.push({id:m.tool_use_id,ts:g.ts,seq:e,type:"tool_use",line:{entryUuid:g.entryUuid,toolName:g.toolName,inputBytes:g.inputBytes,resultBytes:Wx(JSON.stringify(m.content??null)),isError:m.is_error===!0,durationMs:Math.max(0,r-g.ts)}})}}return i}var G8=16*1024*1024,Cf=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.maxBytes=e.maxSessionBytes??G8,this.spoolFile=Gx.default.join(e.spoolDir,`${e.claudeSessionId}.ndjson`),this.metaFile=Gx.default.join(e.spoolDir,`${e.claudeSessionId}.meta.json`);let n=this.readMeta();this.offset=n.tailOffset,this.seq=0}opts;now;maxBytes;spoolFile;metaFile;state=H8();seq;offset;lineNo=0;readMeta(){let e=X(this.metaFile);if(e)try{let n=JSON.parse(e);return{tailOffset:Number(n.tailOffset??0),uploadedBytes:Number(n.uploadedBytes??0),createdAt:Number(n.createdAt??this.now())}}catch{}return{tailOffset:0,uploadedBytes:0,createdAt:this.now()}}writeOffset(e){let n=this.readMeta();pe(this.metaFile,`${JSON.stringify({...n,tailOffset:e})}
181
+ `,384)}spoolSize(){try{return(0,Ge.statSync)(this.spoolFile).size}catch{return 0}}pump(){(0,Ge.mkdirSync)(this.opts.spoolDir,{recursive:!0});let e;try{e=(0,Ge.statSync)(this.opts.transcriptPath).size}catch{return}if(e<this.offset&&(this.offset=0),e===this.offset)return;let n=e-this.offset,o=Buffer.allocUnsafe(n),r=0;try{let l=(0,Ge.openSync)(this.opts.transcriptPath,"r");try{r=(0,Ge.readSync)(l,o,0,n,this.offset)}finally{(0,Ge.closeSync)(l)}}catch{return}let i=o.subarray(0,r).toString("utf8"),s=i.lastIndexOf(`
182
+ `);if(s<0)return;let a=i.slice(0,s),c=[];for(let l of a.split(`
183
+ `)){if(this.lineNo+=1,!l.trim())continue;let u=S0(l,this.opts.redactOpts);if(u)for(let d of K8(u,this.lineNo,this.state))c.push(d)}c.length&&this.spoolSize()<this.maxBytes&&this.append(c),this.offset+=Wx(a)+1,this.writeOffset(this.offset)}end(){this.append([{id:`${this.opts.claudeSessionId}:end`,ts:this.now(),seq:this.seq,type:"session_end",line:{}}])}append(e){let n=e.map(r=>(this.seq=r.seq,JSON.stringify(r))).join(`
184
+ `)+`
185
+ `;(0,Ge.mkdirSync)(this.opts.spoolDir,{recursive:!0});let o=null;try{o=(0,Ge.openSync)(this.spoolFile,"a",384),(0,Ge.writeSync)(o,n),(0,Ge.fsyncSync)(o)}catch{try{(0,Ge.appendFileSync)(this.spoolFile,n,{mode:384})}catch{}}finally{o!==null&&(0,Ge.closeSync)(o)}}};var wL=require("node:zlib"),zs=require("node:fs"),Zx=G(require("node:path"),1);var W8=async({url:t,token:e,headers:n,gzBody:o})=>{try{let r=await fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,...n},body:o}),i=await r.json().catch(()=>null);return{status:r.status,json:i}}catch{return{status:0,json:null}}},Z8=500,q8=1024*1024,Rf=class{constructor(e){this.opts=e;this.upload=e.upload??W8,this.newBatchId=e.newBatchId??(()=>crypto.randomUUID()),this.spoolFile=Zx.default.join(e.spoolDir,`${e.claudeSessionId}.ndjson`),this.metaFile=Zx.default.join(e.spoolDir,`${e.claudeSessionId}.meta.json`)}opts;upload;spoolFile;metaFile;newBatchId;uploadedBytes(){let e=X(this.metaFile);if(!e)return 0;try{return Number(JSON.parse(e).uploadedBytes??0)}catch{return 0}}advance(e){let n=X(this.metaFile),o={};if(n)try{o=JSON.parse(n)}catch{}pe(this.metaFile,`${JSON.stringify({...o,uploadedBytes:e})}
186
+ `,384)}wipe(){for(let e of[this.spoolFile,this.metaFile])try{(0,zs.rmSync)(e,{force:!0})}catch{}}spoolSize(){try{return(0,zs.statSync)(this.spoolFile).size}catch{return 0}}pendingBytes(){return Math.max(0,this.spoolSize()-this.uploadedBytes())}async drain(){let e=!1;for(;;){let n=this.uploadedBytes(),o=this.spoolSize();if(n>=o)return e?"sent":"idle";let r=this.opts.readNodeToken();if(!r)return"backoff";let i=(0,zs.readFileSync)(this.spoolFile).subarray(n).toString("utf8"),s=[],a=0;for(let d of i.split(`
187
+ `)){if(!d)continue;let f=Buffer.byteLength(d,"utf8")+1;if(s.length>=Z8||s.length>0&&a+f>q8)break;s.push(d),a+=f}if(s.length===0)return e?"sent":"idle";let c=`${s.join(`
188
+ `)}
189
+ `,l=(0,wL.gzipSync)(Buffer.from(c,"utf8")),{status:u}=await this.upload({url:`${this.opts.relayUrl.replace(/\/+$/,"")}/ingest/transcript`,token:r,headers:{"content-type":"application/x-ndjson","content-encoding":"gzip","x-batch-id":this.newBatchId(),"x-claude-session-id":this.opts.claudeSessionId,"x-bridge-session-id":this.opts.bridgeSessionId,"x-machine":this.opts.machine},gzBody:l});if(u===200){this.advance(n+Buffer.byteLength(c,"utf8")),e=!0;continue}return u===403?(this.wipe(),this.opts.onCaptureDisabled(),"capture_disabled"):u===401?(this.opts.onUnauthorized?.(),"unauthorized"):u===404?"outage":u===413?"quota":"backoff"}}};var V8=5e3,Wc=15*6e4,J8=4*1024*1024,Y8=5e3,X8=5*6e4,Q8=60*6e4,kL=10*6e4,xL=64*1024*1024;function eW(t,e,n){switch(t){case"sent":case"idle":return{delayMs:n>0?0:Wc,backoffMs:0};case"backoff":case"unauthorized":{let o=Math.min(Math.max(e*2,Y8),X8);return{delayMs:o,backoffMs:o}}case"quota":return{delayMs:Q8,backoffMs:0};case"outage":return{delayMs:Wc,backoffMs:0};case"capture_disabled":return{delayMs:Number.POSITIVE_INFINITY,backoffMs:0}}}function tW(t,e){let n=ir.default.resolve(t);for(;;){if(e(ir.default.join(n,".acbridge-no-capture")))return!0;let o=ir.default.dirname(n);if(o===n)return!1;n=o}}function nW(t,e,n){let o=new Set;for(let r of t){let i=n(r);i&&i.length>=8&&o.add(i)}for(let r of e)r&&r.length>=8&&o.add(r);return[...o]}function rW(t){let e=[],n=ir.default.join(t,"providers"),o;try{o=(0,Jt.readdirSync)(n)}catch{return e}for(let r of o){let i;try{i=(0,Jt.readdirSync)(ir.default.join(n,r))}catch{continue}for(let s of i){if(s==="accounts.json"||!s.endsWith(".json"))continue;let a=X(ir.default.join(n,r,s));if(a)try{let c=l=>{typeof l=="string"?e.push(l):Array.isArray(l)?l.forEach(c):l&&typeof l=="object"&&Object.values(l).forEach(c)};c(JSON.parse(a))}catch{}}}return e}var Af=class{constructor(e){this.opts=e;this.now=e.now??Date.now,this.sessionsDir=e.sessionsDir??Zs,this.spoolDir=e.spoolDir,this.machine=e.machine??qx.default.hostname();let n=e.secretDir??ir.default.dirname(this.spoolDir.replace(/\/telemetry\/spool$/,""));this.redactOpts={homedir:qx.default.homedir(),knownSecrets:nW([sl,...e.extraTokenFiles??[]],rW(n),X)},this.gate=bL({read:e.readEntitlement,now:this.now,onOff:()=>this.captureOff()}),this.scopeSub=e.scopeSub}opts;now;sessionsDir;spoolDir;machine;redactOpts;gate;pipes=new Map;timer=null;disabled=!1;scopeSub;loggedAdoptionVerdicts=new Set;sessionIds(){return[...this.pipes.keys()]}start(){if(process.env.BRIDGE_NO_CAPTURE==="1")return;this.tick();let e=setInterval(()=>this.tick(),V8);e.unref?.(),this.timer=e}pollOnce(){this.tick()}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.pipes.clear()}captureOff(){this.pipes.clear();try{(0,Jt.rmSync)(this.spoolDir,{recursive:!0,force:!0})}catch{}}readHandshakes(){let e;try{e=(0,Jt.readdirSync)(this.sessionsDir).filter(o=>o.endsWith(".json"))}catch{return[]}let n=[];for(let o of e){let r=X(ir.default.join(this.sessionsDir,o));if(r)try{n.push(JSON.parse(r))}catch{}}return n}tick(){if(this.disabled||!this.gate.refresh(this.now()))return;let e=this.now(),n=new Set;for(let o of this.readHandshakes()){if(!o.claudeSessionId||!o.transcriptPath)continue;let r=vd(o.sub,this.scopeSub);if(r!=="adopt"){this.loggedAdoptionVerdicts.has(o.claudeSessionId)||(this.loggedAdoptionVerdicts.add(o.claudeSessionId),console.error(`[hub] telemetry: refusing to tail session ${o.claudeSessionId} \u2014 account-scope verdict "${r}" (AS-T8a; sessions never cross accounts)`));continue}if(o.cwd&&tW(o.cwd,Jt.existsSync))continue;n.add(o.claudeSessionId);let i=this.pipes.get(o.claudeSessionId);i||(i={tailer:new Cf({transcriptPath:o.transcriptPath,claudeSessionId:o.claudeSessionId,spoolDir:this.spoolDir,redactOpts:this.redactOpts,now:this.now}),uploader:new Rf({spoolDir:this.spoolDir,claudeSessionId:o.claudeSessionId,bridgeSessionId:o.id,machine:this.machine,relayUrl:this.opts.relayUrl,readNodeToken:this.opts.readNodeToken,upload:this.opts.upload,now:this.now,onCaptureDisabled:()=>{this.opts.refreshEntitlement(),this.gate.refresh(this.now())},onUnauthorized:()=>this.opts.refreshNodeToken?.()}),cwd:o.cwd??"",lastSeen:e,nextDrainAt:0,backoffMs:0,draining:!1,ending:!1},this.pipes.set(o.claudeSessionId,i)),i.lastSeen=e}for(let[o,r]of this.pipes){if(!n.has(o)&&e-r.lastSeen>kL&&!r.ending){r.ending=!0,r.nextDrainAt=0;try{r.tailer.end()}catch{}}try{r.tailer.pump()}catch{}!r.draining&&(e>=r.nextDrainAt||r.uploader.pendingBytes()>=J8)&&(r.draining=!0,r.uploader.drain().then(i=>{let s=eW(i,r.backoffMs,r.uploader.pendingBytes());r.backoffMs=s.backoffMs,r.nextDrainAt=this.now()+s.delayMs}).catch(()=>{r.nextDrainAt=this.now()+Wc}).finally(()=>{r.draining=!1})),r.ending&&e-r.lastSeen>kL&&r.uploader.pendingBytes()===0&&this.pipes.delete(o)}this.enforceTotalCap()}enforceTotalCap(){let e;try{e=(0,Jt.readdirSync)(this.spoolDir).filter(o=>o.endsWith(".ndjson")).map(o=>{let r=ir.default.join(this.spoolDir,o),i=(0,Jt.statSync)(r);return{file:r,size:i.size,mtime:i.mtimeMs}})}catch{return}let n=e.reduce((o,r)=>o+r.size,0);if(!(n<=xL))for(let o of e.sort((r,i)=>r.mtime-i.mtime)){if(n<=xL)break;try{(0,Jt.rmSync)(o.file,{force:!0}),(0,Jt.rmSync)(o.file.replace(/\.ndjson$/,".meta.json"),{force:!0}),n-=o.size}catch{}}}};var Pf=class{constructor(e=Date.now){this.now=e}now;rows=new Map;record(e){let n=this.now(),o=this.rows.get(e.codexThreadId);this.rows.set(e.codexThreadId,{codexThreadId:e.codexThreadId,bridgeSessionId:e.bridgeSessionId??o?.bridgeSessionId??null,cwd:e.cwd??o?.cwd??null,gitBranch:e.gitBranch??o?.gitBranch??null,inputTokens:Math.max(e.inputTokens,o?.inputTokens??0),cachedInputTokens:Math.max(e.cachedInputTokens,o?.cachedInputTokens??0),outputTokens:Math.max(e.outputTokens,o?.outputTokens??0),firstSeenAt:o?.firstSeenAt??n,lastSeenAt:n,dirty:!0})}dirtyRows(){return[...this.rows.values()].filter(e=>e.dirty)}markClean(e){for(let n of e){let o=this.rows.get(n);o&&(o.dirty=!1)}}markCleanIfUnchanged(e){for(let n of e){let o=this.rows.get(n.codexThreadId);o&&o.inputTokens===n.inputTokens&&o.cachedInputTokens===n.cachedInputTokens&&o.outputTokens===n.outputTokens&&(o.dirty=!1)}}};var oW=async({url:t,token:e,body:n})=>{try{return{status:(await fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify(n)})).status}}catch{return{status:0}}},Df=class{constructor(e){this.opts=e;this.upload=e.upload??oW}opts;upload;async flush(){let e=this.opts.store.dirtyRows();if(e.length===0)return"idle";let n=this.opts.readNodeToken();if(!n)return"backoff";let o=e.map(i=>({codexThreadId:i.codexThreadId,bridgeSessionId:i.bridgeSessionId,cwd:i.cwd,gitBranch:i.gitBranch,inputTokens:i.inputTokens,cachedInputTokens:i.cachedInputTokens,outputTokens:i.outputTokens,firstSeenAt:i.firstSeenAt,lastSeenAt:i.lastSeenAt})),{status:r}=await this.upload({url:`${this.opts.relayUrl.replace(/\/+$/,"")}/ingest/codex-session`,token:n,body:{sessions:o}});return r===200?(this.opts.store.markCleanIfUnchanged(e),"sent"):r===403?(this.opts.onCaptureDisabled(),"capture_disabled"):r===401?(this.opts.onUnauthorized?.(),"unauthorized"):r===404?"outage":"backoff"}};function Vx(t,e){return t===null||e>t}var Jx=require("node:crypto");var iW=/^\/\/(?:wsl\.localhost|wsl\$)\/([^/]+)(\/.*)?$/i,sW=/^\/mnt\/([a-zA-Z])(\/.*)?$/;var aW=t=>t.replace(/\\/g,"/");function SL(t){let e=aW(t),n=iW.exec(e);if(n)return n[2]??"/";let o=sW.exec(e);return o?`${o[1]?.toLowerCase()}:${o[2]??"/"}`.toLowerCase():/^[a-zA-Z]:/.test(e)?e.toLowerCase():e}function hi(t,e){let n=SL(t.replace(/\\/g,"/")),o=SL(e.replace(/\\/g,"/"));if(o===n)return!0;let r=n.endsWith("/")?n:n+"/";return!!(o.startsWith(r)||!n.includes("/")&&o.replace(/\/+$/,"").split("/").pop()?.toLowerCase()===n.toLowerCase())}function _L(t,e){return t.includes("{")?t.replace(/\{pct\}/g,e?.pct!==void 0?String(Math.round(e.pct)):"").replace(/\{window\}/g,e?.window??"").replace(/\{model\}/g,e?.model??"").replace(/\{review\}/g,e?.review??"").replace(/\{cost\}/g,e?.cost!==void 0?e.cost.toFixed(2):"").replace(/\{mins\}/g,e?.minutes!==void 0?String(Math.round(e.minutes)):"").replace(/ {2,}/g," ").trim():t}function cW(t,e){if(!e)return t;let n=t;for(let o of e.split(".")){if(n==null||typeof n!="object")return;n=n[o]}return n}function lW(t,e,n){switch(t){case"eq":return e===n;case"neq":return e!==n;case"gt":return typeof e=="number"&&typeof n=="number"&&e>n;case"lt":return typeof e=="number"&&typeof n=="number"&&e<n;case"gte":return typeof e=="number"&&typeof n=="number"&&e>=n;case"lte":return typeof e=="number"&&typeof n=="number"&&e<=n}}var $f=class{constructor(e){this.deps=e;this.debounceMs=e.debounceMs??800}deps;rules=[];running=!1;lastFired=new Map;debounceMs;notifyPolicy={};setNotifyPolicy(e){this.notifyPolicy=e??{}}setRules(e){let n=this.deps.voice??!1,o=[];for(let r of e){let i=Aa.safeParse(r);if(!i.success){this.deps.log?.(`dropped an invalid rule: ${i.error.message}`);continue}if(n){o.push(i.data);continue}let s=i.data.actions.filter(a=>a.kind!=="notify");s.length!==0&&o.push({...i.data,actions:s})}this.rules=o}loadRules(e){this.setRules(Array.isArray(e?.rules)?e.rules:[])}get ruleCount(){return this.rules.length}start(){this.running=!0}stop(){this.running=!1,this.lastFired.clear()}get isRunning(){return this.running}snapshotGraph(){return this.deps.readGraph()}handleSessionState(e){if(!this.running)return;let n=this.deps.now?.()??Date.now(),o=`${e.sessionId}:${e.state}`,r=this.lastFired.get(o);if(r!==void 0&&n-r<this.debounceMs)return;this.lastFired.set(o,n);let i=this.deps.readGraph();for(let s of this.rules){if(!s.enabled)continue;let a=s.trigger;a.kind==="session"&&a.event===e.state&&(a.sessionId&&a.sessionId!==e.sessionId||a.repo&&!hi(a.repo,e.cwd)||a.agent!==void 0&&a.agent!==(e.agent??"claude")||this.conditionsPass(s.conditions,i)&&this.fireActions(s,{sessionId:e.sessionId,event:e.state,...e.pct!==void 0?{pct:e.pct}:{},...e.window?{window:e.window}:{},...e.model?{model:e.model}:{},...e.review?{review:e.review}:{},...e.cost!==void 0?{cost:e.cost}:{},...e.minutes!==void 0?{minutes:e.minutes}:{}}))}}fireActions(e,n){let o=new Map;for(let r of e.actions)if(r.kind==="device"){let i=o.get(r.deviceId);i?i.push(r):o.set(r.deviceId,[r])}else this.dispatch(r,e,n);for(let r of o.values())this.dispatchChain(r,e)}async dispatchChain(e,n){for(let o of e)await this.dispatch(o,n)}notifySuppressed(e){if(!e.proactive||e.doNotDisturb)return!0;let n=this.deps.now?.()??Date.now();return CT(e.quietHours,n)}conditionsPass(e,n){for(let o of e){let i=n.devices.find(a=>a.id===o.deviceId)?.capabilities.find(a=>a.type===o.capability&&(o.instance?a.instance===o.instance:!0));if(!i)return!1;let s=cW(i.state,o.path);if(!lW(o.op,s,o.value))return!1}return!0}async dispatch(e,n,o){try{if(e.kind==="device"){if(this.deps.isSecuritySensitive?.(e.deviceId,e.capability,e.instance,e.command)&&n.allowSecurity!==!0){this.deps.log?.(`blocked security-sensitive ${e.capability}.${e.command} on ${e.deviceId} (allowSecurity=false)`);return}if(!this.deps.invoke)return;let r={type:"device_command",requestId:(0,Jx.randomUUID)(),deviceId:e.deviceId,ruleId:n.id,capability:e.capability,...e.instance?{instance:e.instance}:{},command:e.command,params:e.params??{},consumer:"rules",confirm:!0};await this.deps.invoke(r)}else if(e.kind==="session")this.deps.dispatchSession?.({type:"prompt",sessionId:e.sessionId,requestId:(0,Jx.randomUUID)(),text:e.text});else if(e.kind==="intent"){if(!o)return;let r=n.trigger.kind==="session"?n.trigger.repo:void 0,i=(n.trigger.kind==="session"?n.trigger.agent:void 0)??"claude";this.deps.submitIntent?.({deviceId:e.deviceId,...e.instance?{instance:e.instance}:{},...e.look?{look:e.look}:{},...e.effect?{effect:e.effect}:{},...e.returnTo?{returnTo:e.returnTo}:{},hold:e.hold,sessionId:o.sessionId,event:o.event,agent:i,...r?{repo:r}:{}})}else{let r=n.trigger.kind==="session"?n.trigger.repo:void 0,i=n.trigger.kind==="session"?n.trigger.agent:void 0,s=r?this.notifyPolicy[Cb(i,r)]:void 0;if(s&&this.notifySuppressed(s)){this.deps.log?.(`notify suppressed by policy (repo ${r}): ${e.title}`);return}this.deps.notify?.({title:_L(e.title,o),body:_L(e.body,o),...r?{repo:r}:{},...o?{sessionId:o.sessionId,event:o.event}:{}})}}catch(r){this.deps.log?.(`rule ${n.id} action failed: ${String(r)}`)}}};var Yx=10,uW=new Set(["compacting","compactDone","started","resumed"]),dW={plan:"modePlan",auto:"modeAuto",acceptEdits:"modeAuto",dontAsk:"modeAuto",bypassPermissions:"modeBypass",bypass:"modeBypass",default:"modeNormal",normal:"modeNormal"},pW=new Set(["contextLow","contextCritical","usageHigh","modePlan","modeAuto","modeBypass","modeNormal","modelChanged","reviewChanged"]);function fW(t,e){let n=t.windowTokens&&t.windowTokens>0?t.windowTokens:e;return!n||n<=0||typeof t.usedTokens!="number"||t.usedTokens<0?t.pct:Math.min(100,Math.round(t.usedTokens/n*1e3)/10)}function TL(t){return t.replace(/\[.*?\]/g,"").replace(/-\d{8}$/,"")}function mW(t){let e=t.replace(/\[.*?\]/g,"").replace(/^claude-/,"").replace(/-\d{8}$/,"").split("-").filter(Boolean),n=[],o=[];for(let i of e)(/^\d+$/.test(i)?o:n).push(i);return[n.map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" "),o.join(".")].filter(Boolean).join(" ")||t}function IL(t){let e=TL(t).replace(/^claude-/,"").split("-").filter(Boolean);return(e.find(n=>!/^\d+$/.test(n))??e[0]??"").toLowerCase()}var Of=class{constructor(e){this.deps=e}deps;perRepo={};modelMatch={};sessions=new Map;setThresholds(e){this.perRepo=e??{}}setModelMatch(e){this.modelMatch=e??{}}handleSignal(e){if(e.state==="ended"){this.sessions.delete(e.sessionId);return}let n=this.entry(e.sessionId,e.cwd,e.agent);if(pW.has(e.state)||this.noteMeta(e.sessionId,n,e),uW.has(e.state)){n.lowFired=!1,n.criticalFired=!1;return}e.context&&this.ingest({sessionId:e.sessionId,context:e.context})}ingest(e){let n=this.entry(e.sessionId,e.cwd,e.agent);this.noteMeta(e.sessionId,n,e);let o=this.thresholdsFor(n.cwd,n.agent),r=this.deps.now?.()??Date.now(),i=(s,a,c)=>{this.deps.log?.(`${s} for ${e.sessionId} at ${Math.round(a)}% (fire-at ${o[s]})`),this.deps.emit({sessionId:e.sessionId,state:s,pct:a,...n.cwd?{cwd:n.cwd}:{},...c?{window:c}:{},...n.agent?{agent:n.agent}:{},ts:r})};if(e.context){typeof e.context.windowTokens=="number"&&e.context.windowTokens>0&&(n.windowTokens=e.context.windowTokens);let s=fW(e.context,n.windowTokens);n.lowFired&&s<=o.contextLow-Yx&&(n.lowFired=!1),n.criticalFired&&s<=o.contextCritical-Yx&&(n.criticalFired=!1),!n.lowFired&&s>=o.contextLow&&(n.lowFired=!0,i("contextLow",s)),!n.criticalFired&&s>=o.contextCritical&&(n.criticalFired=!0,i("contextCritical",s))}if(e.rateLimits){let s=e.rateLimits.fiveHour?.usedPct,a=e.rateLimits.sevenDay?.usedPct,c=Math.max(s??-1,a??-1);if(c>=0){let l=(s??-1)>=(a??-1)?"5-hour":"7-day";n.usageFired&&c<=o.usageHigh-Yx&&(n.usageFired=!1),!n.usageFired&&c>=o.usageHigh&&(n.usageFired=!0,i("usageHigh",c,l))}}if(typeof e.cost=="number"){let s=this.thresholdsFor(n.cwd,n.agent).costHigh;!n.costFired&&e.cost>=s&&(n.costFired=!0,this.deps.emit({sessionId:e.sessionId,state:"costHigh",cost:e.cost,...n.cwd?{cwd:n.cwd}:{},...n.agent?{agent:n.agent}:{},ts:this.deps.now?.()??Date.now()}))}}noteMeta(e,n,o){let r=this.deps.now?.()??Date.now();if(o.mode){let i=dW[o.mode];i&&(n.modeState&&n.modeState!==i&&(this.deps.log?.(`${i} for ${e} (permission mode \u2192 ${o.mode})`),this.deps.emit({sessionId:e,state:i,...n.cwd?{cwd:n.cwd}:{},...n.agent?{agent:n.agent}:{},ts:r})),n.modeState=i)}if(o.model){let i=TL(o.model);if(n.modelId&&n.modelId!==i){let s=this.modelMatchFor(n.cwd,n.agent),a=IL(n.modelId),c=IL(i);if(!s||s.direction==="becomes"&&s.models.includes(c)||s.direction==="leaves"&&s.models.includes(a)&&!s.models.includes(c)){let u=o.modelName??mW(o.model);this.deps.log?.(`modelChanged for ${e} (${n.modelId} \u2192 ${i})`),this.deps.emit({sessionId:e,state:"modelChanged",model:u,...n.cwd?{cwd:n.cwd}:{},...n.agent?{agent:n.agent}:{},ts:r})}}n.modelId=i}o.review!==void 0&&(n.agent===void 0||n.agent==="claude")&&(n.review!==void 0&&n.review!==o.review&&(this.deps.log?.(`reviewChanged for ${e} (${n.review} \u2192 ${o.review})`),this.deps.emit({sessionId:e,state:"reviewChanged",review:o.review,...n.cwd?{cwd:n.cwd}:{},...n.agent?{agent:n.agent}:{},ts:r})),n.review=o.review)}entry(e,n,o){let r=this.sessions.get(e);return r||(r={lowFired:!1,criticalFired:!1,usageFired:!1,costFired:!1},this.sessions.set(e,r)),n&&(r.cwd=n),o&&r.agent===void 0&&(r.agent=o),r}thresholdsFor(e,n){if(e)for(let[o,r]of Object.entries(this.perRepo)){let i=Da(o);if(i.agent===(n??"claude")&&hi(i.repo,e))return{...to,...r}}return{...to}}modelMatchFor(e,n){if(e)for(let[o,r]of Object.entries(this.modelMatch)){let i=Da(o);if(i.agent===(n??"claude")&&hi(i.repo,e))return r}}};var gW=new Set(["finished","idle","needs_permission","needsInput","planReady","ended","error"]),Lf=class{constructor(e){this.deps=e}deps;perRepo={};sessions=new Map;setThresholds(e){this.perRepo=e??{}}handleSignal(e){if(e.state==="ended"){this.clear(e.sessionId);return}let n=this.entry(e.sessionId,e.cwd,e.agent);if(e.state==="working"){this.arm(e.sessionId,n);return}gW.has(e.state)&&this.disarm(n)}arm(e,n){this.disarm(n);let o=this.minutesFor(n.cwd,n.agent);n.timer=this.deps.schedule(o*6e4,()=>{n.timer=void 0,this.deps.log?.(`longRunning for ${e} at ${o} min`),this.deps.emit({sessionId:e,state:"longRunning",minutes:o,...n.cwd?{cwd:n.cwd}:{},...n.agent?{agent:n.agent}:{},ts:this.deps.now?.()??Date.now()})})}disarm(e){e.timer!==void 0&&(this.deps.cancel(e.timer),e.timer=void 0)}clear(e){let n=this.sessions.get(e);n&&this.disarm(n),this.sessions.delete(e)}entry(e,n,o){let r=this.sessions.get(e);return r||(r={},this.sessions.set(e,r)),n&&(r.cwd=n),o&&r.agent===void 0&&(r.agent=o),r}minutesFor(e,n){if(e)for(let[o,r]of Object.entries(this.perRepo)){let i=Da(o);if(i.agent===(n??"claude")&&hi(i.repo,e))return r.longRunning??to.longRunning}return to.longRunning}};var hW=new Set(["started","resumed","ended","error","rateLimited","needs_permission","needsInput","planReady","permissionDenied","sandboxEscalation","finished","taskCompleted"]),yW=5e3,vW=(t,e)=>{let n=setTimeout(t,e);return n.unref(),n},bW=t=>clearTimeout(t);function EL(t,e={}){let n=e.schedule??vW,o=e.cancel??bW,r=new Map,i=new Map,s=null,a=!1,c=(d,f)=>{let m=f[f.length-1];t({type:"session_state",sessionId:d,state:m.state,event:m.event,ts:m.ts,transitions:f})},l=()=>{s!==null&&(o(s),s=null);for(let[d,f]of r)c(d,f);r.clear()},u=()=>{a||s!==null||r.size===0||(s=n(()=>{s=null,l()},yW))};return{note(d){if(a||i.get(d.sessionId)===d.state)return;i.set(d.sessionId,d.state);let f=r.get(d.sessionId)??[];if(f.push({state:d.state,event:d.event,ts:d.ts}),hW.has(d.state)){r.delete(d.sessionId),c(d.sessionId,f),r.size===0&&s!==null&&(o(s),s=null);return}if(r.set(d.sessionId,f),f.length>=xb){r.delete(d.sessionId),c(d.sessionId,f),r.size===0&&s!==null&&(o(s),s=null);return}u()},flush:l,dispose(){a||(a=!0,l())}}}var ae=t=>t;var CL=ae({id:"ActivateScene",target:"hub",customHandler:!0,scaffold:!0,carrier:"scene",utterances:["activate {scene} scene","activate scene {scene}","run scene {scene}","start {scene} scene"],slots:[{name:"scene",type:"SceneName",dynamic:!0,elicitationPrompts:["Which scene?"]}],customTypes:[{name:"SceneName",values:["movie night","good morning","bedtime","focus"]}],deviceCommands:[{capability:"scene",command:"activate"}],args:p.object({scene:p.string()}),result:p.object({ok:p.boolean()}),fromSlots:t=>({scene:t.scene??""}),ackSpeech:()=>"",speak:()=>""});var RL=ae({id:"Attach",target:"hub",skillLocal:!0,carrier:"attach",utterances:["attach to {target}","attach","switch to {target}","use {target}"],slots:[{name:"target",type:"SessionName",required:!0,dynamic:!0,elicitationPrompts:["Which session?","Which one would you like to attach to?"]}],customTypes:[{name:"SessionName",values:["one","two","three","four","five","six","seven","eight","nine","ten"]}],args:p.object({target:p.string()}),result:p.object({name:p.string()}),precheck:(t,e)=>e.sessionCount===0?"No sessions are running yet.":null,fromSlots:t=>({target:t.target??""}),ackSpeech:()=>"",speak:t=>`Entered ${t.name}.`});var AL=ae({id:"AttachBridge",target:"hub",skillLocal:!0,attachLevel:"bridge",carrier:"bridge",utterances:["attach to bridge {bridge}","switch to bridge {bridge}","open bridge {bridge}","go to bridge {bridge}"],slots:[{name:"bridge",type:"BridgeName",required:!0,dynamic:!0,elicitationPrompts:["Which bridge?","Which bridge would you like to attach to?"]}],customTypes:[{name:"BridgeName",values:["one","two","three","four","five","six","seven","eight","nine","ten"]}],args:p.object({target:p.string()}),result:p.object({name:p.string()}),precheck:(t,e)=>(e.bridgeCount??0)===0?"No bridges have a running session yet.":null,fromSlots:t=>({target:t.bridge??""}),ackSpeech:()=>"",speak:t=>`Entered ${t.name}.`});var PL=ae({id:"ControlDevice",target:"hub",customHandler:!0,scaffold:!0,carrier:"turn",utterances:["turn on {device}","turn off {device}","turn on the {device}","turn off the {device}","toggle {device}"],slots:[{name:"device",type:"DeviceName",dynamic:!0,elicitationPrompts:["Which device?"]}],customTypes:[{name:"DeviceName",values:["light","lamp","fan","plug","heater"]}],deviceCommands:[{capability:"power",command:"turnOn"},{capability:"power",command:"turnOff"},{capability:"power",command:"toggle"}],args:p.object({device:p.string()}),result:p.object({ok:p.boolean()}),fromSlots:t=>({device:t.device??""}),ackSpeech:()=>"",speak:()=>""});var DL=ae({id:"ControlGroup",target:"hub",customHandler:!0,scaffold:!0,carrier:"group",utterances:["turn on the {group} group","turn off the {group} group","turn off {group} group"],slots:[{name:"group",type:"GroupName",dynamic:!0,elicitationPrompts:["Which group or room?"]}],customTypes:[{name:"GroupName",values:["living room","bedroom","kitchen","office","studio"]}],deviceCommands:[{capability:"power",command:"turnOn"},{capability:"power",command:"turnOff"}],args:p.object({group:p.string()}),result:p.object({ok:p.boolean()}),fromSlots:t=>({group:t.group??""}),ackSpeech:()=>"",speak:()=>""});var $L=t=>`In the current working directory, ${t}. Keep the answer brief enough to be read aloud.`;var OL=ae({id:"GitStatus",target:"session",carrier:"git",utterances:["git status","what's the git status","any uncommitted changes in git"],slots:[],args:p.object({}),result:p.object({}),fromSlots:()=>({}),ackSpeech:()=>"Asking git status.",speak:()=>"",render:()=>$L("run git status and report the current branch and any uncommitted changes")});var wW=p.object({index:p.number().int().positive(),name:p.string(),id:p.string(),sessionCount:p.number().int().nonnegative()}),LL=ae({id:"ListBridges",target:"hub",carrier:"bridge",utterances:["list bridges","list my bridges","what bridges do I have","what bridges are running","which bridges are running"],slots:[],args:p.object({}),result:p.object({bridges:p.array(wW)}),speaksResult:!0,cacheSource:"bridges",providesBridgeCatalog:!0,fromSlots:()=>({}),ackSpeech:()=>"",speak:t=>{let e=t.bridges.length;if(e===0)return"No bridges have a running session.";let n=t.bridges.map(o=>`${o.index}, ${o.name}`).join("; ");return`${e} bridge${e===1?"":"s"}: ${n}.`}});var kW=p.object({name:p.string(),type:p.string(),room:p.string().nullable(),online:p.boolean()}),xW=p.object({provider:p.string(),status:p.string()}),NL=ae({id:"ListDevices",target:"hub",carrier:"device",utterances:["list devices","list my devices","what devices do I have","what devices are online"],slots:[],args:p.object({}),result:p.object({devices:p.array(kW),accounts:p.array(xW)}),speaksResult:!0,cacheSource:"devices",fromSlots:()=>({}),ackSpeech:()=>"",speak:t=>{let e=t.accounts.filter(i=>i.status!=="linked"),n=e.length?` ${e.map(i=>`${i.provider} needs re-linking`).join("; ")}.`:"",o=t.devices.length;if(o===0)return`No devices are connected.${n}`;let r=t.devices.filter(i=>i.online).length;return`${o} device${o===1?"":"s"}, ${r} online.${n}`}});var SW=p.object({index:p.number().int().positive(),name:p.string(),id:p.string()}),ML=ae({id:"ListSessions",target:"hub",carrier:"session",utterances:["list sessions","list my sessions","what sessions do I have","what sessions are running"],slots:[],args:p.object({}),result:p.object({sessions:p.array(SW)}),speaksResult:!0,cacheSource:"sessions",providesSessionCatalog:!0,fromSlots:()=>({}),ackSpeech:()=>"",speak:t=>{let e=t.sessions.length;if(e===0)return"No sessions are running.";let n=t.sessions.map(o=>`${o.index}, ${o.name}`).join("; ");return`${e} session${e===1?"":"s"}: ${n}.`}});var UL=ae({id:"ReadMore",target:"hub",carrier:"more",utterances:["read more","continue reading","keep reading"],slots:[],args:p.object({}),result:Xu,speaksResult:!0,cacheSource:"output",fromSlots:()=>({}),ackSpeech:()=>"",speak:t=>t.latestReply?t.hasMore?`${t.latestReply} Say read more to continue.`:t.latestReply:"That's the end of the output."});var FL=ae({id:"ReadOutput",target:"hub",carrier:"output",utterances:["read output","read the output","what's the output","read reply","read the reply","what's the reply","read the last reply","read it","replies","read replies","dev replies","any replies","latest reply"],slots:[],args:p.object({}),result:Xu,speaksResult:!0,cacheSource:"output",fromSlots:()=>({}),ackSpeech:()=>"",speak:t=>t.latestReply?t.hasMore?`${t.latestReply} Say read more to continue.`:t.latestReply:"No output yet."});var _W=p.object({index:p.number().int().positive(),name:p.string(),id:p.string(),sessionCount:p.number().int().nonnegative()}),BL=ae({id:"RenameBridge",target:"hub",relayMutation:!0,customHandler:!0,carrier:"bridge",utterances:["rename bridge {bridge}","rename a bridge","rename this bridge","rename the bridge","rename this bridge to {name}","rename the bridge to {name}","call the bridge {name}"],slots:[{name:"bridge",type:"BridgeName",dynamic:!0},{name:"name",type:"AMAZON.SearchQuery",allowFreeText:!0}],args:p.object({name:p.string(),bridgeId:p.string().optional()}),result:p.object({bridges:p.array(_W)}),providesBridgeCatalog:!0,precheck:t=>t.name.trim()?null:"What would you like to call it?",fromSlots:t=>({name:(t.name??"").trim()}),ackSpeech:t=>`Okay, I'll call it ${t.name}.`,speak:()=>""});var IW=p.object({index:p.number().int().positive(),name:p.string(),id:p.string()}),jL=ae({id:"RenameSession",target:"hub",relayMutation:!0,customHandler:!0,carrier:"rename",utterances:["rename","rename a session","rename this session","rename the session","rename it","rename {target}","rename session {target}","rename to {name}","rename this session to {name}","call it {name}"],slots:[{name:"target",type:"SessionName",dynamic:!0},{name:"name",type:"AMAZON.SearchQuery",allowFreeText:!0}],args:p.object({name:p.string()}),result:p.object({sessions:p.array(IW)}),providesSessionCatalog:!0,precheck:t=>t.name.trim()?null:"What would you like to call it?",fromSlots:t=>({name:(t.name??"").trim()}),ackSpeech:t=>`Okay, I'll call it ${t.name}.`,speak:()=>""});var zL=ae({id:"Return",target:"hub",skillLocal:!0,clearsAttach:!0,carrier:"return",utterances:["return","go back","back to the main menu","main menu","leave the session","leave this session"],slots:[],args:p.object({}),result:p.object({}),fromSlots:()=>({}),ackSpeech:()=>"",speak:()=>"Back at the main menu."});var HL=ae({id:"SetBrightness",target:"hub",customHandler:!0,scaffold:!0,carrier:"brightness",utterances:["set brightness of {device} to {level}","set {device} brightness to {level}","dim {device} to {level}"],slots:[{name:"device",type:"DeviceName",dynamic:!0,elicitationPrompts:["Which device?"]},{name:"level",type:"AMAZON.NUMBER",elicitationPrompts:["What level, 0 to 100?"]}],customTypes:[{name:"DeviceName",values:["light","lamp","fan","plug","heater"]}],deviceCommands:[{capability:"brightness",command:"setBrightness"}],args:p.object({device:p.string(),level:p.number()}),result:p.object({ok:p.boolean()}),fromSlots:t=>({device:t.device??"",level:Number(t.level??0)}),ackSpeech:()=>"",speak:()=>""});var KL=ae({id:"SetTemperature",target:"hub",customHandler:!0,scaffold:!0,carrier:"temperature",utterances:["set temperature of {device} to {temperature}","set {device} temperature to {temperature}","set {device} to {temperature} degrees"],slots:[{name:"device",type:"DeviceName",dynamic:!0,elicitationPrompts:["Which thermostat?"]},{name:"temperature",type:"AMAZON.NUMBER",elicitationPrompts:["What temperature?"]}],customTypes:[{name:"DeviceName",values:["light","lamp","fan","plug","heater"]}],deviceCommands:[{capability:"thermostat",command:"setSetpoint"}],args:p.object({device:p.string(),temperature:p.number()}),result:p.object({ok:p.boolean()}),fromSlots:t=>({device:t.device??"",temperature:Number(t.temperature??0)}),ackSpeech:()=>"",speak:()=>""});var GL=[CL,RL,AL,PL,DL,OL,LL,NL,ML,UL,FL,BL,jL,zL,HL,KL],WL=new Map(GL.map(t=>[t.id,t])),_ce=new Map(GL.map(t=>[`${t.id}Intent`,t]));function ZL(t,e){let n=r=>e.sendResult({type:"command_result",requestId:t.requestId,id:t.id,sessionId:t.sessionId,error:r,ts:Date.now()}),o=WL.get(t.id);if(!o)return n("That command isn't available yet.");if(o.target!=="session")return n("That command can't be handled here.");(!t.sessionId||!e.sendToChannel(t.sessionId,t))&&n("No session attached, or that session is offline.")}function Xx(t,e){return e.isSecuritySensitive(t.deviceId,t.capability,t.instance,t.command)?t.confirm===!0?{allowed:!0,secure:!0}:e.requireConfirm?{allowed:!1,secure:!0,reason:"This device needs an explicit confirmation the hub didn't receive."}:{allowed:!0,secure:!0,warn:`actuated a security-sensitive ${t.capability}.${t.command} on ${t.deviceId} WITHOUT an explicit confirm \u2014 this hub is running the BRIDGE_REQUIRE_DEVICE_CONFIRM=0 escape hatch; unset it to refuse instead`}:{allowed:!0,secure:!1}}var VL=require("node:path"),qL=128,Nf=class{entries=new Map;register(e,n,o){let r={...e,bridgeId:e.bridgeId??e.cwd,bridgeName:e.bridgeName??(0,VL.basename)(e.cwd)},i=this.entries.get(r.id);if(i)console.error(`[hub] session ${r.id} re-registered \u2014 closing the previous channel socket`),i.close?.();else if(this.entries.size>=qL){console.error(`[hub] session registry cap (${qL}) reached \u2014 refusing to register ${r.id}`),o?.();return}this.entries.set(r.id,{session:r,send:n,close:o})}remove(e){this.entries.delete(e)}setState(e,n){let o=this.entries.get(e);if(o)return o.session={...o.session,state:n},o.session.cwd}cwdOf(e){return this.entries.get(e)?.session.cwd}list(){return[...this.entries.values()].map(e=>e.session)}send(e,n){let o=this.entries.get(e);return o?o.send(n):!1}broadcast(e){for(let n of this.entries.values())n.send(e)}};var JL=["matter-uid","mac","serial"],QL=new Set(["hue","matter","kasa","wiz","lifx","shelly","esphome"]),YL=(t,e)=>e==="cloud"?0:QL.has(t)?2:1,TW=new Set(["homeassistant"]),XL=(t,e)=>e==="cloud"?0:TW.has(t)?3:QL.has(t)?1:2,EW=t=>[...new Set(t.map(e=>e.type))].sort().join(",");function Yt(t){let e=o=>{let r=JL.findIndex(i=>o.startsWith(`${i}:`));return r===-1?JL.length:r},n=[...t].sort((o,r)=>e(o)-e(r)||(o<r?-1:o>r?1:0))[0]??"";return`dev_${rs(n).slice(0,8)}`}function eN(t){return`area_${rs(t.trim().toLowerCase()).slice(0,8)}`}function CW(t,e){if(t.some(s=>s.type==="effect"))return t;let n=s=>t.some(a=>a.type===s);if(!(e==="light"||n("power")&&(n("color")||n("brightness"))))return t;let r=n("color"),i=["flash","strobe"];return n("brightness")&&i.push("pulse","candle"),r&&i.push("colorFade","colorLoop","rainbow","siren","meter"),[...t,{type:"effect",config:{kinds:i,supportsColor:r},state:{active:null}}]}var Qx=class{parent=new Map;find(e){let n=this.parent.get(e);if(n===void 0)return this.parent.set(e,e),e;for(;n!==this.parent.get(n);){let o=this.parent.get(n);if(o===void 0)break;this.parent.set(n,this.parent.get(o)??o),n=o}return n}union(e,n){let o=this.find(e),r=this.find(n);o!==r&&this.parent.set(o,r)}};function tN(t){let e=new Qx,n=(c,l)=>c.candidate.fingerprints[0]??`idx:${l}`;t.candidates.forEach((c,l)=>{let u=c.candidate.fingerprints.length>0?c.candidate.fingerprints:[`idx:${l}`],d=u[0];for(let f of u)e.union(d,f)});let o=new Map;t.candidates.forEach((c,l)=>{let u=JSON.stringify([c.candidate.type,c.areaId??"",c.candidate.name.trim().toLowerCase(),EW(c.candidate.capabilities)]),d=o.get(u);d?d.push(l):o.set(u,[l])});for(let c of o.values()){if(c.length<2||new Set(c.map(d=>t.candidates[d].candidate.source.provider)).size<2)continue;let u=n(t.candidates[c[0]],c[0]);for(let d of c)e.union(u,n(t.candidates[d],d))}let r=new Map;t.candidates.forEach((c,l)=>{let u=e.find(n(c,l)),d=r.get(u);d?d.push(l):r.set(u,[l])});let i=[],s=new Map,a=[];for(let c of r.values()){let l=c.map(N=>t.candidates[N]),u=[...l].sort((N,M)=>YL(M.candidate.source.provider,M.candidate.source.reachability)-YL(N.candidate.source.provider,N.candidate.source.reachability)),d=[...l].sort((N,M)=>XL(M.candidate.source.provider,M.candidate.source.reachability)-XL(N.candidate.source.provider,N.candidate.source.reachability)),f=d[0],m=[...new Set(l.flatMap(N=>N.candidate.fingerprints))],g=Yt(m),h=u.map(N=>{let M=N.candidate.source;return{sourceId:`${M.provider}:${M.nativeId}`,provider:M.provider,providerAccountId:M.providerAccountId,nativeId:M.nativeId,nativeType:M.nativeType,reachability:M.reachability,online:M.online,attention:M.attention??null,credentialRef:M.credentialRef??null,lastSeen:M.lastSeen??null}}),y=new Map;for(let N of u)for(let M of N.candidate.capabilities){let ue=`${M.type}:${M.instance??""}`;y.has(ue)||y.set(ue,M)}let b=h.some(N=>N.online),w=b?h.some(N=>N.online&&N.reachability==="local")?"local":"cloud":"offline",x=b?null:h.find(N=>N.attention)?.attention??null,I=h.find(N=>N.online)??h[0],E=Math.max(0,...h.map(N=>N.lastSeen??0)),C=d.map(N=>N.candidate.manufacturer).find(N=>N!=null)??null,F=d.map(N=>N.candidate.model).find(N=>N!=null)??null,U=d.map(N=>N.areaId).find(N=>N!=null)??null,W={id:g,type:f.candidate.type,name:f.candidate.name,areaId:U,manufacturer:C,model:F,online:b,reachability:w,...x?{attention:x}:{},sources:h,preferredSourceId:I.sourceId,capabilities:CW([...y.values()],f.candidate.type),updatedAt:E||t.updatedAt};i.push(W),a.push({device:W,candidates:u.map(N=>N.candidate)});for(let N of h)s.set(`${N.provider}:${N.providerAccountId}:${N.nativeId}`,g)}for(let{device:c,candidates:l}of a){for(let d of l){let f=d.source;if(d.parentNativeId){let m=s.get(`${f.provider}:${f.providerAccountId}:${d.parentNativeId}`);if(m&&m!==c.id){c.parentId=m;break}}}let u=l.flatMap(d=>(d.memberNativeIds??[]).map(f=>s.get(`${d.source.provider}:${d.source.providerAccountId}:${f}`))).filter(d=>typeof d=="string"&&d!==c.id);u.length>0&&(c.members=[...new Set(u)])}return{version:1,nodeId:t.nodeId,updatedAt:t.updatedAt,areas:t.areas,accounts:t.accounts,devices:i}}var RW=/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{1,5})?\b/g,AW=/\b(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b/gi,PW=/\[[0-9a-z:.%_-]*:[0-9a-z:.%_-]*\](?::\d{1,5})?/gi,DW=/(?<![0-9a-z:.])(?:[0-9a-f]{0,4}:){2,}(?:\d{1,3}(?:\.\d{1,3}){3}|[0-9a-f]{1,4})?(?:%[0-9a-z]+)?/gi,$W=t=>t.includes("::")||(t.match(/:/g)?.length??0)>=7;function Zc(t){return t.replace(PW,"<lan>").replace(DW,e=>$W(e)?"<lan>":e).replace(RW,"<lan>").replace(AW,"<mac>")}function nN(t,e){let n=t;for(let o of e)o.length<2||(n=n.split(o).join("<secret>"));return n}function OW(t){let e=T(t);return e.length===17?`m_${rs(e).slice(0,12)}`:void 0}function rN(t){let e=!1,n=t.devices.map(o=>{let r=new Map,i=!1,s=o.sources.map(a=>{let c=OW(a.nativeId);if(c===void 0)return a;let l=`${a.provider}:${c}`;return r.set(a.sourceId,l),i=!0,{...a,nativeId:c,sourceId:l}});return i?(e=!0,{...o,sources:s,preferredSourceId:r.get(o.preferredSourceId)??o.preferredSourceId}):o});return e?{...t,devices:n}:t}var LW=300,Mf=class{constructor(e){this.opts=e;this._graph={version:1,nodeId:e.nodeId,updatedAt:this.now(),areas:[],accounts:[],devices:[]}}opts;adapters=new Map;adapterBringUp=new Map;rediscover=new Map;_graph;get graph(){return this._graph}async addAdapter(e,n,o){let r=`${e}:${n}`;if(this.adapters.has(r))return;let i=this.adapterBringUp.get(r);if(i)return i;let s=(async()=>{let a=oL[e](n,o),c={...this.opts.makeContext(e,n),devicesChanged:()=>this.scheduleRediscover(e,n)};await a.init(c);let{devices:l,rooms:u}=await a.discover(),d={adapter:a,candidates:new Map(l.map(f=>[f.source.nativeId,f])),rooms:new Map(u.map(f=>[f.nativeId,f.name])),unsubscribe:null};d.unsubscribe=a.subscribe(f=>this.applyPatch(e,n,f),f=>this.emitEdge(e,n,f)),this.adapters.set(r,d),this.rebuild();try{for(let f of await a.getState())this.applyPatch(e,n,f)}catch{}})();this.adapterBringUp.set(r,s);try{await s}finally{this.adapterBringUp.delete(r)}}async removeAdapter(e,n){let o=`${e}:${n}`,r=this.adapterBringUp.get(o);r&&await r.catch(()=>{});let i=this.adapters.get(o);i&&(i.unsubscribe?.(),await i.adapter.dispose(),this.adapters.delete(o),this.rebuild())}async disposeAll(){for(let e of this.rediscover.values())clearTimeout(e);this.rediscover.clear();for(let e of this.adapters.values())e.unsubscribe?.(),await e.adapter.dispose();this.adapters.clear(),this.rebuild()}scheduleRediscover(e,n){let o=`${e}:${n}`;this.rediscover.has(o)||this.rediscover.set(o,setTimeout(()=>{this.rediscover.delete(o);let r=this.adapters.get(o);r&&r.adapter.discover().then(({devices:i,rooms:s})=>{this.adapters.get(o)===r&&(r.candidates=new Map(i.map(a=>[a.source.nativeId,a])),r.rooms=new Map(s.map(a=>[a.nativeId,a.name])),this.rebuild())}).catch(()=>{})},LW))}hasAdapter(e,n){return this.adapters.has(`${e}:${n}`)}applyPatch(e,n,o){let i=this.adapters.get(`${e}:${n}`)?.candidates.get(o.nativeId);if(i){for(let s of o.patch){let a=i.capabilities.find(c=>c.type===s.type&&(c.instance??"")===(s.instance??""));a&&s.state&&typeof s.state=="object"&&(a.state={...a.state,...s.state})}o.online!==void 0&&(i.source.online=o.online),o.attention!==void 0&&(i.source.attention=o.attention),this.rebuild()}}applyExternalEvent(e,n,o){(o.patch&&o.patch.length>0||o.online!==void 0)&&this.applyPatch(e,n,{nativeId:o.nativeId,patch:o.patch??[],online:o.online,ts:o.ts}),o.edge&&this.emitEdge(e,n,{nativeId:o.nativeId,capability:o.edge.capability,instance:o.edge.instance,event:o.edge.event,payload:o.edge.payload,ts:o.ts})}async invoke(e,n){let o=d=>({type:"device_result",requestId:e.requestId,deviceId:e.deviceId,ok:!1,error:d});if(!n?.internal&&this.planLapsed())return o("Your AC Bridge subscription is inactive \u2014 device control is paused. Renew to resume.");let r=this._graph.devices.find(d=>d.id===e.deviceId);if(!r)return o("I don't know that device.");let i=e.sourceId?r.sources.find(d=>d.sourceId===e.sourceId):r.sources.find(d=>d.sourceId===r.preferredSourceId);if(!i)return o("That device isn't reachable right now.");let s=this.adapters.get(`${i.provider}:${i.providerAccountId}`);if(!s)return o("That device's integration isn't loaded.");let a=vr[e.capability]?.find(d=>d.command===e.command);if(!a)return o("That command isn't available for this device.");let c=a.params.safeParse(e.params);if(!c.success)return o("Those settings weren't understood.");if(e.capability==="effect")return this.opts.effect?this.opts.effect({...e,params:c.data}):o("Effects aren't available for this device.");let l=r.capabilities.find(d=>d.type===e.capability&&(e.instance?d.instance===e.instance:!0)),u=l?Ra(r,l,a):!1;if(!n?.internal&&this.opts.onActuate)try{await this.opts.onActuate(e.deviceId,e.capability)}catch{}try{let d=await s.adapter.sendCommand(i.nativeId,e.capability,e.command,c.data,{readAfter:u,instance:e.instance}),f=d.verifiedState??d.state;return f!==void 0&&this.applyPatch(i.provider,i.providerAccountId,{nativeId:i.nativeId,patch:[{type:e.capability,instance:e.instance,state:f}],ts:this.now()}),{type:"device_result",requestId:e.requestId,deviceId:e.deviceId,ok:!0,verified:u?d.verifiedState!==void 0:void 0,state:f,result:d.result}}catch(d){return o(Zc(String(d)))}}query(e){if(e.kind==="list")return{type:"device_result",requestId:e.requestId,ok:!0,result:this._graph};let n=e.deviceId?this._graph.devices.find(o=>o.id===e.deviceId):void 0;return n?{type:"device_result",requestId:e.requestId,deviceId:n.id,ok:!0,result:n}:{type:"device_result",requestId:e.requestId,deviceId:e.deviceId,ok:!1,error:"I don't know that device."}}async captureNative(e){let n=this.resolvePreferred(e);if(n?.entry.adapter.captureNative)return n.entry.adapter.captureNative(n.source.nativeId).catch(()=>{})}async restoreNative(e,n){let o=this.resolvePreferred(e);return o?.entry.adapter.restoreNative?(await o.entry.adapter.restoreNative(o.source.nativeId,n),!0):!1}resolvePreferred(e){let n=this._graph.devices.find(i=>i.id===e);if(!n)return null;let o=n.sources.find(i=>i.sourceId===n.preferredSourceId)??n.sources[0];if(!o)return null;let r=this.adapters.get(`${o.provider}:${o.providerAccountId}`);return r?{entry:r,source:o}:null}securityOf(e,n,o,r){let i=this._graph.devices.find(c=>c.id===e);if(!i)return!1;let s=i.capabilities.find(c=>c.type===n&&(o?c.instance===o:!0)),a=vr[n]?.find(c=>c.command===r);return!s||!a?!1:Ra(i,s,a)}linkIndex(){let e=new Map;for(let o of this._graph.devices)for(let r of o.sources)e.set(`${r.provider}:${r.providerAccountId}:${r.nativeId}`,o.id);let n=new Map;for(let o of this.adapters.values())for(let r of o.candidates.values()){let i=r.source,s=e.get(`${i.provider}:${i.providerAccountId}:${i.nativeId}`);if(s)for(let a of r.fingerprints)a.startsWith("mac:")&&n.set(T(a.slice(4)),{provider:i.provider,deviceId:s,accountId:i.providerAccountId})}return n}now(){return this.opts.now?.()??Date.now()}planLapsed(){return fL({entitlement:this.opts.readEntitlement?.()??null,paired:this.opts.isPaired?.()??!1,now:this.now()})}emitEdge(e,n,o){let r=this._graph.devices.find(i=>i.sources.some(s=>s.provider===e&&s.providerAccountId===n&&s.nativeId===o.nativeId));r&&this.opts.onEdgeEvent({type:"device_event",deviceId:r.id,capability:o.capability,instance:o.instance,event:o.event,payload:o.payload,ts:o.ts})}rebuild(){let e=new Map,n=[];for(let r of this.adapters.values())for(let i of r.candidates.values()){let s=null;if(i.areaHint){let a=r.rooms.get(i.areaHint.nativeId)??i.areaHint.name;s=eN(a),e.has(s)||e.set(s,{id:s,name:a,providerRefs:[{provider:i.source.provider,nativeId:i.areaHint.nativeId}]})}n.push({candidate:i,areaId:s})}let o=[...this.adapters.values()].map(r=>({accountId:r.adapter.accountId,provider:r.adapter.provider,displayName:`${r.adapter.provider}:${r.adapter.accountId}`,reachability:r.adapter.reachability,status:"linked"}));this._graph=tN({nodeId:this.opts.nodeId,updatedAt:this.now(),areas:[...e.values()],accounts:o,candidates:n}),this.opts.snapshot?.(this._graph),this.opts.onGraphChange()}};var i0=require("node:crypto");var yi=t=>t?T(t):void 0;function oN(t){return Vd(t)?"sensor":Ac(ho(t))}function NW(t){let e=[];for(let[n,o]of Object.entries(t.tuya??{}))e.push({provider:"tuya",nativeId:n,name:o.name,...yi(o.mac)?{mac:yi(o.mac)}:{},...o.category?{nativeType:o.category}:{},...oN(o.category)?{expectedType:oN(o.category)}:{}});for(let n of t.meross?.devices??[]){let o=yi(n.mac);o&&e.push({provider:"meross",nativeId:o,name:n.name??"Meross device",mac:o})}for(let[n,o]of Object.entries(t.ewelink??{}))e.push({provider:"ewelink",nativeId:n,name:o.name??"SONOFF device",...yi(o.mac)?{mac:yi(o.mac)}:{}});return e}function iN(t){let e=new Set,n=new Set;for(let s of t.rows){let a=yi(s.addresses.mac);a&&e.add(a),s.alreadyLinked?.deviceId&&n.add(s.alreadyLinked.deviceId)}let o=[],r=new Set,i=new Set;for(let s of t.graph.devices){if(s.sources.length===0||!s.sources.every(l=>l.reachability==="cloud")||n.has(s.id))continue;let a=s.sources.find(l=>l.sourceId===s.preferredSourceId)??s.sources[0],c=a.provider==="tuya"?yi(t.tuya?.[a.nativeId]?.mac):void 0;o.push({key:c??`${a.provider}:${a.nativeId}`,provider:a.provider,accountId:a.providerAccountId,name:s.name,...c?{mac:c}:{},...a.nativeType?{nativeType:a.nativeType}:{},...s.type?{expectedType:s.type}:{},state:"cloud",deviceId:s.id}),c&&r.add(c),i.add(`${a.provider}:${a.nativeId}`)}for(let s of NW(t)){if(s.mac&&(e.has(s.mac)||t.linkIndex.has(s.mac)||r.has(s.mac)))continue;let a=`${s.provider}:${s.nativeId}`;i.has(a)||(o.push({key:s.mac??a,provider:s.provider,name:s.name,...s.mac?{mac:s.mac}:{},...s.nativeType?{nativeType:s.nativeType}:{},...s.expectedType?{expectedType:s.expectedType}:{},state:"not-seen"}),s.mac&&r.add(s.mac),i.add(a))}return o.sort((s,a)=>s.provider.localeCompare(a.provider)||s.name.localeCompare(a.name)||s.key.localeCompare(a.key))}var sN=1440*60*1e3;function aN(t,e,n){return e.autoConnect==="open-protocols"&&TT(t,n)}var Uf=require("node:crypto"),MW="23x17ahWarFH6w29",UW={eu:"iotx-eu.meross.com",us:"iotx-us.meross.com",ap:"iotx-ap.meross.com"},lN=(t,e)=>fetch(t,e),sr=class extends Error{constructor(n,o){super(n);this.apiStatus=o}apiStatus},uN=t=>(0,Uf.createHash)("md5").update(t,"utf8").digest("hex"),cN=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,FW=new Set([1033]),BW="This Meross account has two-factor authentication enabled. Enter the 6-digit code (from your authenticator app or email) and sign in again.",jW="That two-factor code was incorrect or expired. Enter a fresh 6-digit Meross code and try again.",zW=t=>t.apiStatus!==void 0&&FW.has(t.apiStatus)||/mfa|two.?factor|verification code/i.test(t.message);async function e0(t,e,n,o,r,i){let s=Buffer.from(JSON.stringify(o),"utf8").toString("base64"),a=uN(`${MW}${i.nowMs}${i.nonce}${s}`),c=JSON.stringify({params:s,sign:a,timestamp:i.nowMs,nonce:i.nonce}),l={"content-type":"application/json"};r&&(l.authorization=`Basic ${r}`);let u;try{u=await t(`https://${e}${n}`,{method:"POST",headers:l,body:c})}catch(m){throw new sr(`Meross cloud unreachable: ${m.message}`)}let d=cN(await u.json().catch(()=>{})),f=d&&typeof d.apiStatus=="number"?d.apiStatus:u.status<200||u.status>=300?-1:0;if(f!==0){let m=d&&typeof d.info=="string"&&d.info||`apiStatus ${f}`;throw new sr(`Meross sign-in failed: ${m}. Check your email, password, and region.`,f)}return cN(d?.data)??{}}async function dN(t){let e=UW[t.creds.region.toLowerCase()];if(!e)throw new sr(`Unknown region "${t.creds.region}" \u2014 use eu, us, or ap.`);let n=()=>t.seed??{nowMs:Date.now(),nonce:(0,Uf.randomBytes)(8).toString("hex").toUpperCase()},o;try{o=await e0(t.fetch,e,"/v1/Auth/signIn",{email:t.creds.email,password:uN(t.creds.password),accountCountryCode:"",encryption:1,agree:0,...t.creds.mfaCode?{mfaCode:t.creds.mfaCode}:{}},void 0,n())}catch(c){throw c instanceof sr&&zW(c)?new sr(t.creds.mfaCode?jW:BW,c.apiStatus):c}let r=typeof o.key=="string"?o.key:void 0,i=typeof o.token=="string"?o.token:void 0;if(r===void 0)throw new sr("Meross sign-in returned no account key.");let s=0,a=[];try{let c=await e0(t.fetch,e,"/v1/Device/devList",{},i,n()),l=Array.isArray(c.device)?c.device:Array.isArray(c.devList)?c.devList:[];s=l.length,a=l.map(u=>u&&typeof u=="object"?u:void 0).map(u=>{let d=u&&(typeof u.macAddress=="string"?u.macAddress:typeof u.mac=="string"?u.mac:void 0);if(!d)return;let f=u&&typeof u.devName=="string"?u.devName:void 0;return{mac:d,...f?{name:f}:{}}}).filter(u=>u!==void 0)}catch{}if(i)try{await e0(t.fetch,e,"/v1/Profile/logout",{},i,n())}catch{}return{key:r,deviceCount:s,devices:a}}var pN=require("node:crypto"),HW=process.env.BRIDGE_EWELINK_APP_ID||"4s1FXKC9FaGfoqXhmXSJneb3qcm1gOak",KW=process.env.BRIDGE_EWELINK_APP_SECRET||"oKvCM06gvwkRbfetd6qWRrbC3rFrbIpV",t0={eu:"eu-apia.coolkit.cc",us:"us-apia.coolkit.cc",as:"as-apia.coolkit.cc",cn:"cn-apia.coolkit.cn"},fN=(t,e)=>fetch(t,e),jr=class extends Error{constructor(n,o,r){super(n);this.code=o;this.data=r}code;data},vi=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,ar=t=>typeof t=="string"&&t?t:void 0,GW=t=>(0,pN.createHmac)("sha256",KW).update(t,"utf8").digest("base64");async function n0(t,e,n,o){let r=o.body!==void 0?JSON.stringify(o.body):"",i={"content-type":"application/json","X-CK-Appid":HW};i.Authorization=o.token?`Bearer ${o.token}`:`Sign ${GW(r)}`;let s;try{s=o.method==="GET"?await t(`https://${e}${n}`,{method:"GET",headers:i}):await t(`https://${e}${n}`,{method:"POST",headers:i,body:r})}catch(l){throw new jr(`eWeLink cloud unreachable: ${l.message}`)}let a=vi(await s.json().catch(()=>{})),c=a&&typeof a.error=="number"?a.error:s.status<200||s.status>=300?-1:0;if(c!==0){let l=a&&ar(a.msg)||`error ${c}`;throw new jr(`eWeLink sign-in failed: ${l}. Check your email, password, and region.`,c,vi(a?.data))}return vi(a?.data)??{}}var WW={cn:"+86",us:"+1",eu:"+44",as:"+65"};async function mN(t){let e=t.creds.region.toLowerCase();if(!t0[e])throw new jr(`Unknown region "${t.creds.region}" \u2014 use eu, us, as, or cn.`);let n=t.creds.countryCode||WW[e]||"+86",o={email:t.creds.email,password:t.creds.password,countryCode:n},r=t0[e],i;try{i=await n0(t.fetch,r,"/v2/user/login",{method:"POST",body:o})}catch(u){let d=u instanceof jr&&u.code===10004?t0[ar(u.data?.region)?.toLowerCase()??""]:void 0;if(!d)throw u;r=d,i=await n0(t.fetch,r,"/v2/user/login",{method:"POST",body:o})}let s=ar(i.at);if(!s)throw new jr("eWeLink sign-in returned no access token.");let a=await n0(t.fetch,r,"/v2/device/thing?num=0",{method:"GET",token:s}),c=Array.isArray(a.thingList)?a.thingList:[],l={};for(let u of c){let d=vi(vi(u)?.itemData)??vi(u);if(!d)continue;let f=ar(d.deviceid),m=ar(d.devicekey);if(!f||!m)continue;let g=vi(d.extra),h=ar(d.mac)??(g?ar(g.staMac)??ar(g.mac):void 0);l[f]={devicekey:m,...ar(d.name)?{name:ar(d.name)}:{},...h?{mac:h}:{}}}return{keystore:l,deviceCount:Object.keys(l).length}}var r0={wsl:!1,multicastOk:null,broadcastOk:null},ZW=5*6e4,gN=30*6e4,qW="This computer runs under WSL, which can't receive Govee's LAN reply \u2014 so enabling LAN Control won't help here. Control it by adding a Govee API key (Integrations \u2192 add Govee), running AC Bridge on a native Windows/Mac/Linux install, or enabling WSL mirrored networking.";function VW(t,e,n){return{discoveredId:Pa({ip:t}),addresses:{ip:t},evidence:[],identity:{},bucket:"connect-now",localProtocol:e,expectedCapabilities:[],confidence:"low",firstSeen:n,lastSeen:n}}var JW={command:"local.connect",consumer:"app",enforceFloor:!1},YW={command:"local.autoConnect",consumer:"rules",enforceFloor:!0},XW={command:"local.forget",consumer:"app"},QW={command:"local.rename",consumer:"app"},To={command:"local.link",consumer:"app"},eZ={command:"local.unlink",consumer:"app"},Ff=class{constructor(e){this.o=e;this.discovered=e.store?.load()??{devices:[],env:r0,updatedAt:this.now()},this.roster=e.roster??qd(),this.config=(e.loadConfig??nZ)(),this.startPassive()}o;sessions=new Map;pruneTimers=new Map;inFlightId=null;controller=null;discovered;roster;chain=Promise.resolve();config;passiveHandle=null;passiveEpoch=0;autoAttempts=new Map;defaultSecretsCache=new Map;startScan(){if(this.inFlightId)return{scanId:this.inFlightId};let e=(this.o.genId??tZ)(),n=new AbortController;return this.inFlightId=e,this.controller=n,this.sessions.set(e,{id:e,status:"running",startedAt:this.now(),devices:[],env:r0}),(this.o.scan??Qw)({id:e,signal:n.signal,config:this.config,onUpdate:r=>this.onUpdate(r),onProbeError:(r,i)=>console.error(`[local-discovery] probe "${r}" degraded during scan ${e}:`,i),...this.o.timing?{timing:this.o.timing}:{}}).then(r=>this.onUpdate(r)).catch(r=>this.onFailure(e,r)).finally(()=>{this.inFlightId===e&&(this.inFlightId=null,this.controller=null),this.schedulePrune(e)}),{scanId:e}}getSession(e){let n=this.sessions.get(e);if(!n)return;let o=this.overlayRows(n.devices,n.env);return{...n,devices:o,accountDevices:this.accountRows(o)}}getDiscovered(){let e=this.overlayRows(this.discovered.devices,this.discovered.env);return{...this.discovered,devices:e,accountDevices:this.accountRows(e)}}accountRows(e){return iN({rows:e,graph:this.o.registry.graph,linkIndex:this.o.registry.linkIndex(),tuya:this.o.tuyaKeystore?.()??null,meross:this.o.merossKeystore?.()??null,ewelink:this.o.ewelinkKeystore?.()??null})}overlayTuyaRow(e){if(e.localProtocol)return e;let n=this.o.tuyaKeystore?.();if(!n)return e;if(e.identity.vendorId&&e.evidence.some(r=>r.protocol==="tuya-beacon")){let r=n[e.identity.vendorId];if(r)return this.promoteTuyaRow(e,e.identity.vendorId,r)}let o=e.addresses.mac?T(e.addresses.mac):void 0;if(o&&!e.identity.vendorId){for(let[r,i]of Object.entries(n))if(i.mac&&T(i.mac)===o)return this.promoteTuyaRow(e,r,i)}return e}promoteTuyaRow(e,n,o){let r={...e.identity,vendorId:n,name:o.name};return delete r.hint,{...e,identity:r,bucket:"connect-now",localProtocol:"tuya",expectedType:Ac(ho(o.category)),expectedCapabilities:k$(o.category)}}overlayMerossRow(e){if(e.localProtocol)return e;let n=this.o.merossKeystore?.();if(!n?.key)return e;let o=e.addresses.mac?T(e.addresses.mac):void 0,r=o?n.devices?.find(s=>T(s.mac)===o):void 0;if(!r&&e.identity.manufacturer!=="Meross")return e;let i={...e.identity,...r?.name?{name:r.name}:{}};return delete i.hint,{...e,identity:i,bucket:"connect-now",localProtocol:"meross"}}overlayEwelinkRow(e){if(e.localProtocol)return e;let n=this.o.ewelinkKeystore?.();if(!n)return e;let o=e.addresses.mac?T(e.addresses.mac):void 0;if(!o)return e;for(let r of Object.values(n))if(r.mac&&T(r.mac)===o){let i={...e.identity,...r.name?{name:r.name}:{}};return delete i.hint,{...e,identity:i,bucket:"connect-now",localProtocol:"ewelink"}}return e}overlayGoveeHint(e,n){return e.localProtocol||!n?.wsl||!e.identity.hint||(e.identity.manufacturer??"").toLowerCase()!=="govee"?e:{...e,identity:{...e.identity,hint:qW}}}overlayRow(e,n){return this.overlayGoveeHint(this.overlayEwelinkRow(this.overlayMerossRow(this.overlayTuyaRow(e))),n)}overlayRows(e,n){return e.map(o=>this.overlayRow(o,n))}getConfig(){return this.config}applyConfig(e){this.o.saveConfig?.(e);let n=this.config;return this.config=e,vN(n)!==vN(e)&&(this.stopPassive(),this.startPassive()),this.config}connect(e){return this.serialize(()=>this.connectWork(e))}forget(e){return this.serialize(()=>this.forgetWork(e))}rename(e){return this.serialize(()=>this.renameWork(e))}async linkTuya(e){return this.serialize(async()=>{try{let{keystore:n,deviceCount:o,sleepyCount:r}=await rc({creds:e,fetch:this.o.tuyaFetch??hN}),i=this.secretsFor("tuya");await i.write("cloud",JSON.stringify(e));let s=oc(Cn(await i.read("keystore")),n);return await i.write("keystore",JSON.stringify(s)),this.emitAudit(To,{provider:"tuya",deviceCount:o},"account:tuya",!0),{ok:!0,deviceCount:o,sleepyCount:r}}catch(n){return this.emitAudit(To,{provider:"tuya"},"account:tuya",!1),{ok:!1,error:n instanceof Ue?n.message:`Tuya key wizard failed: ${n.message}`}}})}lastTuyaRefreshAt=Number.NEGATIVE_INFINITY;async refreshTuyaKeystore(){let e=this.now();if(e-this.lastTuyaRefreshAt<2e4)return!1;let n=this.secretsFor("tuya"),o=si(await n.read("cloud"));if(!o)return!1;this.lastTuyaRefreshAt=e;try{let{keystore:r}=await rc({creds:o,fetch:this.o.tuyaFetch??hN}),i=oc(Cn(await n.read("keystore")),r);return await n.write("keystore",JSON.stringify(i)),!0}catch{return!1}}async linkMeross(e){return this.serialize(async()=>{try{let{key:n,deviceCount:o,devices:r}=await dN({creds:e,fetch:this.o.merossFetch??lN});return await this.secretsFor("meross").write("keystore",JSON.stringify({key:n,...r.length?{devices:r}:{}})),this.emitAudit(To,{provider:"meross",deviceCount:o},"account:meross",!0),{ok:!0,deviceCount:o}}catch(n){return this.emitAudit(To,{provider:"meross"},"account:meross",!1),{ok:!1,error:n instanceof sr?n.message:`Meross sign-in failed: ${n.message}`}}})}async linkEwelink(e){return this.serialize(async()=>{try{let{keystore:n,deviceCount:o}=await mN({creds:e,fetch:this.o.ewelinkFetch??fN});return await this.secretsFor("ewelink").write("keystore",JSON.stringify(n)),this.emitAudit(To,{provider:"ewelink",deviceCount:o},"account:ewelink",!0),{ok:!0,deviceCount:o}}catch(n){return this.emitAudit(To,{provider:"ewelink"},"account:ewelink",!1),{ok:!1,error:n instanceof jr?n.message:`eWeLink sign-in failed: ${n.message}`}}})}async linkGovee(e){return this.serialize(async()=>{try{let{keystore:n,deviceCount:o}=await wA({creds:e,fetch:this.o.goveeFetch??rp}),r=this.secretsFor("govee");return await r.write("cloud",JSON.stringify({apiKey:e.apiKey})),await r.write("keystore",JSON.stringify(n)),this.emitAudit(To,{provider:"govee",deviceCount:o},"account:govee",!0),{ok:!0,deviceCount:o}}catch(n){return this.emitAudit(To,{provider:"govee"},"account:govee",!1),{ok:!1,error:n instanceof on?n.message:`Govee sign-in failed: ${n.message}`}}})}async unlinkProvider(e){return this.serialize(async()=>{let n=NR(this.roster,e),o=this.secretsFor(e);for(let i of["keystore","cloud",Tn(e)])try{await o.delete?.(i)}catch{}let r;try{await this.reloadAdapter(e)}catch{r="adapter reload failed \u2014 will settle at hub start"}return this.emitAudit(eZ,{provider:e,removed:n},`account:${e}`,!0,r),{ok:!0,...r?{note:r}:{}}})}dispose(){this.stopPassive(),this.controller?.abort();for(let e of this.pruneTimers.values())clearTimeout(e);this.pruneTimers.clear()}startPassive(){if(this.passiveHandle||!this.o.passive||!this.config.passive)return;let e=++this.passiveEpoch;try{this.passiveHandle=this.o.passive({config:this.config,onDevices:n=>{e===this.passiveEpoch&&this.onPassiveDevices(n)},now:()=>this.now()})}catch(n){this.passiveHandle=null,console.error("[local-discovery] passive listeners failed to start:",n)}}stopPassive(){this.passiveEpoch++;try{this.passiveHandle?.stop()}catch{}this.passiveHandle=null}onPassiveDevices(e){let n=kN({id:"passive",status:"done",startedAt:0,devices:[...e],env:this.discovered.env},this.o.registry.linkIndex(),this.o.registry.graph.accounts).devices,o=this.now()-gN,r=this.discovered.devices.filter(s=>s.lastSeen>=o),i=r.length!==this.discovered.devices.length;for(let s of n)wN(r,s)&&(i=!0);if(this.discovered={devices:r,env:this.discovered.env,updatedAt:this.now()},i)try{this.o.store?.save(this.discovered)}catch(s){console.error("[local-discovery] persist failed:",s)}this.healRosterIps(n).catch(s=>{console.error("[local-discovery] roster heal failed:",s)});for(let s of n)try{this.maybeAutoConnect(s)}catch(a){console.error("[local-discovery] auto-connect evaluation failed:",a)}}rosterCache;enabledRostersCached(){let e=this.now();if(this.rosterCache&&e-this.rosterCache.at<5e3)return this.rosterCache.byProto;let n=new Map;for(let o of Hn.options){let r=nc(this.roster.read(o));r.length>0&&n.set(o,r)}return this.rosterCache={at:e,byProto:n},n}async healRosterIps(e){for(let[n,o]of this.enabledRostersCached()){let r=this.o.probes?.[n];for(let i of e){let s=i.addresses.mac?T(i.addresses.mac):void 0;if(!s)continue;let a=o.find(c=>c.key===s);!a||a.ip===i.addresses.ip||r&&await this.confirmSameDevice(n,s,i,r)&&tc(this.roster,n,s,i.addresses.ip)}}}async confirmSameDevice(e,n,o,r){let i=this.credentialSpecFor(e),s;if(i.length>0&&(s=yN(await this.secretsFor(e).read(Tn(e))),!ed(e)&&(!s||i.some(u=>!s[u.key]))))return!1;let a={...o.identity.vendorId?{vendorId:o.identity.vendorId}:{},mac:n},c=await r(o.addresses.ip,s,a).catch(()=>null);return!c||c.badCredentials!==void 0||c.pairingRequired!==void 0||c.veto?!1:(c.mac?T(c.mac):void 0)===n}maybeAutoConnect(e){let n=e.addresses.mac?T(e.addresses.mac):void 0,o=e.localProtocol;if(!n||!o||!aN(e,this.config,this.credentialSpecs()))return;let r=this.roster.read(o)?.devices.find(s=>s.key===n);if(r&&!r.enabled)return;let i=this.autoAttempts.get(n);i!==void 0&&this.now()-i<sN||(this.autoAttempts.set(n,this.now()),this.serialize(()=>this.connectWork({discoveredId:e.discoveredId,protocol:o},YW)).catch(()=>{}))}async connectWork(e,n=JW){let o=e.ip!==void 0?VW(e.ip,e.protocol,this.now()):e.discoveredId!==void 0?this.findDiscovered(e.discoveredId):void 0;if(!o)return{kind:"unknown-id"};if(o.bucket==="link-ecosystem")return{kind:"link-ecosystem",...o.suggestedProvider?{provider:o.suggestedProvider}:{}};if(o.bucket==="identified-only")return{kind:"identified-only",...o.identity.hint?{hint:o.identity.hint}:{}};if(o.localProtocol!==e.protocol)return{kind:"protocol-mismatch",...o.localProtocol?{expected:o.localProtocol}:{}};let r=this.o.probes?.[e.protocol];if(!r)return{kind:"protocol-unsupported"};let i=Tn(e.protocol),s={protocol:e.protocol,...e.name?{name:e.name}:{}},a=o.addresses.mac?T(o.addresses.mac):void 0;if(a&&e.credentials===void 0){let U=this.liveDeviceId(e.protocol,a,i);if(U)return this.emitAudit(n,s,U,!0),{kind:"ok",deviceId:U,accountId:i,note:"already connected"}}let c=this.credentialSpecFor(e.protocol),l=c.length>0,u=l&&!ed(e.protocol),d=l?this.secretsFor(e.protocol):void 0,f;if(l&&(f=e.credentials??yN(await d.read(i)),u&&(!f||c.some(U=>!f[U.key]))))return this.emitAudit(n,s,a?Yt([`mac:${a}`]):o.discoveredId,!1,"credentials-required"),{kind:"credentials-required"};let m=f?Object.values(f):[],g=U=>m.length?nN(U,m):U,h={...o.identity.vendorId?{vendorId:o.identity.vendorId}:{},...a?{mac:a}:{}},y=await r(o.addresses.ip,f,h).catch(()=>null);if(!y)return this.emitAudit(n,s,a?Yt([`mac:${a}`]):o.discoveredId,!1,g("unreachable")),{kind:"unreachable"};if(y.pairingRequired!==void 0)return this.emitAudit(n,s,a?Yt([`mac:${a}`]):o.discoveredId,!1,"pairing-required"),{kind:"pairing-required",note:y.pairingRequired};if(y.badCredentials!==void 0)return this.emitAudit(n,s,a?Yt([`mac:${a}`]):o.discoveredId,!1,"credentials-required"),{kind:"credentials-required",note:y.badCredentials};if(e.protocol==="tuya"&&(y.veto===px||y.veto===dx)&&await this.refreshTuyaKeystore()){let U=await r(o.addresses.ip,f,h).catch(()=>null);U&&(y=U)}let b=y.mac?T(y.mac):void 0;if(a&&b&&a!==b)return this.emitAudit(n,s,Yt([`mac:${a}`]),!1,g("unreachable")),{kind:"unreachable"};if(y.veto){let U=b??a;return this.emitAudit(n,s,U?Yt([`mac:${U}`]):o.discoveredId,!1,g(y.veto)),{kind:"device-rejected",error:y.veto}}if(n.enforceFloor&&y.expectedType&&os.has(y.expectedType)){let U=b??a;return this.emitAudit(n,s,U?Yt([`mac:${U}`]):o.discoveredId,!1,g("never-auto floor")),{kind:"never-auto-floor"}}let w=a??b;if(!w)return this.emitAudit(n,s,o.discoveredId,!1,g("mac-unresolved")),{kind:"mac-unresolved"};let x=this.liveDeviceId(e.protocol,w,i);if(x)return this.emitAudit(n,s,x,!0),{kind:"ok",deviceId:x,accountId:i,note:"already connected"};l&&e.credentials&&f&&e.protocol!=="esphome"&&await d.write(i,JSON.stringify(f));let I=e.credentials?.encryptionKey;if(l&&e.protocol==="esphome"&&I){let U=Ms(await d.read("keystore"));await d.write("keystore",JSON.stringify(z1(U,w,I)))}let E=e.name??y.name??o.identity.name,C=y.model??o.identity.model;OR(this.roster,e.protocol,{mac:w,ip:o.addresses.ip,...E?{name:E}:{},...C?{model:C}:{},...y.providerDeviceId?{providerDeviceId:y.providerDeviceId}:{}});try{await this.reloadAdapter(e.protocol)}catch(U){let W=g(U instanceof Error?U.message:String(U));return this.emitAudit(n,s,Yt([`mac:${w}`]),!1,W),{kind:"adapter-init-failed",error:W}}let F=Yt([`mac:${w}`]);return this.emitAudit(n,s,F,!0),{kind:"ok",deviceId:F,accountId:i}}async forgetWork(e){let n=this.resolveForget(e.deviceId);if(!n)return{kind:"unknown-device"};if(LR(this.roster,n.protocol,n.mac,e.purge),e.purge&&this.credentialSpecFor(n.protocol).length>0&&(this.roster.read(n.protocol)?.devices??[]).length===0)try{await this.secretsFor(n.protocol).delete?.(Tn(n.protocol))}catch{}let o;try{await this.reloadAdapter(n.protocol)}catch{o="adapter reload failed \u2014 remaining devices will retry at hub start"}if(e.discoveredId!==void 0){let r=this.discovered.devices.filter(i=>i.discoveredId!==e.discoveredId);if(r.length!==this.discovered.devices.length){this.discovered={devices:r,env:this.discovered.env,updatedAt:this.now()};try{this.o.store?.save(this.discovered)}catch{}}}return this.emitAudit(XW,{purge:e.purge},e.deviceId,!0,o),{kind:"ok",...o?{note:o}:{}}}async renameWork(e){let n=this.resolveForget(e.deviceId);if(!n)return{kind:"unknown-device"};let o=e.name.trim();MR(this.roster,n.protocol,n.mac,o||void 0);let r;try{await this.reloadAdapter(n.protocol)}catch{r="adapter reload failed \u2014 the new name applies at hub start"}return this.emitAudit(QW,{renamed:o.length>0},e.deviceId,!0,r),{kind:"ok",...r?{note:r}:{}}}resolveForget(e){let n=new Set(Hn.options),r=this.o.registry.graph.devices.find(i=>i.id===e)?.sources.find(i=>n.has(i.provider));if(r){let i=kt(r.nativeId)?.parentNativeId??r.nativeId;return{protocol:r.provider,mac:i}}for(let i of Hn.options)for(let s of this.roster.read(i)?.devices??[])if(Yt([`mac:${s.key}`])===e)return{protocol:i,mac:s.key}}async reloadAdapter(e){let n=Tn(e),o=Kc(e);await this.o.registry.removeAdapter(o,n);let r=nc(this.roster.read(e));if(r.length===0)return;let i={devices:r,onIpChange:(s,a)=>tc(this.roster,e,s,a)};await this.o.registry.addAdapter(o,n,i)}enabledKey(e,n){return nc(this.roster.read(e)).some(o=>o.key===n)}liveDeviceId(e,n,o){if(!this.enabledKey(e,n))return;let r=Kc(e),i=this.o.registry.graph.devices.find(s=>s.sources.some(a=>a.provider===r&&T(a.nativeId)===n));return i?i.id:this.o.registry.hasAdapter?.(r,o)?Yt([`mac:${n}`]):void 0}credentialSpecs(){return this.o.credentialSpecs??Sb}credentialSpecFor(e){return this.credentialSpecs()[e]??[]}secretsFor(e){if(this.o.secrets)return this.o.secrets(e);let n=this.defaultSecretsCache.get(e);if(!n){let o=new Map;n={read:async r=>o.get(r)??null,write:async(r,i)=>{i===""?o.delete(r):o.set(r,i)},delete:async r=>{o.delete(r)}},this.defaultSecretsCache.set(e,n)}return n}findDiscovered(e){for(let o of[...this.sessions.values()].sort((r,i)=>i.startedAt-r.startedAt)){let r=o.devices.find(i=>i.discoveredId===e);if(r)return this.overlayRow(r,o.env)}let n=this.discovered.devices.find(o=>o.discoveredId===e);return n&&this.overlayRow(n,this.discovered.env)}emitAudit(e,n,o,r,i){try{this.o.audit?.({type:"device_audit",requestId:`laud_${(0,i0.randomBytes)(6).toString("hex")}`,consumer:e.consumer,deviceId:o,capability:"connectivity",command:e.command,params:n,ok:r,confirmRequired:!1,...i?{error:i}:{},ts:this.now()})}catch{}}serialize(e){let n=this.chain.then(e,e);return this.chain=n.then(()=>{},()=>{}),n}onUpdate(e){let n=this.enrich(e);if(this.sessions.set(n.id,n),n.status!=="running"){let o=this.now()-gN,r=this.discovered.devices.filter(i=>i.lastSeen>=o);for(let i of n.devices)wN(r,i);this.discovered={devices:r,env:n.env,updatedAt:this.now()};try{this.o.store?.save(this.discovered)}catch(i){console.error("[local-discovery] persist failed:",i)}for(let i of n.devices)this.maybeAutoConnect(i)}}onFailure(e,n){let o=this.sessions.get(e);this.sessions.set(e,{id:e,status:"failed",startedAt:o?.startedAt??this.now(),finishedAt:this.now(),error:n instanceof Error?n.message:String(n),devices:o?.devices??[],env:o?.env??r0})}schedulePrune(e){if(this.pruneTimers.has(e))return;let n=setTimeout(()=>{this.sessions.delete(e),this.pruneTimers.delete(e)},this.o.pruneAfterMs??ZW);n.unref(),this.pruneTimers.set(e,n)}now(){return this.o.now?.()??Date.now()}enrich(e){return kN(e,this.o.registry.linkIndex(),this.o.registry.graph.accounts)}};function tZ(){return`scan_${(0,i0.randomBytes)(6).toString("hex")}`}var hN=async(t,e)=>{let n=await fetch(t,{method:e.method,headers:e.headers,...e.body!==void 0?{body:e.body}:{}});return{status:n.status,text:()=>n.text()}};function yN(t){if(t)try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let[o,r]of Object.entries(e))typeof r=="string"&&(n[o]=r);return n}catch{return}}function nZ(){return jo.parse({})}function vN(t){return`${t.passive}:${t.protocols.mdns!==!1}:${t.protocols.tuya!==!1}`}function bN(t,e){return t.addresses.ip!==e.addresses.ip||t.addresses.mac!==e.addresses.mac||t.bucket!==e.bucket||t.identity.name!==e.identity.name||t.localProtocol!==e.localProtocol||JSON.stringify(t.alreadyLinked??null)!==JSON.stringify(e.alreadyLinked??null)}function rZ(t,e){let n=e.map(o=>({...o}));for(let o of t){let r=n.find(i=>i.protocol===o.protocol&&i.detail===o.detail);r?r.at=Math.max(r.at,o.at):n.push({...o})}return n.sort((o,r)=>o.at-r.at)}function o0(t,e){let n=rZ(t.evidence,e.evidence),o=Math.min(t.firstSeen,e.firstSeen),r=Math.max(t.lastSeen,e.lastSeen);if(!e.addresses.mac){let b={...t.identity};return b.name===void 0&&e.identity.name!==void 0&&(b.name=e.identity.name),b.manufacturer===void 0&&e.identity.manufacturer!==void 0&&(b.manufacturer=e.identity.manufacturer),b.model===void 0&&e.identity.model!==void 0&&(b.model=e.identity.model),b.hint===void 0&&e.identity.hint!==void 0&&(b.hint=e.identity.hint),b.vendorId===void 0&&e.identity.vendorId!==void 0&&(b.vendorId=e.identity.vendorId),{...t,evidence:n,firstSeen:o,lastSeen:r,identity:b}}let i=t.expectedType!==void 0&&os.has(t.expectedType)&&!(e.expectedType!==void 0&&os.has(e.expectedType)),s=i?t.expectedType:e.expectedType??t.expectedType,a=i?t.expectedCapabilities:e.expectedCapabilities.length>0?e.expectedCapabilities:t.expectedCapabilities,c={},l=e.identity.name??t.identity.name,u=e.identity.manufacturer??t.identity.manufacturer,d=e.identity.model??t.identity.model,f=e.identity.hint??t.identity.hint,m=e.identity.vendorId??t.identity.vendorId;l!==void 0&&(c.name=l),u!==void 0&&(c.manufacturer=u),d!==void 0&&(c.model=d),f!==void 0&&(c.hint=f),m!==void 0&&(c.vendorId=m);let g={discoveredId:e.discoveredId,addresses:{ip:e.addresses.ip,mac:e.addresses.mac},evidence:n,identity:c,bucket:e.bucket,expectedCapabilities:[...a],confidence:e.confidence,firstSeen:o,lastSeen:r},h=e.addresses.hostname??t.addresses.hostname,y=e.addresses.port??t.addresses.port;return h!==void 0&&(g.addresses.hostname=h),y!==void 0&&(g.addresses.port=y),e.localProtocol!==void 0&&(g.localProtocol=e.localProtocol),e.suggestedProvider!==void 0&&(g.suggestedProvider=e.suggestedProvider),s!==void 0&&(g.expectedType=s),e.alreadyLinked!==void 0&&(g.alreadyLinked=e.alreadyLinked),g}function wN(t,e){let n=t.findIndex(i=>i.discoveredId===e.discoveredId);if(n!==-1){let i=t[n];return t[n]=o0(i,e),bN(i,t[n])}if(e.addresses.mac){let i=t.findIndex(s=>!s.addresses.mac&&s.addresses.ip===e.addresses.ip);return i!==-1?(t[i]=o0(t[i],e),!0):(t.push(e),!0)}let o=-1,r=0;for(let i=0;i<t.length;i++)t[i].addresses.ip===e.addresses.ip&&(o=i,r++);if(r===1){let i=t[o];return t[o]=o0(i,e),bN(i,t[o])}return t.push(e),!0}function kN(t,e,n){let o=n.filter(a=>a.status!=="revoked"),r=new Set(o.map(a=>a.provider)),i=new Set(o.filter(a=>a.provider==="hue").map(a=>a.accountId)),s=t.devices.map(a=>{if(a.addresses.mac){let c=e.get(T(a.addresses.mac));if(c)return{...a,alreadyLinked:{provider:c.provider,deviceId:c.deviceId,accountId:c.accountId}}}if(a.suggestedProvider==="smartthings"&&r.has("smartthings"))return{...a,alreadyLinked:{provider:"smartthings"}};if(a.suggestedProvider==="hue"&&a.addresses.mac){let c=oZ(a.addresses.mac);if(c){let l=qs("hue",c);if(i.has(l))return{...a,alreadyLinked:{provider:"hue",accountId:l}}}}return a});return{...t,devices:s}}function oZ(t){let e=t.replace(/[^0-9a-f]/gi,"").toLowerCase();return e.length===12?`${e.slice(0,6)}fffe${e.slice(6)}`:void 0}var s0=require("node:crypto");var bi=t=>Math.max(0,Math.min(100,Math.round(t)));function a0(t){let e={type:t.type,capabilities:t.capabilities},n=[],o=null,r,i,s=0,a=(f,m)=>{let g=vr[f.type]?.find(h=>h.command===m);return!g||g.gate&&!g.gate(f)?!1:Ra(e,f,g)?(s++,!1):!0},c=(f,m,g={})=>{a(f,m)&&n.push({capability:f.type,command:m,params:g,...f.instance?{instance:f.instance}:{}})};for(let f of t.capabilities)switch(f.type){case"power":f.state.on!==null&&a(f,f.state.on?"turnOn":"turnOff")&&(o={on:f.state.on,...f.instance?{instance:f.instance}:{}});break;case"brightness":f.state.level!=null&&c(f,"setBrightness",{level:bi(f.state.level)});break;case"color":r=f;break;case"colorTemperature":i=f;break;case"thermostat":f.state.mode!=null&&c(f,"setThermostatMode",{mode:f.state.mode}),f.config.supportsRange&&f.state.heatC!=null&&f.state.coolC!=null?c(f,"setRange",{heatCelsius:f.state.heatC,coolCelsius:f.state.coolC}):f.state.setpointC!=null&&c(f,"setSetpoint",{celsius:f.state.setpointC});break;case"humidity":f.config.settable&&f.state.targetPct!=null&&c(f,"setHumidity",{percent:bi(f.state.targetPct)});break;case"fan":f.state.on===!1?c(f,"turnOff"):(f.state.level!=null&&c(f,"setFanSpeed",{level:bi(f.state.level)}),f.state.preset!=null&&c(f,"setFanPreset",{preset:f.state.preset}),f.state.oscillating!=null&&c(f,"setOscillate",{oscillating:f.state.oscillating}),f.state.on===!0&&c(f,"turnOn"));break;case"cover":f.config.supportsPosition&&f.state.position!=null?c(f,"setPosition",{position:bi(f.state.position)}):f.state.state==="open"?c(f,"open"):f.state.state==="closed"&&c(f,"close"),f.config.supportsTilt&&f.state.tilt!=null&&c(f,"setTilt",{tilt:bi(f.state.tilt)});break;case"mode":f.state.value!=null&&c(f,"setMode",{value:f.state.value});break;case"toggle":f.state.on!=null&&c(f,"setToggle",{on:f.state.on});break;case"range":f.state.value!=null&&c(f,"setRange",{value:f.state.value});break;case"volume":f.state.level!=null&&c(f,"setVolume",{level:bi(f.state.level)}),f.state.muted!=null&&c(f,"setMute",{muted:f.state.muted});break;case"inputSource":f.state.source!=null&&c(f,"selectInput",{source:f.state.source});break;case"mediaTransport":f.state.state==="playing"?c(f,"play"):f.state.state==="paused"?c(f,"pause"):f.state.state==="stopped"&&c(f,"stop"),f.state.shuffle!=null&&c(f,"setShuffle",{on:f.state.shuffle}),f.state.repeat!=null&&c(f,"setRepeat",{mode:f.state.repeat});break;case"startStop":f.state.state==="stopped"?c(f,"stop"):f.state.state==="paused"&&f.config.supportsPause&&c(f,"pause");break;case"lock":f.state.state==="locked"?c(f,"lock"):f.state.state==="unlocked"&&c(f,"unlock");break;default:break}let l=r&&r.state.hue!=null&&r.state.saturation!=null,u=i&&i.state.kelvin!=null;u&&(!l||(r.state.saturation??0)<=3)?c(i,"setColorTemperature",{kelvin:Math.round(i.state.kelvin)}):l?c(r,"setColor",{hue:Math.round(r.state.hue),saturation:bi(r.state.saturation)}):u&&c(i,"setColorTemperature",{kelvin:Math.round(i.state.kelvin)});let d=[];return o&&!o.on?d.push({capability:"power",command:"turnOff",params:{},...o.instance?{instance:o.instance}:{}}):(d.push(...n),o&&o.on&&d.push({capability:"power",command:"turnOn",params:{},...o.instance?{instance:o.instance}:{}})),{commands:d,skipped:s}}var iZ=p.object({deviceId:p.string(),name:p.string(),deviceType:p.string(),capabilities:p.array(p.unknown()),native:p.unknown().optional()}),sZ=p.object({sessionId:p.string(),generation:p.number().int(),startedAt:p.number(),status:p.enum(["active","reverting","reverted"]),revertOnStop:p.boolean(),owner:p.enum(["app","hook"]).default("app"),devices:p.array(iZ)});function xN(t){return{load:()=>{let e=X(t);if(!e)return null;try{let n=sZ.safeParse(JSON.parse(e));return n.success?n.data:null}catch{return null}},save:e=>pe(t,JSON.stringify(e),384),clear:()=>it(t)}}var aZ=()=>{let t=null;return{load:()=>t,save:e=>{t=e},clear:()=>{t=null}}},cZ=t=>new Promise(e=>{setTimeout(e,t).unref?.()});async function lZ(t,e,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n()),e),o.unref?.()});try{return await Promise.race([t,r])}finally{o&&clearTimeout(o)}}async function uZ(t,e,n){let o=0,r=Math.max(1,Math.min(e,t.length)),i=Array.from({length:r},async()=>{for(;;){let s=o++;if(s>=t.length)return;await n(t[s])}});await Promise.all(i)}var Bf=class{registry;store;now;log;heartbeatTimeoutMs;maxRecoveryAgeMs;deviceRevertTimeoutMs;recoveryOnlineTimeoutMs;concurrency;cancelEffects;resumeEffects;scheduleTimeout;current=null;touched=new Set;reverting=null;watchdog=null;generation=0;recoveryPromise;constructor(e){this.registry=e.registry,this.store=e.store??aZ(),this.now=e.now??Date.now,this.log=e.log??(()=>{}),this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??12e4,this.maxRecoveryAgeMs=e.maxRecoveryAgeMs??30*6e4,this.deviceRevertTimeoutMs=e.deviceRevertTimeoutMs??8e3,this.recoveryOnlineTimeoutMs=e.recoveryOnlineTimeoutMs??25e3,this.concurrency=e.concurrency??6,this.cancelEffects=e.cancelEffects??(async()=>{}),this.resumeEffects=e.resumeEffects??(()=>{}),this.scheduleTimeout=e.scheduleTimeout??((o,r)=>{let i=setTimeout(o,r);return i.unref?.(),()=>clearTimeout(i)});let n=this.store.load();this.generation=n?.generation??0,this.recoveryPromise=this.recover(n).catch(o=>this.log(`recovery failed: ${String(o)}`))}async activate(e){return this.resumeEffects(),e.revertOnStop?this.current&&this.current.status==="active"?this.status():(this.generation+=1,this.current={sessionId:e.sessionId??(0,s0.randomUUID)(),generation:this.generation,startedAt:this.now(),status:"active",revertOnStop:!0,owner:e.owner??"app",devices:[]},this.touched.clear(),this.reverting=null,this.persist(),e.deadman!==!1&&this.armWatchdog(),this.log(`revert session ${this.current.sessionId} armed (gen ${this.generation}, ${this.current.owner})`),this.status()):(this.disarmWatchdog(),this.current=null,this.touched.clear(),this.reverting=null,this.store.clear(),this.status())}get activeOwner(){return this.current&&this.current.status==="active"?this.current.owner:null}async noteActuation(e,n){let o=this.current;if(!(!o||o.status!=="active"||!o.revertOnStop)&&(await this.captureDevice(e,o),n==="scene")){let r=this.registry.graph.devices.find(i=>i.id===e);for(let i of r?.members??[])await this.captureDevice(i,o)}}async captureDevice(e,n){if(!(this.current!==n||n.status!=="active")&&!this.touched.has(e)){if(this.touched.add(e),await this.recoveryPromise.catch(()=>{}),this.current!==n||n.status!=="active"){this.touched.delete(e);return}try{let o=this.registry.graph.devices.find(i=>i.id===e);if(!o){this.touched.delete(e);return}let r=await this.registry.captureNative(e);if(this.current!==n||n.status!=="active")return;n.devices.push({deviceId:e,name:o.name,deviceType:o.type,capabilities:JSON.parse(JSON.stringify(o.capabilities)),...r!==void 0?{native:r}:{}}),this.persist(),this.log(`baseline captured: ${o.name} (${e})${r!==void 0?" [native]":""}`)}catch(o){this.log(`baseline capture failed for ${e}: ${String(o)}`)}}}heartbeat(e){let n=this.current;return n&&n.status==="active"&&n.revertOnStop&&(!e||e===n.sessionId)&&this.armWatchdog(),this.status()}async stop(e){let n=this.current;if(!n)return await this.cancelEffects(),this.status();if(e&&e!==n.sessionId)return this.status();this.disarmWatchdog();let o=await this.runRevert();return{...this.status(),summary:o}}status(){let e=this.current;return!e||e.status!=="active"?{active:!1,touched:0,revertOnStop:!0}:{active:!0,sessionId:e.sessionId,generation:e.generation,touched:e.devices.length,revertOnStop:e.revertOnStop,owner:e.owner}}async ready(){await this.recoveryPromise.catch(()=>{})}dispose(){this.disarmWatchdog()}persist(){this.current&&this.store.save(this.current)}armWatchdog(){this.disarmWatchdog(),this.watchdog=this.scheduleTimeout(()=>{this.onWatchdogExpire()},this.heartbeatTimeoutMs)}disarmWatchdog(){this.watchdog&&this.watchdog(),this.watchdog=null}async onWatchdogExpire(){let e=this.current;!e||e.status!=="active"||(this.log(`no heartbeat for ${Math.round(this.heartbeatTimeoutMs/1e3)}s \u2014 auto-reverting session ${e.sessionId}`),await this.runRevert().catch(n=>this.log(`dead-man revert failed: ${String(n)}`)))}runRevert(){if(this.reverting)return this.reverting;let e=this.current;if(!e||e.status==="reverted")return Promise.resolve({reverted:0,failed:0,skipped:0});e.status="reverting",this.persist();let n=(async()=>{await this.cancelEffects().catch(()=>{});let o=await this.revertDevices(e.devices,!1);return this.current===e&&(e.status="reverted",this.store.clear()),this.log(`revert complete: ${o.reverted} reverted, ${o.failed} failed, ${o.skipped} skipped`),o})();return this.reverting=n,n.catch(()=>{}).finally(()=>{this.reverting===n&&(this.reverting=null)}),n}async recover(e){if(!e||e.status==="reverted"||e.devices.length===0){e&&this.store.clear();return}let n=this.now()-e.startedAt;if(n>this.maxRecoveryAgeMs){this.log(`dangling session ${e.sessionId} too old (${Math.round(n/1e3)}s) \u2014 discarding without revert`),this.store.clear();return}this.log(`recovering dangling session ${e.sessionId} (${e.devices.length} devices)`),await this.revertDevices(e.devices,!0),this.store.clear()}async revertDevices(e,n){let o={reverted:0,failed:0,skipped:0};if(e.length===0)return o;let r=this.deviceRevertTimeoutMs+(n?this.recoveryOnlineTimeoutMs:0);return await uZ(e,this.concurrency,async i=>{let s=await lZ(this.revertOne(i,n).catch(a=>(this.log(`revert ${i.deviceId} failed: ${String(a)}`),"failed")),r,()=>"failed");o[s]+=1}),o}async revertOne(e,n){if(n&&!await this.waitOnline(e.deviceId))return"failed";if(e.native!==void 0&&await this.registry.restoreNative(e.deviceId,e.native).catch(()=>!1))return"reverted";let{commands:o,skipped:r}=a0({type:e.deviceType,capabilities:e.capabilities});if(o.length===0)return r>0?"skipped":"reverted";let i=!1;for(let s of o)(await this.registry.invoke({type:"device_command",requestId:(0,s0.randomUUID)(),deviceId:e.deviceId,capability:s.capability,command:s.command,params:s.params,consumer:"app",...s.instance?{instance:s.instance}:{}},{internal:!0})).ok||(i=!0);return i?"failed":"reverted"}async waitOnline(e){let n=this.now()+this.recoveryOnlineTimeoutMs;for(;;){if(this.registry.graph.devices.find(o=>o.id===e)?.online)return!0;if(this.now()>=n)return!1;await cZ(1e3)}}};var jf=class{timeoutMs;scheduleTimeout;onIdle;watched=new Map;constructor(e){this.timeoutMs=e.timeoutMs??18e5,this.scheduleTimeout=e.scheduleTimeout??((n,o)=>{let r=setTimeout(n,o);return r.unref?.(),()=>clearTimeout(r)}),this.onIdle=e.onIdle}note(e){if(e.agent!=="codex"||e.state==="ended"){this.clear(e.sessionId);return}this.clear(e.sessionId);let n={sessionId:e.sessionId,...e.claudeSessionId!==void 0?{claudeSessionId:e.claudeSessionId}:{},cwd:e.cwd,cancel:()=>{}};n.cancel=this.scheduleTimeout(()=>{this.watched.delete(e.sessionId);let{cancel:o,...r}=n;this.onIdle(r)},this.timeoutMs),this.watched.set(e.sessionId,n)}clear(e){let n=this.watched.get(e);n&&(n.cancel(),this.watched.delete(e))}dispose(){for(let e of this.watched.values())e.cancel();this.watched.clear()}};function dZ(t){switch(t.kind){case"flash":case"strobe":case"colorFade":return!0;case"candle":return t.durationMs!=null;case"pulse":return t.cycles!=null;case"colorLoop":case"rainbow":return t.loops!=null;case"siren":return t.durationMs!=null}}var Eo=class extends Error{constructor(){super("effect aborted"),this.name="AbortError"}},qc=(t,e,n)=>t<e?e:t>n?n:t,$t=t=>Math.round(t),SN=(t,e,n)=>t+(e-t)*n,pZ=t=>t<.5?2*t*t:1-(-2*t+2)**2/2;function fZ(t,e,n){let o=((e-t)%360+540)%360-180;return(t+o*n+360)%360}var mZ=(t,e)=>new Promise((n,o)=>{if(e.aborted)return o(new Eo);let r=()=>{clearTimeout(i),o(new Eo)},i=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);i.unref?.(),e.addEventListener("abort",r,{once:!0})}),zf=class{reg;minStepMs;now;sleep;random;log;meterRunner;meters=new Map;running=new Map;seq=0;suspended=!1;constructor(e){this.reg=e.registry,this.minStepMs=e.minStepMs??60,this.now=e.now??Date.now,this.sleep=e.sleep??mZ,this.random=e.random??Math.random,this.log=e.log??(()=>{}),this.meterRunner=e.meterRunner}async handle(e,n){let o=c=>({type:"device_result",requestId:e.requestId,deviceId:e.deviceId,ok:!0,state:c}),r=c=>({type:"device_result",requestId:e.requestId,deviceId:e.deviceId,ok:!1,error:c});if(e.command==="stopEffect")return await this.cancel(e.deviceId),o({active:null});if(e.command!=="startEffect")return r("That effect command isn't available for this device.");if(this.suspended)return r("The bridge is stopping \u2014 effects are paused.");let i=Bo.safeParse(e.params?.spec);if(!i.success)return r("Those effect settings weren't understood.");let s=i.data;if(!this.deviceKinds(e.deviceId).includes(s.kind))return r(`This light can't run a ${s.kind} effect.`);if(s.kind==="meter"){await this.cancel(e.deviceId);let c=e.sessionId??e.deviceId;return this.meterRunner?.register(c,e.deviceId,s),this.meters.set(e.deviceId,c),o({active:"meter"})}let a=e.consumer==="rules"&&dZ(s);return await this.start(e.deviceId,e.sourceId??null,s,a,n),o({active:s.kind})}deviceKinds(e){let n=this.reg.graph.devices.find(o=>o.id===e)?.capabilities.find(o=>o.type==="effect");return n?.type==="effect"?n.config.kinds:[]}isRunning(e){return this.running.has(e)}async cancel(e){let n=this.meters.get(e);n!==void 0&&(this.meterRunner?.unregister(n,e),this.meters.delete(e));let o=this.running.get(e);if(o){o.controller.abort();try{await o.done}catch{}}}async cancelAll(){this.suspended=!0;let e=[...this.running.values()];for(let n of e)n.controller.abort();await Promise.allSettled(e.map(n=>n.done));for(let[n,o]of this.meters)this.meterRunner?.unregister(o,n);this.meters.clear()}resume(){this.suspended=!1}dispose(){this.suspended=!0;for(let e of this.running.values())e.controller.abort();this.running.clear()}async start(e,n,o,r=!1,i){await this.cancel(e);let s=new AbortController,a=!i&&r?this.snapshot(e):null,c=this.run(e,n,o,s.signal).then(async()=>{s.signal.aborted||(i?await this.applyReturn(e,n,i,s.signal):a&&await this.restore(e,n,a,s.signal))}).catch(l=>{l instanceof Eo||this.log(`effect ${o.kind} on ${e} failed: ${String(l)}`)}).finally(()=>{this.running.get(e)?.controller===s&&this.running.delete(e)});this.running.set(e,{controller:s,done:c})}snapshot(e){let n=this.reg.graph.devices.find(o=>o.id===e);return n?{type:n.type,capabilities:JSON.parse(JSON.stringify(n.capabilities))}:null}async restore(e,n,o,r){for(let i of a0(o).commands)await this.drive(e,n,i.capability,i.command,i.params,r)}async applyReturn(e,n,o,r){if(o.returnTo!=="hold"){if(o.returnTo==="off"){await this.drive(e,n,"power","turnOff",{},r);return}if(o.returnLook)for(let i of Ju(o.returnLook))await this.drive(e,n,i.capability,i.command,i.params,r)}}run(e,n,o,r){switch(o.kind){case"flash":return this.flash(e,n,o,r);case"strobe":return this.strobe(e,n,o,r);case"pulse":return this.pulse(e,n,o,r);case"colorFade":return this.colorFade(e,n,o,r);case"colorLoop":return this.colorLoop(e,n,o,r);case"candle":return this.candle(e,n,o,r);case"rainbow":return this.rainbow(e,n,o,r);case"siren":return this.siren(e,n,o,r)}}async drive(e,n,o,r,i,s){if(s.aborted)throw new Eo;if(await this.reg.invoke({type:"device_command",requestId:`${e}:fx:${this.seq++}`,deviceId:e,...n?{sourceId:n}:{},capability:o,command:r,params:i,consumer:"rules"}),s.aborted)throw new Eo}async wait(e,n){if(await this.sleep(Math.max(this.minStepMs,e),n),n.aborted)throw new Eo}currentColor(e){let o=this.reg.graph.devices.find(r=>r.id===e)?.capabilities.find(r=>r.type==="color");return o?.type!=="color"||o.state.hue==null||o.state.saturation==null?null:{hue:o.state.hue,saturation:o.state.saturation}}async fade(e,n,o,r,i,s,a){if(!o){await this.drive(e,n,"color","setColor",{hue:$t(r.hue),saturation:$t(r.saturation)},a),await this.wait(i,a);return}let c=qc($t(i/120),2,24);for(let l=1;l<=c;l++){let u=s==="ease"?pZ(l/c):l/c;await this.drive(e,n,"color","setColor",{hue:$t(fZ(o.hue,r.hue,u)),saturation:$t(SN(o.saturation,r.saturation,u))},a),await this.wait(i/c,a)}}async flash(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r),o.color&&await this.drive(e,n,"color","setColor",o.color,r),o.brightness!=null&&await this.drive(e,n,"brightness","setBrightness",{level:o.brightness},r);for(let i=0;i<o.count;i++)await this.drive(e,n,"power","turnOn",{},r),await this.wait(o.onMs,r),await this.drive(e,n,"power","turnOff",{},r),i<o.count-1&&await this.wait(o.offMs,r)}async strobe(e,n,o,r){o.color&&await this.drive(e,n,"color","setColor",o.color,r);let i=1e3/o.hz/2,s=this.now()+o.durationMs;for(;this.now()<s;)await this.drive(e,n,"power","turnOn",{},r),await this.wait(i,r),await this.drive(e,n,"power","turnOff",{},r),await this.wait(i,r)}async pulse(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r),o.color&&await this.drive(e,n,"color","setColor",o.color,r);let i=Math.min(o.minPct,o.maxPct),s=Math.max(o.minPct,o.maxPct),a=qc($t(o.periodMs/2/120),2,16),c=o.periodMs/2/a;for(let l=0;o.cycles==null||l<o.cycles;l++)for(let u of[!0,!1])for(let d=1;d<=a;d++){let f=u?d/a:1-d/a;await this.drive(e,n,"brightness","setBrightness",{level:$t(SN(i,s,f))},r),await this.wait(c,r)}}async colorFade(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r),o.from&&await this.drive(e,n,"color","setColor",{hue:$t(o.from.hue),saturation:$t(o.from.saturation)},r),await this.fade(e,n,o.from??this.currentColor(e),o.to,o.durationMs,o.easing,r)}async colorLoop(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r);let i=o.direction==="pingpong"?[...o.colors,...o.colors.slice(1,-1).reverse()]:o.colors,s=this.currentColor(e);for(let a=0;o.loops==null||a<o.loops;a++)for(let c of i)o.fadeMs>0?await this.fade(e,n,s,c,o.fadeMs,"ease",r):await this.drive(e,n,"color","setColor",{hue:$t(c.hue),saturation:$t(c.saturation)},r),s=c,await this.wait(o.holdMs,r)}async candle(e,n,o,r){o.warmthKelvin!=null&&await this.drive(e,n,"colorTemperature","setColorTemperature",{kelvin:o.warmthKelvin},r),await this.drive(e,n,"power","turnOn",{},r);let i=o.durationMs==null?1/0:this.now()+o.durationMs,s=qc(o.intensity*.4,6,40);for(;this.now()<i;){let a=qc($t(o.intensity+(this.random()-.5)*2*s),1,100);await this.drive(e,n,"brightness","setBrightness",{level:a},r),await this.wait(80+this.random()*120,r)}}async rainbow(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r),await this.drive(e,n,"brightness","setBrightness",{level:o.brightness},r);let i=qc($t(o.cycleMs/150),6,36),s=o.cycleMs/i;for(let a=0;o.loops==null||a<o.loops;a++)for(let c=0;c<i;c++)await this.drive(e,n,"color","setColor",{hue:$t(360*c/i),saturation:o.saturation},r),await this.wait(s,r)}async siren(e,n,o,r){await this.drive(e,n,"power","turnOn",{},r);let i=Math.max(this.minStepMs,Math.round(1e3/(o.hz*2))),s=o.durationMs==null?1/0:Math.max(1,Math.ceil(o.durationMs/i));for(let a=0;a<s;a++){let c=a%2===0?o.colorA:o.colorB;await this.drive(e,n,"color","setColor",{hue:c.hue,saturation:c.saturation},r),await this.wait(i,r)}}};var Hf=class t{constructor(e){this.deps=e}deps;active=new Map;static interpolateHue(e,n){let o=[...e].sort((r,i)=>r.at-i.at);if(n<=o[0].at)return o[0].color;if(n>=o[o.length-1].at)return o[o.length-1].color;for(let r=0;r<o.length-1;r++){let i=o[r],s=o[r+1];if(n>=i.at&&n<=s.at){let a=(n-i.at)/(s.at-i.at||1);return{hue:i.color.hue+(s.color.hue-i.color.hue)*a,saturation:i.color.saturation+(s.color.saturation-i.color.saturation)*a}}}return o[o.length-1].color}register(e,n,o){let r=this.active.get(e)??[];r.some(i=>i.deviceId===n)||r.push({deviceId:n,spec:o}),this.active.set(e,r)}unregister(e,n){if(!n){this.active.delete(e);return}let o=(this.active.get(e)??[]).filter(r=>r.deviceId!==n);o.length?this.active.set(e,o):this.active.delete(e)}async onReading(e){let n=this.active.get(e.sessionId);if(n)for(let o of n){let r=o.spec.source==="context"?e.context?.pct:o.spec.source==="usage"?e.usage?.pct:e.cost;if(typeof r!="number")continue;let{hue:i,saturation:s}=t.interpolateHue(o.spec.stops,r),a=Math.round(i);o.lastHue!==a&&(o.lastHue=a,await this.deps.invoke({deviceId:o.deviceId,capability:"color",command:"setColor",params:{hue:a,saturation:Math.round(s)},consumer:"rules"}))}}};var c0=require("node:crypto");var l0=class{slots=new Map;index(e,n){let o=this.slots.get(e)??new Map;this.slots.set(e,o);let r=o.get(n);if(r!=null)return r;let i=new Set(o.values()),s=0;for(;i.has(s);)s+=1;return o.set(n,s),s}colorFor(e,n){return e.palette.length?e.palette[this.index(e.id,n)%e.palette.length]??null:null}free(e){for(let n of this.slots.values())n.delete(e)}},Kf=class{constructor(e){this.deps=e}deps;layers=new Map;winner=new Map;dedicated=new Map;focusedSessionId=null;settings={};profilesById=new Map;bindings={};codexBindings={};palette=new l0;locks=new Map;setConfig(e,n,o,r){this.settings=e??{},this.profilesById=new Map(n.map(i=>[i.id,i])),this.bindings=o??{},this.codexBindings=r??{}}setFocusedSession(e){if(this.focusedSessionId!==e){this.focusedSessionId=e;for(let n of this.layers.keys())this.policyOf(n).arbitration.subMode==="focused"&&this.enqueue(n,()=>this.reapply(n))}}submit(e){this.enqueue(e.deviceId,()=>this.doSubmit(e))}onSessionEnded(e){for(let n of[...this.layers.keys()])this.enqueue(n,async()=>{let o=this.layers.get(n);!o||!o.has(e)||(o.delete(e),this.dedicated.get(n)===e&&this.dedicated.delete(n),o.size===0?(this.layers.delete(n),this.winner.delete(n)):this.winner.get(n)===e&&(this.winner.delete(n),await this.reapply(n)))});this.palette.free(e)}enqueue(e,n){let r=(this.locks.get(e)??Promise.resolve()).then(()=>n()).catch(i=>this.deps.log?.(`arbiter ${e}: ${String(i)}`));this.locks.set(e,r)}policyOf(e){return this.settings[e]??{name:null,instanceNames:{},favouriteScenes:[],groups:[],main:{hs:null,brightness:null,kelvin:null},arbitration:{mode:"shared",subMode:"mostRecent",priorityBy:"session",priority:[],dedicatedTo:null},participate:!0,wakeIfOff:!0,allowSecurity:!1}}sessionColor(e,n){let o=this.profilesById.get(e);return o?this.palette.colorFor(o,n):null}profileFor(e){return e.repo?(e.agent==="codex"?this.codexBindings:this.bindings)[e.repo]:void 0}async doSubmit(e){let n=this.policyOf(e.deviceId);if(!n.participate)return;let o=this.profileFor(e);if(!o)return;let r=n.arbitration,i=n.main,s=this.sessionColor(o,e.sessionId);if(r.mode==="dedicated"){let u=this.dedicated.get(e.deviceId);if(u==null&&(u=r.dedicatedTo??e.sessionId,this.dedicated.set(e.deviceId,u)),u!==e.sessionId)return}let a=this.layers.get(e.deviceId)??new Map;this.layers.set(e.deviceId,a);let c=a.get(e.sessionId)??{sessionId:e.sessionId,profileId:o,repo:e.repo??"",restingLook:null,lastChangeMs:0};e.look&&(!e.effect||e.hold)&&(c.restingLook=kb(e.look,i,s)),c.lastChangeMs=this.now(),a.set(e.sessionId,c);let l=this.resolve(e.deviceId);if(l!=null&&(this.winner.set(e.deviceId,l),!(l!==e.sessionId&&!e.effect)))if(e.effect){let u=e.returnTo??"session",d=u==="main"||u==="session"?this.lookForTarget(u,i,s):null,f=e.effect,m={type:"device_command",requestId:(0,c0.randomUUID)(),deviceId:e.deviceId,...e.instance?{instance:e.instance}:{},capability:"effect",command:"startEffect",params:{spec:f},consumer:"rules",sessionId:e.sessionId,ruleId:`prof:${o}`};this.deps.runEffect?.(m,{returnTo:u,returnLook:d})}else await this.drive(e.deviceId,c.restingLook,e.sessionId,e.instance,o)}async reapply(e){let n=this.resolve(e);if(n==null)return;this.winner.set(e,n);let o=this.layers.get(e)?.get(n);o&&await this.drive(e,o.restingLook,n,void 0,o.profileId)}resolve(e){let n=this.layers.get(e);if(!n||n.size===0)return null;let o=this.policyOf(e).arbitration,r=[...n.values()];if(o.mode==="dedicated"){let i=this.dedicated.get(e);return i&&n.has(i)?i:null}if(o.subMode==="focused"){let i=r.find(s=>s.sessionId===this.focusedSessionId);return i?i.sessionId:this.mostRecent(r)}if(o.subMode==="priority"){let i=c=>o.priorityBy==="profile"?c.profileId:o.priorityBy==="repo"?c.repo:c.sessionId,s=c=>{let l=o.priority.indexOf(i(c));return l===-1?Number.MAX_SAFE_INTEGER:l},a=null;for(let c of r)(a==null||s(c)<s(a)||s(c)===s(a)&&c.lastChangeMs>a.lastChangeMs)&&(a=c);return a?.sessionId??null}return this.mostRecent(r)}mostRecent(e){let n=null;for(let o of e)(n==null||o.lastChangeMs>n.lastChangeMs)&&(n=o);return n?.sessionId??null}lookForTarget(e,n,o){return kb({color:{kind:"token",token:e}},n,o)}async drive(e,n,o,r,i){if(n)for(let s of Ju(n))await this.deps.invoke({type:"device_command",requestId:(0,c0.randomUUID)(),deviceId:e,...r?{instance:r}:{},capability:s.capability,command:s.command,params:s.params,consumer:"rules",sessionId:o,...i?{ruleId:`prof:${i}`}:{}}).catch(a=>this.deps.log?.(`arbiter drive ${e} ${s.command}: ${String(a)}`))}now(){return this.deps.now?.()??Date.now()}};var gZ=1e3;function _N(t){let e=new Nf,n=t.nodeId??process.env.BRIDGE_NODE_ID??"node-local",o=sL({relayUrl:t.relayUrl,readNodeToken:t.readNodeToken}),r=t.classifySessionAdoption??(()=>"adopt"),i=new Set,s=new Set,a=new WeakSet,c=(v,j)=>{a.has(v)||(a.add(v),console.error(`[hub] dropping ${j} from a channel socket without an adopted registration (AS-T8b; sessions never cross accounts)`))},l=v=>{let j=r(v.claudeSessionId);if(j==="adopt")return!0;let ve=v.claudeSessionId??v.sessionId??"(no id)";return s.has(ve)||(s.add(ve),console.error(`[hub] dropping session-state/context signal for ${ve} \u2014 account-scope verdict "${j}" (AS-T8b; sessions never cross accounts)`)),!1},u=new Map,d=v=>{let j=u.get(v);if(!j){let ve=new Map;j={read:async Ee=>ve.get(Ee)??null,write:async(Ee,Fe)=>{Fe===""?ve.delete(Ee):ve.set(Ee,Fe)},delete:async Ee=>{ve.delete(Ee)}},u.set(v,j)}return j},f=t.localSecretsFactory??d,m=null,g=!1,h=()=>t.relaySend({type:"sessions.update",sessions:e.list()}),y=EL(v=>t.relaySend(v)),b=()=>t.relaySend({type:"devices.update",doc:rN(C.graph)}),w=()=>e.broadcast(JSON.stringify({type:"devices.update",doc:C.graph})),x=()=>{if(!g||m)return;let v=setTimeout(()=>{m=null,b()},gZ);v.unref(),m=v},I,E,C=t.devices??new Mf({nodeId:n,makeContext:v=>({localSecrets:f(v),cloudTokens:o,log:j=>console.error(`[devices] ${j}`)}),onGraphChange:()=>{x(),w()},onEdgeEvent:v=>t.relaySend(v),snapshot:t.persistDevices,onActuate:(v,j)=>I?.noteActuation(v,j),effect:v=>E?.handle(v)??Promise.resolve({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:"Effects aren't ready yet."}),...t.readEntitlement?{readEntitlement:t.readEntitlement}:{},...t.isPaired?{isPaired:t.isPaired}:{}}),F=new Hf({invoke:v=>{C.invoke({type:"device_command",requestId:`${v.deviceId}:meter:${Date.now()}`,deviceId:v.deviceId,capability:v.capability,command:v.command,params:v.params,consumer:v.consumer})},log:v=>console.error(`[meter] ${v}`)}),U=new zf({registry:C,meterRunner:F,log:v=>console.error(`[effects] ${v}`)});E=U;let W=new Bf({registry:C,...t.revertStore?{store:t.revertStore}:{},...t.now?{now:t.now}:{},cancelEffects:()=>U.cancelAll(),resumeEffects:()=>U.resume(),log:v=>console.error(`[revert] ${v}`)});I=W;let N=v=>C.invoke(v).then(j=>(t.relaySend({type:"device_audit",requestId:v.requestId,consumer:v.consumer,deviceId:v.deviceId,...v.ruleId?{ruleId:v.ruleId}:{},capability:v.capability,command:v.command,params:v.params,ok:j.ok,confirmRequired:C.securityOf(v.deviceId,v.capability,v.instance,v.command),error:j.error,ts:Date.now()}),j)),M=new Kf({invoke:N,runEffect:(v,j)=>{U.handle(v,j)},...t.now?{now:t.now}:{},log:v=>console.error(`[arbiter] ${v}`)}),ue,de=new Of({emit:v=>ue?.({sessionId:v.sessionId,state:v.state,event:"context",ts:v.ts,...v.cwd?{cwd:v.cwd}:{},...v.pct!==void 0?{pct:v.pct}:{},...v.window?{window:v.window}:{},...v.model?{modelName:v.model}:{},...v.review?{review:v.review}:{},...v.cost!==void 0?{cost:v.cost}:{},...v.agent?{agent:v.agent}:{}}),...t.now?{now:t.now}:{},log:v=>console.error(`[context] ${v}`)}),K=new Lf({emit:v=>ue?.({sessionId:v.sessionId,state:v.state,event:"duration",ts:v.ts,...v.cwd?{cwd:v.cwd}:{},...v.minutes!==void 0?{minutes:v.minutes}:{},...v.agent?{agent:v.agent}:{}}),schedule:(v,j)=>setTimeout(j,v).unref(),cancel:v=>clearTimeout(v),...t.now?{now:t.now}:{},log:v=>console.error(`[duration] ${v}`)}),L=new $f({readGraph:()=>C.graph,...t.voice!==void 0?{voice:t.voice}:{},invoke:N,submitIntent:v=>M.submit(v),dispatchSession:v=>{let j=v.sessionId;j&&e.send(j,JSON.stringify(v))},notify:v=>{v.sessionId&&v.event?t.relaySend({type:"notification",sessionId:v.sessionId,event:v.event,...v.repo?{repo:v.repo}:{},...v.title?{title:v.title}:{},...v.body?{body:v.body}:{}}):console.error(`[rules] notify: ${v.title} \u2014 ${v.body}`)},isSecuritySensitive:(v,j,ve,Ee)=>C.securityOf(v,j,ve,Ee),...t.now?{now:t.now}:{},log:v=>console.error(`[rules] ${v}`)});L.start();let ye=new Ff({registry:C,now:t.now,store:t.localStore,roster:t.localRoster,probes:t.localProbes,audit:v=>t.relaySend(v),loadConfig:t.loadLocalConfig,saveConfig:t.saveLocalConfig,passive:t.localPassive,secrets:f,...t.localTuyaKeystore?{tuyaKeystore:t.localTuyaKeystore}:{},...t.localMerossKeystore?{merossKeystore:t.localMerossKeystore}:{},...t.localEwelinkKeystore?{ewelinkKeystore:t.localEwelinkKeystore}:{}}),ot={registry:e,sendToChannel:(v,j)=>e.send(v,JSON.stringify(j)),sendResult:v=>t.relaySend(v)},cr=new jf({...t.codexIdleCloseMs!==void 0?{timeoutMs:t.codexIdleCloseMs}:{},onIdle:v=>ue?.({sessionId:v.sessionId,...v.claudeSessionId!==void 0?{claudeSessionId:v.claudeSessionId}:{},state:"ended",event:"codex:idle-close",cwd:v.cwd,agent:"codex"})}),fn=v=>{let j=v.sessionId??v.claudeSessionId;if(!j)return;let Ee=e.setState(j,v.state)??v.cwd;if(Ee===void 0)return;cr.note({sessionId:j,cwd:Ee,state:v.state,...v.claudeSessionId!==void 0?{claudeSessionId:v.claudeSessionId}:{},...v.agent?{agent:v.agent}:{}});let Fe=()=>L.handleSessionState({sessionId:j,cwd:Ee,state:v.state,...v.ts!==void 0?{ts:v.ts}:{},...v.pct!==void 0?{pct:v.pct}:{},...v.window?{window:v.window}:{},...v.modelName?{model:v.modelName}:{},...v.review?{review:v.review}:{},...v.cost!==void 0?{cost:v.cost}:{},...v.minutes!==void 0?{minutes:v.minutes}:{},...v.agent?{agent:v.agent}:{}}),Ro=v.claudeSessionId??j,Ao=W.status(),Vf=v.state==="started"||v.state==="resumed"||v.agent==="codex"&&v.state!=="ended"&&!Ao.active;v.state==="ended"&&M.onSessionEnded(j),t.revertOnSessionEnd!==!1&&Vf&&W.activeOwner!=="app"&&!(Ao.active&&Ao.sessionId===Ro)?(async()=>(Ao.active&&await W.stop(Ao.sessionId).catch(()=>{}),await W.activate({sessionId:Ro,revertOnStop:!0,deadman:!1,owner:"hook"}).catch(()=>{}),Fe()))():t.revertOnSessionEnd!==!1&&v.state==="ended"&&W.activeOwner==="hook"?(Fe(),W.stop(Ro).catch(()=>{})):Fe(),y.note({sessionId:j,state:v.state,event:v.event,ts:v.ts??Date.now()}),de.handleSignal({sessionId:j,state:v.state,cwd:Ee,...v.context?{context:v.context}:{},...v.mode?{mode:v.mode}:{},...v.model?{model:v.model}:{},...v.agent?{agent:v.agent}:{}}),K.handleSignal({sessionId:j,state:v.state,cwd:Ee,...v.agent?{agent:v.agent}:{}}),v.context&&F.onReading({sessionId:j,context:{pct:v.context.pct}})};return ue=fn,{registry:e,devices:C,rules:L,arbiter:M,localDiscovery:ye,revertSession:W,sessionIdle:cr,effects:U,sessionDuration:K,meterRunner:F,stateDigest:y,registerChannel(v,j,ve,Ee){let Fe=r(Ee);return Fe!=="adopt"?(i.has(v.id)||(i.add(v.id),console.error(`[hub] refusing to register session ${v.id} \u2014 account-scope verdict "${Fe}" (AS-T8a; sessions never cross accounts)`)),Fe):(e.register(v,j,ve),h(),Fe)},disconnectChannel(v){e.remove(v),h()},sessionContext:de,ingestSessionState(v){l(v)&&fn(v)},ingestSessionContext(v){if(!l(v))return;let j=v.sessionId??v.claudeSessionId;j&&(de.ingest({sessionId:j,...v.cwd?{cwd:v.cwd}:{},...v.context?{context:v.context}:{},...v.rateLimits?{rateLimits:v.rateLimits}:{},...v.mode?{mode:v.mode}:{},...v.model?{model:v.model}:{},...v.modelName?{modelName:v.modelName}:{},...v.review?{review:v.review}:{},...typeof v.cost=="number"?{cost:v.cost}:{},...v.agent?{agent:v.agent}:{}}),F.onReading({sessionId:j,...v.context?{context:{pct:v.context.pct}}:{},...v.rateLimits?{usage:{pct:Math.max(v.rateLimits.fiveHour?.usedPct??-1,v.rateLimits.sevenDay?.usedPct??-1)}}:{},...typeof v.cost=="number"?{cost:v.cost}:{}}))},syncToRelay(){h(),g&&(m&&(clearTimeout(m),m=null),b())},markDevicesReady(){g||(g=!0,m&&(clearTimeout(m),m=null),b())},handleFromRelay(v){switch(v.type){case"command":ZL(v,ot);break;case"prompt":e.send(v.sessionId,JSON.stringify(v))||t.relaySend({type:"command_result",requestId:v.requestId,id:"Prompt",error:"No session attached, or that session is offline.",ts:Date.now()});break;case"permission_verdict":e.send(v.sessionId,JSON.stringify(v))||(console.error(`[hub] permission_verdict undeliverable for session ${v.sessionId}`),t.relaySend({type:"command_result",requestId:v.requestId,id:"Permission",sessionId:v.sessionId,error:"Couldn't deliver the approval \u2014 the session may be offline.",ts:Date.now()}));break;case"device_command":{let j=Xx(v,{isSecuritySensitive:(ve,Ee,Fe,Ro)=>C.securityOf(ve,Ee,Fe,Ro),requireConfirm:t.requireDeviceConfirm===!0});if(j.warn&&console.error(`[hub] ${j.warn}`),!j.allowed){t.relaySend({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:j.reason});break}C.invoke(v).then(ve=>t.relaySend(ve)).catch(ve=>t.relaySend({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:Zc(String(ve))}));break}case"device_query":t.relaySend(C.query(v));break;case"device_source_event":C.applyExternalEvent(v.provider,v.providerAccountId,v);break;case"entitlement":t.onEntitlement?.(v);break;case"device_config":t.onDeviceConfig?.(v);break;default:break}},handleFromChannel(v,j,ve){switch(v.type){case"reply":case"permission_request":if(ve&&ve.sessionId===null){c(ve,`a ${v.type} frame`);break}v.ts??=Date.now(),t.relaySend(v);break;case"device_command":{if(ve?.refused){c(ve,"a device_command frame"),j?.(JSON.stringify({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:"This session isn't signed in to the account this bridge serves."}));break}let Ee=Xx(v,{isSecuritySensitive:(Fe,Ro,Ao,Vf)=>C.securityOf(Fe,Ro,Ao,Vf),requireConfirm:t.requireDeviceConfirm===!0});if(Ee.warn&&console.error(`[hub] ${Ee.warn}`),!Ee.allowed){j?.(JSON.stringify({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:Ee.reason})),t.relaySend({type:"device_audit",requestId:v.requestId,consumer:v.consumer,deviceId:v.deviceId,capability:v.capability,command:v.command,params:v.params,ok:!1,confirmRequired:!0,error:Ee.reason,ts:Date.now()});break}C.invoke(v).then(Fe=>{j?.(JSON.stringify(Fe)),t.relaySend({type:"device_audit",requestId:v.requestId,consumer:v.consumer,deviceId:v.deviceId,capability:v.capability,command:v.command,params:v.params,ok:Fe.ok,confirmRequired:C.securityOf(v.deviceId,v.capability,v.instance,v.command),error:Fe.error,ts:Date.now()})}).catch(Fe=>j?.(JSON.stringify({type:"device_result",requestId:v.requestId,deviceId:v.deviceId,ok:!1,error:Zc(String(Fe))})));break}case"device_query":if(ve?.refused){c(ve,"a device_query frame"),j?.(JSON.stringify({type:"device_result",requestId:v.requestId,ok:!1,error:"This session isn't signed in to the account this bridge serves."}));break}j?.(JSON.stringify(C.query(v)));break;default:break}}}}hd();function EN(t){let e=t.replace(/^http/,"ws").replace(/\/+$/,"");return e.endsWith("/hub")?e:`${e}/hub`}var hZ=1012,yZ=500,vZ=4402,bZ=15*6e4,wZ=4426,kZ=15*6e4,IN=1e3,xZ=3e4,TN=200,SZ=.2,_Z=["disconnect"];function IZ(t,e=Math.random){let n=(e()*2-1)*SZ*t;return Math.max(1,Math.round(t+n))}var TZ={createSocket:(t,e)=>new _r.default(t,e),setTimer:(t,e)=>setTimeout(t,e),clearTimer:t=>clearTimeout(t),setHeartbeat:(t,e)=>setInterval(t,e),clearHeartbeat:t=>clearInterval(t),rand:Math.random};function CN(t,e=TZ){let n=null,o=!1,r=IN,i=0,s=null,a=[],c=()=>{for(;a.length>0&&n&&n.readyState===_r.default.OPEN;)n.send(a.shift())},l=()=>{if(o)return;let u=t.getToken(),d={...u?{authorization:`Bearer ${u}`}:{},...t.clientVersion?{"x-bridge-client-version":t.clientVersion}:{},"x-bridge-caps":_Z.join(",")},f=e.createSocket(t.url,Object.keys(d).length>0?{headers:d}:void 0);n=f;let m=!0,g=null,h=null;f.on("open",()=>{r=IN,i=0,c(),t.onStatus?.(!0),t.onOpen?.(),m=!0,g=e.setHeartbeat(()=>{if(!m){f.terminate();return}m=!1;try{f.ping()}catch{}},3e4)}),f.on("pong",()=>{m=!0}),f.on("message",y=>{try{let b=Qu(y.toString());if(b.type==="disconnect"){h=b.code,console.error(`[hub] relay announced disconnect ${b.code}: ${b.reason}`);return}t.onMessage(b)}catch(b){console.error("[hub] bad relay frame:",b)}}),f.on("error",y=>console.error(`[hub] relay ws error (${t.url}):`,y)),f.on("close",y=>{let b=h??y;if(g&&(e.clearHeartbeat(g),g=null),n===f&&(n=null),t.onStatus?.(!1,b),o)return;let w=b===hZ;w&&(i+=1);let x=w&&i===1,I=b===vZ,E=b===wZ;I&&console.error("[hub] relay refused service: subscription inactive (4402) \u2014 redialing in 15 min"),E&&console.error("[hub] relay refused service: app update required (4426) \u2014 redialing in 15 min");let F=IZ(I?bZ:E?kZ:x?yZ:r,e.rand);!x&&!I&&!E&&(r=Math.min(r*2,xZ)),s=e.setTimer(l,F)})};return l(),{send:u=>{let d=JSON.stringify(u);if(n&&n.readyState===_r.default.OPEN){n.send(d);return}a.length>=TN&&(a.shift(),console.error(`[hub] relay outbound buffer full (${TN}) \u2014 dropping oldest frame`)),a.push(d)},close:()=>{o=!0,s&&e.clearTimer(s),n?.close()}}}var EZ={setTimer:(t,e)=>{let n=setTimeout(t,e);return n.unref?.(),n},clearTimer:t=>clearTimeout(t)},CZ=3e4;function RN(t,e=CZ,n=EZ){let o=null;return{onConnect(){o&&n.clearTimer(o),o=n.setTimer(()=>{o=null,t()},e)},onClose(){o&&(n.clearTimer(o),o=null)}}}var PN=require("node:crypto");function AN(t){return t==="app"||t==="daemon"}var Gf=class{holders=new Map;timer=null;firedEmpty=!1;emptyAt=null;onEmpty;now;isAlive;beatTimeoutMs;graceMs;tickMs;newId;persist;constructor(e){this.onEmpty=e.onEmpty,this.now=e.now??Date.now,this.isAlive=e.isAlive??V0,this.beatTimeoutMs=e.beatTimeoutMs??1e4,this.graceMs=e.graceMs??0,this.tickMs=e.tickMs??3e3,this.newId=e.newId??PN.randomUUID,this.persist=e.persist}seed(e){for(let n of e)this.isAlive(n.pid)&&this.holders.set(n.holderId,{...n,beats:n.beats??AN(n.kind),connected:!1});this.save()}hold(e){let n=this.now();this.emptyAt=null;for(let r of this.holders.values())if(r.kind===e.kind&&r.pid===e.pid)return r.lastBeat=n,e.connected&&(r.connected=!0),this.save(),{holderId:r.holderId};let o=this.newId();return this.holders.set(o,{holderId:o,kind:e.kind,pid:e.pid,beats:AN(e.kind),...e.connected?{connected:!0}:{},since:n,lastBeat:n}),this.save(),{holderId:o}}beat(e){let n=this.holders.get(e);return n?(n.lastBeat=this.now(),!0):!1}release(e){this.holders.delete(e)&&(this.save(),this.checkEmpty())}tick(){let e=this.now(),n=!1;for(let[o,r]of this.holders){let i=!this.isAlive(r.pid),s=(r.beats||r.connected===!1)&&e-r.lastBeat>this.beatTimeoutMs;(i||s)&&(this.holders.delete(o),n=!0)}n&&this.save(),this.checkEmpty()}list(){return[...this.holders.values()]}size(){return this.holders.size}has(e){return this.holders.has(e)}start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.tickMs),this.timer.unref?.())}stop(){this.timer&&clearInterval(this.timer),this.timer=null}checkEmpty(){if(!this.firedEmpty){if(this.holders.size>0){this.emptyAt=null;return}this.emptyAt===null&&(this.emptyAt=this.now()),this.now()-this.emptyAt>=this.graceMs&&(this.firedEmpty=!0,this.onEmpty())}}save(){this.persist?.(this.list())}};var RZ=15*6e4,AZ=W0,wi=process.env.BRIDGE_RELAY_URL,Co=wi&&wi.replace(/^ws/,"http"),FN=process.env.BRIDGE_HUB_HOLDER,DN=Number(process.env.BRIDGE_HUB_HOLDER_PID)||0,BN=cl(FN);H0();var We=pm();console.error(`[hub] account scope: ${We?We.sub:"none"}`);var le=We?ol(We):null,Vc=()=>{},u0=YE({envPath:process.env.BRIDGE_RELAY_TOKEN_FILE,scope:We}),PZ=()=>{if(!u0)return"";try{return(0,Hs.readFileSync)(u0,"utf8").trim()}catch{return""}},$N=!1,Hr=()=>JE(PZ(),We?We.sub:null,Ot,()=>{$N||($N=!0,console.error(`[hub] account switched underneath a pinned hub (pinned=${We?.sub}, incoming token sub differs) \u2014 shutting down (a daemon front-end respawns pinned to the new account; the app front-end picks it up on the next Start)`)),Vc("account-switched")}),jN=(0,MN.randomBytes)(32).toString("hex"),d0=le?le.hubTokenFile:null,ON=process.env.BRIDGE_HUB_TOKEN_FILE??d0??sl,DZ=t=>{let e=(0,UN.dirname)(t);(0,Hs.mkdirSync)(e,{recursive:!0,mode:448}),(0,Hs.chmodSync)(e,448),pe(t,jN,384)};try{DZ(ON)}catch(t){console.error(`[hub] FATAL: cannot write hub token file ${ON}:`,t),process.exit(1)}var LN=new Map;function Wf(t){let e=LN.get(t);return e||(e=new Map,LN.set(t,e)),e}function zr(t,e){return le?sm(le,t,e).read():Wf(t).get(e)??null}function Zf(t,e,n){if(le){sm(le,t,e).write(n);return}n===""?Wf(t).delete(e):Wf(t).set(e,n)}function $Z(t){if(le)return dL(le,t);let e=Wf(t);return{async read(n){return e.get(n)??null},async write(n,o){o===""?e.delete(n):e.set(n,o)},async delete(n){e.delete(n)}}}var zN=()=>{},HN=()=>{},KN=()=>{},GN=()=>{},WN=()=>{},OZ={load:()=>{if(!le)return null;let t=X(le.localDiscoveredFile);if(!t)return null;try{let e=dT.safeParse(JSON.parse(t));return e.success?e.data:null}catch{return null}},save:t=>{le&&pe(le.localDiscoveredFile,JSON.stringify(t))}},p0=le?$R(le):qd(),ZN=x0({isDevBuild:rm()===null}),re=_N({relaySend:t=>zN(t),nodeId:N0(),relayUrl:Co,readNodeToken:Hr,voice:ZN,requireDeviceConfirm:process.env.BRIDGE_REQUIRE_DEVICE_CONFIRM!=="0",localStore:OZ,localRoster:p0,localSecretsFactory:$Z,localProbes:{kasa:EP(),"kasa-klap":HP(),wiz:hO(),lifx:oD(),shelly:_D(),govee:lA(),tapo:JD(),yeelight:tL(),tuya:w$(void 0,{keystore:{read:async()=>Cn(zr("tuya","keystore")),write:async t=>Zf("tuya","keystore",JSON.stringify(t))}}),nanoleaf:sO({read:()=>pf(zr("nanoleaf","keystore")),write:t=>Zf("nanoleaf","keystore",JSON.stringify(t))}),meross:e1(()=>$c(zr("meross","keystore"))?.key??null),ewelink:U$(()=>Pc(zr("ewelink","keystore"))),wled:bO(),elgato:PO(),roku:FO(),esphome:Q1(()=>Ms(zr("esphome","keystore")))},localMerossKeystore:()=>$c(zr("meross","keystore")),localEwelinkKeystore:()=>Pc(zr("ewelink","keystore")),localTuyaKeystore:()=>Cn(zr("tuya","keystore")),...le?{loadLocalConfig:()=>FR(le.localConfigFile),saveLocalConfig:t=>BR(t,le.localConfigFile)}:{},localPassive:t=>Nw(t),onDeviceConfig:t=>FZ(t),onEntitlement:t=>{if(le)try{zx({plan:t.plan,...t.planStatus!==void 0?{planStatus:t.planStatus}:{},...t.serviceOk!==void 0?{serviceOk:t.serviceOk}:{},capture:t.capture,policyVersion:t.policyVersion,fetchedAt:Date.now()},le.entitlementFile)}catch(e){console.error(`[hub] entitlement file write failed: ${String(e)}`)}},...le?{readEntitlement:()=>Hx(le.entitlementFile)}:{},isPaired:()=>Hr()!=="",...le?{revertStore:xN(le.revertSessionFile)}:{},revertOnSessionEnd:process.env.BRIDGE_AUTO_REVERT!=="0",classifySessionAdoption:t=>vd(t?eC(Zs,t):void 0,We?We.sub:null)}),qN=()=>{try{let t=new Set(re.registry.list().map(n=>n.id)),e=vL(Zs,{isLive:n=>!!(n.sessionId&&t.has(n.sessionId))});e.swept>0&&console.error(`[hub] swept ${e.swept} stale session handshake(s), ${e.kept} kept`)}catch(t){console.error(`[hub] session-handshake sweep failed (non-fatal): ${t.message}`)}};qN();var LZ=setInterval(qN,hL);LZ.unref?.();var VN=new Pf,NZ=12e3,Jc=[];process.env.BRIDGE_DEVICES_MOCK&&Jc.push(re.devices.addAdapter("mock","mock-1").catch(t=>console.error("[hub] mock adapter failed:",t)));var JN=(t,e)=>re.devices.addAdapter("homeassistant",t,e).catch(n=>console.error(`[hub] home-assistant ${t} failed:`,n));if(process.env.BRIDGE_HA_URL){let t=process.env.BRIDGE_HA_URL,e=qs("homeassistant",t);if(process.env.BRIDGE_HA_TOKEN)try{Zf("homeassistant",e,process.env.BRIDGE_HA_TOKEN)}catch(o){console.error("[hub] could not store BRIDGE_HA_TOKEN:",o)}let n=process.env.BRIDGE_HA_UNITS;Jc.push(JN(e,{baseUrl:t,...n==="imperial"||n==="metric"?{unitSystem:n}:{}}))}var YN=(t,e)=>re.devices.addAdapter("hue",t,e).catch(n=>console.error(`[hub] hue ${t} failed:`,n));if(process.env.BRIDGE_HUE_HOST){let t=process.env.BRIDGE_HUE_HOST,e=(process.env.BRIDGE_HUE_BRIDGEID??t).toLowerCase(),n=qs("hue",e);if(process.env.BRIDGE_HUE_KEY)try{Zf("hue",n,JSON.stringify({appkey:process.env.BRIDGE_HUE_KEY}))}catch(o){console.error("[hub] could not store BRIDGE_HUE_KEY:",o)}Jc.push(YN(n,{host:t,bridgeId:e}))}function XN(){return iL({paths:le,roster:p0,addHomeAssistant:JN,addHue:YN,addRosterAdapter:(t,e,n)=>re.devices.addAdapter(t,e,n),addMqtt:(t,e)=>re.devices.addAdapter("mqtt",t,e),loadCloudAccounts:()=>tA(zr),addCloudAdapter:(t,e,n)=>re.devices.addAdapter(t,e,n),onIpChange:(t,e,n)=>tc(p0,t,e,n),log:t=>console.error(t)})}Jc.push(XN());Promise.allSettled(Jc).then(()=>re.markDevicesReady());setTimeout(()=>re.markDevicesReady(),NZ).unref();var MZ=(t,e)=>{re.devices.addAdapter("smartthings",t,e).catch(n=>console.error(`[hub] smartthings ${t} failed:`,n))},UZ=()=>uL({paths:le,relayUrl:Co,readNodeToken:Hr,addSmartThings:MZ,log:t=>console.error(t)}),qf=null,QN=(t,e)=>{{try{let{rules:n,notifyPolicy:o,thresholds:r,modelMatch:i}=RT(t,void 0,{voice:ZN});re.rules.setRules(n),re.rules.setNotifyPolicy(o),re.sessionContext.setThresholds(r),re.sessionContext.setModelMatch(i),re.sessionDuration.setThresholds(r);let s=Eb.safeParse({profiles:t?.profiles,bindings:t?.bindings,codexBindings:t?.codexBindings}),a=AT.safeParse(t?.deviceSettings);re.arbiter.setConfig(a.success?a.data:{},s.success?s.data.profiles:[],s.success?s.data.bindings:{},s.success?s.data.codexBindings:{})}catch{re.rules.loadRules(t)}e||console.error(`[hub] rules loaded from device-config: ${re.rules.ruleCount} rule(s)`)}},FZ=t=>{Vx(qf,t.version)&&(qf=t.version,QN(t.config,!0))},f0=async(t=!1)=>{if(!wi)return;let e=Hr();if(e)try{let{status:n,json:o}=await gi({method:"GET",url:`${Co.replace(/\/+$/,"")}/device-config`,token:e});if(n!==200||!o||typeof o!="object")return;let r=o,i=typeof r.version=="number"?r.version:null;if(i!==null&&!Vx(qf,i))return;i!==null&&(qf=i),QN(r.config,t)}catch(n){t||console.error(`[hub] device-config rules load failed: ${String(n)}`)}};if(wi){let t=EN(wi),e=/^ws:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(t);!t.startsWith("wss://")&&!e&&(console.error(`[hub] FATAL: BRIDGE_RELAY_URL must be https:// (got ${wi}) \u2014 refusing to send the token over cleartext.`),process.exit(1));let n=!1,o=async()=>{if(n)return;n=!0,await cL({relayUrl:Co,readNodeToken:Hr,name:q0(),platform:process.platform})||(n=!1)},r=RN(()=>re.syncToRelay());KN=r.onClose;let i=CN({url:t,getToken:Hr,clientVersion:rm()??void 0,onOpen:()=>{console.error(`[hub] relay connected: ${t}`),re.syncToRelay(),r.onConnect(),UZ(),f0(),o()},onStatus:(l,u)=>{l||r.onClose();try{pe(Z0,JSON.stringify({connected:l,ts:Date.now(),paired:!!Gs(),...u!==void 0?{code:u}:{}}),384)}catch{}},onMessage:l=>re.handleFromRelay(l)});zN=i.send,HN=i.close,D0(Gs())&&(console.error("[hub] node-credential self-refresh enabled (sole refresher; machine paired)"),P0(Co,{log:l=>console.error(`[refresh] ${l}`)})),setInterval(()=>{f0(!0)},RZ).unref?.();let a=XE(We?We.sub:null),c=setInterval(()=>{let l=pm()?.sub??null;a(l)==="stop"&&(console.error(`[hub] scope drift detected (pinned=${We?We.sub:"none"}, now=${l??"none"}) \u2014 shutting down so the daemon respawns pinned to the new account`),Vc("account-switched"))},15e3);if(c.unref?.(),GN=()=>clearInterval(c),We&&le){let l=mL({relayUrl:Co,readNodeToken:Hr,file:le.entitlementFile});new Af({relayUrl:Co,readNodeToken:Hr,refreshEntitlement:()=>{l.refreshNow()},spoolDir:le.telemetrySpoolDir,secretDir:le.dir,readEntitlement:()=>Hx(le.entitlementFile),scopeSub:We.sub,extraTokenFiles:[u0,le.relayRefreshFile,...d0?[d0]:[]]}).start();let u=new Df({store:VN,relayUrl:Co,readNodeToken:Hr,onCaptureDisabled:()=>{l.refreshNow()}});u.flush(),setInterval(()=>{u.flush()},Wc).unref?.(),WN=()=>{u.flush()}}else console.error("[hub] no account scope pinned \u2014 entitlement polling and transcript capture stay off")}else console.error("[hub] BRIDGE_RELAY_URL not set \u2014 channel-server-only (M1 local mode).");var BZ=t=>{try{pe(al,JSON.stringify(t),384)}catch{}},jZ=()=>{let t=X(al);if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}},ki=new Gf({persist:BZ,graceMs:2500,onEmpty:BN?()=>Vc("holders-empty"):()=>{}});ki.seed(jZ());BN&&DN&&ki.hold({kind:FN,pid:DN});ki.start();var zZ={hold:t=>ki.hold(t),beat:t=>ki.beat(t),release:t=>ki.release(t),shutdown:()=>Vc("stop-requested")},m0=HE({port:AZ,token:jN,onRequest:WE(re.localDiscovery,re.revertSession,re.ingestSessionState,()=>{f0(!0)},zZ,XN,re.ingestSessionContext,()=>re.devices.graph,We?We.sub:null,t=>VN.record({codexThreadId:t.codexThreadId,bridgeSessionId:t.sessionId??null,cwd:t.cwd??null,gitBranch:t.gitBranch??null,inputTokens:t.inputTokens,cachedInputTokens:t.cachedInputTokens,outputTokens:t.outputTokens})),onRegister:(t,e,n,o)=>{let r=re.registerChannel(t,e,n,o);return r==="adopt"&&console.error(`[hub] channel registered: ${t.id} (${t.name})`),r==="adopt"},onMessage:(t,e,n)=>re.handleFromChannel(t,e,n),onDisconnect:t=>{re.disconnectChannel(t),console.error(`[hub] channel disconnected: ${t}`)}});console.error(`[hub] channel server listening on 127.0.0.1:${m0.port}`);qE({port:m0.port,sub:We?We.sub:null});var NN=!1,HZ=12e3;function g0(t){if(!NN){NN=!0,mm(t),console.error(`[hub] ${t} received \u2014 shutting down`),ki.stop(),GN(),WN(),KN(),re.stateDigest.dispose();try{HN()}catch{}it(al),VE(),it(cm),re.localDiscovery.dispose(),re.revertSession.dispose(),re.sessionIdle.dispose(),(async()=>{try{await Promise.race([re.revertSession.stop(),new Promise(e=>{setTimeout(e,HZ).unref?.()})])}catch(e){console.error(`[hub] shutdown revert failed: ${String(e)}`)}re.effects.dispose(),await re.devices.disposeAll().catch(()=>{}),m0.close(),process.exit(0)})()}}Vc=g0;process.on("SIGINT",()=>g0("SIGINT"));process.on("SIGTERM",()=>g0("SIGTERM"));