@kaeawc/auto-mobile 0.0.51 → 0.0.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.md.backup +1 -1
- package/dist/src/index.js +4 -4
- package/dist/src/index.js.map +1 -1
- package/package.json +2 -1
package/dist/src/index.js
CHANGED
|
@@ -16,7 +16,7 @@ and limitations under the License.
|
|
|
16
16
|
***************************************************************************** */var Xw$;(function($){(function(J){var X=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:Z(),Q=Y($);if(typeof X.Reflect<"u")Q=Y(X.Reflect,Q);if(J(Q,X),typeof X.Reflect>"u")X.Reflect=$;function Y(j,V){return function(K,z){if(Object.defineProperty(j,K,{configurable:!0,writable:!0,value:z}),V)V(K,z)}}function W(){try{return Function("return this;")()}catch(j){}}function G(){try{return(0,eval)("(function() { return this; })()")}catch(j){}}function Z(){return W()||G()}})(function(J,X){var Q=Object.prototype.hasOwnProperty,Y=typeof Symbol==="function",W=Y&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",G=Y&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",Z=typeof Object.create==="function",j={__proto__:[]}instanceof Array,V=!Z&&!j,K={create:Z?function(){return mj(Object.create(null))}:j?function(){return mj({__proto__:null})}:function(){return mj({})},has:V?function(j$,B$){return Q.call(j$,B$)}:function(j$,B$){return B$ in j$},get:V?function(j$,B$){return Q.call(j$,B$)?j$[B$]:void 0}:function(j$,B$){return j$[B$]}},z=Object.getPrototypeOf(Function),L=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:uj(),H=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:LU(),O=typeof WeakMap==="function"?WeakMap:CB(),B=Y?Symbol.for("@reflect-metadata:registry"):void 0,F=HY(),A=OY(F);function _(j$,B$,C$,J0){if(!U0(C$)){if(!E4(j$))throw TypeError();if(!R0(B$))throw TypeError();if(!R0(J0)&&!U0(J0)&&!H1(J0))throw TypeError();if(H1(J0))J0=void 0;return C$=D1(C$),Y$(j$,B$,C$,J0)}else{if(!E4(j$))throw TypeError();if(!T1(B$))throw TypeError();return t(j$,B$)}}J("decorate",_);function q(j$,B$){function C$(J0,$1){if(!R0(J0))throw TypeError();if(!U0($1)&&!j1($1))throw TypeError();k$(j$,B$,J0,$1)}return C$}J("metadata",q);function w(j$,B$,C$,J0){if(!R0(C$))throw TypeError();if(!U0(J0))J0=D1(J0);return k$(j$,B$,C$,J0)}J("defineMetadata",w);function M(j$,B$,C$){if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);return X$(j$,B$,C$)}J("hasMetadata",M);function C(j$,B$,C$){if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);return L$(j$,B$,C$)}J("hasOwnMetadata",C);function f(j$,B$,C$){if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);return O$(j$,B$,C$)}J("getMetadata",f);function I(j$,B$,C$){if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);return u$(j$,B$,C$)}J("getOwnMetadata",I);function c(j$,B$){if(!R0(j$))throw TypeError();if(!U0(B$))B$=D1(B$);return H0(j$,B$)}J("getMetadataKeys",c);function h(j$,B$){if(!R0(j$))throw TypeError();if(!U0(B$))B$=D1(B$);return A0(j$,B$)}J("getOwnMetadataKeys",h);function r(j$,B$,C$){if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);if(!R0(B$))throw TypeError();if(!U0(C$))C$=D1(C$);var J0=AX(B$,C$,!1);if(U0(J0))return!1;return J0.OrdinaryDeleteMetadata(j$,B$,C$)}J("deleteMetadata",r);function t(j$,B$){for(var C$=j$.length-1;C$>=0;--C$){var J0=j$[C$],$1=J0(B$);if(!U0($1)&&!H1($1)){if(!T1($1))throw TypeError();B$=$1}}return B$}function Y$(j$,B$,C$,J0){for(var $1=j$.length-1;$1>=0;--$1){var A6=j$[$1],S6=A6(B$,C$,J0);if(!U0(S6)&&!H1(S6)){if(!R0(S6))throw TypeError();J0=S6}}return J0}function X$(j$,B$,C$){var J0=L$(j$,B$,C$);if(J0)return!0;var $1=l5(B$);if(!H1($1))return X$(j$,$1,C$);return!1}function L$(j$,B$,C$){var J0=AX(B$,C$,!1);if(U0(J0))return!1;return q$(J0.OrdinaryHasOwnMetadata(j$,B$,C$))}function O$(j$,B$,C$){var J0=L$(j$,B$,C$);if(J0)return u$(j$,B$,C$);var $1=l5(B$);if(!H1($1))return O$(j$,$1,C$);return}function u$(j$,B$,C$){var J0=AX(B$,C$,!1);if(U0(J0))return;return J0.OrdinaryGetOwnMetadata(j$,B$,C$)}function k$(j$,B$,C$,J0){var $1=AX(C$,J0,!0);$1.OrdinaryDefineOwnMetadata(j$,B$,C$,J0)}function H0(j$,B$){var C$=A0(j$,B$),J0=l5(j$);if(J0===null)return C$;var $1=H0(J0,B$);if($1.length<=0)return C$;if(C$.length<=0)return $1;var A6=new H,S6=[];for(var t1=0,M0=C$;t1<M0.length;t1++){var h0=M0[t1],d0=A6.has(h0);if(!d0)A6.add(h0),S6.push(h0)}for(var t0=0,S1=$1;t0<S1.length;t0++){var h0=S1[t0],d0=A6.has(h0);if(!d0)A6.add(h0),S6.push(h0)}return S6}function A0(j$,B$){var C$=AX(j$,B$,!1);if(!C$)return[];return C$.OrdinaryOwnMetadataKeys(j$,B$)}function L1(j$){if(j$===null)return 1;switch(typeof j$){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return j$===null?1:6;default:return 6}}function U0(j$){return j$===void 0}function H1(j$){return j$===null}function L0(j$){return typeof j$==="symbol"}function R0(j$){return typeof j$==="object"?j$!==null:typeof j$==="function"}function n(j$,B$){switch(L1(j$)){case 0:return j$;case 1:return j$;case 2:return j$;case 3:return j$;case 4:return j$;case 5:return j$}var C$=B$===3?"string":B$===5?"number":"default",J0=F4(j$,W);if(J0!==void 0){var $1=J0.call(j$,C$);if(R0($1))throw TypeError();return $1}return g(j$,C$==="default"?"number":C$)}function g(j$,B$){if(B$==="string"){var C$=j$.toString;if(E0(C$)){var J0=C$.call(j$);if(!R0(J0))return J0}var $1=j$.valueOf;if(E0($1)){var J0=$1.call(j$);if(!R0(J0))return J0}}else{var $1=j$.valueOf;if(E0($1)){var J0=$1.call(j$);if(!R0(J0))return J0}var A6=j$.toString;if(E0(A6)){var J0=A6.call(j$);if(!R0(J0))return J0}}throw TypeError()}function q$(j$){return!!j$}function Q$(j$){return""+j$}function D1(j$){var B$=n(j$,3);if(L0(B$))return B$;return Q$(B$)}function E4(j$){return Array.isArray?Array.isArray(j$):j$ instanceof Object?j$ instanceof Array:Object.prototype.toString.call(j$)==="[object Array]"}function E0(j$){return typeof j$==="function"}function T1(j$){return typeof j$==="function"}function j1(j$){switch(L1(j$)){case 3:return!0;case 4:return!0;default:return!1}}function S8(j$,B$){return j$===B$||j$!==j$&&B$!==B$}function F4(j$,B$){var C$=j$[B$];if(C$===void 0||C$===null)return;if(!E0(C$))throw TypeError();return C$}function WJ(j$){var B$=F4(j$,G);if(!E0(B$))throw TypeError();var C$=B$.call(j$);if(!R0(C$))throw TypeError();return C$}function u5(j$){return j$.value}function qQ(j$){var B$=j$.next();return B$.done?!1:B$}function m5(j$){var B$=j$.return;if(B$)B$.call(j$)}function l5(j$){var B$=Object.getPrototypeOf(j$);if(typeof j$!=="function"||j$===z)return B$;if(B$!==z)return B$;var C$=j$.prototype,J0=C$&&Object.getPrototypeOf(C$);if(J0==null||J0===Object.prototype)return B$;var $1=J0.constructor;if(typeof $1!=="function")return B$;if($1===j$)return B$;return $1}function hj(){var j$;if(!U0(B)&&typeof X.Reflect<"u"&&!(B in X.Reflect)&&typeof X.Reflect.defineMetadata==="function")j$=gj(X.Reflect);var B$,C$,J0,$1=new O,A6={registerProvider:S6,getProvider:M0,setProvider:d0};return A6;function S6(t0){if(!Object.isExtensible(A6))throw Error("Cannot add provider to a frozen registry.");switch(!0){case j$===t0:break;case U0(B$):B$=t0;break;case B$===t0:break;case U0(C$):C$=t0;break;case C$===t0:break;default:if(J0===void 0)J0=new H;J0.add(t0);break}}function t1(t0,S1){if(!U0(B$)){if(B$.isProviderFor(t0,S1))return B$;if(!U0(C$)){if(C$.isProviderFor(t0,S1))return B$;if(!U0(J0)){var w1=WJ(J0);while(!0){var P4=qQ(w1);if(!P4)return;var z9=u5(P4);if(z9.isProviderFor(t0,S1))return m5(w1),z9}}}}if(!U0(j$)&&j$.isProviderFor(t0,S1))return j$;return}function M0(t0,S1){var w1=$1.get(t0),P4;if(!U0(w1))P4=w1.get(S1);if(!U0(P4))return P4;if(P4=t1(t0,S1),!U0(P4)){if(U0(w1))w1=new L,$1.set(t0,w1);w1.set(S1,P4)}return P4}function h0(t0){if(U0(t0))throw TypeError();return B$===t0||C$===t0||!U0(J0)&&J0.has(t0)}function d0(t0,S1,w1){if(!h0(w1))throw Error("Metadata provider not registered.");var P4=M0(t0,S1);if(P4!==w1){if(!U0(P4))return!1;var z9=$1.get(t0);if(U0(z9))z9=new L,$1.set(t0,z9);z9.set(S1,w1)}return!0}}function HY(){var j$;if(!U0(B)&&R0(X.Reflect)&&Object.isExtensible(X.Reflect))j$=X.Reflect[B];if(U0(j$))j$=hj();if(!U0(B)&&R0(X.Reflect)&&Object.isExtensible(X.Reflect))Object.defineProperty(X.Reflect,B,{enumerable:!1,configurable:!1,writable:!1,value:j$});return j$}function OY(j$){var B$=new O,C$={isProviderFor:function(h0,d0){var t0=B$.get(h0);if(U0(t0))return!1;return t0.has(d0)},OrdinaryDefineOwnMetadata:S6,OrdinaryHasOwnMetadata:$1,OrdinaryGetOwnMetadata:A6,OrdinaryOwnMetadataKeys:t1,OrdinaryDeleteMetadata:M0};return F.registerProvider(C$),C$;function J0(h0,d0,t0){var S1=B$.get(h0),w1=!1;if(U0(S1)){if(!t0)return;S1=new L,B$.set(h0,S1),w1=!0}var P4=S1.get(d0);if(U0(P4)){if(!t0)return;if(P4=new L,S1.set(d0,P4),!j$.setProvider(h0,d0,C$)){if(S1.delete(d0),w1)B$.delete(h0);throw Error("Wrong provider for target.")}}return P4}function $1(h0,d0,t0){var S1=J0(d0,t0,!1);if(U0(S1))return!1;return q$(S1.has(h0))}function A6(h0,d0,t0){var S1=J0(d0,t0,!1);if(U0(S1))return;return S1.get(h0)}function S6(h0,d0,t0,S1){var w1=J0(t0,S1,!0);w1.set(h0,d0)}function t1(h0,d0){var t0=[],S1=J0(h0,d0,!1);if(U0(S1))return t0;var w1=S1.keys(),P4=WJ(w1),z9=0;while(!0){var wQ=qQ(P4);if(!wQ)return t0.length=z9,t0;var HU=u5(wQ);try{t0[z9]=HU}catch(E7){try{m5(P4)}finally{throw E7}}z9++}}function M0(h0,d0,t0){var S1=J0(d0,t0,!1);if(U0(S1))return!1;if(!S1.delete(h0))return!1;if(S1.size===0){var w1=B$.get(d0);if(!U0(w1)){if(w1.delete(t0),w1.size===0)B$.delete(w1)}}return!0}}function gj(j$){var{defineMetadata:B$,hasOwnMetadata:C$,getOwnMetadata:J0,getOwnMetadataKeys:$1,deleteMetadata:A6}=j$,S6=new O,t1={isProviderFor:function(M0,h0){var d0=S6.get(M0);if(!U0(d0)&&d0.has(h0))return!0;if($1(M0,h0).length){if(U0(d0))d0=new H,S6.set(M0,d0);return d0.add(h0),!0}return!1},OrdinaryDefineOwnMetadata:B$,OrdinaryHasOwnMetadata:C$,OrdinaryGetOwnMetadata:J0,OrdinaryOwnMetadataKeys:$1,OrdinaryDeleteMetadata:A6};return t1}function AX(j$,B$,C$){var J0=F.getProvider(j$,B$);if(!U0(J0))return J0;if(C$){if(F.setProvider(j$,B$,A))return A;throw Error("Illegal state.")}return}function uj(){var j$={},B$=[],C$=function(){function t1(M0,h0,d0){this._index=0,this._keys=M0,this._values=h0,this._selector=d0}return t1.prototype["@@iterator"]=function(){return this},t1.prototype[G]=function(){return this},t1.prototype.next=function(){var M0=this._index;if(M0>=0&&M0<this._keys.length){var h0=this._selector(this._keys[M0],this._values[M0]);if(M0+1>=this._keys.length)this._index=-1,this._keys=B$,this._values=B$;else this._index++;return{value:h0,done:!1}}return{value:void 0,done:!0}},t1.prototype.throw=function(M0){if(this._index>=0)this._index=-1,this._keys=B$,this._values=B$;throw M0},t1.prototype.return=function(M0){if(this._index>=0)this._index=-1,this._keys=B$,this._values=B$;return{value:M0,done:!0}},t1}(),J0=function(){function t1(){this._keys=[],this._values=[],this._cacheKey=j$,this._cacheIndex=-2}return Object.defineProperty(t1.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t1.prototype.has=function(M0){return this._find(M0,!1)>=0},t1.prototype.get=function(M0){var h0=this._find(M0,!1);return h0>=0?this._values[h0]:void 0},t1.prototype.set=function(M0,h0){var d0=this._find(M0,!0);return this._values[d0]=h0,this},t1.prototype.delete=function(M0){var h0=this._find(M0,!1);if(h0>=0){var d0=this._keys.length;for(var t0=h0+1;t0<d0;t0++)this._keys[t0-1]=this._keys[t0],this._values[t0-1]=this._values[t0];if(this._keys.length--,this._values.length--,S8(M0,this._cacheKey))this._cacheKey=j$,this._cacheIndex=-2;return!0}return!1},t1.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=j$,this._cacheIndex=-2},t1.prototype.keys=function(){return new C$(this._keys,this._values,$1)},t1.prototype.values=function(){return new C$(this._keys,this._values,A6)},t1.prototype.entries=function(){return new C$(this._keys,this._values,S6)},t1.prototype["@@iterator"]=function(){return this.entries()},t1.prototype[G]=function(){return this.entries()},t1.prototype._find=function(M0,h0){if(!S8(this._cacheKey,M0)){this._cacheIndex=-1;for(var d0=0;d0<this._keys.length;d0++)if(S8(this._keys[d0],M0)){this._cacheIndex=d0;break}}if(this._cacheIndex<0&&h0)this._cacheIndex=this._keys.length,this._keys.push(M0),this._values.push(void 0);return this._cacheIndex},t1}();return J0;function $1(t1,M0){return t1}function A6(t1,M0){return M0}function S6(t1,M0){return[t1,M0]}}function LU(){var j$=function(){function B$(){this._map=new L}return Object.defineProperty(B$.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),B$.prototype.has=function(C$){return this._map.has(C$)},B$.prototype.add=function(C$){return this._map.set(C$,C$),this},B$.prototype.delete=function(C$){return this._map.delete(C$)},B$.prototype.clear=function(){this._map.clear()},B$.prototype.keys=function(){return this._map.keys()},B$.prototype.values=function(){return this._map.keys()},B$.prototype.entries=function(){return this._map.entries()},B$.prototype["@@iterator"]=function(){return this.keys()},B$.prototype[G]=function(){return this.keys()},B$}();return j$}function CB(){var j$=16,B$=K.create(),C$=J0();return function(){function M0(){this._key=J0()}return M0.prototype.has=function(h0){var d0=$1(h0,!1);return d0!==void 0?K.has(d0,this._key):!1},M0.prototype.get=function(h0){var d0=$1(h0,!1);return d0!==void 0?K.get(d0,this._key):void 0},M0.prototype.set=function(h0,d0){var t0=$1(h0,!0);return t0[this._key]=d0,this},M0.prototype.delete=function(h0){var d0=$1(h0,!1);return d0!==void 0?delete d0[this._key]:!1},M0.prototype.clear=function(){this._key=J0()},M0}();function J0(){var M0;do M0="@@WeakMap@@"+t1();while(K.has(B$,M0));return B$[M0]=!0,M0}function $1(M0,h0){if(!Q.call(M0,C$)){if(!h0)return;Object.defineProperty(M0,C$,{value:K.create()})}return M0[C$]}function A6(M0,h0){for(var d0=0;d0<h0;++d0)M0[d0]=Math.random()*255|0;return M0}function S6(M0){if(typeof Uint8Array==="function"){var h0=new Uint8Array(M0);if(typeof crypto<"u")crypto.getRandomValues(h0);else if(typeof msCrypto<"u")msCrypto.getRandomValues(h0);else A6(h0,M0);return h0}return A6(Array(M0),M0)}function t1(){var M0=S6(j$);M0[6]=M0[6]&79|64,M0[8]=M0[8]&191|128;var h0="";for(var d0=0;d0<j$;++d0){var t0=M0[d0];if(d0===4||d0===6||d0===8)h0+="-";if(t0<16)h0+="0";h0+=t0.toString(16).toLowerCase()}return h0}}function mj(j$){return j$.__=void 0,delete j$.__,j$}})})(Xw$||(Xw$={}))});import{existsSync as xL0}from"fs";import{homedir as bL0}from"os";import ss from"path";function C_($="/"){try{return process.cwd()}catch{return $}}function $b($=bL0()){if($.length>0&&xL0($))return $;return"/"}function SB($=C_()){let J=process.env[g2]?.trim();return J&&ss.isAbsolute(J)?J:$}function b4($){if(ss.isAbsolute($))return $;return ss.resolve(SB(),$)}var g2="AUTOMOBILE_DAEMON_LAUNCH_CWD";var _9=()=>{};function Gw$($,J){let X=(Y)=>$.includes(Y.cli)||J[Y.env]==="1",Q={observeResultIncludeElements:!1,toolResultsNoStructuredContent:!1,actionsDiffObserve:!1,actionsNoObserve:!1};for(let Y of IB)Q[Y.field]=X(Y);return Q}function Zw$($){let J=[];for(let X of IB)if($[X.field])J.push(X.cli);return J}var IB;var S_=D(()=>{IB=[{field:"observeResultIncludeElements",cli:"--observe-result-include-elements",env:"AUTOMOBILE_OBSERVE_RESULT_INCLUDE_ELEMENTS",featureFlagKey:"observe-result-include-elements",label:"--observe-result-include-elements"},{field:"toolResultsNoStructuredContent",cli:"--tool-results-no-structured-content",env:"AUTOMOBILE_TOOL_RESULTS_NO_STRUCTURED_CONTENT",featureFlagKey:"tool-results-no-structured-content",label:"--tool-results-no-structured-content"},{field:"actionsDiffObserve",cli:"--actions-diff-observe",env:"AUTOMOBILE_ACTIONS_DIFF_OBSERVE",featureFlagKey:"actions-diff-observe",label:"--actions-diff-observe"},{field:"actionsNoObserve",cli:"--actions-no-observe",env:"AUTOMOBILE_ACTIONS_NO_OBSERVE",featureFlagKey:"actions-no-observe",label:"--actions-no-observe"}]});import{performance as fL0}from"perf_hooks";import vL0 from"fs";import hL0 from"path";function uL0($,J){if($.includes("--startup-benchmark"))return!0;let X=(J.AUTOMOBILE_STARTUP_BENCHMARK??J.AUTO_MOBILE_STARTUP_BENCHMARK??"").toLowerCase();return $.includes("--daemon-mode")&&(X==="1"||X==="true"||X==="yes")}class Vw${marks=new Map;phaseStarts=new Map;phases=new Map;emitted=!1;emittedReport;enabled;outputPath;label;now;fileSystem;constructor($,J={}){this.enabled=$;let X=J.outputPath??lL0;this.outputPath=X?b4(X):void 0,this.label=J.label??pL0,this.now=J.now??fL0.now,this.fileSystem=J.fileSystem??vL0}isEnabled(){return this.enabled}mark($){if(!this.enabled||this.marks.has($))return;this.marks.set($,this.now()),this.persistCheckpoint()}startPhase($){if(!this.enabled||this.phases.has($)||this.phaseStarts.has($))return;this.phaseStarts.set($,this.now()),this.persistCheckpoint()}async runPhase($,J){this.startPhase($);let X=await J();return this.endPhase($),X}endPhase($){if(!this.enabled||this.phases.has($))return;let J=this.phaseStarts.get($);if(J===void 0)return;this.phases.set($,this.now()-J),this.phaseStarts.delete($),this.persistCheckpoint()}recordPhase($,J){if(!this.enabled||this.phases.has($))return;this.phases.set($,J),this.persistCheckpoint()}emit($,J={}){if(!this.enabled||this.emitted)return;this.emitted=!0,this.emittedReport={type:$,meta:J};let X=this.createReport($,"ready",J),Q=JSON.stringify(X);this.writeReport(Q),process.stderr.write(`${gL0} ${Q}
|
|
17
17
|
`)}persistCheckpoint(){if(!this.enabled)return;let $=this.emittedReport?this.createReport(this.emittedReport.type,"ready",this.emittedReport.meta):this.createReport("startup-checkpoint","in_progress");this.writeReport(JSON.stringify($))}createReport($,J,X={}){let Q=Object.fromEntries(this.marks.entries()),Y=Object.fromEntries(this.phases.entries());return{type:$,state:J,timestamp:new Date().toISOString(),pid:process.pid,label:this.label,marks:Q,phases:Y,activePhases:[...this.phaseStarts.keys()],memoryUsage:process.memoryUsage(),meta:X}}writeReport($){if(!this.outputPath)return;let J=hL0.dirname(this.outputPath);if(!this.fileSystem.existsSync(J))this.fileSystem.mkdirSync(J,{recursive:!0});let X=`${this.outputPath}.${process.pid}.tmp`;this.fileSystem.writeFileSync(X,$,"utf-8"),this.fileSystem.renameSync(X,this.outputPath)}}var gL0="STARTUP_BENCHMARK",mL0,lL0,pL0,y4;var Jb=D(()=>{_9();mL0=uL0(process.argv,process.env),lL0=process.env.AUTOMOBILE_STARTUP_BENCHMARK_OUTPUT??process.env.AUTO_MOBILE_STARTUP_BENCHMARK_OUTPUT,pL0=process.env.AUTOMOBILE_STARTUP_BENCHMARK_LABEL??process.env.AUTO_MOBILE_STARTUP_BENCHMARK_LABEL;y4=new Vw$(mL0)});import{createHash as cL0}from"crypto";import{spawnSync as nL0}from"child_process";class Kw${run;constructor($=oL0){this.run=$}readVersion($,J){if($.split(/[\\/]/).includes("node_modules"))return null;let X=this.execute($,["rev-parse","--show-toplevel"]);if(!X||J(X)!==dL0)return null;let Q=this.execute($,["rev-parse","--short=12","HEAD"]);if(!Q)return null;let Y=this.execute($,["status","--porcelain","--untracked-files=no"]),W=Y!==null&&Y.length>0,G=null;if(W){let Z=this.execute($,["diff","HEAD"]);if(Z)G=cL0("sha256").update(Z).digest("hex").slice(0,12)}return{shortSha:Q,dirty:W,dirtyHash:G}}execute($,J){return this.run("git",J,{cwd:$,timeoutMs:iL0})}}var dL0="@kaeawc/auto-mobile",iL0=2000,oL0=($,J,{cwd:X,timeoutMs:Q})=>{let Y=null;try{Y=nL0("git",J,{cwd:X,encoding:"utf-8",timeout:Q,killSignal:"SIGTERM"})}catch(W){}if(!Y||Y.status!==0||Y.error)return null;return(typeof Y.stdout==="string"?Y.stdout:Y.stdout.toString()).trim()},Uw$;var zw$=D(()=>{Uw$=new Kw$});import es from"fs";import Qb from"path";import{fileURLToPath as rL0}from"url";var Xb=null,Lw$=($)=>{let J=$;for(let X=0;X<6;X++){let Q=Qb.join(J,"package.json");if(es.existsSync(Q))return Q;let Y=Qb.dirname(J);if(Y===J)break;J=Y}return null},Hw$=()=>Qb.dirname(rL0(import.meta.url)),tL0=($)=>{try{let J=es.readFileSync(Qb.join($,"package.json"),"utf-8");return JSON.parse(J).name??null}catch{}return null},aL0=()=>{let $=Lw$(Hw$())??Lw$(process.cwd());if(!$)return null;try{let J=es.readFileSync($,"utf-8");return JSON.parse(J).version??null}catch{}return null},sL0=($=Hw$(),J=Uw$,X=tL0)=>J.readVersion($,X),GJ=($)=>$.split("+")[0],eL0=($,J)=>{if(!J||J.shortSha.length===0)return $;let X=J.dirty?J.dirtyHash?`.dirty.${J.dirtyHash}`:".dirty":"";return`${$}+g${J.shortSha}${X}`},$H0=($)=>{let J=$.env.MCP_SERVER_VERSION;if(J)return J;let X=$.env.npm_package_version||$.readPackageVersion()||"unknown";if(X==="unknown")return X;return eL0(X,$.readGitVersion())},M9=()=>{if(Xb)return Xb;return Xb=$H0({env:{MCP_SERVER_VERSION:process.env.MCP_SERVER_VERSION,npm_package_version:process.env.npm_package_version},readPackageVersion:aL0,readGitVersion:()=>sL0()}),Xb};var P7=D(()=>{zw$()});function NQ($){return $==="1"||$?.toLowerCase()==="true"}function Yb($,J=process.env){return $.includes("--skip-ctrl-proxy-download")||$.includes("--skip-accessibility-download")||NQ(J.AUTOMOBILE_SKIP_CTRL_PROXY_DOWNLOAD)}var $e="--skip-ctrl-proxy-download",OU="AUTOMOBILE_SKIP_CTRL_PROXY_DOWNLOAD";function f4($,J){if($ instanceof R)return $;let X=$ instanceof Error?$.message:String($);return new R(`${J}: ${X}`)}var R;var l4=D(()=>{R=class R extends Error{constructor($){super($)}}});import{promises as u2}from"fs";var lj,Ow$,BU,DU,Bw$,I_,Dw$=async($)=>{await u2.mkdir($,{recursive:!0})};var FU=D(()=>{lj=u2.readFile,Ow$=u2.writeFile,BU=u2.stat,DU=u2.readdir,Bw$=u2.rename,I_=u2.unlink});import JH0 from"fs";import Fw$ from"os";import Wb from"path";function QH0($=process.env,J=Fw$.homedir()){let X=($.AUTOMOBILE_DATA_DIR??$.AUTO_MOBILE_DATA_DIR)?.trim();if(X&&X.length>0)return Wb.resolve(X);if(J&&J.length>0)return Wb.join(J,".auto-mobile");return Wb.join(Fw$.tmpdir(),"auto-mobile")}function H9($){return Wb.join(QH0(),$)}function qU($){let J=H9($);return JH0.mkdirSync(J,{recursive:!0,mode:XH0}),J}var XH0=448,ZJ;var MX=D(()=>{ZJ={LOGS:"logs",TOOL_LOGS:"tool_logs",SCREENSHOTS:"screenshots",NAVIGATION_SCREENSHOTS:"navigation-screenshots",VIEW_HIERARCHY:"view_hierarchy",OBSERVE_RESULTS:"observe_results",TOOL_OUTPUTS:"tool_outputs",WINDOW:"window",CACHE:"cache",STATE:"state"}});import qw$ from"path";function YH0($){try{return process.kill($,0),!0}catch(J){return J?.code==="EPERM"}}function ww$($,J){return $===`${J}.log`||$.startsWith(`${J}-`)}function WH0($){let J=/^(?:stdio|server|daemon-launch)-(\d+)(?:-.*)?\.log$/.exec($);return J?Number(J[1]):void 0}async function Nw$($){let J=$.now??Date.now(),X=$.isProcessAlive??YH0,Q;try{Q=await DU($.dir)}catch(G){$.logger?.debug(`log pruning skipped because the log directory could not be read: ${G}`,G);return}let Y=Q.filter((G)=>G.endsWith(".log")),W=Y.filter((G)=>ww$(G,$.ownPrefix)).sort();if(W.length>$.maxOwnFiles)for(let G of W.slice(0,W.length-$.maxOwnFiles))await I_(qw$.join($.dir,G)).catch(()=>{});for(let G of Y){if(ww$(G,$.ownPrefix))continue;let Z=WH0(G);if(Z===void 0)continue;if(X(Z))continue;let j=qw$.join($.dir,G);try{let V=await BU(j);if(J-V.mtimeMs>$.abandonedMaxAgeMs)await I_(j).catch(()=>{})}catch{}}}var Aw$=D(()=>{FU()});var Cw$={};u1(Cw$,{sanitizeMessage:()=>jb,safeStringify:()=>Tw$,resolveProcessLogPrefix:()=>Rw$,parseAutomobileLogLevel:()=>Mw$,logger:()=>U,SENSITIVE_ENV_KEYS:()=>Pw$,LogLevel:()=>RX});import p2 from"fs";import _w$ from"path";function Mw$($){if($===void 0)return null;let J=$.trim().toLowerCase();if(J.length===0)return null;switch(J){case"debug":return RX.DEBUG;case"info":return RX.INFO;case"warn":case"warning":return RX.WARN;case"error":return RX.ERROR;case"none":case"silent":return RX.NONE;default:return null}}function Rw$($,J){return $.includes("--daemon-mode")?"daemon":`stdio-${J}`}var RX,kB,Je=!1,Xe,Gb=($)=>{Xe=Xe.then(()=>$)},xB,Qe,m2,l2,GH0=10485760,ZH0=10,jH0=86400000,Ew$=()=>Nw$({dir:xB,ownPrefix:Qe,maxOwnFiles:ZH0,abandonedMaxAgeMs:jH0}),VH0=async()=>{try{if(p2.existsSync(m2)){if((await BU(m2)).size>=GH0){l2.end();let J=new Date().toISOString().replace(/:/g,"-"),X=_w$.join(xB,`${Qe}-${J}.log`);if(p2.existsSync(m2))await Bw$(m2,X);l2=p2.createWriteStream(m2,{flags:"a"}),await Ew$()}}}catch($){if(l2.destroyed||!l2.writable)l2=p2.createWriteStream(m2,{flags:"a"});console.error("Log rotation failed:",$)}},Pw$,Tw$=($)=>{if(typeof $!=="object"||$===null)return String($);return JSON.stringify($,(J,X)=>{if(typeof X==="object"&&X!==null){let Q={};for(let[Y,W]of Object.entries(X))if(!Pw$.has(Y.toUpperCase()))Q[Y]=W;return Q}return X})},jb=($)=>{return $.replace(/[\r\n\t]/g," ")},Zb=async($,J,X)=>{try{await VH0();let Q=new Date().toISOString(),Y=jb(J),W=`${Q} [${$}] ${Y}`;if(X.length>0){let Z=X.map((j)=>{if(typeof j==="object")return jb(Tw$(j));return jb(String(j))}).join(" ");W+=` ${Z}`}if(W.length>1000)W=W.substring(0,1000)+"... (truncated)";let G=W.replace(/[\r\n\t]/g," ");if(l2.write(G+`
|
|
18
18
|
`),Je)process.stdout.write(`${G}
|
|
19
|
-
`)}catch(Q){console.error("Failed to write log:",Q)}},U;var d=D(()=>{FU();MX();Aw$();RX={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};kB=Mw$(process.env.AUTOMOBILE_LOG_LEVEL)??RX.INFO,Xe=Promise.resolve(),xB=H9(ZJ.LOGS);if(!p2.existsSync(xB))p2.mkdirSync(xB,{recursive:!0});Dw$(xB).catch(($)=>{console.error("Failed to create logs directory:",$)});Qe=Rw$(process.argv,process.pid),m2=_w$.join(xB,`${Qe}.log`),l2=p2.createWriteStream(m2,{flags:"a"});Ew$().catch(()=>{});Pw$=new Set(["PASSWORD","TOKEN","SECRET","KEY","CREDENTIAL","AUTH","API_KEY","PRIVATE_KEY","ACCESS_TOKEN","REFRESH_TOKEN","CLIENT_SECRET","DATABASE_URL","DB_PASSWORD","GITHUB_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY"]),U={setLogLevel($){kB=$},getLogLevel(){return kB},enableStdoutLogging(){Je=!0},disableStdoutLogging(){Je=!1},debug($,...J){if(kB<=RX.DEBUG)Gb(Zb("DEBUG",$,J).catch((X)=>{console.error("Failed to write debug log:",X)}))},info($,...J){if(kB<=RX.INFO)Gb(Zb("INFO",$,J).catch((X)=>{console.error("Failed to write info log:",X)}))},warn($,...J){if(kB<=RX.WARN)Gb(Zb("WARN",$,J).catch((X)=>{console.error("Failed to write warn log:",X)}))},error($,...J){if(kB<=RX.ERROR)Gb(Zb("ERROR",$,J).catch((X)=>{console.error("Failed to write error log:",X)}))},async flush(){await Xe},close(){l2.end()}}});var Ye=o((dP1,Sw$)=>{Sw$.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Vb=o((kw$)=>{var Iw$={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function KH0($){return function(...J){if(J.length)$=$.replace(/\{(\d)\}/g,(X,Q)=>J[Q]||"");return Error("ADM-ZIP: "+$)}}for(let $ of Object.keys(Iw$))kw$[$]=KH0(Iw$[$])});var vw$=o((oP1,fw$)=>{var UH0=q0("fs"),R9=q0("path"),xw$=Ye(),zH0=Vb(),LH0=typeof process==="object"&&process.platform==="win32",bw$=($)=>typeof $==="object"&&$!==null,yw$=new Uint32Array(256).map(($,J)=>{for(let X=0;X<8;X++)if((J&1)!==0)J=3988292384^J>>>1;else J>>>=1;return J>>>0});function I8($){if(this.sep=R9.sep,this.fs=UH0,bw$($)){if(bw$($.fs)&&typeof $.fs.statSync==="function")this.fs=$.fs}}fw$.exports=I8;I8.prototype.makeDir=function($){let J=this;function X(Q){let Y=Q.split(J.sep)[0];Q.split(J.sep).forEach(function(W){if(!W||W.substr(-1,1)===":")return;Y+=J.sep+W;var G;try{G=J.fs.statSync(Y)}catch(Z){if(Z.message&&Z.message.startsWith("ENOENT"))J.fs.mkdirSync(Y);else throw Z}if(G&&G.isFile())throw zH0.FILE_IN_THE_WAY(`"${Y}"`)})}X($)};I8.prototype.writeFileTo=function($,J,X,Q){let Y=this;if(Y.fs.existsSync($)){if(!X)return!1;var W=Y.fs.statSync($);if(W.isDirectory())return!1}var G=R9.dirname($);if(!Y.fs.existsSync(G))Y.makeDir(G);var Z;try{Z=Y.fs.openSync($,"w",438)}catch(j){Y.fs.chmodSync($,438),Z=Y.fs.openSync($,"w",438)}if(Z)try{Y.fs.writeSync(Z,J,0,J.length,0)}finally{Y.fs.closeSync(Z)}return Y.fs.chmodSync($,Q||438),!0};I8.prototype.writeFileToAsync=function($,J,X,Q,Y){if(typeof Q==="function")Y=Q,Q=void 0;let W=this;W.fs.exists($,function(G){if(G&&!X)return Y(!1);W.fs.stat($,function(Z,j){if(G&&j&&j.isDirectory())return Y(!1);var V=R9.dirname($);W.fs.exists(V,function(K){if(!K)try{W.makeDir(V)}catch(L){return Y(!1)}let z=function(L){W.fs.write(L,J,0,J.length,0,function(H){W.fs.close(L,function(){if(H)return Y(!1);W.fs.chmod($,Q||438,function(){Y(!0)})})})};W.fs.open($,"w",438,function(L,H){if(L)W.fs.chmod($,438,function(){W.fs.open($,"w",438,function(O,B){if(O||!B)return Y(!1);z(B)})});else if(H)z(H);else Y(!1)})})})})};I8.prototype.findFiles=function($){let J=this;function X(Q,Y,W,G){if(typeof Y==="boolean")W=Y,Y=void 0;let Z=[];return J.fs.readdirSync(Q).forEach(function(j){let V=R9.join(Q,j),K=J.fs.statSync(V);if(!Y||Y.test(V))Z.push(R9.normalize(V)+(K.isDirectory()?J.sep:""));if(K.isDirectory()&&W){let z=J.fs.realpathSync(V);if(!G.has(z))G.add(z),Z=Z.concat(X(V,Y,W,G))}}),Z}return X($,void 0,!0,new Set([J.fs.realpathSync($)]))};I8.prototype.findFilesAsync=function($,J){let X=this,Q=[],Y=!1,W=function(Z){if(Y)return;Y=!0,J(Z,Z?void 0:Q)},G=function(Z,j,V){X.fs.readdir(Z,function(K,z){if(K)return V(K);let L=z.length;if(!L)return V();z.forEach(function(H){let O=R9.join(Z,H);X.fs.stat(O,function(B,F){if(B)return V(B);if(!F){if(!--L)V();return}if(Q.push(R9.normalize(O)+(F.isDirectory()?X.sep:"")),!F.isDirectory()){if(!--L)V();return}X.fs.realpath(O,function(A,_){if(A)return V(A);if(j.has(_)){if(!--L)V();return}j.add(_),G(O,j,function(q){if(q)return V(q);if(!--L)V()})})})})})};X.fs.realpath($,function(Z,j){if(Z)return W(Z);G($,new Set([j]),W)})};I8.prototype.getAttributes=function(){};I8.prototype.setAttributes=function(){};I8.crc32update=function($,J){return yw$[($^J)&255]^$>>>8};I8.crc32=function($){if(typeof $==="string")$=Buffer.from($,"utf8");let J=$.length,X=-1;for(let Q=0;Q<J;)X=I8.crc32update(X,$[Q++]);return~X>>>0};I8.methodToString=function($){switch($){case xw$.STORED:return"STORED ("+$+")";case xw$.DEFLATED:return"DEFLATED ("+$+")";default:return"UNSUPPORTED ("+$+")"}};I8.canonical=function($){if(!$)return"";let J=R9.posix.normalize("/"+$.split("\\").join("/"));return R9.join(".",J)};I8.zipnamefix=function($){if(!$)return"";let J=R9.posix.normalize("/"+$.split("\\").join("/"));return R9.posix.join(".",J)};I8.findLast=function($,J){if(!Array.isArray($))throw TypeError("arr is not array");let X=$.length>>>0;for(let Q=X-1;Q>=0;Q--)if(J($[Q],Q,$))return $[Q];return};I8.sanitize=function($,J){$=R9.resolve(R9.normalize($));var X=J.split("/");for(var Q=0,Y=X.length;Q<Y;Q++){var W=R9.normalize(R9.join($,X.slice(Q,Y).join(R9.sep)));if(W===$||W.startsWith($+R9.sep))return W}return R9.normalize(R9.join($,R9.basename(J)))};I8.toBuffer=function(J,X){if(Buffer.isBuffer(J))return J;else if(J instanceof Uint8Array)return Buffer.from(J);else return typeof J==="string"?X(J):Buffer.alloc(0)};I8.readBigUInt64LE=function($,J){let X=$.readUInt32LE(J);return $.readUInt32LE(J+4)*4294967296+X};I8.writeBigUInt64LE=function($,J,X){let Q=J>>>0,Y=Math.floor(J/4294967296)>>>0;$.writeUInt32LE(Q,X),$.writeUInt32LE(Y,X+4)};I8.fromDOS2Date=function($){return new Date(($>>25&127)+1980,Math.max(($>>21&15)-1,0),Math.max($>>16&31,1),$>>11&31,$>>5&63,($&31)<<1)};I8.fromDate2DOS=function($){let J=0,X=0;if($.getFullYear()>1979)J=($.getFullYear()-1980&127)<<9|$.getMonth()+1<<5|$.getDate(),X=$.getHours()<<11|$.getMinutes()<<5|$.getSeconds()>>1;return J<<16|X};I8.isWin=LH0;I8.crcTable=yw$});var gw$=o((rP1,hw$)=>{var HH0=q0("path");hw$.exports=function($,{fs:J}){var X=$||"",Q=W(),Y=null;function W(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}if(X&&J.existsSync(X))Y=J.statSync(X),Q.directory=Y.isDirectory(),Q.mtime=Y.mtime,Q.atime=Y.atime,Q.executable=(73&Y.mode)!==0,Q.readonly=(128&Y.mode)===0,Q.hidden=HH0.basename(X)[0]===".";else console.warn("Invalid path: "+X);return{get directory(){return Q.directory},get readOnly(){return Q.readonly},get hidden(){return Q.hidden},get mtime(){return Q.mtime},get atime(){return Q.atime},get executable(){return Q.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:X,isDirectory:Q.directory,isReadOnly:Q.readonly,isHidden:Q.hidden,isExecutable:Q.executable,mTime:Q.mtime,aTime:Q.atime}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var mw$=o((tP1,uw$)=>{uw$.exports={efs:!0,encode:($)=>Buffer.from($,"utf8"),decode:($)=>$.toString("utf8")}});var yB=o((aP1,bB)=>{bB.exports=vw$();bB.exports.Constants=Ye();bB.exports.Errors=Vb();bB.exports.FileAttr=gw$();bB.exports.decoder=mw$()});var pw$=o((sP1,lw$)=>{var wU=yB(),x0=wU.Constants;lw$.exports=function(){var $=20,J=10,X=0,Q=0,Y=0,W=0,G=0,Z=0,j=0,V=0,K=0,z=0,L=0,H=0,O=0;$|=wU.isWin?2560:768,X|=x0.FLG_EFS;let B={extraLen:0},F=(q)=>Math.max(0,q)>>>0,A=(q)=>Math.max(0,q)&65535,_=(q)=>Math.max(0,q)&255;return Y=wU.fromDate2DOS(new Date),{get made(){return $},set made(q){$=q},get version(){return J},set version(q){J=q},get flags(){return X},set flags(q){X=q},get flags_efs(){return(X&x0.FLG_EFS)>0},set flags_efs(q){if(q)X|=x0.FLG_EFS;else X&=~x0.FLG_EFS},get flags_desc(){return(X&x0.FLG_DESC)>0},set flags_desc(q){if(q)X|=x0.FLG_DESC;else X&=~x0.FLG_DESC},get method(){return Q},set method(q){switch(q){case x0.STORED:this.version=10;break;case x0.DEFLATED:default:this.version=20}Q=q},get time(){return wU.fromDOS2Date(this.timeval)},set time(q){q=new Date(q),this.timeval=wU.fromDate2DOS(q)},get timeval(){return Y},set timeval(q){Y=F(q)},get timeHighByte(){return _(Y>>>8)},get crc(){return W},set crc(q){W=F(q)},get compressedSize(){return G},set compressedSize(q){G=F(q)},get size(){return Z},set size(q){Z=F(q)},get fileNameLength(){return j},set fileNameLength(q){j=q},get extraLength(){return V},set extraLength(q){V=q},get extraLocalLength(){return B.extraLen},set extraLocalLength(q){B.extraLen=q},get commentLength(){return K},set commentLength(q){K=q},get diskNumStart(){return z},set diskNumStart(q){z=F(q)},get inAttr(){return L},set inAttr(q){L=F(q)},get attr(){return H},set attr(q){H=F(q)},get fileAttr(){return(H||0)>>16&4095},get offset(){return O},set offset(q){O=F(q)},get encrypted(){return(X&x0.FLG_ENC)===x0.FLG_ENC},get centralHeaderSize(){return x0.CENHDR+j+V+K},get realDataOffset(){return O+x0.LOCHDR+B.fnameLen+B.extraLen},get localHeader(){return B},loadLocalHeaderFromBinary:function(q){var w=q.slice(O,O+x0.LOCHDR);if(w.readUInt32LE(0)!==x0.LOCSIG)throw wU.Errors.INVALID_LOC();B.version=w.readUInt16LE(x0.LOCVER),B.flags=w.readUInt16LE(x0.LOCFLG),B.flags_desc=(B.flags&x0.FLG_DESC)>0,B.method=w.readUInt16LE(x0.LOCHOW),B.time=w.readUInt32LE(x0.LOCTIM),B.crc=w.readUInt32LE(x0.LOCCRC),B.compressedSize=w.readUInt32LE(x0.LOCSIZ),B.size=w.readUInt32LE(x0.LOCLEN),B.fnameLen=w.readUInt16LE(x0.LOCNAM),B.extraLen=w.readUInt16LE(x0.LOCEXT);let M=O+x0.LOCHDR+B.fnameLen,C=M+B.extraLen;return q.slice(M,C)},loadFromBinary:function(q){if(q.length!==x0.CENHDR||q.readUInt32LE(0)!==x0.CENSIG)throw wU.Errors.INVALID_CEN();$=q.readUInt16LE(x0.CENVEM),J=q.readUInt16LE(x0.CENVER),X=q.readUInt16LE(x0.CENFLG),Q=q.readUInt16LE(x0.CENHOW),Y=q.readUInt32LE(x0.CENTIM),W=q.readUInt32LE(x0.CENCRC),G=q.readUInt32LE(x0.CENSIZ),Z=q.readUInt32LE(x0.CENLEN),j=q.readUInt16LE(x0.CENNAM),V=q.readUInt16LE(x0.CENEXT),K=q.readUInt16LE(x0.CENCOM),z=q.readUInt16LE(x0.CENDSK),L=q.readUInt16LE(x0.CENATT),H=q.readUInt32LE(x0.CENATX),O=q.readUInt32LE(x0.CENOFF)},localHeaderToBinary:function(){var q=Buffer.alloc(x0.LOCHDR);return q.writeUInt32LE(x0.LOCSIG,0),q.writeUInt16LE(J,x0.LOCVER),q.writeUInt16LE(X&~x0.FLG_DESC,x0.LOCFLG),q.writeUInt16LE(Q,x0.LOCHOW),q.writeUInt32LE(Y,x0.LOCTIM),q.writeUInt32LE(W,x0.LOCCRC),q.writeUInt32LE(G,x0.LOCSIZ),q.writeUInt32LE(Z,x0.LOCLEN),q.writeUInt16LE(j,x0.LOCNAM),q.writeUInt16LE(B.extraLen,x0.LOCEXT),q},centralHeaderToBinary:function(){var q=Buffer.alloc(x0.CENHDR+j+V+K);return q.writeUInt32LE(x0.CENSIG,0),q.writeUInt16LE($,x0.CENVEM),q.writeUInt16LE(J,x0.CENVER),q.writeUInt16LE(X&~x0.FLG_DESC,x0.CENFLG),q.writeUInt16LE(Q,x0.CENHOW),q.writeUInt32LE(Y,x0.CENTIM),q.writeUInt32LE(W,x0.CENCRC),q.writeUInt32LE(G,x0.CENSIZ),q.writeUInt32LE(Z,x0.CENLEN),q.writeUInt16LE(j,x0.CENNAM),q.writeUInt16LE(V,x0.CENEXT),q.writeUInt16LE(K,x0.CENCOM),q.writeUInt16LE(z,x0.CENDSK),q.writeUInt16LE(L,x0.CENATT),q.writeUInt32LE(H,x0.CENATX),q.writeUInt32LE(O,x0.CENOFF),q},toJSON:function(){let q=function(w){return w+" bytes"};return{made:$,version:J,flags:X,method:wU.methodToString(Q),time:this.time,crc:"0x"+W.toString(16).toUpperCase(),compressedSize:q(G),size:q(Z),fileNameLength:q(j),extraLength:q(V),commentLength:q(K),diskNumStart:z,inAttr:L,attr:H,offset:O,centralHeaderSize:q(x0.CENHDR+j+V+K)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var nw$=o((eP1,cw$)=>{var AQ=yB(),K1=AQ.Constants;cw$.exports=function(){var $=0,J=0,X=0,Q=0,Y=0;let W=()=>$>K1.EF_ZIP64_OR_16||J>K1.EF_ZIP64_OR_16||X>K1.EF_ZIP64_OR_32||Q>K1.EF_ZIP64_OR_32;return{get diskEntries(){return $},set diskEntries(G){$=J=G},get totalEntries(){return J},set totalEntries(G){J=$=G},get size(){return X},set size(G){X=G},get offset(){return Q},set offset(G){Q=G},get commentLength(){return Y},set commentLength(G){Y=G},get mainHeaderSize(){return(W()?K1.ZIP64HDR+K1.END64HDR:0)+K1.ENDHDR+Y},loadFromBinary:function(G){if((G.length!==K1.ENDHDR||G.readUInt32LE(0)!==K1.ENDSIG)&&(G.length<K1.ZIP64HDR||G.readUInt32LE(0)!==K1.ZIP64SIG))throw AQ.Errors.INVALID_END();if(G.readUInt32LE(0)===K1.ENDSIG)$=G.readUInt16LE(K1.ENDSUB),J=G.readUInt16LE(K1.ENDTOT),X=G.readUInt32LE(K1.ENDSIZ),Q=G.readUInt32LE(K1.ENDOFF),Y=G.readUInt16LE(K1.ENDCOM);else $=AQ.readBigUInt64LE(G,K1.ZIP64SUB),J=AQ.readBigUInt64LE(G,K1.ZIP64TOT),X=AQ.readBigUInt64LE(G,K1.ZIP64SIZB),Q=AQ.readBigUInt64LE(G,K1.ZIP64OFF),Y=0},toBinary:function(){if(!W()){var G=Buffer.alloc(K1.ENDHDR+Y);return G.writeUInt32LE(K1.ENDSIG,0),G.writeUInt32LE(0,4),G.writeUInt16LE($,K1.ENDSUB),G.writeUInt16LE(J,K1.ENDTOT),G.writeUInt32LE(X,K1.ENDSIZ),G.writeUInt32LE(Q,K1.ENDOFF),G.writeUInt16LE(Y,K1.ENDCOM),G.fill(" ",K1.ENDHDR),G}var G=Buffer.alloc(this.mainHeaderSize);let Z=0;G.writeUInt32LE(K1.ZIP64SIG,Z),AQ.writeBigUInt64LE(G,K1.ZIP64HDR-K1.ZIP64LEAD,Z+K1.ZIP64SIZE),G.writeUInt16LE(45,Z+K1.ZIP64VEM),G.writeUInt16LE(45,Z+K1.ZIP64VER),G.writeUInt32LE(0,Z+K1.ZIP64DSK),G.writeUInt32LE(0,Z+K1.ZIP64DSKDIR),AQ.writeBigUInt64LE(G,$,Z+K1.ZIP64SUB),AQ.writeBigUInt64LE(G,J,Z+K1.ZIP64TOT),AQ.writeBigUInt64LE(G,X,Z+K1.ZIP64SIZB),AQ.writeBigUInt64LE(G,Q,Z+K1.ZIP64OFF);let j=Q+X;return Z+=K1.ZIP64HDR,G.writeUInt32LE(K1.END64SIG,Z),G.writeUInt32LE(0,Z+K1.END64START),AQ.writeBigUInt64LE(G,j,Z+K1.END64OFF),G.writeUInt32LE(1,Z+K1.END64NUMDISKS),Z+=K1.END64HDR,G.writeUInt32LE(K1.ENDSIG,Z),G.writeUInt32LE(0,Z+4),G.writeUInt16LE(Math.min($,K1.EF_ZIP64_OR_16),Z+K1.ENDSUB),G.writeUInt16LE(Math.min(J,K1.EF_ZIP64_OR_16),Z+K1.ENDTOT),G.writeUInt32LE(Math.min(X,K1.EF_ZIP64_OR_32),Z+K1.ENDSIZ),G.writeUInt32LE(Math.min(Q,K1.EF_ZIP64_OR_32),Z+K1.ENDOFF),G.writeUInt16LE(Y,Z+K1.ENDCOM),G.fill(" ",Z+K1.ENDHDR),G},toJSON:function(){let G=function(Z,j){let V=Z.toString(16).toUpperCase();while(V.length<j)V="0"+V;return"0x"+V};return{diskEntries:$,totalEntries:J,size:X+" bytes",offset:G(Q,4),commentLength:Y}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var We=o((OH0)=>{OH0.EntryHeader=pw$();OH0.MainHeader=nw$()});var iw$=o((JT1,dw$)=>{dw$.exports=function($){var J=q0("zlib"),X={chunkSize:(parseInt($.length/1024)+1)*1024};return{deflate:function(){return J.deflateRawSync($,X)},deflateAsync:function(Q){var Y=J.createDeflateRaw(X),W=[],G=0;Y.on("data",function(Z){W.push(Z),G+=Z.length}),Y.on("end",function(){var Z=Buffer.alloc(G),j=0;Z.fill(0);for(var V=0;V<W.length;V++){var K=W[V];K.copy(Z,j),j+=K.length}Q&&Q(Z)}),Y.end($)}}}});var rw$=o((XT1,ow$)=>{var FH0=+(process?.versions?.node??"").split(".")[0]||0;ow$.exports=function($,J){var X=q0("zlib");let Q=FH0>=15&&J>0?{maxOutputLength:J}:{};return{inflate:function(){return X.inflateRawSync($,Q)},inflateAsync:function(Y){var W=X.createInflateRaw(Q),G=[],Z=0;W.on("data",function(j){G.push(j),Z+=j.length}),W.on("end",function(){var j=Buffer.alloc(Z),V=0;j.fill(0);for(var K=0;K<G.length;K++){var z=G[K];z.copy(j,V),V+=z.length}Y&&Y(j)}),W.end($)}}}});var $N$=o((QT1,ew$)=>{var{randomFillSync:tw$}=q0("crypto"),qH0=Vb(),wH0=new Uint32Array(256).map(($,J)=>{for(let X=0;X<8;X++)if((J&1)!==0)J=J>>>1^3988292384;else J>>>=1;return J>>>0}),sw$=($,J)=>Math.imul($,J)>>>0,aw$=($,J)=>{return wH0[($^J)&255]^$>>>8},k_=()=>{if(typeof tw$==="function")return tw$(Buffer.alloc(12));else return k_.node()};k_.node=()=>{let $=Buffer.alloc(12),J=$.length;for(let X=0;X<J;X++)$[X]=Math.random()*256&255;return $};var Kb={genSalt:k_};function Ub($){let J=Buffer.isBuffer($)?$:Buffer.from($);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let X=0;X<J.length;X++)this.updateKeys(J[X])}Ub.prototype.updateKeys=function($){let J=this.keys;return J[0]=aw$(J[0],$),J[1]+=J[0]&255,J[1]=sw$(J[1],134775813)+1,J[2]=aw$(J[2],J[1]>>>24),$};Ub.prototype.next=function(){let $=(this.keys[2]|2)>>>0;return sw$($,$^1)>>8&255};function NH0($){let J=new Ub($);return function(X){let Q=Buffer.alloc(X.length),Y=0;for(let W of X)Q[Y++]=J.updateKeys(W^J.next());return Q}}function AH0($){let J=new Ub($);return function(X,Q,Y=0){if(!Q)Q=Buffer.alloc(X.length);for(let W of X){let G=J.next();Q[Y++]=W^G,J.updateKeys(W)}return Q}}function _H0($,J,X){if(!$||!Buffer.isBuffer($)||$.length<12)return Buffer.alloc(0);let Q=NH0(X),Y=Q($.slice(0,12)),W=(J.flags&8)===8?J.timeHighByte:J.crc>>>24;if(Y[11]!==W)throw qH0.WRONG_PASSWORD();return Q($.slice(12))}function MH0($){if(Buffer.isBuffer($)&&$.length>=12)Kb.genSalt=function(){return $.slice(0,12)};else if($==="node")Kb.genSalt=k_.node;else Kb.genSalt=k_}function RH0($,J,X,Q=!1){if($==null)$=Buffer.alloc(0);if(!Buffer.isBuffer($))$=Buffer.from($.toString());let Y=AH0(X),W=Kb.genSalt();if(W[11]=J.crc>>>24&255,Q)W[10]=J.crc>>>16&255;let G=Buffer.alloc($.length+12);return Y(W,G),Y($,G,12)}ew$.exports={decrypt:_H0,encrypt:RH0,_salter:MH0}});var JN$=o((EH0)=>{EH0.Deflater=iw$();EH0.Inflater=rw$();EH0.ZipCrypto=$N$()});var Ze=o((WT1,XN$)=>{var U8=yB(),SH0=We(),EX=U8.Constants,Ge=JN$();XN$.exports=function($,J){var X=new SH0.EntryHeader,Q=Buffer.alloc(0),Y=Buffer.alloc(0),W=!1,G=null,Z=Buffer.alloc(0),j=Buffer.alloc(0),V=!0;let K=$,z=typeof K.decoder==="object"?K.decoder:U8.decoder;V=z.hasOwnProperty("efs")?z.efs:!1;function L(){if(!J||!(J instanceof Uint8Array))return Buffer.alloc(0);return j=X.loadLocalHeaderFromBinary(J),J.slice(X.realDataOffset,X.realDataOffset+X.compressedSize)}function H(q){let w=X.flags_desc||X.localHeader.flags_desc?X.crc:X.localHeader.crc;return U8.crc32(q)===w}function O(q,w,M){if(typeof w>"u"&&typeof q==="string")M=q,q=void 0;if(W){if(q&&w)w(Buffer.alloc(0),U8.Errors.DIRECTORY_CONTENT_ERROR());return Buffer.alloc(0)}var C=L();if(C.length===0){if(q&&w)w(C);return C}if(X.encrypted){if(typeof M!=="string"&&!Buffer.isBuffer(M))throw U8.Errors.INVALID_PASS_PARAM();C=Ge.ZipCrypto.decrypt(C,X,M)}var f;switch(X.method){case U8.Constants.STORED:if(f=Buffer.alloc(C.length),C.copy(f),!H(f)){if(q&&w)w(f,U8.Errors.BAD_CRC());throw U8.Errors.BAD_CRC()}else{if(q&&w)w(f);return f}case U8.Constants.DEFLATED:var I=new Ge.Inflater(C,X.size);if(!q){if(f=I.inflate(),!H(f))throw U8.Errors.BAD_CRC(`"${z.decode(Q)}"`);return f}else I.inflateAsync(function(c){if(w)if(!H(c))w(c,U8.Errors.BAD_CRC());else w(c)});break;default:if(q&&w)w(Buffer.alloc(0),U8.Errors.UNKNOWN_METHOD());throw U8.Errors.UNKNOWN_METHOD()}}function B(q,w){if((!G||!G.length)&&Buffer.isBuffer(J)){if(q&&w)w(L());return L()}if(G.length&&!W){var M;switch(X.method){case U8.Constants.STORED:if(X.compressedSize=X.size,M=Buffer.alloc(G.length),G.copy(M),q&&w)w(M);return M;default:case U8.Constants.DEFLATED:var C=new Ge.Deflater(G);if(!q){var f=C.deflate();return X.compressedSize=f.length,f}else C.deflateAsync(function(I){M=Buffer.alloc(I.length),X.compressedSize=I.length,I.copy(M),w&&w(M)});C=null;break}}else if(q&&w)w(Buffer.alloc(0));else return Buffer.alloc(0)}function F(q,w){return U8.readBigUInt64LE(q,w)}function A(q){try{var w=0,M,C,f;while(w+4<q.length)if(M=q.readUInt16LE(w),w+=2,C=q.readUInt16LE(w),w+=2,f=q.slice(w,w+C),w+=C,EX.ID_ZIP64===M)_(f)}catch(I){throw U8.Errors.EXTRA_FIELD_PARSE_ERROR()}}function _(q){var w,M,C,f;if(q.length>=EX.EF_ZIP64_SCOMP){if(w=F(q,EX.EF_ZIP64_SUNCOMP),X.size===EX.EF_ZIP64_OR_32)X.size=w}if(q.length>=EX.EF_ZIP64_RHO){if(M=F(q,EX.EF_ZIP64_SCOMP),X.compressedSize===EX.EF_ZIP64_OR_32)X.compressedSize=M}if(q.length>=EX.EF_ZIP64_DSN){if(C=F(q,EX.EF_ZIP64_RHO),X.offset===EX.EF_ZIP64_OR_32)X.offset=C}if(q.length>=EX.EF_ZIP64_DSN+4){if(f=q.readUInt32LE(EX.EF_ZIP64_DSN),X.diskNumStart===EX.EF_ZIP64_OR_16)X.diskNumStart=f}}return{get entryName(){return z.decode(Q)},get rawEntryName(){return Q},set entryName(q){Q=U8.toBuffer(q,z.encode);var w=Q[Q.length-1];W=w===47||w===92,X.fileNameLength=Q.length},get efs(){if(typeof V==="function")return V(this.entryName);else return V},get extra(){return Z},set extra(q){Z=q,X.extraLength=q.length,A(q)},get comment(){return z.decode(Y)},set comment(q){if(Y=U8.toBuffer(q,z.encode),X.commentLength=Y.length,Y.length>65535)throw U8.Errors.COMMENT_TOO_LONG()},get name(){let q=z.decode(Q);return W?q.replace(/[/\\]$/,"").split("/").pop():q.split("/").pop()},get isDirectory(){return W},getCompressedData:function(){return B(!1,null)},getCompressedDataAsync:function(q){B(!0,q)},setData:function(q){if(G=U8.toBuffer(q,U8.decoder.encode),!W&&G.length)X.size=G.length,X.method=U8.Constants.DEFLATED,X.crc=U8.crc32(q),X.changed=!0;else X.method=U8.Constants.STORED},getData:function(q){if(X.changed)return G;else return O(!1,null,q)},getDataAsync:function(q,w){if(X.changed)q(G);else O(!0,q,w)},set attr(q){X.attr=q},get attr(){return X.attr},set header(q){X.loadFromBinary(q)},get header(){return X},packCentralHeader:function(){X.flags_efs=this.efs,X.extraLength=Z.length;var q=X.centralHeaderToBinary(),w=U8.Constants.CENHDR;return Q.copy(q,w),w+=Q.length,Z.copy(q,w),w+=X.extraLength,Y.copy(q,w),q},packLocalHeader:function(){let q=0;X.flags_efs=this.efs,X.extraLocalLength=j.length;let w=X.localHeaderToBinary(),M=Buffer.alloc(w.length+Q.length+X.extraLocalLength);return w.copy(M,q),q+=w.length,Q.copy(M,q),q+=Q.length,j.copy(M,q),q+=j.length,M},toJSON:function(){let q=function(w){return"<"+(w&&w.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:X.toJSON(),compressedData:q(J),data:q(G)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var WN$=o((GT1,YN$)=>{var QN$=Ze(),IH0=We(),p5=yB();YN$.exports=function($,J){var X=[],Q=Object.create(null),Y=Buffer.alloc(0),W=new IH0.MainHeader,G=!1,Z=null;let j=new Set,V=J,{noSort:K,decoder:z}=V;if($)O(V.readEntries);else G=!0;function L(){let F=new Set;for(let A of Object.keys(Q)){let _=A.split("/");if(_.pop(),!_.length)continue;for(let q=0;q<_.length;q++){let w=_.slice(0,q+1).join("/")+"/";F.add(w)}}for(let A of F)if(!(A in Q)){let _=new QN$(V);_.entryName=A,_.attr=16,_.temporary=!0,X.push(_),Q[_.entryName]=_,j.add(_)}}function H(){if(G=!0,Q=Object.create(null),W.diskEntries>($.length-W.offset)/p5.Constants.CENHDR)throw p5.Errors.DISK_ENTRY_TOO_LARGE();X=Array(W.diskEntries);var F=W.offset;for(var A=0;A<X.length;A++){var _=F,q=new QN$(V,$);if(q.header=$.slice(_,_+=p5.Constants.CENHDR),q.entryName=$.slice(_,_+=q.header.fileNameLength),q.header.extraLength)q.extra=$.slice(_,_+=q.header.extraLength);if(q.header.commentLength)q.comment=$.slice(_,_+q.header.commentLength);F+=q.header.centralHeaderSize,X[A]=q,Q[q.entryName]=q}j.clear(),L()}function O(F){var A=$.length-p5.Constants.ENDHDR,_=Math.max(0,A-65535),q=_,w=$.length,M=-1,C=0;if(typeof V.trailingSpace==="boolean"?V.trailingSpace:!1)_=0;for(A;A>=q;A--){if($[A]!==80)continue;if($.readUInt32LE(A)===p5.Constants.ENDSIG){M=A,C=A,w=A+p5.Constants.ENDHDR,q=A-p5.Constants.END64HDR;continue}if($.readUInt32LE(A)===p5.Constants.END64SIG){q=_;continue}if($.readUInt32LE(A)===p5.Constants.ZIP64SIG){M=A,w=A+p5.readBigUInt64LE($,A+p5.Constants.ZIP64SIZE)+p5.Constants.ZIP64LEAD;break}}if(M==-1)throw p5.Errors.INVALID_FORMAT();if(W.loadFromBinary($.slice(M,w)),W.commentLength)Y=$.slice(C+p5.Constants.ENDHDR);if(F)H()}function B(){if(X.length>1&&!K)X=X.map((F)=>({entry:F,key:F.entryName.toLowerCase()})).sort((F,A)=>F.key.localeCompare(A.key)).map((F)=>F.entry)}return{get entries(){if(!G)H();return X.filter((F)=>!j.has(F))},get comment(){return z.decode(Y)},set comment(F){Y=p5.toBuffer(F,z.encode),W.commentLength=Y.length},getEntryCount:function(){if(!G)return W.diskEntries;return X.length},forEach:function(F){this.entries.forEach(F)},getEntry:function(F){if(!G)H();return Q[F]||null},setEntry:function(F){if(!G)H();X.push(F),Q[F.entryName]=F,W.totalEntries=X.length},deleteFile:function(F,A=!0){if(!G)H();let _=Q[F];this.getEntryChildren(_,A).map((w)=>w.entryName).forEach(this.deleteEntry)},deleteEntry:function(F){if(!G)H();let A=Q[F],_=X.indexOf(A);if(_>=0)X.splice(_,1),delete Q[F],W.totalEntries=X.length},getEntryChildren:function(F,A=!0){if(!G)H();if(typeof F==="object")if(F.isDirectory&&A){let _=[],q=F.entryName;for(let w of X)if(w.entryName.startsWith(q))_.push(w);return _}else return[F];return[]},getChildCount:function(F){if(F&&F.isDirectory){let A=this.getEntryChildren(F);return A.includes(F)?A.length-1:A.length}return 0},compressToBuffer:function(){if(!G)H();B();let F=[],A=[],_=0,q=0;W.size=0,W.offset=0;let w=0;for(let f of this.entries){let I=f.getCompressedData();f.header.offset=q;let c=f.packLocalHeader(),h=c.length+I.length;q+=h,F.push(c),F.push(I);let r=f.packCentralHeader();A.push(r),W.size+=r.length,_+=h+r.length,w++}_+=W.mainHeaderSize,W.offset=q,W.totalEntries=w,q=0;let M=Buffer.alloc(_);for(let f of F)f.copy(M,q),q+=f.length;for(let f of A)f.copy(M,q),q+=f.length;let C=W.toBinary();if(Y)Y.copy(C,C.length-Y.length);return C.copy(M,q),$=M,G=!1,M},toAsyncBuffer:function(F,A,_,q){try{if(!G)H();B();let w=[],M=[],C=0,f=0,I=0;W.size=0,W.offset=0;let c=function(h){if(h.length>0){let r=h.shift(),t=r.entryName+r.extra.toString();if(_)_(t);r.getCompressedDataAsync(function(Y$){if(q)q(t);r.header.offset=f;let X$=r.packLocalHeader(),L$=X$.length+Y$.length;f+=L$,w.push(X$),w.push(Y$);let O$=r.packCentralHeader();M.push(O$),W.size+=O$.length,C+=L$+O$.length,I++,c(h)})}else{C+=W.mainHeaderSize,W.offset=f,W.totalEntries=I,f=0;let r=Buffer.alloc(C);w.forEach(function(Y$){Y$.copy(r,f),f+=Y$.length}),M.forEach(function(Y$){Y$.copy(r,f),f+=Y$.length});let t=W.toBinary();if(Y)Y.copy(t,t.length-Y.length);t.copy(r,f),$=r,G=!1,F(r)}};c(Array.from(this.entries))}catch(w){A(w)}}}}});var x_=o((ZT1,ZN$)=>{var r8=yB(),o8=q0("path"),kH0=Ze(),xH0=WN$(),c2=(...$)=>r8.findLast($,(J)=>typeof J==="boolean"),GN$=(...$)=>r8.findLast($,(J)=>typeof J==="string"),bH0=(...$)=>r8.findLast($,(J)=>typeof J==="function"),yH0={noSort:!1,readEntries:!1,method:r8.Constants.NONE,fs:null};ZN$.exports=function($,J){let X=null,Q=Object.assign(Object.create(null),yH0);if($&&typeof $==="object"){if(!($ instanceof Uint8Array)){if(Object.assign(Q,$),$=Q.input?Q.input:void 0,Q.input)delete Q.input}if(Buffer.isBuffer($))X=$,Q.method=r8.Constants.BUFFER,$=void 0}Object.assign(Q,J);let Y=new r8(Q),W=(O)=>{O.filter((B)=>B.attr).sort((B,F)=>F.path.length-B.path.length).forEach((B)=>Y.fs.chmodSync(B.path,B.attr))};if(typeof Q.decoder!=="object"||typeof Q.decoder.encode!=="function"||typeof Q.decoder.decode!=="function")Q.decoder=r8.decoder;if($&&typeof $==="string")if(Y.fs.existsSync($))Q.method=r8.Constants.FILE,Q.filename=$,X=Y.fs.readFileSync($);else throw r8.Errors.INVALID_FILENAME();let G=new xH0(X,Q),{canonical:Z,sanitize:j,zipnamefix:V}=r8;function K(O){if(O&&G){var B;if(typeof O==="string")B=G.getEntry(o8.posix.normalize(O));if(typeof O==="object"&&typeof O.entryName<"u"&&typeof O.header<"u")B=G.getEntry(O.entryName);if(B)return B}return null}function z(O){let{join:B,normalize:F,sep:A}=o8.posix;return B(o8.isAbsolute(O)?"/":".",F(A+O.split("\\").join(A)+A))}function L(O){if(O instanceof RegExp)return function(B){return function(F){return B.test(F)}}(O);else if(typeof O!=="function")return()=>!0;return O}let H=(O,B)=>{let F=B.slice(-1);return F=F===Y.sep?Y.sep:"",o8.relative(O,B)+F};return{readFile:function(O,B){var F=K(O);return F&&F.getData(B)||null},childCount:function(O){let B=K(O);if(B)return G.getChildCount(B)},readFileAsync:function(O,B){var F=K(O);if(F)F.getDataAsync(B);else B(null,"getEntry failed for:"+O)},readAsText:function(O,B){var F=K(O);if(F){var A=F.getData();if(A&&A.length)return A.toString(B||"utf8")}return""},readAsTextAsync:function(O,B,F){var A=K(O);if(A)A.getDataAsync(function(_,q){if(q){B(_,q);return}if(_&&_.length)B(_.toString(F||"utf8"));else B("")});else B("")},deleteFile:function(O,B=!0){var F=K(O);if(F)G.deleteFile(F.entryName,B)},deleteEntry:function(O){var B=K(O);if(B)G.deleteEntry(B.entryName)},addZipComment:function(O){G.comment=O},getZipComment:function(){return G.comment||""},addZipEntryComment:function(O,B){var F=K(O);if(F)F.comment=B},getZipEntryComment:function(O){var B=K(O);if(B)return B.comment||"";return""},updateFile:function(O,B){var F=K(O);if(F)F.setData(B)},addLocalFile:function(O,B,F,A){if(Y.fs.existsSync(O)){B=B?z(B):"";let _=o8.win32.basename(o8.win32.normalize(O));B+=F?F:_;let q=Y.fs.statSync(O),w=q.isFile()?Y.fs.readFileSync(O):Buffer.alloc(0);if(q.isDirectory())B+=Y.sep;this.addFile(B,w,A,q)}else throw r8.Errors.FILE_NOT_FOUND(O)},addLocalFileAsync:function(O,B){O=typeof O==="object"?O:{localPath:O};let F=o8.resolve(O.localPath),{comment:A}=O,{zipPath:_,zipName:q}=O,w=this;Y.fs.stat(F,function(M,C){if(M)return B(M,!1);_=_?z(_):"";let f=o8.win32.basename(o8.win32.normalize(F));if(_+=q?q:f,C.isFile())Y.fs.readFile(F,function(I,c){if(I)return B(I,!1);return w.addFile(_,c,A,C),setImmediate(B,void 0,!0)});else if(C.isDirectory())return _+=Y.sep,w.addFile(_,Buffer.alloc(0),A,C),setImmediate(B,void 0,!0)})},addLocalFolder:function(O,B,F){if(F=L(F),B=B?z(B):"",O=o8.normalize(O),Y.fs.existsSync(O)){let A=Y.findFiles(O),_=this;if(A.length)for(let q of A){let w=o8.join(B,H(O,q));if(F(w))_.addLocalFile(q,o8.dirname(w))}}else throw r8.Errors.FILE_NOT_FOUND(O)},addLocalFolderAsync:function(O,B,F,A){A=L(A),F=F?z(F):"",O=o8.normalize(O);var _=this;Y.fs.open(O,"r",function(q){if(q&&q.code==="ENOENT")B(void 0,r8.Errors.FILE_NOT_FOUND(O));else if(q)B(void 0,q);else{var w=Y.findFiles(O),M=-1,C=function(){if(M+=1,M<w.length){var f=w[M],I=H(O,f).split("\\").join("/");if(I=I.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(I))Y.fs.stat(f,function(c,h){if(c)B(void 0,c);if(h.isFile())Y.fs.readFile(f,function(r,t){if(r)B(void 0,r);else _.addFile(F+I,t,"",h),C()});else _.addFile(F+I+"/",Buffer.alloc(0),"",h),C()});else process.nextTick(()=>{C()})}else B(!0,void 0)};C()}})},addLocalFolderAsync2:function(O,B){let F=this;O=typeof O==="object"?O:{localPath:O};let A=o8.resolve(z(O.localPath)),{zipPath:_,filter:q,namefix:w}=O;if(q instanceof RegExp)q=function(f){return function(I){return f.test(I)}}(q);else if(typeof q!=="function")q=function(){return!0};if(_=_?z(_):"",w==="latin1")w=(f)=>f.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(typeof w!=="function")w=(f)=>f;let M=(f)=>o8.join(_,w(H(A,f))),C=(f)=>o8.win32.basename(o8.win32.normalize(w(f)));Y.fs.open(A,"r",function(f){if(f&&f.code==="ENOENT")B(void 0,r8.Errors.FILE_NOT_FOUND(A));else if(f)B(void 0,f);else Y.findFilesAsync(A,function(I,c){if(I)return B(I);if(c=c.filter((h)=>q(M(h))),!c.length)B(void 0,!1);setImmediate(c.reverse().reduce(function(h,r){return function(t,Y$){if(t||Y$===!1)return setImmediate(h,t,!1);F.addLocalFileAsync({localPath:r,zipPath:o8.dirname(M(r)),zipName:C(r)},h)}},B))})})},addLocalFolderPromise:function(O,B){return new Promise((F,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:O},B),(_,q)=>{if(_)A(_);if(q)F(this)})})},addFile:function(O,B,F,A){O=V(O);let _=K(O),q=_!=null;if(!q)_=new kH0(Q),_.entryName=O;_.comment=F||"";let w=typeof A==="object"&&A instanceof Y.fs.Stats;if(w)_.header.time=A.mtime;var M=_.isDirectory?16:0;let C=_.isDirectory?16384:32768;if(w)C|=4095&A.mode;else if(typeof A==="number")C|=4095&A;else C|=_.isDirectory?493:420;if(M=(M|C<<16)>>>0,_.attr=M,_.setData(B),!q)G.setEntry(_);return _},getEntries:function(O){return G.password=O,G?G.entries:[]},getEntry:function(O){return K(O)},getEntryCount:function(){return G.getEntryCount()},forEach:function(O){return G.forEach(O)},extractEntryTo:function(O,B,F,A,_,q){A=c2(!1,A),_=c2(!1,_),F=c2(!0,F),q=GN$(_,q);var w=K(O);if(!w)throw r8.Errors.NO_ENTRY();var M=Z(w.entryName),C=j(B,q&&!w.isDirectory?Z(q):F?M:o8.basename(M));if(w.isDirectory){var f=G.getEntryChildren(w);return f.forEach(function(h){if(h.isDirectory)return;var r=h.getData();if(!r)throw r8.Errors.CANT_EXTRACT_FILE();var t=Z(F?h.entryName:h.entryName.substring(w.entryName.length)),Y$=j(B,t);let X$=_?h.header.fileAttr:void 0;Y.writeFileTo(Y$,r,A,X$)}),!0}var I=w.getData(G.password);if(!I)throw r8.Errors.CANT_EXTRACT_FILE();if(Y.fs.existsSync(C)&&!A)throw r8.Errors.CANT_OVERRIDE();let c=_?O.header.fileAttr:void 0;return Y.writeFileTo(C,I,A,c),!0},test:function(O){if(!G)return!1;for(var B of G.entries)try{if(B.isDirectory)continue;var F=B.getData(O);if(!F)return!1}catch(A){return!1}return!0},extractAllTo:function(O,B,F,A){if(F=c2(!1,F),A=GN$(F,A),B=c2(!1,B),!G)throw r8.Errors.NO_ZIP();let _=[];G.entries.forEach(function(q){var w=j(O,Z(q.entryName));if(q.isDirectory){if(Y.makeDir(w),F)_.push({path:w,attr:q.header.fileAttr});return}var M=q.getData(A);if(!M)throw r8.Errors.CANT_EXTRACT_FILE();let C=F?q.header.fileAttr:void 0;Y.writeFileTo(w,M,B,C);try{Y.fs.utimesSync(w,q.header.time,q.header.time)}catch(f){}}),W(_)},extractAllToAsync:function(O,B,F,A){if(A=bH0(B,F,A),F=c2(!1,F),B=c2(!1,B),!A)return new Promise((I,c)=>{this.extractAllToAsync(O,B,F,function(h){if(h)c(h);else I(this)})});if(!G){A(r8.Errors.NO_ZIP());return}O=o8.resolve(O);let _=(I)=>j(O,o8.normalize(Z(I.entryName))),q=(I,c)=>Error(I+': "'+c+'"'),w=[],M=[];G.entries.forEach((I)=>{if(I.isDirectory)w.push(I);else M.push(I)});let C=[];for(let I of w){let c=_(I),h=F?I.header.fileAttr:void 0;try{Y.makeDir(c)}catch(r){A(q("Unable to create folder",c));continue}if(h)C.push({path:c,attr:h});try{Y.fs.utimesSync(c,I.header.time,I.header.time)}catch(r){}}let f=(I)=>{if(!I)try{W(C)}catch(c){return A(q("Unable to set folder permissions",c.path||""))}A(I)};M.reverse().reduce(function(I,c){return function(h){if(h)I(h);else{let r=o8.normalize(Z(c.entryName)),t=j(O,r);c.getDataAsync(function(Y$,X$){if(X$)I(X$);else if(!Y$)I(r8.Errors.CANT_EXTRACT_FILE());else{let L$=F?c.header.fileAttr:void 0;Y.writeFileToAsync(t,Y$,B,L$,function(O$){if(!O$)return I(q("Unable to write file",t));Y.fs.utimes(t,c.header.time,c.header.time,function(){I()})})}})}}},f)()},writeZip:function(O,B){if(arguments.length===1){if(typeof O==="function")B=O,O=""}if(!O&&Q.filename)O=Q.filename;if(!O)return;var F=G.compressToBuffer();if(F){var A=Y.writeFileTo(O,F,!0);if(typeof B==="function")B(!A?Error("failed"):null,"")}},writeZipPromise:function(O,B){let{overwrite:F,perm:A}=Object.assign({overwrite:!0},B);return new Promise((_,q)=>{if(!O&&Q.filename)O=Q.filename;if(!O)q("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((w)=>{let M=(C)=>C?_(C):q("ADM-ZIP: Wasn't able to write zip file");Y.writeFileToAsync(O,w,F,A,M)},q)})},toBufferPromise:function(){return new Promise((O,B)=>{G.toAsyncBuffer(O,B)})},toBuffer:function(O,B,F,A){if(typeof O==="function")return G.toAsyncBuffer(O,B,F,A),null;return G.compressToBuffer()}}}});function jN$($,J,X=j5){if(X.length===0)return"";let Y=$.trim().toLowerCase()===Z5?X[0]:X.find((W)=>W.version===$);if(!Y)return"";return J==="android"?Y.apkSha256:Y.ipaSha256}function Lb($=process.env,J=j5){if(J.length===0)return;let X=Z4($);return X===Z5?J[0]:J.find((Q)=>Q.version===X)}function Ve($=process.env,J=j5){return Lb($,J)?.runnerSha256??""}function VN$($=process.env,J=j5){return Lb($,J)?.runnerSha256Target??"runner"}function fH0($=j5){if($.length===0)return Z5;return $[0].version}function E9($,J=j5){if($===Z5)return fH0(J);return $}function gH0($){let J=$[KN$];return J==="1"||J?.toLowerCase()==="true"}function Ke($,J,X=process.env){let Q;try{Q=new URL($)}catch{throw new R(`${J} must be an absolute URL, for example https://mirror.example/auto-mobile.`)}if(Q.protocol==="https:")return;if(gH0(X))return;throw new R(`${J} must use https:// (got ${Q.protocol}//). Plaintext/non-TLS asset downloads are a confidentiality and downgrade risk. Set ${KN$}=1 to opt out for a trusted loopback/dev mirror.`)}function Z4($=process.env){let J=$[hH0]?.trim();if(!J||J.length===0)return Z5;return J.toLowerCase()===Z5?Z5:J}function pj($=process.env){return Z4($)!==Z5}function n2($=process.env,J=j5){let X=Z4($);if(X===Z5)return J.length>0;return J.some((Q)=>Q.version===X)}function Hb($=process.env){let J=$[zb]?.trim();if(J&&J.length>0){let X;try{X=new URL(J)}catch{throw new R(`${zb} must be an absolute URL, for example https://mirror.example/auto-mobile.`)}if(J.includes("?")||J.includes("#"))throw new R(`${zb} must not include a query string or fragment; use a path-only base URL such as ${X.origin}${X.pathname.replace(/\/+$/,"")}.`);return Ke(`${X.origin}${X.pathname}`,zb,$),`${X.origin}${X.pathname}`.replace(/\/+$/,"")}return je}function Ob($,J,X=je,Q=j5){let Y=E9(J,Q);if(Y===Z5){if(X===je)return`https://github.com/kaeawc/auto-mobile/releases/latest/download/${$}`;return`${X}/latest/${$}`}return`${X}/${Y}/${$}`}function cj($=process.env,J=j5){return Ob("control-proxy-debug.apk",Z4($),Hb($),J)}function d2($=process.env,J=j5){return Ob("control-proxy.ipa",Z4($),Hb($),J)}function NU($=process.env){return jN$(Z4($),"android")}function i2($=process.env){return jN$(Z4($),"ios")}function UN$($=process.env,J=j5){return Ob(uH0,Z4($),Hb($),J)}function zN$($=process.env,J=j5){return Lb($,J)?.videoJarSha256??""}function LN$($=process.env,J=j5){return Ob(Ue,Z4($),Hb($),J)}function HN$($=process.env,J=j5){return Lb($,J)?.screenCaptureHelperSha256??""}function T7($=process.env){return`${vH0}@${E9(Z4($))}`}var Z5="latest",j5,vH0="@kaeawc/auto-mobile",hH0="AUTOMOBILE_VERSION",zb="AUTOMOBILE_ASSET_BASE_URL",KN$="AUTOMOBILE_ALLOW_INSECURE_ASSET_URL",je="https://github.com/kaeawc/auto-mobile/releases/download",uH0="automobile-video.jar",Ue="screen-capture-helper-macos-universal.zip",VT1,KT1,UT1,zT1,Bb="",LT1;var TJ=D(()=>{l4();j5=[{version:"0.0.51",apkSha256:"e9da610303113dd13094b3f885090b846f5b8705ac203b09deeb267801049255",ipaSha256:"db5606723087f7b973893d4adefcdeb6aadf1da0e2bcc435ce1fe8787bafb712",runnerSha256:"abba47298118068aaad3b8ea4502d685263b6e83cd2c30bb0518840cb8443202",runnerSha256Target:"xctest",videoJarSha256:"e5ce791aed17a1bf391db5737367a8ca2d7792b805f2fa4235e4ec7f8cee062c",screenCaptureHelperSha256:"a46ec61cdd2c3ab64e0f621f3498726578e52bee407d16cd90cde32ca8164798"},{version:"0.0.50",apkSha256:"8007f267d566144d805d29d22fb0e69790d34edcdbdd0d444bad6d80175943e2",ipaSha256:"838025a37b8a9f0d15b0b1ad06ff40e5a2b0b3e09eeca845f9a874d3bac4030d",runnerSha256:"5e53b1614986f90b875e5ada0a8c97f5343c22e70bdaeafd9a8389e5b6ef78ae",runnerSha256Target:"xctest",videoJarSha256:"254d1bad102a96b1e8e90ee9ff6ff991aa6d65f7a36a35c3887db91f369ea12e",screenCaptureHelperSha256:"965a49653d0c8bc8a88d45e1919ef0a62267d6774c50579411076dbe397bb89d"},{version:"0.0.49",apkSha256:"c1023110ebbd12c012880b08be6715d2389294fd24c4a147a40d1d342ec473da",ipaSha256:"dbeacd346a39976414432964de1250a3f356baf783cd3a83d916f0117e772d5b",runnerSha256:"fc033a529c67d373c6eca965ec063343b6164628d62e14eca220385810427ae6",runnerSha256Target:"xctest",videoJarSha256:"254d1bad102a96b1e8e90ee9ff6ff991aa6d65f7a36a35c3887db91f369ea12e",screenCaptureHelperSha256:"67079809a52e3cad50a38f04e4e25d795c0756b35352b377ba9609bebb62ab0f"},{version:"0.0.48",apkSha256:"059162e622fbe25bce40b32658c9749318a909eb8b48398648c77a84cf3c25aa",ipaSha256:"86558163f69a0bf36e69546dbf685d16d8f3bf05385f1f7795a164e3a5fddf96",runnerSha256:"ff000ff053a57a1dac1d552463e474fdea5346acb08c96051695554e73428317",runnerSha256Target:"xctest",videoJarSha256:"1cada2f3bc86cacbed76efc8e46c1e110cb0b046036502b422d67cce0725cf4b",screenCaptureHelperSha256:"f284e9863cedb2e02de25f526114fd4017eece1ce1e19337210647c7b49d1898"},{version:"0.0.47",apkSha256:"aa50a056447337ca14c251795b064e792879a28d088fe484fe57893a020b9323",ipaSha256:"ef5d10dd97d78d8e372680fffbb511335781b03ffbf0c91e2692048da4c5f143",runnerSha256:"078375d34d3e8bfa0c3171e3f1a6558d0ca2c0ca1f0c5999cb49077934fbfc0a",runnerSha256Target:"xctest",videoJarSha256:"5e3760d04436af89ec909586bd244d79cd7acec9b84993f4302fa7bf480916cb",screenCaptureHelperSha256:"501e1253ded9fa2f331051b88013b47ca37343a1966fc106d4fcaa5e9bbe4c39"},{version:"0.0.46",apkSha256:"00771c13f372baff325c659e2b40050e72951fd8adfc395cff667850a2a9b376",ipaSha256:"ef353a4f14fa7615810de891595d118ff193d43fcc940f936f4d11ae311dd563",screenCaptureHelperSha256:"da7e138266156eedda9f8cb98bb7d5b63f29ad28746a1c144a16122a1639e2b2",runnerSha256:"b0eb970aad424d1c0dd84261c26d74b8c95570ba0f3866f18f1755586184c51a",runnerSha256Target:"xctest",videoJarSha256:"3f3135e22fffed1e088bd434545eec873a5aec48c7c038cd2ffecdeb6b642c06"},{version:"0.0.45",apkSha256:"68dbf04ba3c1871da0ed9ec540e1dbfec08610dd2afc1706d4a7fd94d1c3b5b1",ipaSha256:"8c678b2d7ae4b5c25400f8fd53cb5e1f12d730950e0eef4e608dfb8b50dcd773",runnerSha256:"bb5234ca32636506e5b8e02662381895eaedeefbcf007598e3ee9b9ac3c501b5",runnerSha256Target:"xctest",videoJarSha256:"bae314fbaa3f3101ab5f7ba5eddc9bd77bb927c54cb508d38ed04ca9544b9a51"},{version:"0.0.44",apkSha256:"e95f2b14e218bc51e92a44680cf38ceca9c9143014b2f74b803f47650614cf39",ipaSha256:"73dd4551ef7226d67a46423f6925775fc10d68198913b5b23bc1cbdceb50b663",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.43",apkSha256:"7e4e2ce3c19b7473d171433186dbc7487df60ff6045dba66da7a320d31e63cd3",ipaSha256:"db0e3c4c172681068ae7ae24182f5569519b5fab034fbcf0e85abdc952b398dd",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.42",apkSha256:"cb00a835f58ce2d0344483f27b7c35036bb6faa973aa3fcc66fe67e75428abb0",ipaSha256:"de55b77ee0e821b4f08b7cd1b84f9a2706f69279422901546e2dc6fdd4cc3f0f",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.41",apkSha256:"ee1dff240e4dfc89b016197c80e929797485aa23292e061eee361b7404c772b4",ipaSha256:"01eaedef0cfcf38acd0a1fa8eebe08c3009e5db59320b23a045cd26506eb235c",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.40",apkSha256:"8e89fbab6462ac1ead1f3f0a334aff4f5f299e7ae72e192045cf75e893ca87aa",ipaSha256:"38adaed641ac6a8590773682e127a80a86c54e5804d47394e1b0cd437009b9ff",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.39",apkSha256:"eaad59dd85e17c4633098b772b9f761f2124ffb73a5ca7ede703a9b435046942",ipaSha256:"87a720544c83718e5b70c987aecf30d2e43bdb0f23163ac75ac225bb4aec0ae4",runnerSha256:""},{version:"0.0.38",apkSha256:"0fb955a617654695036642662634d042c2e3d278b8e1dce20ccb37e425f059f3",ipaSha256:"f5a4a485ff8ebf3bfd0d73c8b7b10769177b419ccd62e48db188bb5122a2fcde",runnerSha256:""},{version:"0.0.37",apkSha256:"f9b0cc92bf8f7416cdb0c458e16c7a41e4fdeefb80bb9429ab7c603388c99083",ipaSha256:"caccbfaa4da0015bab701a36b81ac87e3f3f3330cee77bb10ec8553724275f4f",runnerSha256:""},{version:"0.0.36",apkSha256:"b5f56bb0ab065c60385a22013c97ee706213eb16deb5d4bcfa42f0a707b8620a",ipaSha256:"40e973dc8c87149e40a616658c74d90e648c6514cc642a5c3dd4a45a187e7600",runnerSha256:""},{version:"0.0.35",apkSha256:"039b359bcf35f1ab6cc666005a57823d71a771a96bd9bcaf4f82f2ec945e306d",ipaSha256:"e6afdfd04a90d2388dc4604e7957d3eef87b90a51ca37c5457b8139a54728108",runnerSha256:""},{version:"0.0.34",apkSha256:"4dcee4f6a7359847d081c5e184c57ed100ad135af2e62f3abfc7b0defaa1153c",ipaSha256:"c2a26ca065c85e9f8d5cfcd6dbad1dbaf3ce38b18d770b0983f7bad62129e4a3",runnerSha256:""},{version:"0.0.33",apkSha256:"7289eba90b22890d3c36e05e99db72a545fa4becdf46df079885783a919e6aed",ipaSha256:"425dfa4db4ad5a4febc9f05ffc97df38f3a1098ccdd9330adff1c0b5c877697d",runnerSha256:""},{version:"0.0.32",apkSha256:"4c4a743af5d18ed58214e64b85986c9e2f2332b015edcf7d9d68a24cd6dfda21",ipaSha256:"40f4d9084d3368995b57c0e81c4fe85f38851353da9f789eaff93027aee456a0",runnerSha256:""},{version:"0.0.31",apkSha256:"0b5802ada8d9adccdb69ee140ae788b3251832c0605d2f6baa3e9b7a78260764",ipaSha256:"e60f8689fb6ddd5c06a5d2ff57569b264f407229afb986258d1ce20326dc24c7",runnerSha256:""},{version:"0.0.30",apkSha256:"a1be5e6240f204ee99540e99cc198f7c0b592dbaf3699330c14f6ded7d333ec3",ipaSha256:"5ac285dd5be16439d3a8a8973c98606920461acfce489830e54ee20759a7b235",runnerSha256:""},{version:"0.0.29",apkSha256:"b33a67c7efa84aca2b07faa965aecb3b1819b4defd441dcc8d3bf7e2af209cd8",ipaSha256:"d47c1aea4495270c1489cae361286ea1439c2ba4e7d5bcfd73f66e4580a6c45d",runnerSha256:""},{version:"0.0.28",apkSha256:"0f683d5939bc308afe038ea1259eb29997dff38af0795136a281ad305986e40e",ipaSha256:"eee7accfbca717bb8b89fafd0676f10d8bb08561c3fbd7a04750c9b12c2a7104",runnerSha256:""},{version:"0.0.27",apkSha256:"9966113ae44f38f3cf34544b1375d3c9a3706701edba45a1eec1f220b9c676cc",ipaSha256:"8620de6b014df18465876334f9ba8c106292f6c3059370eea2349f1e44db4f4d",runnerSha256:""},{version:"0.0.26",apkSha256:"2eb2f156fd27602c85003ab8f6e00d3e06850e84f5453d75b7494aa5bbed7be0",ipaSha256:"905df276d2224d31cbc5aa2258d2dcc60eaeb9813727081ddd32c95394fec411",runnerSha256:""},{version:"0.0.25",apkSha256:"f727079edb4906e3b7928dbb641e788543e86b11fff3fc1b76f0c51b9c8d6e5d",ipaSha256:"d8032cc1cebcb456b7232aa67fc42c89ff62729bacf141aa8f594ce6f8bcd980",runnerSha256:""},{version:"0.0.24",apkSha256:"9047795bc6098f4ec687c126123c73c423806a9fd52888af391d6fb5b94ac93f",ipaSha256:"1dd3e0370cb8ed01d8e1020558d8a2808f208bd947bafcf6688211eddc928bf8",runnerSha256:""},{version:"0.0.18",apkSha256:"fd3c8d9f0b8542eaad56c78b18cf8e5666367b04ae8c4af74d8aa6dd1c8d1834",ipaSha256:"2a5eec63bce2f9dfc227c0732fcce67378305e945604d5eedd0e3df48e37fd39",runnerSha256:""},{version:"0.0.17",apkSha256:"916033440931666644474f227c8e39d13d9c80c3515e4292cc5581fd5bd4cc2f",ipaSha256:"e4dcf064d024f2371b8fd79281000e2d49751ef95b8817d1494d685aeda746ac",runnerSha256:""}];VT1=cj({}),KT1=NU({}),UT1=d2({}),zT1=i2({}),LT1=Ve({})});import{createReadStream as mH0}from"fs";import{createHash as lH0}from"crypto";class c5{async computeFileSha256($){let J=lH0("sha256");return await new Promise((X,Q)=>{let Y=mH0($);Y.on("data",(W)=>J.update(W)),Y.on("error",Q),Y.on("end",()=>X())}),{checksum:J.digest("hex"),source:"node"}}}var AU=()=>{};import{execFile as pH0}from"child_process";import{createWriteStream as cH0}from"fs";import*as BN$ from"fs/promises";import nH0 from"http";import dH0 from"https";import*as DN$ from"path";import{promisify as iH0}from"util";class BY{async download($,J,X){if(X?.aborted)throw Error(`Download aborted before starting: ${$}`);await BN$.mkdir(DN$.dirname(J),{recursive:!0});try{await this.downloadWithCurl($,J,X);return}catch(Q){if(!this.isCommandUnavailable(Q,"curl"))throw Q;U.warn("[FileDownloader] curl unavailable, falling back to wget",{error:Q instanceof Error?Q.message:String(Q)})}try{await this.downloadWithWget($,J,X);return}catch(Q){if(!this.isCommandUnavailable(Q,"wget"))throw Q;U.warn("[FileDownloader] wget unavailable, falling back to Node HTTP",{error:Q instanceof Error?Q.message:String(Q)})}await this.downloadWithNodeHttp($,J,0,X)}async downloadWithCurl($,J,X){await ON$("curl",["--fail","--location","--retry","3","--retry-delay","1","--silent","--show-error","-o",J,$],{timeout:120000,maxBuffer:10485760,signal:X})}async downloadWithWget($,J,X){await ON$("wget",["--tries=3","--timeout=30","-O",J,$],{timeout:120000,maxBuffer:10485760,signal:X})}async downloadWithNodeHttp($,J,X,Q){if(X>5)throw Error(`Too many redirects while downloading ${$}`);await new Promise((Y,W)=>{let G=$.startsWith("https:")?dH0:nH0,Z=()=>{j.destroy(Error(`Download aborted: ${$}`))},j=G.get($,{headers:{"User-Agent":"auto-mobile"}},(V)=>{let K=V.statusCode??0;if(K>=300&&K<400&&V.headers.location){V.resume();let L=new URL(V.headers.location,$).toString();this.downloadWithNodeHttp(L,J,X+1,Q).then(Y).catch(W);return}if(K<200||K>=300){V.resume(),W(Error(`Download failed with status ${K} from ${$}`));return}let z=cH0(J);V.pipe(z),z.on("finish",()=>z.close(()=>Y())),z.on("error",(L)=>{z.close(),W(L)})});if(j.setTimeout(30000,()=>{j.destroy(Error(`Download request timed out for ${$}`))}),j.on("error",W),j.once("close",()=>Q?.removeEventListener("abort",Z)),Q?.addEventListener("abort",Z,{once:!0}),Q?.aborted)Z()})}isCommandUnavailable($,J){if(!$||typeof $!=="object")return!1;let X=$,Q=typeof X.code==="number"?X.code:Number(X.code);if(X.code==="ENOENT"||!Number.isNaN(Q)&&Q===127)return!0;let Y=`${X.message??""} ${X.stderr??""}`.toLowerCase();if(Y.includes("command not found")||Y.includes("not recognized as an internal or external command")||Y.includes(`${J}: not found`)||Y.includes(`not found: ${J}`))return!0;return!1}}var ON$;var fB=D(()=>{d();ON$=iH0(pH0)});import{setTimeout as oH0}from"timers/promises";class vB{async sleep($){return oH0($)}setTimeout($,J){return global.setTimeout($,J)}clearTimeout($){global.clearTimeout($)}setInterval($,J){return global.setInterval($,J)}clearInterval($){global.clearInterval($)}now(){return Date.now()}}var u;var U$=D(()=>{u=new vB});import*as V5 from"fs/promises";import Db from"path";class C7{static instance=null;static expectedChecksumOverride=null;downloader;checksumCalculator;cacheDir;usesDefaultCacheDir;timer;env;inFlight=null;constructor($={}){this.downloader=$.downloader??new BY,this.checksumCalculator=$.checksumCalculator??new c5,this.timer=$.timer??u,this.env=$.env??process.env,this.usesDefaultCacheDir=$.cacheDir===void 0,this.cacheDir=$.cacheDir??H9(qN$)}static getInstance(){if(C7.instance===null)C7.instance=new C7;return C7.instance}static resetInstances(){C7.instance=null,C7.expectedChecksumOverride=null}static setExpectedChecksumForTesting($){C7.expectedChecksumOverride=$}async computeLocalJarIntegrity($){let[{checksum:J},X]=await Promise.all([this.checksumCalculator.computeFileSha256($),V5.stat($)]);return{sha256:J.toLowerCase(),size:X.size}}get cachedJarPath(){return Db.join(this.cacheDir,wN$)}get metadataPath(){return Db.join(this.cacheDir,NN$)}expectedChecksum(){return C7.expectedChecksumOverride??zN$(this.env)}async ensure(){if(this.inFlight!==null)return this.inFlight;return this.inFlight=this.doEnsure().finally(()=>{this.inFlight=null}),this.inFlight}async doEnsure(){let $=this.expectedChecksum();if($.length===0)return U.info("[VIDEO_JAR] Expected checksum unknown for the pinned version; returning null without touching the network (jar is integrity-unverifiable)"),null;let J=await this.tryCache($);if(J)return U.info("[VIDEO_JAR] Reusing verified cached jar",{path:J}),J;return this.download($)}async tryCache($){let J;try{J=JSON.parse(await V5.readFile(this.metadataPath,"utf8"))}catch(Q){return U.debug(`[VIDEO_JAR] No usable cache metadata (cache miss): ${Q}`),null}if(J.sha256.toLowerCase()!==$.toLowerCase())return null;let X;try{X=await V5.stat(this.cachedJarPath)}catch(Q){return U.debug(`[VIDEO_JAR] Cached jar file missing despite metadata: ${Q}`),null}if(X.size!==J.size)return U.warn("[VIDEO_JAR] Cached jar size differs from sidecar; will re-download",{expected:J.size,actual:X.size}),null;return this.cachedJarPath}async ensureSecureCacheDir(){if(this.usesDefaultCacheDir)return qU(qN$);return await V5.mkdir(this.cacheDir,{recursive:!0,mode:rH0}),this.cacheDir}async download($){let J=UN$(this.env),X=await this.ensureSecureCacheDir(),Q=Db.join(X,wN$),Y=`${Q}.download`;U.info("[VIDEO_JAR] Downloading persistent-encoder jar",{url:J,destination:Y});try{await this.downloader.download(J,Y),await V5.chmod(Y,FN$);let{checksum:W}=await this.checksumCalculator.computeFileSha256(Y);if(W.toLowerCase()!==$.toLowerCase())throw new R(`video-server jar checksum verification failed. Expected: ${$}, Got: ${W}. The downloaded automobile-video.jar does not match the pinned release checksum; this indicates a corrupted or tampered download and is never silently accepted.`);if(!this.hasClassesDex(Y))throw new R("video-server jar is not a valid zip containing classes.dex (truncated or error-page download).");let{size:G}=await V5.stat(Y);return await V5.rename(Y,Q),await this.writeMetadata(X,W,G),U.info("[VIDEO_JAR] Downloaded, verified, and cached jar",{path:Q,sha256:W}),Q}catch(W){throw await V5.rm(Y,{force:!0}).catch(()=>{}),W}}async writeMetadata($,J,X){let Q={version:Z4(this.env),sha256:J,size:X,downloadedAt:this.timer.now()};await V5.writeFile(Db.join($,NN$),JSON.stringify(Q,null,2),{encoding:"utf8",mode:FN$})}hasClassesDex($){try{return new AN$.default($).getEntries().some((X)=>X.entryName===tH0)}catch(J){return U.warn("[VIDEO_JAR] Structural check failed (not a valid zip)",{path:$,error:J instanceof Error?J.message:String(J)}),!1}}}var AN$,FN$=384,rH0=448,qN$="video-server",wN$="automobile-video.jar",NN$="video-server-jar.json",tH0="classes.dex";var Fb=D(()=>{TJ();l4();AU();fB();d();U$();MX();AN$=y1(x_(),1)});function t8($){return $===!0||$==="true"}function _N$($){return $===!1||$==="false"}function ze($){return typeof $==="string"&&aH0.has($)}var aH0;var Le=D(()=>{aH0=new Set(["done","go","search","send"])});function DY($){if(!$)return null;let{nativeScale:J,pixelWidth:X,pixelHeight:Q}=$;if(typeof J!=="number"||!Number.isFinite(J)||J<=0||typeof X!=="number"||!Number.isFinite(X)||X<=0||typeof Q!=="number"||!Number.isFinite(Q)||Q<=0)return null;return{nativeScale:J,pixelWidth:X,pixelHeight:Q}}function b_($){return DY($)??{}}var He="immediate";var t$=D(()=>{l4();Le()});function RN$($){return $==="main"?"4d002a":"42e02a"}function hB($,J){return Math.ceil($/16)*Math.ceil(J/16)}function EN$($){return $.length>=4&&($[0]&31)===7?$.subarray(1,4).toString("hex"):void 0}function sH0($){let J=EN$($);return J?Number.parseInt(J.slice(4,6),16):void 0}function PN$($,J="constrained-baseline"){let X=EN$($);if(X&&!Be(X,J))return{compatible:!1,reason:`H.264 SPS profile ${X.slice(0,4)} is incompatible with negotiated ${J}.`};let Q=sH0($);if(Q!==void 0&&Q>42)return{compatible:!1,reason:`H.264 SPS level ${Q} exceeds negotiated level 42.`};return{compatible:!0}}function Be($,J){return J==="main"?$O0($):eH0($)}function eH0($){return Number.parseInt($.slice(0,2),16)===66}function $O0($){return Number.parseInt($.slice(0,2),16)===77}var MN$="constrained-baseline",Oe=42,dW=8192;class y_{chunks=[];headOffset=0;length=0;append($){if($.length===0)return;this.chunks.push($),this.length+=$.length}peek($){if($>this.length)throw RangeError(`cannot peek ${$} bytes from ${this.length}-byte queue`);let J=this.chunks[0];if(J.length-this.headOffset>=$)return J.subarray(this.headOffset,this.headOffset+$);let Q=Buffer.allocUnsafe($);return this.copyTo(Q,$),Q}takeDetached($){if($>this.length)throw RangeError(`cannot take ${$} bytes from ${this.length}-byte queue`);let J=Buffer.allocUnsafe($);return this.copyTo(J,$),this.discard($),J}discard($){if($>this.length)throw RangeError(`cannot discard ${$} bytes from ${this.length}-byte queue`);let J=$;while(J>0){let Q=this.chunks[0].length-this.headOffset;if(J<Q){this.headOffset+=J,this.length-=J;return}this.chunks.shift(),this.headOffset=0,this.length-=Q,J-=Q}}toBuffer(){if(this.length===0)return Buffer.alloc(0);let $=this.chunks[0];if(this.chunks.length===1)return $.subarray(this.headOffset);let J=Buffer.allocUnsafe(this.length);return this.copyTo(J,this.length),J}replace($){this.chunks=$.length===0?[]:[$],this.headOffset=0,this.length=$.length}copyTo($,J){let X=0;for(let Q=0;X<J;Q++){let Y=this.chunks[Q],W=Q===0?this.headOffset:0,G=Y.length-W,Z=Math.min(G,J-X);Y.copy($,X,W,W+Z),X+=Z}}}class wb{buffer=new y_;pendingHeader=null;highWaterMarkBytes=0;resynchronizing=!1;push($,J,X,Q,Y){let W=[],G=0;while(G<$.length){let Z=_U+qb-this.buffer.length;if(Z===0){if(!this.decodeAvailable(W,J,X,Q,Y))throw Error("FrameDecoder reached its raw-frame buffer limit without a complete frame");continue}let j=Math.min($.length,G+Z);this.buffer.append($.subarray(G,j)),this.highWaterMarkBytes=Math.max(this.highWaterMarkBytes,this.buffer.length),G=j,this.decodeAvailable(W,J,X,Q,Y)}return W}getMetrics(){return{bufferedBytes:this.buffer.length,highWaterMarkBytes:this.highWaterMarkBytes,maxBufferedBytes:_U+qb}}decodeAvailable($,J,X,Q,Y){let W=!1;while(!0){if(this.resynchronizing&&!this.resynchronize())return W;if(this.pendingHeader===null){let V=this.takeHeader(J);if(V==="starved")return W;if(V==="malformed"){W=!0;continue}this.pendingHeader=V,W=!0}let G=this.pendingHeader,Z=GO0(G);if(this.buffer.length<Z)return W;let j=this.buffer.takeDetached(Z);this.emitRecord(G,j,$,X,Q,Y),this.pendingHeader=null,W=!0}}emitRecord($,J,X,Q,Y,W){if(qe($)){Q?.({pcm16le:J});return}if(we($)){W?.({keyframe:($.height&WO0)!==0,presentationTimestampMs:$.timestampMs,payload:J});return}let G={header:$,pixels:J};if(Y)Y(G);else X.push(G)}takeHeader($){if(this.buffer.length<_U)return"starved";let J=this.buffer.peek(_U),X=CN$(J,0);if(X)return this.resynchronizing=!0,$?.({reason:X,header:Fe(J,0)}),"malformed";let Q=Fe(J,0);return this.buffer.discard(_U),Q}resynchronize(){let $=this.buffer.toBuffer(),J=0;while(J<=$.length-De.length){let X=$.indexOf(De,J);if(X<0)break;if(X+_U>$.length)return this.replaceBuffer($.subarray(X)),!1;if(CN$($,X)===null)return this.replaceBuffer($.subarray(X)),this.resynchronizing=!1,!0;J=X+1}return this.replaceBuffer($.subarray(Math.max(0,$.length-(De.length-1)))),!1}replaceBuffer($){this.buffer.replace($.length===0?Buffer.alloc(0):Buffer.from($))}}function qe($){return $.width===0&&$.height===8000&&$.bytesPerRow===1}function we($){return $.width===0&&($.height&kN$)>>>0===IN$}function GO0($){if(qe($))return $.timestampMs;if(we($))return $.bytesPerRow;return $.height*$.bytesPerRow}function Fe($,J){return{width:$.readUInt32LE(J+8),height:$.readUInt32LE(J+12),bytesPerRow:$.readUInt32LE(J+16),timestampMs:$.readUInt32LE(J+20)}}function CN$($,J){if($.readUInt32LE(J)!==SN$)return"header_magic_mismatch";if($.readUInt32LE(J+4)!==xN$($.subarray(J+JO0,J+_U)))return"header_checksum_mismatch";return ZO0(Fe($,J))}function ZO0($){if(qe($))return $.timestampMs>QO0?"audio_payload_too_large":null;if(we($))return $.bytesPerRow>YO0?"encoded_video_payload_too_large":null;if($.width===0)return"header_width_zero";if($.height===0)return"header_height_zero";if($.bytesPerRow<$.width*4)return"header_bytes_per_row_too_small";if($.width>TN$||$.height>TN$)return"header_dimensions_out_of_range";if($.bytesPerRow>$.width*4+XO0)return"header_bytes_per_row_too_large";if($.height*$.bytesPerRow>qb)return"header_payload_too_large";return null}function VO0(){let $=new Uint32Array(256);for(let J=0;J<256;J++){let X=J;for(let Q=0;Q<8;Q++)X=(X&1)!==0?3988292384^X>>>1:X>>>1;$[J]=X>>>0}return $}function xN$($){let J=4294967295;for(let X=0;X<$.length;X++)J=J>>>8^jO0[(J^$[X])&255];return(J^4294967295)>>>0}var SN$=826690881,De,_U=24,JO0=8,TN$=16384,XO0=4096,qb=33554432,QO0=16777216,YO0=16777216,IN$=3798204416,kN$=4294967294,WO0=1,jO0;var Ne=D(()=>{De=Buffer.from([65,77,70,49]);jO0=VO0()});class gB{options;pending=null;droppedFrames=0;highWaterMarkBytes=0;lastCaptureTimestampMs=null;constructor($){this.options=$}enqueue($){if(this.lastCaptureTimestampMs=$.header.timestampMs,$.pixels.length>this.options.maxFrameBytes)return this.droppedFrames++,!1;if(this.pending!==null)this.droppedFrames++;return this.pending={frame:$,enqueuedAtMs:this.options.now()},this.highWaterMarkBytes=Math.max(this.highWaterMarkBytes,$.pixels.length),!0}take(){let $=this.pending;return this.pending=null,$?.frame??null}clear($=!1){if($&&this.pending!==null)this.droppedFrames++;this.pending=null}metrics(){let $=this.pending;return{captureTimestampMs:$?.frame.header.timestampMs??this.lastCaptureTimestampMs,frameAgeMs:$===null?null:Math.max(0,this.options.now()-$.enqueuedAtMs),queueDepth:$===null?0:1,droppedFrames:this.droppedFrames,bytesQueued:$?.frame.pixels.length??0,highWaterMarkBytes:this.highWaterMarkBytes,maxFrameBytes:this.options.maxFrameBytes}}}import{spawn as KO0}from"child_process";import{EventEmitter as UO0}from"events";function zO0($){let J=$.trim();if(!J.startsWith(Re))return null;let X=J.slice(Re.length).trim();return X.length>0?X:null}function LO0($){if(!$.startsWith(Me))return null;try{let J=JSON.parse($.slice(Me.length));if(!HO0(J))return null;return J}catch(J){return U.debug(`[IOSScreenCaptureHelper] ignored malformed native frame metrics: ${J instanceof Error?J.message:String(J)}`),null}}function HO0($){if($===null||typeof $!=="object")return!1;let J=$;return Ae(J.captureTimestampMs)&&Ae(J.frameQueueAgeMs)&&(J.frameQueueDepth===0||J.frameQueueDepth===1)&&_e(J.droppedFrames)&&_e(J.bytesQueued)&&_e(J.highWaterMarkBytes)&&Ae(J.lastOutputWriteDurationMs)}function Ae($){return $===null||typeof $==="number"&&Number.isFinite($)}function _e($){return typeof $==="number"&&Number.isFinite($)&&$>=0}function FO0($){switch($.kind){case"device":return $.deviceId!==void 0?["--device-id",$.deviceId]:[];case"simulator":{let J=["--simulator-window",String($.windowID)];if($.fps!==void 0){if(!Number.isInteger($.fps)||$.fps<f_||$.fps>v_)throw RangeError(`simulator fps must be an integer in [${f_}, ${v_}]; got ${$.fps}`);J.push("--simulator-fps",String($.fps))}if($.audio===!0)J.push("--audio");return qO0(J,$.encode),J}}}function qO0($,J){if(J===void 0)return;switch($.push("--encode",J.codec),J.bitrate.kind){case"explicitBps":$.push("--bitrate-bps",String(Math.round(J.bitrate.bps)));break;case"bitsPerPixel":$.push("--bits-per-pixel",String(J.bitrate.bpp));break;case"videoToolboxDefault":break}}var bN$=33554432,Me="automobile-frame-metrics:",Re="capture-capability:",o2="encoded-video-h264",f_=5,v_=60,Ee=5,r2,OO0,yN$=2000,BO0=($,J,X)=>KO0($,J,X),DO0=($,J)=>{process.kill(-$,J)};var uB=D(()=>{l4();d();U$();Ne();r2=class r2 extends UO0{binaryPath;target;spawner;timer;stopGraceMs;processGroupKiller;decoder=new wb;frameQueue;frameDeliveryScheduler;process=null;helperCapabilities=new Set;stderrBuffer="";exitPromise=null;frameDeliveryScheduled=!1;constructor($){super();this.binaryPath=$.binaryPath,this.target=$.target,this.spawner=$.spawner??BO0,this.timer=$.timer??u,this.stopGraceMs=$.stopGraceMs??yN$,this.processGroupKiller=$.processGroupKiller??DO0,this.frameQueue=new gB({maxFrameBytes:bN$,now:$.now??Date.now}),this.frameDeliveryScheduler=$.frameDeliveryScheduler??OO0}on($,J){return super.on($,J)}emit($,...J){return super.emit($,...J)}get isRunning(){return this.process!==null&&this.process.exitCode===null&&!this.process.killed}getFrameMetrics(){return this.frameQueue.metrics()}start(){if(this.process!==null)throw Error("IOSScreenCaptureHelper already started");let $=FO0(this.target);this.emitReadiness("helper-executable-found",this.binaryPath);let J=this.spawner(this.binaryPath,$,{detached:process.platform==="darwin",stdio:["pipe","pipe","pipe"]});this.process=J,this.emitReadiness("helper-process-spawned",`pid=${J.pid??"?"}`),J.stdout.on("data",(X)=>{let Q=Buffer.isBuffer(X)?X:Buffer.from(X),Y=this.decoder.push(Q,(W)=>this.emit("malformed",W),(W)=>this.emit("audio",W),(W)=>this.enqueueFrame(W),(W)=>this.emit("encodedVideo",W));for(let W of Y)this.enqueueFrame(W)}),J.stderr.on("data",(X)=>{let Q=Buffer.isBuffer(X)?X.toString("utf8"):String(X);this.appendStderr(Q)}),J.once("error",(X)=>{this.emit("error",X instanceof Error?X:Error(String(X)))}),this.exitPromise=new Promise((X)=>{J.once("exit",(Q,Y)=>{if(this.stderrBuffer.length>0)this.handleStderrLine(this.stderrBuffer),this.stderrBuffer="";let W={code:Q,signal:Y};this.emit("exit",W),X(W)})}),U.debug(`[IOSScreenCaptureHelper] spawned ${this.binaryPath} pid=${J.pid??"?"}`)}async stop(){let $=this.process;if($===null)return null;if($.exitCode!==null||$.killed){let X=await this.waitForExitWithinGrace();return this.cleanupProcess($),X??{code:$.exitCode,signal:$.signalCode}}$.kill("SIGTERM");let J=await this.waitForExitWithinGrace();if(J!==null)return this.cleanupProcess($),J;if(U.warn(`[IOSScreenCaptureHelper] helper pid=${$.pid??"?"} did not exit after SIGTERM; escalating to SIGKILL`),$.kill("SIGKILL"),process.platform==="darwin")if($.pid!==void 0)try{this.processGroupKiller($.pid,"SIGKILL")}catch(X){U.warn(`[IOSScreenCaptureHelper] process-group cleanup failed for pid=${$.pid}; detached children may leak: ${X}`)}else U.warn("[IOSScreenCaptureHelper] helper pid unknown after SIGKILL; cannot group-kill, detached children may leak");return this.cleanupProcess($),{code:$.exitCode,signal:$.signalCode??"SIGKILL"}}appendStderr($){if(this.stderrBuffer+=$,this.stderrBuffer.length>r2.STDERR_BUFFER_MAX){this.emit("stderr",this.stderrBuffer),this.stderrBuffer="";return}let J=this.stderrBuffer.split(`
|
|
19
|
+
`)}catch(Q){console.error("Failed to write log:",Q)}},U;var d=D(()=>{FU();MX();Aw$();RX={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};kB=Mw$(process.env.AUTOMOBILE_LOG_LEVEL)??RX.INFO,Xe=Promise.resolve(),xB=H9(ZJ.LOGS);if(!p2.existsSync(xB))p2.mkdirSync(xB,{recursive:!0});Dw$(xB).catch(($)=>{console.error("Failed to create logs directory:",$)});Qe=Rw$(process.argv,process.pid),m2=_w$.join(xB,`${Qe}.log`),l2=p2.createWriteStream(m2,{flags:"a"});Ew$().catch(()=>{});Pw$=new Set(["PASSWORD","TOKEN","SECRET","KEY","CREDENTIAL","AUTH","API_KEY","PRIVATE_KEY","ACCESS_TOKEN","REFRESH_TOKEN","CLIENT_SECRET","DATABASE_URL","DB_PASSWORD","GITHUB_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY"]),U={setLogLevel($){kB=$},getLogLevel(){return kB},enableStdoutLogging(){Je=!0},disableStdoutLogging(){Je=!1},debug($,...J){if(kB<=RX.DEBUG)Gb(Zb("DEBUG",$,J).catch((X)=>{console.error("Failed to write debug log:",X)}))},info($,...J){if(kB<=RX.INFO)Gb(Zb("INFO",$,J).catch((X)=>{console.error("Failed to write info log:",X)}))},warn($,...J){if(kB<=RX.WARN)Gb(Zb("WARN",$,J).catch((X)=>{console.error("Failed to write warn log:",X)}))},error($,...J){if(kB<=RX.ERROR)Gb(Zb("ERROR",$,J).catch((X)=>{console.error("Failed to write error log:",X)}))},async flush(){await Xe},close(){l2.end()}}});var Ye=o((dP1,Sw$)=>{Sw$.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Vb=o((kw$)=>{var Iw$={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function KH0($){return function(...J){if(J.length)$=$.replace(/\{(\d)\}/g,(X,Q)=>J[Q]||"");return Error("ADM-ZIP: "+$)}}for(let $ of Object.keys(Iw$))kw$[$]=KH0(Iw$[$])});var vw$=o((oP1,fw$)=>{var UH0=q0("fs"),R9=q0("path"),xw$=Ye(),zH0=Vb(),LH0=typeof process==="object"&&process.platform==="win32",bw$=($)=>typeof $==="object"&&$!==null,yw$=new Uint32Array(256).map(($,J)=>{for(let X=0;X<8;X++)if((J&1)!==0)J=3988292384^J>>>1;else J>>>=1;return J>>>0});function I8($){if(this.sep=R9.sep,this.fs=UH0,bw$($)){if(bw$($.fs)&&typeof $.fs.statSync==="function")this.fs=$.fs}}fw$.exports=I8;I8.prototype.makeDir=function($){let J=this;function X(Q){let Y=Q.split(J.sep)[0];Q.split(J.sep).forEach(function(W){if(!W||W.substr(-1,1)===":")return;Y+=J.sep+W;var G;try{G=J.fs.statSync(Y)}catch(Z){if(Z.message&&Z.message.startsWith("ENOENT"))J.fs.mkdirSync(Y);else throw Z}if(G&&G.isFile())throw zH0.FILE_IN_THE_WAY(`"${Y}"`)})}X($)};I8.prototype.writeFileTo=function($,J,X,Q){let Y=this;if(Y.fs.existsSync($)){if(!X)return!1;var W=Y.fs.statSync($);if(W.isDirectory())return!1}var G=R9.dirname($);if(!Y.fs.existsSync(G))Y.makeDir(G);var Z;try{Z=Y.fs.openSync($,"w",438)}catch(j){Y.fs.chmodSync($,438),Z=Y.fs.openSync($,"w",438)}if(Z)try{Y.fs.writeSync(Z,J,0,J.length,0)}finally{Y.fs.closeSync(Z)}return Y.fs.chmodSync($,Q||438),!0};I8.prototype.writeFileToAsync=function($,J,X,Q,Y){if(typeof Q==="function")Y=Q,Q=void 0;let W=this;W.fs.exists($,function(G){if(G&&!X)return Y(!1);W.fs.stat($,function(Z,j){if(G&&j&&j.isDirectory())return Y(!1);var V=R9.dirname($);W.fs.exists(V,function(K){if(!K)try{W.makeDir(V)}catch(L){return Y(!1)}let z=function(L){W.fs.write(L,J,0,J.length,0,function(H){W.fs.close(L,function(){if(H)return Y(!1);W.fs.chmod($,Q||438,function(){Y(!0)})})})};W.fs.open($,"w",438,function(L,H){if(L)W.fs.chmod($,438,function(){W.fs.open($,"w",438,function(O,B){if(O||!B)return Y(!1);z(B)})});else if(H)z(H);else Y(!1)})})})})};I8.prototype.findFiles=function($){let J=this;function X(Q,Y,W,G){if(typeof Y==="boolean")W=Y,Y=void 0;let Z=[];return J.fs.readdirSync(Q).forEach(function(j){let V=R9.join(Q,j),K=J.fs.statSync(V);if(!Y||Y.test(V))Z.push(R9.normalize(V)+(K.isDirectory()?J.sep:""));if(K.isDirectory()&&W){let z=J.fs.realpathSync(V);if(!G.has(z))G.add(z),Z=Z.concat(X(V,Y,W,G))}}),Z}return X($,void 0,!0,new Set([J.fs.realpathSync($)]))};I8.prototype.findFilesAsync=function($,J){let X=this,Q=[],Y=!1,W=function(Z){if(Y)return;Y=!0,J(Z,Z?void 0:Q)},G=function(Z,j,V){X.fs.readdir(Z,function(K,z){if(K)return V(K);let L=z.length;if(!L)return V();z.forEach(function(H){let O=R9.join(Z,H);X.fs.stat(O,function(B,F){if(B)return V(B);if(!F){if(!--L)V();return}if(Q.push(R9.normalize(O)+(F.isDirectory()?X.sep:"")),!F.isDirectory()){if(!--L)V();return}X.fs.realpath(O,function(A,_){if(A)return V(A);if(j.has(_)){if(!--L)V();return}j.add(_),G(O,j,function(q){if(q)return V(q);if(!--L)V()})})})})})};X.fs.realpath($,function(Z,j){if(Z)return W(Z);G($,new Set([j]),W)})};I8.prototype.getAttributes=function(){};I8.prototype.setAttributes=function(){};I8.crc32update=function($,J){return yw$[($^J)&255]^$>>>8};I8.crc32=function($){if(typeof $==="string")$=Buffer.from($,"utf8");let J=$.length,X=-1;for(let Q=0;Q<J;)X=I8.crc32update(X,$[Q++]);return~X>>>0};I8.methodToString=function($){switch($){case xw$.STORED:return"STORED ("+$+")";case xw$.DEFLATED:return"DEFLATED ("+$+")";default:return"UNSUPPORTED ("+$+")"}};I8.canonical=function($){if(!$)return"";let J=R9.posix.normalize("/"+$.split("\\").join("/"));return R9.join(".",J)};I8.zipnamefix=function($){if(!$)return"";let J=R9.posix.normalize("/"+$.split("\\").join("/"));return R9.posix.join(".",J)};I8.findLast=function($,J){if(!Array.isArray($))throw TypeError("arr is not array");let X=$.length>>>0;for(let Q=X-1;Q>=0;Q--)if(J($[Q],Q,$))return $[Q];return};I8.sanitize=function($,J){$=R9.resolve(R9.normalize($));var X=J.split("/");for(var Q=0,Y=X.length;Q<Y;Q++){var W=R9.normalize(R9.join($,X.slice(Q,Y).join(R9.sep)));if(W===$||W.startsWith($+R9.sep))return W}return R9.normalize(R9.join($,R9.basename(J)))};I8.toBuffer=function(J,X){if(Buffer.isBuffer(J))return J;else if(J instanceof Uint8Array)return Buffer.from(J);else return typeof J==="string"?X(J):Buffer.alloc(0)};I8.readBigUInt64LE=function($,J){let X=$.readUInt32LE(J);return $.readUInt32LE(J+4)*4294967296+X};I8.writeBigUInt64LE=function($,J,X){let Q=J>>>0,Y=Math.floor(J/4294967296)>>>0;$.writeUInt32LE(Q,X),$.writeUInt32LE(Y,X+4)};I8.fromDOS2Date=function($){return new Date(($>>25&127)+1980,Math.max(($>>21&15)-1,0),Math.max($>>16&31,1),$>>11&31,$>>5&63,($&31)<<1)};I8.fromDate2DOS=function($){let J=0,X=0;if($.getFullYear()>1979)J=($.getFullYear()-1980&127)<<9|$.getMonth()+1<<5|$.getDate(),X=$.getHours()<<11|$.getMinutes()<<5|$.getSeconds()>>1;return J<<16|X};I8.isWin=LH0;I8.crcTable=yw$});var gw$=o((rP1,hw$)=>{var HH0=q0("path");hw$.exports=function($,{fs:J}){var X=$||"",Q=W(),Y=null;function W(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}if(X&&J.existsSync(X))Y=J.statSync(X),Q.directory=Y.isDirectory(),Q.mtime=Y.mtime,Q.atime=Y.atime,Q.executable=(73&Y.mode)!==0,Q.readonly=(128&Y.mode)===0,Q.hidden=HH0.basename(X)[0]===".";else console.warn("Invalid path: "+X);return{get directory(){return Q.directory},get readOnly(){return Q.readonly},get hidden(){return Q.hidden},get mtime(){return Q.mtime},get atime(){return Q.atime},get executable(){return Q.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:X,isDirectory:Q.directory,isReadOnly:Q.readonly,isHidden:Q.hidden,isExecutable:Q.executable,mTime:Q.mtime,aTime:Q.atime}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var mw$=o((tP1,uw$)=>{uw$.exports={efs:!0,encode:($)=>Buffer.from($,"utf8"),decode:($)=>$.toString("utf8")}});var yB=o((aP1,bB)=>{bB.exports=vw$();bB.exports.Constants=Ye();bB.exports.Errors=Vb();bB.exports.FileAttr=gw$();bB.exports.decoder=mw$()});var pw$=o((sP1,lw$)=>{var wU=yB(),x0=wU.Constants;lw$.exports=function(){var $=20,J=10,X=0,Q=0,Y=0,W=0,G=0,Z=0,j=0,V=0,K=0,z=0,L=0,H=0,O=0;$|=wU.isWin?2560:768,X|=x0.FLG_EFS;let B={extraLen:0},F=(q)=>Math.max(0,q)>>>0,A=(q)=>Math.max(0,q)&65535,_=(q)=>Math.max(0,q)&255;return Y=wU.fromDate2DOS(new Date),{get made(){return $},set made(q){$=q},get version(){return J},set version(q){J=q},get flags(){return X},set flags(q){X=q},get flags_efs(){return(X&x0.FLG_EFS)>0},set flags_efs(q){if(q)X|=x0.FLG_EFS;else X&=~x0.FLG_EFS},get flags_desc(){return(X&x0.FLG_DESC)>0},set flags_desc(q){if(q)X|=x0.FLG_DESC;else X&=~x0.FLG_DESC},get method(){return Q},set method(q){switch(q){case x0.STORED:this.version=10;break;case x0.DEFLATED:default:this.version=20}Q=q},get time(){return wU.fromDOS2Date(this.timeval)},set time(q){q=new Date(q),this.timeval=wU.fromDate2DOS(q)},get timeval(){return Y},set timeval(q){Y=F(q)},get timeHighByte(){return _(Y>>>8)},get crc(){return W},set crc(q){W=F(q)},get compressedSize(){return G},set compressedSize(q){G=F(q)},get size(){return Z},set size(q){Z=F(q)},get fileNameLength(){return j},set fileNameLength(q){j=q},get extraLength(){return V},set extraLength(q){V=q},get extraLocalLength(){return B.extraLen},set extraLocalLength(q){B.extraLen=q},get commentLength(){return K},set commentLength(q){K=q},get diskNumStart(){return z},set diskNumStart(q){z=F(q)},get inAttr(){return L},set inAttr(q){L=F(q)},get attr(){return H},set attr(q){H=F(q)},get fileAttr(){return(H||0)>>16&4095},get offset(){return O},set offset(q){O=F(q)},get encrypted(){return(X&x0.FLG_ENC)===x0.FLG_ENC},get centralHeaderSize(){return x0.CENHDR+j+V+K},get realDataOffset(){return O+x0.LOCHDR+B.fnameLen+B.extraLen},get localHeader(){return B},loadLocalHeaderFromBinary:function(q){var w=q.slice(O,O+x0.LOCHDR);if(w.readUInt32LE(0)!==x0.LOCSIG)throw wU.Errors.INVALID_LOC();B.version=w.readUInt16LE(x0.LOCVER),B.flags=w.readUInt16LE(x0.LOCFLG),B.flags_desc=(B.flags&x0.FLG_DESC)>0,B.method=w.readUInt16LE(x0.LOCHOW),B.time=w.readUInt32LE(x0.LOCTIM),B.crc=w.readUInt32LE(x0.LOCCRC),B.compressedSize=w.readUInt32LE(x0.LOCSIZ),B.size=w.readUInt32LE(x0.LOCLEN),B.fnameLen=w.readUInt16LE(x0.LOCNAM),B.extraLen=w.readUInt16LE(x0.LOCEXT);let M=O+x0.LOCHDR+B.fnameLen,C=M+B.extraLen;return q.slice(M,C)},loadFromBinary:function(q){if(q.length!==x0.CENHDR||q.readUInt32LE(0)!==x0.CENSIG)throw wU.Errors.INVALID_CEN();$=q.readUInt16LE(x0.CENVEM),J=q.readUInt16LE(x0.CENVER),X=q.readUInt16LE(x0.CENFLG),Q=q.readUInt16LE(x0.CENHOW),Y=q.readUInt32LE(x0.CENTIM),W=q.readUInt32LE(x0.CENCRC),G=q.readUInt32LE(x0.CENSIZ),Z=q.readUInt32LE(x0.CENLEN),j=q.readUInt16LE(x0.CENNAM),V=q.readUInt16LE(x0.CENEXT),K=q.readUInt16LE(x0.CENCOM),z=q.readUInt16LE(x0.CENDSK),L=q.readUInt16LE(x0.CENATT),H=q.readUInt32LE(x0.CENATX),O=q.readUInt32LE(x0.CENOFF)},localHeaderToBinary:function(){var q=Buffer.alloc(x0.LOCHDR);return q.writeUInt32LE(x0.LOCSIG,0),q.writeUInt16LE(J,x0.LOCVER),q.writeUInt16LE(X&~x0.FLG_DESC,x0.LOCFLG),q.writeUInt16LE(Q,x0.LOCHOW),q.writeUInt32LE(Y,x0.LOCTIM),q.writeUInt32LE(W,x0.LOCCRC),q.writeUInt32LE(G,x0.LOCSIZ),q.writeUInt32LE(Z,x0.LOCLEN),q.writeUInt16LE(j,x0.LOCNAM),q.writeUInt16LE(B.extraLen,x0.LOCEXT),q},centralHeaderToBinary:function(){var q=Buffer.alloc(x0.CENHDR+j+V+K);return q.writeUInt32LE(x0.CENSIG,0),q.writeUInt16LE($,x0.CENVEM),q.writeUInt16LE(J,x0.CENVER),q.writeUInt16LE(X&~x0.FLG_DESC,x0.CENFLG),q.writeUInt16LE(Q,x0.CENHOW),q.writeUInt32LE(Y,x0.CENTIM),q.writeUInt32LE(W,x0.CENCRC),q.writeUInt32LE(G,x0.CENSIZ),q.writeUInt32LE(Z,x0.CENLEN),q.writeUInt16LE(j,x0.CENNAM),q.writeUInt16LE(V,x0.CENEXT),q.writeUInt16LE(K,x0.CENCOM),q.writeUInt16LE(z,x0.CENDSK),q.writeUInt16LE(L,x0.CENATT),q.writeUInt32LE(H,x0.CENATX),q.writeUInt32LE(O,x0.CENOFF),q},toJSON:function(){let q=function(w){return w+" bytes"};return{made:$,version:J,flags:X,method:wU.methodToString(Q),time:this.time,crc:"0x"+W.toString(16).toUpperCase(),compressedSize:q(G),size:q(Z),fileNameLength:q(j),extraLength:q(V),commentLength:q(K),diskNumStart:z,inAttr:L,attr:H,offset:O,centralHeaderSize:q(x0.CENHDR+j+V+K)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var nw$=o((eP1,cw$)=>{var AQ=yB(),K1=AQ.Constants;cw$.exports=function(){var $=0,J=0,X=0,Q=0,Y=0;let W=()=>$>K1.EF_ZIP64_OR_16||J>K1.EF_ZIP64_OR_16||X>K1.EF_ZIP64_OR_32||Q>K1.EF_ZIP64_OR_32;return{get diskEntries(){return $},set diskEntries(G){$=J=G},get totalEntries(){return J},set totalEntries(G){J=$=G},get size(){return X},set size(G){X=G},get offset(){return Q},set offset(G){Q=G},get commentLength(){return Y},set commentLength(G){Y=G},get mainHeaderSize(){return(W()?K1.ZIP64HDR+K1.END64HDR:0)+K1.ENDHDR+Y},loadFromBinary:function(G){if((G.length!==K1.ENDHDR||G.readUInt32LE(0)!==K1.ENDSIG)&&(G.length<K1.ZIP64HDR||G.readUInt32LE(0)!==K1.ZIP64SIG))throw AQ.Errors.INVALID_END();if(G.readUInt32LE(0)===K1.ENDSIG)$=G.readUInt16LE(K1.ENDSUB),J=G.readUInt16LE(K1.ENDTOT),X=G.readUInt32LE(K1.ENDSIZ),Q=G.readUInt32LE(K1.ENDOFF),Y=G.readUInt16LE(K1.ENDCOM);else $=AQ.readBigUInt64LE(G,K1.ZIP64SUB),J=AQ.readBigUInt64LE(G,K1.ZIP64TOT),X=AQ.readBigUInt64LE(G,K1.ZIP64SIZB),Q=AQ.readBigUInt64LE(G,K1.ZIP64OFF),Y=0},toBinary:function(){if(!W()){var G=Buffer.alloc(K1.ENDHDR+Y);return G.writeUInt32LE(K1.ENDSIG,0),G.writeUInt32LE(0,4),G.writeUInt16LE($,K1.ENDSUB),G.writeUInt16LE(J,K1.ENDTOT),G.writeUInt32LE(X,K1.ENDSIZ),G.writeUInt32LE(Q,K1.ENDOFF),G.writeUInt16LE(Y,K1.ENDCOM),G.fill(" ",K1.ENDHDR),G}var G=Buffer.alloc(this.mainHeaderSize);let Z=0;G.writeUInt32LE(K1.ZIP64SIG,Z),AQ.writeBigUInt64LE(G,K1.ZIP64HDR-K1.ZIP64LEAD,Z+K1.ZIP64SIZE),G.writeUInt16LE(45,Z+K1.ZIP64VEM),G.writeUInt16LE(45,Z+K1.ZIP64VER),G.writeUInt32LE(0,Z+K1.ZIP64DSK),G.writeUInt32LE(0,Z+K1.ZIP64DSKDIR),AQ.writeBigUInt64LE(G,$,Z+K1.ZIP64SUB),AQ.writeBigUInt64LE(G,J,Z+K1.ZIP64TOT),AQ.writeBigUInt64LE(G,X,Z+K1.ZIP64SIZB),AQ.writeBigUInt64LE(G,Q,Z+K1.ZIP64OFF);let j=Q+X;return Z+=K1.ZIP64HDR,G.writeUInt32LE(K1.END64SIG,Z),G.writeUInt32LE(0,Z+K1.END64START),AQ.writeBigUInt64LE(G,j,Z+K1.END64OFF),G.writeUInt32LE(1,Z+K1.END64NUMDISKS),Z+=K1.END64HDR,G.writeUInt32LE(K1.ENDSIG,Z),G.writeUInt32LE(0,Z+4),G.writeUInt16LE(Math.min($,K1.EF_ZIP64_OR_16),Z+K1.ENDSUB),G.writeUInt16LE(Math.min(J,K1.EF_ZIP64_OR_16),Z+K1.ENDTOT),G.writeUInt32LE(Math.min(X,K1.EF_ZIP64_OR_32),Z+K1.ENDSIZ),G.writeUInt32LE(Math.min(Q,K1.EF_ZIP64_OR_32),Z+K1.ENDOFF),G.writeUInt16LE(Y,Z+K1.ENDCOM),G.fill(" ",Z+K1.ENDHDR),G},toJSON:function(){let G=function(Z,j){let V=Z.toString(16).toUpperCase();while(V.length<j)V="0"+V;return"0x"+V};return{diskEntries:$,totalEntries:J,size:X+" bytes",offset:G(Q,4),commentLength:Y}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var We=o((OH0)=>{OH0.EntryHeader=pw$();OH0.MainHeader=nw$()});var iw$=o((JT1,dw$)=>{dw$.exports=function($){var J=q0("zlib"),X={chunkSize:(parseInt($.length/1024)+1)*1024};return{deflate:function(){return J.deflateRawSync($,X)},deflateAsync:function(Q){var Y=J.createDeflateRaw(X),W=[],G=0;Y.on("data",function(Z){W.push(Z),G+=Z.length}),Y.on("end",function(){var Z=Buffer.alloc(G),j=0;Z.fill(0);for(var V=0;V<W.length;V++){var K=W[V];K.copy(Z,j),j+=K.length}Q&&Q(Z)}),Y.end($)}}}});var rw$=o((XT1,ow$)=>{var FH0=+(process?.versions?.node??"").split(".")[0]||0;ow$.exports=function($,J){var X=q0("zlib");let Q=FH0>=15&&J>0?{maxOutputLength:J}:{};return{inflate:function(){return X.inflateRawSync($,Q)},inflateAsync:function(Y){var W=X.createInflateRaw(Q),G=[],Z=0;W.on("data",function(j){G.push(j),Z+=j.length}),W.on("end",function(){var j=Buffer.alloc(Z),V=0;j.fill(0);for(var K=0;K<G.length;K++){var z=G[K];z.copy(j,V),V+=z.length}Y&&Y(j)}),W.end($)}}}});var $N$=o((QT1,ew$)=>{var{randomFillSync:tw$}=q0("crypto"),qH0=Vb(),wH0=new Uint32Array(256).map(($,J)=>{for(let X=0;X<8;X++)if((J&1)!==0)J=J>>>1^3988292384;else J>>>=1;return J>>>0}),sw$=($,J)=>Math.imul($,J)>>>0,aw$=($,J)=>{return wH0[($^J)&255]^$>>>8},k_=()=>{if(typeof tw$==="function")return tw$(Buffer.alloc(12));else return k_.node()};k_.node=()=>{let $=Buffer.alloc(12),J=$.length;for(let X=0;X<J;X++)$[X]=Math.random()*256&255;return $};var Kb={genSalt:k_};function Ub($){let J=Buffer.isBuffer($)?$:Buffer.from($);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let X=0;X<J.length;X++)this.updateKeys(J[X])}Ub.prototype.updateKeys=function($){let J=this.keys;return J[0]=aw$(J[0],$),J[1]+=J[0]&255,J[1]=sw$(J[1],134775813)+1,J[2]=aw$(J[2],J[1]>>>24),$};Ub.prototype.next=function(){let $=(this.keys[2]|2)>>>0;return sw$($,$^1)>>8&255};function NH0($){let J=new Ub($);return function(X){let Q=Buffer.alloc(X.length),Y=0;for(let W of X)Q[Y++]=J.updateKeys(W^J.next());return Q}}function AH0($){let J=new Ub($);return function(X,Q,Y=0){if(!Q)Q=Buffer.alloc(X.length);for(let W of X){let G=J.next();Q[Y++]=W^G,J.updateKeys(W)}return Q}}function _H0($,J,X){if(!$||!Buffer.isBuffer($)||$.length<12)return Buffer.alloc(0);let Q=NH0(X),Y=Q($.slice(0,12)),W=(J.flags&8)===8?J.timeHighByte:J.crc>>>24;if(Y[11]!==W)throw qH0.WRONG_PASSWORD();return Q($.slice(12))}function MH0($){if(Buffer.isBuffer($)&&$.length>=12)Kb.genSalt=function(){return $.slice(0,12)};else if($==="node")Kb.genSalt=k_.node;else Kb.genSalt=k_}function RH0($,J,X,Q=!1){if($==null)$=Buffer.alloc(0);if(!Buffer.isBuffer($))$=Buffer.from($.toString());let Y=AH0(X),W=Kb.genSalt();if(W[11]=J.crc>>>24&255,Q)W[10]=J.crc>>>16&255;let G=Buffer.alloc($.length+12);return Y(W,G),Y($,G,12)}ew$.exports={decrypt:_H0,encrypt:RH0,_salter:MH0}});var JN$=o((EH0)=>{EH0.Deflater=iw$();EH0.Inflater=rw$();EH0.ZipCrypto=$N$()});var Ze=o((WT1,XN$)=>{var U8=yB(),SH0=We(),EX=U8.Constants,Ge=JN$();XN$.exports=function($,J){var X=new SH0.EntryHeader,Q=Buffer.alloc(0),Y=Buffer.alloc(0),W=!1,G=null,Z=Buffer.alloc(0),j=Buffer.alloc(0),V=!0;let K=$,z=typeof K.decoder==="object"?K.decoder:U8.decoder;V=z.hasOwnProperty("efs")?z.efs:!1;function L(){if(!J||!(J instanceof Uint8Array))return Buffer.alloc(0);return j=X.loadLocalHeaderFromBinary(J),J.slice(X.realDataOffset,X.realDataOffset+X.compressedSize)}function H(q){let w=X.flags_desc||X.localHeader.flags_desc?X.crc:X.localHeader.crc;return U8.crc32(q)===w}function O(q,w,M){if(typeof w>"u"&&typeof q==="string")M=q,q=void 0;if(W){if(q&&w)w(Buffer.alloc(0),U8.Errors.DIRECTORY_CONTENT_ERROR());return Buffer.alloc(0)}var C=L();if(C.length===0){if(q&&w)w(C);return C}if(X.encrypted){if(typeof M!=="string"&&!Buffer.isBuffer(M))throw U8.Errors.INVALID_PASS_PARAM();C=Ge.ZipCrypto.decrypt(C,X,M)}var f;switch(X.method){case U8.Constants.STORED:if(f=Buffer.alloc(C.length),C.copy(f),!H(f)){if(q&&w)w(f,U8.Errors.BAD_CRC());throw U8.Errors.BAD_CRC()}else{if(q&&w)w(f);return f}case U8.Constants.DEFLATED:var I=new Ge.Inflater(C,X.size);if(!q){if(f=I.inflate(),!H(f))throw U8.Errors.BAD_CRC(`"${z.decode(Q)}"`);return f}else I.inflateAsync(function(c){if(w)if(!H(c))w(c,U8.Errors.BAD_CRC());else w(c)});break;default:if(q&&w)w(Buffer.alloc(0),U8.Errors.UNKNOWN_METHOD());throw U8.Errors.UNKNOWN_METHOD()}}function B(q,w){if((!G||!G.length)&&Buffer.isBuffer(J)){if(q&&w)w(L());return L()}if(G.length&&!W){var M;switch(X.method){case U8.Constants.STORED:if(X.compressedSize=X.size,M=Buffer.alloc(G.length),G.copy(M),q&&w)w(M);return M;default:case U8.Constants.DEFLATED:var C=new Ge.Deflater(G);if(!q){var f=C.deflate();return X.compressedSize=f.length,f}else C.deflateAsync(function(I){M=Buffer.alloc(I.length),X.compressedSize=I.length,I.copy(M),w&&w(M)});C=null;break}}else if(q&&w)w(Buffer.alloc(0));else return Buffer.alloc(0)}function F(q,w){return U8.readBigUInt64LE(q,w)}function A(q){try{var w=0,M,C,f;while(w+4<q.length)if(M=q.readUInt16LE(w),w+=2,C=q.readUInt16LE(w),w+=2,f=q.slice(w,w+C),w+=C,EX.ID_ZIP64===M)_(f)}catch(I){throw U8.Errors.EXTRA_FIELD_PARSE_ERROR()}}function _(q){var w,M,C,f;if(q.length>=EX.EF_ZIP64_SCOMP){if(w=F(q,EX.EF_ZIP64_SUNCOMP),X.size===EX.EF_ZIP64_OR_32)X.size=w}if(q.length>=EX.EF_ZIP64_RHO){if(M=F(q,EX.EF_ZIP64_SCOMP),X.compressedSize===EX.EF_ZIP64_OR_32)X.compressedSize=M}if(q.length>=EX.EF_ZIP64_DSN){if(C=F(q,EX.EF_ZIP64_RHO),X.offset===EX.EF_ZIP64_OR_32)X.offset=C}if(q.length>=EX.EF_ZIP64_DSN+4){if(f=q.readUInt32LE(EX.EF_ZIP64_DSN),X.diskNumStart===EX.EF_ZIP64_OR_16)X.diskNumStart=f}}return{get entryName(){return z.decode(Q)},get rawEntryName(){return Q},set entryName(q){Q=U8.toBuffer(q,z.encode);var w=Q[Q.length-1];W=w===47||w===92,X.fileNameLength=Q.length},get efs(){if(typeof V==="function")return V(this.entryName);else return V},get extra(){return Z},set extra(q){Z=q,X.extraLength=q.length,A(q)},get comment(){return z.decode(Y)},set comment(q){if(Y=U8.toBuffer(q,z.encode),X.commentLength=Y.length,Y.length>65535)throw U8.Errors.COMMENT_TOO_LONG()},get name(){let q=z.decode(Q);return W?q.replace(/[/\\]$/,"").split("/").pop():q.split("/").pop()},get isDirectory(){return W},getCompressedData:function(){return B(!1,null)},getCompressedDataAsync:function(q){B(!0,q)},setData:function(q){if(G=U8.toBuffer(q,U8.decoder.encode),!W&&G.length)X.size=G.length,X.method=U8.Constants.DEFLATED,X.crc=U8.crc32(q),X.changed=!0;else X.method=U8.Constants.STORED},getData:function(q){if(X.changed)return G;else return O(!1,null,q)},getDataAsync:function(q,w){if(X.changed)q(G);else O(!0,q,w)},set attr(q){X.attr=q},get attr(){return X.attr},set header(q){X.loadFromBinary(q)},get header(){return X},packCentralHeader:function(){X.flags_efs=this.efs,X.extraLength=Z.length;var q=X.centralHeaderToBinary(),w=U8.Constants.CENHDR;return Q.copy(q,w),w+=Q.length,Z.copy(q,w),w+=X.extraLength,Y.copy(q,w),q},packLocalHeader:function(){let q=0;X.flags_efs=this.efs,X.extraLocalLength=j.length;let w=X.localHeaderToBinary(),M=Buffer.alloc(w.length+Q.length+X.extraLocalLength);return w.copy(M,q),q+=w.length,Q.copy(M,q),q+=Q.length,j.copy(M,q),q+=j.length,M},toJSON:function(){let q=function(w){return"<"+(w&&w.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:X.toJSON(),compressedData:q(J),data:q(G)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var WN$=o((GT1,YN$)=>{var QN$=Ze(),IH0=We(),p5=yB();YN$.exports=function($,J){var X=[],Q=Object.create(null),Y=Buffer.alloc(0),W=new IH0.MainHeader,G=!1,Z=null;let j=new Set,V=J,{noSort:K,decoder:z}=V;if($)O(V.readEntries);else G=!0;function L(){let F=new Set;for(let A of Object.keys(Q)){let _=A.split("/");if(_.pop(),!_.length)continue;for(let q=0;q<_.length;q++){let w=_.slice(0,q+1).join("/")+"/";F.add(w)}}for(let A of F)if(!(A in Q)){let _=new QN$(V);_.entryName=A,_.attr=16,_.temporary=!0,X.push(_),Q[_.entryName]=_,j.add(_)}}function H(){if(G=!0,Q=Object.create(null),W.diskEntries>($.length-W.offset)/p5.Constants.CENHDR)throw p5.Errors.DISK_ENTRY_TOO_LARGE();X=Array(W.diskEntries);var F=W.offset;for(var A=0;A<X.length;A++){var _=F,q=new QN$(V,$);if(q.header=$.slice(_,_+=p5.Constants.CENHDR),q.entryName=$.slice(_,_+=q.header.fileNameLength),q.header.extraLength)q.extra=$.slice(_,_+=q.header.extraLength);if(q.header.commentLength)q.comment=$.slice(_,_+q.header.commentLength);F+=q.header.centralHeaderSize,X[A]=q,Q[q.entryName]=q}j.clear(),L()}function O(F){var A=$.length-p5.Constants.ENDHDR,_=Math.max(0,A-65535),q=_,w=$.length,M=-1,C=0;if(typeof V.trailingSpace==="boolean"?V.trailingSpace:!1)_=0;for(A;A>=q;A--){if($[A]!==80)continue;if($.readUInt32LE(A)===p5.Constants.ENDSIG){M=A,C=A,w=A+p5.Constants.ENDHDR,q=A-p5.Constants.END64HDR;continue}if($.readUInt32LE(A)===p5.Constants.END64SIG){q=_;continue}if($.readUInt32LE(A)===p5.Constants.ZIP64SIG){M=A,w=A+p5.readBigUInt64LE($,A+p5.Constants.ZIP64SIZE)+p5.Constants.ZIP64LEAD;break}}if(M==-1)throw p5.Errors.INVALID_FORMAT();if(W.loadFromBinary($.slice(M,w)),W.commentLength)Y=$.slice(C+p5.Constants.ENDHDR);if(F)H()}function B(){if(X.length>1&&!K)X=X.map((F)=>({entry:F,key:F.entryName.toLowerCase()})).sort((F,A)=>F.key.localeCompare(A.key)).map((F)=>F.entry)}return{get entries(){if(!G)H();return X.filter((F)=>!j.has(F))},get comment(){return z.decode(Y)},set comment(F){Y=p5.toBuffer(F,z.encode),W.commentLength=Y.length},getEntryCount:function(){if(!G)return W.diskEntries;return X.length},forEach:function(F){this.entries.forEach(F)},getEntry:function(F){if(!G)H();return Q[F]||null},setEntry:function(F){if(!G)H();X.push(F),Q[F.entryName]=F,W.totalEntries=X.length},deleteFile:function(F,A=!0){if(!G)H();let _=Q[F];this.getEntryChildren(_,A).map((w)=>w.entryName).forEach(this.deleteEntry)},deleteEntry:function(F){if(!G)H();let A=Q[F],_=X.indexOf(A);if(_>=0)X.splice(_,1),delete Q[F],W.totalEntries=X.length},getEntryChildren:function(F,A=!0){if(!G)H();if(typeof F==="object")if(F.isDirectory&&A){let _=[],q=F.entryName;for(let w of X)if(w.entryName.startsWith(q))_.push(w);return _}else return[F];return[]},getChildCount:function(F){if(F&&F.isDirectory){let A=this.getEntryChildren(F);return A.includes(F)?A.length-1:A.length}return 0},compressToBuffer:function(){if(!G)H();B();let F=[],A=[],_=0,q=0;W.size=0,W.offset=0;let w=0;for(let f of this.entries){let I=f.getCompressedData();f.header.offset=q;let c=f.packLocalHeader(),h=c.length+I.length;q+=h,F.push(c),F.push(I);let r=f.packCentralHeader();A.push(r),W.size+=r.length,_+=h+r.length,w++}_+=W.mainHeaderSize,W.offset=q,W.totalEntries=w,q=0;let M=Buffer.alloc(_);for(let f of F)f.copy(M,q),q+=f.length;for(let f of A)f.copy(M,q),q+=f.length;let C=W.toBinary();if(Y)Y.copy(C,C.length-Y.length);return C.copy(M,q),$=M,G=!1,M},toAsyncBuffer:function(F,A,_,q){try{if(!G)H();B();let w=[],M=[],C=0,f=0,I=0;W.size=0,W.offset=0;let c=function(h){if(h.length>0){let r=h.shift(),t=r.entryName+r.extra.toString();if(_)_(t);r.getCompressedDataAsync(function(Y$){if(q)q(t);r.header.offset=f;let X$=r.packLocalHeader(),L$=X$.length+Y$.length;f+=L$,w.push(X$),w.push(Y$);let O$=r.packCentralHeader();M.push(O$),W.size+=O$.length,C+=L$+O$.length,I++,c(h)})}else{C+=W.mainHeaderSize,W.offset=f,W.totalEntries=I,f=0;let r=Buffer.alloc(C);w.forEach(function(Y$){Y$.copy(r,f),f+=Y$.length}),M.forEach(function(Y$){Y$.copy(r,f),f+=Y$.length});let t=W.toBinary();if(Y)Y.copy(t,t.length-Y.length);t.copy(r,f),$=r,G=!1,F(r)}};c(Array.from(this.entries))}catch(w){A(w)}}}}});var x_=o((ZT1,ZN$)=>{var r8=yB(),o8=q0("path"),kH0=Ze(),xH0=WN$(),c2=(...$)=>r8.findLast($,(J)=>typeof J==="boolean"),GN$=(...$)=>r8.findLast($,(J)=>typeof J==="string"),bH0=(...$)=>r8.findLast($,(J)=>typeof J==="function"),yH0={noSort:!1,readEntries:!1,method:r8.Constants.NONE,fs:null};ZN$.exports=function($,J){let X=null,Q=Object.assign(Object.create(null),yH0);if($&&typeof $==="object"){if(!($ instanceof Uint8Array)){if(Object.assign(Q,$),$=Q.input?Q.input:void 0,Q.input)delete Q.input}if(Buffer.isBuffer($))X=$,Q.method=r8.Constants.BUFFER,$=void 0}Object.assign(Q,J);let Y=new r8(Q),W=(O)=>{O.filter((B)=>B.attr).sort((B,F)=>F.path.length-B.path.length).forEach((B)=>Y.fs.chmodSync(B.path,B.attr))};if(typeof Q.decoder!=="object"||typeof Q.decoder.encode!=="function"||typeof Q.decoder.decode!=="function")Q.decoder=r8.decoder;if($&&typeof $==="string")if(Y.fs.existsSync($))Q.method=r8.Constants.FILE,Q.filename=$,X=Y.fs.readFileSync($);else throw r8.Errors.INVALID_FILENAME();let G=new xH0(X,Q),{canonical:Z,sanitize:j,zipnamefix:V}=r8;function K(O){if(O&&G){var B;if(typeof O==="string")B=G.getEntry(o8.posix.normalize(O));if(typeof O==="object"&&typeof O.entryName<"u"&&typeof O.header<"u")B=G.getEntry(O.entryName);if(B)return B}return null}function z(O){let{join:B,normalize:F,sep:A}=o8.posix;return B(o8.isAbsolute(O)?"/":".",F(A+O.split("\\").join(A)+A))}function L(O){if(O instanceof RegExp)return function(B){return function(F){return B.test(F)}}(O);else if(typeof O!=="function")return()=>!0;return O}let H=(O,B)=>{let F=B.slice(-1);return F=F===Y.sep?Y.sep:"",o8.relative(O,B)+F};return{readFile:function(O,B){var F=K(O);return F&&F.getData(B)||null},childCount:function(O){let B=K(O);if(B)return G.getChildCount(B)},readFileAsync:function(O,B){var F=K(O);if(F)F.getDataAsync(B);else B(null,"getEntry failed for:"+O)},readAsText:function(O,B){var F=K(O);if(F){var A=F.getData();if(A&&A.length)return A.toString(B||"utf8")}return""},readAsTextAsync:function(O,B,F){var A=K(O);if(A)A.getDataAsync(function(_,q){if(q){B(_,q);return}if(_&&_.length)B(_.toString(F||"utf8"));else B("")});else B("")},deleteFile:function(O,B=!0){var F=K(O);if(F)G.deleteFile(F.entryName,B)},deleteEntry:function(O){var B=K(O);if(B)G.deleteEntry(B.entryName)},addZipComment:function(O){G.comment=O},getZipComment:function(){return G.comment||""},addZipEntryComment:function(O,B){var F=K(O);if(F)F.comment=B},getZipEntryComment:function(O){var B=K(O);if(B)return B.comment||"";return""},updateFile:function(O,B){var F=K(O);if(F)F.setData(B)},addLocalFile:function(O,B,F,A){if(Y.fs.existsSync(O)){B=B?z(B):"";let _=o8.win32.basename(o8.win32.normalize(O));B+=F?F:_;let q=Y.fs.statSync(O),w=q.isFile()?Y.fs.readFileSync(O):Buffer.alloc(0);if(q.isDirectory())B+=Y.sep;this.addFile(B,w,A,q)}else throw r8.Errors.FILE_NOT_FOUND(O)},addLocalFileAsync:function(O,B){O=typeof O==="object"?O:{localPath:O};let F=o8.resolve(O.localPath),{comment:A}=O,{zipPath:_,zipName:q}=O,w=this;Y.fs.stat(F,function(M,C){if(M)return B(M,!1);_=_?z(_):"";let f=o8.win32.basename(o8.win32.normalize(F));if(_+=q?q:f,C.isFile())Y.fs.readFile(F,function(I,c){if(I)return B(I,!1);return w.addFile(_,c,A,C),setImmediate(B,void 0,!0)});else if(C.isDirectory())return _+=Y.sep,w.addFile(_,Buffer.alloc(0),A,C),setImmediate(B,void 0,!0)})},addLocalFolder:function(O,B,F){if(F=L(F),B=B?z(B):"",O=o8.normalize(O),Y.fs.existsSync(O)){let A=Y.findFiles(O),_=this;if(A.length)for(let q of A){let w=o8.join(B,H(O,q));if(F(w))_.addLocalFile(q,o8.dirname(w))}}else throw r8.Errors.FILE_NOT_FOUND(O)},addLocalFolderAsync:function(O,B,F,A){A=L(A),F=F?z(F):"",O=o8.normalize(O);var _=this;Y.fs.open(O,"r",function(q){if(q&&q.code==="ENOENT")B(void 0,r8.Errors.FILE_NOT_FOUND(O));else if(q)B(void 0,q);else{var w=Y.findFiles(O),M=-1,C=function(){if(M+=1,M<w.length){var f=w[M],I=H(O,f).split("\\").join("/");if(I=I.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(I))Y.fs.stat(f,function(c,h){if(c)B(void 0,c);if(h.isFile())Y.fs.readFile(f,function(r,t){if(r)B(void 0,r);else _.addFile(F+I,t,"",h),C()});else _.addFile(F+I+"/",Buffer.alloc(0),"",h),C()});else process.nextTick(()=>{C()})}else B(!0,void 0)};C()}})},addLocalFolderAsync2:function(O,B){let F=this;O=typeof O==="object"?O:{localPath:O};let A=o8.resolve(z(O.localPath)),{zipPath:_,filter:q,namefix:w}=O;if(q instanceof RegExp)q=function(f){return function(I){return f.test(I)}}(q);else if(typeof q!=="function")q=function(){return!0};if(_=_?z(_):"",w==="latin1")w=(f)=>f.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(typeof w!=="function")w=(f)=>f;let M=(f)=>o8.join(_,w(H(A,f))),C=(f)=>o8.win32.basename(o8.win32.normalize(w(f)));Y.fs.open(A,"r",function(f){if(f&&f.code==="ENOENT")B(void 0,r8.Errors.FILE_NOT_FOUND(A));else if(f)B(void 0,f);else Y.findFilesAsync(A,function(I,c){if(I)return B(I);if(c=c.filter((h)=>q(M(h))),!c.length)B(void 0,!1);setImmediate(c.reverse().reduce(function(h,r){return function(t,Y$){if(t||Y$===!1)return setImmediate(h,t,!1);F.addLocalFileAsync({localPath:r,zipPath:o8.dirname(M(r)),zipName:C(r)},h)}},B))})})},addLocalFolderPromise:function(O,B){return new Promise((F,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:O},B),(_,q)=>{if(_)A(_);if(q)F(this)})})},addFile:function(O,B,F,A){O=V(O);let _=K(O),q=_!=null;if(!q)_=new kH0(Q),_.entryName=O;_.comment=F||"";let w=typeof A==="object"&&A instanceof Y.fs.Stats;if(w)_.header.time=A.mtime;var M=_.isDirectory?16:0;let C=_.isDirectory?16384:32768;if(w)C|=4095&A.mode;else if(typeof A==="number")C|=4095&A;else C|=_.isDirectory?493:420;if(M=(M|C<<16)>>>0,_.attr=M,_.setData(B),!q)G.setEntry(_);return _},getEntries:function(O){return G.password=O,G?G.entries:[]},getEntry:function(O){return K(O)},getEntryCount:function(){return G.getEntryCount()},forEach:function(O){return G.forEach(O)},extractEntryTo:function(O,B,F,A,_,q){A=c2(!1,A),_=c2(!1,_),F=c2(!0,F),q=GN$(_,q);var w=K(O);if(!w)throw r8.Errors.NO_ENTRY();var M=Z(w.entryName),C=j(B,q&&!w.isDirectory?Z(q):F?M:o8.basename(M));if(w.isDirectory){var f=G.getEntryChildren(w);return f.forEach(function(h){if(h.isDirectory)return;var r=h.getData();if(!r)throw r8.Errors.CANT_EXTRACT_FILE();var t=Z(F?h.entryName:h.entryName.substring(w.entryName.length)),Y$=j(B,t);let X$=_?h.header.fileAttr:void 0;Y.writeFileTo(Y$,r,A,X$)}),!0}var I=w.getData(G.password);if(!I)throw r8.Errors.CANT_EXTRACT_FILE();if(Y.fs.existsSync(C)&&!A)throw r8.Errors.CANT_OVERRIDE();let c=_?O.header.fileAttr:void 0;return Y.writeFileTo(C,I,A,c),!0},test:function(O){if(!G)return!1;for(var B of G.entries)try{if(B.isDirectory)continue;var F=B.getData(O);if(!F)return!1}catch(A){return!1}return!0},extractAllTo:function(O,B,F,A){if(F=c2(!1,F),A=GN$(F,A),B=c2(!1,B),!G)throw r8.Errors.NO_ZIP();let _=[];G.entries.forEach(function(q){var w=j(O,Z(q.entryName));if(q.isDirectory){if(Y.makeDir(w),F)_.push({path:w,attr:q.header.fileAttr});return}var M=q.getData(A);if(!M)throw r8.Errors.CANT_EXTRACT_FILE();let C=F?q.header.fileAttr:void 0;Y.writeFileTo(w,M,B,C);try{Y.fs.utimesSync(w,q.header.time,q.header.time)}catch(f){}}),W(_)},extractAllToAsync:function(O,B,F,A){if(A=bH0(B,F,A),F=c2(!1,F),B=c2(!1,B),!A)return new Promise((I,c)=>{this.extractAllToAsync(O,B,F,function(h){if(h)c(h);else I(this)})});if(!G){A(r8.Errors.NO_ZIP());return}O=o8.resolve(O);let _=(I)=>j(O,o8.normalize(Z(I.entryName))),q=(I,c)=>Error(I+': "'+c+'"'),w=[],M=[];G.entries.forEach((I)=>{if(I.isDirectory)w.push(I);else M.push(I)});let C=[];for(let I of w){let c=_(I),h=F?I.header.fileAttr:void 0;try{Y.makeDir(c)}catch(r){A(q("Unable to create folder",c));continue}if(h)C.push({path:c,attr:h});try{Y.fs.utimesSync(c,I.header.time,I.header.time)}catch(r){}}let f=(I)=>{if(!I)try{W(C)}catch(c){return A(q("Unable to set folder permissions",c.path||""))}A(I)};M.reverse().reduce(function(I,c){return function(h){if(h)I(h);else{let r=o8.normalize(Z(c.entryName)),t=j(O,r);c.getDataAsync(function(Y$,X$){if(X$)I(X$);else if(!Y$)I(r8.Errors.CANT_EXTRACT_FILE());else{let L$=F?c.header.fileAttr:void 0;Y.writeFileToAsync(t,Y$,B,L$,function(O$){if(!O$)return I(q("Unable to write file",t));Y.fs.utimes(t,c.header.time,c.header.time,function(){I()})})}})}}},f)()},writeZip:function(O,B){if(arguments.length===1){if(typeof O==="function")B=O,O=""}if(!O&&Q.filename)O=Q.filename;if(!O)return;var F=G.compressToBuffer();if(F){var A=Y.writeFileTo(O,F,!0);if(typeof B==="function")B(!A?Error("failed"):null,"")}},writeZipPromise:function(O,B){let{overwrite:F,perm:A}=Object.assign({overwrite:!0},B);return new Promise((_,q)=>{if(!O&&Q.filename)O=Q.filename;if(!O)q("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((w)=>{let M=(C)=>C?_(C):q("ADM-ZIP: Wasn't able to write zip file");Y.writeFileToAsync(O,w,F,A,M)},q)})},toBufferPromise:function(){return new Promise((O,B)=>{G.toAsyncBuffer(O,B)})},toBuffer:function(O,B,F,A){if(typeof O==="function")return G.toAsyncBuffer(O,B,F,A),null;return G.compressToBuffer()}}}});function jN$($,J,X=j5){if(X.length===0)return"";let Y=$.trim().toLowerCase()===Z5?X[0]:X.find((W)=>W.version===$);if(!Y)return"";return J==="android"?Y.apkSha256:Y.ipaSha256}function Lb($=process.env,J=j5){if(J.length===0)return;let X=Z4($);return X===Z5?J[0]:J.find((Q)=>Q.version===X)}function Ve($=process.env,J=j5){return Lb($,J)?.runnerSha256??""}function VN$($=process.env,J=j5){return Lb($,J)?.runnerSha256Target??"runner"}function fH0($=j5){if($.length===0)return Z5;return $[0].version}function E9($,J=j5){if($===Z5)return fH0(J);return $}function gH0($){let J=$[KN$];return J==="1"||J?.toLowerCase()==="true"}function Ke($,J,X=process.env){let Q;try{Q=new URL($)}catch{throw new R(`${J} must be an absolute URL, for example https://mirror.example/auto-mobile.`)}if(Q.protocol==="https:")return;if(gH0(X))return;throw new R(`${J} must use https:// (got ${Q.protocol}//). Plaintext/non-TLS asset downloads are a confidentiality and downgrade risk. Set ${KN$}=1 to opt out for a trusted loopback/dev mirror.`)}function Z4($=process.env){let J=$[hH0]?.trim();if(!J||J.length===0)return Z5;return J.toLowerCase()===Z5?Z5:J}function pj($=process.env){return Z4($)!==Z5}function n2($=process.env,J=j5){let X=Z4($);if(X===Z5)return J.length>0;return J.some((Q)=>Q.version===X)}function Hb($=process.env){let J=$[zb]?.trim();if(J&&J.length>0){let X;try{X=new URL(J)}catch{throw new R(`${zb} must be an absolute URL, for example https://mirror.example/auto-mobile.`)}if(J.includes("?")||J.includes("#"))throw new R(`${zb} must not include a query string or fragment; use a path-only base URL such as ${X.origin}${X.pathname.replace(/\/+$/,"")}.`);return Ke(`${X.origin}${X.pathname}`,zb,$),`${X.origin}${X.pathname}`.replace(/\/+$/,"")}return je}function Ob($,J,X=je,Q=j5){let Y=E9(J,Q);if(Y===Z5){if(X===je)return`https://github.com/kaeawc/auto-mobile/releases/latest/download/${$}`;return`${X}/latest/${$}`}return`${X}/${Y}/${$}`}function cj($=process.env,J=j5){return Ob("control-proxy-debug.apk",Z4($),Hb($),J)}function d2($=process.env,J=j5){return Ob("control-proxy.ipa",Z4($),Hb($),J)}function NU($=process.env){return jN$(Z4($),"android")}function i2($=process.env){return jN$(Z4($),"ios")}function UN$($=process.env,J=j5){return Ob(uH0,Z4($),Hb($),J)}function zN$($=process.env,J=j5){return Lb($,J)?.videoJarSha256??""}function LN$($=process.env,J=j5){return Ob(Ue,Z4($),Hb($),J)}function HN$($=process.env,J=j5){return Lb($,J)?.screenCaptureHelperSha256??""}function T7($=process.env){return`${vH0}@${E9(Z4($))}`}var Z5="latest",j5,vH0="@kaeawc/auto-mobile",hH0="AUTOMOBILE_VERSION",zb="AUTOMOBILE_ASSET_BASE_URL",KN$="AUTOMOBILE_ALLOW_INSECURE_ASSET_URL",je="https://github.com/kaeawc/auto-mobile/releases/download",uH0="automobile-video.jar",Ue="screen-capture-helper-macos-universal.zip",VT1,KT1,UT1,zT1,Bb="",LT1;var TJ=D(()=>{l4();j5=[{version:"0.0.52",apkSha256:"b733c267e42d4af3b24ba15ae7c94393cdf775018c3167deb13d06f33c6d5124",ipaSha256:"f8c9d00607dfc9c25bd7ee3de785f5a0f7e516ee90c6a7209ae5af9129063be5",runnerSha256:"7573432ea9c86c29acec30662ad7512cdb299150bc607350c7e3361882577f1c",runnerSha256Target:"xctest",videoJarSha256:"e5ce791aed17a1bf391db5737367a8ca2d7792b805f2fa4235e4ec7f8cee062c",screenCaptureHelperSha256:"f15e2bc4f4b2fece0daa85cb3fa3acbfcd08318cc420fc0637b469cd078d34b8"},{version:"0.0.51",apkSha256:"e9da610303113dd13094b3f885090b846f5b8705ac203b09deeb267801049255",ipaSha256:"db5606723087f7b973893d4adefcdeb6aadf1da0e2bcc435ce1fe8787bafb712",runnerSha256:"abba47298118068aaad3b8ea4502d685263b6e83cd2c30bb0518840cb8443202",runnerSha256Target:"xctest",videoJarSha256:"e5ce791aed17a1bf391db5737367a8ca2d7792b805f2fa4235e4ec7f8cee062c",screenCaptureHelperSha256:"a46ec61cdd2c3ab64e0f621f3498726578e52bee407d16cd90cde32ca8164798"},{version:"0.0.50",apkSha256:"8007f267d566144d805d29d22fb0e69790d34edcdbdd0d444bad6d80175943e2",ipaSha256:"838025a37b8a9f0d15b0b1ad06ff40e5a2b0b3e09eeca845f9a874d3bac4030d",runnerSha256:"5e53b1614986f90b875e5ada0a8c97f5343c22e70bdaeafd9a8389e5b6ef78ae",runnerSha256Target:"xctest",videoJarSha256:"254d1bad102a96b1e8e90ee9ff6ff991aa6d65f7a36a35c3887db91f369ea12e",screenCaptureHelperSha256:"965a49653d0c8bc8a88d45e1919ef0a62267d6774c50579411076dbe397bb89d"},{version:"0.0.49",apkSha256:"c1023110ebbd12c012880b08be6715d2389294fd24c4a147a40d1d342ec473da",ipaSha256:"dbeacd346a39976414432964de1250a3f356baf783cd3a83d916f0117e772d5b",runnerSha256:"fc033a529c67d373c6eca965ec063343b6164628d62e14eca220385810427ae6",runnerSha256Target:"xctest",videoJarSha256:"254d1bad102a96b1e8e90ee9ff6ff991aa6d65f7a36a35c3887db91f369ea12e",screenCaptureHelperSha256:"67079809a52e3cad50a38f04e4e25d795c0756b35352b377ba9609bebb62ab0f"},{version:"0.0.48",apkSha256:"059162e622fbe25bce40b32658c9749318a909eb8b48398648c77a84cf3c25aa",ipaSha256:"86558163f69a0bf36e69546dbf685d16d8f3bf05385f1f7795a164e3a5fddf96",runnerSha256:"ff000ff053a57a1dac1d552463e474fdea5346acb08c96051695554e73428317",runnerSha256Target:"xctest",videoJarSha256:"1cada2f3bc86cacbed76efc8e46c1e110cb0b046036502b422d67cce0725cf4b",screenCaptureHelperSha256:"f284e9863cedb2e02de25f526114fd4017eece1ce1e19337210647c7b49d1898"},{version:"0.0.47",apkSha256:"aa50a056447337ca14c251795b064e792879a28d088fe484fe57893a020b9323",ipaSha256:"ef5d10dd97d78d8e372680fffbb511335781b03ffbf0c91e2692048da4c5f143",runnerSha256:"078375d34d3e8bfa0c3171e3f1a6558d0ca2c0ca1f0c5999cb49077934fbfc0a",runnerSha256Target:"xctest",videoJarSha256:"5e3760d04436af89ec909586bd244d79cd7acec9b84993f4302fa7bf480916cb",screenCaptureHelperSha256:"501e1253ded9fa2f331051b88013b47ca37343a1966fc106d4fcaa5e9bbe4c39"},{version:"0.0.46",apkSha256:"00771c13f372baff325c659e2b40050e72951fd8adfc395cff667850a2a9b376",ipaSha256:"ef353a4f14fa7615810de891595d118ff193d43fcc940f936f4d11ae311dd563",screenCaptureHelperSha256:"da7e138266156eedda9f8cb98bb7d5b63f29ad28746a1c144a16122a1639e2b2",runnerSha256:"b0eb970aad424d1c0dd84261c26d74b8c95570ba0f3866f18f1755586184c51a",runnerSha256Target:"xctest",videoJarSha256:"3f3135e22fffed1e088bd434545eec873a5aec48c7c038cd2ffecdeb6b642c06"},{version:"0.0.45",apkSha256:"68dbf04ba3c1871da0ed9ec540e1dbfec08610dd2afc1706d4a7fd94d1c3b5b1",ipaSha256:"8c678b2d7ae4b5c25400f8fd53cb5e1f12d730950e0eef4e608dfb8b50dcd773",runnerSha256:"bb5234ca32636506e5b8e02662381895eaedeefbcf007598e3ee9b9ac3c501b5",runnerSha256Target:"xctest",videoJarSha256:"bae314fbaa3f3101ab5f7ba5eddc9bd77bb927c54cb508d38ed04ca9544b9a51"},{version:"0.0.44",apkSha256:"e95f2b14e218bc51e92a44680cf38ceca9c9143014b2f74b803f47650614cf39",ipaSha256:"73dd4551ef7226d67a46423f6925775fc10d68198913b5b23bc1cbdceb50b663",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.43",apkSha256:"7e4e2ce3c19b7473d171433186dbc7487df60ff6045dba66da7a320d31e63cd3",ipaSha256:"db0e3c4c172681068ae7ae24182f5569519b5fab034fbcf0e85abdc952b398dd",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.42",apkSha256:"cb00a835f58ce2d0344483f27b7c35036bb6faa973aa3fcc66fe67e75428abb0",ipaSha256:"de55b77ee0e821b4f08b7cd1b84f9a2706f69279422901546e2dc6fdd4cc3f0f",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.41",apkSha256:"ee1dff240e4dfc89b016197c80e929797485aa23292e061eee361b7404c772b4",ipaSha256:"01eaedef0cfcf38acd0a1fa8eebe08c3009e5db59320b23a045cd26506eb235c",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.40",apkSha256:"8e89fbab6462ac1ead1f3f0a334aff4f5f299e7ae72e192045cf75e893ca87aa",ipaSha256:"38adaed641ac6a8590773682e127a80a86c54e5804d47394e1b0cd437009b9ff",runnerSha256:"b281f9fd516116164a76dc049a413d5123bfb7bf96c79c6ad654ba90c08ed982"},{version:"0.0.39",apkSha256:"eaad59dd85e17c4633098b772b9f761f2124ffb73a5ca7ede703a9b435046942",ipaSha256:"87a720544c83718e5b70c987aecf30d2e43bdb0f23163ac75ac225bb4aec0ae4",runnerSha256:""},{version:"0.0.38",apkSha256:"0fb955a617654695036642662634d042c2e3d278b8e1dce20ccb37e425f059f3",ipaSha256:"f5a4a485ff8ebf3bfd0d73c8b7b10769177b419ccd62e48db188bb5122a2fcde",runnerSha256:""},{version:"0.0.37",apkSha256:"f9b0cc92bf8f7416cdb0c458e16c7a41e4fdeefb80bb9429ab7c603388c99083",ipaSha256:"caccbfaa4da0015bab701a36b81ac87e3f3f3330cee77bb10ec8553724275f4f",runnerSha256:""},{version:"0.0.36",apkSha256:"b5f56bb0ab065c60385a22013c97ee706213eb16deb5d4bcfa42f0a707b8620a",ipaSha256:"40e973dc8c87149e40a616658c74d90e648c6514cc642a5c3dd4a45a187e7600",runnerSha256:""},{version:"0.0.35",apkSha256:"039b359bcf35f1ab6cc666005a57823d71a771a96bd9bcaf4f82f2ec945e306d",ipaSha256:"e6afdfd04a90d2388dc4604e7957d3eef87b90a51ca37c5457b8139a54728108",runnerSha256:""},{version:"0.0.34",apkSha256:"4dcee4f6a7359847d081c5e184c57ed100ad135af2e62f3abfc7b0defaa1153c",ipaSha256:"c2a26ca065c85e9f8d5cfcd6dbad1dbaf3ce38b18d770b0983f7bad62129e4a3",runnerSha256:""},{version:"0.0.33",apkSha256:"7289eba90b22890d3c36e05e99db72a545fa4becdf46df079885783a919e6aed",ipaSha256:"425dfa4db4ad5a4febc9f05ffc97df38f3a1098ccdd9330adff1c0b5c877697d",runnerSha256:""},{version:"0.0.32",apkSha256:"4c4a743af5d18ed58214e64b85986c9e2f2332b015edcf7d9d68a24cd6dfda21",ipaSha256:"40f4d9084d3368995b57c0e81c4fe85f38851353da9f789eaff93027aee456a0",runnerSha256:""},{version:"0.0.31",apkSha256:"0b5802ada8d9adccdb69ee140ae788b3251832c0605d2f6baa3e9b7a78260764",ipaSha256:"e60f8689fb6ddd5c06a5d2ff57569b264f407229afb986258d1ce20326dc24c7",runnerSha256:""},{version:"0.0.30",apkSha256:"a1be5e6240f204ee99540e99cc198f7c0b592dbaf3699330c14f6ded7d333ec3",ipaSha256:"5ac285dd5be16439d3a8a8973c98606920461acfce489830e54ee20759a7b235",runnerSha256:""},{version:"0.0.29",apkSha256:"b33a67c7efa84aca2b07faa965aecb3b1819b4defd441dcc8d3bf7e2af209cd8",ipaSha256:"d47c1aea4495270c1489cae361286ea1439c2ba4e7d5bcfd73f66e4580a6c45d",runnerSha256:""},{version:"0.0.28",apkSha256:"0f683d5939bc308afe038ea1259eb29997dff38af0795136a281ad305986e40e",ipaSha256:"eee7accfbca717bb8b89fafd0676f10d8bb08561c3fbd7a04750c9b12c2a7104",runnerSha256:""},{version:"0.0.27",apkSha256:"9966113ae44f38f3cf34544b1375d3c9a3706701edba45a1eec1f220b9c676cc",ipaSha256:"8620de6b014df18465876334f9ba8c106292f6c3059370eea2349f1e44db4f4d",runnerSha256:""},{version:"0.0.26",apkSha256:"2eb2f156fd27602c85003ab8f6e00d3e06850e84f5453d75b7494aa5bbed7be0",ipaSha256:"905df276d2224d31cbc5aa2258d2dcc60eaeb9813727081ddd32c95394fec411",runnerSha256:""},{version:"0.0.25",apkSha256:"f727079edb4906e3b7928dbb641e788543e86b11fff3fc1b76f0c51b9c8d6e5d",ipaSha256:"d8032cc1cebcb456b7232aa67fc42c89ff62729bacf141aa8f594ce6f8bcd980",runnerSha256:""},{version:"0.0.24",apkSha256:"9047795bc6098f4ec687c126123c73c423806a9fd52888af391d6fb5b94ac93f",ipaSha256:"1dd3e0370cb8ed01d8e1020558d8a2808f208bd947bafcf6688211eddc928bf8",runnerSha256:""},{version:"0.0.18",apkSha256:"fd3c8d9f0b8542eaad56c78b18cf8e5666367b04ae8c4af74d8aa6dd1c8d1834",ipaSha256:"2a5eec63bce2f9dfc227c0732fcce67378305e945604d5eedd0e3df48e37fd39",runnerSha256:""},{version:"0.0.17",apkSha256:"916033440931666644474f227c8e39d13d9c80c3515e4292cc5581fd5bd4cc2f",ipaSha256:"e4dcf064d024f2371b8fd79281000e2d49751ef95b8817d1494d685aeda746ac",runnerSha256:""}];VT1=cj({}),KT1=NU({}),UT1=d2({}),zT1=i2({}),LT1=Ve({})});import{createReadStream as mH0}from"fs";import{createHash as lH0}from"crypto";class c5{async computeFileSha256($){let J=lH0("sha256");return await new Promise((X,Q)=>{let Y=mH0($);Y.on("data",(W)=>J.update(W)),Y.on("error",Q),Y.on("end",()=>X())}),{checksum:J.digest("hex"),source:"node"}}}var AU=()=>{};import{execFile as pH0}from"child_process";import{createWriteStream as cH0}from"fs";import*as BN$ from"fs/promises";import nH0 from"http";import dH0 from"https";import*as DN$ from"path";import{promisify as iH0}from"util";class BY{async download($,J,X){if(X?.aborted)throw Error(`Download aborted before starting: ${$}`);await BN$.mkdir(DN$.dirname(J),{recursive:!0});try{await this.downloadWithCurl($,J,X);return}catch(Q){if(!this.isCommandUnavailable(Q,"curl"))throw Q;U.warn("[FileDownloader] curl unavailable, falling back to wget",{error:Q instanceof Error?Q.message:String(Q)})}try{await this.downloadWithWget($,J,X);return}catch(Q){if(!this.isCommandUnavailable(Q,"wget"))throw Q;U.warn("[FileDownloader] wget unavailable, falling back to Node HTTP",{error:Q instanceof Error?Q.message:String(Q)})}await this.downloadWithNodeHttp($,J,0,X)}async downloadWithCurl($,J,X){await ON$("curl",["--fail","--location","--retry","3","--retry-delay","1","--silent","--show-error","-o",J,$],{timeout:120000,maxBuffer:10485760,signal:X})}async downloadWithWget($,J,X){await ON$("wget",["--tries=3","--timeout=30","-O",J,$],{timeout:120000,maxBuffer:10485760,signal:X})}async downloadWithNodeHttp($,J,X,Q){if(X>5)throw Error(`Too many redirects while downloading ${$}`);await new Promise((Y,W)=>{let G=$.startsWith("https:")?dH0:nH0,Z=()=>{j.destroy(Error(`Download aborted: ${$}`))},j=G.get($,{headers:{"User-Agent":"auto-mobile"}},(V)=>{let K=V.statusCode??0;if(K>=300&&K<400&&V.headers.location){V.resume();let L=new URL(V.headers.location,$).toString();this.downloadWithNodeHttp(L,J,X+1,Q).then(Y).catch(W);return}if(K<200||K>=300){V.resume(),W(Error(`Download failed with status ${K} from ${$}`));return}let z=cH0(J);V.pipe(z),z.on("finish",()=>z.close(()=>Y())),z.on("error",(L)=>{z.close(),W(L)})});if(j.setTimeout(30000,()=>{j.destroy(Error(`Download request timed out for ${$}`))}),j.on("error",W),j.once("close",()=>Q?.removeEventListener("abort",Z)),Q?.addEventListener("abort",Z,{once:!0}),Q?.aborted)Z()})}isCommandUnavailable($,J){if(!$||typeof $!=="object")return!1;let X=$,Q=typeof X.code==="number"?X.code:Number(X.code);if(X.code==="ENOENT"||!Number.isNaN(Q)&&Q===127)return!0;let Y=`${X.message??""} ${X.stderr??""}`.toLowerCase();if(Y.includes("command not found")||Y.includes("not recognized as an internal or external command")||Y.includes(`${J}: not found`)||Y.includes(`not found: ${J}`))return!0;return!1}}var ON$;var fB=D(()=>{d();ON$=iH0(pH0)});import{setTimeout as oH0}from"timers/promises";class vB{async sleep($){return oH0($)}setTimeout($,J){return global.setTimeout($,J)}clearTimeout($){global.clearTimeout($)}setInterval($,J){return global.setInterval($,J)}clearInterval($){global.clearInterval($)}now(){return Date.now()}}var u;var U$=D(()=>{u=new vB});import*as V5 from"fs/promises";import Db from"path";class C7{static instance=null;static expectedChecksumOverride=null;downloader;checksumCalculator;cacheDir;usesDefaultCacheDir;timer;env;inFlight=null;constructor($={}){this.downloader=$.downloader??new BY,this.checksumCalculator=$.checksumCalculator??new c5,this.timer=$.timer??u,this.env=$.env??process.env,this.usesDefaultCacheDir=$.cacheDir===void 0,this.cacheDir=$.cacheDir??H9(qN$)}static getInstance(){if(C7.instance===null)C7.instance=new C7;return C7.instance}static resetInstances(){C7.instance=null,C7.expectedChecksumOverride=null}static setExpectedChecksumForTesting($){C7.expectedChecksumOverride=$}async computeLocalJarIntegrity($){let[{checksum:J},X]=await Promise.all([this.checksumCalculator.computeFileSha256($),V5.stat($)]);return{sha256:J.toLowerCase(),size:X.size}}get cachedJarPath(){return Db.join(this.cacheDir,wN$)}get metadataPath(){return Db.join(this.cacheDir,NN$)}expectedChecksum(){return C7.expectedChecksumOverride??zN$(this.env)}async ensure(){if(this.inFlight!==null)return this.inFlight;return this.inFlight=this.doEnsure().finally(()=>{this.inFlight=null}),this.inFlight}async doEnsure(){let $=this.expectedChecksum();if($.length===0)return U.info("[VIDEO_JAR] Expected checksum unknown for the pinned version; returning null without touching the network (jar is integrity-unverifiable)"),null;let J=await this.tryCache($);if(J)return U.info("[VIDEO_JAR] Reusing verified cached jar",{path:J}),J;return this.download($)}async tryCache($){let J;try{J=JSON.parse(await V5.readFile(this.metadataPath,"utf8"))}catch(Q){return U.debug(`[VIDEO_JAR] No usable cache metadata (cache miss): ${Q}`),null}if(J.sha256.toLowerCase()!==$.toLowerCase())return null;let X;try{X=await V5.stat(this.cachedJarPath)}catch(Q){return U.debug(`[VIDEO_JAR] Cached jar file missing despite metadata: ${Q}`),null}if(X.size!==J.size)return U.warn("[VIDEO_JAR] Cached jar size differs from sidecar; will re-download",{expected:J.size,actual:X.size}),null;return this.cachedJarPath}async ensureSecureCacheDir(){if(this.usesDefaultCacheDir)return qU(qN$);return await V5.mkdir(this.cacheDir,{recursive:!0,mode:rH0}),this.cacheDir}async download($){let J=UN$(this.env),X=await this.ensureSecureCacheDir(),Q=Db.join(X,wN$),Y=`${Q}.download`;U.info("[VIDEO_JAR] Downloading persistent-encoder jar",{url:J,destination:Y});try{await this.downloader.download(J,Y),await V5.chmod(Y,FN$);let{checksum:W}=await this.checksumCalculator.computeFileSha256(Y);if(W.toLowerCase()!==$.toLowerCase())throw new R(`video-server jar checksum verification failed. Expected: ${$}, Got: ${W}. The downloaded automobile-video.jar does not match the pinned release checksum; this indicates a corrupted or tampered download and is never silently accepted.`);if(!this.hasClassesDex(Y))throw new R("video-server jar is not a valid zip containing classes.dex (truncated or error-page download).");let{size:G}=await V5.stat(Y);return await V5.rename(Y,Q),await this.writeMetadata(X,W,G),U.info("[VIDEO_JAR] Downloaded, verified, and cached jar",{path:Q,sha256:W}),Q}catch(W){throw await V5.rm(Y,{force:!0}).catch(()=>{}),W}}async writeMetadata($,J,X){let Q={version:Z4(this.env),sha256:J,size:X,downloadedAt:this.timer.now()};await V5.writeFile(Db.join($,NN$),JSON.stringify(Q,null,2),{encoding:"utf8",mode:FN$})}hasClassesDex($){try{return new AN$.default($).getEntries().some((X)=>X.entryName===tH0)}catch(J){return U.warn("[VIDEO_JAR] Structural check failed (not a valid zip)",{path:$,error:J instanceof Error?J.message:String(J)}),!1}}}var AN$,FN$=384,rH0=448,qN$="video-server",wN$="automobile-video.jar",NN$="video-server-jar.json",tH0="classes.dex";var Fb=D(()=>{TJ();l4();AU();fB();d();U$();MX();AN$=y1(x_(),1)});function t8($){return $===!0||$==="true"}function _N$($){return $===!1||$==="false"}function ze($){return typeof $==="string"&&aH0.has($)}var aH0;var Le=D(()=>{aH0=new Set(["done","go","search","send"])});function DY($){if(!$)return null;let{nativeScale:J,pixelWidth:X,pixelHeight:Q}=$;if(typeof J!=="number"||!Number.isFinite(J)||J<=0||typeof X!=="number"||!Number.isFinite(X)||X<=0||typeof Q!=="number"||!Number.isFinite(Q)||Q<=0)return null;return{nativeScale:J,pixelWidth:X,pixelHeight:Q}}function b_($){return DY($)??{}}var He="immediate";var t$=D(()=>{l4();Le()});function RN$($){return $==="main"?"4d002a":"42e02a"}function hB($,J){return Math.ceil($/16)*Math.ceil(J/16)}function EN$($){return $.length>=4&&($[0]&31)===7?$.subarray(1,4).toString("hex"):void 0}function sH0($){let J=EN$($);return J?Number.parseInt(J.slice(4,6),16):void 0}function PN$($,J="constrained-baseline"){let X=EN$($);if(X&&!Be(X,J))return{compatible:!1,reason:`H.264 SPS profile ${X.slice(0,4)} is incompatible with negotiated ${J}.`};let Q=sH0($);if(Q!==void 0&&Q>42)return{compatible:!1,reason:`H.264 SPS level ${Q} exceeds negotiated level 42.`};return{compatible:!0}}function Be($,J){return J==="main"?$O0($):eH0($)}function eH0($){return Number.parseInt($.slice(0,2),16)===66}function $O0($){return Number.parseInt($.slice(0,2),16)===77}var MN$="constrained-baseline",Oe=42,dW=8192;class y_{chunks=[];headOffset=0;length=0;append($){if($.length===0)return;this.chunks.push($),this.length+=$.length}peek($){if($>this.length)throw RangeError(`cannot peek ${$} bytes from ${this.length}-byte queue`);let J=this.chunks[0];if(J.length-this.headOffset>=$)return J.subarray(this.headOffset,this.headOffset+$);let Q=Buffer.allocUnsafe($);return this.copyTo(Q,$),Q}takeDetached($){if($>this.length)throw RangeError(`cannot take ${$} bytes from ${this.length}-byte queue`);let J=Buffer.allocUnsafe($);return this.copyTo(J,$),this.discard($),J}discard($){if($>this.length)throw RangeError(`cannot discard ${$} bytes from ${this.length}-byte queue`);let J=$;while(J>0){let Q=this.chunks[0].length-this.headOffset;if(J<Q){this.headOffset+=J,this.length-=J;return}this.chunks.shift(),this.headOffset=0,this.length-=Q,J-=Q}}toBuffer(){if(this.length===0)return Buffer.alloc(0);let $=this.chunks[0];if(this.chunks.length===1)return $.subarray(this.headOffset);let J=Buffer.allocUnsafe(this.length);return this.copyTo(J,this.length),J}replace($){this.chunks=$.length===0?[]:[$],this.headOffset=0,this.length=$.length}copyTo($,J){let X=0;for(let Q=0;X<J;Q++){let Y=this.chunks[Q],W=Q===0?this.headOffset:0,G=Y.length-W,Z=Math.min(G,J-X);Y.copy($,X,W,W+Z),X+=Z}}}class wb{buffer=new y_;pendingHeader=null;highWaterMarkBytes=0;resynchronizing=!1;push($,J,X,Q,Y){let W=[],G=0;while(G<$.length){let Z=_U+qb-this.buffer.length;if(Z===0){if(!this.decodeAvailable(W,J,X,Q,Y))throw Error("FrameDecoder reached its raw-frame buffer limit without a complete frame");continue}let j=Math.min($.length,G+Z);this.buffer.append($.subarray(G,j)),this.highWaterMarkBytes=Math.max(this.highWaterMarkBytes,this.buffer.length),G=j,this.decodeAvailable(W,J,X,Q,Y)}return W}getMetrics(){return{bufferedBytes:this.buffer.length,highWaterMarkBytes:this.highWaterMarkBytes,maxBufferedBytes:_U+qb}}decodeAvailable($,J,X,Q,Y){let W=!1;while(!0){if(this.resynchronizing&&!this.resynchronize())return W;if(this.pendingHeader===null){let V=this.takeHeader(J);if(V==="starved")return W;if(V==="malformed"){W=!0;continue}this.pendingHeader=V,W=!0}let G=this.pendingHeader,Z=GO0(G);if(this.buffer.length<Z)return W;let j=this.buffer.takeDetached(Z);this.emitRecord(G,j,$,X,Q,Y),this.pendingHeader=null,W=!0}}emitRecord($,J,X,Q,Y,W){if(qe($)){Q?.({pcm16le:J});return}if(we($)){W?.({keyframe:($.height&WO0)!==0,presentationTimestampMs:$.timestampMs,payload:J});return}let G={header:$,pixels:J};if(Y)Y(G);else X.push(G)}takeHeader($){if(this.buffer.length<_U)return"starved";let J=this.buffer.peek(_U),X=CN$(J,0);if(X)return this.resynchronizing=!0,$?.({reason:X,header:Fe(J,0)}),"malformed";let Q=Fe(J,0);return this.buffer.discard(_U),Q}resynchronize(){let $=this.buffer.toBuffer(),J=0;while(J<=$.length-De.length){let X=$.indexOf(De,J);if(X<0)break;if(X+_U>$.length)return this.replaceBuffer($.subarray(X)),!1;if(CN$($,X)===null)return this.replaceBuffer($.subarray(X)),this.resynchronizing=!1,!0;J=X+1}return this.replaceBuffer($.subarray(Math.max(0,$.length-(De.length-1)))),!1}replaceBuffer($){this.buffer.replace($.length===0?Buffer.alloc(0):Buffer.from($))}}function qe($){return $.width===0&&$.height===8000&&$.bytesPerRow===1}function we($){return $.width===0&&($.height&kN$)>>>0===IN$}function GO0($){if(qe($))return $.timestampMs;if(we($))return $.bytesPerRow;return $.height*$.bytesPerRow}function Fe($,J){return{width:$.readUInt32LE(J+8),height:$.readUInt32LE(J+12),bytesPerRow:$.readUInt32LE(J+16),timestampMs:$.readUInt32LE(J+20)}}function CN$($,J){if($.readUInt32LE(J)!==SN$)return"header_magic_mismatch";if($.readUInt32LE(J+4)!==xN$($.subarray(J+JO0,J+_U)))return"header_checksum_mismatch";return ZO0(Fe($,J))}function ZO0($){if(qe($))return $.timestampMs>QO0?"audio_payload_too_large":null;if(we($))return $.bytesPerRow>YO0?"encoded_video_payload_too_large":null;if($.width===0)return"header_width_zero";if($.height===0)return"header_height_zero";if($.bytesPerRow<$.width*4)return"header_bytes_per_row_too_small";if($.width>TN$||$.height>TN$)return"header_dimensions_out_of_range";if($.bytesPerRow>$.width*4+XO0)return"header_bytes_per_row_too_large";if($.height*$.bytesPerRow>qb)return"header_payload_too_large";return null}function VO0(){let $=new Uint32Array(256);for(let J=0;J<256;J++){let X=J;for(let Q=0;Q<8;Q++)X=(X&1)!==0?3988292384^X>>>1:X>>>1;$[J]=X>>>0}return $}function xN$($){let J=4294967295;for(let X=0;X<$.length;X++)J=J>>>8^jO0[(J^$[X])&255];return(J^4294967295)>>>0}var SN$=826690881,De,_U=24,JO0=8,TN$=16384,XO0=4096,qb=33554432,QO0=16777216,YO0=16777216,IN$=3798204416,kN$=4294967294,WO0=1,jO0;var Ne=D(()=>{De=Buffer.from([65,77,70,49]);jO0=VO0()});class gB{options;pending=null;droppedFrames=0;highWaterMarkBytes=0;lastCaptureTimestampMs=null;constructor($){this.options=$}enqueue($){if(this.lastCaptureTimestampMs=$.header.timestampMs,$.pixels.length>this.options.maxFrameBytes)return this.droppedFrames++,!1;if(this.pending!==null)this.droppedFrames++;return this.pending={frame:$,enqueuedAtMs:this.options.now()},this.highWaterMarkBytes=Math.max(this.highWaterMarkBytes,$.pixels.length),!0}take(){let $=this.pending;return this.pending=null,$?.frame??null}clear($=!1){if($&&this.pending!==null)this.droppedFrames++;this.pending=null}metrics(){let $=this.pending;return{captureTimestampMs:$?.frame.header.timestampMs??this.lastCaptureTimestampMs,frameAgeMs:$===null?null:Math.max(0,this.options.now()-$.enqueuedAtMs),queueDepth:$===null?0:1,droppedFrames:this.droppedFrames,bytesQueued:$?.frame.pixels.length??0,highWaterMarkBytes:this.highWaterMarkBytes,maxFrameBytes:this.options.maxFrameBytes}}}import{spawn as KO0}from"child_process";import{EventEmitter as UO0}from"events";function zO0($){let J=$.trim();if(!J.startsWith(Re))return null;let X=J.slice(Re.length).trim();return X.length>0?X:null}function LO0($){if(!$.startsWith(Me))return null;try{let J=JSON.parse($.slice(Me.length));if(!HO0(J))return null;return J}catch(J){return U.debug(`[IOSScreenCaptureHelper] ignored malformed native frame metrics: ${J instanceof Error?J.message:String(J)}`),null}}function HO0($){if($===null||typeof $!=="object")return!1;let J=$;return Ae(J.captureTimestampMs)&&Ae(J.frameQueueAgeMs)&&(J.frameQueueDepth===0||J.frameQueueDepth===1)&&_e(J.droppedFrames)&&_e(J.bytesQueued)&&_e(J.highWaterMarkBytes)&&Ae(J.lastOutputWriteDurationMs)}function Ae($){return $===null||typeof $==="number"&&Number.isFinite($)}function _e($){return typeof $==="number"&&Number.isFinite($)&&$>=0}function FO0($){switch($.kind){case"device":return $.deviceId!==void 0?["--device-id",$.deviceId]:[];case"simulator":{let J=["--simulator-window",String($.windowID)];if($.fps!==void 0){if(!Number.isInteger($.fps)||$.fps<f_||$.fps>v_)throw RangeError(`simulator fps must be an integer in [${f_}, ${v_}]; got ${$.fps}`);J.push("--simulator-fps",String($.fps))}if($.audio===!0)J.push("--audio");return qO0(J,$.encode),J}}}function qO0($,J){if(J===void 0)return;switch($.push("--encode",J.codec),J.bitrate.kind){case"explicitBps":$.push("--bitrate-bps",String(Math.round(J.bitrate.bps)));break;case"bitsPerPixel":$.push("--bits-per-pixel",String(J.bitrate.bpp));break;case"videoToolboxDefault":break}}var bN$=33554432,Me="automobile-frame-metrics:",Re="capture-capability:",o2="encoded-video-h264",f_=5,v_=60,Ee=5,r2,OO0,yN$=2000,BO0=($,J,X)=>KO0($,J,X),DO0=($,J)=>{process.kill(-$,J)};var uB=D(()=>{l4();d();U$();Ne();r2=class r2 extends UO0{binaryPath;target;spawner;timer;stopGraceMs;processGroupKiller;decoder=new wb;frameQueue;frameDeliveryScheduler;process=null;helperCapabilities=new Set;stderrBuffer="";exitPromise=null;frameDeliveryScheduled=!1;constructor($){super();this.binaryPath=$.binaryPath,this.target=$.target,this.spawner=$.spawner??BO0,this.timer=$.timer??u,this.stopGraceMs=$.stopGraceMs??yN$,this.processGroupKiller=$.processGroupKiller??DO0,this.frameQueue=new gB({maxFrameBytes:bN$,now:$.now??Date.now}),this.frameDeliveryScheduler=$.frameDeliveryScheduler??OO0}on($,J){return super.on($,J)}emit($,...J){return super.emit($,...J)}get isRunning(){return this.process!==null&&this.process.exitCode===null&&!this.process.killed}getFrameMetrics(){return this.frameQueue.metrics()}start(){if(this.process!==null)throw Error("IOSScreenCaptureHelper already started");let $=FO0(this.target);this.emitReadiness("helper-executable-found",this.binaryPath);let J=this.spawner(this.binaryPath,$,{detached:process.platform==="darwin",stdio:["pipe","pipe","pipe"]});this.process=J,this.emitReadiness("helper-process-spawned",`pid=${J.pid??"?"}`),J.stdout.on("data",(X)=>{let Q=Buffer.isBuffer(X)?X:Buffer.from(X),Y=this.decoder.push(Q,(W)=>this.emit("malformed",W),(W)=>this.emit("audio",W),(W)=>this.enqueueFrame(W),(W)=>this.emit("encodedVideo",W));for(let W of Y)this.enqueueFrame(W)}),J.stderr.on("data",(X)=>{let Q=Buffer.isBuffer(X)?X.toString("utf8"):String(X);this.appendStderr(Q)}),J.once("error",(X)=>{this.emit("error",X instanceof Error?X:Error(String(X)))}),this.exitPromise=new Promise((X)=>{J.once("exit",(Q,Y)=>{if(this.stderrBuffer.length>0)this.handleStderrLine(this.stderrBuffer),this.stderrBuffer="";let W={code:Q,signal:Y};this.emit("exit",W),X(W)})}),U.debug(`[IOSScreenCaptureHelper] spawned ${this.binaryPath} pid=${J.pid??"?"}`)}async stop(){let $=this.process;if($===null)return null;if($.exitCode!==null||$.killed){let X=await this.waitForExitWithinGrace();return this.cleanupProcess($),X??{code:$.exitCode,signal:$.signalCode}}$.kill("SIGTERM");let J=await this.waitForExitWithinGrace();if(J!==null)return this.cleanupProcess($),J;if(U.warn(`[IOSScreenCaptureHelper] helper pid=${$.pid??"?"} did not exit after SIGTERM; escalating to SIGKILL`),$.kill("SIGKILL"),process.platform==="darwin")if($.pid!==void 0)try{this.processGroupKiller($.pid,"SIGKILL")}catch(X){U.warn(`[IOSScreenCaptureHelper] process-group cleanup failed for pid=${$.pid}; detached children may leak: ${X}`)}else U.warn("[IOSScreenCaptureHelper] helper pid unknown after SIGKILL; cannot group-kill, detached children may leak");return this.cleanupProcess($),{code:$.exitCode,signal:$.signalCode??"SIGKILL"}}appendStderr($){if(this.stderrBuffer+=$,this.stderrBuffer.length>r2.STDERR_BUFFER_MAX){this.emit("stderr",this.stderrBuffer),this.stderrBuffer="";return}let J=this.stderrBuffer.split(`
|
|
20
20
|
`);this.stderrBuffer=J.pop()??"";for(let X of J)this.handleStderrLine(X)}enqueueFrame($){if(!this.frameQueue.enqueue($)){this.emit("frameMetrics",this.frameQueue.metrics());return}if(this.emit("frameMetrics",this.frameQueue.metrics()),this.frameDeliveryScheduled)return;this.frameDeliveryScheduled=!0,this.frameDeliveryScheduler.schedule(()=>this.deliverLatestFrame())}deliverLatestFrame(){this.frameDeliveryScheduled=!1;let $=this.frameQueue.take();if($===null)return;if(this.emit("frame",$),this.emit("frameMetrics",this.frameQueue.metrics()),this.frameQueue.metrics().queueDepth===1)this.frameDeliveryScheduled=!0,this.frameDeliveryScheduler.schedule(()=>this.deliverLatestFrame())}handleStderrLine($){let J=LO0($);if(J!==null){this.emit("captureMetrics",J);return}let X=zO0($);if(X!==null){this.helperCapabilities.add(X),this.emit("capability",X);return}this.emit("stderr",$),this.emitReadinessFromMarker($)}get capabilities(){return this.helperCapabilities}supportsEncodedVideo(){return this.helperCapabilities.has(o2)}requestKeyFrame(){let $=this.process;if($===null||!this.isRunning)return!1;try{return $.stdin.write(`${JSON.stringify({cmd:"forceKeyFrame"})}
|
|
21
21
|
`),!0}catch(J){return U.debug(`[IOSScreenCaptureHelper] forceKeyFrame control write failed: ${J}`),!1}}assertSupportsEncodedVideo(){if(this.supportsEncodedVideo())return;throw new R("The screen-capture-helper did not advertise the '"+o2+"' capability at startup, so it cannot emit encoded H.264 video. This is an outdated helper. Unset AUTOMOBILE_IOS_SCREEN_CAPTURE_HELPER to use the checksum-pinned release helper, or point it at a build that advertises '"+o2+"'.")}async waitForExitWithinGrace(){let $=this.exitPromise??Promise.resolve(null),J,X=new Promise((Q)=>{J=this.timer.setTimeout(()=>Q(null),this.stopGraceMs)});try{return await Promise.race([$,X])}finally{if(J)this.timer.clearTimeout(J)}}cleanupProcess($){if($.stdout.removeAllListeners(),$.stderr.removeAllListeners(),$.removeAllListeners(),this.frameQueue.clear(),this.frameDeliveryScheduled=!1,this.process===$)this.process=null}emitReadinessFromMarker($){let J=$.trim();if(J.startsWith("capture-phase: permission-ready"))this.emitReadiness("permission-ready");else if(J.startsWith("capture-phase: resolved-window"))this.emitReadiness("target-resolved",J);else if(J.startsWith("capture-phase: capture-started"))this.emitReadiness("capture-started",J);else if(J.startsWith("capture-phase: first-frame"))this.emitReadiness("first-frame",J)}emitReadiness($,J){this.emit("readiness",{phase:$,atMs:this.timer.now(),detail:J})}static STDERR_BUFFER_MAX=65536};OO0={schedule($){setImmediate($)}}});function AO0($){if(!$||!$.trim())return;let J=$.trim();if(J.startsWith("[")){let X;try{X=JSON.parse(J)}catch{throw new R(`Invalid JSON in ${X8.ICE_SERVERS}.`)}if(!Array.isArray(X))throw new R(`${X8.ICE_SERVERS} JSON must be an array of { urls } objects.`);let Q=[];for(let Y of X){let{username:W,credential:G}=Y??{};if(typeof Y?.urls==="string")Q.push({urls:Y.urls,username:W,credential:G});else if(Array.isArray(Y?.urls)&&Y.urls.every((Z)=>typeof Z==="string"))for(let Z of Y.urls)Q.push({urls:Z,username:W,credential:G});else throw new R(`${X8.ICE_SERVERS} JSON entries must have a string or string[] "urls".`)}return Q}return J.split(",").map((X)=>X.trim()).filter((X)=>X.length>0).map((X)=>({urls:X}))}function _O0($){if(!$||!$.trim())return;let J=/^(\d+)\s*x\s*(\d+)$/i.exec($.trim());if(!J)throw new R(`Invalid size "${$}"; expected WIDTHxHEIGHT (e.g. 1280x720).`);return cN$({width:Number(J[1]),height:Number(J[2])})}function Pe($){if(!$)return!1;return["1","true","yes","on"].includes($.trim().toLowerCase())}function MO0($){if(!$||!$.trim())return;let J=Number($.trim());if(!Number.isFinite(J)||J<=0)throw new R(`Invalid bitrate "${$}"; expected a positive number of kbps.`);return Math.round(J)}function mN$($={},J=process.env){let X=$.whipEndpoint??J[X8.WHIP_ENDPOINT];if(!X||!X.trim())throw new R(`No WHIP endpoint configured. Set ${X8.WHIP_ENDPOINT} or pass whipEndpoint.`);let Q=$.iceServers??AO0(J[X8.ICE_SERVERS])??NO0,Y=$.bitrateKbps===void 0?MO0(J[X8.BITRATE_KBPS]):PO0($.bitrateKbps),W=$.size===void 0?_O0(J[X8.MAX_SIZE]):cN$($.size),G=$.iosSimulatorFps===void 0?RO0(J[X8.IOS_SIMULATOR_FPS])??Te:lN$($.iosSimulatorFps),Z=$.androidFps===void 0?EO0(J[X8.ANDROID_FPS])??wO0:pN$($.androidFps),j=$.trickleIce??Pe(J[X8.TRICKLE_ICE]),V=$.audioEnabled??Pe(J[X8.AUDIO]);return{whipEndpoint:CO0(X,J),bearerToken:$.bearerToken??J[X8.WHIP_TOKEN]??void 0,iceServers:Q,bitrateKbps:Y,size:W,iosSimulatorFps:G,androidFps:Z,trickleIce:j,audioEnabled:V}}function RO0($){if(!$||!$.trim())return;return lN$(Number($.trim()),$.trim())}function lN$($,J=String($)){if(!Number.isInteger($)||$<fN$||$>vN$)throw new R(`Invalid iOS Simulator capture fps "${J}"; expected an integer in [${fN$}, ${vN$}]. Set ${X8.IOS_SIMULATOR_FPS} or pass iosSimulatorFps.`);return $}function EO0($){if(!$||!$.trim())return;return pN$(Number($.trim()),$.trim())}function pN$($,J=String($)){if(!Number.isInteger($)||$<hN$||$>gN$)throw new R(`Invalid Android capture fps "${J}"; expected an integer in [${hN$}, ${gN$}]. Set ${X8.ANDROID_FPS} or pass androidFps.`);return $}function PO0($){if(!Number.isFinite($)||$<=0)throw new R(`Invalid bitrate "${$}"; expected a positive number of kbps.`);return Math.round($)}function cN$($){let{width:J,height:X}=$;if(!Number.isSafeInteger(J)||!Number.isSafeInteger(X)||J<=0||X<=0||J%2!==0||X%2!==0||hB(J,X)>dW)throw new R(`Invalid size "${J}x${X}"; width and height must be positive even integers within the H.264 Level 4.2 frame limit.`);return{width:J,height:X}}function nN$($){let J=$.toLowerCase().replace(/^\[/,"").replace(/\]$/,"");if(TO0.has(J))return!0;return/^127(?:\.\d{1,3}){3}$/.test(J)}function dN$($=process.env){return Pe($[X8.ALLOW_INSECURE_WHIP])}function iN$($){let J=$.trim(),X;try{X=new URL(J)}catch{throw new R(`Invalid WHIP endpoint "${J}"; expected an absolute http(s) URL.`)}if(X.protocol!=="http:"&&X.protocol!=="https:")throw new R(`Invalid WHIP endpoint "${J}"; expected an absolute http(s) URL.`);return X}function CO0($,J=process.env){let X=iN$($);if(X.protocol==="http:"&&!nN$(X.hostname)&&!dN$(J))throw new R(`Refusing plaintext WHIP endpoint "${$.trim()}": http:// is only permitted for loopback (127.0.0.1/localhost/::1) because the bearer token and SDP would travel in cleartext. Use https://, or set ${X8.ALLOW_INSECURE_WHIP}=1 to allow insecure endpoints (not recommended).`);return $.trim()}function SO0($){if(!$||!$.trim())return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}function uN$($){let J=$.includes("://")?$:`https://${$}`;if(!URL.canParse(J))return;let X=new URL(J).origin;return X==="null"?void 0:X}function oN$($,J=process.env){if(dN$(J))return;let X=iN$($);if(nN$(X.hostname))return;let Q=new Set,Y=J[X8.WHIP_ENDPOINT];if(Y&&Y.trim()){let W=uN$(Y.trim());if(W)Q.add(W)}for(let W of SO0(J[X8.WHIP_ALLOWED_ORIGINS])){let G=uN$(W);if(G)Q.add(G)}if(!Q.has(X.origin))throw new R(`Refusing WHIP endpoint override "${$.trim()}": its origin ${X.origin} is not allow-listed. Add it to ${X8.WHIP_ALLOWED_ORIGINS} (comma-separated origins), align it with the daemon's ${X8.WHIP_ENDPOINT}, or set ${X8.ALLOW_INSECURE_WHIP}=1 to accept arbitrary destinations (not recommended).`)}var fN$,vN$,Te=15,hN$=1,gN$=60,wO0=30,X8,NO0,TO0;var mB=D(()=>{t$();uB();fN$=f_,vN$=v_,X8={WHIP_ENDPOINT:"AUTOMOBILE_WEBRTC_WHIP_ENDPOINT",WHIP_TOKEN:"AUTOMOBILE_WEBRTC_WHIP_TOKEN",ICE_SERVERS:"AUTOMOBILE_WEBRTC_ICE_SERVERS",BITRATE_KBPS:"AUTOMOBILE_WEBRTC_BITRATE_KBPS",MAX_SIZE:"AUTOMOBILE_WEBRTC_MAX_SIZE",IOS_SIMULATOR_FPS:"AUTOMOBILE_WEBRTC_IOS_SIMULATOR_FPS",ANDROID_FPS:"AUTOMOBILE_WEBRTC_ANDROID_FPS",TRICKLE_ICE:"AUTOMOBILE_WEBRTC_TRICKLE_ICE",AUDIO:"AUTOMOBILE_WEBRTC_AUDIO",ALLOW_INSECURE_WHIP:"AUTOMOBILE_WEBRTC_ALLOW_INSECURE_WHIP",WHIP_ALLOWED_ORIGINS:"AUTOMOBILE_WEBRTC_WHIP_ALLOWED_ORIGINS"},NO0=[{urls:"stun:stun.l.google.com:19302"}];TO0=new Set(["localhost","127.0.0.1","::1"])});import{existsSync as rN$}from"fs";import IO0 from"path";function aN$($){let J=$[tN$];return J&&rN$(J)?J:null}function kO0($){let J=IO0.resolve($,"android","video-server","build","libs","automobile-video.jar");return rN$(J)?J:null}async function Nb($={}){let J=$.env??process.env,X=$.cwd??process.cwd(),Q=aN$(J);if(Q)return U.info("[VIDEO_JAR] Using AUTOMOBILE_VIDEO_SERVER_JAR override",{path:Q}),Q;let Y=NQ(J[Se]),W=NQ(J[Ce]);if(!Y){let j=await($.provider??C7.getInstance()).ensure();if(j)return j}else U.info("[VIDEO_JAR] AUTOMOBILE_SKIP_VIDEO_SERVER_DOWNLOAD set; resolving local sources only");let G=kO0(X);if(G)return U.info("[VIDEO_JAR] Using local Gradle build output",{path:G}),G;if(W)throw new R(`${Ce} is set but no verifiable automobile-video.jar is available (no override, no ${Y?"":"downloadable or "}locally-built jar). Provide ${tN$}, build \`:video-server:d8Dex\`, pin a release whose checksum registry includes videoJarSha256, or unset ${Ce} to allow the screenrecord fallback.`);return U.info("[VIDEO_JAR] No verifiable jar available; degrading to screenrecord"),null}async function sN$($={}){let J=$.env??process.env;if(!J[X8.WHIP_ENDPOINT]?.trim()){U.debug("[VIDEO_JAR] No WHIP endpoint configured; skipping background jar prefetch");return}if(NQ(J[Se])){U.debug(`[VIDEO_JAR] ${Se} set; skipping background jar prefetch`);return}if(aN$(J)){U.debug("[VIDEO_JAR] Local override present; skipping background jar prefetch (download unused)");return}let Q=$.provider??C7.getInstance();U.info("[VIDEO_JAR] Prefetching video-server jar in the background (WebRTC streaming configured)");try{let Y=await Q.ensure();if(Y)U.info("[VIDEO_JAR] Background prefetch warmed the jar cache",{path:Y})}catch(Y){U.warn(`[VIDEO_JAR] Background jar prefetch failed: ${Y instanceof Error?Y.message:String(Y)}`,Y)}}var tN$="AUTOMOBILE_VIDEO_SERVER_JAR",Ce="AUTOMOBILE_REQUIRE_VIDEO_SERVER",Se="AUTOMOBILE_SKIP_VIDEO_SERVER_DOWNLOAD";var Ab=D(()=>{l4();d();Fb();mB()});import*as jJ from"fs/promises";import h_ from"path";class iW{static instance=null;downloader;checksumCalculator;cacheDir;usesDefaultCacheDir;timer;env;expectedChecksumOverride;releaseUrlOverride;downloadTimeoutMs;platform;inFlight=null;constructor($={}){this.downloader=$.downloader??new BY,this.checksumCalculator=$.checksumCalculator??new c5,this.cacheDir=$.cacheDir??H9(eN$),this.usesDefaultCacheDir=$.cacheDir===void 0,this.timer=$.timer??u,this.env=$.env??process.env,this.expectedChecksumOverride=$.expectedChecksum,this.releaseUrlOverride=$.releaseUrl,this.downloadTimeoutMs=$.downloadTimeoutMs??bO0,this.platform=$.platform??process.platform}static getInstance(){return iW.instance??=new iW,iW.instance}static resetInstances(){iW.instance=null}async ensure(){if(this.inFlight)return this.inFlight;return this.inFlight=this.doEnsure().finally(()=>{this.inFlight=null}),this.inFlight}async doEnsure(){let $=this.expectedChecksumOverride??HN$(this.env);if($.length===0)return U.info("[SCREEN_CAPTURE_HELPER] Expected checksum unknown for the pinned version; no release helper can be trusted."),null;let J=await this.tryCache($);if(J)return U.info("[SCREEN_CAPTURE_HELPER] Reusing verified release helper",{path:J}),J;return this.download($)}get helperPath(){return h_.join(this.cacheDir,g_)}get metadataPath(){return h_.join(this.cacheDir,YA$)}async tryCache($){let J;try{J=JSON.parse(await jJ.readFile(this.metadataPath,"utf8"))}catch(X){return U.debug("[SCREEN_CAPTURE_HELPER] No usable cached helper metadata",{error:X instanceof Error?X.message:String(X)}),null}if(J.sha256.toLowerCase()!==$.toLowerCase())return null;try{let X=await jJ.stat(this.helperPath);if(!X.isFile()||X.size!==J.size||this.platform!=="win32"&&(X.mode&73)===0)return null}catch(X){return U.debug("[SCREEN_CAPTURE_HELPER] No usable cached helper executable",{error:X instanceof Error?X.message:String(X)}),null}return this.helperPath}async ensureSecureCacheDir(){if(this.usesDefaultCacheDir)return qU(eN$);return await jJ.mkdir(this.cacheDir,{recursive:!0,mode:xO0}),this.cacheDir}async download($){let J=await this.ensureSecureCacheDir(),X=h_.join(J,`${QA$}.download`),Q=h_.join(J,`${g_}.download`),Y=new AbortController,W=this.timer.setTimeout(()=>Y.abort(),this.downloadTimeoutMs);try{await this.downloader.download(this.releaseUrlOverride??LN$(this.env),X,Y.signal),await jJ.chmod(X,$A$);let{checksum:G}=await this.checksumCalculator.computeFileSha256(X);if(G.toLowerCase()!==$.toLowerCase())throw new R(`screen-capture-helper checksum verification failed. Expected: ${$}, Got: ${G}. The downloaded release asset is corrupted or tampered.`);await jJ.writeFile(Q,yO0(X),{mode:JA$}),await jJ.chmod(Q,JA$);let{size:Z}=await jJ.stat(Q);return await jJ.rename(Q,this.helperPath),await jJ.writeFile(this.metadataPath,JSON.stringify({version:Z4(this.env),sha256:G,size:Z,downloadedAt:this.timer.now()},null,2),{encoding:"utf8",mode:$A$}),U.info("[SCREEN_CAPTURE_HELPER] Downloaded and verified release helper",{path:this.helperPath,sha256:G}),this.helperPath}catch(G){if(await Promise.all([jJ.rm(X,{force:!0}),jJ.rm(Q,{force:!0})]),Y.signal.aborted)throw new R(`Timed out downloading screen-capture-helper after ${this.downloadTimeoutMs}ms. Check GitHub Release asset availability or set AUTOMOBILE_IOS_SCREEN_CAPTURE_HELPER for local development.`);throw G}finally{this.timer.clearTimeout(W)}}}function yO0($){let J;try{J=new XA$.default($)}catch(Q){throw new R(`screen-capture-helper release asset is not a valid zip archive: ${Q instanceof Error?Q.message:String(Q)}`)}let X=J.getEntries().filter((Q)=>!Q.isDirectory&&h_.posix.basename(Q.entryName)===g_);if(X.length!==1)throw new R(`screen-capture-helper release asset must contain exactly one ${g_}.`);try{return X[0].getData()}catch(Q){if(Q instanceof R)throw Q;throw new R(`Unable to extract screen-capture-helper release asset: ${Q instanceof Error?Q.message:String(Q)}`)}}var XA$,eN$="screen-capture-helper",xO0=448,$A$=384,JA$=448,bO0=30000,QA$,g_="screen-capture-helper",YA$="screen-capture-helper.json";var _b=D(()=>{TJ();l4();AU();fB();d();U$();MX();XA$=y1(x_(),1),QA$=Ue});function Mb($,J){for(let X=0;X<$.length;X++){let Q=$[X];if(J.includes(Q)){let W=$[X+1];if(!W||W.startsWith("--"))return;return W}let Y=J.find((W)=>Q.startsWith(`${W}=`));if(Y)return Q.slice(Y.length+1)}return}function Rb($){for(let J=0;J<$.length;J++){let X=$[J];if(X.startsWith(`${oW}=`))return!0;if(X===oW){let Q=$[J+1];return Q!==void 0&&!Q.startsWith("--")}}return!1}function vO0($){return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}function Eb($,J){let X=Mb($,[oW])??J[fO0];if(!X)return[];return vO0(X)}var oW="--event-all-markers",fO0="AUTOMOBILE_EVENT_ALL_MARKERS";var Pb=()=>{};var WA$={};u1(WA$,{serverConfig:()=>f$});class lB{static instance;_uiPerfModeEnabled=!0;_accessibilityAuditConfig=null;_memPerfAuditEnabled=!1;_predictiveUiEnabled=!1;_rawElementSearchEnabled=!1;_planExecutionLockScope="session";_videoRecordingDefaults={};_deviceSnapshotDefaults={};_appearanceDefaults={};_skipCtrlProxyDownload=!1;_embeddedSdkEnabled=!1;_networkMockableEnabled=!1;_mcpRecordingEnabled=!1;_dismissKeyboardAfterInputEnabled=!1;_eventAllMarkers=[];_navigationScreenshotsEnabled=!0;_waitForPollingOverheadEnabled=!0;_a11yIncludeNotImportantViews=!0;_a11yReportViewIds=!0;_a11yRetrieveInteractiveWindows=!0;_occlusionEnabled=!0;_planExecutionActive=!1;_observeResultIncludeElements=!1;_toolResultsNoStructuredContent=!1;_actionsDiffObserve=!1;_actionsNoObserve=!1;_toolOutputsDir;constructor(){}static getInstance(){if(!lB.instance)lB.instance=new lB;return lB.instance}setUiPerfMode($){this._uiPerfModeEnabled=$}isUiPerfModeEnabled(){return this._uiPerfModeEnabled}setAccessibilityAuditConfig($){this._accessibilityAuditConfig=$}getAccessibilityAuditConfig(){return this._accessibilityAuditConfig}isAccessibilityAuditEnabled(){return this._accessibilityAuditConfig!==null}setMemPerfAuditMode($){this._memPerfAuditEnabled=$}isMemPerfAuditEnabled(){return this._memPerfAuditEnabled}setPredictiveUiEnabled($){this._predictiveUiEnabled=$}isPredictiveUiEnabled(){return this._predictiveUiEnabled}setRawElementSearchEnabled($){this._rawElementSearchEnabled=$}isRawElementSearchEnabled(){return this._rawElementSearchEnabled}setPlanExecutionLockScope($){this._planExecutionLockScope=$}getPlanExecutionLockScope(){return this._planExecutionLockScope}setVideoRecordingDefaults($){this._videoRecordingDefaults={...$}}getVideoRecordingDefaults(){return{...this._videoRecordingDefaults}}setDeviceSnapshotDefaults($){this._deviceSnapshotDefaults={...$}}getDeviceSnapshotDefaults(){return{...this._deviceSnapshotDefaults}}setAppearanceDefaults($){this._appearanceDefaults={...$}}getAppearanceDefaults(){return{...this._appearanceDefaults}}setToolOutputsDir($){this._toolOutputsDir=$}getToolOutputsDir(){return this._toolOutputsDir}isToolOutputArtifactModeEnabled(){return this._toolOutputsDir!==void 0}setSkipCtrlProxyDownload($){this._skipCtrlProxyDownload=$}isSkipCtrlProxyDownloadEnabled(){return this._skipCtrlProxyDownload}setEmbeddedSdkEnabled($){this._embeddedSdkEnabled=$}isEmbeddedSdkEnabled(){return this._embeddedSdkEnabled}setNetworkMockableEnabled($){this._networkMockableEnabled=$}isNetworkMockableEnabled(){return this._networkMockableEnabled}setMcpRecordingEnabled($){this._mcpRecordingEnabled=$}isMcpRecordingEnabled(){return this._mcpRecordingEnabled}setDismissKeyboardAfterInputEnabled($){this._dismissKeyboardAfterInputEnabled=$}isDismissKeyboardAfterInputEnabled(){return this._dismissKeyboardAfterInputEnabled}setEventAllMarkers($){this._eventAllMarkers=[...$]}getEventAllMarkers(){return this._eventAllMarkers}setNavigationScreenshotsEnabled($){this._navigationScreenshotsEnabled=$}isNavigationScreenshotsEnabled(){return this._navigationScreenshotsEnabled}setWaitForPollingOverheadEnabled($){this._waitForPollingOverheadEnabled=$}isWaitForPollingOverheadEnabled(){return this._waitForPollingOverheadEnabled}setA11yIncludeNotImportantViews($){this._a11yIncludeNotImportantViews=$}setA11yReportViewIds($){this._a11yReportViewIds=$}setA11yRetrieveInteractiveWindows($){this._a11yRetrieveInteractiveWindows=$}setOcclusionEnabled($){this._occlusionEnabled=$}getAccessibilityFlagsConfig(){return{includeNotImportantViews:this._a11yIncludeNotImportantViews,reportViewIds:this._a11yReportViewIds,retrieveInteractiveWindows:this._a11yRetrieveInteractiveWindows,occlusionEnabled:this._occlusionEnabled}}setPlanExecutionActive($){this._planExecutionActive=$}isPlanExecutionActive(){return this._planExecutionActive}setObserveResultIncludeElementsEnabled($){this._observeResultIncludeElements=$}isObserveResultIncludeElementsEnabled(){return this._observeResultIncludeElements}setToolResultsNoStructuredContentEnabled($){this._toolResultsNoStructuredContent=$}isToolResultsNoStructuredContentEnabled(){return this._toolResultsNoStructuredContent}setActionsDiffObserveEnabled($){this._actionsDiffObserve=$}isActionsDiffObserveEnabled(){return this._actionsDiffObserve}setActionsNoObserveEnabled($){this._actionsNoObserve=$}isActionsNoObserveEnabled(){return this._actionsNoObserve}}var f$;var t4=D(()=>{f$=lB.getInstance()});import GA$ from"path";function gO0($,J){let X=$?.trim();if(!X)return;return GA$.isAbsolute(X)?X:GA$.resolve(J,X)}function Tb($,J,X){let Q=Mb($,[Ie,ke]);return gO0(Q??J[xe]??J[hO0],X)}function ZA$(){return H9(ZJ.TOOL_OUTPUTS)}var Ie="--tool-outputs-dir",ke="--tool-output-dir",xe="AUTOMOBILE_TOOL_OUTPUTS_DIR",hO0="AUTO_MOBILE_TOOL_OUTPUTS_DIR";var Cb=D(()=>{t$();t4();MX()});class VA${lifecycleProcess;installed=!1;shutdownInProgress=!1;shutdownHandler;fatalProcessHandler;constructor($){this.lifecycleProcess=$}install(){if(this.installed)return;this.installed=!0,this.lifecycleProcess.on("SIGINT",()=>{this.shutdown("SIGINT")}),this.lifecycleProcess.on("SIGTERM",()=>{this.shutdown("SIGTERM")}),this.lifecycleProcess.on("uncaughtException",($)=>{this.handleFatalProcessEvent({type:"uncaughtException",error:$})}),this.lifecycleProcess.on("unhandledRejection",($,J)=>{this.handleFatalProcessEvent({type:"unhandledRejection",reason:$,promise:J})})}setShutdownHandler($){this.shutdownHandler=$}setFatalProcessHandler($){this.fatalProcessHandler=$}async shutdown($){if(this.shutdownInProgress)return;this.shutdownInProgress=!0;try{await this.shutdownHandler?.($),this.lifecycleProcess.exit(0)}catch(J){console.error(`Error during ${$} shutdown:`,J),this.lifecycleProcess.exit(1)}}async handleFatalProcessEvent($){let J=this.fatalProcessHandler;if(!J){if($.type==="uncaughtException")console.error("Uncaught exception:",$.error);else console.error("Unhandled rejection at:",$.promise,"reason:",$.reason);this.lifecycleProcess.exit(1);return}try{await J($)}catch(X){console.error("Error in fatal process handler:",X),this.lifecycleProcess.exit(1)}}}function Sb(){be.install()}function Ib($){be.setShutdownHandler($)}function kb($){be.setFatalProcessHandler($)}var be;var ye=D(()=>{be=new VA$(process)});function HA$($,J){for(let X of J)if($[X]!==void 0)return $[X];return}function ve($){let J=[],X=HA$($,["AUTOMOBILE_DEVICE_RECOVERY_ON_LOSS","AUTO_MOBILE_DEVICE_RECOVERY_ON_LOSS","AUTOMOBILE_ANDROID_REBOOT_ON_DEATH","AUTO_MOBILE_ANDROID_REBOOT_ON_DEATH"]),Q=!1;if(X!==void 0){if(X==="1")Q=!0;else if(X!=="0")J.push(`Invalid AUTOMOBILE_DEVICE_RECOVERY_ON_LOSS value ${JSON.stringify(X)}; using 0.`)}let Y=HA$($,["AUTOMOBILE_DEVICE_RECOVERY_MAX_ATTEMPTS","AUTO_MOBILE_DEVICE_RECOVERY_MAX_ATTEMPTS"]),W=2;if(Y!==void 0)if(/^[1-9]\d*$/.test(Y)){let G=Number(Y);if(G<=10)W=G;else J.push(`Invalid AUTOMOBILE_DEVICE_RECOVERY_MAX_ATTEMPTS value ${JSON.stringify(Y)}; using 2.`)}else J.push(`Invalid AUTOMOBILE_DEVICE_RECOVERY_MAX_ATTEMPTS value ${JSON.stringify(Y)}; using 2.`);return{policy:{onLoss:Q,maxAttempts:W},warnings:J}}function OA$(){return ve(process.env).policy}function nj(){return(process.env.AUTOMOBILE_DEVICE_POOL_AUTOLOCK??process.env.AUTO_MOBILE_DEVICE_POOL_AUTOLOCK)==="1"}function BA$(){let $=process.env.AUTOMOBILE_DEVICE_POOL_TIMEOUT??process.env.AUTO_MOBILE_DEVICE_POOL_TIMEOUT,J=$?Number.parseInt($,10):NaN;return Number.isFinite(J)&&J>0?J*1000:60000}var fe,lO0,xb;var pB=D(()=>{fe=process.env.AUTOMOBILE_DEVICE_POOL_MATCHING??process.env.AUTO_MOBILE_DEVICE_POOL_MATCHING,lO0=["LATEST","RANDOM","MINIMUM"],xb=fe&&lO0.includes(fe)?fe:"LATEST"});class qA${get($){return process.env[$]}}class wA${environment;constructor($=new qA$){this.environment=$}isCreationAllowed($){if(typeof $==="boolean")return $;return cO0(this.environment.get("AUTOMOBILE_ALLOW_DEVICE_CREATE"))}describeSource($){if(typeof $==="boolean")return`--create-if-missing=${$}`;let J=this.environment.get("AUTOMOBILE_ALLOW_DEVICE_CREATE");if(J===void 0)return"default (off)";return`AUTOMOBILE_ALLOW_DEVICE_CREATE=${J}`}}function cO0($){if($===void 0)return!1;return pO0.has($.trim().toLowerCase())}function cB(){if(!he)he=new wA$;return he}var DA$="AUTOMOBILE_ALLOW_DEVICE_CREATE",pO0,FA$="AutoMobile",he=null;var u_=D(()=>{pO0=new Set(["1","true"])});import{existsSync as nO0}from"fs";import{access as dO0}from"fs/promises";import{homedir as iO0,platform as oO0}from"os";import{execFile as rO0}from"child_process";import{promisify as tO0}from"util";class FY{getCurrentPlatform(){return oO0()}getHomeDir(){return iO0()}getEnvVar($){return process.env[$]}fileExistsSync($){return nO0($)}async fileExists($){return dO0($).then(()=>!0,()=>!1)}async executeCommand($,J=[]){return tO0(rO0)($,J)}}var nB=()=>{};import{join as dj,dirname as NA$}from"path";function aO0($){return $ instanceof t2||$ instanceof a2}function m_($){if(aO0($))throw $}function _A$($){return $.replace(/\\/g,"/")}function dB($){let J=_A$($);if(J.endsWith("/cmdline-tools/latest"))return J.replace(/\/cmdline-tools\/latest$/,"");if(J.endsWith("/cmdline-tools"))return J.replace(/\/cmdline-tools$/,"");return J}function iB($){let J=_A$($).toLowerCase();return J.includes("/homebrew/")||J.includes("/share/android-commandlinetools/")}function MU($=ij()){let J=s2($);if(!J)return null;let X=dj(J,"system-images");if(!$.fileExistsSync(X))return null;return{androidHome:J,systemImagesPath:X}}function ue($=ij()){let J=$.getCurrentPlatform(),X=$.getHomeDir();switch(J){case"darwin":return[dj(X,"Library/Android/sdk"),"/opt/android-sdk","/usr/local/android-sdk"];case"linux":return[dj(X,"Android/Sdk"),"/opt/android-sdk","/usr/local/android-sdk"];case"win32":return[dj(X,"AppData/Local/Android/Sdk"),"C:/Android/Sdk","C:/android-sdk"];default:return[]}}async function eO0($){if($.getCurrentPlatform()!=="darwin")return null;let J=["/opt/homebrew/share/android-commandlinetools/cmdline-tools/latest","/usr/local/share/android-commandlinetools/cmdline-tools/latest"];for(let X of J)if(await $.fileExists(X))return X;return null}function s2($=ij()){let J=$.getEnvVar("ANDROID_HOME");if(J&&$.fileExistsSync(J))return J;let X=$.getEnvVar("ANDROID_SDK_ROOT");if(X&&$.fileExistsSync(X))return X;return null}async function $B0($){let J=$.getEnvVar("ANDROID_HOME");if(J&&await $.fileExists(J))return J;let X=$.getEnvVar("ANDROID_SDK_ROOT");if(X&&await $.fileExists(X))return X;return null}async function l_($,J=ij()){try{let X=J.getCurrentPlatform()==="win32"?"where":"which";return await J.executeCommand(X,[$]),!0}catch(X){return m_(X),U.debug(`src/utils/android-cmdline-tools/detection.ts fallback failed: ${X}`,X),!1}}async function me($,J=ij()){try{let X=J.getCurrentPlatform()==="win32"?"where":"which";return(await J.executeCommand(X,[$])).stdout.trim().split(`
|
|
22
22
|
`)[0]||null}catch(X){return m_(X),U.debug(`src/utils/android-cmdline-tools/detection.ts fallback failed: ${X}`,X),null}}async function ge($,J){if(!await J.fileExists($))return[];let X=[],Q=dj($,"bin");if(!await J.fileExists(Q))return[];for(let Y of Object.keys(MA$)){let W=dj(Q,Y),G=dj(Q,`${Y}.bat`);if(await J.fileExists(W)||await J.fileExists(G))X.push(Y)}return X}async function le($=ij()){let J=await eO0($);if(!J)return null;let X=await ge(J,$);if(X.length===0)return null;return{path:J,source:"homebrew",available_tools:X}}async function pe($=ij()){let J=[];U.debug("Looking for Android SDK tools");let X=await $B0($);if(X){let Y=dj(X,"cmdline-tools","latest"),W=await ge(Y,$);if(W.length>0){let G=$.getEnvVar("ANDROID_HOME")?"android_home":"android_sdk_root";J.push({path:Y,source:G,available_tools:W})}}let Q=ue($);for(let Y of Q){U.debug(`Checking typical path for Android SDK: ${Y}`);let W=$.getEnvVar("ANDROID_HOME"),G=$.getEnvVar("ANDROID_SDK_ROOT");if(W===Y||G===Y)continue;let Z=dj(Y,"cmdline-tools","latest"),j=await ge(Z,$);if(j.length>0)J.push({path:Z,source:"typical",available_tools:j})}return J}async function JB0($=ij()){let J=[],X={};U.debug("Looking for Android SDK tools in PATH");for(let Z of Object.keys(MA$))if(await l_(Z,$)){let j=await me(Z,$);if(j)U.debug(`Tool ${Z} was in PATH`),J.push(Z),X[Z]=j}if(J.length===0)return null;let Y=Object.values(X).map((Z)=>NA$(Z)).reduce((Z,j)=>{return Z[j]=(Z[j]||0)+1,Z},{}),W=Object.entries(Y).sort(([,Z],[,j])=>j-Z)[0]?.[0];return{path:W?NA$(W):"",source:"path",available_tools:J}}async function _Q($=sO0){let J=AA$.get($);if(J!==void 0)return U.debug("Already cached Android tools locations. Returning cached result."),J;let X=[];U.debug("Starting Android command line tools detection...");try{let W=await le($);if(W)X.push(W),U.debug(`Found Homebrew Android tools at: ${W.path}`)}catch(W){m_(W),U.warn(`Error detecting Homebrew Android tools: ${W.message}`)}try{let W=await pe($);X.push(...W);for(let G of W)U.debug(`Found Android SDK tools at: ${G.path} (source: ${G.source})`)}catch(W){m_(W),U.warn(`Error detecting Android SDK tools: ${W.message}`)}try{let W=await JB0($);if(W)X.push(W),U.debug(`Found Android tools in PATH: ${W.available_tools.join(", ")}`)}catch(W){m_(W),U.warn(`Error detecting Android tools in PATH: ${W.message}`)}let Q=new Map;for(let W of X)if(!Q.has(W.path))Q.set(W.path,W);let Y=Array.from(Q.values());return U.debug(`Detection complete. Found ${Y.length} unique Android tools installations.`),AA$.set($,Y),Y}function MQ($){if($.length===0)return null;let J={android_home:1,android_sdk_root:2,typical:3,homebrew:4,path:5,manual:6},X=$.map((Q)=>{let Y=J[Q.source]||10,W=Q.available_tools.length,G=Y*100-W;return{location:Q,score:G}});return X.sort((Q,Y)=>Q.score-Y.score),X[0]?.location||null}function oB($,J){let X=J.filter((Q)=>!$.available_tools.includes(Q));return{valid:X.length===0,missing:X}}var t2,a2,ij=()=>new FY,sO0,AA$,MA$;var oj=D(()=>{d();nB();t2=class t2 extends Error{constructor($){super($);this.name="AndroidToolsDetectionTimeoutError"}};a2=class a2 extends Error{abortError;constructor($){super($.message);this.abortError=$;this.name="AndroidToolsDetectionAbortError"}};sO0=ij();AA$=new WeakMap,MA$={apkanalyzer:{name:"apkanalyzer",description:"APK analysis and inspection"},avdmanager:{name:"avdmanager",description:"Android Virtual Device management"},sdkmanager:{name:"sdkmanager",description:"SDK package management"},lint:{name:"lint",description:"Static code analysis"},screenshot2:{name:"screenshot2",description:"Device screenshot capture"},d8:{name:"d8",description:"DEX compiler"},r8:{name:"r8",description:"Code shrinking and obfuscation"},resourceshrinker:{name:"resourceshrinker",description:"Resource optimization"},retrace:{name:"retrace",description:"Stack trace de-obfuscation"},profgen:{name:"profgen",description:"ART profile generation"}}});import{AsyncLocalStorage as XB0}from"async_hooks";var RA$,EA$=async($,J)=>{return RA$.run({signal:$},J)},ce=()=>{return RA$.getStore()?.signal};var ne=D(()=>{RA$=new XB0});var rB=0.02,VJ="Operation cancelled";var QB0=($)=>{let J=tB($);return{delayForAttempt(X){return bb(X),J}}},p_=($)=>{if($.length===0)throw Error("sequenceBackoff requires at least one delay");let J=$.map(tB);return{delayForAttempt(X){return bb(X),J[Math.min(X-1,J.length-1)]}}},CJ=($)=>{let J=tB($.initialDelayMs),X=$.multiplier??2,Q=$.maxDelayMs===void 0?Number.POSITIVE_INFINITY:tB($.maxDelayMs);if(!Number.isFinite(X)||X<1)throw Error(`exponentialBackoff multiplier must be >= 1, got ${X}`);return{delayForAttempt(Y){return bb(Y),tB(Math.min(J*X**(Y-1),Q))}}},rj=($)=>{if(typeof $==="number")return QB0($);if(Array.isArray($))return p_($);if(typeof $==="function")return{delayForAttempt(J){return bb(J),tB($(J))}};return $},PA$=($,J)=>rj($).delayForAttempt(J),bb=($)=>{if(!Number.isInteger($)||$<1)throw Error(`Backoff attempt must be a positive integer, got ${$}`)},tB=($)=>{if(!Number.isFinite($))throw Error(`Backoff delay must be finite, got ${$}`);return Math.max(0,Math.floor($))};class CA${timer;constructor($=u){this.timer=$}async execute($,J){let X=J?.maxAttempts??TA$.maxAttempts,Q=J?.delays??TA$.delays,Y=J?.shouldRetry??(()=>!0),W=J?.onRetry,G=J?.signal,Z=this.timer.now(),j;for(let V=1;V<=X;V++){if(G?.aborted)return{success:!1,error:Error("Operation aborted"),attempts:V,totalTimeMs:this.timer.now()-Z};try{return{success:!0,value:await $(V),attempts:V,totalTimeMs:this.timer.now()-Z}}catch(K){if(j=K instanceof Error?K:Error(String(K)),V<X){if(!Y(j,V))return{success:!1,error:j,attempts:V,totalTimeMs:this.timer.now()-Z};let z=PA$(Q,V);if(W?.(j,V,z),z>0)if(G){if(await Promise.race([this.timer.sleep(z).then(()=>!1),new Promise((H)=>{if(G.aborted){H(!0);return}G.addEventListener("abort",()=>H(!0),{once:!0})})]))return{success:!1,error:Error("Operation aborted"),attempts:V,totalTimeMs:this.timer.now()-Z}}else await this.timer.sleep(z)}}}return{success:!1,error:j,attempts:X,totalTimeMs:this.timer.now()-Z}}async executeOrThrow($,J){let X=await this.execute($,J);if(!X.success)throw X.error??Error("Operation failed after retries");return X.value}}var TA$,RU;var c_=D(()=>{U$();TA$={maxAttempts:3,delays:1000};RU=new CA$});class EU{timer;entries=new Map;ttlMs;maxEntries;maxSizeBytes;currentSizeBytes=0;stats={hits:0,misses:0,size:0,ttlEvictions:0,sizeEvictions:0};constructor($=u,J){this.timer=$;this.ttlMs=J?.ttlMs??SA$.ttlMs,this.maxEntries=J?.maxEntries??SA$.maxEntries,this.maxSizeBytes=J?.maxSizeBytes??1/0}get($){let J=this.entries.get($);if(!J){this.stats.misses++;return}let X=this.timer.now();if(X-J.createdAt>=this.ttlMs){this.entries.delete($),this.currentSizeBytes-=J.sizeBytes??0,this.stats.ttlEvictions++,this.stats.misses++,this.updateSizeStats();return}return J.lastAccessedAt=X,this.stats.hits++,J.value}set($,J,X){let Q=this.timer.now(),Y=this.entries.get($);if(Y)this.currentSizeBytes-=Y.sizeBytes??0,this.entries.delete($);if(X!==void 0&&this.maxSizeBytes!==1/0)while(this.currentSizeBytes+X>this.maxSizeBytes&&this.entries.size>0)this.evictOldest(),this.stats.sizeEvictions++;while(this.maxEntries>0&&this.entries.size>=this.maxEntries&&this.entries.size>0)this.evictOldest(),this.stats.sizeEvictions++;if(this.maxEntries<=0)return;let W={value:J,createdAt:Q,lastAccessedAt:Q,sizeBytes:X};this.entries.set($,W),this.currentSizeBytes+=X??0,this.updateSizeStats()}has($){let J=this.entries.get($);if(!J)return!1;if(this.timer.now()-J.createdAt>=this.ttlMs)return this.entries.delete($),this.currentSizeBytes-=J.sizeBytes??0,this.stats.ttlEvictions++,this.updateSizeStats(),!1;return!0}delete($){let J=this.entries.get($);if(J)return this.currentSizeBytes-=J.sizeBytes??0,this.entries.delete($),this.updateSizeStats(),!0;return!1}clear(){this.entries.clear(),this.currentSizeBytes=0,this.updateSizeStats()}size(){return this.entries.size}getStats(){return{...this.stats}}cleanup(){let $=this.timer.now(),J=0;for(let[X,Q]of this.entries)if($-Q.createdAt>=this.ttlMs)this.entries.delete(X),this.currentSizeBytes-=Q.sizeBytes??0,this.stats.ttlEvictions++,J++;return this.updateSizeStats(),J}getCurrentSizeBytes(){return this.currentSizeBytes}keys(){return Array.from(this.entries.keys())}evictOldest(){let $,J=1/0;for(let[X,Q]of this.entries)if(Q.lastAccessedAt<J)J=Q.lastAccessedAt,$=X;if($!==void 0){let X=this.entries.get($);if(X)this.currentSizeBytes-=X.sizeBytes??0;this.entries.delete($)}}updateSizeStats(){this.stats.size=this.entries.size}}var SA$;var yb=D(()=>{U$();SA$={ttlMs:60000,maxEntries:1/0}});function fb($){if(typeof $==="string")return $;if(Buffer.isBuffer($))return $.toString();return""}function de($){let J=$.trim();if(J.length<=4000)return J;return`...${J.slice(-4000)}`}function YB0($,J=[]){return[$,...J].join(" ")}function WB0($,J){let X=$??{},Q=de($ instanceof Error?$.message:String($)),Y=fb(J.stdout)||fb(X.stdout),W=fb(J.stderr)||fb(X.stderr),G=[`Command failed: ${YB0(J.command,J.args)}`];if(J.cwd)G.push(`cwd: ${J.cwd}`);if(typeof X.code==="number")G.push(`exit code: ${X.code}`);else if(typeof X.code==="string")G.push(`error code: ${X.code}`);if(X.signal)G.push(`signal: ${X.signal}`);if(G.push(`raw error: (last 4000 chars) ${Q}`),Y.trim().length>0)G.push("stdout: (last 4000 chars)",de(Y));if(W.trim().length>0)G.push("stderr: (last 4000 chars)",de(W));return G.join(`
|
|
@@ -26,7 +26,7 @@ and limitations under the License.
|
|
|
26
26
|
`);for(let Q=0;Q<X.length;Q++){let W=X[Q].match(/UserInfo\{(\d+):([^:]+):([0-9a-fA-F]+)\}/);if(W){let G=parseInt(W[1],10),Z=W[2],j=parseInt(W[3],16),V=!1;for(let K=Q+1;K<Math.min(Q+10,X.length);K++){let z=X[K];if(z.match(/UserInfo\{/))break;if(z.match(/State:\s+(RUNNING_UNLOCKED|RUNNING_LOCKED)/)){V=!0;break}if(z.match(/State:\s+SHUTDOWN/)){V=!1;break}}if(Z==="null"){let K=$.match(/Owner name:\s+(.+)/);if(K&&G===0)Z=K[1].trim();else Z=`User ${G}`}J.push({userId:G,name:Z,flags:j,running:V})}}return J}async listUsersLegacy($){try{let J=await this.executeCommand("shell pm list users",void 0,void 0,!0,$),X=J.stdout.split(`
|
|
27
27
|
`),Q=[];for(let Y of X){let W=Y.match(/UserInfo\{(\d+):([^:]+):([0-9a-fA-F]+)\}\s*(running)?/);if(W)Q.push({userId:parseInt(W[1],10),name:W[2],flags:parseInt(W[3],16),running:W[4]==="running"})}if(Q.length>0)return U.info(`[ADB] Found ${Q.length} user(s) via pm: ${Q.map((Y)=>`${Y.userId}:${Y.name}`).join(", ")}`),Q;return U.warn(`[ADB] Failed to parse users from pm list users. Raw output: ${J.stdout.substring(0,200)}`),[{userId:0,name:"Owner",flags:19,running:!0}]}catch(J){return U.warn(`[ADB] Failed to list users via pm: ${J.message}`),[{userId:0,name:"Owner",flags:19,running:!0}]}}async getForegroundApp($){try{let X=(await this.executeCommand('shell dumpsys activity activities | grep -E "(mResumedActivity|mFocusedActivity|topResumedActivity)" | head -1',void 0,void 0,!0,$)).stdout.match(/u(\d+)\s+([^\s/]+)\//);if(X){let Q=parseInt(X[1],10),Y=X[2];return U.info(`[ADB] Foreground app: ${Y} (user ${Q})`),{packageName:Y,userId:Q}}return U.debug("[ADB] No foreground app detected"),null}catch(J){return U.debug(`[ADB] Failed to get foreground app: ${J.message}`),null}}}var rW,oe,yA$,gb=null,xA$,VB0=5000,KB0=60000,LB0=async($,J,X)=>{if(process.env.DEBUG_ADB_EXEC)console.warn(`[DEBUG_ADB_EXEC] Real execFileAsync called: ${$} ${J.join(" ")}`),console.warn("[DEBUG_ADB_EXEC] Stack trace:",Error().stack);let Q=X?{maxBuffer:X}:void 0,Y=await jB0(bA$)($,J,Q);return{stdout:typeof Y.stdout==="string"?Y.stdout:Y.stdout.toString(),stderr:typeof Y.stderr==="string"?Y.stderr:Y.stderr.toString(),toString(){return this.stdout},trim(){return this.stdout.trim()},includes(G){return this.stdout.includes(G)}}};var mb=D(()=>{d();oj();ne();c_();yb();U$();hb();nB();rW=class rW extends Error{constructor($){super($);this.name="AdbCommandTimeoutError"}};oe=class oe extends Error{constructor($){super($);this.name="AdbUnavailableError"}};yA$=u,xA$=new WeakMap});class fA${create($,J){if(J)return new n5($??null,null,null,J);return new n5($??null)}}var V$;var P0=D(()=>{mb();V$=new fA$});function RQ($,J){return{stdout:typeof $==="string"?$:$.toString(),stderr:typeof J==="string"?J:J.toString(),toString(){return this.stdout},trim(){return this.stdout.trim()},includes(X){return this.stdout.includes(X)}}}class hA${root;current;timer;constructor($=u){this.timer=$;let J=this.timer.now();this.root={name:"root",type:"serial",startMs:J,entries:[],parent:null},this.current=this.root}serial($){let J={name:$,type:"serial",startMs:this.timer.now(),entries:[],parent:this.current};return this.current=J,this}parallel($){let J={name:$,type:"parallel",startMs:this.timer.now(),entries:{},parent:this.current};return this.current=J,this}async track($,J){let X=this.timer.now();try{return await J()}finally{let Q=this.timer.now()-X,Y={name:$,durationMs:Q};if(Array.isArray(this.current.entries))this.current.entries.push(Y);else this.current.entries[$]=Y}}trackSync($,J){let X=this.timer.now();try{return J()}finally{let Q=this.timer.now()-X,Y={name:$,durationMs:Q};if(Array.isArray(this.current.entries))this.current.entries.push(Y);else this.current.entries[$]=Y}}end(){if(this.current.parent){let $=this.timer.now()-this.current.startMs,J={name:this.current.name,durationMs:$,children:this.current.entries},X=this.current.parent;if(Array.isArray(X.entries))X.entries.push(J);else X.entries[this.current.name]=J;this.current=X}return this}getTimings(){while(this.current.parent)this.end();return this.root.entries}isEnabled(){return!0}addExternalTiming($,J){let X=Array.isArray(J)?J:[J],Q={name:$,durationMs:X.reduce((Y,W)=>Y+W.durationMs,0),children:X};if(Array.isArray(this.current.entries))this.current.entries.push(Q);else this.current.entries[$]=Q}operationStarts=new Map;startOperation($){this.operationStarts.set($,this.timer.now())}endOperation($){let J=this.operationStarts.get($);if(J===void 0)return;this.operationStarts.delete($);let X=this.timer.now()-J,Q={name:$,durationMs:X};if(Array.isArray(this.current.entries))this.current.entries.push(Q);else this.current.entries[$]=Q}}class M${root={name:"noop",type:"serial",startMs:0,entries:[],parent:null};current=this.root;operationStarts=new Map;serial($){return this}parallel($){return this}async track($,J){return J()}trackSync($,J){return J()}end(){return this}getTimings(){return null}isEnabled(){return!1}addExternalTiming($,J){}startOperation($){}endOperation($){}}function tj($,J=u){return $?new hA$(J):new M$}function lb($){ae=$}function gA$(){return ae}function Z0(){return tj(ae)}function re($){if(Array.isArray($))return $.filter((J)=>J.durationMs>0).map((J)=>({...J,children:J.children?re(J.children):void 0})).filter((J)=>{if(J.children)return Array.isArray(J.children)?J.children.length>0:Object.keys(J.children).length>0;return!0});else{let J={};for(let[X,Q]of Object.entries($))if(Q.durationMs>0){let Y={...Q,children:Q.children?re(Q.children):void 0};if(Y.children){if(Array.isArray(Y.children)?Y.children.length>0:Object.keys(Y.children).length>0)J[X]=Y}else J[X]=Y}return J}}function vA$($){return JSON.stringify($).length}function te($,J=[]){let X=[];if(Array.isArray($))$.forEach((Q,Y)=>{if(X.push({path:[...J,Q.name],entry:Q,parent:$,key:Y}),Q.children)X.push(...te(Q.children,[...J,Q.name]))});else for(let[Q,Y]of Object.entries($))if(X.push({path:[...J,Q],entry:Y,parent:$,key:Q}),Y.children)X.push(...te(Y.children,[...J,Q]));return X}function OB0($,J){if(Array.isArray($))$.splice(J,1);else delete $[J]}function BB0($,J){let X=structuredClone($),Q=vA$(X);if(Q<=J)return{data:X};let Y=!1;while(Q>J){let W=te(X);if(W.length===0)break;W.sort((Z,j)=>Z.entry.durationMs-j.entry.durationMs);let G=W[0];OB0(G.parent,G.key),Y=!0,Q=vA$(X)}return{data:X,truncated:Y?!0:void 0}}function uA$($){if(!$)return null;let J=re($);if(Array.isArray(J)?J.length===0:Object.keys(J).length===0)return null;return BB0(J,HB0)}var ae=!1,HB0=51200;var _0=D(()=>{U$()});var tW=120000;import{spawn as DB0}from"child_process";class qY{process;timeoutMs;maxOutputBytes;timer;constructor($=wB0,J={}){this.process=$;this.timeoutMs=J.timeoutMs??FB0,this.maxOutputBytes=J.maxOutputBytes??qB0,this.timer=J.timer??u}async readJsonFile($,J){return this.parseJson(await this.run(["-convert","json","-o","-","--",$],void 0,J))}async readJsonBytes($,J){return this.parseJson(await this.run(["-convert","json","-o","-","--","-"],$,J))}async readXmlFile($,J){return(await this.run(["-convert","xml1","-o","-","--",$],void 0,J)).toString("utf8")}async readXmlBytes($,J){return(await this.run(["-convert","xml1","-o","-","--","-"],$,J)).toString("utf8")}async extractRawFile($,J,X){return(await this.run(["-extract",$,"raw","-o","-","--",J],void 0,X)).toString("utf8")}async isAvailable(){try{return await this.run(["-help"]),!0}catch($){return U.debug(`src/utils/ios-cmdline-tools/PlistClient.ts availability check failed: ${$}`,$),!1}}async run($,J,X={}){let Q=new AbortController,Y=()=>Q.abort();if(X.signal?.aborted)Q.abort();else X.signal?.addEventListener("abort",Y,{once:!0});let W=X.timeoutMs??this.timeoutMs,G,Z=`plutil ${$.map((K)=>JSON.stringify(K)).join(" ")}`,j=this.process({args:$,input:J,signal:Q.signal,maxOutputBytes:this.maxOutputBytes});j.catch(()=>{});let V=new Promise((K,z)=>{G=this.timer.setTimeout(()=>{z(new R(`plutil timed out after ${W}ms: ${Z}`)),Q.abort()},W)});try{let K=await Promise.race([j,V]);if(K.stdout.length>this.maxOutputBytes)throw new R(`plutil output exceeded ${this.maxOutputBytes} bytes`);return K.stdout}catch(K){if(K instanceof R)throw K;let z=K instanceof Error?K.message:String(K);throw new R(`plutil failed (${Z}): ${z}`)}finally{if(G)this.timer.clearTimeout(G);X.signal?.removeEventListener("abort",Y)}}parseJson($){try{return JSON.parse($.toString("utf8"))}catch(J){let X=J instanceof Error?J.message:String(J);throw new R(`plutil produced malformed JSON: ${X}`)}}}var FB0=15000,qB0=16777216,wB0=({args:$,input:J,signal:X,maxOutputBytes:Q})=>new Promise((Y,W)=>{if(X?.aborted){W(Error("plutil execution was cancelled"));return}let G=DB0("plutil",$,{stdio:["pipe","pipe","pipe"]}),Z=[],j=[],V=0,K=!1,z=(O)=>{if(K)return;if(K=!0,X?.removeEventListener("abort",L),O)W(O);else Y({stdout:Buffer.concat(Z),stderr:Buffer.concat(j)})},L=()=>{G.kill("SIGTERM"),z(Error("plutil execution was cancelled"))},H=(O)=>(B)=>{if(V+=B.length,V>Q){G.kill("SIGTERM"),z(Error(`plutil output exceeded ${Q} bytes`));return}O.push(B)};X?.addEventListener("abort",L,{once:!0}),G.once("error",(O)=>z(O)),G.stdout?.on("data",H(Z)),G.stderr?.on("data",H(j)),G.once("close",(O)=>{if(O===0)z();else z(Error(`plutil exited with code ${O}: ${Buffer.concat(j).toString("utf8").trim()}`))}),G.stdin?.end(J)});var aB=D(()=>{t$();U$();d()});function m1($){return NB0.test($)}function MB0($){return AB0.test($)||_B0.test($)}function mA$($){return m1($)||MB0($)}var NB0,AB0,_B0;var A8=D(()=>{NB0=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,AB0=/^[0-9A-F]{8}-[0-9A-F]{16}$/i,_B0=/^[0-9A-F]{40}$/i});import{execFile as RB0,spawn as EB0}from"child_process";import{promisify as PB0}from"util";import{promises as e2}from"fs";import{tmpdir as TB0}from"os";import{join as lA$}from"path";function IB0($,J,X){return EB0($,J,X??{})}function kB0($){let J=$.trim();if(!J)throw Error("Command cannot be empty");let X=[],Q="",Y=!1,W=null,G=()=>{if(Y)X.push(Q),Q="",Y=!1};for(let Z=0;Z<J.length;Z++){let j=J[Z];if(j==="\\"&&Z+1<J.length){Q+=J[Z+1],Y=!0,Z++;continue}if(W){if(j===W)W=null;else Q+=j;continue}if(j==="'"||j==='"'){W=j,Y=!0;continue}if(/\s/.test(j)){G();continue}Q+=j,Y=!0}return G(),X}function pA$($,J){let X=J?.trim();if(X)return X;if(!$)return;let Q=$.match(/iOS[-_](\d+(?:[-_]\d+)*)/);if(!Q)return;return Q[1].replace(/_/g,".").replace(/-/g,".")}function xB0($,J){let X=$.split(".").map((W)=>Number.parseInt(W,10)||0),Q=J.split(".").map((W)=>Number.parseInt(W,10)||0),Y=Math.max(X.length,Q.length);for(let W=0;W<Y;W++){let G=(X[W]??0)-(Q[W]??0);if(G!==0)return G}return 0}function bB0($,J){return $.filter((X)=>typeof X.version==="string"&&X.version.startsWith(J)).sort((X,Q)=>xB0(X.version,Q.version)).pop()}function cA$($){if(!$)return;if($.includes("iPad"))return"tablet";if($.includes("iPhone"))return"phone";return}function yB0($,J){if(!m1(J)||!($ instanceof Error))return!1;let X=$,Q=typeof X.stderr==="string"?X.stderr:Buffer.isBuffer(X.stderr)?X.stderr.toString():"";return typeof X.code==="number"&&X.code!==0&&Q.includes("domain=com.apple.CoreSimulator.SimError, code=405")&&Q.includes("Unable to boot device in current state: Booted")}class o0{plist;device;execAsync;timer;platform;usesInjectedExecAsync;spawnProcess;fileSystem;bootOptions;headlessSessionCache=null;static deviceListCache=null;static DEVICE_LIST_CACHE_TTL=5000;static localSimctlAvailability=null;constructor($=null,J=null,X=u,Q=process.platform,Y=IB0,W=CB0,G=fB0,Z=new qY){this.plist=Z;this.device=$,this.usesInjectedExecAsync=J!==null,this.execAsync=J||SB0,this.timer=X,this.platform=Q,this.spawnProcess=Y,this.fileSystem=W,this.bootOptions={maxAttempts:Math.max(1,G.maxAttempts),retryBackoffMs:Math.max(0,G.retryBackoffMs)}}setDevice($){this.device=$}async executeCommand($,J){let X=kB0($);return this.executeCommandArgv(X,J,$)}async executeCommandArgs($,J){return this.executeCommandArgv($,J,$.join(" "))}async startCommandArgs($,J){if($.length===0)throw Error("Command cannot be empty");await this.ensureAvailableForCommand();let X=["simctl",...$];return U.debug(`[iOS] Starting command: xcrun ${X.join(" ")}`),this.spawnProcess("xcrun",X,J)}async ensureAvailableForCommand(){try{await this.ensureLocalSimctlAvailable()}catch($){let J=$ instanceof Error?$.message:String($),X=this.platform==="darwin"?`simctl is not available. Please install Xcode command line tools to continue. ${J}`:"iOS simulator tooling is only available on macOS.";throw new R(X)}}async executeCommandArgv($,J,X){if($.length===0)throw Error("Command cannot be empty");let Q=X??$.map((V)=>JSON.stringify(V)).join(" "),W=["simctl",...$],G=`xcrun simctl ${Q}`,Z=this.timer.now();U.debug(`[iOS] Executing command: ${G}`),await this.ensureAvailableForCommand();let j=(V)=>this.execAsync("xcrun",W,void 0,V);if(J){let V,K=new AbortController,z=new Promise((H,O)=>{V=this.timer.setTimeout(()=>{K.abort(),O(Error(`Command timed out after ${J}ms: ${G}`))},J)}),L=j(K.signal);L.catch(()=>{});try{let H=await Promise.race([L,z]),O=this.timer.now()-Z;return U.debug(`[iOS] Command completed in ${O}ms: ${Q}`),H}catch(H){let O=this.timer.now()-Z;throw U.warn(`[iOS] Command failed after ${O}ms: ${Q} - ${H.message}`),H}finally{clearTimeout(V)}}try{let V=await j(),K=this.timer.now()-Z;return U.debug(`[iOS] Command completed in ${K}ms: ${Q}`),V}catch(V){let K=this.timer.now()-Z;throw U.warn(`[iOS] Command failed after ${K}ms: ${Q} - ${V.message}`),V}}async isAvailable(){return this.isLocalSimctlAvailable()}async ensureLocalSimctlAvailable(){if(this.usesInjectedExecAsync){await this.execAsync("xcrun",["simctl","--version"]);return}if(this.platform!=="darwin")throw new R("iOS simulator tooling is only available on macOS.");if(!o0.localSimctlAvailability)o0.localSimctlAvailability=this.execAsync("xcrun",["simctl","--version"]).then(()=>{return}).catch(($)=>{throw o0.localSimctlAvailability=null,U.debug(`[iOS] simctl unavailable: ${$ instanceof Error?$.message:String($)}`),$});await o0.localSimctlAvailability}async isLocalSimctlAvailable(){try{return await this.ensureLocalSimctlAvailable(),!0}catch($){return U.debug(`src/utils/ios-cmdline-tools/SimCtlClient.ts fallback failed: ${$}`,$),!1}}async listSimulators($){let J=Z0();J.startOperation("simctlListDevices");let X=await this.executeCommandArgs(["list","devices","--json"],$);J.endOperation("simctlListDevices");try{J.startOperation("jsonParse");let Q=JSON.parse(X.stdout);return J.endOperation("jsonParse"),Q}catch(Q){let Y=X.stdout.trim().slice(0,300),W=X.stderr.trim().slice(0,300);throw U.error(`Failed to parse simctl device list: ${Q}`),new R(`Failed to parse iOS device list from 'xcrun simctl list devices --json'. ${Q instanceof Error?Q.message:String(Q)}. stdout (first 300 chars): ${Y||"<empty>"}. stderr (first 300 chars): ${W||"<empty>"}.`)}}async isSimulatorRunning($){return(await this.getBootedSimulators()).some((J)=>J.deviceId===$||J.name===$)}async startSimulator($,J=tW){U.debug(`Starting iOS simulator ${$}`);let X=Z0();X.startOperation("bootstatus");try{await this.bootAndVerify($,this.bootDeadline(J))}finally{X.endOperation("bootstatus")}try{X.startOperation("openSimulatorApp"),await this.openSimulatorApp($),X.endOperation("openSimulatorApp")}catch{X.endOperation("openSimulatorApp"),U.debug("Could not open Simulator.app (non-fatal)")}return{pid:void 0,kill:()=>{return this.executeCommandArgs(["shutdown",$]).catch((Q)=>{U.debug(`[iOS] handle.kill() shutdown failed for ${$}: ${Q}`)}),!0},killed:!1,connected:!1,exitCode:0,signalCode:null}}async killSimulator($){U.debug(`Killing iOS simulator ${$.deviceId}`),await this.executeCommandArgs(["shutdown",$.deviceId])}async eraseSimulator($){U.debug(`Erasing iOS simulator ${$}`),await this.executeCommandArgs(["erase",$])}async waitForSimulatorReady($,J,X){let Q=Z0();if(X?.assumeBooted)return this.resolveReadySimulator($);Q.startOperation("bootstatus");try{await this.bootAndVerify($,this.bootDeadline(J??tW))}catch(Y){let W=Y instanceof Error?Y.message:String(Y);if(W.includes("Invalid device"))throw new R(`Simulator with UDID ${$} not found`);throw new R(`Simulator with UDID ${$} failed to become ready: ${W}`)}finally{Q.endOperation("bootstatus")}return this.resolveReadySimulator($)}async bootAndVerify($,J){let{maxAttempts:X,retryBackoffMs:Q}=this.bootOptions,Y="";for(let W=1;W<=X;W++){let G=!1;try{await this.executeCommandArgs(["bootstatus",$,"-b"],this.remainingBootTimeoutMs(J))}catch(j){if(!yB0(j,$))throw j;U.debug(`[iOS] bootstatus returned expected CoreSimulator error 405 for ${$}; verifying simulator state: ${j}`),G=!0}let Z=await this.readSimulatorState($,this.remainingBootTimeoutMs(J));if(Z==="Booted")return;if(Y=G?`bootstatus reported CoreSimulator error 405 but device state is ${Z??"unknown"}, not Booted`:`bootstatus exited 0 but device state is ${Z??"unknown"}, not Booted`,U.warn(`[iOS] Boot verification failed for ${$} on attempt ${W}/${X}: ${Y}`),W<X){try{await this.executeCommandArgs(["shutdown",$],this.remainingBootTimeoutMs(J))}catch(j){U.debug(`[iOS] shutdown before boot retry failed for ${$}: ${j}`)}await this.timer.sleep(Math.min(Q,this.remainingBootTimeoutMs(J)))}}throw new R(`Simulator ${$} did not reach the Booted state after ${X} boot attempt(s): ${Y}. The simulator is likely wedged. Try 'xcrun simctl shutdown all' (or erase the device with 'xcrun simctl erase ${$}') and start it again.`)}bootDeadline($){return this.timer.now()+$}remainingBootTimeoutMs($){let J=$-this.timer.now();if(J<=0)throw Error("Simulator boot verification timed out before the next recovery step");return J}async resolveRuntimeIdentifier($){let J=($??await this.detectIosSdkVersion()).trim();if(!J)throw new R("Could not determine an iOS version to target. Ensure Xcode is installed and 'xcrun --sdk iphonesimulator --show-sdk-version' returns a version.");let X=await this.listIosRuntimes(),Q=J.split(".").slice(0,2).join("."),Y=J.split(".")[0],W=[J,`${Q}.`,`${Y}.`];for(let Z of W){let j=bB0(X,Z);if(j)return U.debug(`[iOS] Resolved runtime ${j.identifier} for iOS ${J} (prefix "${Z}")`),j.identifier}let G=X.map((Z)=>`${Z.name} (${Z.version})`).join(", ")||"<none>";throw new R(`No iOS simulator runtime found for iOS ${J} (tried ${J}, ${Q}.x, ${Y}.x). Available runtimes: ${G}. Install one via Xcode > Settings > Components.`)}async detectIosSdkVersion(){try{return(await this.execAsync("xcrun",["--sdk","iphonesimulator","--show-sdk-version"])).stdout.trim()}catch($){throw new R(`Could not detect the iOS SDK version from Xcode ('xcrun --sdk iphonesimulator --show-sdk-version' failed: ${$ instanceof Error?$.message:String($)}). Ensure Xcode and its command line tools are installed and selected via xcode-select.`)}}async listIosRuntimes(){let $=await this.executeCommandArgs(["list","runtimes","iOS","--json"]);try{return(JSON.parse($.stdout).runtimes??[]).filter((X)=>X.isAvailable!==!1)}catch(J){throw new R(`Failed to parse iOS simulator runtimes from 'xcrun simctl list runtimes iOS --json': ${J instanceof Error?J.message:String(J)}. stdout (first 300 chars): ${$.stdout.trim().slice(0,300)||"<empty>"}.`)}}async readSimulatorState($,J){try{let X=await this.listSimulators(J);for(let Q of Object.values(X.devices)){let Y=Q.find((W)=>W.udid===$);if(Y)return Y.state}return}catch(X){U.warn(`[iOS] Could not read simulator state for ${$}: ${X instanceof Error?X.message:String(X)}`,X);return}}async resolveReadySimulator($){let J=Z0();J.startOperation("deviceLookup");let X=(await this.listSimulatorImages()).find((Q)=>Q.deviceId===$);if(J.endOperation("deviceLookup"),!X)throw new R(`Simulator with UDID ${$} not found after boot`);return{name:X.name,platform:X.platform,deviceId:X.deviceId}}async listSimulatorImages(){if(o0.deviceListCache){let $=this.timer.now()-o0.deviceListCache.timestamp;if($<o0.DEVICE_LIST_CACHE_TTL)return U.info(`Getting list of iOS simulators (cached, age: ${$}ms)`),o0.deviceListCache.devices}U.debug("Getting list of iOS simulators");try{let $=await this.listSimulators(),J=[];for(let[X,Q]of Object.entries($.devices))for(let Y of Q){U.debug(`Found iOS simulator: ${Y.name} (${Y.udid}) state=${Y.state}`);let W=pA$(X,Y.os_version);J.push({name:Y.name,platform:"ios",deviceId:Y.udid,isRunning:Y.state==="Booted",state:Y.state,isAvailable:Y.isAvailable,availabilityError:Y.availabilityError,iosVersion:W,osVersion:W,formFactor:cA$(Y.deviceTypeIdentifier),deviceType:Y.deviceTypeIdentifier,runtime:X,model:Y.model,architecture:Y.architecture})}if(J.sort((X,Q)=>(X.deviceId||"").localeCompare(Q.deviceId||"")),J.length>0)o0.deviceListCache={devices:J,timestamp:this.timer.now()};else o0.deviceListCache=null;return J}catch($){o0.deviceListCache=null;let J=$ instanceof Error?$.message:String($);throw U.warn(`Failed to get iOS devices: ${J}`),new R(`Failed to list iOS simulator devices: ${J}`)}}async getBootedSimulators($){try{return await this.getBootedSimulatorsChecked($)}catch(J){return U.debug(`Failed to get booted iOS devices: ${J}`),[]}}async getBootedSimulatorsChecked($){let J=await this.listSimulators($);U.debug(`Found simulator list: ${J}`);let X=[];for(let[Q,Y]of Object.entries(J.devices))for(let W of Y)if(W.isAvailable&&W.state==="Booted"){let G=pA$(Q,W.os_version);X.push({name:W.name,platform:"ios",deviceId:W.udid,iosVersion:G,osVersion:G,formFactor:cA$(W.deviceTypeIdentifier)})}return X.sort((Q,Y)=>Q.deviceId.localeCompare(Y.deviceId)),X}async getDeviceInfo($){try{let J=await this.listSimulators();for(let[X,Q]of Object.entries(J.devices)){let Y=Q.find((W)=>W.udid===$);if(Y)return{...Y,runtime:X}}return null}catch(J){return U.warn(`Failed to get iOS device info for ${$}: ${J}`),null}}async bootSimulator($){U.debug(`Booting iOS simulator ${$}`);let J=Z0(),X=this.bootDeadline(tW);J.startOperation("simctlBoot"),await this.bootAndVerify($,X),J.endOperation("simctlBoot"),J.startOperation("bootRegistration");let Y=(await this.getBootedSimulators(this.remainingBootTimeoutMs(X))).find((W)=>W.deviceId===$);if(J.endOperation("bootRegistration"),!Y)throw new R(`Failed to boot iOS simulator ${$}`);return Y}async getDeviceTypes(){let $=await this.executeCommandArgs(["list","devicetypes","--json"]);try{return JSON.parse($.stdout).devicetypes??[]}catch(J){return U.warn(`Failed to parse device types from simctl: ${J}`),[]}}async getRuntimes(){let $=await this.executeCommandArgs(["list","runtimes","--json"]);try{return(JSON.parse($.stdout).runtimes??[]).filter((X)=>X.isAvailable)}catch(J){return U.warn(`Failed to parse runtimes from simctl: ${J}`),[]}}async createSimulator($,J,X){U.debug(`Creating iOS simulator: ${$} (${J}, ${X})`);let Y=(await this.executeCommandArgs(["create",$,J,X])).stdout.trim();if(!Y)throw new R(`Failed to create iOS simulator ${$}`);return o0.invalidateDeviceListCache(),U.debug(`Created iOS simulator ${$} with UDID: ${Y}`),Y}static invalidateDeviceListCache(){o0.deviceListCache=null}async deleteSimulator($){U.debug(`Deleting iOS simulator ${$}`),await this.executeCommandArgs(["delete",$])}async listApps($){let J=$||this.device?.deviceId||"booted";U.debug(`Listing installed apps on iOS simulator ${J}`);try{let X=(Y)=>{let W=JSON.parse(Y);if(Array.isArray(W))return W;if(!W||typeof W!=="object")return[];return Object.entries(W).map(([G,Z])=>{return{...Z&&typeof Z==="object"?Z:{},bundleId:G}})},Q=async(Y)=>{let W=await this.executeCommandArgs(["listapps",...Y]);try{return JSON.parse(W.stdout),W.stdout}catch(G){return U.debug(`[iOS] listapps returned plist; converting with plutil: ${G}`),JSON.stringify(await this.plist.readJsonBytes(Buffer.from(W.stdout,"utf8")))}};try{return X(await Q([J,"--all"]))}catch(Y){U.warn(`Failed to list iOS apps with --all: ${Y}`)}return X(await Q([J]))}catch(X){return U.warn(`Failed to list iOS apps: ${X}`),[]}}async launchApp($,J,X){let Q=X||this.device?.deviceId||"booted";U.debug(`Launching app ${$} on iOS simulator ${Q}`);try{let W=(await this.executeCommandArgs(["launch",Q,$])).stdout.match(/:\s*(\d+)/);return{success:!0,pid:W?parseInt(W[1],10):void 0}}catch(Y){return U.warn(`Failed to launch iOS app ${$}: ${Y}`),{success:!1,error:Y.message}}}async terminateApp($,J){let X=J||this.device?.deviceId||"booted";U.debug(`Terminating app ${$} on iOS simulator ${X}`);try{await this.executeCommandArgs(["terminate",X,$])}catch(Q){throw U.warn(`Failed to terminate iOS app ${$}: ${Q}`),Q}}async installApp($,J){let X=J||this.device?.deviceId||"booted";U.debug(`Installing app ${$} on iOS simulator ${X}`),await this.executeCommandArgs(["install",X,$])}async uninstallApp($,J){let X=J||this.device?.deviceId||"booted";U.debug(`Uninstalling app ${$} from iOS simulator ${X}`),await this.executeCommandArgs(["uninstall",X,$])}async getScreenSize($){let J=$||this.device?.deviceId||"booted";U.info(`[iOS] Getting screen size for simulator ${J}`);let Q=(await this.executeCommandArgs(["io",J,"enumerate"])).stdout.split(`
|
|
28
28
|
`),Y=!1,W=0,G=0,Z=1;for(let j=0;j<Q.length;j++){let V=Q[j].trim();if(V.includes("LCD:")||V.includes("Screen Type: Integrated")){Y=!0;continue}if(Y){if(V.includes("Pixel Size:")){let K=V.match(/Pixel Size:\s*\{(\d+),\s*(\d+)\}/);if(K)W=parseInt(K[1],10),G=parseInt(K[2],10)}if(V.includes("Preferred UI Scale:")){let K=V.match(/Preferred UI Scale:\s*(\d+(?:\.\d+)?)/);if(K)Z=parseFloat(K[1])}}if(V.startsWith("Port:")&&Y)Y=!1}if(W>0&&G>0&&Z>0)return{width:Math.round(W/Z),height:Math.round(G/Z)};throw new R("Unable to determine screen size from provided data.")}async setAppearance($,J){let X=J||this.device?.deviceId||"booted";await this.executeCommandArgs(["ui",X,"appearance",$])}async pushNotification($,J,X){let Q=await e2.mkdtemp(lA$(TB0(),"automobile-apns-")),Y=lA$(Q,"payload.apns");try{await e2.writeFile(Y,X,"utf-8");let W=await this.executeCommandArgs(["push",$,J,Y]);if((W.stderr||"").trim().length>0)return{success:!1,error:W.stderr.trim()};return{success:!0}}catch(W){return{success:!1,error:W instanceof Error?W.message:String(W)}}finally{await e2.rm(Q,{recursive:!0,force:!0}).catch(()=>{})}}async openSimulatorApp($){if(await this.isHeadlessSession()){U.debug("Skipping open -a Simulator: headless session (no Aqua GUI)");return}if(await this.execAsync("open",["-a","Simulator"]),$)try{await this.execAsync("osascript",["-e",'tell application "Simulator" to activate'])}catch(J){U.debug(`[iOS] Could not activate Simulator.app for ${$}: ${J}`)}}async isHeadlessSession(){if(this.platform!=="darwin")return!0;let $=process.env.AUTOMOBILE_IOS_HEADLESS;if($!==void 0)return $==="true"||$==="1";if(this.headlessSessionCache===null)this.headlessSessionCache=await this.detectHeadlessSession();return this.headlessSessionCache}async detectHeadlessSession(){try{return((await this.execAsync("launchctl",["managername"])).stdout||"").trim()!=="Aqua"}catch($){return U.debug(`launchctl managername probe failed, assuming GUI session: ${$}`),!1}}}var CB0,SB0=async($,J,X,Q)=>{let Y=X&&Q?{maxBuffer:X,signal:Q}:X?{maxBuffer:X}:Q?{signal:Q}:void 0,W=await PB0(RB0)($,J,Y),G=typeof W.stdout==="string"?W.stdout:W.stdout.toString(),Z=typeof W.stderr==="string"?W.stderr:W.stderr.toString();return RQ(G,Z)},fB0;var z8=D(()=>{d();t$();U$();_0();aB();A8();CB0={mkdtemp:($)=>e2.mkdtemp($),writeFile:($,J,X)=>e2.writeFile($,J,X),readFile:($,J)=>e2.readFile($,J),rm:($,J)=>e2.rm($,J)};fB0={maxAttempts:2,retryBackoffMs:2000}});function hB0($){return vB0[$]}class d_{readFileFn;existsFn;avdHome;configHome;constructor($,J,X){let Q=q0("fs"),Y=q0("path");this.readFileFn=$??((V,K)=>Q.promises.readFile(V,K)),this.existsFn=J??((V)=>Q.existsSync(V));let W=process.env.HOME||process.env.USERPROFILE,G=process.env.ANDROID_USER_HOME||void 0,Z=process.env.ANDROID_AVD_HOME||void 0,j=process.env.ANDROID_EMULATOR_HOME||G||(process.env.ANDROID_SDK_HOME?Y.join(process.env.ANDROID_SDK_HOME,".android"):void 0)||(W?Y.join(W,".android"):"");this.avdHome=X??Z??Y.join(j,"avd"),this.configHome=X?Y.dirname(X):process.env.ANDROID_EMULATOR_HOME||G||(process.env.ANDROID_SDK_HOME?Y.join(process.env.ANDROID_SDK_HOME,".android"):void 0)||(Z?Y.dirname(this.avdHome):j)}async readConfig($){let Q=q0("path").join(this.avdHome,`${$}.avd`,"config.ini"),Y=await this.resolveRegistryConfigPath($);if(Y)Q=Y;else if(!this.existsFn(Q))return U.debug(`AVD config.ini not found: ${Q}`),null;try{let W=await this.readFileFn(Q,"utf-8");return gB0(W)}catch(W){return U.warn(`Failed to read AVD config for ${$}: ${W}`),null}}async resolveRegistryConfigPath($){let X=q0("path").join(this.avdHome,`${$}.ini`);if(!this.existsFn(X))return null;try{let Q=nA$(await this.readFileFn(X,"utf-8"));return uB0(Q,this.configHome).find((W)=>this.existsFn(W))??null}catch(Q){return U.warn(`Failed to read AVD registry for ${$}: ${Q}`),null}}}function gB0($){let J=nA$($);return{...mB0(J),...lB0(J),...pB0(J),...cB0(J)}}function nA$($){let J=new Map;for(let X of $.split(`
|
|
29
|
-
`)){let Q=X.trim();if(!Q||Q.startsWith("#"))continue;let Y=Q.indexOf("=");if(Y<0)continue;J.set(Q.slice(0,Y).trim(),Q.slice(Y+1).trim())}return J}function uB0($,J){let X=q0("path"),Q=[],Y=$.get("path");if(Y&&X.isAbsolute(Y))Q.push(X.join(Y,"config.ini"));let W=$.get("path.rel");if(W&&!X.isAbsolute(W)){let G=X.resolve(J),Z=X.resolve(G,W);Q.push(X.join(Z,"config.ini"))}return Q}function mB0($){return{screenWidth:se($.get("hw.lcd.width")),screenHeight:se($.get("hw.lcd.height")),screenDensity:se($.get("hw.lcd.density"))}}function se($){if(!$)return;return Number.parseInt($,10)||void 0}function lB0($){let J=$.get("hw.ramSize");if(!J)return{};let X=Number.parseInt(J,10);return Number.isFinite(X)?{ramSizeMb:X}:{}}function pB0($){return{...$.get("hw.device.name")?{deviceName:$.get("hw.device.name")}:{},...$.get("tag.id")?{tag:$.get("tag.id")}:{}}}function cB0($){let X=$.get("image.sysdir.1")?.match(/android-(\d+)/);if(!X)return{};let Q=Number.parseInt(X[1],10);return{apiLevel:Q,osVersion:hB0(Q)??String(Q)}}var PU=2048,vB0;var ee=D(()=>{d();vB0={21:"5.0",22:"5.1",23:"6.0",24:"7.0",25:"7.1",26:"8.0",27:"8.1",28:"9",29:"10",30:"11",31:"12",32:"12L",33:"13",34:"14",35:"15",36:"16"}});async function TU($,J,X=u){let Q=$,Y=J===void 0?void 0:X.now()+J;try{if(typeof Q.getAndroidApiLevel==="function"){let j=await Q.getAndroidApiLevel(J);if(j!==null&&j!==void 0)return j}let W=J;if(Y!==void 0){let j=Y-X.now();if(j<=0)return null;W=j}let G=await $.executeCommand("shell getprop ro.build.version.sdk",W,void 0,!0),Z=parseInt(G.stdout.trim(),10);return Number.isFinite(Z)?Z:null}catch(W){return U.debug(`src/utils/android-cmdline-tools/readAndroidDeviceApiLevel.ts fallback failed: ${W}`,W),null}}var i_=D(()=>{d();U$()});function dA$($,J){if(!J)return null;return{commands:[`shell input keycombination KEYCODE_SHIFT_LEFT ${$}`]}}function oA$($){return/^[A-Z]$/.test($)||Object.hasOwn(iA$,$)}function o_($,J){if(/^[a-z]$/.test($))return{commands:[`shell input keyevent KEYCODE_${$.toUpperCase()}`]};if(/^[A-Z]$/.test($))return dA$(`KEYCODE_${$}`,J);if(/^[0-9]$/.test($))return{commands:[`shell input keyevent KEYCODE_${$}`]};let X=nB0[$];if(X)return{commands:[`shell input keyevent ${X}`]};let Q=iA$[$];if(Q)return dA$(Q,J);return null}var pb=31,nB0,iA$;var $$$=D(()=>{nB0={" ":"KEYCODE_SPACE","-":"KEYCODE_MINUS","=":"KEYCODE_EQUALS","[":"KEYCODE_LEFT_BRACKET","]":"KEYCODE_RIGHT_BRACKET","\\":"KEYCODE_BACKSLASH",";":"KEYCODE_SEMICOLON","'":"KEYCODE_APOSTROPHE",",":"KEYCODE_COMMA",".":"KEYCODE_PERIOD","/":"KEYCODE_SLASH","`":"KEYCODE_GRAVE","@":"KEYCODE_AT"},iA$={"!":"KEYCODE_1","#":"KEYCODE_3",$:"KEYCODE_4","%":"KEYCODE_5","^":"KEYCODE_6","&":"KEYCODE_7","*":"KEYCODE_8","(":"KEYCODE_9",")":"KEYCODE_0",_:"KEYCODE_MINUS","+":"KEYCODE_EQUALS","{":"KEYCODE_LEFT_BRACKET","}":"KEYCODE_RIGHT_BRACKET","|":"KEYCODE_BACKSLASH",":":"KEYCODE_SEMICOLON",'"':"KEYCODE_APOSTROPHE","<":"KEYCODE_COMMA",">":"KEYCODE_PERIOD","?":"KEYCODE_SLASH","~":"KEYCODE_GRAVE"}});class r_{device;adb;timer;credentialStore;iosUnlocker;keyCombinationSupported;constructor($,J=V$,X={}){if(this.device=$,J&&typeof J.create==="function")this.adb=J.create($);else if(J)this.adb=J;else this.adb=V$.create($);this.timer=X.timer??u,this.credentialStore=X.credentialStore,this.iosUnlocker=X.iosUnlocker}async execute($){switch(this.device.platform){case"android":return this.executeAndroid($);case"ios":return this.executeIos();default:throw new R(`wakeAndUnlock: unsupported platform ${this.device.platform}`)}}async executeAndroid($){let X=await this.adb.getWakefulness()!=="Awake";if(X)U.info("[WakeAndUnlock] device asleep, sending KEYCODE_WAKEUP"),await this.adb.executeCommand("shell input keyevent KEYCODE_WAKEUP"),await this.timer.sleep(dB0);let Q=await this.adb.getDeviceLock();if(Q===null)return U.warn("[WakeAndUnlock] device woken but lock state could not be read"),{success:!1,platform:"android",wasAsleep:X,wasLocked:!1,unlocked:!1,error:"Could not read device lock state (dumpsys window policy unavailable); the device was woken but its lock status is unknown"};if(!Q.locked)return{success:!0,platform:"android",wasAsleep:X,wasLocked:!1,secure:Q.secure,unlocked:!0};return await this.adb.executeCommand("shell wm dismiss-keyguard"),Q.secure===!1?this.dismissSwipe(X):this.unlockSecure(X,$,Q.secure)}async dismissSwipe($){let J=await this.pollUnlocked();if(J)await this.rememberLock("swipe",null);return{success:J,platform:"android",wasAsleep:$,wasLocked:!0,secure:!1,unlocked:J,error:J?void 0:"Swipe keyguard did not dismiss"}}async unlockSecure($,J,X){let Q=J?null:await this.getRecordedCredential(),Y=J??Q,W=!J&&!!Q;if(!Y){if(X===!0)throw new R("Device is secure-locked (PIN/pattern/password); provide `pin` to unlock it. Unlocking once with a `pin` lets AutoMobile remember it for later in this session.");if(await this.pollUnlocked())return await this.rememberLock("swipe",null),{success:!0,platform:"android",wasAsleep:$,wasLocked:!0,secure:void 0,unlocked:!0};throw new R("Device is locked and its secure status could not be read; provide `pin` to unlock it if it is secure.")}let G=await this.buildCredentialCommands(Y);await this.timer.sleep(iB0);for(let j of G)await this.adb.executeCommand(j);if(await this.adb.executeCommand("shell input keyevent KEYCODE_ENTER"),!await this.pollUnlocked()){if(U.warn("[WakeAndUnlock] device remained locked after credential entry"),W)await this.rememberLock("pin",null);return{success:!1,platform:"android",wasAsleep:$,wasLocked:!0,secure:X,unlocked:!1,usedRecordedCredential:W,error:"Device remained locked after PIN entry (wrong credential or entry failed)"}}if(J)await this.rememberLock("pin",J);return{success:!0,platform:"android",wasAsleep:$,wasLocked:!0,secure:!0,unlocked:!0,usedRecordedCredential:W}}async buildCredentialCommands($){let J=await this.supportsKeyCombination(),X=Array.from($),Q=[];for(let Y=0;Y<X.length;Y++){let W=o_(X[Y]??"",J);if(!W)throw new R(`wakeAndUnlock: the credential character at position ${Y+1} cannot be sent as a key event on this device`);Q.push(...W.commands)}return Q}async executeIos(){if(!this.iosUnlocker)throw new R("wakeAndUnlock: iOS unlocker is not configured");let $=await this.iosUnlocker.wakeAndDismiss();return{success:$.success,platform:"ios",wasAsleep:!1,wasLocked:!1,unlocked:$.success,error:$.error}}async pollUnlocked(){let $=0;while($<oB0){let X=await this.adb.getDeviceLock();if(X&&!X.locked)return!0;await this.timer.sleep(rA$),$+=rA$}let J=await this.adb.getDeviceLock();return!!J&&!J.locked}async getRecordedCredential(){if(!this.credentialStore)return null;try{return await this.credentialStore.getRecordedCredential(this.device.deviceId)}catch($){return U.warn(`[WakeAndUnlock] failed to read recorded credential for ${this.device.deviceId}: ${$}`),null}}async rememberLock($,J){if(!this.credentialStore)return;try{await this.credentialStore.rememberLock(this.device.deviceId,$,J)}catch(X){U.warn(`[WakeAndUnlock] failed to remember lock for ${this.device.deviceId}: ${X}`)}}async supportsKeyCombination(){if(this.keyCombinationSupported!==void 0)return this.keyCombinationSupported;let $=await TU(this.adb);return this.keyCombinationSupported=$!==null&&$>=pb,this.keyCombinationSupported}}var dB0=500,iB0=900,rA$=250,oB0=2500;var J$$=D(()=>{t$();d();U$();P0();i_();$$$()});function d5($){return typeof $>"u"||$===void 0}function C1($){return typeof $==="string"}function wY($){return typeof $==="number"}function aj($){return typeof $==="boolean"}function CU($){return $===null}function sB($){return $ instanceof Date}function SU($){return typeof $==="bigint"}function cb($){return typeof Buffer<"u"&&Buffer.isBuffer($)}function a4($){return typeof $==="function"}function L6($){return typeof $==="object"&&$!==null}function eB($){if(!L6($)||JD0($)!=="[object Object]")return!1;if(Object.getPrototypeOf($)===null)return!0;let J=$;while(Object.getPrototypeOf(J)!==null)J=Object.getPrototypeOf(J);return Object.getPrototypeOf($)===J}function tA$($){return $[$.length-1]}function P($){return Object.freeze($)}function t_($){if(KJ($))return $;else return[$]}function KJ($){return Array.isArray($)}function UJ($){return $}function nb($,J){if(KJ($)&&KJ(J))return rB0($,J);else if(L6($)&&L6(J))return tB0($,J);return $===J}function aA$($){return $ instanceof Error?$.message:String($)}function rB0($,J){if($.length!==J.length)return!1;for(let X=0;X<$.length;++X)if(!nb($[X],J[X]))return!1;return!0}function tB0($,J){if(cb($)&&cb(J))return aB0($,J);else if(sB($)&&sB(J))return sB0($,J);return eB0($,J)}function aB0($,J){return Buffer.compare($,J)===0}function sB0($,J){return $.getTime()===J.getTime()}function eB0($,J){let X=Object.keys($),Q=Object.keys(J);if(X.length!==Q.length)return!1;for(let Y of X)if(!nb($[Y],J[Y]))return!1;return!0}function JD0($){if($==null)return $===void 0?"[object Undefined]":"[object Null]";return $D0.call($)}var $D0;var G$=D(()=>{$D0=Object.prototype.toString});var s4;var $L=D(()=>{G$();s4=P({is($){return $.kind==="AlterTableNode"},create($){return P({kind:"AlterTableNode",table:$})},cloneWithTableProps($,J){return P({...$,...J})},cloneWithColumnAlteration($,J){return P({...$,columnAlterations:$.columnAlterations?[...$.columnAlterations,J]:[J]})}})});var U1;var k6=D(()=>{G$();U1=P({is($){return $.kind==="IdentifierNode"},create($){return P({kind:"IdentifierNode",name:$})}})});var NY;var db=D(()=>{G$();k6();NY=P({is($){return $.kind==="CreateIndexNode"},create($){return P({kind:"CreateIndexNode",name:U1.create($)})},cloneWith($,J){return P({...$,...J})},cloneWithColumns($,J){return P({...$,columns:[...$.columns||[],...J]})}})});var ib;var ob=D(()=>{G$();k6();ib=P({is($){return $.kind==="CreateSchemaNode"},create($,J){return P({kind:"CreateSchemaNode",schema:U1.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var sA$,zJ;var $D=D(()=>{G$();sA$=["preserve rows","delete rows","drop"],zJ=P({is($){return $.kind==="CreateTableNode"},create($){return P({kind:"CreateTableNode",table:$,columns:P([])})},cloneWithColumn($,J){return P({...$,columns:P([...$.columns,J])})},cloneWithConstraint($,J){return P({...$,constraints:$.constraints?P([...$.constraints,J]):P([J])})},cloneWithIndex($,J){return P({...$,indexes:$.indexes?P([...$.indexes,J]):P([J])})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):P([J])})},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):P([J])})},cloneWith($,J){return P({...$,...J})}})});var K5;var sj=D(()=>{G$();k6();K5=P({is($){return $.kind==="SchemableIdentifierNode"},create($){return P({kind:"SchemableIdentifierNode",identifier:U1.create($)})},createWithSchema($,J){return P({kind:"SchemableIdentifierNode",schema:U1.create($),identifier:U1.create(J)})}})});var IU;var a_=D(()=>{G$();sj();IU=P({is($){return $.kind==="DropIndexNode"},create($,J){return P({kind:"DropIndexNode",name:K5.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var s_;var rb=D(()=>{G$();k6();s_=P({is($){return $.kind==="DropSchemaNode"},create($,J){return P({kind:"DropSchemaNode",schema:U1.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var JD;var tb=D(()=>{G$();JD=P({is($){return $.kind==="DropTableNode"},create($,J){return P({kind:"DropTableNode",table:$,...J})},cloneWith($,J){return P({...$,...J})}})});var LJ;var AY=D(()=>{G$();LJ=P({is($){return $.kind==="AliasNode"},create($,J){return P({kind:"AliasNode",node:$,alias:J})}})});var S7;var XD=D(()=>{G$();sj();S7=P({is($){return $.kind==="TableNode"},create($){return P({kind:"TableNode",table:K5.create($)})},createWithSchema($,J){return P({kind:"TableNode",table:K5.createWithSchema($,J)})}})});function x6($){return L6($)&&a4($.toOperationNode)}var i5=D(()=>{G$()});function ab($){return L6($)&&"expressionType"in $&&x6($)}function eA$($){return L6($)&&"expression"in $&&C1($.alias)&&x6($)}var sb=D(()=>{i5();G$()});var aW;var X$$=D(()=>{G$();aW=P({is($){return $.kind==="SelectModifierNode"},create($,J){return P({kind:"SelectModifierNode",modifier:$,of:J})},createWithExpression($){return P({kind:"SelectModifierNode",rawModifier:$})}})});var I7;var kU=D(()=>{G$();I7=P({is($){return $.kind==="AndNode"},create($,J){return P({kind:"AndNode",left:$,right:J})}})});var _Y;var JL=D(()=>{G$();_Y=P({is($){return $.kind==="OrNode"},create($,J){return P({kind:"OrNode",left:$,right:J})}})});var eb;var Q$$=D(()=>{G$();kU();JL();eb=P({is($){return $.kind==="OnNode"},create($){return P({kind:"OnNode",on:$})},cloneWithOperation($,J,X){return P({...$,on:J==="And"?I7.create($.on,X):_Y.create($.on,X)})}})});var MY;var QD=D(()=>{G$();Q$$();MY=P({is($){return $.kind==="JoinNode"},create($,J){return P({kind:"JoinNode",joinType:$,table:J,on:void 0})},createWithOn($,J,X){return P({kind:"JoinNode",joinType:$,table:J,on:eb.create(X)})},cloneWithOn($,J){return P({...$,on:$.on?eb.cloneWithOperation($.on,"And",J):eb.create(J)})}})});var sW;var e_=D(()=>{G$();sW=P({is($){return $.kind==="BinaryOperationNode"},create($,J,X){return P({kind:"BinaryOperationNode",leftOperand:$,operator:J,rightOperand:X})}})});function G_$($){return C1($)&&Q_$[$]}function Z_$($){return C1($)&&X_$[$]}function j_$($){return C1($)&&W_$[$]}var $_$,_b1,J_$,Mb1,X_$,XD0,Q_$,QD0,Y_$,Rb1,W_$,YD0,Eb1,HJ;var ej=D(()=>{G$();$_$=P({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),_b1=Object.keys($_$),J_$=P({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),Mb1=Object.keys(J_$),X_$=P({"->":!0,"->>":!0}),XD0=Object.keys(X_$),Q_$=P({...$_$,...J_$,"||":!0}),QD0=Object.keys(Q_$),Y_$=P({exists:!0,"not exists":!0}),Rb1=Object.keys(Y_$),W_$=P({...Y_$,"-":!0,not:!0}),YD0=Object.keys(W_$),Eb1=[...QD0,...XD0,...YD0,"between","between symmetric"],HJ=P({is($){return $.kind==="OperatorNode"},create($){return P({kind:"OperatorNode",operator:$})}})});var T4;var U5=D(()=>{G$();k6();T4=P({is($){return $.kind==="ColumnNode"},create($){return P({kind:"ColumnNode",column:U1.create($)})}})});var YD;var $M=D(()=>{G$();YD=P({is($){return $.kind==="SelectAllNode"},create(){return P({kind:"SelectAllNode"})}})});var WD;var $y=D(()=>{$M();G$();WD=P({is($){return $.kind==="ReferenceNode"},create($,J){return P({kind:"ReferenceNode",table:J,column:$})},createSelectAll($){return P({kind:"ReferenceNode",table:$,column:YD.create()})}})});class Y$${#$;get dynamicReference(){return this.#$}get refType(){return}constructor($){this.#$=$}toOperationNode(){return W$$(this.#$)}}function Jy($){return L6($)&&x6($)&&C1($.dynamicReference)}var JM=D(()=>{i5();OJ();G$()});var RY;var Xy=D(()=>{G$();RY=P({is($){return $.kind==="OrderByItemNode"},create($,J){return P({kind:"OrderByItemNode",orderBy:$,direction:J})},cloneWith($,J){return P({...$,...J})}})});var v4;var PX=D(()=>{G$();v4=P({is($){return $.kind==="RawNode"},create($,J){return P({kind:"RawNode",sqlFragments:P($),parameters:P(J)})},createWithSql($){return v4.create([$],[])},createWithChild($){return v4.create(["",""],[$])},createWithChildren($){return v4.create(Array($.length+1).fill(""),$)}})});var V_$;var G$$=D(()=>{G$();k6();V_$=P({is($){return $.kind==="CollateNode"},create($){return P({kind:"CollateNode",collation:U1.create($)})}})});class xU{#$;constructor($){this.#$=P($)}desc(){return new xU({node:RY.cloneWith(this.#$.node,{direction:v4.createWithSql("desc")})})}asc(){return new xU({node:RY.cloneWith(this.#$.node,{direction:v4.createWithSql("asc")})})}nullsLast(){return new xU({node:RY.cloneWith(this.#$.node,{nulls:"last"})})}nullsFirst(){return new xU({node:RY.cloneWith(this.#$.node,{nulls:"first"})})}collate($){return new xU({node:RY.cloneWith(this.#$.node,{collation:V_$.create($)})})}toOperationNode(){return this.#$.node}}var Z$$=D(()=>{G$$();Xy();PX();G$()});function GD($){if(K_$.has($))return;K_$.add($),console.log($)}var K_$;var j$$=D(()=>{K_$=new Set});function K$$($){return $==="asc"||$==="desc"}function TX($){if($.length===2)return[V$$($[0],$[1])];if($.length===1){let[J]=$;if(Array.isArray(J))return GD("orderBy(array) is deprecated, use multiple orderBy calls instead."),J.map((X)=>V$$(X));return[V$$(J)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${$.length}`)}function V$$($,J){let X=WD0($);if(RY.is(X)){if(J)throw Error("Cannot specify direction twice!");return X}return U_$(X,J)}function WD0($){if($V($))return BJ($);if(Jy($))return $.toOperationNode();let[J,X]=$.split(" ");if(X)return GD("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),U_$(k7(J),X);return k7($)}function U_$($,J){if(typeof J==="string"){if(!K$$(J))throw Error(`Invalid order by direction: ${J}`);return RY.create($,v4.createWithSql(J))}if(ab(J))return GD("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),RY.create($,J.toOperationNode());let X=RY.create($);if(!J)return X;return J(new xU({node:X})).toOperationNode()}var XL=D(()=>{JM();sb();Xy();PX();Z$$();j$$();EQ();OJ()});var ZD;var Qy=D(()=>{G$();ZD=P({is($){return $.kind==="JSONReferenceNode"},create($,J){return P({kind:"JSONReferenceNode",reference:$,traversal:J})},cloneWithTraversal($,J){return P({...$,traversal:J})}})});var Yy;var Wy=D(()=>{G$();Yy=P({is($){return $.kind==="JSONOperatorChainNode"},create($){return P({kind:"JSONOperatorChainNode",operator:$,values:P([])})},cloneWithValue($,J){return P({...$,values:P([...$.values,J])})}})});var bU;var XM=D(()=>{G$();bU=P({is($){return $.kind==="JSONPathNode"},create($){return P({kind:"JSONPathNode",inOperator:$,pathLegs:P([])})},cloneWithLeg($,J){return P({...$,pathLegs:P([...$.pathLegs,J])})}})});function W$$($){if(C1($))return k7($);return $.toOperationNode()}function JV($){if(KJ($))return $.map((J)=>P9(J));else return[P9($)]}function P9($){if($V($))return BJ($);return W$$($)}function z_$($,J){if(Z_$(J))return ZD.create(k7($),Yy.create(HJ.create(J)));if(J==="->$"||J==="->>$")return ZD.create(k7($),bU.create(HJ.create(J.slice(0,-1))));throw Error(`Invalid JSON operator: ${J}`)}function k7($){if(!$.includes("."))return WD.create(T4.create($));let X=$.split(".").map(z$$);if(X.length===3)return GD0(X);if(X.length===2)return ZD0(X);throw Error(`invalid column reference ${$}`)}function L_$($){if($.includes(" as ")){let[X,Q]=$.split(" as ").map(z$$);return LJ.create(k7(X),U1.create(Q))}else return k7($)}function U$$($){return T4.create($)}function jD($){if($.includes(" ")){let[X,Q]=$.split(" ").map(z$$);if(!K$$(Q))throw Error(`invalid order direction "${Q}" next to "${X}"`);return TX([X,Q])[0]}else return U$$($)}function GD0($){let[J,X,Q]=$;return WD.create(T4.create(Q),S7.createWithSchema(J,X))}function ZD0($){let[J,X]=$;return WD.create(T4.create(X),S7.create(J))}function z$$($){return $.trim()}var OJ=D(()=>{AY();U5();$y();XD();G$();EQ();k6();XL();ej();Qy();Wy();XM()});var VD;var QM=D(()=>{G$();VD=P({is($){return $.kind==="PrimitiveValueListNode"},create($){return P({kind:"PrimitiveValueListNode",values:P([...$])})}})});var eW;var QL=D(()=>{G$();eW=P({is($){return $.kind==="ValueListNode"},create($){return P({kind:"ValueListNode",values:P($)})}})});var n6;var CX=D(()=>{G$();n6=P({is($){return $.kind==="ValueNode"},create($){return P({kind:"ValueNode",value:$})},createImmediate($){return P({kind:"ValueNode",value:$,immediate:!0})}})});function H_$($){if(KJ($))return jD0($);return b6($)}function b6($){if($V($))return BJ($);return n6.create($)}function Gy($){return wY($)||aj($)||CU($)}function YM($){if(!Gy($))throw Error(`unsafe immediate value ${JSON.stringify($)}`);return n6.createImmediate($)}function jD0($){if($.some($V))return eW.create($.map((J)=>b6(J)));return VD.create($)}var $G=D(()=>{QM();QL();CX();G$();EQ()});var SX;var KD=D(()=>{G$();SX=P({is($){return $.kind==="ParensNode"},create($){return P({kind:"ParensNode",node:$})}})});function d6($){if($.length===3)return Zy($[0],$[1],$[2]);else if($.length===1)return b6($[0]);throw Error(`invalid arguments: ${JSON.stringify($)}`)}function Zy($,J,X){if(VD0(J)&&B_$(X))return sW.create(P9($),L$$(J),n6.createImmediate(X));return sW.create(P9($),L$$(J),H_$(X))}function O9($,J,X){return sW.create(P9($),L$$(J),P9(X))}function H$$($,J){return UD(Object.entries($).filter(([,X])=>!d5(X)).map(([X,Q])=>Zy(X,B_$(Q)?"is":"=",Q)),J)}function UD($,J,X=!0){let Q=J==="and"?I7.create:_Y.create;if($.length===0)return sW.create(n6.createImmediate(1),HJ.create("="),n6.createImmediate(J==="and"?1:0));let Y=O_$($[0]);for(let W=1;W<$.length;++W)Y=Q(Y,O_$($[W]));if($.length>1&&X)return SX.create(Y);return Y}function VD0($){return $==="is"||$==="is not"}function B_$($){return CU($)||aj($)}function L$$($){if(G_$($))return HJ.create($);if(x6($))return $.toOperationNode();throw Error(`invalid operator ${JSON.stringify($)}`)}function O_$($){return x6($)?$.toOperationNode():$}var IX=D(()=>{e_();G$();i5();ej();OJ();$G();CX();kU();KD();JL()});var XV;var WM=D(()=>{G$();XV=P({is($){return $.kind==="OrderByNode"},create($){return P({kind:"OrderByNode",items:P([...$])})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var O$$;var B$$=D(()=>{G$();O$$=P({is($){return $.kind==="PartitionByNode"},create($){return P({kind:"PartitionByNode",items:P($)})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var GM;var jy=D(()=>{G$();WM();B$$();GM=P({is($){return $.kind==="OverNode"},create(){return P({kind:"OverNode"})},cloneWithOrderByItems($,J){return P({...$,orderBy:$.orderBy?XV.cloneWithItems($.orderBy,J):XV.create(J)})},cloneWithPartitionByItems($,J){return P({...$,partitionBy:$.partitionBy?O$$.cloneWithItems($.partitionBy,J):O$$.create(J)})}})});var YL;var ZM=D(()=>{G$();YL=P({is($){return $.kind==="FromNode"},create($){return P({kind:"FromNode",froms:P($)})},cloneWithFroms($,J){return P({...$,froms:P([...$.froms,...J])})}})});var D$$;var F$$=D(()=>{G$();D$$=P({is($){return $.kind==="GroupByNode"},create($){return P({kind:"GroupByNode",items:P($)})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var q$$;var w$$=D(()=>{G$();kU();JL();q$$=P({is($){return $.kind==="HavingNode"},create($){return P({kind:"HavingNode",having:$})},cloneWithOperation($,J,X){return P({...$,having:J==="And"?I7.create($.having,X):_Y.create($.having,X)})}})});var k8;var WL=D(()=>{G$();k8=P({is($){return $.kind==="InsertQueryNode"},create($,J,X){return P({kind:"InsertQueryNode",into:$,...J&&{with:J},replace:X})},createWithoutInto(){return P({kind:"InsertQueryNode"})},cloneWith($,J){return P({...$,...J})}})});var Vy;var Ky=D(()=>{G$();Vy=P({is($){return $.kind==="ListNode"},create($){return P({kind:"ListNode",items:P($)})}})});var JG;var zD=D(()=>{G$();ZM();Ky();JG=P({is($){return $.kind==="UpdateQueryNode"},create($,J){return P({kind:"UpdateQueryNode",table:$.length===1?$[0]:Vy.create($),...J&&{with:J}})},createWithoutTable(){return P({kind:"UpdateQueryNode"})},cloneWithFromItems($,J){return P({...$,from:$.from?YL.cloneWithFroms($.from,J):YL.create(J)})},cloneWithUpdates($,J){return P({...$,updates:$.updates?P([...$.updates,...J]):J})},cloneWithLimit($,J){return P({...$,limit:J})}})});var jM;var Uy=D(()=>{G$();jM=P({is($){return $.kind==="UsingNode"},create($){return P({kind:"UsingNode",tables:P($)})},cloneWithTables($,J){return P({...$,tables:P([...$.tables,...J])})}})});var yU;var VM=D(()=>{G$();ZM();Uy();PQ();yU=P({is($){return $.kind==="DeleteQueryNode"},create($,J){return P({kind:"DeleteQueryNode",from:YL.create($),...J&&{with:J}})},cloneWithOrderByItems:($,J)=>F0.cloneWithOrderByItems($,J),cloneWithoutOrderBy:($)=>F0.cloneWithoutOrderBy($),cloneWithLimit($,J){return P({...$,limit:J})},cloneWithoutLimit($){return P({...$,limit:void 0})},cloneWithUsing($,J){return P({...$,using:$.using!==void 0?jM.cloneWithTables($.using,J):jM.create(J)})}})});var SJ;var KM=D(()=>{G$();kU();JL();SJ=P({is($){return $.kind==="WhereNode"},create($){return P({kind:"WhereNode",where:$})},cloneWithOperation($,J,X){return P({...$,where:J==="And"?I7.create($.where,X):_Y.create($.where,X)})}})});var N$$;var A$$=D(()=>{G$();N$$=P({is($){return $.kind==="ReturningNode"},create($){return P({kind:"ReturningNode",selections:P($)})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})}})});var D_$;var _$$=D(()=>{G$();D_$=P({is($){return $.kind==="ExplainNode"},create($,J){return P({kind:"ExplainNode",format:$,options:J})}})});var x7;var GL=D(()=>{G$();x7=P({is($){return $.kind==="WhenNode"},create($){return P({kind:"WhenNode",condition:$})},cloneWithResult($,J){return P({...$,result:J})}})});var kX;var UM=D(()=>{G$();GL();kX=P({is($){return $.kind==="MergeQueryNode"},create($,J){return P({kind:"MergeQueryNode",into:$,...J&&{with:J}})},cloneWithUsing($,J){return P({...$,using:J})},cloneWithWhen($,J){return P({...$,whens:$.whens?P([...$.whens,J]):P([J])})},cloneWithThen($,J){return P({...$,whens:$.whens?P([...$.whens.slice(0,-1),x7.cloneWithResult($.whens[$.whens.length-1],J)]):void 0})}})});var M$$;var R$$=D(()=>{G$();M$$=P({is($){return $.kind==="OutputNode"},create($){return P({kind:"OutputNode",selections:P($)})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})}})});var F0;var PQ=D(()=>{WL();ZL();zD();VM();KM();G$();A$$();_$$();UM();R$$();WM();F0=P({is($){return H6.is($)||k8.is($)||JG.is($)||yU.is($)||kX.is($)},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):P([J])})},cloneWithWhere($,J){return P({...$,where:$.where?SJ.cloneWithOperation($.where,"And",J):SJ.create(J)})},cloneWithJoin($,J){return P({...$,joins:$.joins?P([...$.joins,J]):P([J])})},cloneWithReturning($,J){return P({...$,returning:$.returning?N$$.cloneWithSelections($.returning,J):N$$.create(J)})},cloneWithoutReturning($){return P({...$,returning:void 0})},cloneWithoutWhere($){return P({...$,where:void 0})},cloneWithExplain($,J,X){return P({...$,explain:D_$.create(J,X?.toOperationNode())})},cloneWithTop($,J){return P({...$,top:J})},cloneWithOutput($,J){return P({...$,output:$.output?M$$.cloneWithSelections($.output,J):M$$.create(J)})},cloneWithOrderByItems($,J){return P({...$,orderBy:$.orderBy?XV.cloneWithItems($.orderBy,J):XV.create(J)})},cloneWithoutOrderBy($){return P({...$,orderBy:void 0})}})});var H6;var ZL=D(()=>{G$();ZM();F$$();w$$();PQ();H6=P({is($){return $.kind==="SelectQueryNode"},create($){return P({kind:"SelectQueryNode",...$&&{with:$}})},createFrom($,J){return P({kind:"SelectQueryNode",from:YL.create($),...J&&{with:J}})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})},cloneWithDistinctOn($,J){return P({...$,distinctOn:$.distinctOn?P([...$.distinctOn,...J]):P(J)})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):P([J])})},cloneWithOrderByItems:($,J)=>F0.cloneWithOrderByItems($,J),cloneWithGroupByItems($,J){return P({...$,groupBy:$.groupBy?D$$.cloneWithItems($.groupBy,J):D$$.create(J)})},cloneWithLimit($,J){return P({...$,limit:J})},cloneWithOffset($,J){return P({...$,offset:J})},cloneWithFetch($,J){return P({...$,fetch:J})},cloneWithHaving($,J){return P({...$,having:$.having?q$$.cloneWithOperation($.having,"And",J):q$$.create(J)})},cloneWithSetOperations($,J){return P({...$,setOperations:$.setOperations?P([...$.setOperations,...J]):P([...J])})},cloneWithoutSelections($){return P({...$,selections:[]})},cloneWithoutLimit($){return P({...$,limit:void 0})},cloneWithoutOffset($){return P({...$,offset:void 0})},cloneWithoutOrderBy:($)=>F0.cloneWithoutOrderBy($),cloneWithoutGroupBy($){return P({...$,groupBy:void 0})}})});class LD{#$;constructor($){this.#$=P($)}on(...$){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,d6($))})}onRef($,J,X){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,O9($,J,X))})}onTrue(){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,v4.createWithSql("true"))})}$call($){return $(this)}toOperationNode(){return this.#$.joinNode}}var E$$=D(()=>{QD();PX();IX();G$()});var F_$;var P$$=D(()=>{G$();F_$=P({is($){return $.kind==="PartitionByItemNode"},create($){return P({kind:"PartitionByItemNode",partitionBy:$})}})});function q_$($){return JV($).map(F_$.create)}var w_$=D(()=>{P$$();OJ()});class HD{#$;constructor($){this.#$=P($)}orderBy(...$){return new HD({overNode:GM.cloneWithOrderByItems(this.#$.overNode,TX($))})}clearOrderBy(){return new HD({overNode:F0.cloneWithoutOrderBy(this.#$.overNode)})}partitionBy($){return new HD({overNode:GM.cloneWithPartitionByItems(this.#$.overNode,q_$($))})}$call($){return $(this)}toOperationNode(){return this.#$.overNode}}var N_$=D(()=>{jy();PQ();XL();w_$();G$()});var OD;var T$$=D(()=>{G$();$y();$M();OD=P({is($){return $.kind==="SelectionNode"},create($){return P({kind:"SelectionNode",selection:$})},createSelectAll(){return P({kind:"SelectionNode",selection:YD.create()})},createSelectAllFromTable($){return P({kind:"SelectionNode",selection:WD.createSelectAll($)})}})});function u9($){if(a4($))return u9($(EY()));else if(KJ($))return $.map((J)=>A_$(J));else return[A_$($)]}function A_$($){if(C1($))return OD.create(L_$($));else if(Jy($))return OD.create($.toOperationNode());else return OD.create(zy($))}function DJ($){if(!$)return[OD.createSelectAll()];else if(Array.isArray($))return $.map(__$);else return[__$($)]}function __$($){if(C1($))return OD.createSelectAllFromTable(e4($));throw Error(`invalid value selectAll expression: ${JSON.stringify($)}`)}var fU=D(()=>{G$();T$$();OJ();JM();EQ();IJ();jL()});var M_$;var C$$=D(()=>{G$();M_$=P({is($){return $.kind==="ValuesNode"},create($){return P({kind:"ValuesNode",values:P($)})}})});var R_$;var S$$=D(()=>{G$();R_$=P({is($){return $.kind==="DefaultInsertValueNode"},create(){return P({kind:"DefaultInsertValueNode"})}})});function Ly($){let J=a4($)?$(EY()):$,X=KJ(J)?J:P([J]);return KD0(X)}function KD0($){let J=UD0($);return[P([...J.keys()].map(T4.create)),M_$.create($.map((X)=>zD0(X,J)))]}function UD0($){let J=new Map;for(let X of $){let Q=Object.keys(X);for(let Y of Q)if(!J.has(Y)&&X[Y]!==void 0)J.set(Y,J.size)}return J}function zD0($,J){let X=Object.keys($),Q=Array.from({length:J.size}),Y=!1,W=X.length;for(let Z of X){let j=J.get(Z);if(d5(j)){W--;continue}let V=$[Z];if(d5(V)||$V(V))Y=!0;Q[j]=V}if(W<J.size||Y){let Z=R_$.create();return eW.create(Q.map((j)=>d5(j)?Z:b6(j)))}return VD.create(Q)}var I$$=D(()=>{U5();QM();QL();G$();$G();C$$();EQ();S$$();jL()});var k$$;var x$$=D(()=>{G$();k$$=P({is($){return $.kind==="ColumnUpdateNode"},create($,J){return P({kind:"ColumnUpdateNode",column:$,value:J})}})});function E_$(...$){if($.length===2)return[k$$.create(P9($[0]),b6($[1]))];return zM($[0])}function zM($){let J=a4($)?$(EY()):$;return Object.entries(J).filter(([X,Q])=>Q!==void 0).map(([X,Q])=>{return k$$.create(T4.create(X),b6(Q))})}var Hy=D(()=>{U5();x$$();jL();G$();$G();OJ()});var P_$;var b$$=D(()=>{G$();P_$=P({is($){return $.kind==="OnDuplicateKeyNode"},create($){return P({kind:"OnDuplicateKeyNode",updates:$})}})});class y$${insertId;numInsertedOrUpdatedRows;constructor($,J){this.insertId=$,this.numInsertedOrUpdatedRows=J}}function XG($){return Object.prototype.hasOwnProperty.call($,"prototype")}var PY;var VL=D(()=>{PY=class PY extends Error{node;constructor($){super("no result");this.node=$}}});var o5;var Oy=D(()=>{G$();KM();o5=P({is($){return $.kind==="OnConflictNode"},create(){return P({kind:"OnConflictNode"})},cloneWith($,J){return P({...$,...J})},cloneWithIndexWhere($,J){return P({...$,indexWhere:$.indexWhere?SJ.cloneWithOperation($.indexWhere,"And",J):SJ.create(J)})},cloneWithIndexOrWhere($,J){return P({...$,indexWhere:$.indexWhere?SJ.cloneWithOperation($.indexWhere,"Or",J):SJ.create(J)})},cloneWithUpdateWhere($,J){return P({...$,updateWhere:$.updateWhere?SJ.cloneWithOperation($.updateWhere,"And",J):SJ.create(J)})},cloneWithUpdateOrWhere($,J){return P({...$,updateWhere:$.updateWhere?SJ.cloneWithOperation($.updateWhere,"Or",J):SJ.create(J)})},cloneWithoutIndexWhere($){return P({...$,indexWhere:void 0})},cloneWithoutUpdateWhere($){return P({...$,updateWhere:void 0})}})});class QG{#$;constructor($){this.#$=P($)}column($){let J=T4.create($);return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?P([...this.#$.onConflictNode.columns,J]):P([J])})})}columns($){let J=$.map(T4.create);return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?P([...this.#$.onConflictNode.columns,...J]):P(J)})})}constraint($){return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{constraint:U1.create($)})})}expression($){return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{indexExpression:$.toOperationNode()})})}where(...$){return new QG({...this.#$,onConflictNode:o5.cloneWithIndexWhere(this.#$.onConflictNode,d6($))})}whereRef($,J,X){return new QG({...this.#$,onConflictNode:o5.cloneWithIndexWhere(this.#$.onConflictNode,O9($,J,X))})}clearWhere(){return new QG({...this.#$,onConflictNode:o5.cloneWithoutIndexWhere(this.#$.onConflictNode)})}doNothing(){return new T_$({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{doNothing:!0})})}doUpdateSet($){return new LM({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{updates:zM($)})})}$call($){return $(this)}}class T_${#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.onConflictNode}}class LM{#$;constructor($){this.#$=P($)}where(...$){return new LM({...this.#$,onConflictNode:o5.cloneWithUpdateWhere(this.#$.onConflictNode,d6($))})}whereRef($,J,X){return new LM({...this.#$,onConflictNode:o5.cloneWithUpdateWhere(this.#$.onConflictNode,O9($,J,X))})}clearWhere(){return new LM({...this.#$,onConflictNode:o5.cloneWithoutUpdateWhere(this.#$.onConflictNode)})}$call($){return $(this)}toOperationNode(){return this.#$.onConflictNode}}var f$$=D(()=>{U5();k6();Oy();IX();Hy();G$()});var C_$;var v$$=D(()=>{G$();C_$=P({is($){return $.kind==="TopNode"},create($,J){return P({kind:"TopNode",expression:$,modifiers:J})}})});function TY($,J){if(!wY($)&&!SU($))throw Error(`Invalid top expression: ${$}`);if(!d5(J)&&!LD0(J))throw Error(`Invalid top modifiers: ${J}`);return C_$.create($,J)}function LD0($){return $==="percent"||$==="with ties"||$==="percent with ties"}var BD=D(()=>{v$$();G$()});var KL;var h$$=D(()=>{G$();KL=P({is($){return $.kind==="OrActionNode"},create($){return P({kind:"OrActionNode",action:$})}})});class y6{#$;constructor($){this.#$=P($)}values($){let[J,X]=Ly($);return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{columns:J,values:X})})}columns($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{columns:P($.map(T4.create))})})}expression($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{values:BJ($)})})}defaultValues(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{defaultValues:!0})})}modifyEnd($){return new y6({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}ignore(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("ignore")})})}orIgnore(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("ignore")})})}orAbort(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("abort")})})}orFail(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("fail")})})}orReplace(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("replace")})})}orRollback(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("rollback")})})}top($,J){return new y6({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}onConflict($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{onConflict:$(new QG({onConflictNode:o5.create()})).toOperationNode()})})}onDuplicateKeyUpdate($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{onDuplicateKey:P_$.create(zM($))})})}returning($){return new y6({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll(){return new y6({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ())})}output($){return new y6({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new y6({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}clearReturning(){return new y6({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new y6({...this.#$})}$castTo(){return new y6(this.#$)}$narrowType(){return new y6(this.#$)}$assertType(){return new y6(this.#$)}withPlugin($){return new y6({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new y$$(X.insertId,X.numAffectedRows??BigInt(0))]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new y6({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var g$$=D(()=>{fU();I$$();WL();PQ();Hy();G$();b$$();VL();EQ();U5();f$$();Oy();BD();h$$()});class u$${numDeletedRows;constructor($){this.numDeletedRows=$}}var DD;var HM=D(()=>{G$();DD=P({is($){return $.kind==="LimitNode"},create($){return P({kind:"LimitNode",limit:$})}})});class By{#$;constructor($){this.#$=P($)}where(...$){return new x8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new x8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}clearWhere(){return new x8({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}top($,J){return new x8({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}using($){return new x8({...this.#$,queryNode:yU.cloneWithUsing(this.#$.queryNode,CY($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}#J($,J){return new x8({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}returning($){return new x8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new x8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new x8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new x8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}clearReturning(){return new x8({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}clearLimit(){return new x8({...this.#$,queryNode:yU.cloneWithoutLimit(this.#$.queryNode)})}orderBy(...$){return new x8({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}clearOrderBy(){return new x8({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}limit($){return new x8({...this.#$,queryNode:yU.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}modifyEnd($){return new x8({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}$call($){return $(this)}$if($,J){if($)return J(this);return new x8({...this.#$})}$castTo(){return new x8(this.#$)}$narrowType(){return new x8(this.#$)}$assertType(){return new x8(this.#$)}withPlugin($){return new x8({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new u$$(X.numAffectedRows??BigInt(0))]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new x8({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var x8;var m$$=D(()=>{OM();IJ();fU();PQ();G$();VL();VM();HM();XL();IX();$G();BD();x8=By});class l$${numUpdatedRows;numChangedRows;constructor($,J){this.numUpdatedRows=$,this.numChangedRows=J}}class FD{#$;constructor($){this.#$=P($)}where(...$){return new b8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new b8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}clearWhere(){return new b8({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}top($,J){return new b8({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}from($){return new b8({...this.#$,queryNode:JG.cloneWithFromItems(this.#$.queryNode,CY($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}#J($,J){return new b8({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}orderBy(...$){return new b8({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}clearOrderBy(){return new b8({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}limit($){return new b8({...this.#$,queryNode:JG.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}set(...$){return new b8({...this.#$,queryNode:JG.cloneWithUpdates(this.#$.queryNode,E_$(...$))})}returning($){return new b8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new b8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new b8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new b8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}modifyEnd($){return new b8({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}clearReturning(){return new b8({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new b8({...this.#$})}$castTo(){return new b8(this.#$)}$narrowType(){return new b8(this.#$)}$assertType(){return new b8(this.#$)}withPlugin($){return new b8({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new l$$(X.numAffectedRows??BigInt(0),X.numChangedRows)]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new b8({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var b8;var Dy=D(()=>{OM();IJ();fU();PQ();zD();Hy();G$();VL();IX();$G();HM();BD();XL();b8=FD});var p$$;var c$$=D(()=>{G$();U5();XD();p$$=P({is($){return $.kind==="CommonTableExpressionNameNode"},create($,J){return P({kind:"CommonTableExpressionNameNode",table:S7.create($),columns:J?P(J.map(T4.create)):void 0})}})});var qD;var Fy=D(()=>{G$();qD=P({is($){return $.kind==="CommonTableExpressionNode"},create($,J){return P({kind:"CommonTableExpressionNode",name:$,expression:J})},cloneWith($,J){return P({...$,...J})}})});class BM{#$;constructor($){this.#$=P($)}materialized(){return new BM({...this.#$,node:qD.cloneWith(this.#$.node,{materialized:!0})})}notMaterialized(){return new BM({...this.#$,node:qD.cloneWith(this.#$.node,{materialized:!1})})}toOperationNode(){return this.#$.node}}var S_$=D(()=>{Fy();G$()});function n$$($,J){let X=x6(J)?J.toOperationNode():J(x_$()).toOperationNode();if(a4($))return $(HD0(X)).toOperationNode();return qD.create(I_$($),X)}function HD0($){return(J)=>{return new BM({node:qD.create(I_$(J),$)})}}function I_$($){if($.includes("(")){let J=$.split(/[\(\)]/),X=J[0],Q=J[1].split(",").map((Y)=>Y.trim());return p$$.create(X,Q)}else return p$$.create($)}var k_$=D(()=>{c$$();qy();G$();S_$();Fy();i5()});var DM;var d$$=D(()=>{G$();DM=P({is($){return $.kind==="WithNode"},create($,J){return P({kind:"WithNode",expressions:P([$]),...J})},cloneWithExpression($,J){return P({...$,expressions:P([...$.expressions,J])})}})});function wy($){let J="";for(let X=0;X<$;++X)J+=OD0();return J}function OD0(){return b_$[~~(Math.random()*b_$.length)]}var b_$;var i$$=D(()=>{b_$=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function M1(){return new y_$}class y_${#$;get queryId(){if(this.#$===void 0)this.#$=wy(8);return this.#$}}var SY=D(()=>{i$$()});class xX{nodeStack=[];#$=P({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode($,J){if(!$)return $;this.nodeStack.push($);let X=this.transformNodeImpl($,J);return this.nodeStack.pop(),P(X)}transformNodeImpl($,J){return this.#$[$.kind]($,J)}transformNodeList($,J){if(!$)return $;return P($.map((X)=>this.transformNode(X,J)))}transformSelectQuery($,J){return{kind:"SelectQueryNode",from:this.transformNode($.from,J),selections:this.transformNodeList($.selections,J),distinctOn:this.transformNodeList($.distinctOn,J),joins:this.transformNodeList($.joins,J),groupBy:this.transformNode($.groupBy,J),orderBy:this.transformNode($.orderBy,J),where:this.transformNode($.where,J),frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),limit:this.transformNode($.limit,J),offset:this.transformNode($.offset,J),with:this.transformNode($.with,J),having:this.transformNode($.having,J),explain:this.transformNode($.explain,J),setOperations:this.transformNodeList($.setOperations,J),fetch:this.transformNode($.fetch,J),top:this.transformNode($.top,J)}}transformSelection($,J){return{kind:"SelectionNode",selection:this.transformNode($.selection,J)}}transformColumn($,J){return{kind:"ColumnNode",column:this.transformNode($.column,J)}}transformAlias($,J){return{kind:"AliasNode",node:this.transformNode($.node,J),alias:this.transformNode($.alias,J)}}transformTable($,J){return{kind:"TableNode",table:this.transformNode($.table,J)}}transformFrom($,J){return{kind:"FromNode",froms:this.transformNodeList($.froms,J)}}transformReference($,J){return{kind:"ReferenceNode",column:this.transformNode($.column,J),table:this.transformNode($.table,J)}}transformAnd($,J){return{kind:"AndNode",left:this.transformNode($.left,J),right:this.transformNode($.right,J)}}transformOr($,J){return{kind:"OrNode",left:this.transformNode($.left,J),right:this.transformNode($.right,J)}}transformValueList($,J){return{kind:"ValueListNode",values:this.transformNodeList($.values,J)}}transformParens($,J){return{kind:"ParensNode",node:this.transformNode($.node,J)}}transformJoin($,J){return{kind:"JoinNode",joinType:$.joinType,table:this.transformNode($.table,J),on:this.transformNode($.on,J)}}transformRaw($,J){return{kind:"RawNode",sqlFragments:P([...$.sqlFragments]),parameters:this.transformNodeList($.parameters,J)}}transformWhere($,J){return{kind:"WhereNode",where:this.transformNode($.where,J)}}transformInsertQuery($,J){return{kind:"InsertQueryNode",into:this.transformNode($.into,J),columns:this.transformNodeList($.columns,J),values:this.transformNode($.values,J),returning:this.transformNode($.returning,J),onConflict:this.transformNode($.onConflict,J),onDuplicateKey:this.transformNode($.onDuplicateKey,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),orAction:this.transformNode($.orAction,J),replace:$.replace,explain:this.transformNode($.explain,J),defaultValues:$.defaultValues,top:this.transformNode($.top,J),output:this.transformNode($.output,J)}}transformValues($,J){return{kind:"ValuesNode",values:this.transformNodeList($.values,J)}}transformDeleteQuery($,J){return{kind:"DeleteQueryNode",from:this.transformNode($.from,J),using:this.transformNode($.using,J),joins:this.transformNodeList($.joins,J),where:this.transformNode($.where,J),returning:this.transformNode($.returning,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),orderBy:this.transformNode($.orderBy,J),limit:this.transformNode($.limit,J),explain:this.transformNode($.explain,J),top:this.transformNode($.top,J),output:this.transformNode($.output,J)}}transformReturning($,J){return{kind:"ReturningNode",selections:this.transformNodeList($.selections,J)}}transformCreateTable($,J){return{kind:"CreateTableNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),constraints:this.transformNodeList($.constraints,J),indexes:this.transformNodeList($.indexes,J),temporary:$.temporary,ifNotExists:$.ifNotExists,onCommit:$.onCommit,frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),selectQuery:this.transformNode($.selectQuery,J)}}transformColumnDefinition($,J){return{kind:"ColumnDefinitionNode",column:this.transformNode($.column,J),dataType:this.transformNode($.dataType,J),references:this.transformNode($.references,J),primaryKey:$.primaryKey,autoIncrement:$.autoIncrement,unique:$.unique,notNull:$.notNull,unsigned:$.unsigned,defaultTo:this.transformNode($.defaultTo,J),check:this.transformNode($.check,J),generated:this.transformNode($.generated,J),frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),nullsNotDistinct:$.nullsNotDistinct,identity:$.identity,ifNotExists:$.ifNotExists}}transformAddColumn($,J){return{kind:"AddColumnNode",column:this.transformNode($.column,J)}}transformDropTable($,J){return{kind:"DropTableNode",table:this.transformNode($.table,J),ifExists:$.ifExists,cascade:$.cascade,temporary:$.temporary}}transformOrderBy($,J){return{kind:"OrderByNode",items:this.transformNodeList($.items,J)}}transformOrderByItem($,J){return{kind:"OrderByItemNode",orderBy:this.transformNode($.orderBy,J),direction:this.transformNode($.direction,J),collation:this.transformNode($.collation,J),nulls:$.nulls}}transformGroupBy($,J){return{kind:"GroupByNode",items:this.transformNodeList($.items,J)}}transformGroupByItem($,J){return{kind:"GroupByItemNode",groupBy:this.transformNode($.groupBy,J)}}transformUpdateQuery($,J){return{kind:"UpdateQueryNode",table:this.transformNode($.table,J),from:this.transformNode($.from,J),joins:this.transformNodeList($.joins,J),where:this.transformNode($.where,J),updates:this.transformNodeList($.updates,J),returning:this.transformNode($.returning,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),explain:this.transformNode($.explain,J),limit:this.transformNode($.limit,J),top:this.transformNode($.top,J),output:this.transformNode($.output,J),orderBy:this.transformNode($.orderBy,J)}}transformColumnUpdate($,J){return{kind:"ColumnUpdateNode",column:this.transformNode($.column,J),value:this.transformNode($.value,J)}}transformLimit($,J){return{kind:"LimitNode",limit:this.transformNode($.limit,J)}}transformOffset($,J){return{kind:"OffsetNode",offset:this.transformNode($.offset,J)}}transformOnConflict($,J){return{kind:"OnConflictNode",columns:this.transformNodeList($.columns,J),constraint:this.transformNode($.constraint,J),indexExpression:this.transformNode($.indexExpression,J),indexWhere:this.transformNode($.indexWhere,J),updates:this.transformNodeList($.updates,J),updateWhere:this.transformNode($.updateWhere,J),doNothing:$.doNothing}}transformOnDuplicateKey($,J){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList($.updates,J)}}transformCreateIndex($,J){return{kind:"CreateIndexNode",name:this.transformNode($.name,J),table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),unique:$.unique,using:this.transformNode($.using,J),ifNotExists:$.ifNotExists,where:this.transformNode($.where,J),nullsNotDistinct:$.nullsNotDistinct}}transformList($,J){return{kind:"ListNode",items:this.transformNodeList($.items,J)}}transformDropIndex($,J){return{kind:"DropIndexNode",name:this.transformNode($.name,J),table:this.transformNode($.table,J),ifExists:$.ifExists,cascade:$.cascade}}transformPrimaryKeyConstraint($,J){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList($.columns,J),name:this.transformNode($.name,J),deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformUniqueConstraint($,J){return{kind:"UniqueConstraintNode",columns:this.transformNodeList($.columns,J),name:this.transformNode($.name,J),nullsNotDistinct:$.nullsNotDistinct,deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformForeignKeyConstraint($,J){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList($.columns,J),references:this.transformNode($.references,J),name:this.transformNode($.name,J),onDelete:$.onDelete,onUpdate:$.onUpdate,deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformSetOperation($,J){return{kind:"SetOperationNode",operator:$.operator,expression:this.transformNode($.expression,J),all:$.all}}transformReferences($,J){return{kind:"ReferencesNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),onDelete:$.onDelete,onUpdate:$.onUpdate}}transformCheckConstraint($,J){return{kind:"CheckConstraintNode",expression:this.transformNode($.expression,J),name:this.transformNode($.name,J)}}transformWith($,J){return{kind:"WithNode",expressions:this.transformNodeList($.expressions,J),recursive:$.recursive}}transformCommonTableExpression($,J){return{kind:"CommonTableExpressionNode",name:this.transformNode($.name,J),materialized:$.materialized,expression:this.transformNode($.expression,J)}}transformCommonTableExpressionName($,J){return{kind:"CommonTableExpressionNameNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J)}}transformHaving($,J){return{kind:"HavingNode",having:this.transformNode($.having,J)}}transformCreateSchema($,J){return{kind:"CreateSchemaNode",schema:this.transformNode($.schema,J),ifNotExists:$.ifNotExists}}transformDropSchema($,J){return{kind:"DropSchemaNode",schema:this.transformNode($.schema,J),ifExists:$.ifExists,cascade:$.cascade}}transformAlterTable($,J){return{kind:"AlterTableNode",table:this.transformNode($.table,J),renameTo:this.transformNode($.renameTo,J),setSchema:this.transformNode($.setSchema,J),columnAlterations:this.transformNodeList($.columnAlterations,J),addConstraint:this.transformNode($.addConstraint,J),dropConstraint:this.transformNode($.dropConstraint,J),renameConstraint:this.transformNode($.renameConstraint,J),addIndex:this.transformNode($.addIndex,J),dropIndex:this.transformNode($.dropIndex,J)}}transformDropColumn($,J){return{kind:"DropColumnNode",column:this.transformNode($.column,J),ifExists:$.ifExists}}transformRenameColumn($,J){return{kind:"RenameColumnNode",column:this.transformNode($.column,J),renameTo:this.transformNode($.renameTo,J)}}transformAlterColumn($,J){return{kind:"AlterColumnNode",column:this.transformNode($.column,J),dataType:this.transformNode($.dataType,J),dataTypeExpression:this.transformNode($.dataTypeExpression,J),setDefault:this.transformNode($.setDefault,J),dropDefault:$.dropDefault,setNotNull:$.setNotNull,dropNotNull:$.dropNotNull}}transformModifyColumn($,J){return{kind:"ModifyColumnNode",column:this.transformNode($.column,J)}}transformAddConstraint($,J){return{kind:"AddConstraintNode",constraint:this.transformNode($.constraint,J)}}transformDropConstraint($,J){return{kind:"DropConstraintNode",constraintName:this.transformNode($.constraintName,J),ifExists:$.ifExists,modifier:$.modifier}}transformRenameConstraint($,J){return{kind:"RenameConstraintNode",oldName:this.transformNode($.oldName,J),newName:this.transformNode($.newName,J)}}transformCreateView($,J){return{kind:"CreateViewNode",name:this.transformNode($.name,J),temporary:$.temporary,orReplace:$.orReplace,ifNotExists:$.ifNotExists,materialized:$.materialized,columns:this.transformNodeList($.columns,J),as:this.transformNode($.as,J)}}transformRefreshMaterializedView($,J){return{kind:"RefreshMaterializedViewNode",name:this.transformNode($.name,J),concurrently:$.concurrently,withNoData:$.withNoData}}transformDropView($,J){return{kind:"DropViewNode",name:this.transformNode($.name,J),ifExists:$.ifExists,materialized:$.materialized,cascade:$.cascade}}transformGenerated($,J){return{kind:"GeneratedNode",byDefault:$.byDefault,always:$.always,identity:$.identity,stored:$.stored,expression:this.transformNode($.expression,J)}}transformDefaultValue($,J){return{kind:"DefaultValueNode",defaultValue:this.transformNode($.defaultValue,J)}}transformOn($,J){return{kind:"OnNode",on:this.transformNode($.on,J)}}transformSelectModifier($,J){return{kind:"SelectModifierNode",modifier:$.modifier,rawModifier:this.transformNode($.rawModifier,J),of:this.transformNodeList($.of,J)}}transformCreateType($,J){return{kind:"CreateTypeNode",name:this.transformNode($.name,J),enum:this.transformNode($.enum,J)}}transformDropType($,J){return{kind:"DropTypeNode",name:this.transformNode($.name,J),additionalNames:this.transformNodeList($.additionalNames,J),cascade:$.cascade,ifExists:$.ifExists}}transformExplain($,J){return{kind:"ExplainNode",format:$.format,options:this.transformNode($.options,J)}}transformSchemableIdentifier($,J){return{kind:"SchemableIdentifierNode",schema:this.transformNode($.schema,J),identifier:this.transformNode($.identifier,J)}}transformAggregateFunction($,J){return{kind:"AggregateFunctionNode",func:$.func,aggregated:this.transformNodeList($.aggregated,J),distinct:$.distinct,orderBy:this.transformNode($.orderBy,J),withinGroup:this.transformNode($.withinGroup,J),filter:this.transformNode($.filter,J),over:this.transformNode($.over,J)}}transformOver($,J){return{kind:"OverNode",orderBy:this.transformNode($.orderBy,J),partitionBy:this.transformNode($.partitionBy,J)}}transformPartitionBy($,J){return{kind:"PartitionByNode",items:this.transformNodeList($.items,J)}}transformPartitionByItem($,J){return{kind:"PartitionByItemNode",partitionBy:this.transformNode($.partitionBy,J)}}transformBinaryOperation($,J){return{kind:"BinaryOperationNode",leftOperand:this.transformNode($.leftOperand,J),operator:this.transformNode($.operator,J),rightOperand:this.transformNode($.rightOperand,J)}}transformUnaryOperation($,J){return{kind:"UnaryOperationNode",operator:this.transformNode($.operator,J),operand:this.transformNode($.operand,J)}}transformUsing($,J){return{kind:"UsingNode",tables:this.transformNodeList($.tables,J)}}transformFunction($,J){return{kind:"FunctionNode",func:$.func,arguments:this.transformNodeList($.arguments,J)}}transformCase($,J){return{kind:"CaseNode",value:this.transformNode($.value,J),when:this.transformNodeList($.when,J),else:this.transformNode($.else,J),isStatement:$.isStatement}}transformWhen($,J){return{kind:"WhenNode",condition:this.transformNode($.condition,J),result:this.transformNode($.result,J)}}transformJSONReference($,J){return{kind:"JSONReferenceNode",reference:this.transformNode($.reference,J),traversal:this.transformNode($.traversal,J)}}transformJSONPath($,J){return{kind:"JSONPathNode",inOperator:this.transformNode($.inOperator,J),pathLegs:this.transformNodeList($.pathLegs,J)}}transformJSONPathLeg($,J){return{kind:"JSONPathLegNode",type:$.type,value:$.value}}transformJSONOperatorChain($,J){return{kind:"JSONOperatorChainNode",operator:this.transformNode($.operator,J),values:this.transformNodeList($.values,J)}}transformTuple($,J){return{kind:"TupleNode",values:this.transformNodeList($.values,J)}}transformMergeQuery($,J){return{kind:"MergeQueryNode",into:this.transformNode($.into,J),using:this.transformNode($.using,J),whens:this.transformNodeList($.whens,J),with:this.transformNode($.with,J),top:this.transformNode($.top,J),endModifiers:this.transformNodeList($.endModifiers,J),output:this.transformNode($.output,J),returning:this.transformNode($.returning,J)}}transformMatched($,J){return{kind:"MatchedNode",not:$.not,bySource:$.bySource}}transformAddIndex($,J){return{kind:"AddIndexNode",name:this.transformNode($.name,J),columns:this.transformNodeList($.columns,J),unique:$.unique,using:this.transformNode($.using,J),ifNotExists:$.ifNotExists}}transformCast($,J){return{kind:"CastNode",expression:this.transformNode($.expression,J),dataType:this.transformNode($.dataType,J)}}transformFetch($,J){return{kind:"FetchNode",rowCount:this.transformNode($.rowCount,J),modifier:$.modifier}}transformTop($,J){return{kind:"TopNode",expression:$.expression,modifiers:$.modifiers}}transformOutput($,J){return{kind:"OutputNode",selections:this.transformNodeList($.selections,J)}}transformAlterType($,J){return{kind:"AlterTypeNode",name:this.transformNode($.name,J),addValue:this.transformNode($.addValue,J),renameTo:this.transformNode($.renameTo,J),renameValue:this.transformNode($.renameValue,J),setSchema:this.transformNode($.setSchema,J)}}transformAddValue($,J){return{kind:"AddValueNode",value:this.transformNode($.value,J),ifNotExists:$.ifNotExists,isBefore:$.isBefore,neighborValue:this.transformNode($.neighborValue,J)}}transformRenameValue($,J){return{kind:"RenameValueNode",oldValue:this.transformNode($.oldValue,J),newValue:this.transformNode($.newValue,J)}}transformDataType($,J){return $}transformSelectAll($,J){return $}transformIdentifier($,J){return $}transformValue($,J){return $}transformPrimitiveValueList($,J){return $}transformOperator($,J){return $}transformDefaultInsertValue($,J){return $}transformOrAction($,J){return $}transformCollate($,J){return $}}var hU=D(()=>{G$()});function f_$($){return L6($)&&C1($.kind)}var v_$=D(()=>{G$()});function h_$($){return f_$($)&&BD0[$.kind]===!0}var BD0;var g_$=D(()=>{v_$();BD0={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}});var DD0,o$$;var u_$=D(()=>{AY();k6();QD();Ky();hU();g_$();sj();XD();Uy();G$();DD0=P({json_agg:!0,to_json:!0});o$$=class o$$ extends xX{#$;#J=new Set;#X=new Set;constructor($){super();this.#$=$}transformNodeImpl($,J){if(!h_$($))return super.transformNodeImpl($,J);let X=this.#G($);for(let W of X)this.#X.add(W);let Q=this.#Y($);for(let W of Q)this.#J.add(W);let Y=super.transformNodeImpl($,J);for(let W of Q)this.#J.delete(W);for(let W of X)this.#X.delete(W);return Y}transformSchemableIdentifier($,J){let X=super.transformSchemableIdentifier($,J);if(X.schema||!this.#J.has($.identifier.name))return X;return{...X,schema:U1.create(this.#$)}}transformReferences($,J){let X=super.transformReferences($,J);if(X.table.table.schema)return X;return{...X,table:S7.createWithSchema(this.#$,X.table.table.identifier.name)}}transformAggregateFunction($,J){return{...super.transformAggregateFunction({...$,aggregated:[]},J),aggregated:this.#Q($,J,"aggregated")}}transformFunction($,J){return{...super.transformFunction({...$,arguments:[]},J),arguments:this.#Q($,J,"arguments")}}transformSelectModifier($,J){return{...super.transformSelectModifier({...$,of:void 0},J),of:$.of?.map((X)=>S7.is(X)&&!X.table.schema?{...X,table:this.transformIdentifier(X.table.identifier,J)}:this.transformNode(X,J))}}#Q($,J,X){return DD0[$.func]?$[X].map((Q)=>!S7.is(Q)||Q.table.schema?this.transformNode(Q,J):{...Q,table:this.transformIdentifier(Q.table.identifier,J)}):this.transformNodeList($[X],J)}#Y($){let J=new Set;if("name"in $&&$.name&&K5.is($.name))this.#Z($.name,J);if("from"in $&&$.from)for(let X of $.from.froms)this.#W(X,J);if("into"in $&&$.into)this.#W($.into,J);if("table"in $&&$.table)this.#W($.table,J);if("joins"in $&&$.joins)for(let X of $.joins)this.#W(X.table,J);if("using"in $&&$.using)if(MY.is($.using))this.#W($.using.table,J);else this.#W($.using,J);return J}#G($){let J=new Set;if("with"in $&&$.with)this.#j($.with,J);return J}#W($,J){if(S7.is($))return this.#Z($.table,J);if(LJ.is($)&&S7.is($.node))return this.#Z($.node.table,J);if(Vy.is($)){for(let X of $.items)this.#W(X,J);return}if(jM.is($)){for(let X of $.tables)this.#W(X,J);return}}#Z($,J){let X=$.identifier.name;if(!this.#J.has(X)&&!this.#X.has(X))J.add(X)}#j($,J){for(let X of $.expressions){let Q=X.name.table.table.identifier.name;if(!this.#X.has(Q))J.add(Q)}}}});class IY{#$;constructor($){this.#$=new o$$($)}transformQuery($){return this.#$.transformNode($.node,$.queryId)}async transformResult($){return $.result}}var wD=D(()=>{u_$()});var m_$;var r$$=D(()=>{G$();m_$=P({is($){return $.kind==="MatchedNode"},create($,J=!1){return P({kind:"MatchedNode",not:$,bySource:J})}})});function t$$($,J,X){return x7.create(UD([m_$.create(!$.isMatched,$.bySource),...J&&J.length>0?[J.length===3&&X?O9(J[0],J[1],J[2]):d6(J)]:[]],"and",!1))}function ND($){if(C1($))return v4.create([$],[]);if(x6($))return $.toOperationNode();return $}var l_$=D(()=>{r$$();i5();PX();GL();G$();IX()});class z5{#$;#J;#X;constructor(){this.#$=new Promise(($,J)=>{this.#X=J,this.#J=$})}get promise(){return this.#$}resolve=($)=>{this.#J?.($),this.#J=this.#X=void 0};reject=($)=>{this.#X?.($),this.#X=this.#J=void 0}}async function AD($,J){let X=new z5,Q=new z5;return $.provideConnection(async(Y)=>{return X.resolve(Y),await Q.promise},J).catch((Y)=>X.reject(Y)),P({connection:await X.promise,release:Q.resolve})}var a$$=D(()=>{G$()});function c_$($="ignore query",J,X){if($==="ignore query")return;if($==="cancel query"){let Q=J.cancelQuery;if(!Q)p_$($,J.killSession?"kill session":void 0);return Q.bind(J)}if($==="kill session"){let Q=J.killSession;if(!Q)p_$($,J.cancelQuery?"cancel query":void 0);return Q.bind(J)}throw X(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${$}"`)}function p_$($,J){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${$}". Use "ignore query"${J?` or "${J}"`:""} instead.`)}function QV($,J,X){if($?.aborted)X?.(),gU($.reason,J)}function gU($,J){throw FD0($,J),$}async function uU($,J,X,Q){if(!J)return $;QV(J,`before ${X}`,Q);let{promise:Y,resolve:W}=new z5,G=()=>W(bX);J.addEventListener("abort",G);try{QV(J,`before ${X}`,Q);let Z=await Promise.race([$,Y]);if(Z!==bX)return Z;Q?.(),gU(J.reason,`during ${X}`)}finally{J.removeEventListener("abort",G),W(bX)}}function YG($){return(J)=>console.error(`\`${$}\` failed in the background after abortion: ${aA$(J)}`)}function FD0($,J){if($!==null&&typeof $==="object"&&!Object.isFrozen($))Object.defineProperty($,"__kysely_timing__",{configurable:!0,enumerable:!1,value:J,writable:!1})}var bX;var Ny=D(()=>{G$();bX={}});class FM{#$;constructor($=qD0){this.#$=$}get plugins(){return this.#$}transformQuery($,J){for(let X of this.#$){let Q=X.transformQuery({node:$,queryId:J});if(Q.kind===$.kind)$=Q;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${$.kind}`,`but it returned a ${Q.kind}`].join(" "))}return $}async executeQuery($,J){let{inflightQueryAbortStrategy:X="ignore query",signal:Q}=J||{};if(!Q){let K=await this.provideConnection(async(z)=>{return await z.executeQuery($)},J);return await this.#J(K,$.queryId)}QV(Q,"before query execution"),J=P({signal:Q});let{connection:Y,release:W}=await AD(this,J),G=this.provideConnection.bind(this),{promise:Z,resolve:j}=new z5,V=()=>j(bX);Q.addEventListener("abort",V,{once:!0});try{QV(Q,"before query execution",W);let K=c_$(X,Y,W);if(K&&Y.collectSessionInfo){QV(Q,"before query execution",W);let B=Y.collectSessionInfo();if(await Promise.race([Z,B]).catch((A)=>{throw W(),A})===bX)B.catch(YG("collectSessionInfo")).finally(W),gU(Q.reason,"before query execution")}let z=Y.executeQuery($,J),L=await Promise.race([Z,z]).catch((B)=>{throw W(),B});if(L===bX)Promise.allSettled([z.catch(YG("query")),K?.(G).catch(YG("inflightQueryAbortHandler"))]).finally(W),gU(Q.reason,"during query execution");else W();let H=this.#J(L,$.queryId,J),O=await Promise.race([Z,H]);if(O===bX)H.catch(YG("plugins.transformResult")),gU(Q.reason,"during result transformation");return O}finally{j(bX),Q.removeEventListener("abort",V)}}async*stream($,J,X){let{signal:Q}=X||{};if(!Q){let{connection:L,release:H}=await AD(this);try{for await(let O of L.streamQuery($,J))yield await this.#J(O,$.queryId,X)}finally{H()}return}X=P({signal:Q}),QV(Q,"before connection acquisition");let{connection:Y,release:W}=await AD(this,X),{promise:G,resolve:Z}=new z5,j=()=>Z(bX);Q.addEventListener("abort",j,{once:!0});let V,K;QV(Q,"before query streaming",W);let{queryId:z}=$;try{V=Y.streamQuery($,J,X);while(!0){QV(Q,"during query streaming");let L=V.next(),H=await Promise.race([G,L]);if(H===bX)K=L.catch(YG("iterator.next")),gU(Q.reason,"during query streaming");if(H.done)break;let O=this.#J(H.value,z,X),B=await Promise.race([G,O]);if(B===bX)K=O.catch(YG("plugins.transformResult")),gU(Q.reason,"during result transformation");yield B}}finally{Z(bX),Q.removeEventListener("abort",j);let L=(V?.return?.()||Promise.resolve()).finally(()=>K).finally(W);if(!K)await L}}async#J($,J,X){let{signal:Q}=X||{};for(let Y of this.#$)$=await Y.transformResult(P({queryId:J,result:$,signal:Q}));return $}}var qD0;var s$$=D(()=>{G$();a$$();Ny();qD0=P([])});var _D,mU;var MD=D(()=>{s$$();_D=class _D extends FM{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin($){return new _D([...this.plugins,$])}withPlugins($){return new _D([...this.plugins,...$])}withPluginAtFront($){return new _D([$,...this.plugins])}withoutPlugins(){return new _D([])}};mU=new _D});class e$${numChangedRows;constructor($){this.numChangedRows=$}}class YV{#$;constructor($){this.#$=P($)}modifyEnd($){return new YV({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,J){return new YV({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}using(...$){return new b7({...this.#$,queryNode:kX.cloneWithUsing(this.#$.queryNode,vU("Using",$))})}returning($){return new YV({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new YV({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new YV({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new YV({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}}class b7{#$;constructor($){this.#$=P($)}modifyEnd($){return new b7({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,J){return new b7({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}whenMatched(){return this.#J([])}whenMatchedAnd(...$){return this.#J($)}whenMatchedAndRef($,J,X){return this.#J([$,J,X],!0)}#J($,J){return new $0$({...this.#$,queryNode:kX.cloneWithWhen(this.#$.queryNode,t$$({isMatched:!0},$,J))})}whenNotMatched(){return this.#X([])}whenNotMatchedAnd(...$){return this.#X($)}whenNotMatchedAndRef($,J,X){return this.#X([$,J,X],!0)}whenNotMatchedBySource(){return this.#X([],!1,!0)}whenNotMatchedBySourceAnd(...$){return this.#X($,!1,!0)}whenNotMatchedBySourceAndRef($,J,X){return this.#X([$,J,X],!0,!0)}returning($){return new b7({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new b7({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new b7({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new b7({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}#X($,J=!1,X=!1){let Q={...this.#$,queryNode:kX.cloneWithWhen(this.#$.queryNode,t$$({isMatched:!1,bySource:X},$,J))};return new(X?$0$:n_$)(Q)}$call($){return $(this)}$if($,J){if($)return J(this);return new b7({...this.#$})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new e$$(X.numAffectedRows)]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}}class $0${#$;constructor($){this.#$=P($)}thenDelete(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("delete"))})}thenDoNothing(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("do nothing"))})}thenUpdate($){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND($(new FD({queryId:this.#$.queryId,executor:mU,queryNode:JG.createWithoutTable()}))))})}thenUpdateSet(...$){return this.thenUpdate((J)=>J.set(...$))}}class n_${#$;constructor($){this.#$=P($)}thenDoNothing(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("do nothing"))})}thenInsertValues($){let[J,X]=Ly($);return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND(k8.cloneWith(k8.createWithoutInto(),{columns:J,values:X})))})}}var J0$=D(()=>{WL();UM();PQ();zD();I$$();OM();l_$();fU();BD();MD();G$();VL();Dy()});class WG{#$;constructor($){this.#$=P($)}selectFrom($){return qM({queryId:M1(),executor:this.#$.executor,queryNode:H6.createFrom(CY($),this.#$.withNode)})}selectNoFrom($){return qM({queryId:M1(),executor:this.#$.executor,queryNode:H6.cloneWithSelections(H6.create(this.#$.withNode),u9($))})}insertInto($){return new y6({queryId:M1(),executor:this.#$.executor,queryNode:k8.create(e4($),this.#$.withNode)})}replaceInto($){return new y6({queryId:M1(),executor:this.#$.executor,queryNode:k8.create(e4($),this.#$.withNode,!0)})}deleteFrom($){return new By({queryId:M1(),executor:this.#$.executor,queryNode:yU.create(CY($),this.#$.withNode)})}updateTable($){return new FD({queryId:M1(),executor:this.#$.executor,queryNode:JG.create(CY($),this.#$.withNode)})}mergeInto($){return new YV({queryId:M1(),executor:this.#$.executor,queryNode:kX.create(X0$($),this.#$.withNode)})}with($,J){let X=n$$($,J);return new WG({...this.#$,withNode:this.#$.withNode?DM.cloneWithExpression(this.#$.withNode,X):DM.create(X)})}withRecursive($,J){let X=n$$($,J);return new WG({...this.#$,withNode:this.#$.withNode?DM.cloneWithExpression(this.#$.withNode,X):DM.create(X,{recursive:!0})})}withPlugin($){return new WG({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new WG({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new WG({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}}var Ay=D(()=>{_y();g$$();m$$();Dy();VM();WL();ZL();zD();IJ();k_$();d$$();SY();wD();G$();fU();J0$();UM()});function x_$(){return new WG({executor:mU})}function d_$($,J){return new LD({joinNode:MY.create($,UL(J))})}function i_$(){return new HD({overNode:GM.create()})}var qy=D(()=>{QD();jy();E$$();N_$();Ay();MD();IJ()});function vU($,J){if(J.length===3)return ND0($,J[0],J[1],J[2]);else if(J.length===2)return wD0($,J[0],J[1]);else if(J.length===1)return AD0($,J[0]);else throw Error("not implemented")}function wD0($,J,X){return X(d_$($,J)).toOperationNode()}function ND0($,J,X,Q){return MY.createWithOn($,UL(J),O9(X,"=",Q))}function AD0($,J){return MY.create($,UL(J))}var OM=D(()=>{QD();IX();qy();IJ()});var o_$;var Q0$=D(()=>{G$();o_$=P({is($){return $.kind==="OffsetNode"},create($){return P({kind:"OffsetNode",offset:$})}})});var r_$;var Y0$=D(()=>{G$();r_$=P({is($){return $.kind==="GroupByItemNode"},create($){return P({kind:"GroupByItemNode",groupBy:$})}})});function t_$($){return $=a4($)?$(EY()):$,JV($).map(r_$.create)}var a_$=D(()=>{Y0$();jL();G$();OJ()});var My;var Ry=D(()=>{G$();My=P({is($){return $.kind==="SetOperationNode"},create($,J,X){return P({kind:"SetOperationNode",operator:$,expression:J,all:X})}})});function zL($,J,X){if(a4(J))J=J(W0$());if(!KJ(J))J=[J];return J.map((Q)=>My.create($,BJ(Q),X))}var s_$=D(()=>{jL();Ry();G$();EQ()});class O6{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}or(...$){return new Ey(_Y.create(this.#$,d6($)))}and(...$){return new Py(I7.create(this.#$,d6($)))}$castTo(){return new O6(this.#$)}$notNull(){return new O6(this.#$)}toOperationNode(){return this.#$}}class Ty{#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}class Ey{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}or(...$){return new Ey(_Y.create(this.#$,d6($)))}$castTo(){return new Ey(this.#$)}toOperationNode(){return SX.create(this.#$)}}class Py{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}and(...$){return new Py(I7.create(this.#$,d6($)))}$castTo(){return new Py(this.#$)}toOperationNode(){return SX.create(this.#$)}}var RD=D(()=>{AY();kU();k6();i5();JL();KD();IX()});var e_$;var G0$=D(()=>{G$();CX();e_$=P({is($){return $.kind==="FetchNode"},create($,J){return{kind:"FetchNode",rowCount:n6.create($),modifier:J}}})});function $M$($,J){if(!wY($)&&!SU($))throw Error(`Invalid fetch row count: ${$}`);if(!_D0(J))throw Error(`Invalid fetch modifier: ${J}`);return e_$.create($,J)}function _D0($){return $==="only"||$==="with ties"}var JM$=D(()=>{G0$();G$()});class Z0${#$;constructor($){this.#$=P($)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...$){return new j4({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new j4({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}having(...$){return new j4({...this.#$,queryNode:H6.cloneWithHaving(this.#$.queryNode,d6($))})}havingRef($,J,X){return new j4({...this.#$,queryNode:H6.cloneWithHaving(this.#$.queryNode,O9($,J,X))})}select($){return new j4({...this.#$,queryNode:H6.cloneWithSelections(this.#$.queryNode,u9($))})}distinctOn($){return new j4({...this.#$,queryNode:H6.cloneWithDistinctOn(this.#$.queryNode,JV($))})}modifyFront($){return new j4({...this.#$,queryNode:H6.cloneWithFrontModifier(this.#$.queryNode,aW.createWithExpression($.toOperationNode()))})}modifyEnd($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.createWithExpression($.toOperationNode()))})}distinct(){return new j4({...this.#$,queryNode:H6.cloneWithFrontModifier(this.#$.queryNode,aW.create("Distinct"))})}forUpdate($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForUpdate",$?t_($).map(e4):void 0))})}forShare($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForShare",$?t_($).map(e4):void 0))})}forKeyShare($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForKeyShare",$?t_($).map(e4):void 0))})}forNoKeyUpdate($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForNoKeyUpdate",$?t_($).map(e4):void 0))})}skipLocked(){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("SkipLocked"))})}noWait(){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("NoWait"))})}selectAll($){return new j4({...this.#$,queryNode:H6.cloneWithSelections(this.#$.queryNode,DJ($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}crossJoin(...$){return this.#J("CrossJoin",$)}innerJoinLateral(...$){return this.#J("LateralInnerJoin",$)}leftJoinLateral(...$){return this.#J("LateralLeftJoin",$)}crossJoinLateral(...$){return this.#J("LateralCrossJoin",$)}crossApply(...$){return this.#J("CrossApply",$)}outerApply(...$){return this.#J("OuterApply",$)}#J($,J){return new j4({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}orderBy(...$){return new j4({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}groupBy($){return new j4({...this.#$,queryNode:H6.cloneWithGroupByItems(this.#$.queryNode,t_$($))})}limit($){return new j4({...this.#$,queryNode:H6.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}offset($){return new j4({...this.#$,queryNode:H6.cloneWithOffset(this.#$.queryNode,o_$.create(b6($)))})}fetch($,J="only"){return new j4({...this.#$,queryNode:H6.cloneWithFetch(this.#$.queryNode,$M$($,J))})}top($,J){return new j4({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}union($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("union",$,!1))})}unionAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("union",$,!0))})}intersect($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("intersect",$,!1))})}intersectAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("intersect",$,!0))})}except($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("except",$,!1))})}exceptAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("except",$,!0))})}as($){return new XM$(this,$)}clearSelect(){return new j4({...this.#$,queryNode:H6.cloneWithoutSelections(this.#$.queryNode)})}clearWhere(){return new j4({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}clearLimit(){return new j4({...this.#$,queryNode:H6.cloneWithoutLimit(this.#$.queryNode)})}clearOffset(){return new j4({...this.#$,queryNode:H6.cloneWithoutOffset(this.#$.queryNode)})}clearOrderBy(){return new j4({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}clearGroupBy(){return new j4({...this.#$,queryNode:H6.cloneWithoutGroupBy(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new j4({...this.#$})}$castTo(){return new j4(this.#$)}$narrowType(){return new j4(this.#$)}$assertType(){return new j4(this.#$)}$asTuple(){return new O6(this.toOperationNode())}$asScalar(){return new O6(this.toOperationNode())}withPlugin($){return new j4({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile();return(await this.#$.executor.executeQuery(J,$)).rows}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new j4({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}function qM($){return new Z0$($)}class XM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return LJ.create(this.#$.toOperationNode(),U1.create(this.#J))}}var j4;var _y=D(()=>{AY();X$$();OM();IJ();fU();OJ();ZL();PQ();XL();HM();Q0$();G$();a_$();VL();k6();s_$();IX();RD();$G();JM$();BD();j4=Z0$});var GG;var Cy=D(()=>{G$();KM();WM();GG=P({is($){return $.kind==="AggregateFunctionNode"},create($,J=[]){return P({kind:"AggregateFunctionNode",func:$,aggregated:J})},cloneWithDistinct($){return P({...$,distinct:!0})},cloneWithOrderBy($,J,X=!1){let Q=X?"withinGroup":"orderBy";return P({...$,[Q]:$[Q]?XV.cloneWithItems($[Q],J):XV.create(J)})},cloneWithFilter($,J){return P({...$,filter:$.filter?SJ.cloneWithOperation($.filter,"And",J):SJ.create(J)})},cloneWithOrFilter($,J){return P({...$,filter:$.filter?SJ.cloneWithOperation($.filter,"Or",J):SJ.create(J)})},cloneWithOver($,J){return P({...$,over:J})}})});var j0$;var V0$=D(()=>{G$();j0$=P({is($){return $.kind==="FunctionNode"},create($,J){return P({kind:"FunctionNode",func:$,arguments:J})}})});class y7{#$;constructor($){this.#$=P($)}get expressionType(){return}as($){return new QM$(this,$)}distinct(){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithDistinct(this.#$.aggregateFunctionNode)})}orderBy(...$){return new y7({...this.#$,aggregateFunctionNode:F0.cloneWithOrderByItems(this.#$.aggregateFunctionNode,TX($))})}clearOrderBy(){return new y7({...this.#$,aggregateFunctionNode:F0.cloneWithoutOrderBy(this.#$.aggregateFunctionNode)})}withinGroupOrderBy(...$){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithOrderBy(this.#$.aggregateFunctionNode,TX($),!0)})}filterWhere(...$){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithFilter(this.#$.aggregateFunctionNode,d6($))})}filterWhereRef($,J,X){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithFilter(this.#$.aggregateFunctionNode,O9($,J,X))})}over($){let J=i_$();return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithOver(this.#$.aggregateFunctionNode,($?$(J):J).toOperationNode())})}$call($){return $(this)}$castTo(){return new y7(this.#$)}$notNull(){return new y7(this.#$)}toOperationNode(){return this.#$.aggregateFunctionNode}}class QM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),U1.create(this.#J))}}var K0$=D(()=>{G$();Cy();AY();k6();qy();IX();XL();PQ()});function Sy(){let $=(X,Q)=>{return new O6(j0$.create(X,JV(Q??[])))},J=(X,Q)=>{return new y7({aggregateFunctionNode:GG.create(X,Q?JV(Q):void 0)})};return Object.assign($,{agg:J,avg(X){return J("avg",[X])},coalesce(...X){return $("coalesce",X)},count(X){return J("count",[X])},countAll(X){return new y7({aggregateFunctionNode:GG.create("count",DJ(X))})},max(X){return J("max",[X])},min(X){return J("min",[X])},sum(X){return J("sum",[X])},any(X){return $("any",[X])},jsonAgg(X){return new y7({aggregateFunctionNode:GG.create("json_agg",[C1(X)?e4(X):X.toOperationNode()])})},toJson(X){return new O6(j0$.create("to_json",[C1(X)?e4(X):X.toOperationNode()]))}})}var Iy=D(()=>{RD();Cy();V0$();OJ();fU();K0$();G$();IJ()});var YM$;var U0$=D(()=>{G$();YM$=P({is($){return $.kind==="UnaryOperationNode"},create($,J){return P({kind:"UnaryOperationNode",operator:$,operand:J})}})});function WM$($,J){if(j_$($))return YM$.create(HJ.create($),P9(J));throw Error(`invalid unary operator ${JSON.stringify($)}`)}var GM$=D(()=>{ej();U0$();OJ()});var kJ;var wM=D(()=>{G$();GL();kJ=P({is($){return $.kind==="CaseNode"},create($){return P({kind:"CaseNode",value:$})},cloneWithWhen($,J){return P({...$,when:P($.when?[...$.when,J]:[J])})},cloneWithThen($,J){return P({...$,when:$.when?P([...$.when.slice(0,-1),x7.cloneWithResult($.when[$.when.length-1],J)]):void 0})},cloneWith($,J){return P({...$,...J})}})});class AM{#$;constructor($){this.#$=P($)}when(...$){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(d6($)))})}whenRef($,J,X){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(O9($,J,X)))})}}class NM{#$;constructor($){this.#$=P($)}then($){return new z0$({...this.#$,node:kJ.cloneWithThen(this.#$.node,Gy($)?YM($):b6($))})}thenRef($){return new z0$({...this.#$,node:kJ.cloneWithThen(this.#$.node,P9($))})}}class z0${#$;constructor($){this.#$=P($)}when(...$){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(d6($)))})}whenRef($,J,X){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(O9($,J,X)))})}else($){return new L0$({...this.#$,node:kJ.cloneWith(this.#$.node,{else:Gy($)?YM($):b6($)})})}elseRef($){return new L0$({...this.#$,node:kJ.cloneWith(this.#$.node,{else:P9($)})})}end(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!0}))}}class L0${#$;constructor($){this.#$=P($)}end(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!0}))}}var ky=D(()=>{RD();G$();OJ();wM();GL();IX();$G()});var H0$;var O0$=D(()=>{G$();H0$=P({is($){return $.kind==="JSONPathLegNode"},create($,J){return P({kind:"JSONPathLegNode",type:$,value:J})}})});class MM{#$;constructor($){this.#$=$}at($){if(typeof $!=="number"&&typeof $!=="string"||typeof $==="number"&&!Number.isInteger($)||typeof $==="string"&&$!=="last"&&!MD0.test($))throw Error(`Unexpected index value in .at(...): ${$}`);return this.#J("ArrayLocation",$)}key($){return this.#J("Member",$)}#J($,J){if(ZD.is(this.#$))return new _M(ZD.cloneWithTraversal(this.#$,bU.is(this.#$.traversal)?bU.cloneWithLeg(this.#$.traversal,H0$.create($,J)):Yy.cloneWithValue(this.#$.traversal,n6.createImmediate(J))));return new _M(bU.cloneWithLeg(this.#$,H0$.create($,J)))}}class ZM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}var MD0,_M;var B0$=D(()=>{AY();k6();Wy();O0$();XM();Qy();i5();CX();MD0=/^#-\d+$/;_M=class _M extends MM{#$;constructor($){super($);this.#$=$}get expressionType(){return}as($){return new ZM$(this,$)}$castTo(){return new _M(this.#$)}$notNull(){return new _M(this.#$)}toOperationNode(){return this.#$}}});var D0$;var F0$=D(()=>{G$();D0$=P({is($){return $.kind==="TupleNode"},create($){return P({kind:"TupleNode",values:P($)})}})});function VM$($){return RD0[$]||ED0.some((J)=>J.test($))}var RD0,ED0,jM$;var q0$=D(()=>{G$();RD0=P({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),ED0=P([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),jM$=P({is($){return $.kind==="DataTypeNode"},create($){return P({kind:"DataTypeNode",dataType:$})}})});function kY($){if(x6($))return $.toOperationNode();if(VM$($))return jM$.create($);throw Error(`invalid column data type ${JSON.stringify($)}`)}var RM=D(()=>{q0$();i5()});var KM$;var w0$=D(()=>{G$();KM$=P({is($){return $.kind==="CastNode"},create($,J){return P({kind:"CastNode",expression:$,dataType:J})}})});function W0$($=mU){function J(Y,W,G){return new O6(Zy(Y,W,G))}function X(Y,W){return new O6(WM$(Y,W))}let Q=Object.assign(J,{fn:void 0,eb:void 0,selectFrom(Y){return qM({queryId:M1(),executor:$,queryNode:H6.createFrom(CY(Y))})},case(Y){return new AM({node:kJ.create(d5(Y)?void 0:P9(Y))})},ref(Y,W){if(d5(W))return new O6(k7(Y));return new MM(z_$(Y,W))},jsonPath(){return new MM(bU.create())},table(Y){return new O6(e4(Y))},val(Y){return new O6(b6(Y))},refTuple(...Y){return new O6(D0$.create(Y.map(P9)))},tuple(...Y){return new O6(D0$.create(Y.map(b6)))},lit(Y){return new O6(YM(Y))},unary:X,not(Y){return X("not",Y)},exists(Y){return X("exists",Y)},neg(Y){return X("-",Y)},between(Y,W,G){return new O6(sW.create(P9(Y),HJ.create("between"),I7.create(b6(W),b6(G))))},betweenSymmetric(Y,W,G){return new O6(sW.create(P9(Y),HJ.create("between symmetric"),I7.create(b6(W),b6(G))))},and(Y){if(KJ(Y))return new O6(UD(Y,"and"));return new O6(H$$(Y,"and"))},or(Y){if(KJ(Y))return new O6(UD(Y,"or"));return new O6(H$$(Y,"or"))},parens(...Y){let W=d6(Y);if(SX.is(W))return new O6(W);else return new O6(SX.create(W))},cast(Y,W){return new O6(KM$.create(P9(Y),kY(W)))}});return Q.fn=Sy(),Q.eb=Q,Q}function EY($){return W0$()}var jL=D(()=>{_y();ZL();IJ();SY();Iy();OJ();IX();KD();RD();ej();GM$();$G();MD();ky();wM();G$();B0$();e_();kU();F0$();XM();RM();w0$()});function BJ($){if(x6($))return $.toOperationNode();else if(a4($))return $(EY()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify($)}`)}function zy($){if(x6($))return $.toOperationNode();else if(a4($))return $(EY()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify($)}`)}function $V($){return ab($)||eA$($)||a4($)}var EQ=D(()=>{sb();i5();jL();G$()});class N0${#$;get table(){return this.#$}constructor($){this.#$=$}as($){return new UM$(this.#$,$)}}class UM${#$;#J;get table(){return this.#$}get alias(){return this.#J}constructor($,J){this.#$=$,this.#J=J}toOperationNode(){return LJ.create(e4(this.#$),U1.create(this.#J))}}function zM$($){return L6($)&&x6($)&&C1($.table)&&C1($.alias)}var xy=D(()=>{AY();k6();i5();IJ();G$()});function CY($){if(KJ($))return $.map((J)=>UL(J));else return[UL($)]}function UL($){if(C1($))return X0$($);else if(zM$($))return $.toOperationNode();else return zy($)}function X0$($){if($.includes(" as ")){let[X,Q]=$.split(" as ").map(LM$);return LJ.create(e4(X),U1.create(Q))}else return e4($)}function e4($){if($.includes(".")){let[X,Q]=$.split(".").map(LM$);return S7.createWithSchema(X,Q)}else return S7.create($)}function LM$($){return $.trim()}var IJ=D(()=>{G$();AY();XD();EQ();k6();xy()});var A0$;var _0$=D(()=>{G$();A0$=P({is($){return $.kind==="AddColumnNode"},create($){return P({kind:"AddColumnNode",column:$})}})});var Q8;var EM=D(()=>{G$();U5();Q8=P({is($){return $.kind==="ColumnDefinitionNode"},create($,J){return P({kind:"ColumnDefinitionNode",column:T4.create($),dataType:J})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):[J]})},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):[J]})},cloneWith($,J){return P({...$,...J})}})});var PM;var by=D(()=>{G$();U5();PM=P({is($){return $.kind==="DropColumnNode"},create($){return P({kind:"DropColumnNode",column:T4.create($)})},cloneWith($,J){return P({...$,...J})}})});var M0$;var R0$=D(()=>{G$();U5();M0$=P({is($){return $.kind==="RenameColumnNode"},create($,J){return P({kind:"RenameColumnNode",column:T4.create($),renameTo:T4.create(J)})}})});var ED;var TM=D(()=>{G$();k6();ED=P({is($){return $.kind==="CheckConstraintNode"},create($,J){return P({kind:"CheckConstraintNode",expression:$,name:J?U1.create(J):void 0})}})});function OM$($){return C1($)&&HM$[$]}var HM$,Ic1,PD;var CM=D(()=>{G$();HM$=P({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),Ic1=Object.keys(HM$),PD=P({is($){return $.kind==="ReferencesNode"},create($,J){return P({kind:"ReferencesNode",table:$,columns:P([...J])})},cloneWithOnDelete($,J){return P({...$,onDelete:J})},cloneWithOnUpdate($,J){return P({...$,onUpdate:J})}})});function yy($){return x6($)?$.toOperationNode():n6.createImmediate($)}var E0$=D(()=>{i5();CX()});var SM;var P0$=D(()=>{G$();SM=P({is($){return $.kind==="GeneratedNode"},create($){return P({kind:"GeneratedNode",...$})},createWithExpression($){return P({kind:"GeneratedNode",always:!0,expression:$})},cloneWith($,J){return P({...$,...J})}})});var BM$;var T0$=D(()=>{G$();BM$=P({is($){return $.kind==="DefaultValueNode"},create($){return P({kind:"DefaultValueNode",defaultValue:$})}})});function TD($){if(OM$($))return $;throw Error(`invalid OnModifyForeignAction ${$}`)}var C0$=D(()=>{CM()});class Y8{#$;constructor($){this.#$=$}autoIncrement(){return new Y8(Q8.cloneWith(this.#$,{autoIncrement:!0}))}identity(){return new Y8(Q8.cloneWith(this.#$,{identity:!0}))}primaryKey(){return new Y8(Q8.cloneWith(this.#$,{primaryKey:!0}))}references($){let J=k7($);if(!J.table||YD.is(J.column))throw Error(`invalid call references('${$}'). The reference must have format table.column or schema.table.column`);return new Y8(Q8.cloneWith(this.#$,{references:PD.create(J.table,[J.column])}))}onDelete($){if(!this.#$.references)throw Error("on delete constraint can only be added for foreign keys");return new Y8(Q8.cloneWith(this.#$,{references:PD.cloneWithOnDelete(this.#$.references,TD($))}))}onUpdate($){if(!this.#$.references)throw Error("on update constraint can only be added for foreign keys");return new Y8(Q8.cloneWith(this.#$,{references:PD.cloneWithOnUpdate(this.#$.references,TD($))}))}unique(){return new Y8(Q8.cloneWith(this.#$,{unique:!0}))}notNull(){return new Y8(Q8.cloneWith(this.#$,{notNull:!0}))}unsigned(){return new Y8(Q8.cloneWith(this.#$,{unsigned:!0}))}defaultTo($){return new Y8(Q8.cloneWith(this.#$,{defaultTo:BM$.create(yy($))}))}check($){return new Y8(Q8.cloneWith(this.#$,{check:ED.create($.toOperationNode())}))}generatedAlwaysAs($){return new Y8(Q8.cloneWith(this.#$,{generated:SM.createWithExpression($.toOperationNode())}))}generatedAlwaysAsIdentity(){return new Y8(Q8.cloneWith(this.#$,{generated:SM.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new Y8(Q8.cloneWith(this.#$,{generated:SM.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#$.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new Y8(Q8.cloneWith(this.#$,{generated:SM.cloneWith(this.#$.generated,{stored:!0})}))}modifyFront($){return new Y8(Q8.cloneWithFrontModifier(this.#$,$.toOperationNode()))}nullsNotDistinct(){return new Y8(Q8.cloneWith(this.#$,{nullsNotDistinct:!0}))}ifNotExists(){return new Y8(Q8.cloneWith(this.#$,{ifNotExists:!0}))}modifyEnd($){return new Y8(Q8.cloneWithEndModifier(this.#$,$.toOperationNode()))}$call($){return $(this)}toOperationNode(){return this.#$}}var fy=D(()=>{TM();CM();$M();OJ();EM();E0$();P0$();T0$();C0$()});var S0$;var I0$=D(()=>{G$();S0$=P({is($){return $.kind==="ModifyColumnNode"},create($){return P({kind:"ModifyColumnNode",column:$})}})});var xY;var IM=D(()=>{G$();k6();CM();xY=P({is($){return $.kind==="ForeignKeyConstraintNode"},create($,J,X,Q){return P({kind:"ForeignKeyConstraintNode",columns:$,references:PD.create(J,X),name:Q?U1.create(Q):void 0})},cloneWith($,J){return P({...$,...J})}})});class bY{#$;constructor($){this.#$=$}onDelete($){return new bY(xY.cloneWith(this.#$,{onDelete:TD($)}))}onUpdate($){return new bY(xY.cloneWith(this.#$,{onUpdate:TD($)}))}deferrable(){return new bY(xY.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new bY(xY.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new bY(xY.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new bY(xY.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var vy=D(()=>{IM();C0$()});var CD;var hy=D(()=>{G$();CD=P({is($){return $.kind==="AddConstraintNode"},create($){return P({kind:"AddConstraintNode",constraint:$})}})});var ZG;var kM=D(()=>{j$$();G$();U5();k6();ZG=P({is($){return $.kind==="UniqueConstraintNode"},create($,J,X){if(C1($.at(0)))GD("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),$=$.map(T4.create);return P({kind:"UniqueConstraintNode",columns:P($),name:J?U1.create(J):void 0,nullsNotDistinct:X})},cloneWith($,J){return P({...$,...J})}})});var SD;var gy=D(()=>{G$();k6();SD=P({is($){return $.kind==="DropConstraintNode"},create($){return P({kind:"DropConstraintNode",constraintName:U1.create($)})},cloneWith($,J){return P({...$,...J})}})});var ID;var k0$=D(()=>{G$();U5();ID=P({is($){return $.kind==="AlterColumnNode"},create($,J,X){return P({kind:"AlterColumnNode",column:T4.create($),[J]:X})}})});class uy{#$;constructor($){this.#$=$}setDataType($){return new kD(ID.create(this.#$,"dataType",kY($)))}setDefault($){return new kD(ID.create(this.#$,"setDefault",yy($)))}dropDefault(){return new kD(ID.create(this.#$,"dropDefault",!0))}setNotNull(){return new kD(ID.create(this.#$,"setNotNull",!0))}dropNotNull(){return new kD(ID.create(this.#$,"dropNotNull",!0))}$call($){return $(this)}}class kD{#$;constructor($){this.#$=$}toOperationNode(){return this.#$}}var x0$=D(()=>{k0$();RM();E0$()});class lU{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var DM$=D(()=>{G$()});class WV{#$;constructor($){this.#$=P($)}onDelete($){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.onDelete($)})}onUpdate($){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.onUpdate($)})}deferrable(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.deferrable()})}notDeferrable(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.initiallyImmediate()})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(this.#$.constraintBuilder.toOperationNode())}),this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var FM$=D(()=>{hy();$L();G$()});class LL{#$;constructor($){this.#$=P($)}ifExists(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{ifExists:!0})})})}cascade(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{modifier:"restrict"})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var qM$=D(()=>{$L();gy();G$()});var GV;var xM=D(()=>{G$();U5();k6();GV=P({is($){return $.kind==="PrimaryKeyConstraintNode"},create($,J){return P({kind:"PrimaryKeyConstraintNode",columns:P($.map(T4.create)),name:J?U1.create(J):void 0})},cloneWith($,J){return P({...$,...J})}})});var yX;var xD=D(()=>{G$();k6();yX=P({is($){return $.kind==="AddIndexNode"},create($){return P({kind:"AddIndexNode",name:U1.create($)})},cloneWith($,J){return P({...$,...J})},cloneWithColumns($,J){return P({...$,columns:[...$.columns||[],...J]})}})});class pU{#$;constructor($){this.#$=P($)}unique(){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWith(this.#$.node.addIndex,{unique:!0})})})}column($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,[C1($)?jD($):$.toOperationNode()])})})}columns($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,$.map((J)=>C1(J)?jD(J):J.toOperationNode()))})})}expression($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,[$.toOperationNode()])})})}using($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWith(this.#$.node.addIndex,{using:v4.createWithSql($)})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var wM$=D(()=>{xD();$L();PX();OJ();G$()});class jG{#$;constructor($){this.#$=$}nullsNotDistinct(){return new jG(ZG.cloneWith(this.#$,{nullsNotDistinct:!0}))}deferrable(){return new jG(ZG.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new jG(ZG.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new jG(ZG.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new jG(ZG.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var b0$=D(()=>{kM()});class ZV{#$;constructor($){this.#$=$}deferrable(){return new ZV(GV.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new ZV(GV.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new ZV(GV.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new ZV(GV.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var y0$=D(()=>{xM()});class bM{#$;constructor($){this.#$=$}$call($){return $(this)}toOperationNode(){return this.#$}}var NM$;var f0$=D(()=>{G$();k6();NM$=P({is($){return $.kind==="RenameConstraintNode"},create($,J){return P({kind:"RenameConstraintNode",oldName:U1.create($),newName:U1.create(J)})}})});class yM{#$;constructor($){this.#$=P({...$})}ifExists(){return new yM({...this.#$,node:PM.cloneWith(this.#$.node,{ifExists:!0})})}toOperationNode(){return this.#$.node}}var v0$=D(()=>{by();G$()});class h0${#$;constructor($){this.#$=P($)}renameTo($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{renameTo:e4($)})})}setSchema($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{setSchema:U1.create($)})})}alterColumn($,J){let X=J(new uy($));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}dropColumn($,J=UJ){let X=J(new yM({node:PM.create($)}));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}renameColumn($,J){return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,M0$.create($,J))})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,A0$.create(Q.toOperationNode()))})}modifyColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,S0$.create(Q.toOperationNode()))})}addUniqueConstraint($,J,X=UJ){let Q=X(new jG(ZG.create(J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)),$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}addCheckConstraint($,J,X=UJ){let Q=X(new bM(ED.create(J.toOperationNode(),$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}addForeignKeyConstraint($,J,X,Q,Y=UJ){let W=Y(new bY(xY.create(J.map(T4.create),e4(X),Q.map(T4.create),$)));return new WV({...this.#$,constraintBuilder:W})}addPrimaryKeyConstraint($,J,X=UJ){let Q=X(new ZV(GV.create(J,$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}dropConstraint($){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.create($)})})}renameConstraint($,J){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{renameConstraint:NM$.create($,J)})})}addIndex($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.create($)})})}dropIndex($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropIndex:IU.create($)})})}$call($){return $(this)}}class yY{#$;constructor($){this.#$=P($)}alterColumn($,J){let X=J(new uy($));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}dropColumn($,J=UJ){let X=J(new yM({node:PM.create($)}));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}renameColumn($,J){return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,M0$.create($,J))})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,A0$.create(Q.toOperationNode()))})}modifyColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,S0$.create(Q.toOperationNode()))})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var g0$=D(()=>{_0$();$L();EM();by();k6();R0$();G$();fy();I0$();RM();vy();hy();kM();TM();IM();U5();IJ();gy();x0$();DM$();FM$();qM$();xM();a_();xD();wM$();b0$();y0$();f0$();EQ();v0$()});var fM;var u0$=D(()=>{hU();QL();CX();fM=class fM extends xX{transformPrimitiveValueList($){return eW.create($.values.map(n6.createImmediate))}transformValue($){return n6.createImmediate($.value)}}});class TQ{#$;constructor($){this.#$=P($)}ifNotExists(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{ifNotExists:!0})})}unique(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{unique:!0})})}nullsNotDistinct(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{nullsNotDistinct:!0})})}on($){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{table:e4($)})})}column($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,[C1($)?jD($):$.toOperationNode()])})}columns($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,$.map((J)=>C1(J)?jD(J):J.toOperationNode()))})}expression($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,[$.toOperationNode()])})}using($){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{using:v4.createWithSql($)})})}where(...$){let J=new fM;return new TQ({...this.#$,node:F0.cloneWithWhere(this.#$.node,J.transformNode(d6($),this.#$.queryId))})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var m0$=D(()=>{db();PX();OJ();IJ();G$();IX();PQ();u0$()});class my{#$;constructor($){this.#$=P($)}ifNotExists(){return new my({...this.#$,node:ib.cloneWith(this.#$.node,{ifNotExists:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var l0$=D(()=>{ob();G$()});function AM$($){if(sA$.includes($))return $;throw Error(`invalid OnCommitAction ${$}`)}var _M$=D(()=>{$D()});class ly{#$;constructor($){this.#$=$}using($){return new ly(yX.cloneWith(this.#$,{using:v4.createWithSql($)}))}$call($){return $(this)}toOperationNode(){return this.#$}}var MM$=D(()=>{xD();PX()});class r5{#$;constructor($){this.#$=P($)}temporary(){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{temporary:!0})})}onCommit($){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{onCommit:AM$($)})})}ifNotExists(){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{ifNotExists:!0})})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new r5({...this.#$,node:zJ.cloneWithColumn(this.#$.node,Q.toOperationNode())})}addPrimaryKeyConstraint($,J,X=UJ){let Q=X(new ZV(GV.create(J,$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addUniqueConstraint($,J,X=UJ){let Q=X(new jG(ZG.create(J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addIndex($,J,X=UJ){let Q=X(new ly(yX.cloneWithColumns(yX.create($),J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)))));return new r5({...this.#$,node:zJ.cloneWithIndex(this.#$.node,Q.toOperationNode())})}addCheckConstraint($,J,X=UJ){let Q=X(new bM(ED.create(J.toOperationNode(),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addForeignKeyConstraint($,J,X,Q,Y=UJ){let W=Y(new bY(xY.create(J.map(T4.create),e4(X),Q.map(T4.create),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,W.toOperationNode())})}modifyFront($){return new r5({...this.#$,node:zJ.cloneWithFrontModifier(this.#$.node,$.toOperationNode())})}modifyEnd($){return new r5({...this.#$,node:zJ.cloneWithEndModifier(this.#$.node,$.toOperationNode())})}as($){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{selectQuery:BJ($)})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var p0$=D(()=>{EM();$D();fy();G$();IM();U5();vy();RM();xM();kM();TM();IJ();_M$();b0$();EQ();y0$();xD();MM$()});class bD{#$;constructor($){this.#$=P($)}on($){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{table:e4($)})})}ifExists(){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var c0$=D(()=>{a_();IJ();G$()});class vM{#$;constructor($){this.#$=P($)}ifExists(){return new vM({...this.#$,node:s_.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new vM({...this.#$,node:s_.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var n0$=D(()=>{rb();G$()});class yD{#$;constructor($){this.#$=P($)}temporary(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{temporary:!0})})}ifExists(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var d0$=D(()=>{tb();G$()});var fY;var hM=D(()=>{G$();sj();fY=P({is($){return $.kind==="CreateViewNode"},create($){return P({kind:"CreateViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class i0${#$=new fM;transformQuery($){return this.#$.transformNode($.node,$.queryId)}transformResult($){return Promise.resolve($.result)}}var RM$=D(()=>{u0$()});class jV{#$;constructor($){this.#$=P($)}temporary(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{temporary:!0})})}materialized(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{materialized:!0})})}ifNotExists(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{ifNotExists:!0})})}orReplace(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{orReplace:!0})})}columns($){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{columns:$.map(U$$)})})}as($){let J=$.withPlugin(new i0$).toOperationNode();return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{as:J})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var o0$=D(()=>{G$();hM();OJ();RM$()});var fD;var py=D(()=>{G$();sj();fD=P({is($){return $.kind==="DropViewNode"},create($){return P({kind:"DropViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class vD{#$;constructor($){this.#$=P($)}materialized(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{materialized:!0})})}ifExists(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var r0$=D(()=>{G$();py()});var cy;var ny=D(()=>{G$();QL();CX();cy=P({is($){return $.kind==="CreateTypeNode"},create($){return P({kind:"CreateTypeNode",name:$})},cloneWithEnum($,J){return P({...$,enum:eW.create(J.map(n6.createImmediate))})}})});class dy{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}asEnum($){return new dy({...this.#$,node:cy.cloneWithEnum(this.#$.node,$)})}$call($){return $(this)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var t0$=D(()=>{G$();ny()});var gM;var iy=D(()=>{G$();gM=P({is($){return $.kind==="DropTypeNode"},create($){if(!Array.isArray($))$=[$];return P({kind:"DropTypeNode",name:$[0],additionalNames:$.slice(1)})},cloneWith($,J){return P({...$,...J})}})});class uM{#$;constructor($){this.#$=P($)}ifExists(){return new uM({...this.#$,node:gM.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new uM({...this.#$,node:gM.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var a0$=D(()=>{iy();G$()});function oy($){if($.includes(".")){let X=$.split(".").map(PD0);if(X.length===2)return K5.createWithSchema(X[0],X[1]);else throw Error(`invalid schemable identifier ${$}`)}else return K5.create($)}function EM$($){if(!Array.isArray($))$=[$];return $.map(oy)}function PD0($){return $.trim()}var PM$=D(()=>{sj()});var hD;var ry=D(()=>{G$();sj();hD=P({is($){return $.kind==="RefreshMaterializedViewNode"},create($){return P({kind:"RefreshMaterializedViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class gD{#$;constructor($){this.#$=P($)}concurrently(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{concurrently:!0,withNoData:!1})})}withData(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{withNoData:!1})})}withNoData(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{withNoData:!0,concurrently:!1})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var s0$=D(()=>{G$();ry()});var VG;var mM=D(()=>{G$();VG=P({is($){return $.kind==="AlterTypeNode"},create($){return P({kind:"AlterTypeNode",name:$})},cloneWith($,J){return P({...$,...J})}})});var lM;var ty=D(()=>{G$();lM=P({is($){return $.kind==="AddValueNode"},create($){return P({kind:"AddValueNode",value:$})},cloneWith($,J){return P({...$,...J})}})});class HL{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){return await this.#$.executor.executeQuery(this.compile(),$)}}var ay=D(()=>{G$()});var e0$,sy;var TM$=D(()=>{ty();CX();mM();ay();sy=class sy extends HL{#$;constructor($){super($);this.#$=$}ifNotExists(){return new e0$({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.cloneWith(this.#$.node.addValue,{ifNotExists:!0})})})}before($){return this.#J($,!0)}after($){return this.#J($,!1)}#J($,J){return new e0$({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.cloneWith(this.#$.node.addValue,{isBefore:J,neighborValue:n6.createImmediate($)})})})}};e0$=sy});var CM$;var $1$=D(()=>{G$();CM$=P({is($){return $.kind==="RenameValueNode"},create($,J){return P({kind:"RenameValueNode",oldValue:$,newValue:J})}})});class J1${#$;constructor($){this.#$=P($)}addValue($){return new sy({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.create(n6.createImmediate($))})})}renameTo($){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{renameTo:U1.create($)})})}renameValue($,J){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{renameValue:CM$.create(n6.createImmediate($),n6.createImmediate(J))})})}setSchema($){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{setSchema:U1.create($)})})}}var SM$=D(()=>{G$();mM();k6();TM$();ty();CX();ay();$1$()});class uD{#$;constructor($){this.#$=$}createTable($){return new r5({queryId:M1(),executor:this.#$,node:zJ.create(e4($))})}dropTable($){return new yD({queryId:M1(),executor:this.#$,node:JD.create(e4($))})}createIndex($){return new TQ({queryId:M1(),executor:this.#$,node:NY.create($)})}dropIndex($){return new bD({queryId:M1(),executor:this.#$,node:IU.create($)})}createSchema($){return new my({queryId:M1(),executor:this.#$,node:ib.create($)})}dropSchema($){return new vM({queryId:M1(),executor:this.#$,node:s_.create($)})}alterTable($){return new h0$({queryId:M1(),executor:this.#$,node:s4.create(e4($))})}createView($){return new jV({queryId:M1(),executor:this.#$,node:fY.create($)})}refreshMaterializedView($){return new gD({queryId:M1(),executor:this.#$,node:hD.create($)})}dropView($){return new vD({queryId:M1(),executor:this.#$,node:fD.create($)})}createType($){return new dy({queryId:M1(),executor:this.#$,node:cy.create(oy($))})}alterType($){return new J1$({executor:this.#$,node:VG.create(oy($)),queryId:M1()})}dropType($){return new uM({queryId:M1(),executor:this.#$,node:gM.create(EM$($))})}withPlugin($){return new uD(this.#$.withPlugin($))}withoutPlugins(){return new uD(this.#$.withoutPlugins())}withSchema($){return new uD(this.#$.withPluginAtFront(new IY($)))}}var X1$=D(()=>{$L();db();ob();$D();a_();rb();tb();IJ();g0$();m0$();l0$();p0$();c0$();n0$();d0$();SY();wD();o0$();hM();r0$();py();t0$();a0$();ny();iy();PM$();s0$();ry();SM$();mM()});class Q1${ref($){return new Y$$($)}table($){return new N0$($)}}var Y1$=D(()=>{JM();xy()});class W1${#$;constructor($){this.#$=$}async provideConnection($,J){let X=await this.#$.acquireConnection(J);try{return await $(X)}finally{await this.#$.releaseConnection(X,J)}}}var cU;var G1$=D(()=>{s$$();cU=class cU extends FM{#$;#J;#X;constructor($,J,X,Q=[]){super(Q);this.#$=$,this.#J=J,this.#X=X}get adapter(){return this.#J}compileQuery($,J){return this.#$.compileQuery($,J)}provideConnection($,J){return this.#X.provideConnection($,J)}withPlugins($){return new cU(this.#$,this.#J,this.#X,[...this.plugins,...$])}withPlugin($){return new cU(this.#$,this.#J,this.#X,[...this.plugins,$])}withPluginAtFront($){return new cU(this.#$,this.#J,this.#X,[$,...this.plugins])}withConnectionProvider($){return new cU(this.#$,this.#J,$,[...this.plugins])}withoutPlugins(){return new cU(this.#$,this.#J,this.#X,[])}}});function ey(){if(typeof performance<"u"&&a4(performance.now))return performance.now();else return Date.now()}var IM$=D(()=>{G$()});class Z1${#$;#J;async obtainLock(){while(this.#$)await this.#$;this.#$=new Promise(($)=>{this.#J=$})}releaseLock(){let $=this.#J;this.#$=void 0,this.#J=void 0,$?.()}}class j1${#$;#J;#X;#Q;#Y;#G=new WeakSet;#W;constructor($,J,X){if(this.#$=$,this.#Q=!1,this.#J=X,J.supportsMultipleConnections===!1)this.#W=new Z1$}async init($){if(this.#Y)throw Error("driver has already been destroyed");this.#X??=this.#$.init($).then(()=>{this.#Q=!0}).catch((J)=>{throw this.#X=void 0,J}),await uU(this.#X,$?.signal,"init")}async acquireConnection($){if(this.#Y)throw Error("driver has already been destroyed");if(!this.#Q)await this.init($);if(this.#W){let Q=this.#W.obtainLock();await uU(Q,$?.signal,"acquireConnection:mutex",()=>Q.then(()=>this.#W?.releaseLock()))}let J=this.#$.acquireConnection($),X=await uU(J,$?.signal,"acquireConnection:acquire",()=>J?.then((Q)=>this.releaseConnection(Q).catch(YG("driver.releaseConnection"))).catch(YG("driver.acquireConnection")));if(!this.#G.has(X)){if(this.#Z())this.#j(X);this.#G.add(X)}return X}async releaseConnection($,J){await this.#$.releaseConnection($,J),this.#W?.releaseLock()}async beginTransaction($,J){return await this.#$.beginTransaction($,J)}async commitTransaction($){return await this.#$.commitTransaction($)}async rollbackTransaction($){return await this.#$.rollbackTransaction($)}async savepoint($,J,X){if(this.#$.savepoint)return await this.#$.savepoint($,J,X);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint($,J,X){if(this.#$.rollbackToSavepoint)return await this.#$.rollbackToSavepoint($,J,X);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint($,J,X){if(this.#$.releaseSavepoint)return await this.#$.releaseSavepoint($,J,X);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy($){if(!this.#X)return;await uU(this.#X,$?.signal,"destroy:initPromise"),this.#Y??=this.#$.destroy($).catch((J)=>{throw this.#Y=void 0,J}),await uU(this.#Y,$?.signal,"destroy")}#Z(){return this.#J.isLevelEnabled("query")||this.#J.isLevelEnabled("error")}#j($){let{executeQuery:J,streamQuery:X}=$,Q=this;$.executeQuery=async(Y,W)=>{let G,Z=ey();try{return await J.call($,Y,W)}catch(j){throw G=j,await Q.#V(j,Y,Z),j}finally{if(!G)await Q.#U(Y,Z)}},$.streamQuery=async function*(Y,W,G){let Z,j=ey();try{for await(let V of X.call($,Y,W,G))yield V}catch(V){throw Z=V,await Q.#V(V,Y,j),V}finally{if(!Z)await Q.#U(Y,j,!0)}}}async#V($,J,X){await this.#J.error(()=>({level:"error",error:$,query:J,queryDurationMillis:this.#z(X)}))}async#U($,J,X=!1){await this.#J.query(()=>({level:"query",isStream:X,query:$,queryDurationMillis:this.#z(J)}))}#z($){return ey()-$}}var kM$=D(()=>{Ny();IM$()});class pM{#$;#J;constructor($){this.#$=$}async provideConnection($){while(this.#J)await this.#J.catch(TD0);return this.#J=this.#X($).finally(()=>{this.#J=void 0}),this.#J}async#X($){return await $(this.#$)}}var TD0=()=>{};function V1$($){if($.accessMode&&!CD0.includes($.accessMode))throw Error(`invalid transaction access mode ${$.accessMode}`);if($.isolationLevel&&!SD0.includes($.isolationLevel))throw Error(`invalid transaction isolation level ${$.isolationLevel}`)}var CD0,SD0;var K1$=D(()=>{CD0=["read only","read write"],SD0=["read uncommitted","read committed","repeatable read","serializable","snapshot"]});class U1${#$;#J;constructor($){if(a4($))this.#J=$,this.#$=P({query:!0,error:!0});else this.#J=kD0,this.#$=P({query:$.includes("query"),error:$.includes("error")})}isLevelEnabled($){return this.#$[$]}async query($){if(this.#$.query)await this.#J($())}async error($){if(this.#$.error)await this.#J($())}}function kD0($){if($.level==="query"){let J=`kysely:query:${$.isStream?"stream:":""}`;console.log(`${J} ${$.query.sql}`),console.log(`${J} duration: ${$.queryDurationMillis.toFixed(1)}ms`)}else if($.level==="error")if($.error instanceof Error)console.error(`kysely:error: ${$.error.stack??$.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:$.error,query:$.query.sql,queryDurationMillis:$.queryDurationMillis})}`)}var ID0,Ir1;var z1$=D(()=>{G$();ID0=["query","error"],Ir1=P(ID0)});function xM$($){return L6($)&&a4($.compile)}var L1$=D(()=>{G$()});function xD0($){return L6($)&&L6($.config)&&L6($.driver)&&L6($.executor)&&L6($.dialect)}class bM${#$;constructor($){this.#$=P($)}async execute($,J){return this.#$.executor.provideConnection(async(X)=>{let Q=this.#$.executor.withConnectionProvider(new pM(X)),Y=new vY({...this.#$,executor:Q});return await $(Y)},P({signal:J?.signal}))}}class $f{#$;constructor($){this.#$=P($)}setAccessMode($){return new $f({...this.#$,accessMode:$})}setIsolationLevel($){return new $f({...this.#$,isolationLevel:$})}async execute($){let{isolationLevel:J,accessMode:X,...Q}=this.#$,Y={isolationLevel:J,accessMode:X};return V1$(Y),this.#$.executor.provideConnection(async(W)=>{let G={isCommitted:!1,isRolledBack:!1},Z=new VV(this.#$.executor.withConnectionProvider(new pM(W)),G),j=new KG({...Q,executor:Z}),V=!1;try{await this.#$.driver.beginTransaction(W,Y),V=!0;let K=await $(j);return await this.#$.driver.commitTransaction(W),G.isCommitted=!0,K}catch(K){if(V)await this.#$.driver.rollbackTransaction(W),G.isRolledBack=!0;throw K}})}}class Jf{#$;constructor($){this.#$=P($)}setAccessMode($){return new Jf({...this.#$,accessMode:$})}setIsolationLevel($){return new Jf({...this.#$,isolationLevel:$})}async execute(){let{isolationLevel:$,accessMode:J,...X}=this.#$,Q={isolationLevel:$,accessMode:J};V1$(Q);let Y=await AD(this.#$.executor);return await this.#$.driver.beginTransaction(Y.connection,Q),new CQ({...X,connection:Y,executor:this.#$.executor.withConnectionProvider(new pM(Y.connection))})}}class mD{#$;constructor($){this.#$=$}async execute(){return await this.#$()}}function OL($){if($.isCommitted)throw Error("Transaction is already committed");if($.isRolledBack)throw Error("Transaction is already rolled back")}class VV{#$;#J;constructor($,J){this.#$=$ instanceof VV?$.#$:$,this.#J=J}get adapter(){return this.#$.adapter}get plugins(){return this.#$.plugins}transformQuery($,J){return this.#$.transformQuery($,J)}compileQuery($,J){return this.#$.compileQuery($,J)}provideConnection($,J){return this.#$.provideConnection($,J)}executeQuery($,J){return OL(this.#J),this.#$.executeQuery($,J)}stream($,J,X){return OL(this.#J),this.#$.stream($,J,X)}withConnectionProvider($){return new VV(this.#$.withConnectionProvider($),this.#J)}withPlugin($){return new VV(this.#$.withPlugin($),this.#J)}withPlugins($){return new VV(this.#$.withPlugins($),this.#J)}withPluginAtFront($){return new VV(this.#$.withPluginAtFront($),this.#J)}withoutPlugins(){return new VV(this.#$.withoutPlugins(),this.#J)}}var vY,KG,CQ;var yM$=D(()=>{X1$();Y1$();Ay();G1$();G$();kM$();K1$();Iy();z1$();SY();L1$();ky();wM();EQ();wD();a$$();Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");vY=class vY extends WG{#$;constructor($){let J,X;if(xD0($))J={executor:$.executor},X={...$};else{let Q=$.dialect,Y=Q.createDriver(),W=Q.createQueryCompiler(),G=Q.createAdapter(),Z=new U1$($.log??[]),j=new j1$(Y,G,Z),V=new W1$(j),K=new cU(W,G,V,$.plugins??[]);J={executor:K},X={config:$,executor:K,dialect:Q,driver:j}}super(J);this.#$=P(X)}get schema(){return new uD(this.#$.executor)}get dynamic(){return new Q1$}get introspection(){return this.#$.dialect.createIntrospector(this.withoutPlugins())}case($){return new AM({node:kJ.create(d5($)?void 0:BJ($))})}get fn(){return Sy()}transaction(){return new $f({...this.#$})}startTransaction(){return new Jf({...this.#$})}connection(){return new bM$({...this.#$})}withPlugin($){return new vY({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new vY({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new vY({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}$extendTables(){return new vY({...this.#$})}$omitTables(){return new vY({...this.#$})}$pickTables(){return new vY({...this.#$})}withTables(){return this.$extendTables()}async destroy(){await this.#$.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#$.executor}async executeQuery($,J){let X=xM$($)?$.compile():$;return await this.#$.executor.executeQuery(X,J)}async[Symbol.asyncDispose](){await this.destroy()}};KG=class KG extends vY{#$;constructor($){super($);this.#$=$}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin($){return new KG({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new KG({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new KG({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}withTables(){return new KG({...this.#$})}$extendTables(){return new KG({...this.#$})}$omitTables(){return new KG({...this.#$})}$pickTables(){return new KG({...this.#$})}};CQ=class CQ extends KG{#$;#J;#X;constructor($){let J={isCommitted:!1,isRolledBack:!1};$={...$,executor:new VV($.executor,J)};let{connection:X,...Q}=$;super(Q);this.#$=P($),this.#X=J;let Y=M1();this.#J=(W)=>$.executor.compileQuery(W,Y)}get isCommitted(){return this.#X.isCommitted}get isRolledBack(){return this.#X.isRolledBack}commit(){return OL(this.#X),new mD(async()=>{await this.#$.driver.commitTransaction(this.#$.connection.connection),this.#X.isCommitted=!0,this.#$.connection.release()})}rollback(){return OL(this.#X),new mD(async()=>{await this.#$.driver.rollbackTransaction(this.#$.connection.connection),this.#X.isRolledBack=!0,this.#$.connection.release()})}savepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.savepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}rollbackToSavepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.rollbackToSavepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}releaseSavepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.releaseSavepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}withPlugin($){return new CQ({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new CQ({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new CQ({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}withTables(){return new CQ({...this.#$})}$extendTables(){return new CQ({...this.#$})}$omitTables(){return new CQ({...this.#$})}$pickTables(){return new CQ({...this.#$})}}});class cM{#$;constructor($){this.#$=P($)}get expressionType(){return}get isRawBuilder(){return!0}as($){return new fM$(this,$)}$castTo(){return new cM({...this.#$})}$notNull(){return new cM(this.#$)}withPlugin($){return new cM({...this.#$,plugins:this.#$.plugins!==void 0?P([...this.#$.plugins,$]):P([$])})}toOperationNode(){return this.#X(this.#J())}compile($){return this.#Q(this.#J($))}async execute($,J){let X=this.#J($);return X.executeQuery(this.#Q(X),J)}#J($){let J=$!==void 0?$.getExecutor():mU;return this.#$.plugins!==void 0?J.withPlugins(this.#$.plugins):J}#X($){return $.transformQuery(this.#$.rawNode,this.#$.queryId)}#Q($){return $.compileQuery(this.#X($),this.#$.queryId)}}function KV($){return new cM($)}class fM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}get rawBuilder(){return this.#$}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}var H1$=D(()=>{AY();G$();MD();k6();i5()});function vM$($){if(x6($))return $.toOperationNode();return b6($)}var $0;var nU=D(()=>{k6();i5();PX();CX();OJ();IJ();$G();SY();H1$();$0=Object.assign(($,...J)=>{return KV({queryId:M1(),rawNode:v4.create($,J?.map(vM$)??[])})},{ref($){return KV({queryId:M1(),rawNode:v4.createWithChild(k7($))})},val($){return KV({queryId:M1(),rawNode:v4.createWithChild(b6($))})},table($){return KV({queryId:M1(),rawNode:v4.createWithChild(e4($))})},id(...$){let J=Array($.length+1).fill(".");return J[0]="",J[J.length-1]="",KV({queryId:M1(),rawNode:v4.create(J,$.map(U1.create))})},lit($){return KV({queryId:M1(),rawNode:v4.createWithChild(n6.createImmediate($))})},raw($){return KV({queryId:M1(),rawNode:v4.createWithSql($)})},join($,J=$0`, `){let X=Array(Math.max(2*$.length-1,0)),Q=J.toOperationNode();for(let Y=0;Y<$.length;++Y)if(X[2*Y]=vM$($[Y]),Y!==$.length-1)X[2*Y+1]=Q;return KV({queryId:M1(),rawNode:v4.createWithChildren(X)})}})});class O1${nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#$=P({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=($)=>{this.nodeStack.push($),this.#$[$.kind]($),this.nodeStack.pop()}}var B1$=D(()=>{G$()});var bD0,yD0,UV,fD0,hM$,vD0;var BL=D(()=>{$D();WL();B1$();ej();KD();PX();G$();hM();Ry();GL();bD0=/'/g,yD0=/['"]/g;UV=class UV extends O1${#$="";#J=[];get numParameters(){return this.#J.length}compileQuery($,J){return this.#$="",this.#J=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode($),P({query:$,queryId:J,sql:this.getSql(),parameters:[...this.#J]})}getSql(){return this.#$}visitSelectQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!k8.is(this.parentNode)&&!zJ.is(this.parentNode)&&!fY.is(this.parentNode)&&!My.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("select"),$.distinctOn)this.append(" "),this.compileDistinctOn($.distinctOn);if($.frontModifiers?.length)this.append(" "),this.compileList($.frontModifiers," ");if($.top)this.append(" "),this.visitNode($.top);if($.selections)this.append(" "),this.compileList($.selections);if($.from)this.append(" "),this.visitNode($.from);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.groupBy)this.append(" "),this.visitNode($.groupBy);if($.having)this.append(" "),this.visitNode($.having);if($.setOperations)this.append(" "),this.compileList($.setOperations," ");if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if($.offset)this.append(" "),this.visitNode($.offset);if($.fetch)this.append(" "),this.visitNode($.fetch);if($.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers($.endModifiers)," ");if(J)this.append(")")}visitFrom($){this.append("from "),this.compileList($.froms)}visitSelection($){this.visitNode($.selection)}visitColumn($){this.visitNode($.column)}compileDistinctOn($){this.append("distinct on ("),this.compileList($),this.append(")")}compileList($,J=", "){let X=$.length-1;for(let Q=0;Q<=X;Q++)if(this.visitNode($[Q]),Q<X)this.append(J)}visitWhere($){this.append("where "),this.visitNode($.where)}visitHaving($){this.append("having "),this.visitNode($.having)}visitInsertQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode)&&!x7.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append($.replace?"replace":"insert"),$.orAction)this.append(" "),this.visitNode($.orAction);if($.top)this.append(" "),this.visitNode($.top);if($.into)this.append(" into "),this.visitNode($.into);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.output)this.append(" "),this.visitNode($.output);if($.values)this.append(" "),this.visitNode($.values);if($.defaultValues)this.append(" "),this.append("default values");if($.onConflict)this.append(" "),this.visitNode($.onConflict);if($.onDuplicateKey)this.append(" "),this.visitNode($.onDuplicateKey);if($.returning)this.append(" "),this.visitNode($.returning);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitValues($){this.append("values "),this.compileList($.values)}visitDeleteQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("delete "),$.top)this.visitNode($.top),this.append(" ");if(this.visitNode($.from),$.output)this.append(" "),this.visitNode($.output);if($.using)this.append(" "),this.visitNode($.using);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.returning)this.append(" "),this.visitNode($.returning);if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitReturning($){this.append("returning "),this.compileList($.selections)}visitAlias($){this.visitNode($.node),this.append(" as "),this.visitNode($.alias)}visitReference($){if($.table)this.visitNode($.table),this.append(".");this.visitNode($.column)}visitSelectAll($){this.append("*")}visitIdentifier($){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier($),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier($){if(!C1($.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier($.name))}visitAnd($){this.visitNode($.left),this.append(" and "),this.visitNode($.right)}visitOr($){this.visitNode($.left),this.append(" or "),this.visitNode($.right)}visitValue($){if($.immediate)this.appendImmediateValue($.value);else this.appendValue($.value)}visitValueList($){this.append("("),this.compileList($.values),this.append(")")}visitTuple($){this.append("("),this.compileList($.values),this.append(")")}visitPrimitiveValueList($){this.append("(");let{values:J}=$;for(let X=0;X<J.length;++X)if(this.appendValue(J[X]),X!==J.length-1)this.append(", ");this.append(")")}visitParens($){this.append("("),this.visitNode($.node),this.append(")")}visitJoin($){if(this.append(vD0[$.joinType]),this.append(" "),this.visitNode($.table),$.on)this.append(" "),this.visitNode($.on)}visitOn($){this.append("on "),this.visitNode($.on)}visitRaw($){let{sqlFragments:J,parameters:X}=$;for(let Q=0;Q<J.length;++Q)if(this.append(J[Q]),X.length>Q)this.visitNode(X[Q])}visitOperator($){this.append($.operator)}visitTable($){this.visitNode($.table)}visitSchemableIdentifier($){if($.schema)this.visitNode($.schema),this.append(".");this.visitNode($.identifier)}visitCreateTable($){if(this.append("create "),$.frontModifiers?.length)this.compileList($.frontModifiers," "),this.append(" ");if($.temporary)this.append("temporary ");if(this.append("table "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.table),!$.selectQuery)this.append(" ("),this.compileList([...$.columns,...$.constraints??[],...$.indexes??[]]),this.append(")");if($.onCommit)this.append(" on commit "),this.append($.onCommit);if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ");if($.selectQuery)this.append(" as "),this.visitNode($.selectQuery)}visitColumnDefinition($){if($.ifNotExists)this.append("if not exists ");if(this.visitNode($.column),this.append(" "),this.visitNode($.dataType),$.unsigned)this.append(" unsigned");if($.frontModifiers&&$.frontModifiers.length>0)this.append(" "),this.compileList($.frontModifiers," ");if($.generated)this.append(" "),this.visitNode($.generated);if($.identity)this.append(" identity");if($.defaultTo)this.append(" "),this.visitNode($.defaultTo);if($.notNull)this.append(" not null");if($.unique)this.append(" unique");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.primaryKey)this.append(" primary key");if($.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if($.references)this.append(" "),this.visitNode($.references);if($.check)this.append(" "),this.visitNode($.check);if($.endModifiers&&$.endModifiers.length>0)this.append(" "),this.compileList($.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences($){if(this.append("references "),this.visitNode($.table),this.append(" ("),this.compileList($.columns),this.append(")"),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate)}visitDropTable($){if(this.append("drop "),$.temporary)this.append("temporary ");if(this.append("table "),$.ifExists)this.append("if exists ");if(this.visitNode($.table),$.cascade)this.append(" cascade")}visitDataType($){this.append($.dataType)}visitOrderBy($){this.append("order by "),this.compileList($.items)}visitOrderByItem($){if(this.visitNode($.orderBy),$.collation)this.append(" "),this.visitNode($.collation);if($.direction)this.append(" "),this.visitNode($.direction);if($.nulls)this.append(" nulls "),this.append($.nulls)}visitGroupBy($){this.append("group by "),this.compileList($.items)}visitGroupByItem($){this.visitNode($.groupBy)}visitUpdateQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode)&&!x7.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("update "),$.top)this.visitNode($.top),this.append(" ");if($.table)this.visitNode($.table),this.append(" ");if(this.append("set "),$.updates)this.compileList($.updates);if($.output)this.append(" "),this.visitNode($.output);if($.from)this.append(" "),this.visitNode($.from);if($.joins){if(!$.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList($.joins," ")}if($.where)this.append(" "),this.visitNode($.where);if($.returning)this.append(" "),this.visitNode($.returning);if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitColumnUpdate($){this.visitNode($.column),this.append(" = "),this.visitNode($.value)}visitLimit($){this.append("limit "),this.visitNode($.limit)}visitOffset($){this.append("offset "),this.visitNode($.offset)}visitOnConflict($){if(this.append("on conflict"),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");else if($.constraint)this.append(" on constraint "),this.visitNode($.constraint);else if($.indexExpression)this.append(" ("),this.visitNode($.indexExpression),this.append(")");if($.indexWhere)this.append(" "),this.visitNode($.indexWhere);if($.doNothing===!0)this.append(" do nothing");else if($.updates){if(this.append(" do update set "),this.compileList($.updates),$.updateWhere)this.append(" "),this.visitNode($.updateWhere)}}visitOnDuplicateKey($){this.append("on duplicate key update "),this.compileList($.updates)}visitCreateIndex($){if(this.append("create "),$.unique)this.append("unique ");if(this.append("index "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.using)this.append(" using "),this.visitNode($.using);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.where)this.append(" "),this.visitNode($.where)}visitDropIndex($){if(this.append("drop index "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.cascade)this.append(" cascade")}visitCreateSchema($){if(this.append("create schema "),$.ifNotExists)this.append("if not exists ");this.visitNode($.schema)}visitDropSchema($){if(this.append("drop schema "),$.ifExists)this.append("if exists ");if(this.visitNode($.schema),$.cascade)this.append(" cascade")}visitPrimaryKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("primary key ("),this.compileList($.columns),this.append(")"),this.buildDeferrable($)}buildDeferrable($){if($.deferrable!==void 0)if($.deferrable)this.append(" deferrable");else this.append(" not deferrable");if($.initiallyDeferred!==void 0)if($.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("unique"),$.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList($.columns),this.append(")"),this.buildDeferrable($)}visitCheckConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("check ("),this.visitNode($.expression),this.append(")")}visitForeignKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("foreign key ("),this.compileList($.columns),this.append(") "),this.visitNode($.references),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate);this.buildDeferrable($)}visitList($){this.compileList($.items)}visitWith($){if(this.append("with "),$.recursive)this.append("recursive ");this.compileList($.expressions)}visitCommonTableExpression($){if(this.visitNode($.name),this.append(" as "),aj($.materialized)){if(!$.materialized)this.append("not ");this.append("materialized ")}this.visitNode($.expression)}visitCommonTableExpressionName($){if(this.visitNode($.table),$.columns)this.append("("),this.compileList($.columns),this.append(")")}visitAlterTable($){if(this.append("alter table "),this.visitNode($.table),this.append(" "),$.renameTo)this.append("rename to "),this.visitNode($.renameTo);if($.setSchema)this.append("set schema "),this.visitNode($.setSchema);if($.addConstraint)this.visitNode($.addConstraint);if($.dropConstraint)this.visitNode($.dropConstraint);if($.renameConstraint)this.visitNode($.renameConstraint);if($.columnAlterations)this.compileColumnAlterations($.columnAlterations);if($.addIndex)this.visitNode($.addIndex);if($.dropIndex)this.visitNode($.dropIndex)}visitAddColumn($){this.append("add column "),this.visitNode($.column)}visitRenameColumn($){this.append("rename column "),this.visitNode($.column),this.append(" to "),this.visitNode($.renameTo)}visitDropColumn($){if(this.append("drop column "),$.ifExists)this.append("if exists ");this.visitNode($.column)}visitAlterColumn($){if(this.append("alter column "),this.visitNode($.column),this.append(" "),$.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode($.dataType),$.dataTypeExpression)this.append("using "),this.visitNode($.dataTypeExpression)}if($.setDefault)this.append("set default "),this.visitNode($.setDefault);if($.dropDefault)this.append("drop default");if($.setNotNull)this.append("set not null");if($.dropNotNull)this.append("drop not null")}visitModifyColumn($){this.append("modify column "),this.visitNode($.column)}visitAddConstraint($){this.append("add "),this.visitNode($.constraint)}visitDropConstraint($){if(this.append("drop constraint "),$.ifExists)this.append("if exists ");if(this.visitNode($.constraintName),$.modifier==="cascade")this.append(" cascade");else if($.modifier==="restrict")this.append(" restrict")}visitRenameConstraint($){this.append("rename constraint "),this.visitNode($.oldName),this.append(" to "),this.visitNode($.newName)}visitSetOperation($){if(this.append($.operator),this.append(" "),$.all)this.append("all ");this.visitNode($.expression)}visitCreateView($){if(this.append("create "),$.orReplace)this.append("or replace ");if($.materialized)this.append("materialized ");if($.temporary)this.append("temporary ");if(this.append("view "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),this.append(" "),$.columns)this.append("("),this.compileList($.columns),this.append(") ");if($.as)this.append("as "),this.visitNode($.as)}visitRefreshMaterializedView($){if(this.append("refresh materialized view "),$.concurrently)this.append("concurrently ");if(this.visitNode($.name),$.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView($){if(this.append("drop "),$.materialized)this.append("materialized ");if(this.append("view "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.cascade)this.append(" cascade")}visitGenerated($){if(this.append("generated "),$.always)this.append("always ");if($.byDefault)this.append("by default ");if(this.append("as "),$.identity)this.append("identity");if($.expression)this.append("("),this.visitNode($.expression),this.append(")");if($.stored)this.append(" stored")}visitDefaultValue($){this.append("default "),this.visitNode($.defaultValue)}visitSelectModifier($){if($.rawModifier)this.visitNode($.rawModifier);else this.append(fD0[$.modifier]);if($.of)this.append(" of "),this.compileList($.of,", ")}visitCreateType($){if(this.append("create type "),this.visitNode($.name),$.enum)this.append(" as enum "),this.visitNode($.enum)}visitDropType($){if(this.append("drop type "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.additionalNames?.length)this.append(", "),this.compileList($.additionalNames);if($.cascade)this.append(" cascade")}visitAlterType($){if(this.append("alter type "),this.visitNode($.name),this.append(" "),$.addValue)this.visitNode($.addValue);else if($.renameTo)this.append("rename to "),this.visitNode($.renameTo);else if($.renameValue)this.visitNode($.renameValue);else if($.setSchema)this.append("set schema "),this.visitNode($.setSchema)}visitAddValue($){if(this.append("add value "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.value),$.neighborValue)this.append($.isBefore?" before ":" after "),this.visitNode($.neighborValue)}visitRenameValue($){this.append("rename value "),this.visitNode($.oldValue),this.append(" to "),this.visitNode($.newValue)}visitExplain($){if(this.append("explain"),$.options||$.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),$.options){if(this.visitNode($.options),$.format)this.append(this.getExplainOptionsDelimiter())}if($.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append($.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue($){this.append("default")}visitAggregateFunction($){if(this.append($.func),this.append("("),$.distinct)this.append("distinct ");if(this.compileList($.aggregated),$.orderBy)this.append(" "),this.visitNode($.orderBy);if(this.append(")"),$.withinGroup)this.append(" within group ("),this.visitNode($.withinGroup),this.append(")");if($.filter)this.append(" filter("),this.visitNode($.filter),this.append(")");if($.over)this.append(" "),this.visitNode($.over)}visitOver($){if(this.append("over("),$.partitionBy){if(this.visitNode($.partitionBy),$.orderBy)this.append(" ")}if($.orderBy)this.visitNode($.orderBy);this.append(")")}visitPartitionBy($){this.append("partition by "),this.compileList($.items)}visitPartitionByItem($){this.visitNode($.partitionBy)}visitBinaryOperation($){this.visitNode($.leftOperand),this.append(" "),this.visitNode($.operator),this.append(" "),this.visitNode($.rightOperand)}visitUnaryOperation($){if(this.visitNode($.operator),!this.isMinusOperator($.operator))this.append(" ");this.visitNode($.operand)}isMinusOperator($){return HJ.is($)&&$.operator==="-"}visitUsing($){this.append("using "),this.compileList($.tables)}visitFunction($){this.append($.func),this.append("("),this.compileList($.arguments),this.append(")")}visitCase($){if(this.append("case"),$.value)this.append(" "),this.visitNode($.value);if($.when)this.append(" "),this.compileList($.when," ");if($.else)this.append(" else "),this.visitNode($.else);if(this.append(" end"),$.isStatement)this.append(" case")}visitWhen($){if(this.append("when "),this.visitNode($.condition),$.result)this.append(" then "),this.visitNode($.result)}visitJSONReference($){this.visitNode($.reference),this.visitNode($.traversal)}visitJSONPath($){if($.inOperator)this.visitNode($.inOperator);this.append("'$");for(let J of $.pathLegs)this.visitNode(J);this.append("'")}visitJSONPathLeg($){let J=$.type==="ArrayLocation",X=String($.value);if(J)this.append("["),this.append(this.sanitizeStringLiteral(X)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(X)),this.append('"')}visitJSONOperatorChain($){for(let J=0,X=$.values.length;J<X;J++){if(J===X-1)this.visitNode($.operator);else this.append("->");this.visitNode($.values[J])}}visitMergeQuery($){if($.with)this.visitNode($.with),this.append(" ");if(this.append("merge "),$.top)this.visitNode($.top),this.append(" ");if(this.append("into "),this.visitNode($.into),$.using)this.append(" "),this.visitNode($.using);if($.whens)this.append(" "),this.compileList($.whens," ");if($.returning)this.append(" "),this.visitNode($.returning);if($.output)this.append(" "),this.visitNode($.output);if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitMatched($){if($.not)this.append("not ");if(this.append("matched"),$.bySource)this.append(" by source")}visitAddIndex($){if(!this.parentNode||!zJ.is(this.parentNode))this.append("add ");if($.unique)this.append("unique ");if(this.append("index "),this.visitNode($.name),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.using)this.append(" using "),this.visitNode($.using)}visitCast($){this.append("cast("),this.visitNode($.expression),this.append(" as "),this.visitNode($.dataType),this.append(")")}visitFetch($){this.append("fetch next "),this.visitNode($.rowCount),this.append(` rows ${$.modifier}`)}visitOutput($){this.append("output "),this.compileList($.selections)}visitTop($){if(this.append(`top(${$.expression})`),$.modifiers)this.append(` ${$.modifiers}`)}visitOrAction($){this.append($.action)}visitCollate($){this.append("collate "),this.visitNode($.collation)}append($){this.#$+=$}appendValue($){this.addParameter($),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier($){let J=this.getLeftIdentifierWrapper(),X=this.getRightIdentifierWrapper(),Q="";for(let Y of $)if(Q+=Y,Y===J)Q+=J;else if(Y===X)Q+=X;return Q}sanitizeStringLiteral($){return $.replace(bD0,"''")}sanitizeJSONPathMemberValue($){return $.replace(yD0,(J)=>J==="'"?"''":"\\\"")}addParameter($){this.#J.push($)}appendImmediateValue($){if(C1($))this.appendStringLiteral($);else if(wY($)||aj($)||SU($))this.append($.toString());else if(CU($))this.append("null");else if(sB($))this.appendImmediateValue($.toISOString());else throw Error(`invalid immediate value ${$}`)}appendStringLiteral($){this.append("'"),this.append(this.sanitizeStringLiteral($)),this.append("'")}sortSelectModifiers($){return P($.toSorted((J,X)=>J.modifier&&X.modifier?hM$[J.modifier]-hM$[X.modifier]:1))}compileColumnAlterations($){this.compileList($)}announcesNewColumnDataType(){return!0}};fD0=P({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),hM$=P({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),vD0=P({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var a8;var lD=D(()=>{PX();G$();SY();a8=P({raw($,J=[]){return P({sql:$,query:v4.createWithSql($),parameters:P(J),queryId:M1()})}})});class zV{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}function L5($,J){return v4.createWithChildren([v4.createWithSql(`${$} `),U1.create(J)])}var nM=D(()=>{k6();PX()});class D1${#$;#J;#X;constructor($){this.#$=P({...$})}async init($){if(this.#J=a4(this.#$.database)?await this.#$.database($):this.#$.database,this.#X=new gM$(this.#J),this.#$.onCreateConnection)await this.#$.onCreateConnection(this.#X,$)}async acquireConnection(){return this.#X}async beginTransaction($){await $.executeQuery(a8.raw("begin"))}async commitTransaction($){await $.executeQuery(a8.raw("commit"))}async rollbackTransaction($){await $.executeQuery(a8.raw("rollback"))}async savepoint($,J,X){await $.executeQuery(X(L5("savepoint",J),M1()))}async rollbackToSavepoint($,J,X){await $.executeQuery(X(L5("rollback to",J),M1()))}async releaseSavepoint($,J,X){await $.executeQuery(X(L5("release",J),M1()))}async releaseConnection(){}async destroy(){this.#J?.close()}}class gM${#$;constructor($){this.#$=$}async executeQuery($){let{sql:J,parameters:X}=$,Q=this.#$.prepare(J);if(Q.reader)return{rows:Q.all(X)};let{changes:Y,lastInsertRowid:W}=Q.run(X);return{insertId:W!=null?BigInt(W):void 0,numAffectedRows:Y!=null?BigInt(Y):void 0,rows:[]}}async*streamQuery($,J){let{sql:X,parameters:Q,query:Y}=$,W=this.#$.prepare(X);if(!H6.is(Y))throw Error("Sqlite driver only supports streaming of select queries");let G=W.iterate(Q);for(let Z of G)yield{rows:[Z]}}}var F1$=D(()=>{ZL();nM();lD();G$();SY()});var hD0,gD0,dM;var q1$=D(()=>{BL();hD0=/"/g,gD0=/[\\'"]/g;dM=class dM extends UV{visitOrAction($){this.append("or "),this.append($.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier($){return $.replace(hD0,'""')}sanitizeJSONPathMemberValue($){return $.replace(gD0,(J)=>J==="\\"?"\\\\":J==="'"?"''":"\\\"")}visitDefaultInsertValue($){this.append("null")}}});class w1${transformQuery($){return $.node}async transformResult($){return $.result}}class A1${#$;constructor($){this.#$=P($)}async getMigrations(){let J=await this.#K(this.#Q)?await this.#$.db.withPlugin(this.#W).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#F()).map(({name:Q,...Y})=>{let W=J.find((G)=>G.name===Q);return{name:Q,migration:Y,executedAt:W?new Date(W.timestamp):void 0}})}async migrateToLatest($){return this.#J(()=>({direction:"Up",step:1/0}),$)}async migrateTo($,J){return this.#J(({migrations:X,executedMigrations:Q,pendingMigrations:Y})=>{if(L6($)&&$.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!X.find((Z)=>Z.name===$))throw Error(`migration "${$}" doesn't exist`);let W=Q.indexOf($),G=Y.findIndex((Z)=>Z.name===$);if(W!==-1)return{direction:"Down",step:Q.length-W-1};if(G!==-1)return{direction:"Up",step:G+1};throw Error(`migration "${$}" isn't executed or pending`)},J)}async migrateUp($){return this.#J(()=>({direction:"Up",step:1}),$)}async migrateDown($){return this.#J(()=>({direction:"Down",step:1}),$)}async#J($,J){try{return await this.#Z(),await this.#j(),await this.#V(),await this.#U(),await this.#L($,J)}catch(X){if(X instanceof Xf)return X.resultSet;return{error:X}}}get#X(){return this.#$.migrationTableSchema}get#Q(){return this.#$.migrationTableName??_8}get#Y(){return this.#$.migrationLockTableName??UG}get#G(){return this.#$.allowUnorderedMigrations??uD0}get#W(){if(this.#X)return new IY(this.#X);return new w1$}async#Z(){if(!this.#X)return;if(await this.#z())return;try{await this.#H(this.#$.db.schema.createSchema(this.#X))}catch(J){if(!await this.#z())throw J}}async#j(){if(await this.#K(this.#Q))return;try{await this.#H(this.#$.db.schema.withPlugin(this.#W).createTable(this.#Q).addColumn("name","varchar(255)",(J)=>J.notNull().primaryKey()).addColumn("timestamp","varchar(255)",(J)=>J.notNull()))}catch(J){if(!await this.#K(this.#Q))throw J}}async#V(){if(await this.#K(this.#Y))return;try{await this.#H(this.#$.db.schema.withPlugin(this.#W).createTable(this.#Y).addColumn("id","varchar(255)",(J)=>J.notNull().primaryKey()).addColumn("is_locked","integer",(J)=>J.notNull().defaultTo(0)))}catch(J){if(!await this.#K(this.#Y))throw J}}async#U(){if(await this.#O())return;try{await this.#$.db.withPlugin(this.#W).insertInto(this.#Y).values({id:N1$,is_locked:0}).execute()}catch(J){if(!await this.#O())throw J}}async#z(){return(await this.#$.db.introspection.getSchemas()).some((J)=>J.name===this.#X)}async#K($){let J=this.#X;return(await this.#$.db.introspection.getTables({withInternalKyselyTables:!0})).some((Q)=>Q.name===$&&(!J||Q.schema===J))}async#O(){return!!await this.#$.db.withPlugin(this.#W).selectFrom(this.#Y).where("id","=",N1$).select("id").executeTakeFirst()}async#L($,J){let X=this.#$.db.getExecutor().adapter,Q=P({lockTable:this.#$.migrationLockTableName??UG,lockRowId:N1$,lockTableSchema:this.#$.migrationTableSchema}),Y=async(Z)=>{let j=await this.#N(Z);if(j.migrations.length===0)return{results:[]};let{direction:V,step:K}=$(j);if(K<=0)return{results:[]};if(V==="Down")return await this.#q(Z,j,K);else if(V==="Up")return await this.#E(Z,j,K);return{results:[]}},W=async(Z,j)=>{try{return await X.acquireMigrationLock(Z,Q),await j(Z)}finally{await X.releaseMigrationLock(Z,Q)}},G=J?.disableTransactions??this.#$.disableTransactions;if(this.#$.db.isTransaction){if(!X.supportsTransactionalDdl)throw Error("Transactional DDL is not supported in this dialect. Passing a transaction to this migrator would result in failure or unexpected behavior.");if(G)throw Error("`disableTransactions` is true but the migrator was given a transaction. Passing a transaction to this migrator would result in failure or unexpected behavior.");return W(this.#$.db,Y)}if(X.supportsTransactionalDdl&&!G)return this.#$.db.connection().execute((Z)=>W(Z,(j)=>j.transaction().execute((V)=>Y(V))));return this.#$.db.connection().execute((Z)=>W(Z,Y))}async#N($){let J=await this.#F(),X=await this.#_($);if(this.#M(J,X),!this.#G)this.#R(J,X);let Q=this.#A(J,X);return P({migrations:J,executedMigrations:X,lastMigration:tA$(X),pendingMigrations:Q})}#A($,J){return $.filter((X)=>{return!J.includes(X.name)})}async#F(){let $=await this.#$.provider.getMigrations();return Object.keys($).sort().map((J)=>({...$[J],name:J}))}async#_($){let J=await $.withPlugin(this.#W).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute(),X=this.#$.nameComparator||((Q,Y)=>Q.localeCompare(Y));return J.sort((Q,Y)=>{if(Q.timestamp===Y.timestamp)return X(Q.name,Y.name);return new Date(Q.timestamp).getTime()-new Date(Y.timestamp).getTime()}).map((Q)=>Q.name)}#M($,J){for(let X of J)if(!$.some((Q)=>Q.name===X))throw Error(`corrupted migrations: previously executed migration ${X} is missing`)}#R($,J){for(let X=0;X<J.length;++X)if($[X].name!==J[X])throw Error(`corrupted migrations: expected previously executed migration ${J[X]} to be at index ${X} but ${$[X].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#q($,J,X){let Q=J.executedMigrations.toReversed().slice(0,X).map((W)=>{return J.migrations.find((G)=>G.name===W)}),Y=Q.map((W)=>{return{migrationName:W.name,direction:"Down",status:"NotExecuted"}});for(let W=0;W<Y.length;++W){let G=Q[W];try{if(G.down)await G.down($),await $.withPlugin(this.#W).deleteFrom(this.#Q).where("name","=",G.name).execute(),Y[W]={migrationName:G.name,direction:"Down",status:"Success"}}catch(Z){throw Y[W]={migrationName:G.name,direction:"Down",status:"Error"},new Xf({error:Z,results:Y})}}return{results:Y}}async#E($,J,X){let Y=J.pendingMigrations.slice(0,X).map((W)=>{return{migrationName:W.name,direction:"Up",status:"NotExecuted"}});for(let W=0;W<Y.length;W++){let G=J.pendingMigrations[W];try{await G.up($),await $.withPlugin(this.#W).insertInto(this.#Q).values({name:G.name,timestamp:new Date().toISOString()}).execute(),Y[W]={migrationName:G.name,direction:"Up",status:"Success"}}catch(Z){throw Y[W]={migrationName:G.name,direction:"Up",status:"Error"},new Xf({error:Z,results:Y})}}return{results:Y}}async#H($){if(this.#$.db.getExecutor().adapter.supportsCreateIfNotExists)$=$.ifNotExists();await $.execute()}}var _8="kysely_migration",UG="kysely_migration_lock",uD0=!1,N1$="migration_lock",rt1,Xf;var DL=D(()=>{wD();G$();rt1=P({__noMigrations__:!0});Xf=class Xf extends Error{#$;constructor($){super();this.#$=$}get resultSet(){return this.#$}}});class iM{#$;constructor($){this.#$=$}async getSchemas(){return[]}async getTables($={withInternalKyselyTables:!1}){return await this.#X($)}#J($,J){let X=$.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!J.withInternalKyselyTables)X=X.where("name","!=",_8).where("name","!=",UG);return X}async#X($){let J=await this.#J(this.#$,$).execute(),X=await this.#$.with("table_list",(Y)=>this.#J(Y,$)).selectFrom(["table_list as tl",$0`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),Q={};for(let Y of X)Q[Y.table]??=[],Q[Y.table].push(Y);return J.map(({name:Y,sql:W,type:G})=>{let Z=W?.split(/[\(\),]/)?.find((V)=>V.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),j=Q[Y]??[];if(!Z){let V=j.filter((K)=>K.pk>0);if(V.length===1&&V[0].type.toLowerCase()==="integer")Z=V[0].name}return{name:Y,isView:G==="view",isForeign:!1,columns:j.map((V)=>({name:V.name,dataType:V.type,isNullable:!V.notnull,isAutoIncrementing:V.name===Z,hasDefaultValue:V.dflt_value!=null,comment:void 0}))}})}}var _1$=D(()=>{DL();nU()});var oM;var M1$=D(()=>{oM=class oM extends zV{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock($,J){}async releaseMigrationLock($,J){}}});class mD0{#$;constructor($){this.#$=P({...$})}createDriver(){return new D1$(this.#$)}createQueryCompiler(){return new dM}createAdapter(){return new oM}createIntrospector($){return new iM($)}}var uM$=D(()=>{F1$();q1$();_1$();M1$();G$()});function dU($,J){if(lD0($)&&J.stack){let X=J.stack.split(`
|
|
29
|
+
`)){let Q=X.trim();if(!Q||Q.startsWith("#"))continue;let Y=Q.indexOf("=");if(Y<0)continue;J.set(Q.slice(0,Y).trim(),Q.slice(Y+1).trim())}return J}function uB0($,J){let X=q0("path"),Q=[],Y=$.get("path");if(Y&&X.isAbsolute(Y))Q.push(X.join(Y,"config.ini"));let W=$.get("path.rel");if(W&&!X.isAbsolute(W)){let G=X.resolve(J),Z=X.resolve(G,W);Q.push(X.join(Z,"config.ini"))}return Q}function mB0($){return{screenWidth:se($.get("hw.lcd.width")),screenHeight:se($.get("hw.lcd.height")),screenDensity:se($.get("hw.lcd.density"))}}function se($){if(!$)return;return Number.parseInt($,10)||void 0}function lB0($){let J=$.get("hw.ramSize");if(J===void 0)return{};let X=/^(\d+)\s*(?:(k|m|g)(?:i?b)?)?$/i.exec(J);if(!X)return{ramSizeInvalid:!0};let Q=Number(X[1]),Y=X[2]?.toLowerCase(),G=Q*(Y==="g"?1024:Y==="k"?0.0009765625:1);return Number.isFinite(G)?{ramSizeMb:G}:{}}function pB0($){return{...$.get("hw.device.name")?{deviceName:$.get("hw.device.name")}:{},...$.get("tag.id")?{tag:$.get("tag.id")}:{}}}function cB0($){let X=$.get("image.sysdir.1")?.match(/android-(\d+)/);if(!X)return{};let Q=Number.parseInt(X[1],10);return{apiLevel:Q,osVersion:hB0(Q)??String(Q)}}var PU=2048,vB0;var ee=D(()=>{d();vB0={21:"5.0",22:"5.1",23:"6.0",24:"7.0",25:"7.1",26:"8.0",27:"8.1",28:"9",29:"10",30:"11",31:"12",32:"12L",33:"13",34:"14",35:"15",36:"16"}});async function TU($,J,X=u){let Q=$,Y=J===void 0?void 0:X.now()+J;try{if(typeof Q.getAndroidApiLevel==="function"){let j=await Q.getAndroidApiLevel(J);if(j!==null&&j!==void 0)return j}let W=J;if(Y!==void 0){let j=Y-X.now();if(j<=0)return null;W=j}let G=await $.executeCommand("shell getprop ro.build.version.sdk",W,void 0,!0),Z=parseInt(G.stdout.trim(),10);return Number.isFinite(Z)?Z:null}catch(W){return U.debug(`src/utils/android-cmdline-tools/readAndroidDeviceApiLevel.ts fallback failed: ${W}`,W),null}}var i_=D(()=>{d();U$()});function dA$($,J){if(!J)return null;return{commands:[`shell input keycombination KEYCODE_SHIFT_LEFT ${$}`]}}function oA$($){return/^[A-Z]$/.test($)||Object.hasOwn(iA$,$)}function o_($,J){if(/^[a-z]$/.test($))return{commands:[`shell input keyevent KEYCODE_${$.toUpperCase()}`]};if(/^[A-Z]$/.test($))return dA$(`KEYCODE_${$}`,J);if(/^[0-9]$/.test($))return{commands:[`shell input keyevent KEYCODE_${$}`]};let X=nB0[$];if(X)return{commands:[`shell input keyevent ${X}`]};let Q=iA$[$];if(Q)return dA$(Q,J);return null}var pb=31,nB0,iA$;var $$$=D(()=>{nB0={" ":"KEYCODE_SPACE","-":"KEYCODE_MINUS","=":"KEYCODE_EQUALS","[":"KEYCODE_LEFT_BRACKET","]":"KEYCODE_RIGHT_BRACKET","\\":"KEYCODE_BACKSLASH",";":"KEYCODE_SEMICOLON","'":"KEYCODE_APOSTROPHE",",":"KEYCODE_COMMA",".":"KEYCODE_PERIOD","/":"KEYCODE_SLASH","`":"KEYCODE_GRAVE","@":"KEYCODE_AT"},iA$={"!":"KEYCODE_1","#":"KEYCODE_3",$:"KEYCODE_4","%":"KEYCODE_5","^":"KEYCODE_6","&":"KEYCODE_7","*":"KEYCODE_8","(":"KEYCODE_9",")":"KEYCODE_0",_:"KEYCODE_MINUS","+":"KEYCODE_EQUALS","{":"KEYCODE_LEFT_BRACKET","}":"KEYCODE_RIGHT_BRACKET","|":"KEYCODE_BACKSLASH",":":"KEYCODE_SEMICOLON",'"':"KEYCODE_APOSTROPHE","<":"KEYCODE_COMMA",">":"KEYCODE_PERIOD","?":"KEYCODE_SLASH","~":"KEYCODE_GRAVE"}});class r_{device;adb;timer;credentialStore;iosUnlocker;keyCombinationSupported;constructor($,J=V$,X={}){if(this.device=$,J&&typeof J.create==="function")this.adb=J.create($);else if(J)this.adb=J;else this.adb=V$.create($);this.timer=X.timer??u,this.credentialStore=X.credentialStore,this.iosUnlocker=X.iosUnlocker}async execute($){switch(this.device.platform){case"android":return this.executeAndroid($);case"ios":return this.executeIos();default:throw new R(`wakeAndUnlock: unsupported platform ${this.device.platform}`)}}async executeAndroid($){let X=await this.adb.getWakefulness()!=="Awake";if(X)U.info("[WakeAndUnlock] device asleep, sending KEYCODE_WAKEUP"),await this.adb.executeCommand("shell input keyevent KEYCODE_WAKEUP"),await this.timer.sleep(dB0);let Q=await this.adb.getDeviceLock();if(Q===null)return U.warn("[WakeAndUnlock] device woken but lock state could not be read"),{success:!1,platform:"android",wasAsleep:X,wasLocked:!1,unlocked:!1,error:"Could not read device lock state (dumpsys window policy unavailable); the device was woken but its lock status is unknown"};if(!Q.locked)return{success:!0,platform:"android",wasAsleep:X,wasLocked:!1,secure:Q.secure,unlocked:!0};return await this.adb.executeCommand("shell wm dismiss-keyguard"),Q.secure===!1?this.dismissSwipe(X):this.unlockSecure(X,$,Q.secure)}async dismissSwipe($){let J=await this.pollUnlocked();if(J)await this.rememberLock("swipe",null);return{success:J,platform:"android",wasAsleep:$,wasLocked:!0,secure:!1,unlocked:J,error:J?void 0:"Swipe keyguard did not dismiss"}}async unlockSecure($,J,X){let Q=J?null:await this.getRecordedCredential(),Y=J??Q,W=!J&&!!Q;if(!Y){if(X===!0)throw new R("Device is secure-locked (PIN/pattern/password); provide `pin` to unlock it. Unlocking once with a `pin` lets AutoMobile remember it for later in this session.");if(await this.pollUnlocked())return await this.rememberLock("swipe",null),{success:!0,platform:"android",wasAsleep:$,wasLocked:!0,secure:void 0,unlocked:!0};throw new R("Device is locked and its secure status could not be read; provide `pin` to unlock it if it is secure.")}let G=await this.buildCredentialCommands(Y);await this.timer.sleep(iB0);for(let j of G)await this.adb.executeCommand(j);if(await this.adb.executeCommand("shell input keyevent KEYCODE_ENTER"),!await this.pollUnlocked()){if(U.warn("[WakeAndUnlock] device remained locked after credential entry"),W)await this.rememberLock("pin",null);return{success:!1,platform:"android",wasAsleep:$,wasLocked:!0,secure:X,unlocked:!1,usedRecordedCredential:W,error:"Device remained locked after PIN entry (wrong credential or entry failed)"}}if(J)await this.rememberLock("pin",J);return{success:!0,platform:"android",wasAsleep:$,wasLocked:!0,secure:!0,unlocked:!0,usedRecordedCredential:W}}async buildCredentialCommands($){let J=await this.supportsKeyCombination(),X=Array.from($),Q=[];for(let Y=0;Y<X.length;Y++){let W=o_(X[Y]??"",J);if(!W)throw new R(`wakeAndUnlock: the credential character at position ${Y+1} cannot be sent as a key event on this device`);Q.push(...W.commands)}return Q}async executeIos(){if(!this.iosUnlocker)throw new R("wakeAndUnlock: iOS unlocker is not configured");let $=await this.iosUnlocker.wakeAndDismiss();return{success:$.success,platform:"ios",wasAsleep:!1,wasLocked:!1,unlocked:$.success,error:$.error}}async pollUnlocked(){let $=0;while($<oB0){let X=await this.adb.getDeviceLock();if(X&&!X.locked)return!0;await this.timer.sleep(rA$),$+=rA$}let J=await this.adb.getDeviceLock();return!!J&&!J.locked}async getRecordedCredential(){if(!this.credentialStore)return null;try{return await this.credentialStore.getRecordedCredential(this.device.deviceId)}catch($){return U.warn(`[WakeAndUnlock] failed to read recorded credential for ${this.device.deviceId}: ${$}`),null}}async rememberLock($,J){if(!this.credentialStore)return;try{await this.credentialStore.rememberLock(this.device.deviceId,$,J)}catch(X){U.warn(`[WakeAndUnlock] failed to remember lock for ${this.device.deviceId}: ${X}`)}}async supportsKeyCombination(){if(this.keyCombinationSupported!==void 0)return this.keyCombinationSupported;let $=await TU(this.adb);return this.keyCombinationSupported=$!==null&&$>=pb,this.keyCombinationSupported}}var dB0=500,iB0=900,rA$=250,oB0=2500;var J$$=D(()=>{t$();d();U$();P0();i_();$$$()});function d5($){return typeof $>"u"||$===void 0}function C1($){return typeof $==="string"}function wY($){return typeof $==="number"}function aj($){return typeof $==="boolean"}function CU($){return $===null}function sB($){return $ instanceof Date}function SU($){return typeof $==="bigint"}function cb($){return typeof Buffer<"u"&&Buffer.isBuffer($)}function a4($){return typeof $==="function"}function L6($){return typeof $==="object"&&$!==null}function eB($){if(!L6($)||JD0($)!=="[object Object]")return!1;if(Object.getPrototypeOf($)===null)return!0;let J=$;while(Object.getPrototypeOf(J)!==null)J=Object.getPrototypeOf(J);return Object.getPrototypeOf($)===J}function tA$($){return $[$.length-1]}function P($){return Object.freeze($)}function t_($){if(KJ($))return $;else return[$]}function KJ($){return Array.isArray($)}function UJ($){return $}function nb($,J){if(KJ($)&&KJ(J))return rB0($,J);else if(L6($)&&L6(J))return tB0($,J);return $===J}function aA$($){return $ instanceof Error?$.message:String($)}function rB0($,J){if($.length!==J.length)return!1;for(let X=0;X<$.length;++X)if(!nb($[X],J[X]))return!1;return!0}function tB0($,J){if(cb($)&&cb(J))return aB0($,J);else if(sB($)&&sB(J))return sB0($,J);return eB0($,J)}function aB0($,J){return Buffer.compare($,J)===0}function sB0($,J){return $.getTime()===J.getTime()}function eB0($,J){let X=Object.keys($),Q=Object.keys(J);if(X.length!==Q.length)return!1;for(let Y of X)if(!nb($[Y],J[Y]))return!1;return!0}function JD0($){if($==null)return $===void 0?"[object Undefined]":"[object Null]";return $D0.call($)}var $D0;var G$=D(()=>{$D0=Object.prototype.toString});var s4;var $L=D(()=>{G$();s4=P({is($){return $.kind==="AlterTableNode"},create($){return P({kind:"AlterTableNode",table:$})},cloneWithTableProps($,J){return P({...$,...J})},cloneWithColumnAlteration($,J){return P({...$,columnAlterations:$.columnAlterations?[...$.columnAlterations,J]:[J]})}})});var U1;var k6=D(()=>{G$();U1=P({is($){return $.kind==="IdentifierNode"},create($){return P({kind:"IdentifierNode",name:$})}})});var NY;var db=D(()=>{G$();k6();NY=P({is($){return $.kind==="CreateIndexNode"},create($){return P({kind:"CreateIndexNode",name:U1.create($)})},cloneWith($,J){return P({...$,...J})},cloneWithColumns($,J){return P({...$,columns:[...$.columns||[],...J]})}})});var ib;var ob=D(()=>{G$();k6();ib=P({is($){return $.kind==="CreateSchemaNode"},create($,J){return P({kind:"CreateSchemaNode",schema:U1.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var sA$,zJ;var $D=D(()=>{G$();sA$=["preserve rows","delete rows","drop"],zJ=P({is($){return $.kind==="CreateTableNode"},create($){return P({kind:"CreateTableNode",table:$,columns:P([])})},cloneWithColumn($,J){return P({...$,columns:P([...$.columns,J])})},cloneWithConstraint($,J){return P({...$,constraints:$.constraints?P([...$.constraints,J]):P([J])})},cloneWithIndex($,J){return P({...$,indexes:$.indexes?P([...$.indexes,J]):P([J])})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):P([J])})},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):P([J])})},cloneWith($,J){return P({...$,...J})}})});var K5;var sj=D(()=>{G$();k6();K5=P({is($){return $.kind==="SchemableIdentifierNode"},create($){return P({kind:"SchemableIdentifierNode",identifier:U1.create($)})},createWithSchema($,J){return P({kind:"SchemableIdentifierNode",schema:U1.create($),identifier:U1.create(J)})}})});var IU;var a_=D(()=>{G$();sj();IU=P({is($){return $.kind==="DropIndexNode"},create($,J){return P({kind:"DropIndexNode",name:K5.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var s_;var rb=D(()=>{G$();k6();s_=P({is($){return $.kind==="DropSchemaNode"},create($,J){return P({kind:"DropSchemaNode",schema:U1.create($),...J})},cloneWith($,J){return P({...$,...J})}})});var JD;var tb=D(()=>{G$();JD=P({is($){return $.kind==="DropTableNode"},create($,J){return P({kind:"DropTableNode",table:$,...J})},cloneWith($,J){return P({...$,...J})}})});var LJ;var AY=D(()=>{G$();LJ=P({is($){return $.kind==="AliasNode"},create($,J){return P({kind:"AliasNode",node:$,alias:J})}})});var S7;var XD=D(()=>{G$();sj();S7=P({is($){return $.kind==="TableNode"},create($){return P({kind:"TableNode",table:K5.create($)})},createWithSchema($,J){return P({kind:"TableNode",table:K5.createWithSchema($,J)})}})});function x6($){return L6($)&&a4($.toOperationNode)}var i5=D(()=>{G$()});function ab($){return L6($)&&"expressionType"in $&&x6($)}function eA$($){return L6($)&&"expression"in $&&C1($.alias)&&x6($)}var sb=D(()=>{i5();G$()});var aW;var X$$=D(()=>{G$();aW=P({is($){return $.kind==="SelectModifierNode"},create($,J){return P({kind:"SelectModifierNode",modifier:$,of:J})},createWithExpression($){return P({kind:"SelectModifierNode",rawModifier:$})}})});var I7;var kU=D(()=>{G$();I7=P({is($){return $.kind==="AndNode"},create($,J){return P({kind:"AndNode",left:$,right:J})}})});var _Y;var JL=D(()=>{G$();_Y=P({is($){return $.kind==="OrNode"},create($,J){return P({kind:"OrNode",left:$,right:J})}})});var eb;var Q$$=D(()=>{G$();kU();JL();eb=P({is($){return $.kind==="OnNode"},create($){return P({kind:"OnNode",on:$})},cloneWithOperation($,J,X){return P({...$,on:J==="And"?I7.create($.on,X):_Y.create($.on,X)})}})});var MY;var QD=D(()=>{G$();Q$$();MY=P({is($){return $.kind==="JoinNode"},create($,J){return P({kind:"JoinNode",joinType:$,table:J,on:void 0})},createWithOn($,J,X){return P({kind:"JoinNode",joinType:$,table:J,on:eb.create(X)})},cloneWithOn($,J){return P({...$,on:$.on?eb.cloneWithOperation($.on,"And",J):eb.create(J)})}})});var sW;var e_=D(()=>{G$();sW=P({is($){return $.kind==="BinaryOperationNode"},create($,J,X){return P({kind:"BinaryOperationNode",leftOperand:$,operator:J,rightOperand:X})}})});function G_$($){return C1($)&&Q_$[$]}function Z_$($){return C1($)&&X_$[$]}function j_$($){return C1($)&&W_$[$]}var $_$,_b1,J_$,Mb1,X_$,XD0,Q_$,QD0,Y_$,Rb1,W_$,YD0,Eb1,HJ;var ej=D(()=>{G$();$_$=P({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),_b1=Object.keys($_$),J_$=P({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),Mb1=Object.keys(J_$),X_$=P({"->":!0,"->>":!0}),XD0=Object.keys(X_$),Q_$=P({...$_$,...J_$,"||":!0}),QD0=Object.keys(Q_$),Y_$=P({exists:!0,"not exists":!0}),Rb1=Object.keys(Y_$),W_$=P({...Y_$,"-":!0,not:!0}),YD0=Object.keys(W_$),Eb1=[...QD0,...XD0,...YD0,"between","between symmetric"],HJ=P({is($){return $.kind==="OperatorNode"},create($){return P({kind:"OperatorNode",operator:$})}})});var T4;var U5=D(()=>{G$();k6();T4=P({is($){return $.kind==="ColumnNode"},create($){return P({kind:"ColumnNode",column:U1.create($)})}})});var YD;var $M=D(()=>{G$();YD=P({is($){return $.kind==="SelectAllNode"},create(){return P({kind:"SelectAllNode"})}})});var WD;var $y=D(()=>{$M();G$();WD=P({is($){return $.kind==="ReferenceNode"},create($,J){return P({kind:"ReferenceNode",table:J,column:$})},createSelectAll($){return P({kind:"ReferenceNode",table:$,column:YD.create()})}})});class Y$${#$;get dynamicReference(){return this.#$}get refType(){return}constructor($){this.#$=$}toOperationNode(){return W$$(this.#$)}}function Jy($){return L6($)&&x6($)&&C1($.dynamicReference)}var JM=D(()=>{i5();OJ();G$()});var RY;var Xy=D(()=>{G$();RY=P({is($){return $.kind==="OrderByItemNode"},create($,J){return P({kind:"OrderByItemNode",orderBy:$,direction:J})},cloneWith($,J){return P({...$,...J})}})});var v4;var PX=D(()=>{G$();v4=P({is($){return $.kind==="RawNode"},create($,J){return P({kind:"RawNode",sqlFragments:P($),parameters:P(J)})},createWithSql($){return v4.create([$],[])},createWithChild($){return v4.create(["",""],[$])},createWithChildren($){return v4.create(Array($.length+1).fill(""),$)}})});var V_$;var G$$=D(()=>{G$();k6();V_$=P({is($){return $.kind==="CollateNode"},create($){return P({kind:"CollateNode",collation:U1.create($)})}})});class xU{#$;constructor($){this.#$=P($)}desc(){return new xU({node:RY.cloneWith(this.#$.node,{direction:v4.createWithSql("desc")})})}asc(){return new xU({node:RY.cloneWith(this.#$.node,{direction:v4.createWithSql("asc")})})}nullsLast(){return new xU({node:RY.cloneWith(this.#$.node,{nulls:"last"})})}nullsFirst(){return new xU({node:RY.cloneWith(this.#$.node,{nulls:"first"})})}collate($){return new xU({node:RY.cloneWith(this.#$.node,{collation:V_$.create($)})})}toOperationNode(){return this.#$.node}}var Z$$=D(()=>{G$$();Xy();PX();G$()});function GD($){if(K_$.has($))return;K_$.add($),console.log($)}var K_$;var j$$=D(()=>{K_$=new Set});function K$$($){return $==="asc"||$==="desc"}function TX($){if($.length===2)return[V$$($[0],$[1])];if($.length===1){let[J]=$;if(Array.isArray(J))return GD("orderBy(array) is deprecated, use multiple orderBy calls instead."),J.map((X)=>V$$(X));return[V$$(J)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${$.length}`)}function V$$($,J){let X=WD0($);if(RY.is(X)){if(J)throw Error("Cannot specify direction twice!");return X}return U_$(X,J)}function WD0($){if($V($))return BJ($);if(Jy($))return $.toOperationNode();let[J,X]=$.split(" ");if(X)return GD("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),U_$(k7(J),X);return k7($)}function U_$($,J){if(typeof J==="string"){if(!K$$(J))throw Error(`Invalid order by direction: ${J}`);return RY.create($,v4.createWithSql(J))}if(ab(J))return GD("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),RY.create($,J.toOperationNode());let X=RY.create($);if(!J)return X;return J(new xU({node:X})).toOperationNode()}var XL=D(()=>{JM();sb();Xy();PX();Z$$();j$$();EQ();OJ()});var ZD;var Qy=D(()=>{G$();ZD=P({is($){return $.kind==="JSONReferenceNode"},create($,J){return P({kind:"JSONReferenceNode",reference:$,traversal:J})},cloneWithTraversal($,J){return P({...$,traversal:J})}})});var Yy;var Wy=D(()=>{G$();Yy=P({is($){return $.kind==="JSONOperatorChainNode"},create($){return P({kind:"JSONOperatorChainNode",operator:$,values:P([])})},cloneWithValue($,J){return P({...$,values:P([...$.values,J])})}})});var bU;var XM=D(()=>{G$();bU=P({is($){return $.kind==="JSONPathNode"},create($){return P({kind:"JSONPathNode",inOperator:$,pathLegs:P([])})},cloneWithLeg($,J){return P({...$,pathLegs:P([...$.pathLegs,J])})}})});function W$$($){if(C1($))return k7($);return $.toOperationNode()}function JV($){if(KJ($))return $.map((J)=>P9(J));else return[P9($)]}function P9($){if($V($))return BJ($);return W$$($)}function z_$($,J){if(Z_$(J))return ZD.create(k7($),Yy.create(HJ.create(J)));if(J==="->$"||J==="->>$")return ZD.create(k7($),bU.create(HJ.create(J.slice(0,-1))));throw Error(`Invalid JSON operator: ${J}`)}function k7($){if(!$.includes("."))return WD.create(T4.create($));let X=$.split(".").map(z$$);if(X.length===3)return GD0(X);if(X.length===2)return ZD0(X);throw Error(`invalid column reference ${$}`)}function L_$($){if($.includes(" as ")){let[X,Q]=$.split(" as ").map(z$$);return LJ.create(k7(X),U1.create(Q))}else return k7($)}function U$$($){return T4.create($)}function jD($){if($.includes(" ")){let[X,Q]=$.split(" ").map(z$$);if(!K$$(Q))throw Error(`invalid order direction "${Q}" next to "${X}"`);return TX([X,Q])[0]}else return U$$($)}function GD0($){let[J,X,Q]=$;return WD.create(T4.create(Q),S7.createWithSchema(J,X))}function ZD0($){let[J,X]=$;return WD.create(T4.create(X),S7.create(J))}function z$$($){return $.trim()}var OJ=D(()=>{AY();U5();$y();XD();G$();EQ();k6();XL();ej();Qy();Wy();XM()});var VD;var QM=D(()=>{G$();VD=P({is($){return $.kind==="PrimitiveValueListNode"},create($){return P({kind:"PrimitiveValueListNode",values:P([...$])})}})});var eW;var QL=D(()=>{G$();eW=P({is($){return $.kind==="ValueListNode"},create($){return P({kind:"ValueListNode",values:P($)})}})});var n6;var CX=D(()=>{G$();n6=P({is($){return $.kind==="ValueNode"},create($){return P({kind:"ValueNode",value:$})},createImmediate($){return P({kind:"ValueNode",value:$,immediate:!0})}})});function H_$($){if(KJ($))return jD0($);return b6($)}function b6($){if($V($))return BJ($);return n6.create($)}function Gy($){return wY($)||aj($)||CU($)}function YM($){if(!Gy($))throw Error(`unsafe immediate value ${JSON.stringify($)}`);return n6.createImmediate($)}function jD0($){if($.some($V))return eW.create($.map((J)=>b6(J)));return VD.create($)}var $G=D(()=>{QM();QL();CX();G$();EQ()});var SX;var KD=D(()=>{G$();SX=P({is($){return $.kind==="ParensNode"},create($){return P({kind:"ParensNode",node:$})}})});function d6($){if($.length===3)return Zy($[0],$[1],$[2]);else if($.length===1)return b6($[0]);throw Error(`invalid arguments: ${JSON.stringify($)}`)}function Zy($,J,X){if(VD0(J)&&B_$(X))return sW.create(P9($),L$$(J),n6.createImmediate(X));return sW.create(P9($),L$$(J),H_$(X))}function O9($,J,X){return sW.create(P9($),L$$(J),P9(X))}function H$$($,J){return UD(Object.entries($).filter(([,X])=>!d5(X)).map(([X,Q])=>Zy(X,B_$(Q)?"is":"=",Q)),J)}function UD($,J,X=!0){let Q=J==="and"?I7.create:_Y.create;if($.length===0)return sW.create(n6.createImmediate(1),HJ.create("="),n6.createImmediate(J==="and"?1:0));let Y=O_$($[0]);for(let W=1;W<$.length;++W)Y=Q(Y,O_$($[W]));if($.length>1&&X)return SX.create(Y);return Y}function VD0($){return $==="is"||$==="is not"}function B_$($){return CU($)||aj($)}function L$$($){if(G_$($))return HJ.create($);if(x6($))return $.toOperationNode();throw Error(`invalid operator ${JSON.stringify($)}`)}function O_$($){return x6($)?$.toOperationNode():$}var IX=D(()=>{e_();G$();i5();ej();OJ();$G();CX();kU();KD();JL()});var XV;var WM=D(()=>{G$();XV=P({is($){return $.kind==="OrderByNode"},create($){return P({kind:"OrderByNode",items:P([...$])})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var O$$;var B$$=D(()=>{G$();O$$=P({is($){return $.kind==="PartitionByNode"},create($){return P({kind:"PartitionByNode",items:P($)})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var GM;var jy=D(()=>{G$();WM();B$$();GM=P({is($){return $.kind==="OverNode"},create(){return P({kind:"OverNode"})},cloneWithOrderByItems($,J){return P({...$,orderBy:$.orderBy?XV.cloneWithItems($.orderBy,J):XV.create(J)})},cloneWithPartitionByItems($,J){return P({...$,partitionBy:$.partitionBy?O$$.cloneWithItems($.partitionBy,J):O$$.create(J)})}})});var YL;var ZM=D(()=>{G$();YL=P({is($){return $.kind==="FromNode"},create($){return P({kind:"FromNode",froms:P($)})},cloneWithFroms($,J){return P({...$,froms:P([...$.froms,...J])})}})});var D$$;var F$$=D(()=>{G$();D$$=P({is($){return $.kind==="GroupByNode"},create($){return P({kind:"GroupByNode",items:P($)})},cloneWithItems($,J){return P({...$,items:P([...$.items,...J])})}})});var q$$;var w$$=D(()=>{G$();kU();JL();q$$=P({is($){return $.kind==="HavingNode"},create($){return P({kind:"HavingNode",having:$})},cloneWithOperation($,J,X){return P({...$,having:J==="And"?I7.create($.having,X):_Y.create($.having,X)})}})});var k8;var WL=D(()=>{G$();k8=P({is($){return $.kind==="InsertQueryNode"},create($,J,X){return P({kind:"InsertQueryNode",into:$,...J&&{with:J},replace:X})},createWithoutInto(){return P({kind:"InsertQueryNode"})},cloneWith($,J){return P({...$,...J})}})});var Vy;var Ky=D(()=>{G$();Vy=P({is($){return $.kind==="ListNode"},create($){return P({kind:"ListNode",items:P($)})}})});var JG;var zD=D(()=>{G$();ZM();Ky();JG=P({is($){return $.kind==="UpdateQueryNode"},create($,J){return P({kind:"UpdateQueryNode",table:$.length===1?$[0]:Vy.create($),...J&&{with:J}})},createWithoutTable(){return P({kind:"UpdateQueryNode"})},cloneWithFromItems($,J){return P({...$,from:$.from?YL.cloneWithFroms($.from,J):YL.create(J)})},cloneWithUpdates($,J){return P({...$,updates:$.updates?P([...$.updates,...J]):J})},cloneWithLimit($,J){return P({...$,limit:J})}})});var jM;var Uy=D(()=>{G$();jM=P({is($){return $.kind==="UsingNode"},create($){return P({kind:"UsingNode",tables:P($)})},cloneWithTables($,J){return P({...$,tables:P([...$.tables,...J])})}})});var yU;var VM=D(()=>{G$();ZM();Uy();PQ();yU=P({is($){return $.kind==="DeleteQueryNode"},create($,J){return P({kind:"DeleteQueryNode",from:YL.create($),...J&&{with:J}})},cloneWithOrderByItems:($,J)=>F0.cloneWithOrderByItems($,J),cloneWithoutOrderBy:($)=>F0.cloneWithoutOrderBy($),cloneWithLimit($,J){return P({...$,limit:J})},cloneWithoutLimit($){return P({...$,limit:void 0})},cloneWithUsing($,J){return P({...$,using:$.using!==void 0?jM.cloneWithTables($.using,J):jM.create(J)})}})});var SJ;var KM=D(()=>{G$();kU();JL();SJ=P({is($){return $.kind==="WhereNode"},create($){return P({kind:"WhereNode",where:$})},cloneWithOperation($,J,X){return P({...$,where:J==="And"?I7.create($.where,X):_Y.create($.where,X)})}})});var N$$;var A$$=D(()=>{G$();N$$=P({is($){return $.kind==="ReturningNode"},create($){return P({kind:"ReturningNode",selections:P($)})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})}})});var D_$;var _$$=D(()=>{G$();D_$=P({is($){return $.kind==="ExplainNode"},create($,J){return P({kind:"ExplainNode",format:$,options:J})}})});var x7;var GL=D(()=>{G$();x7=P({is($){return $.kind==="WhenNode"},create($){return P({kind:"WhenNode",condition:$})},cloneWithResult($,J){return P({...$,result:J})}})});var kX;var UM=D(()=>{G$();GL();kX=P({is($){return $.kind==="MergeQueryNode"},create($,J){return P({kind:"MergeQueryNode",into:$,...J&&{with:J}})},cloneWithUsing($,J){return P({...$,using:J})},cloneWithWhen($,J){return P({...$,whens:$.whens?P([...$.whens,J]):P([J])})},cloneWithThen($,J){return P({...$,whens:$.whens?P([...$.whens.slice(0,-1),x7.cloneWithResult($.whens[$.whens.length-1],J)]):void 0})}})});var M$$;var R$$=D(()=>{G$();M$$=P({is($){return $.kind==="OutputNode"},create($){return P({kind:"OutputNode",selections:P($)})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})}})});var F0;var PQ=D(()=>{WL();ZL();zD();VM();KM();G$();A$$();_$$();UM();R$$();WM();F0=P({is($){return H6.is($)||k8.is($)||JG.is($)||yU.is($)||kX.is($)},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):P([J])})},cloneWithWhere($,J){return P({...$,where:$.where?SJ.cloneWithOperation($.where,"And",J):SJ.create(J)})},cloneWithJoin($,J){return P({...$,joins:$.joins?P([...$.joins,J]):P([J])})},cloneWithReturning($,J){return P({...$,returning:$.returning?N$$.cloneWithSelections($.returning,J):N$$.create(J)})},cloneWithoutReturning($){return P({...$,returning:void 0})},cloneWithoutWhere($){return P({...$,where:void 0})},cloneWithExplain($,J,X){return P({...$,explain:D_$.create(J,X?.toOperationNode())})},cloneWithTop($,J){return P({...$,top:J})},cloneWithOutput($,J){return P({...$,output:$.output?M$$.cloneWithSelections($.output,J):M$$.create(J)})},cloneWithOrderByItems($,J){return P({...$,orderBy:$.orderBy?XV.cloneWithItems($.orderBy,J):XV.create(J)})},cloneWithoutOrderBy($){return P({...$,orderBy:void 0})}})});var H6;var ZL=D(()=>{G$();ZM();F$$();w$$();PQ();H6=P({is($){return $.kind==="SelectQueryNode"},create($){return P({kind:"SelectQueryNode",...$&&{with:$}})},createFrom($,J){return P({kind:"SelectQueryNode",from:YL.create($),...J&&{with:J}})},cloneWithSelections($,J){return P({...$,selections:$.selections?P([...$.selections,...J]):P(J)})},cloneWithDistinctOn($,J){return P({...$,distinctOn:$.distinctOn?P([...$.distinctOn,...J]):P(J)})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):P([J])})},cloneWithOrderByItems:($,J)=>F0.cloneWithOrderByItems($,J),cloneWithGroupByItems($,J){return P({...$,groupBy:$.groupBy?D$$.cloneWithItems($.groupBy,J):D$$.create(J)})},cloneWithLimit($,J){return P({...$,limit:J})},cloneWithOffset($,J){return P({...$,offset:J})},cloneWithFetch($,J){return P({...$,fetch:J})},cloneWithHaving($,J){return P({...$,having:$.having?q$$.cloneWithOperation($.having,"And",J):q$$.create(J)})},cloneWithSetOperations($,J){return P({...$,setOperations:$.setOperations?P([...$.setOperations,...J]):P([...J])})},cloneWithoutSelections($){return P({...$,selections:[]})},cloneWithoutLimit($){return P({...$,limit:void 0})},cloneWithoutOffset($){return P({...$,offset:void 0})},cloneWithoutOrderBy:($)=>F0.cloneWithoutOrderBy($),cloneWithoutGroupBy($){return P({...$,groupBy:void 0})}})});class LD{#$;constructor($){this.#$=P($)}on(...$){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,d6($))})}onRef($,J,X){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,O9($,J,X))})}onTrue(){return new LD({...this.#$,joinNode:MY.cloneWithOn(this.#$.joinNode,v4.createWithSql("true"))})}$call($){return $(this)}toOperationNode(){return this.#$.joinNode}}var E$$=D(()=>{QD();PX();IX();G$()});var F_$;var P$$=D(()=>{G$();F_$=P({is($){return $.kind==="PartitionByItemNode"},create($){return P({kind:"PartitionByItemNode",partitionBy:$})}})});function q_$($){return JV($).map(F_$.create)}var w_$=D(()=>{P$$();OJ()});class HD{#$;constructor($){this.#$=P($)}orderBy(...$){return new HD({overNode:GM.cloneWithOrderByItems(this.#$.overNode,TX($))})}clearOrderBy(){return new HD({overNode:F0.cloneWithoutOrderBy(this.#$.overNode)})}partitionBy($){return new HD({overNode:GM.cloneWithPartitionByItems(this.#$.overNode,q_$($))})}$call($){return $(this)}toOperationNode(){return this.#$.overNode}}var N_$=D(()=>{jy();PQ();XL();w_$();G$()});var OD;var T$$=D(()=>{G$();$y();$M();OD=P({is($){return $.kind==="SelectionNode"},create($){return P({kind:"SelectionNode",selection:$})},createSelectAll(){return P({kind:"SelectionNode",selection:YD.create()})},createSelectAllFromTable($){return P({kind:"SelectionNode",selection:WD.createSelectAll($)})}})});function u9($){if(a4($))return u9($(EY()));else if(KJ($))return $.map((J)=>A_$(J));else return[A_$($)]}function A_$($){if(C1($))return OD.create(L_$($));else if(Jy($))return OD.create($.toOperationNode());else return OD.create(zy($))}function DJ($){if(!$)return[OD.createSelectAll()];else if(Array.isArray($))return $.map(__$);else return[__$($)]}function __$($){if(C1($))return OD.createSelectAllFromTable(e4($));throw Error(`invalid value selectAll expression: ${JSON.stringify($)}`)}var fU=D(()=>{G$();T$$();OJ();JM();EQ();IJ();jL()});var M_$;var C$$=D(()=>{G$();M_$=P({is($){return $.kind==="ValuesNode"},create($){return P({kind:"ValuesNode",values:P($)})}})});var R_$;var S$$=D(()=>{G$();R_$=P({is($){return $.kind==="DefaultInsertValueNode"},create(){return P({kind:"DefaultInsertValueNode"})}})});function Ly($){let J=a4($)?$(EY()):$,X=KJ(J)?J:P([J]);return KD0(X)}function KD0($){let J=UD0($);return[P([...J.keys()].map(T4.create)),M_$.create($.map((X)=>zD0(X,J)))]}function UD0($){let J=new Map;for(let X of $){let Q=Object.keys(X);for(let Y of Q)if(!J.has(Y)&&X[Y]!==void 0)J.set(Y,J.size)}return J}function zD0($,J){let X=Object.keys($),Q=Array.from({length:J.size}),Y=!1,W=X.length;for(let Z of X){let j=J.get(Z);if(d5(j)){W--;continue}let V=$[Z];if(d5(V)||$V(V))Y=!0;Q[j]=V}if(W<J.size||Y){let Z=R_$.create();return eW.create(Q.map((j)=>d5(j)?Z:b6(j)))}return VD.create(Q)}var I$$=D(()=>{U5();QM();QL();G$();$G();C$$();EQ();S$$();jL()});var k$$;var x$$=D(()=>{G$();k$$=P({is($){return $.kind==="ColumnUpdateNode"},create($,J){return P({kind:"ColumnUpdateNode",column:$,value:J})}})});function E_$(...$){if($.length===2)return[k$$.create(P9($[0]),b6($[1]))];return zM($[0])}function zM($){let J=a4($)?$(EY()):$;return Object.entries(J).filter(([X,Q])=>Q!==void 0).map(([X,Q])=>{return k$$.create(T4.create(X),b6(Q))})}var Hy=D(()=>{U5();x$$();jL();G$();$G();OJ()});var P_$;var b$$=D(()=>{G$();P_$=P({is($){return $.kind==="OnDuplicateKeyNode"},create($){return P({kind:"OnDuplicateKeyNode",updates:$})}})});class y$${insertId;numInsertedOrUpdatedRows;constructor($,J){this.insertId=$,this.numInsertedOrUpdatedRows=J}}function XG($){return Object.prototype.hasOwnProperty.call($,"prototype")}var PY;var VL=D(()=>{PY=class PY extends Error{node;constructor($){super("no result");this.node=$}}});var o5;var Oy=D(()=>{G$();KM();o5=P({is($){return $.kind==="OnConflictNode"},create(){return P({kind:"OnConflictNode"})},cloneWith($,J){return P({...$,...J})},cloneWithIndexWhere($,J){return P({...$,indexWhere:$.indexWhere?SJ.cloneWithOperation($.indexWhere,"And",J):SJ.create(J)})},cloneWithIndexOrWhere($,J){return P({...$,indexWhere:$.indexWhere?SJ.cloneWithOperation($.indexWhere,"Or",J):SJ.create(J)})},cloneWithUpdateWhere($,J){return P({...$,updateWhere:$.updateWhere?SJ.cloneWithOperation($.updateWhere,"And",J):SJ.create(J)})},cloneWithUpdateOrWhere($,J){return P({...$,updateWhere:$.updateWhere?SJ.cloneWithOperation($.updateWhere,"Or",J):SJ.create(J)})},cloneWithoutIndexWhere($){return P({...$,indexWhere:void 0})},cloneWithoutUpdateWhere($){return P({...$,updateWhere:void 0})}})});class QG{#$;constructor($){this.#$=P($)}column($){let J=T4.create($);return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?P([...this.#$.onConflictNode.columns,J]):P([J])})})}columns($){let J=$.map(T4.create);return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?P([...this.#$.onConflictNode.columns,...J]):P(J)})})}constraint($){return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{constraint:U1.create($)})})}expression($){return new QG({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{indexExpression:$.toOperationNode()})})}where(...$){return new QG({...this.#$,onConflictNode:o5.cloneWithIndexWhere(this.#$.onConflictNode,d6($))})}whereRef($,J,X){return new QG({...this.#$,onConflictNode:o5.cloneWithIndexWhere(this.#$.onConflictNode,O9($,J,X))})}clearWhere(){return new QG({...this.#$,onConflictNode:o5.cloneWithoutIndexWhere(this.#$.onConflictNode)})}doNothing(){return new T_$({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{doNothing:!0})})}doUpdateSet($){return new LM({...this.#$,onConflictNode:o5.cloneWith(this.#$.onConflictNode,{updates:zM($)})})}$call($){return $(this)}}class T_${#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.onConflictNode}}class LM{#$;constructor($){this.#$=P($)}where(...$){return new LM({...this.#$,onConflictNode:o5.cloneWithUpdateWhere(this.#$.onConflictNode,d6($))})}whereRef($,J,X){return new LM({...this.#$,onConflictNode:o5.cloneWithUpdateWhere(this.#$.onConflictNode,O9($,J,X))})}clearWhere(){return new LM({...this.#$,onConflictNode:o5.cloneWithoutUpdateWhere(this.#$.onConflictNode)})}$call($){return $(this)}toOperationNode(){return this.#$.onConflictNode}}var f$$=D(()=>{U5();k6();Oy();IX();Hy();G$()});var C_$;var v$$=D(()=>{G$();C_$=P({is($){return $.kind==="TopNode"},create($,J){return P({kind:"TopNode",expression:$,modifiers:J})}})});function TY($,J){if(!wY($)&&!SU($))throw Error(`Invalid top expression: ${$}`);if(!d5(J)&&!LD0(J))throw Error(`Invalid top modifiers: ${J}`);return C_$.create($,J)}function LD0($){return $==="percent"||$==="with ties"||$==="percent with ties"}var BD=D(()=>{v$$();G$()});var KL;var h$$=D(()=>{G$();KL=P({is($){return $.kind==="OrActionNode"},create($){return P({kind:"OrActionNode",action:$})}})});class y6{#$;constructor($){this.#$=P($)}values($){let[J,X]=Ly($);return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{columns:J,values:X})})}columns($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{columns:P($.map(T4.create))})})}expression($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{values:BJ($)})})}defaultValues(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{defaultValues:!0})})}modifyEnd($){return new y6({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}ignore(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("ignore")})})}orIgnore(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("ignore")})})}orAbort(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("abort")})})}orFail(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("fail")})})}orReplace(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("replace")})})}orRollback(){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{orAction:KL.create("rollback")})})}top($,J){return new y6({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}onConflict($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{onConflict:$(new QG({onConflictNode:o5.create()})).toOperationNode()})})}onDuplicateKeyUpdate($){return new y6({...this.#$,queryNode:k8.cloneWith(this.#$.queryNode,{onDuplicateKey:P_$.create(zM($))})})}returning($){return new y6({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll(){return new y6({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ())})}output($){return new y6({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new y6({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}clearReturning(){return new y6({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new y6({...this.#$})}$castTo(){return new y6(this.#$)}$narrowType(){return new y6(this.#$)}$assertType(){return new y6(this.#$)}withPlugin($){return new y6({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new y$$(X.insertId,X.numAffectedRows??BigInt(0))]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new y6({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var g$$=D(()=>{fU();I$$();WL();PQ();Hy();G$();b$$();VL();EQ();U5();f$$();Oy();BD();h$$()});class u$${numDeletedRows;constructor($){this.numDeletedRows=$}}var DD;var HM=D(()=>{G$();DD=P({is($){return $.kind==="LimitNode"},create($){return P({kind:"LimitNode",limit:$})}})});class By{#$;constructor($){this.#$=P($)}where(...$){return new x8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new x8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}clearWhere(){return new x8({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}top($,J){return new x8({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}using($){return new x8({...this.#$,queryNode:yU.cloneWithUsing(this.#$.queryNode,CY($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}#J($,J){return new x8({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}returning($){return new x8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new x8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new x8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new x8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}clearReturning(){return new x8({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}clearLimit(){return new x8({...this.#$,queryNode:yU.cloneWithoutLimit(this.#$.queryNode)})}orderBy(...$){return new x8({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}clearOrderBy(){return new x8({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}limit($){return new x8({...this.#$,queryNode:yU.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}modifyEnd($){return new x8({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}$call($){return $(this)}$if($,J){if($)return J(this);return new x8({...this.#$})}$castTo(){return new x8(this.#$)}$narrowType(){return new x8(this.#$)}$assertType(){return new x8(this.#$)}withPlugin($){return new x8({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new u$$(X.numAffectedRows??BigInt(0))]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new x8({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var x8;var m$$=D(()=>{OM();IJ();fU();PQ();G$();VL();VM();HM();XL();IX();$G();BD();x8=By});class l$${numUpdatedRows;numChangedRows;constructor($,J){this.numUpdatedRows=$,this.numChangedRows=J}}class FD{#$;constructor($){this.#$=P($)}where(...$){return new b8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new b8({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}clearWhere(){return new b8({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}top($,J){return new b8({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}from($){return new b8({...this.#$,queryNode:JG.cloneWithFromItems(this.#$.queryNode,CY($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}#J($,J){return new b8({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}orderBy(...$){return new b8({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}clearOrderBy(){return new b8({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}limit($){return new b8({...this.#$,queryNode:JG.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}set(...$){return new b8({...this.#$,queryNode:JG.cloneWithUpdates(this.#$.queryNode,E_$(...$))})}returning($){return new b8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new b8({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new b8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new b8({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}modifyEnd($){return new b8({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}clearReturning(){return new b8({...this.#$,queryNode:F0.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new b8({...this.#$})}$castTo(){return new b8(this.#$)}$narrowType(){return new b8(this.#$)}$assertType(){return new b8(this.#$)}withPlugin($){return new b8({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new l$$(X.numAffectedRows??BigInt(0),X.numChangedRows)]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new b8({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}var b8;var Dy=D(()=>{OM();IJ();fU();PQ();zD();Hy();G$();VL();IX();$G();HM();BD();XL();b8=FD});var p$$;var c$$=D(()=>{G$();U5();XD();p$$=P({is($){return $.kind==="CommonTableExpressionNameNode"},create($,J){return P({kind:"CommonTableExpressionNameNode",table:S7.create($),columns:J?P(J.map(T4.create)):void 0})}})});var qD;var Fy=D(()=>{G$();qD=P({is($){return $.kind==="CommonTableExpressionNode"},create($,J){return P({kind:"CommonTableExpressionNode",name:$,expression:J})},cloneWith($,J){return P({...$,...J})}})});class BM{#$;constructor($){this.#$=P($)}materialized(){return new BM({...this.#$,node:qD.cloneWith(this.#$.node,{materialized:!0})})}notMaterialized(){return new BM({...this.#$,node:qD.cloneWith(this.#$.node,{materialized:!1})})}toOperationNode(){return this.#$.node}}var S_$=D(()=>{Fy();G$()});function n$$($,J){let X=x6(J)?J.toOperationNode():J(x_$()).toOperationNode();if(a4($))return $(HD0(X)).toOperationNode();return qD.create(I_$($),X)}function HD0($){return(J)=>{return new BM({node:qD.create(I_$(J),$)})}}function I_$($){if($.includes("(")){let J=$.split(/[\(\)]/),X=J[0],Q=J[1].split(",").map((Y)=>Y.trim());return p$$.create(X,Q)}else return p$$.create($)}var k_$=D(()=>{c$$();qy();G$();S_$();Fy();i5()});var DM;var d$$=D(()=>{G$();DM=P({is($){return $.kind==="WithNode"},create($,J){return P({kind:"WithNode",expressions:P([$]),...J})},cloneWithExpression($,J){return P({...$,expressions:P([...$.expressions,J])})}})});function wy($){let J="";for(let X=0;X<$;++X)J+=OD0();return J}function OD0(){return b_$[~~(Math.random()*b_$.length)]}var b_$;var i$$=D(()=>{b_$=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function M1(){return new y_$}class y_${#$;get queryId(){if(this.#$===void 0)this.#$=wy(8);return this.#$}}var SY=D(()=>{i$$()});class xX{nodeStack=[];#$=P({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode($,J){if(!$)return $;this.nodeStack.push($);let X=this.transformNodeImpl($,J);return this.nodeStack.pop(),P(X)}transformNodeImpl($,J){return this.#$[$.kind]($,J)}transformNodeList($,J){if(!$)return $;return P($.map((X)=>this.transformNode(X,J)))}transformSelectQuery($,J){return{kind:"SelectQueryNode",from:this.transformNode($.from,J),selections:this.transformNodeList($.selections,J),distinctOn:this.transformNodeList($.distinctOn,J),joins:this.transformNodeList($.joins,J),groupBy:this.transformNode($.groupBy,J),orderBy:this.transformNode($.orderBy,J),where:this.transformNode($.where,J),frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),limit:this.transformNode($.limit,J),offset:this.transformNode($.offset,J),with:this.transformNode($.with,J),having:this.transformNode($.having,J),explain:this.transformNode($.explain,J),setOperations:this.transformNodeList($.setOperations,J),fetch:this.transformNode($.fetch,J),top:this.transformNode($.top,J)}}transformSelection($,J){return{kind:"SelectionNode",selection:this.transformNode($.selection,J)}}transformColumn($,J){return{kind:"ColumnNode",column:this.transformNode($.column,J)}}transformAlias($,J){return{kind:"AliasNode",node:this.transformNode($.node,J),alias:this.transformNode($.alias,J)}}transformTable($,J){return{kind:"TableNode",table:this.transformNode($.table,J)}}transformFrom($,J){return{kind:"FromNode",froms:this.transformNodeList($.froms,J)}}transformReference($,J){return{kind:"ReferenceNode",column:this.transformNode($.column,J),table:this.transformNode($.table,J)}}transformAnd($,J){return{kind:"AndNode",left:this.transformNode($.left,J),right:this.transformNode($.right,J)}}transformOr($,J){return{kind:"OrNode",left:this.transformNode($.left,J),right:this.transformNode($.right,J)}}transformValueList($,J){return{kind:"ValueListNode",values:this.transformNodeList($.values,J)}}transformParens($,J){return{kind:"ParensNode",node:this.transformNode($.node,J)}}transformJoin($,J){return{kind:"JoinNode",joinType:$.joinType,table:this.transformNode($.table,J),on:this.transformNode($.on,J)}}transformRaw($,J){return{kind:"RawNode",sqlFragments:P([...$.sqlFragments]),parameters:this.transformNodeList($.parameters,J)}}transformWhere($,J){return{kind:"WhereNode",where:this.transformNode($.where,J)}}transformInsertQuery($,J){return{kind:"InsertQueryNode",into:this.transformNode($.into,J),columns:this.transformNodeList($.columns,J),values:this.transformNode($.values,J),returning:this.transformNode($.returning,J),onConflict:this.transformNode($.onConflict,J),onDuplicateKey:this.transformNode($.onDuplicateKey,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),orAction:this.transformNode($.orAction,J),replace:$.replace,explain:this.transformNode($.explain,J),defaultValues:$.defaultValues,top:this.transformNode($.top,J),output:this.transformNode($.output,J)}}transformValues($,J){return{kind:"ValuesNode",values:this.transformNodeList($.values,J)}}transformDeleteQuery($,J){return{kind:"DeleteQueryNode",from:this.transformNode($.from,J),using:this.transformNode($.using,J),joins:this.transformNodeList($.joins,J),where:this.transformNode($.where,J),returning:this.transformNode($.returning,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),orderBy:this.transformNode($.orderBy,J),limit:this.transformNode($.limit,J),explain:this.transformNode($.explain,J),top:this.transformNode($.top,J),output:this.transformNode($.output,J)}}transformReturning($,J){return{kind:"ReturningNode",selections:this.transformNodeList($.selections,J)}}transformCreateTable($,J){return{kind:"CreateTableNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),constraints:this.transformNodeList($.constraints,J),indexes:this.transformNodeList($.indexes,J),temporary:$.temporary,ifNotExists:$.ifNotExists,onCommit:$.onCommit,frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),selectQuery:this.transformNode($.selectQuery,J)}}transformColumnDefinition($,J){return{kind:"ColumnDefinitionNode",column:this.transformNode($.column,J),dataType:this.transformNode($.dataType,J),references:this.transformNode($.references,J),primaryKey:$.primaryKey,autoIncrement:$.autoIncrement,unique:$.unique,notNull:$.notNull,unsigned:$.unsigned,defaultTo:this.transformNode($.defaultTo,J),check:this.transformNode($.check,J),generated:this.transformNode($.generated,J),frontModifiers:this.transformNodeList($.frontModifiers,J),endModifiers:this.transformNodeList($.endModifiers,J),nullsNotDistinct:$.nullsNotDistinct,identity:$.identity,ifNotExists:$.ifNotExists}}transformAddColumn($,J){return{kind:"AddColumnNode",column:this.transformNode($.column,J)}}transformDropTable($,J){return{kind:"DropTableNode",table:this.transformNode($.table,J),ifExists:$.ifExists,cascade:$.cascade,temporary:$.temporary}}transformOrderBy($,J){return{kind:"OrderByNode",items:this.transformNodeList($.items,J)}}transformOrderByItem($,J){return{kind:"OrderByItemNode",orderBy:this.transformNode($.orderBy,J),direction:this.transformNode($.direction,J),collation:this.transformNode($.collation,J),nulls:$.nulls}}transformGroupBy($,J){return{kind:"GroupByNode",items:this.transformNodeList($.items,J)}}transformGroupByItem($,J){return{kind:"GroupByItemNode",groupBy:this.transformNode($.groupBy,J)}}transformUpdateQuery($,J){return{kind:"UpdateQueryNode",table:this.transformNode($.table,J),from:this.transformNode($.from,J),joins:this.transformNodeList($.joins,J),where:this.transformNode($.where,J),updates:this.transformNodeList($.updates,J),returning:this.transformNode($.returning,J),endModifiers:this.transformNodeList($.endModifiers,J),with:this.transformNode($.with,J),explain:this.transformNode($.explain,J),limit:this.transformNode($.limit,J),top:this.transformNode($.top,J),output:this.transformNode($.output,J),orderBy:this.transformNode($.orderBy,J)}}transformColumnUpdate($,J){return{kind:"ColumnUpdateNode",column:this.transformNode($.column,J),value:this.transformNode($.value,J)}}transformLimit($,J){return{kind:"LimitNode",limit:this.transformNode($.limit,J)}}transformOffset($,J){return{kind:"OffsetNode",offset:this.transformNode($.offset,J)}}transformOnConflict($,J){return{kind:"OnConflictNode",columns:this.transformNodeList($.columns,J),constraint:this.transformNode($.constraint,J),indexExpression:this.transformNode($.indexExpression,J),indexWhere:this.transformNode($.indexWhere,J),updates:this.transformNodeList($.updates,J),updateWhere:this.transformNode($.updateWhere,J),doNothing:$.doNothing}}transformOnDuplicateKey($,J){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList($.updates,J)}}transformCreateIndex($,J){return{kind:"CreateIndexNode",name:this.transformNode($.name,J),table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),unique:$.unique,using:this.transformNode($.using,J),ifNotExists:$.ifNotExists,where:this.transformNode($.where,J),nullsNotDistinct:$.nullsNotDistinct}}transformList($,J){return{kind:"ListNode",items:this.transformNodeList($.items,J)}}transformDropIndex($,J){return{kind:"DropIndexNode",name:this.transformNode($.name,J),table:this.transformNode($.table,J),ifExists:$.ifExists,cascade:$.cascade}}transformPrimaryKeyConstraint($,J){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList($.columns,J),name:this.transformNode($.name,J),deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformUniqueConstraint($,J){return{kind:"UniqueConstraintNode",columns:this.transformNodeList($.columns,J),name:this.transformNode($.name,J),nullsNotDistinct:$.nullsNotDistinct,deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformForeignKeyConstraint($,J){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList($.columns,J),references:this.transformNode($.references,J),name:this.transformNode($.name,J),onDelete:$.onDelete,onUpdate:$.onUpdate,deferrable:$.deferrable,initiallyDeferred:$.initiallyDeferred}}transformSetOperation($,J){return{kind:"SetOperationNode",operator:$.operator,expression:this.transformNode($.expression,J),all:$.all}}transformReferences($,J){return{kind:"ReferencesNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J),onDelete:$.onDelete,onUpdate:$.onUpdate}}transformCheckConstraint($,J){return{kind:"CheckConstraintNode",expression:this.transformNode($.expression,J),name:this.transformNode($.name,J)}}transformWith($,J){return{kind:"WithNode",expressions:this.transformNodeList($.expressions,J),recursive:$.recursive}}transformCommonTableExpression($,J){return{kind:"CommonTableExpressionNode",name:this.transformNode($.name,J),materialized:$.materialized,expression:this.transformNode($.expression,J)}}transformCommonTableExpressionName($,J){return{kind:"CommonTableExpressionNameNode",table:this.transformNode($.table,J),columns:this.transformNodeList($.columns,J)}}transformHaving($,J){return{kind:"HavingNode",having:this.transformNode($.having,J)}}transformCreateSchema($,J){return{kind:"CreateSchemaNode",schema:this.transformNode($.schema,J),ifNotExists:$.ifNotExists}}transformDropSchema($,J){return{kind:"DropSchemaNode",schema:this.transformNode($.schema,J),ifExists:$.ifExists,cascade:$.cascade}}transformAlterTable($,J){return{kind:"AlterTableNode",table:this.transformNode($.table,J),renameTo:this.transformNode($.renameTo,J),setSchema:this.transformNode($.setSchema,J),columnAlterations:this.transformNodeList($.columnAlterations,J),addConstraint:this.transformNode($.addConstraint,J),dropConstraint:this.transformNode($.dropConstraint,J),renameConstraint:this.transformNode($.renameConstraint,J),addIndex:this.transformNode($.addIndex,J),dropIndex:this.transformNode($.dropIndex,J)}}transformDropColumn($,J){return{kind:"DropColumnNode",column:this.transformNode($.column,J),ifExists:$.ifExists}}transformRenameColumn($,J){return{kind:"RenameColumnNode",column:this.transformNode($.column,J),renameTo:this.transformNode($.renameTo,J)}}transformAlterColumn($,J){return{kind:"AlterColumnNode",column:this.transformNode($.column,J),dataType:this.transformNode($.dataType,J),dataTypeExpression:this.transformNode($.dataTypeExpression,J),setDefault:this.transformNode($.setDefault,J),dropDefault:$.dropDefault,setNotNull:$.setNotNull,dropNotNull:$.dropNotNull}}transformModifyColumn($,J){return{kind:"ModifyColumnNode",column:this.transformNode($.column,J)}}transformAddConstraint($,J){return{kind:"AddConstraintNode",constraint:this.transformNode($.constraint,J)}}transformDropConstraint($,J){return{kind:"DropConstraintNode",constraintName:this.transformNode($.constraintName,J),ifExists:$.ifExists,modifier:$.modifier}}transformRenameConstraint($,J){return{kind:"RenameConstraintNode",oldName:this.transformNode($.oldName,J),newName:this.transformNode($.newName,J)}}transformCreateView($,J){return{kind:"CreateViewNode",name:this.transformNode($.name,J),temporary:$.temporary,orReplace:$.orReplace,ifNotExists:$.ifNotExists,materialized:$.materialized,columns:this.transformNodeList($.columns,J),as:this.transformNode($.as,J)}}transformRefreshMaterializedView($,J){return{kind:"RefreshMaterializedViewNode",name:this.transformNode($.name,J),concurrently:$.concurrently,withNoData:$.withNoData}}transformDropView($,J){return{kind:"DropViewNode",name:this.transformNode($.name,J),ifExists:$.ifExists,materialized:$.materialized,cascade:$.cascade}}transformGenerated($,J){return{kind:"GeneratedNode",byDefault:$.byDefault,always:$.always,identity:$.identity,stored:$.stored,expression:this.transformNode($.expression,J)}}transformDefaultValue($,J){return{kind:"DefaultValueNode",defaultValue:this.transformNode($.defaultValue,J)}}transformOn($,J){return{kind:"OnNode",on:this.transformNode($.on,J)}}transformSelectModifier($,J){return{kind:"SelectModifierNode",modifier:$.modifier,rawModifier:this.transformNode($.rawModifier,J),of:this.transformNodeList($.of,J)}}transformCreateType($,J){return{kind:"CreateTypeNode",name:this.transformNode($.name,J),enum:this.transformNode($.enum,J)}}transformDropType($,J){return{kind:"DropTypeNode",name:this.transformNode($.name,J),additionalNames:this.transformNodeList($.additionalNames,J),cascade:$.cascade,ifExists:$.ifExists}}transformExplain($,J){return{kind:"ExplainNode",format:$.format,options:this.transformNode($.options,J)}}transformSchemableIdentifier($,J){return{kind:"SchemableIdentifierNode",schema:this.transformNode($.schema,J),identifier:this.transformNode($.identifier,J)}}transformAggregateFunction($,J){return{kind:"AggregateFunctionNode",func:$.func,aggregated:this.transformNodeList($.aggregated,J),distinct:$.distinct,orderBy:this.transformNode($.orderBy,J),withinGroup:this.transformNode($.withinGroup,J),filter:this.transformNode($.filter,J),over:this.transformNode($.over,J)}}transformOver($,J){return{kind:"OverNode",orderBy:this.transformNode($.orderBy,J),partitionBy:this.transformNode($.partitionBy,J)}}transformPartitionBy($,J){return{kind:"PartitionByNode",items:this.transformNodeList($.items,J)}}transformPartitionByItem($,J){return{kind:"PartitionByItemNode",partitionBy:this.transformNode($.partitionBy,J)}}transformBinaryOperation($,J){return{kind:"BinaryOperationNode",leftOperand:this.transformNode($.leftOperand,J),operator:this.transformNode($.operator,J),rightOperand:this.transformNode($.rightOperand,J)}}transformUnaryOperation($,J){return{kind:"UnaryOperationNode",operator:this.transformNode($.operator,J),operand:this.transformNode($.operand,J)}}transformUsing($,J){return{kind:"UsingNode",tables:this.transformNodeList($.tables,J)}}transformFunction($,J){return{kind:"FunctionNode",func:$.func,arguments:this.transformNodeList($.arguments,J)}}transformCase($,J){return{kind:"CaseNode",value:this.transformNode($.value,J),when:this.transformNodeList($.when,J),else:this.transformNode($.else,J),isStatement:$.isStatement}}transformWhen($,J){return{kind:"WhenNode",condition:this.transformNode($.condition,J),result:this.transformNode($.result,J)}}transformJSONReference($,J){return{kind:"JSONReferenceNode",reference:this.transformNode($.reference,J),traversal:this.transformNode($.traversal,J)}}transformJSONPath($,J){return{kind:"JSONPathNode",inOperator:this.transformNode($.inOperator,J),pathLegs:this.transformNodeList($.pathLegs,J)}}transformJSONPathLeg($,J){return{kind:"JSONPathLegNode",type:$.type,value:$.value}}transformJSONOperatorChain($,J){return{kind:"JSONOperatorChainNode",operator:this.transformNode($.operator,J),values:this.transformNodeList($.values,J)}}transformTuple($,J){return{kind:"TupleNode",values:this.transformNodeList($.values,J)}}transformMergeQuery($,J){return{kind:"MergeQueryNode",into:this.transformNode($.into,J),using:this.transformNode($.using,J),whens:this.transformNodeList($.whens,J),with:this.transformNode($.with,J),top:this.transformNode($.top,J),endModifiers:this.transformNodeList($.endModifiers,J),output:this.transformNode($.output,J),returning:this.transformNode($.returning,J)}}transformMatched($,J){return{kind:"MatchedNode",not:$.not,bySource:$.bySource}}transformAddIndex($,J){return{kind:"AddIndexNode",name:this.transformNode($.name,J),columns:this.transformNodeList($.columns,J),unique:$.unique,using:this.transformNode($.using,J),ifNotExists:$.ifNotExists}}transformCast($,J){return{kind:"CastNode",expression:this.transformNode($.expression,J),dataType:this.transformNode($.dataType,J)}}transformFetch($,J){return{kind:"FetchNode",rowCount:this.transformNode($.rowCount,J),modifier:$.modifier}}transformTop($,J){return{kind:"TopNode",expression:$.expression,modifiers:$.modifiers}}transformOutput($,J){return{kind:"OutputNode",selections:this.transformNodeList($.selections,J)}}transformAlterType($,J){return{kind:"AlterTypeNode",name:this.transformNode($.name,J),addValue:this.transformNode($.addValue,J),renameTo:this.transformNode($.renameTo,J),renameValue:this.transformNode($.renameValue,J),setSchema:this.transformNode($.setSchema,J)}}transformAddValue($,J){return{kind:"AddValueNode",value:this.transformNode($.value,J),ifNotExists:$.ifNotExists,isBefore:$.isBefore,neighborValue:this.transformNode($.neighborValue,J)}}transformRenameValue($,J){return{kind:"RenameValueNode",oldValue:this.transformNode($.oldValue,J),newValue:this.transformNode($.newValue,J)}}transformDataType($,J){return $}transformSelectAll($,J){return $}transformIdentifier($,J){return $}transformValue($,J){return $}transformPrimitiveValueList($,J){return $}transformOperator($,J){return $}transformDefaultInsertValue($,J){return $}transformOrAction($,J){return $}transformCollate($,J){return $}}var hU=D(()=>{G$()});function f_$($){return L6($)&&C1($.kind)}var v_$=D(()=>{G$()});function h_$($){return f_$($)&&BD0[$.kind]===!0}var BD0;var g_$=D(()=>{v_$();BD0={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}});var DD0,o$$;var u_$=D(()=>{AY();k6();QD();Ky();hU();g_$();sj();XD();Uy();G$();DD0=P({json_agg:!0,to_json:!0});o$$=class o$$ extends xX{#$;#J=new Set;#X=new Set;constructor($){super();this.#$=$}transformNodeImpl($,J){if(!h_$($))return super.transformNodeImpl($,J);let X=this.#G($);for(let W of X)this.#X.add(W);let Q=this.#Y($);for(let W of Q)this.#J.add(W);let Y=super.transformNodeImpl($,J);for(let W of Q)this.#J.delete(W);for(let W of X)this.#X.delete(W);return Y}transformSchemableIdentifier($,J){let X=super.transformSchemableIdentifier($,J);if(X.schema||!this.#J.has($.identifier.name))return X;return{...X,schema:U1.create(this.#$)}}transformReferences($,J){let X=super.transformReferences($,J);if(X.table.table.schema)return X;return{...X,table:S7.createWithSchema(this.#$,X.table.table.identifier.name)}}transformAggregateFunction($,J){return{...super.transformAggregateFunction({...$,aggregated:[]},J),aggregated:this.#Q($,J,"aggregated")}}transformFunction($,J){return{...super.transformFunction({...$,arguments:[]},J),arguments:this.#Q($,J,"arguments")}}transformSelectModifier($,J){return{...super.transformSelectModifier({...$,of:void 0},J),of:$.of?.map((X)=>S7.is(X)&&!X.table.schema?{...X,table:this.transformIdentifier(X.table.identifier,J)}:this.transformNode(X,J))}}#Q($,J,X){return DD0[$.func]?$[X].map((Q)=>!S7.is(Q)||Q.table.schema?this.transformNode(Q,J):{...Q,table:this.transformIdentifier(Q.table.identifier,J)}):this.transformNodeList($[X],J)}#Y($){let J=new Set;if("name"in $&&$.name&&K5.is($.name))this.#Z($.name,J);if("from"in $&&$.from)for(let X of $.from.froms)this.#W(X,J);if("into"in $&&$.into)this.#W($.into,J);if("table"in $&&$.table)this.#W($.table,J);if("joins"in $&&$.joins)for(let X of $.joins)this.#W(X.table,J);if("using"in $&&$.using)if(MY.is($.using))this.#W($.using.table,J);else this.#W($.using,J);return J}#G($){let J=new Set;if("with"in $&&$.with)this.#j($.with,J);return J}#W($,J){if(S7.is($))return this.#Z($.table,J);if(LJ.is($)&&S7.is($.node))return this.#Z($.node.table,J);if(Vy.is($)){for(let X of $.items)this.#W(X,J);return}if(jM.is($)){for(let X of $.tables)this.#W(X,J);return}}#Z($,J){let X=$.identifier.name;if(!this.#J.has(X)&&!this.#X.has(X))J.add(X)}#j($,J){for(let X of $.expressions){let Q=X.name.table.table.identifier.name;if(!this.#X.has(Q))J.add(Q)}}}});class IY{#$;constructor($){this.#$=new o$$($)}transformQuery($){return this.#$.transformNode($.node,$.queryId)}async transformResult($){return $.result}}var wD=D(()=>{u_$()});var m_$;var r$$=D(()=>{G$();m_$=P({is($){return $.kind==="MatchedNode"},create($,J=!1){return P({kind:"MatchedNode",not:$,bySource:J})}})});function t$$($,J,X){return x7.create(UD([m_$.create(!$.isMatched,$.bySource),...J&&J.length>0?[J.length===3&&X?O9(J[0],J[1],J[2]):d6(J)]:[]],"and",!1))}function ND($){if(C1($))return v4.create([$],[]);if(x6($))return $.toOperationNode();return $}var l_$=D(()=>{r$$();i5();PX();GL();G$();IX()});class z5{#$;#J;#X;constructor(){this.#$=new Promise(($,J)=>{this.#X=J,this.#J=$})}get promise(){return this.#$}resolve=($)=>{this.#J?.($),this.#J=this.#X=void 0};reject=($)=>{this.#X?.($),this.#X=this.#J=void 0}}async function AD($,J){let X=new z5,Q=new z5;return $.provideConnection(async(Y)=>{return X.resolve(Y),await Q.promise},J).catch((Y)=>X.reject(Y)),P({connection:await X.promise,release:Q.resolve})}var a$$=D(()=>{G$()});function c_$($="ignore query",J,X){if($==="ignore query")return;if($==="cancel query"){let Q=J.cancelQuery;if(!Q)p_$($,J.killSession?"kill session":void 0);return Q.bind(J)}if($==="kill session"){let Q=J.killSession;if(!Q)p_$($,J.cancelQuery?"cancel query":void 0);return Q.bind(J)}throw X(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${$}"`)}function p_$($,J){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${$}". Use "ignore query"${J?` or "${J}"`:""} instead.`)}function QV($,J,X){if($?.aborted)X?.(),gU($.reason,J)}function gU($,J){throw FD0($,J),$}async function uU($,J,X,Q){if(!J)return $;QV(J,`before ${X}`,Q);let{promise:Y,resolve:W}=new z5,G=()=>W(bX);J.addEventListener("abort",G);try{QV(J,`before ${X}`,Q);let Z=await Promise.race([$,Y]);if(Z!==bX)return Z;Q?.(),gU(J.reason,`during ${X}`)}finally{J.removeEventListener("abort",G),W(bX)}}function YG($){return(J)=>console.error(`\`${$}\` failed in the background after abortion: ${aA$(J)}`)}function FD0($,J){if($!==null&&typeof $==="object"&&!Object.isFrozen($))Object.defineProperty($,"__kysely_timing__",{configurable:!0,enumerable:!1,value:J,writable:!1})}var bX;var Ny=D(()=>{G$();bX={}});class FM{#$;constructor($=qD0){this.#$=$}get plugins(){return this.#$}transformQuery($,J){for(let X of this.#$){let Q=X.transformQuery({node:$,queryId:J});if(Q.kind===$.kind)$=Q;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${$.kind}`,`but it returned a ${Q.kind}`].join(" "))}return $}async executeQuery($,J){let{inflightQueryAbortStrategy:X="ignore query",signal:Q}=J||{};if(!Q){let K=await this.provideConnection(async(z)=>{return await z.executeQuery($)},J);return await this.#J(K,$.queryId)}QV(Q,"before query execution"),J=P({signal:Q});let{connection:Y,release:W}=await AD(this,J),G=this.provideConnection.bind(this),{promise:Z,resolve:j}=new z5,V=()=>j(bX);Q.addEventListener("abort",V,{once:!0});try{QV(Q,"before query execution",W);let K=c_$(X,Y,W);if(K&&Y.collectSessionInfo){QV(Q,"before query execution",W);let B=Y.collectSessionInfo();if(await Promise.race([Z,B]).catch((A)=>{throw W(),A})===bX)B.catch(YG("collectSessionInfo")).finally(W),gU(Q.reason,"before query execution")}let z=Y.executeQuery($,J),L=await Promise.race([Z,z]).catch((B)=>{throw W(),B});if(L===bX)Promise.allSettled([z.catch(YG("query")),K?.(G).catch(YG("inflightQueryAbortHandler"))]).finally(W),gU(Q.reason,"during query execution");else W();let H=this.#J(L,$.queryId,J),O=await Promise.race([Z,H]);if(O===bX)H.catch(YG("plugins.transformResult")),gU(Q.reason,"during result transformation");return O}finally{j(bX),Q.removeEventListener("abort",V)}}async*stream($,J,X){let{signal:Q}=X||{};if(!Q){let{connection:L,release:H}=await AD(this);try{for await(let O of L.streamQuery($,J))yield await this.#J(O,$.queryId,X)}finally{H()}return}X=P({signal:Q}),QV(Q,"before connection acquisition");let{connection:Y,release:W}=await AD(this,X),{promise:G,resolve:Z}=new z5,j=()=>Z(bX);Q.addEventListener("abort",j,{once:!0});let V,K;QV(Q,"before query streaming",W);let{queryId:z}=$;try{V=Y.streamQuery($,J,X);while(!0){QV(Q,"during query streaming");let L=V.next(),H=await Promise.race([G,L]);if(H===bX)K=L.catch(YG("iterator.next")),gU(Q.reason,"during query streaming");if(H.done)break;let O=this.#J(H.value,z,X),B=await Promise.race([G,O]);if(B===bX)K=O.catch(YG("plugins.transformResult")),gU(Q.reason,"during result transformation");yield B}}finally{Z(bX),Q.removeEventListener("abort",j);let L=(V?.return?.()||Promise.resolve()).finally(()=>K).finally(W);if(!K)await L}}async#J($,J,X){let{signal:Q}=X||{};for(let Y of this.#$)$=await Y.transformResult(P({queryId:J,result:$,signal:Q}));return $}}var qD0;var s$$=D(()=>{G$();a$$();Ny();qD0=P([])});var _D,mU;var MD=D(()=>{s$$();_D=class _D extends FM{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin($){return new _D([...this.plugins,$])}withPlugins($){return new _D([...this.plugins,...$])}withPluginAtFront($){return new _D([$,...this.plugins])}withoutPlugins(){return new _D([])}};mU=new _D});class e$${numChangedRows;constructor($){this.numChangedRows=$}}class YV{#$;constructor($){this.#$=P($)}modifyEnd($){return new YV({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,J){return new YV({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}using(...$){return new b7({...this.#$,queryNode:kX.cloneWithUsing(this.#$.queryNode,vU("Using",$))})}returning($){return new YV({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new YV({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new YV({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new YV({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}}class b7{#$;constructor($){this.#$=P($)}modifyEnd($){return new b7({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,J){return new b7({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}whenMatched(){return this.#J([])}whenMatchedAnd(...$){return this.#J($)}whenMatchedAndRef($,J,X){return this.#J([$,J,X],!0)}#J($,J){return new $0$({...this.#$,queryNode:kX.cloneWithWhen(this.#$.queryNode,t$$({isMatched:!0},$,J))})}whenNotMatched(){return this.#X([])}whenNotMatchedAnd(...$){return this.#X($)}whenNotMatchedAndRef($,J,X){return this.#X([$,J,X],!0)}whenNotMatchedBySource(){return this.#X([],!1,!0)}whenNotMatchedBySourceAnd(...$){return this.#X($,!1,!0)}whenNotMatchedBySourceAndRef($,J,X){return this.#X([$,J,X],!0,!0)}returning($){return new b7({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,u9($))})}returningAll($){return new b7({...this.#$,queryNode:F0.cloneWithReturning(this.#$.queryNode,DJ($))})}output($){return new b7({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,u9($))})}outputAll($){return new b7({...this.#$,queryNode:F0.cloneWithOutput(this.#$.queryNode,DJ($))})}#X($,J=!1,X=!1){let Q={...this.#$,queryNode:kX.cloneWithWhen(this.#$.queryNode,t$$({isMatched:!1,bySource:X},$,J))};return new(X?$0$:n_$)(Q)}$call($){return $(this)}$if($,J){if($)return J(this);return new b7({...this.#$})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile(),X=await this.#$.executor.executeQuery(J,$),{adapter:Q}=this.#$.executor,Y=J.query;if(Y.returning&&Q.supportsReturning||Y.output&&Q.supportsOutput)return X.rows;return[new e$$(X.numAffectedRows)]}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}}class $0${#$;constructor($){this.#$=P($)}thenDelete(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("delete"))})}thenDoNothing(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("do nothing"))})}thenUpdate($){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND($(new FD({queryId:this.#$.queryId,executor:mU,queryNode:JG.createWithoutTable()}))))})}thenUpdateSet(...$){return this.thenUpdate((J)=>J.set(...$))}}class n_${#$;constructor($){this.#$=P($)}thenDoNothing(){return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND("do nothing"))})}thenInsertValues($){let[J,X]=Ly($);return new b7({...this.#$,queryNode:kX.cloneWithThen(this.#$.queryNode,ND(k8.cloneWith(k8.createWithoutInto(),{columns:J,values:X})))})}}var J0$=D(()=>{WL();UM();PQ();zD();I$$();OM();l_$();fU();BD();MD();G$();VL();Dy()});class WG{#$;constructor($){this.#$=P($)}selectFrom($){return qM({queryId:M1(),executor:this.#$.executor,queryNode:H6.createFrom(CY($),this.#$.withNode)})}selectNoFrom($){return qM({queryId:M1(),executor:this.#$.executor,queryNode:H6.cloneWithSelections(H6.create(this.#$.withNode),u9($))})}insertInto($){return new y6({queryId:M1(),executor:this.#$.executor,queryNode:k8.create(e4($),this.#$.withNode)})}replaceInto($){return new y6({queryId:M1(),executor:this.#$.executor,queryNode:k8.create(e4($),this.#$.withNode,!0)})}deleteFrom($){return new By({queryId:M1(),executor:this.#$.executor,queryNode:yU.create(CY($),this.#$.withNode)})}updateTable($){return new FD({queryId:M1(),executor:this.#$.executor,queryNode:JG.create(CY($),this.#$.withNode)})}mergeInto($){return new YV({queryId:M1(),executor:this.#$.executor,queryNode:kX.create(X0$($),this.#$.withNode)})}with($,J){let X=n$$($,J);return new WG({...this.#$,withNode:this.#$.withNode?DM.cloneWithExpression(this.#$.withNode,X):DM.create(X)})}withRecursive($,J){let X=n$$($,J);return new WG({...this.#$,withNode:this.#$.withNode?DM.cloneWithExpression(this.#$.withNode,X):DM.create(X,{recursive:!0})})}withPlugin($){return new WG({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new WG({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new WG({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}}var Ay=D(()=>{_y();g$$();m$$();Dy();VM();WL();ZL();zD();IJ();k_$();d$$();SY();wD();G$();fU();J0$();UM()});function x_$(){return new WG({executor:mU})}function d_$($,J){return new LD({joinNode:MY.create($,UL(J))})}function i_$(){return new HD({overNode:GM.create()})}var qy=D(()=>{QD();jy();E$$();N_$();Ay();MD();IJ()});function vU($,J){if(J.length===3)return ND0($,J[0],J[1],J[2]);else if(J.length===2)return wD0($,J[0],J[1]);else if(J.length===1)return AD0($,J[0]);else throw Error("not implemented")}function wD0($,J,X){return X(d_$($,J)).toOperationNode()}function ND0($,J,X,Q){return MY.createWithOn($,UL(J),O9(X,"=",Q))}function AD0($,J){return MY.create($,UL(J))}var OM=D(()=>{QD();IX();qy();IJ()});var o_$;var Q0$=D(()=>{G$();o_$=P({is($){return $.kind==="OffsetNode"},create($){return P({kind:"OffsetNode",offset:$})}})});var r_$;var Y0$=D(()=>{G$();r_$=P({is($){return $.kind==="GroupByItemNode"},create($){return P({kind:"GroupByItemNode",groupBy:$})}})});function t_$($){return $=a4($)?$(EY()):$,JV($).map(r_$.create)}var a_$=D(()=>{Y0$();jL();G$();OJ()});var My;var Ry=D(()=>{G$();My=P({is($){return $.kind==="SetOperationNode"},create($,J,X){return P({kind:"SetOperationNode",operator:$,expression:J,all:X})}})});function zL($,J,X){if(a4(J))J=J(W0$());if(!KJ(J))J=[J];return J.map((Q)=>My.create($,BJ(Q),X))}var s_$=D(()=>{jL();Ry();G$();EQ()});class O6{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}or(...$){return new Ey(_Y.create(this.#$,d6($)))}and(...$){return new Py(I7.create(this.#$,d6($)))}$castTo(){return new O6(this.#$)}$notNull(){return new O6(this.#$)}toOperationNode(){return this.#$}}class Ty{#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}class Ey{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}or(...$){return new Ey(_Y.create(this.#$,d6($)))}$castTo(){return new Ey(this.#$)}toOperationNode(){return SX.create(this.#$)}}class Py{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new Ty(this,$)}and(...$){return new Py(I7.create(this.#$,d6($)))}$castTo(){return new Py(this.#$)}toOperationNode(){return SX.create(this.#$)}}var RD=D(()=>{AY();kU();k6();i5();JL();KD();IX()});var e_$;var G0$=D(()=>{G$();CX();e_$=P({is($){return $.kind==="FetchNode"},create($,J){return{kind:"FetchNode",rowCount:n6.create($),modifier:J}}})});function $M$($,J){if(!wY($)&&!SU($))throw Error(`Invalid fetch row count: ${$}`);if(!_D0(J))throw Error(`Invalid fetch modifier: ${J}`);return e_$.create($,J)}function _D0($){return $==="only"||$==="with ties"}var JM$=D(()=>{G0$();G$()});class Z0${#$;constructor($){this.#$=P($)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...$){return new j4({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,d6($))})}whereRef($,J,X){return new j4({...this.#$,queryNode:F0.cloneWithWhere(this.#$.queryNode,O9($,J,X))})}having(...$){return new j4({...this.#$,queryNode:H6.cloneWithHaving(this.#$.queryNode,d6($))})}havingRef($,J,X){return new j4({...this.#$,queryNode:H6.cloneWithHaving(this.#$.queryNode,O9($,J,X))})}select($){return new j4({...this.#$,queryNode:H6.cloneWithSelections(this.#$.queryNode,u9($))})}distinctOn($){return new j4({...this.#$,queryNode:H6.cloneWithDistinctOn(this.#$.queryNode,JV($))})}modifyFront($){return new j4({...this.#$,queryNode:H6.cloneWithFrontModifier(this.#$.queryNode,aW.createWithExpression($.toOperationNode()))})}modifyEnd($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.createWithExpression($.toOperationNode()))})}distinct(){return new j4({...this.#$,queryNode:H6.cloneWithFrontModifier(this.#$.queryNode,aW.create("Distinct"))})}forUpdate($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForUpdate",$?t_($).map(e4):void 0))})}forShare($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForShare",$?t_($).map(e4):void 0))})}forKeyShare($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForKeyShare",$?t_($).map(e4):void 0))})}forNoKeyUpdate($){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("ForNoKeyUpdate",$?t_($).map(e4):void 0))})}skipLocked(){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("SkipLocked"))})}noWait(){return new j4({...this.#$,queryNode:F0.cloneWithEndModifier(this.#$.queryNode,aW.create("NoWait"))})}selectAll($){return new j4({...this.#$,queryNode:H6.cloneWithSelections(this.#$.queryNode,DJ($))})}innerJoin(...$){return this.#J("InnerJoin",$)}leftJoin(...$){return this.#J("LeftJoin",$)}rightJoin(...$){return this.#J("RightJoin",$)}fullJoin(...$){return this.#J("FullJoin",$)}crossJoin(...$){return this.#J("CrossJoin",$)}innerJoinLateral(...$){return this.#J("LateralInnerJoin",$)}leftJoinLateral(...$){return this.#J("LateralLeftJoin",$)}crossJoinLateral(...$){return this.#J("LateralCrossJoin",$)}crossApply(...$){return this.#J("CrossApply",$)}outerApply(...$){return this.#J("OuterApply",$)}#J($,J){return new j4({...this.#$,queryNode:F0.cloneWithJoin(this.#$.queryNode,vU($,J))})}orderBy(...$){return new j4({...this.#$,queryNode:F0.cloneWithOrderByItems(this.#$.queryNode,TX($))})}groupBy($){return new j4({...this.#$,queryNode:H6.cloneWithGroupByItems(this.#$.queryNode,t_$($))})}limit($){return new j4({...this.#$,queryNode:H6.cloneWithLimit(this.#$.queryNode,DD.create(b6($)))})}offset($){return new j4({...this.#$,queryNode:H6.cloneWithOffset(this.#$.queryNode,o_$.create(b6($)))})}fetch($,J="only"){return new j4({...this.#$,queryNode:H6.cloneWithFetch(this.#$.queryNode,$M$($,J))})}top($,J){return new j4({...this.#$,queryNode:F0.cloneWithTop(this.#$.queryNode,TY($,J))})}union($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("union",$,!1))})}unionAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("union",$,!0))})}intersect($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("intersect",$,!1))})}intersectAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("intersect",$,!0))})}except($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("except",$,!1))})}exceptAll($){return new j4({...this.#$,queryNode:H6.cloneWithSetOperations(this.#$.queryNode,zL("except",$,!0))})}as($){return new XM$(this,$)}clearSelect(){return new j4({...this.#$,queryNode:H6.cloneWithoutSelections(this.#$.queryNode)})}clearWhere(){return new j4({...this.#$,queryNode:F0.cloneWithoutWhere(this.#$.queryNode)})}clearLimit(){return new j4({...this.#$,queryNode:H6.cloneWithoutLimit(this.#$.queryNode)})}clearOffset(){return new j4({...this.#$,queryNode:H6.cloneWithoutOffset(this.#$.queryNode)})}clearOrderBy(){return new j4({...this.#$,queryNode:F0.cloneWithoutOrderBy(this.#$.queryNode)})}clearGroupBy(){return new j4({...this.#$,queryNode:H6.cloneWithoutGroupBy(this.#$.queryNode)})}$call($){return $(this)}$if($,J){if($)return J(this);return new j4({...this.#$})}$castTo(){return new j4(this.#$)}$narrowType(){return new j4(this.#$)}$assertType(){return new j4(this.#$)}$asTuple(){return new O6(this.toOperationNode())}$asScalar(){return new O6(this.toOperationNode())}withPlugin($){return new j4({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){let J=this.compile();return(await this.#$.executor.executeQuery(J,$)).rows}async executeTakeFirst($){let[J]=await this.execute($);return J}async executeTakeFirstOrThrow($){if(typeof $==="function")$={errorConstructor:$};let J=await this.executeTakeFirst($);if(J===void 0){let X=$?.errorConstructor??PY;throw XG(X)?new X(this.toOperationNode()):X(this.toOperationNode())}return J}async*stream($){if(typeof $!=="object")$={chunkSize:$};let J=this.compile(),X=this.#$.executor.stream(J,$.chunkSize??100,$);for await(let Q of X)yield*Q.rows}async explain($,J){return await new j4({...this.#$,queryNode:F0.cloneWithExplain(this.#$.queryNode,$,J)}).execute()}}function qM($){return new Z0$($)}class XM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return LJ.create(this.#$.toOperationNode(),U1.create(this.#J))}}var j4;var _y=D(()=>{AY();X$$();OM();IJ();fU();OJ();ZL();PQ();XL();HM();Q0$();G$();a_$();VL();k6();s_$();IX();RD();$G();JM$();BD();j4=Z0$});var GG;var Cy=D(()=>{G$();KM();WM();GG=P({is($){return $.kind==="AggregateFunctionNode"},create($,J=[]){return P({kind:"AggregateFunctionNode",func:$,aggregated:J})},cloneWithDistinct($){return P({...$,distinct:!0})},cloneWithOrderBy($,J,X=!1){let Q=X?"withinGroup":"orderBy";return P({...$,[Q]:$[Q]?XV.cloneWithItems($[Q],J):XV.create(J)})},cloneWithFilter($,J){return P({...$,filter:$.filter?SJ.cloneWithOperation($.filter,"And",J):SJ.create(J)})},cloneWithOrFilter($,J){return P({...$,filter:$.filter?SJ.cloneWithOperation($.filter,"Or",J):SJ.create(J)})},cloneWithOver($,J){return P({...$,over:J})}})});var j0$;var V0$=D(()=>{G$();j0$=P({is($){return $.kind==="FunctionNode"},create($,J){return P({kind:"FunctionNode",func:$,arguments:J})}})});class y7{#$;constructor($){this.#$=P($)}get expressionType(){return}as($){return new QM$(this,$)}distinct(){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithDistinct(this.#$.aggregateFunctionNode)})}orderBy(...$){return new y7({...this.#$,aggregateFunctionNode:F0.cloneWithOrderByItems(this.#$.aggregateFunctionNode,TX($))})}clearOrderBy(){return new y7({...this.#$,aggregateFunctionNode:F0.cloneWithoutOrderBy(this.#$.aggregateFunctionNode)})}withinGroupOrderBy(...$){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithOrderBy(this.#$.aggregateFunctionNode,TX($),!0)})}filterWhere(...$){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithFilter(this.#$.aggregateFunctionNode,d6($))})}filterWhereRef($,J,X){return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithFilter(this.#$.aggregateFunctionNode,O9($,J,X))})}over($){let J=i_$();return new y7({...this.#$,aggregateFunctionNode:GG.cloneWithOver(this.#$.aggregateFunctionNode,($?$(J):J).toOperationNode())})}$call($){return $(this)}$castTo(){return new y7(this.#$)}$notNull(){return new y7(this.#$)}toOperationNode(){return this.#$.aggregateFunctionNode}}class QM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),U1.create(this.#J))}}var K0$=D(()=>{G$();Cy();AY();k6();qy();IX();XL();PQ()});function Sy(){let $=(X,Q)=>{return new O6(j0$.create(X,JV(Q??[])))},J=(X,Q)=>{return new y7({aggregateFunctionNode:GG.create(X,Q?JV(Q):void 0)})};return Object.assign($,{agg:J,avg(X){return J("avg",[X])},coalesce(...X){return $("coalesce",X)},count(X){return J("count",[X])},countAll(X){return new y7({aggregateFunctionNode:GG.create("count",DJ(X))})},max(X){return J("max",[X])},min(X){return J("min",[X])},sum(X){return J("sum",[X])},any(X){return $("any",[X])},jsonAgg(X){return new y7({aggregateFunctionNode:GG.create("json_agg",[C1(X)?e4(X):X.toOperationNode()])})},toJson(X){return new O6(j0$.create("to_json",[C1(X)?e4(X):X.toOperationNode()]))}})}var Iy=D(()=>{RD();Cy();V0$();OJ();fU();K0$();G$();IJ()});var YM$;var U0$=D(()=>{G$();YM$=P({is($){return $.kind==="UnaryOperationNode"},create($,J){return P({kind:"UnaryOperationNode",operator:$,operand:J})}})});function WM$($,J){if(j_$($))return YM$.create(HJ.create($),P9(J));throw Error(`invalid unary operator ${JSON.stringify($)}`)}var GM$=D(()=>{ej();U0$();OJ()});var kJ;var wM=D(()=>{G$();GL();kJ=P({is($){return $.kind==="CaseNode"},create($){return P({kind:"CaseNode",value:$})},cloneWithWhen($,J){return P({...$,when:P($.when?[...$.when,J]:[J])})},cloneWithThen($,J){return P({...$,when:$.when?P([...$.when.slice(0,-1),x7.cloneWithResult($.when[$.when.length-1],J)]):void 0})},cloneWith($,J){return P({...$,...J})}})});class AM{#$;constructor($){this.#$=P($)}when(...$){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(d6($)))})}whenRef($,J,X){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(O9($,J,X)))})}}class NM{#$;constructor($){this.#$=P($)}then($){return new z0$({...this.#$,node:kJ.cloneWithThen(this.#$.node,Gy($)?YM($):b6($))})}thenRef($){return new z0$({...this.#$,node:kJ.cloneWithThen(this.#$.node,P9($))})}}class z0${#$;constructor($){this.#$=P($)}when(...$){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(d6($)))})}whenRef($,J,X){return new NM({...this.#$,node:kJ.cloneWithWhen(this.#$.node,x7.create(O9($,J,X)))})}else($){return new L0$({...this.#$,node:kJ.cloneWith(this.#$.node,{else:Gy($)?YM($):b6($)})})}elseRef($){return new L0$({...this.#$,node:kJ.cloneWith(this.#$.node,{else:P9($)})})}end(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!0}))}}class L0${#$;constructor($){this.#$=P($)}end(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new O6(kJ.cloneWith(this.#$.node,{isStatement:!0}))}}var ky=D(()=>{RD();G$();OJ();wM();GL();IX();$G()});var H0$;var O0$=D(()=>{G$();H0$=P({is($){return $.kind==="JSONPathLegNode"},create($,J){return P({kind:"JSONPathLegNode",type:$,value:J})}})});class MM{#$;constructor($){this.#$=$}at($){if(typeof $!=="number"&&typeof $!=="string"||typeof $==="number"&&!Number.isInteger($)||typeof $==="string"&&$!=="last"&&!MD0.test($))throw Error(`Unexpected index value in .at(...): ${$}`);return this.#J("ArrayLocation",$)}key($){return this.#J("Member",$)}#J($,J){if(ZD.is(this.#$))return new _M(ZD.cloneWithTraversal(this.#$,bU.is(this.#$.traversal)?bU.cloneWithLeg(this.#$.traversal,H0$.create($,J)):Yy.cloneWithValue(this.#$.traversal,n6.createImmediate(J))));return new _M(bU.cloneWithLeg(this.#$,H0$.create($,J)))}}class ZM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}var MD0,_M;var B0$=D(()=>{AY();k6();Wy();O0$();XM();Qy();i5();CX();MD0=/^#-\d+$/;_M=class _M extends MM{#$;constructor($){super($);this.#$=$}get expressionType(){return}as($){return new ZM$(this,$)}$castTo(){return new _M(this.#$)}$notNull(){return new _M(this.#$)}toOperationNode(){return this.#$}}});var D0$;var F0$=D(()=>{G$();D0$=P({is($){return $.kind==="TupleNode"},create($){return P({kind:"TupleNode",values:P($)})}})});function VM$($){return RD0[$]||ED0.some((J)=>J.test($))}var RD0,ED0,jM$;var q0$=D(()=>{G$();RD0=P({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),ED0=P([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),jM$=P({is($){return $.kind==="DataTypeNode"},create($){return P({kind:"DataTypeNode",dataType:$})}})});function kY($){if(x6($))return $.toOperationNode();if(VM$($))return jM$.create($);throw Error(`invalid column data type ${JSON.stringify($)}`)}var RM=D(()=>{q0$();i5()});var KM$;var w0$=D(()=>{G$();KM$=P({is($){return $.kind==="CastNode"},create($,J){return P({kind:"CastNode",expression:$,dataType:J})}})});function W0$($=mU){function J(Y,W,G){return new O6(Zy(Y,W,G))}function X(Y,W){return new O6(WM$(Y,W))}let Q=Object.assign(J,{fn:void 0,eb:void 0,selectFrom(Y){return qM({queryId:M1(),executor:$,queryNode:H6.createFrom(CY(Y))})},case(Y){return new AM({node:kJ.create(d5(Y)?void 0:P9(Y))})},ref(Y,W){if(d5(W))return new O6(k7(Y));return new MM(z_$(Y,W))},jsonPath(){return new MM(bU.create())},table(Y){return new O6(e4(Y))},val(Y){return new O6(b6(Y))},refTuple(...Y){return new O6(D0$.create(Y.map(P9)))},tuple(...Y){return new O6(D0$.create(Y.map(b6)))},lit(Y){return new O6(YM(Y))},unary:X,not(Y){return X("not",Y)},exists(Y){return X("exists",Y)},neg(Y){return X("-",Y)},between(Y,W,G){return new O6(sW.create(P9(Y),HJ.create("between"),I7.create(b6(W),b6(G))))},betweenSymmetric(Y,W,G){return new O6(sW.create(P9(Y),HJ.create("between symmetric"),I7.create(b6(W),b6(G))))},and(Y){if(KJ(Y))return new O6(UD(Y,"and"));return new O6(H$$(Y,"and"))},or(Y){if(KJ(Y))return new O6(UD(Y,"or"));return new O6(H$$(Y,"or"))},parens(...Y){let W=d6(Y);if(SX.is(W))return new O6(W);else return new O6(SX.create(W))},cast(Y,W){return new O6(KM$.create(P9(Y),kY(W)))}});return Q.fn=Sy(),Q.eb=Q,Q}function EY($){return W0$()}var jL=D(()=>{_y();ZL();IJ();SY();Iy();OJ();IX();KD();RD();ej();GM$();$G();MD();ky();wM();G$();B0$();e_();kU();F0$();XM();RM();w0$()});function BJ($){if(x6($))return $.toOperationNode();else if(a4($))return $(EY()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify($)}`)}function zy($){if(x6($))return $.toOperationNode();else if(a4($))return $(EY()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify($)}`)}function $V($){return ab($)||eA$($)||a4($)}var EQ=D(()=>{sb();i5();jL();G$()});class N0${#$;get table(){return this.#$}constructor($){this.#$=$}as($){return new UM$(this.#$,$)}}class UM${#$;#J;get table(){return this.#$}get alias(){return this.#J}constructor($,J){this.#$=$,this.#J=J}toOperationNode(){return LJ.create(e4(this.#$),U1.create(this.#J))}}function zM$($){return L6($)&&x6($)&&C1($.table)&&C1($.alias)}var xy=D(()=>{AY();k6();i5();IJ();G$()});function CY($){if(KJ($))return $.map((J)=>UL(J));else return[UL($)]}function UL($){if(C1($))return X0$($);else if(zM$($))return $.toOperationNode();else return zy($)}function X0$($){if($.includes(" as ")){let[X,Q]=$.split(" as ").map(LM$);return LJ.create(e4(X),U1.create(Q))}else return e4($)}function e4($){if($.includes(".")){let[X,Q]=$.split(".").map(LM$);return S7.createWithSchema(X,Q)}else return S7.create($)}function LM$($){return $.trim()}var IJ=D(()=>{G$();AY();XD();EQ();k6();xy()});var A0$;var _0$=D(()=>{G$();A0$=P({is($){return $.kind==="AddColumnNode"},create($){return P({kind:"AddColumnNode",column:$})}})});var Q8;var EM=D(()=>{G$();U5();Q8=P({is($){return $.kind==="ColumnDefinitionNode"},create($,J){return P({kind:"ColumnDefinitionNode",column:T4.create($),dataType:J})},cloneWithFrontModifier($,J){return P({...$,frontModifiers:$.frontModifiers?P([...$.frontModifiers,J]):[J]})},cloneWithEndModifier($,J){return P({...$,endModifiers:$.endModifiers?P([...$.endModifiers,J]):[J]})},cloneWith($,J){return P({...$,...J})}})});var PM;var by=D(()=>{G$();U5();PM=P({is($){return $.kind==="DropColumnNode"},create($){return P({kind:"DropColumnNode",column:T4.create($)})},cloneWith($,J){return P({...$,...J})}})});var M0$;var R0$=D(()=>{G$();U5();M0$=P({is($){return $.kind==="RenameColumnNode"},create($,J){return P({kind:"RenameColumnNode",column:T4.create($),renameTo:T4.create(J)})}})});var ED;var TM=D(()=>{G$();k6();ED=P({is($){return $.kind==="CheckConstraintNode"},create($,J){return P({kind:"CheckConstraintNode",expression:$,name:J?U1.create(J):void 0})}})});function OM$($){return C1($)&&HM$[$]}var HM$,Ic1,PD;var CM=D(()=>{G$();HM$=P({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),Ic1=Object.keys(HM$),PD=P({is($){return $.kind==="ReferencesNode"},create($,J){return P({kind:"ReferencesNode",table:$,columns:P([...J])})},cloneWithOnDelete($,J){return P({...$,onDelete:J})},cloneWithOnUpdate($,J){return P({...$,onUpdate:J})}})});function yy($){return x6($)?$.toOperationNode():n6.createImmediate($)}var E0$=D(()=>{i5();CX()});var SM;var P0$=D(()=>{G$();SM=P({is($){return $.kind==="GeneratedNode"},create($){return P({kind:"GeneratedNode",...$})},createWithExpression($){return P({kind:"GeneratedNode",always:!0,expression:$})},cloneWith($,J){return P({...$,...J})}})});var BM$;var T0$=D(()=>{G$();BM$=P({is($){return $.kind==="DefaultValueNode"},create($){return P({kind:"DefaultValueNode",defaultValue:$})}})});function TD($){if(OM$($))return $;throw Error(`invalid OnModifyForeignAction ${$}`)}var C0$=D(()=>{CM()});class Y8{#$;constructor($){this.#$=$}autoIncrement(){return new Y8(Q8.cloneWith(this.#$,{autoIncrement:!0}))}identity(){return new Y8(Q8.cloneWith(this.#$,{identity:!0}))}primaryKey(){return new Y8(Q8.cloneWith(this.#$,{primaryKey:!0}))}references($){let J=k7($);if(!J.table||YD.is(J.column))throw Error(`invalid call references('${$}'). The reference must have format table.column or schema.table.column`);return new Y8(Q8.cloneWith(this.#$,{references:PD.create(J.table,[J.column])}))}onDelete($){if(!this.#$.references)throw Error("on delete constraint can only be added for foreign keys");return new Y8(Q8.cloneWith(this.#$,{references:PD.cloneWithOnDelete(this.#$.references,TD($))}))}onUpdate($){if(!this.#$.references)throw Error("on update constraint can only be added for foreign keys");return new Y8(Q8.cloneWith(this.#$,{references:PD.cloneWithOnUpdate(this.#$.references,TD($))}))}unique(){return new Y8(Q8.cloneWith(this.#$,{unique:!0}))}notNull(){return new Y8(Q8.cloneWith(this.#$,{notNull:!0}))}unsigned(){return new Y8(Q8.cloneWith(this.#$,{unsigned:!0}))}defaultTo($){return new Y8(Q8.cloneWith(this.#$,{defaultTo:BM$.create(yy($))}))}check($){return new Y8(Q8.cloneWith(this.#$,{check:ED.create($.toOperationNode())}))}generatedAlwaysAs($){return new Y8(Q8.cloneWith(this.#$,{generated:SM.createWithExpression($.toOperationNode())}))}generatedAlwaysAsIdentity(){return new Y8(Q8.cloneWith(this.#$,{generated:SM.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new Y8(Q8.cloneWith(this.#$,{generated:SM.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#$.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new Y8(Q8.cloneWith(this.#$,{generated:SM.cloneWith(this.#$.generated,{stored:!0})}))}modifyFront($){return new Y8(Q8.cloneWithFrontModifier(this.#$,$.toOperationNode()))}nullsNotDistinct(){return new Y8(Q8.cloneWith(this.#$,{nullsNotDistinct:!0}))}ifNotExists(){return new Y8(Q8.cloneWith(this.#$,{ifNotExists:!0}))}modifyEnd($){return new Y8(Q8.cloneWithEndModifier(this.#$,$.toOperationNode()))}$call($){return $(this)}toOperationNode(){return this.#$}}var fy=D(()=>{TM();CM();$M();OJ();EM();E0$();P0$();T0$();C0$()});var S0$;var I0$=D(()=>{G$();S0$=P({is($){return $.kind==="ModifyColumnNode"},create($){return P({kind:"ModifyColumnNode",column:$})}})});var xY;var IM=D(()=>{G$();k6();CM();xY=P({is($){return $.kind==="ForeignKeyConstraintNode"},create($,J,X,Q){return P({kind:"ForeignKeyConstraintNode",columns:$,references:PD.create(J,X),name:Q?U1.create(Q):void 0})},cloneWith($,J){return P({...$,...J})}})});class bY{#$;constructor($){this.#$=$}onDelete($){return new bY(xY.cloneWith(this.#$,{onDelete:TD($)}))}onUpdate($){return new bY(xY.cloneWith(this.#$,{onUpdate:TD($)}))}deferrable(){return new bY(xY.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new bY(xY.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new bY(xY.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new bY(xY.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var vy=D(()=>{IM();C0$()});var CD;var hy=D(()=>{G$();CD=P({is($){return $.kind==="AddConstraintNode"},create($){return P({kind:"AddConstraintNode",constraint:$})}})});var ZG;var kM=D(()=>{j$$();G$();U5();k6();ZG=P({is($){return $.kind==="UniqueConstraintNode"},create($,J,X){if(C1($.at(0)))GD("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),$=$.map(T4.create);return P({kind:"UniqueConstraintNode",columns:P($),name:J?U1.create(J):void 0,nullsNotDistinct:X})},cloneWith($,J){return P({...$,...J})}})});var SD;var gy=D(()=>{G$();k6();SD=P({is($){return $.kind==="DropConstraintNode"},create($){return P({kind:"DropConstraintNode",constraintName:U1.create($)})},cloneWith($,J){return P({...$,...J})}})});var ID;var k0$=D(()=>{G$();U5();ID=P({is($){return $.kind==="AlterColumnNode"},create($,J,X){return P({kind:"AlterColumnNode",column:T4.create($),[J]:X})}})});class uy{#$;constructor($){this.#$=$}setDataType($){return new kD(ID.create(this.#$,"dataType",kY($)))}setDefault($){return new kD(ID.create(this.#$,"setDefault",yy($)))}dropDefault(){return new kD(ID.create(this.#$,"dropDefault",!0))}setNotNull(){return new kD(ID.create(this.#$,"setNotNull",!0))}dropNotNull(){return new kD(ID.create(this.#$,"dropNotNull",!0))}$call($){return $(this)}}class kD{#$;constructor($){this.#$=$}toOperationNode(){return this.#$}}var x0$=D(()=>{k0$();RM();E0$()});class lU{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var DM$=D(()=>{G$()});class WV{#$;constructor($){this.#$=P($)}onDelete($){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.onDelete($)})}onUpdate($){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.onUpdate($)})}deferrable(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.deferrable()})}notDeferrable(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new WV({...this.#$,constraintBuilder:this.#$.constraintBuilder.initiallyImmediate()})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(this.#$.constraintBuilder.toOperationNode())}),this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var FM$=D(()=>{hy();$L();G$()});class LL{#$;constructor($){this.#$=P($)}ifExists(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{ifExists:!0})})})}cascade(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.cloneWith(this.#$.node.dropConstraint,{modifier:"restrict"})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var qM$=D(()=>{$L();gy();G$()});var GV;var xM=D(()=>{G$();U5();k6();GV=P({is($){return $.kind==="PrimaryKeyConstraintNode"},create($,J){return P({kind:"PrimaryKeyConstraintNode",columns:P($.map(T4.create)),name:J?U1.create(J):void 0})},cloneWith($,J){return P({...$,...J})}})});var yX;var xD=D(()=>{G$();k6();yX=P({is($){return $.kind==="AddIndexNode"},create($){return P({kind:"AddIndexNode",name:U1.create($)})},cloneWith($,J){return P({...$,...J})},cloneWithColumns($,J){return P({...$,columns:[...$.columns||[],...J]})}})});class pU{#$;constructor($){this.#$=P($)}unique(){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWith(this.#$.node.addIndex,{unique:!0})})})}column($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,[C1($)?jD($):$.toOperationNode()])})})}columns($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,$.map((J)=>C1(J)?jD(J):J.toOperationNode()))})})}expression($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWithColumns(this.#$.node.addIndex,[$.toOperationNode()])})})}using($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.cloneWith(this.#$.node.addIndex,{using:v4.createWithSql($)})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var wM$=D(()=>{xD();$L();PX();OJ();G$()});class jG{#$;constructor($){this.#$=$}nullsNotDistinct(){return new jG(ZG.cloneWith(this.#$,{nullsNotDistinct:!0}))}deferrable(){return new jG(ZG.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new jG(ZG.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new jG(ZG.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new jG(ZG.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var b0$=D(()=>{kM()});class ZV{#$;constructor($){this.#$=$}deferrable(){return new ZV(GV.cloneWith(this.#$,{deferrable:!0}))}notDeferrable(){return new ZV(GV.cloneWith(this.#$,{deferrable:!1}))}initiallyDeferred(){return new ZV(GV.cloneWith(this.#$,{initiallyDeferred:!0}))}initiallyImmediate(){return new ZV(GV.cloneWith(this.#$,{initiallyDeferred:!1}))}$call($){return $(this)}toOperationNode(){return this.#$}}var y0$=D(()=>{xM()});class bM{#$;constructor($){this.#$=$}$call($){return $(this)}toOperationNode(){return this.#$}}var NM$;var f0$=D(()=>{G$();k6();NM$=P({is($){return $.kind==="RenameConstraintNode"},create($,J){return P({kind:"RenameConstraintNode",oldName:U1.create($),newName:U1.create(J)})}})});class yM{#$;constructor($){this.#$=P({...$})}ifExists(){return new yM({...this.#$,node:PM.cloneWith(this.#$.node,{ifExists:!0})})}toOperationNode(){return this.#$.node}}var v0$=D(()=>{by();G$()});class h0${#$;constructor($){this.#$=P($)}renameTo($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{renameTo:e4($)})})}setSchema($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{setSchema:U1.create($)})})}alterColumn($,J){let X=J(new uy($));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}dropColumn($,J=UJ){let X=J(new yM({node:PM.create($)}));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}renameColumn($,J){return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,M0$.create($,J))})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,A0$.create(Q.toOperationNode()))})}modifyColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,S0$.create(Q.toOperationNode()))})}addUniqueConstraint($,J,X=UJ){let Q=X(new jG(ZG.create(J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)),$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}addCheckConstraint($,J,X=UJ){let Q=X(new bM(ED.create(J.toOperationNode(),$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}addForeignKeyConstraint($,J,X,Q,Y=UJ){let W=Y(new bY(xY.create(J.map(T4.create),e4(X),Q.map(T4.create),$)));return new WV({...this.#$,constraintBuilder:W})}addPrimaryKeyConstraint($,J,X=UJ){let Q=X(new ZV(GV.create(J,$)));return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addConstraint:CD.create(Q.toOperationNode())})})}dropConstraint($){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropConstraint:SD.create($)})})}renameConstraint($,J){return new LL({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{renameConstraint:NM$.create($,J)})})}addIndex($){return new pU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{addIndex:yX.create($)})})}dropIndex($){return new lU({...this.#$,node:s4.cloneWithTableProps(this.#$.node,{dropIndex:IU.create($)})})}$call($){return $(this)}}class yY{#$;constructor($){this.#$=P($)}alterColumn($,J){let X=J(new uy($));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}dropColumn($,J=UJ){let X=J(new yM({node:PM.create($)}));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,X.toOperationNode())})}renameColumn($,J){return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,M0$.create($,J))})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,A0$.create(Q.toOperationNode()))})}modifyColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new yY({...this.#$,node:s4.cloneWithColumnAlteration(this.#$.node,S0$.create(Q.toOperationNode()))})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var g0$=D(()=>{_0$();$L();EM();by();k6();R0$();G$();fy();I0$();RM();vy();hy();kM();TM();IM();U5();IJ();gy();x0$();DM$();FM$();qM$();xM();a_();xD();wM$();b0$();y0$();f0$();EQ();v0$()});var fM;var u0$=D(()=>{hU();QL();CX();fM=class fM extends xX{transformPrimitiveValueList($){return eW.create($.values.map(n6.createImmediate))}transformValue($){return n6.createImmediate($.value)}}});class TQ{#$;constructor($){this.#$=P($)}ifNotExists(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{ifNotExists:!0})})}unique(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{unique:!0})})}nullsNotDistinct(){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{nullsNotDistinct:!0})})}on($){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{table:e4($)})})}column($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,[C1($)?jD($):$.toOperationNode()])})}columns($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,$.map((J)=>C1(J)?jD(J):J.toOperationNode()))})}expression($){return new TQ({...this.#$,node:NY.cloneWithColumns(this.#$.node,[$.toOperationNode()])})}using($){return new TQ({...this.#$,node:NY.cloneWith(this.#$.node,{using:v4.createWithSql($)})})}where(...$){let J=new fM;return new TQ({...this.#$,node:F0.cloneWithWhere(this.#$.node,J.transformNode(d6($),this.#$.queryId))})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var m0$=D(()=>{db();PX();OJ();IJ();G$();IX();PQ();u0$()});class my{#$;constructor($){this.#$=P($)}ifNotExists(){return new my({...this.#$,node:ib.cloneWith(this.#$.node,{ifNotExists:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var l0$=D(()=>{ob();G$()});function AM$($){if(sA$.includes($))return $;throw Error(`invalid OnCommitAction ${$}`)}var _M$=D(()=>{$D()});class ly{#$;constructor($){this.#$=$}using($){return new ly(yX.cloneWith(this.#$,{using:v4.createWithSql($)}))}$call($){return $(this)}toOperationNode(){return this.#$}}var MM$=D(()=>{xD();PX()});class r5{#$;constructor($){this.#$=P($)}temporary(){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{temporary:!0})})}onCommit($){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{onCommit:AM$($)})})}ifNotExists(){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{ifNotExists:!0})})}addColumn($,J,X=UJ){let Q=X(new Y8(Q8.create($,kY(J))));return new r5({...this.#$,node:zJ.cloneWithColumn(this.#$.node,Q.toOperationNode())})}addPrimaryKeyConstraint($,J,X=UJ){let Q=X(new ZV(GV.create(J,$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addUniqueConstraint($,J,X=UJ){let Q=X(new jG(ZG.create(J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addIndex($,J,X=UJ){let Q=X(new ly(yX.cloneWithColumns(yX.create($),J.map((Y)=>C1(Y)?T4.create(Y):BJ(Y)))));return new r5({...this.#$,node:zJ.cloneWithIndex(this.#$.node,Q.toOperationNode())})}addCheckConstraint($,J,X=UJ){let Q=X(new bM(ED.create(J.toOperationNode(),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,Q.toOperationNode())})}addForeignKeyConstraint($,J,X,Q,Y=UJ){let W=Y(new bY(xY.create(J.map(T4.create),e4(X),Q.map(T4.create),$)));return new r5({...this.#$,node:zJ.cloneWithConstraint(this.#$.node,W.toOperationNode())})}modifyFront($){return new r5({...this.#$,node:zJ.cloneWithFrontModifier(this.#$.node,$.toOperationNode())})}modifyEnd($){return new r5({...this.#$,node:zJ.cloneWithEndModifier(this.#$.node,$.toOperationNode())})}as($){return new r5({...this.#$,node:zJ.cloneWith(this.#$.node,{selectQuery:BJ($)})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var p0$=D(()=>{EM();$D();fy();G$();IM();U5();vy();RM();xM();kM();TM();IJ();_M$();b0$();EQ();y0$();xD();MM$()});class bD{#$;constructor($){this.#$=P($)}on($){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{table:e4($)})})}ifExists(){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new bD({...this.#$,node:IU.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var c0$=D(()=>{a_();IJ();G$()});class vM{#$;constructor($){this.#$=P($)}ifExists(){return new vM({...this.#$,node:s_.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new vM({...this.#$,node:s_.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var n0$=D(()=>{rb();G$()});class yD{#$;constructor($){this.#$=P($)}temporary(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{temporary:!0})})}ifExists(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new yD({...this.#$,node:JD.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var d0$=D(()=>{tb();G$()});var fY;var hM=D(()=>{G$();sj();fY=P({is($){return $.kind==="CreateViewNode"},create($){return P({kind:"CreateViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class i0${#$=new fM;transformQuery($){return this.#$.transformNode($.node,$.queryId)}transformResult($){return Promise.resolve($.result)}}var RM$=D(()=>{u0$()});class jV{#$;constructor($){this.#$=P($)}temporary(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{temporary:!0})})}materialized(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{materialized:!0})})}ifNotExists(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{ifNotExists:!0})})}orReplace(){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{orReplace:!0})})}columns($){return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{columns:$.map(U$$)})})}as($){let J=$.withPlugin(new i0$).toOperationNode();return new jV({...this.#$,node:fY.cloneWith(this.#$.node,{as:J})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var o0$=D(()=>{G$();hM();OJ();RM$()});var fD;var py=D(()=>{G$();sj();fD=P({is($){return $.kind==="DropViewNode"},create($){return P({kind:"DropViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class vD{#$;constructor($){this.#$=P($)}materialized(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{materialized:!0})})}ifExists(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new vD({...this.#$,node:fD.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var r0$=D(()=>{G$();py()});var cy;var ny=D(()=>{G$();QL();CX();cy=P({is($){return $.kind==="CreateTypeNode"},create($){return P({kind:"CreateTypeNode",name:$})},cloneWithEnum($,J){return P({...$,enum:eW.create(J.map(n6.createImmediate))})}})});class dy{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}asEnum($){return new dy({...this.#$,node:cy.cloneWithEnum(this.#$.node,$)})}$call($){return $(this)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var t0$=D(()=>{G$();ny()});var gM;var iy=D(()=>{G$();gM=P({is($){return $.kind==="DropTypeNode"},create($){if(!Array.isArray($))$=[$];return P({kind:"DropTypeNode",name:$[0],additionalNames:$.slice(1)})},cloneWith($,J){return P({...$,...J})}})});class uM{#$;constructor($){this.#$=P($)}ifExists(){return new uM({...this.#$,node:gM.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new uM({...this.#$,node:gM.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var a0$=D(()=>{iy();G$()});function oy($){if($.includes(".")){let X=$.split(".").map(PD0);if(X.length===2)return K5.createWithSchema(X[0],X[1]);else throw Error(`invalid schemable identifier ${$}`)}else return K5.create($)}function EM$($){if(!Array.isArray($))$=[$];return $.map(oy)}function PD0($){return $.trim()}var PM$=D(()=>{sj()});var hD;var ry=D(()=>{G$();sj();hD=P({is($){return $.kind==="RefreshMaterializedViewNode"},create($){return P({kind:"RefreshMaterializedViewNode",name:K5.create($)})},cloneWith($,J){return P({...$,...J})}})});class gD{#$;constructor($){this.#$=P($)}concurrently(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{concurrently:!0,withNoData:!1})})}withData(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{withNoData:!1})})}withNoData(){return new gD({...this.#$,node:hD.cloneWith(this.#$.node,{withNoData:!0,concurrently:!1})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){await this.#$.executor.executeQuery(this.compile(),$)}}var s0$=D(()=>{G$();ry()});var VG;var mM=D(()=>{G$();VG=P({is($){return $.kind==="AlterTypeNode"},create($){return P({kind:"AlterTypeNode",name:$})},cloneWith($,J){return P({...$,...J})}})});var lM;var ty=D(()=>{G$();lM=P({is($){return $.kind==="AddValueNode"},create($){return P({kind:"AddValueNode",value:$})},cloneWith($,J){return P({...$,...J})}})});class HL{#$;constructor($){this.#$=P($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute($){return await this.#$.executor.executeQuery(this.compile(),$)}}var ay=D(()=>{G$()});var e0$,sy;var TM$=D(()=>{ty();CX();mM();ay();sy=class sy extends HL{#$;constructor($){super($);this.#$=$}ifNotExists(){return new e0$({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.cloneWith(this.#$.node.addValue,{ifNotExists:!0})})})}before($){return this.#J($,!0)}after($){return this.#J($,!1)}#J($,J){return new e0$({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.cloneWith(this.#$.node.addValue,{isBefore:J,neighborValue:n6.createImmediate($)})})})}};e0$=sy});var CM$;var $1$=D(()=>{G$();CM$=P({is($){return $.kind==="RenameValueNode"},create($,J){return P({kind:"RenameValueNode",oldValue:$,newValue:J})}})});class J1${#$;constructor($){this.#$=P($)}addValue($){return new sy({...this.#$,node:VG.cloneWith(this.#$.node,{addValue:lM.create(n6.createImmediate($))})})}renameTo($){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{renameTo:U1.create($)})})}renameValue($,J){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{renameValue:CM$.create(n6.createImmediate($),n6.createImmediate(J))})})}setSchema($){return new HL({...this.#$,node:VG.cloneWith(this.#$.node,{setSchema:U1.create($)})})}}var SM$=D(()=>{G$();mM();k6();TM$();ty();CX();ay();$1$()});class uD{#$;constructor($){this.#$=$}createTable($){return new r5({queryId:M1(),executor:this.#$,node:zJ.create(e4($))})}dropTable($){return new yD({queryId:M1(),executor:this.#$,node:JD.create(e4($))})}createIndex($){return new TQ({queryId:M1(),executor:this.#$,node:NY.create($)})}dropIndex($){return new bD({queryId:M1(),executor:this.#$,node:IU.create($)})}createSchema($){return new my({queryId:M1(),executor:this.#$,node:ib.create($)})}dropSchema($){return new vM({queryId:M1(),executor:this.#$,node:s_.create($)})}alterTable($){return new h0$({queryId:M1(),executor:this.#$,node:s4.create(e4($))})}createView($){return new jV({queryId:M1(),executor:this.#$,node:fY.create($)})}refreshMaterializedView($){return new gD({queryId:M1(),executor:this.#$,node:hD.create($)})}dropView($){return new vD({queryId:M1(),executor:this.#$,node:fD.create($)})}createType($){return new dy({queryId:M1(),executor:this.#$,node:cy.create(oy($))})}alterType($){return new J1$({executor:this.#$,node:VG.create(oy($)),queryId:M1()})}dropType($){return new uM({queryId:M1(),executor:this.#$,node:gM.create(EM$($))})}withPlugin($){return new uD(this.#$.withPlugin($))}withoutPlugins(){return new uD(this.#$.withoutPlugins())}withSchema($){return new uD(this.#$.withPluginAtFront(new IY($)))}}var X1$=D(()=>{$L();db();ob();$D();a_();rb();tb();IJ();g0$();m0$();l0$();p0$();c0$();n0$();d0$();SY();wD();o0$();hM();r0$();py();t0$();a0$();ny();iy();PM$();s0$();ry();SM$();mM()});class Q1${ref($){return new Y$$($)}table($){return new N0$($)}}var Y1$=D(()=>{JM();xy()});class W1${#$;constructor($){this.#$=$}async provideConnection($,J){let X=await this.#$.acquireConnection(J);try{return await $(X)}finally{await this.#$.releaseConnection(X,J)}}}var cU;var G1$=D(()=>{s$$();cU=class cU extends FM{#$;#J;#X;constructor($,J,X,Q=[]){super(Q);this.#$=$,this.#J=J,this.#X=X}get adapter(){return this.#J}compileQuery($,J){return this.#$.compileQuery($,J)}provideConnection($,J){return this.#X.provideConnection($,J)}withPlugins($){return new cU(this.#$,this.#J,this.#X,[...this.plugins,...$])}withPlugin($){return new cU(this.#$,this.#J,this.#X,[...this.plugins,$])}withPluginAtFront($){return new cU(this.#$,this.#J,this.#X,[$,...this.plugins])}withConnectionProvider($){return new cU(this.#$,this.#J,$,[...this.plugins])}withoutPlugins(){return new cU(this.#$,this.#J,this.#X,[])}}});function ey(){if(typeof performance<"u"&&a4(performance.now))return performance.now();else return Date.now()}var IM$=D(()=>{G$()});class Z1${#$;#J;async obtainLock(){while(this.#$)await this.#$;this.#$=new Promise(($)=>{this.#J=$})}releaseLock(){let $=this.#J;this.#$=void 0,this.#J=void 0,$?.()}}class j1${#$;#J;#X;#Q;#Y;#G=new WeakSet;#W;constructor($,J,X){if(this.#$=$,this.#Q=!1,this.#J=X,J.supportsMultipleConnections===!1)this.#W=new Z1$}async init($){if(this.#Y)throw Error("driver has already been destroyed");this.#X??=this.#$.init($).then(()=>{this.#Q=!0}).catch((J)=>{throw this.#X=void 0,J}),await uU(this.#X,$?.signal,"init")}async acquireConnection($){if(this.#Y)throw Error("driver has already been destroyed");if(!this.#Q)await this.init($);if(this.#W){let Q=this.#W.obtainLock();await uU(Q,$?.signal,"acquireConnection:mutex",()=>Q.then(()=>this.#W?.releaseLock()))}let J=this.#$.acquireConnection($),X=await uU(J,$?.signal,"acquireConnection:acquire",()=>J?.then((Q)=>this.releaseConnection(Q).catch(YG("driver.releaseConnection"))).catch(YG("driver.acquireConnection")));if(!this.#G.has(X)){if(this.#Z())this.#j(X);this.#G.add(X)}return X}async releaseConnection($,J){await this.#$.releaseConnection($,J),this.#W?.releaseLock()}async beginTransaction($,J){return await this.#$.beginTransaction($,J)}async commitTransaction($){return await this.#$.commitTransaction($)}async rollbackTransaction($){return await this.#$.rollbackTransaction($)}async savepoint($,J,X){if(this.#$.savepoint)return await this.#$.savepoint($,J,X);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint($,J,X){if(this.#$.rollbackToSavepoint)return await this.#$.rollbackToSavepoint($,J,X);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint($,J,X){if(this.#$.releaseSavepoint)return await this.#$.releaseSavepoint($,J,X);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy($){if(!this.#X)return;await uU(this.#X,$?.signal,"destroy:initPromise"),this.#Y??=this.#$.destroy($).catch((J)=>{throw this.#Y=void 0,J}),await uU(this.#Y,$?.signal,"destroy")}#Z(){return this.#J.isLevelEnabled("query")||this.#J.isLevelEnabled("error")}#j($){let{executeQuery:J,streamQuery:X}=$,Q=this;$.executeQuery=async(Y,W)=>{let G,Z=ey();try{return await J.call($,Y,W)}catch(j){throw G=j,await Q.#V(j,Y,Z),j}finally{if(!G)await Q.#U(Y,Z)}},$.streamQuery=async function*(Y,W,G){let Z,j=ey();try{for await(let V of X.call($,Y,W,G))yield V}catch(V){throw Z=V,await Q.#V(V,Y,j),V}finally{if(!Z)await Q.#U(Y,j,!0)}}}async#V($,J,X){await this.#J.error(()=>({level:"error",error:$,query:J,queryDurationMillis:this.#z(X)}))}async#U($,J,X=!1){await this.#J.query(()=>({level:"query",isStream:X,query:$,queryDurationMillis:this.#z(J)}))}#z($){return ey()-$}}var kM$=D(()=>{Ny();IM$()});class pM{#$;#J;constructor($){this.#$=$}async provideConnection($){while(this.#J)await this.#J.catch(TD0);return this.#J=this.#X($).finally(()=>{this.#J=void 0}),this.#J}async#X($){return await $(this.#$)}}var TD0=()=>{};function V1$($){if($.accessMode&&!CD0.includes($.accessMode))throw Error(`invalid transaction access mode ${$.accessMode}`);if($.isolationLevel&&!SD0.includes($.isolationLevel))throw Error(`invalid transaction isolation level ${$.isolationLevel}`)}var CD0,SD0;var K1$=D(()=>{CD0=["read only","read write"],SD0=["read uncommitted","read committed","repeatable read","serializable","snapshot"]});class U1${#$;#J;constructor($){if(a4($))this.#J=$,this.#$=P({query:!0,error:!0});else this.#J=kD0,this.#$=P({query:$.includes("query"),error:$.includes("error")})}isLevelEnabled($){return this.#$[$]}async query($){if(this.#$.query)await this.#J($())}async error($){if(this.#$.error)await this.#J($())}}function kD0($){if($.level==="query"){let J=`kysely:query:${$.isStream?"stream:":""}`;console.log(`${J} ${$.query.sql}`),console.log(`${J} duration: ${$.queryDurationMillis.toFixed(1)}ms`)}else if($.level==="error")if($.error instanceof Error)console.error(`kysely:error: ${$.error.stack??$.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:$.error,query:$.query.sql,queryDurationMillis:$.queryDurationMillis})}`)}var ID0,Ir1;var z1$=D(()=>{G$();ID0=["query","error"],Ir1=P(ID0)});function xM$($){return L6($)&&a4($.compile)}var L1$=D(()=>{G$()});function xD0($){return L6($)&&L6($.config)&&L6($.driver)&&L6($.executor)&&L6($.dialect)}class bM${#$;constructor($){this.#$=P($)}async execute($,J){return this.#$.executor.provideConnection(async(X)=>{let Q=this.#$.executor.withConnectionProvider(new pM(X)),Y=new vY({...this.#$,executor:Q});return await $(Y)},P({signal:J?.signal}))}}class $f{#$;constructor($){this.#$=P($)}setAccessMode($){return new $f({...this.#$,accessMode:$})}setIsolationLevel($){return new $f({...this.#$,isolationLevel:$})}async execute($){let{isolationLevel:J,accessMode:X,...Q}=this.#$,Y={isolationLevel:J,accessMode:X};return V1$(Y),this.#$.executor.provideConnection(async(W)=>{let G={isCommitted:!1,isRolledBack:!1},Z=new VV(this.#$.executor.withConnectionProvider(new pM(W)),G),j=new KG({...Q,executor:Z}),V=!1;try{await this.#$.driver.beginTransaction(W,Y),V=!0;let K=await $(j);return await this.#$.driver.commitTransaction(W),G.isCommitted=!0,K}catch(K){if(V)await this.#$.driver.rollbackTransaction(W),G.isRolledBack=!0;throw K}})}}class Jf{#$;constructor($){this.#$=P($)}setAccessMode($){return new Jf({...this.#$,accessMode:$})}setIsolationLevel($){return new Jf({...this.#$,isolationLevel:$})}async execute(){let{isolationLevel:$,accessMode:J,...X}=this.#$,Q={isolationLevel:$,accessMode:J};V1$(Q);let Y=await AD(this.#$.executor);return await this.#$.driver.beginTransaction(Y.connection,Q),new CQ({...X,connection:Y,executor:this.#$.executor.withConnectionProvider(new pM(Y.connection))})}}class mD{#$;constructor($){this.#$=$}async execute(){return await this.#$()}}function OL($){if($.isCommitted)throw Error("Transaction is already committed");if($.isRolledBack)throw Error("Transaction is already rolled back")}class VV{#$;#J;constructor($,J){this.#$=$ instanceof VV?$.#$:$,this.#J=J}get adapter(){return this.#$.adapter}get plugins(){return this.#$.plugins}transformQuery($,J){return this.#$.transformQuery($,J)}compileQuery($,J){return this.#$.compileQuery($,J)}provideConnection($,J){return this.#$.provideConnection($,J)}executeQuery($,J){return OL(this.#J),this.#$.executeQuery($,J)}stream($,J,X){return OL(this.#J),this.#$.stream($,J,X)}withConnectionProvider($){return new VV(this.#$.withConnectionProvider($),this.#J)}withPlugin($){return new VV(this.#$.withPlugin($),this.#J)}withPlugins($){return new VV(this.#$.withPlugins($),this.#J)}withPluginAtFront($){return new VV(this.#$.withPluginAtFront($),this.#J)}withoutPlugins(){return new VV(this.#$.withoutPlugins(),this.#J)}}var vY,KG,CQ;var yM$=D(()=>{X1$();Y1$();Ay();G1$();G$();kM$();K1$();Iy();z1$();SY();L1$();ky();wM();EQ();wD();a$$();Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");vY=class vY extends WG{#$;constructor($){let J,X;if(xD0($))J={executor:$.executor},X={...$};else{let Q=$.dialect,Y=Q.createDriver(),W=Q.createQueryCompiler(),G=Q.createAdapter(),Z=new U1$($.log??[]),j=new j1$(Y,G,Z),V=new W1$(j),K=new cU(W,G,V,$.plugins??[]);J={executor:K},X={config:$,executor:K,dialect:Q,driver:j}}super(J);this.#$=P(X)}get schema(){return new uD(this.#$.executor)}get dynamic(){return new Q1$}get introspection(){return this.#$.dialect.createIntrospector(this.withoutPlugins())}case($){return new AM({node:kJ.create(d5($)?void 0:BJ($))})}get fn(){return Sy()}transaction(){return new $f({...this.#$})}startTransaction(){return new Jf({...this.#$})}connection(){return new bM$({...this.#$})}withPlugin($){return new vY({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new vY({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new vY({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}$extendTables(){return new vY({...this.#$})}$omitTables(){return new vY({...this.#$})}$pickTables(){return new vY({...this.#$})}withTables(){return this.$extendTables()}async destroy(){await this.#$.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#$.executor}async executeQuery($,J){let X=xM$($)?$.compile():$;return await this.#$.executor.executeQuery(X,J)}async[Symbol.asyncDispose](){await this.destroy()}};KG=class KG extends vY{#$;constructor($){super($);this.#$=$}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin($){return new KG({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new KG({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new KG({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}withTables(){return new KG({...this.#$})}$extendTables(){return new KG({...this.#$})}$omitTables(){return new KG({...this.#$})}$pickTables(){return new KG({...this.#$})}};CQ=class CQ extends KG{#$;#J;#X;constructor($){let J={isCommitted:!1,isRolledBack:!1};$={...$,executor:new VV($.executor,J)};let{connection:X,...Q}=$;super(Q);this.#$=P($),this.#X=J;let Y=M1();this.#J=(W)=>$.executor.compileQuery(W,Y)}get isCommitted(){return this.#X.isCommitted}get isRolledBack(){return this.#X.isRolledBack}commit(){return OL(this.#X),new mD(async()=>{await this.#$.driver.commitTransaction(this.#$.connection.connection),this.#X.isCommitted=!0,this.#$.connection.release()})}rollback(){return OL(this.#X),new mD(async()=>{await this.#$.driver.rollbackTransaction(this.#$.connection.connection),this.#X.isRolledBack=!0,this.#$.connection.release()})}savepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.savepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}rollbackToSavepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.rollbackToSavepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}releaseSavepoint($){return OL(this.#X),new mD(async()=>{return await this.#$.driver.releaseSavepoint?.(this.#$.connection.connection,$,this.#J),new CQ({...this.#$})})}withPlugin($){return new CQ({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new CQ({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new CQ({...this.#$,executor:this.#$.executor.withPluginAtFront(new IY($))})}withTables(){return new CQ({...this.#$})}$extendTables(){return new CQ({...this.#$})}$omitTables(){return new CQ({...this.#$})}$pickTables(){return new CQ({...this.#$})}}});class cM{#$;constructor($){this.#$=P($)}get expressionType(){return}get isRawBuilder(){return!0}as($){return new fM$(this,$)}$castTo(){return new cM({...this.#$})}$notNull(){return new cM(this.#$)}withPlugin($){return new cM({...this.#$,plugins:this.#$.plugins!==void 0?P([...this.#$.plugins,$]):P([$])})}toOperationNode(){return this.#X(this.#J())}compile($){return this.#Q(this.#J($))}async execute($,J){let X=this.#J($);return X.executeQuery(this.#Q(X),J)}#J($){let J=$!==void 0?$.getExecutor():mU;return this.#$.plugins!==void 0?J.withPlugins(this.#$.plugins):J}#X($){return $.transformQuery(this.#$.rawNode,this.#$.queryId)}#Q($){return $.compileQuery(this.#X($),this.#$.queryId)}}function KV($){return new cM($)}class fM${#$;#J;constructor($,J){this.#$=$,this.#J=J}get expression(){return this.#$}get alias(){return this.#J}get rawBuilder(){return this.#$}toOperationNode(){return LJ.create(this.#$.toOperationNode(),x6(this.#J)?this.#J.toOperationNode():U1.create(this.#J))}}var H1$=D(()=>{AY();G$();MD();k6();i5()});function vM$($){if(x6($))return $.toOperationNode();return b6($)}var $0;var nU=D(()=>{k6();i5();PX();CX();OJ();IJ();$G();SY();H1$();$0=Object.assign(($,...J)=>{return KV({queryId:M1(),rawNode:v4.create($,J?.map(vM$)??[])})},{ref($){return KV({queryId:M1(),rawNode:v4.createWithChild(k7($))})},val($){return KV({queryId:M1(),rawNode:v4.createWithChild(b6($))})},table($){return KV({queryId:M1(),rawNode:v4.createWithChild(e4($))})},id(...$){let J=Array($.length+1).fill(".");return J[0]="",J[J.length-1]="",KV({queryId:M1(),rawNode:v4.create(J,$.map(U1.create))})},lit($){return KV({queryId:M1(),rawNode:v4.createWithChild(n6.createImmediate($))})},raw($){return KV({queryId:M1(),rawNode:v4.createWithSql($)})},join($,J=$0`, `){let X=Array(Math.max(2*$.length-1,0)),Q=J.toOperationNode();for(let Y=0;Y<$.length;++Y)if(X[2*Y]=vM$($[Y]),Y!==$.length-1)X[2*Y+1]=Q;return KV({queryId:M1(),rawNode:v4.createWithChildren(X)})}})});class O1${nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#$=P({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=($)=>{this.nodeStack.push($),this.#$[$.kind]($),this.nodeStack.pop()}}var B1$=D(()=>{G$()});var bD0,yD0,UV,fD0,hM$,vD0;var BL=D(()=>{$D();WL();B1$();ej();KD();PX();G$();hM();Ry();GL();bD0=/'/g,yD0=/['"]/g;UV=class UV extends O1${#$="";#J=[];get numParameters(){return this.#J.length}compileQuery($,J){return this.#$="",this.#J=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode($),P({query:$,queryId:J,sql:this.getSql(),parameters:[...this.#J]})}getSql(){return this.#$}visitSelectQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!k8.is(this.parentNode)&&!zJ.is(this.parentNode)&&!fY.is(this.parentNode)&&!My.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("select"),$.distinctOn)this.append(" "),this.compileDistinctOn($.distinctOn);if($.frontModifiers?.length)this.append(" "),this.compileList($.frontModifiers," ");if($.top)this.append(" "),this.visitNode($.top);if($.selections)this.append(" "),this.compileList($.selections);if($.from)this.append(" "),this.visitNode($.from);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.groupBy)this.append(" "),this.visitNode($.groupBy);if($.having)this.append(" "),this.visitNode($.having);if($.setOperations)this.append(" "),this.compileList($.setOperations," ");if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if($.offset)this.append(" "),this.visitNode($.offset);if($.fetch)this.append(" "),this.visitNode($.fetch);if($.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers($.endModifiers)," ");if(J)this.append(")")}visitFrom($){this.append("from "),this.compileList($.froms)}visitSelection($){this.visitNode($.selection)}visitColumn($){this.visitNode($.column)}compileDistinctOn($){this.append("distinct on ("),this.compileList($),this.append(")")}compileList($,J=", "){let X=$.length-1;for(let Q=0;Q<=X;Q++)if(this.visitNode($[Q]),Q<X)this.append(J)}visitWhere($){this.append("where "),this.visitNode($.where)}visitHaving($){this.append("having "),this.visitNode($.having)}visitInsertQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode)&&!x7.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append($.replace?"replace":"insert"),$.orAction)this.append(" "),this.visitNode($.orAction);if($.top)this.append(" "),this.visitNode($.top);if($.into)this.append(" into "),this.visitNode($.into);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.output)this.append(" "),this.visitNode($.output);if($.values)this.append(" "),this.visitNode($.values);if($.defaultValues)this.append(" "),this.append("default values");if($.onConflict)this.append(" "),this.visitNode($.onConflict);if($.onDuplicateKey)this.append(" "),this.visitNode($.onDuplicateKey);if($.returning)this.append(" "),this.visitNode($.returning);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitValues($){this.append("values "),this.compileList($.values)}visitDeleteQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("delete "),$.top)this.visitNode($.top),this.append(" ");if(this.visitNode($.from),$.output)this.append(" "),this.visitNode($.output);if($.using)this.append(" "),this.visitNode($.using);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.returning)this.append(" "),this.visitNode($.returning);if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitReturning($){this.append("returning "),this.compileList($.selections)}visitAlias($){this.visitNode($.node),this.append(" as "),this.visitNode($.alias)}visitReference($){if($.table)this.visitNode($.table),this.append(".");this.visitNode($.column)}visitSelectAll($){this.append("*")}visitIdentifier($){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier($),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier($){if(!C1($.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier($.name))}visitAnd($){this.visitNode($.left),this.append(" and "),this.visitNode($.right)}visitOr($){this.visitNode($.left),this.append(" or "),this.visitNode($.right)}visitValue($){if($.immediate)this.appendImmediateValue($.value);else this.appendValue($.value)}visitValueList($){this.append("("),this.compileList($.values),this.append(")")}visitTuple($){this.append("("),this.compileList($.values),this.append(")")}visitPrimitiveValueList($){this.append("(");let{values:J}=$;for(let X=0;X<J.length;++X)if(this.appendValue(J[X]),X!==J.length-1)this.append(", ");this.append(")")}visitParens($){this.append("("),this.visitNode($.node),this.append(")")}visitJoin($){if(this.append(vD0[$.joinType]),this.append(" "),this.visitNode($.table),$.on)this.append(" "),this.visitNode($.on)}visitOn($){this.append("on "),this.visitNode($.on)}visitRaw($){let{sqlFragments:J,parameters:X}=$;for(let Q=0;Q<J.length;++Q)if(this.append(J[Q]),X.length>Q)this.visitNode(X[Q])}visitOperator($){this.append($.operator)}visitTable($){this.visitNode($.table)}visitSchemableIdentifier($){if($.schema)this.visitNode($.schema),this.append(".");this.visitNode($.identifier)}visitCreateTable($){if(this.append("create "),$.frontModifiers?.length)this.compileList($.frontModifiers," "),this.append(" ");if($.temporary)this.append("temporary ");if(this.append("table "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.table),!$.selectQuery)this.append(" ("),this.compileList([...$.columns,...$.constraints??[],...$.indexes??[]]),this.append(")");if($.onCommit)this.append(" on commit "),this.append($.onCommit);if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ");if($.selectQuery)this.append(" as "),this.visitNode($.selectQuery)}visitColumnDefinition($){if($.ifNotExists)this.append("if not exists ");if(this.visitNode($.column),this.append(" "),this.visitNode($.dataType),$.unsigned)this.append(" unsigned");if($.frontModifiers&&$.frontModifiers.length>0)this.append(" "),this.compileList($.frontModifiers," ");if($.generated)this.append(" "),this.visitNode($.generated);if($.identity)this.append(" identity");if($.defaultTo)this.append(" "),this.visitNode($.defaultTo);if($.notNull)this.append(" not null");if($.unique)this.append(" unique");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.primaryKey)this.append(" primary key");if($.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if($.references)this.append(" "),this.visitNode($.references);if($.check)this.append(" "),this.visitNode($.check);if($.endModifiers&&$.endModifiers.length>0)this.append(" "),this.compileList($.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences($){if(this.append("references "),this.visitNode($.table),this.append(" ("),this.compileList($.columns),this.append(")"),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate)}visitDropTable($){if(this.append("drop "),$.temporary)this.append("temporary ");if(this.append("table "),$.ifExists)this.append("if exists ");if(this.visitNode($.table),$.cascade)this.append(" cascade")}visitDataType($){this.append($.dataType)}visitOrderBy($){this.append("order by "),this.compileList($.items)}visitOrderByItem($){if(this.visitNode($.orderBy),$.collation)this.append(" "),this.visitNode($.collation);if($.direction)this.append(" "),this.visitNode($.direction);if($.nulls)this.append(" nulls "),this.append($.nulls)}visitGroupBy($){this.append("group by "),this.compileList($.items)}visitGroupByItem($){this.visitNode($.groupBy)}visitUpdateQuery($){let J=this.parentNode!==void 0&&!SX.is(this.parentNode)&&!v4.is(this.parentNode)&&!x7.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(J)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("update "),$.top)this.visitNode($.top),this.append(" ");if($.table)this.visitNode($.table),this.append(" ");if(this.append("set "),$.updates)this.compileList($.updates);if($.output)this.append(" "),this.visitNode($.output);if($.from)this.append(" "),this.visitNode($.from);if($.joins){if(!$.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList($.joins," ")}if($.where)this.append(" "),this.visitNode($.where);if($.returning)this.append(" "),this.visitNode($.returning);if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if(J)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitColumnUpdate($){this.visitNode($.column),this.append(" = "),this.visitNode($.value)}visitLimit($){this.append("limit "),this.visitNode($.limit)}visitOffset($){this.append("offset "),this.visitNode($.offset)}visitOnConflict($){if(this.append("on conflict"),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");else if($.constraint)this.append(" on constraint "),this.visitNode($.constraint);else if($.indexExpression)this.append(" ("),this.visitNode($.indexExpression),this.append(")");if($.indexWhere)this.append(" "),this.visitNode($.indexWhere);if($.doNothing===!0)this.append(" do nothing");else if($.updates){if(this.append(" do update set "),this.compileList($.updates),$.updateWhere)this.append(" "),this.visitNode($.updateWhere)}}visitOnDuplicateKey($){this.append("on duplicate key update "),this.compileList($.updates)}visitCreateIndex($){if(this.append("create "),$.unique)this.append("unique ");if(this.append("index "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.using)this.append(" using "),this.visitNode($.using);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.where)this.append(" "),this.visitNode($.where)}visitDropIndex($){if(this.append("drop index "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.cascade)this.append(" cascade")}visitCreateSchema($){if(this.append("create schema "),$.ifNotExists)this.append("if not exists ");this.visitNode($.schema)}visitDropSchema($){if(this.append("drop schema "),$.ifExists)this.append("if exists ");if(this.visitNode($.schema),$.cascade)this.append(" cascade")}visitPrimaryKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("primary key ("),this.compileList($.columns),this.append(")"),this.buildDeferrable($)}buildDeferrable($){if($.deferrable!==void 0)if($.deferrable)this.append(" deferrable");else this.append(" not deferrable");if($.initiallyDeferred!==void 0)if($.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("unique"),$.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList($.columns),this.append(")"),this.buildDeferrable($)}visitCheckConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("check ("),this.visitNode($.expression),this.append(")")}visitForeignKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("foreign key ("),this.compileList($.columns),this.append(") "),this.visitNode($.references),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate);this.buildDeferrable($)}visitList($){this.compileList($.items)}visitWith($){if(this.append("with "),$.recursive)this.append("recursive ");this.compileList($.expressions)}visitCommonTableExpression($){if(this.visitNode($.name),this.append(" as "),aj($.materialized)){if(!$.materialized)this.append("not ");this.append("materialized ")}this.visitNode($.expression)}visitCommonTableExpressionName($){if(this.visitNode($.table),$.columns)this.append("("),this.compileList($.columns),this.append(")")}visitAlterTable($){if(this.append("alter table "),this.visitNode($.table),this.append(" "),$.renameTo)this.append("rename to "),this.visitNode($.renameTo);if($.setSchema)this.append("set schema "),this.visitNode($.setSchema);if($.addConstraint)this.visitNode($.addConstraint);if($.dropConstraint)this.visitNode($.dropConstraint);if($.renameConstraint)this.visitNode($.renameConstraint);if($.columnAlterations)this.compileColumnAlterations($.columnAlterations);if($.addIndex)this.visitNode($.addIndex);if($.dropIndex)this.visitNode($.dropIndex)}visitAddColumn($){this.append("add column "),this.visitNode($.column)}visitRenameColumn($){this.append("rename column "),this.visitNode($.column),this.append(" to "),this.visitNode($.renameTo)}visitDropColumn($){if(this.append("drop column "),$.ifExists)this.append("if exists ");this.visitNode($.column)}visitAlterColumn($){if(this.append("alter column "),this.visitNode($.column),this.append(" "),$.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode($.dataType),$.dataTypeExpression)this.append("using "),this.visitNode($.dataTypeExpression)}if($.setDefault)this.append("set default "),this.visitNode($.setDefault);if($.dropDefault)this.append("drop default");if($.setNotNull)this.append("set not null");if($.dropNotNull)this.append("drop not null")}visitModifyColumn($){this.append("modify column "),this.visitNode($.column)}visitAddConstraint($){this.append("add "),this.visitNode($.constraint)}visitDropConstraint($){if(this.append("drop constraint "),$.ifExists)this.append("if exists ");if(this.visitNode($.constraintName),$.modifier==="cascade")this.append(" cascade");else if($.modifier==="restrict")this.append(" restrict")}visitRenameConstraint($){this.append("rename constraint "),this.visitNode($.oldName),this.append(" to "),this.visitNode($.newName)}visitSetOperation($){if(this.append($.operator),this.append(" "),$.all)this.append("all ");this.visitNode($.expression)}visitCreateView($){if(this.append("create "),$.orReplace)this.append("or replace ");if($.materialized)this.append("materialized ");if($.temporary)this.append("temporary ");if(this.append("view "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),this.append(" "),$.columns)this.append("("),this.compileList($.columns),this.append(") ");if($.as)this.append("as "),this.visitNode($.as)}visitRefreshMaterializedView($){if(this.append("refresh materialized view "),$.concurrently)this.append("concurrently ");if(this.visitNode($.name),$.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView($){if(this.append("drop "),$.materialized)this.append("materialized ");if(this.append("view "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.cascade)this.append(" cascade")}visitGenerated($){if(this.append("generated "),$.always)this.append("always ");if($.byDefault)this.append("by default ");if(this.append("as "),$.identity)this.append("identity");if($.expression)this.append("("),this.visitNode($.expression),this.append(")");if($.stored)this.append(" stored")}visitDefaultValue($){this.append("default "),this.visitNode($.defaultValue)}visitSelectModifier($){if($.rawModifier)this.visitNode($.rawModifier);else this.append(fD0[$.modifier]);if($.of)this.append(" of "),this.compileList($.of,", ")}visitCreateType($){if(this.append("create type "),this.visitNode($.name),$.enum)this.append(" as enum "),this.visitNode($.enum)}visitDropType($){if(this.append("drop type "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.additionalNames?.length)this.append(", "),this.compileList($.additionalNames);if($.cascade)this.append(" cascade")}visitAlterType($){if(this.append("alter type "),this.visitNode($.name),this.append(" "),$.addValue)this.visitNode($.addValue);else if($.renameTo)this.append("rename to "),this.visitNode($.renameTo);else if($.renameValue)this.visitNode($.renameValue);else if($.setSchema)this.append("set schema "),this.visitNode($.setSchema)}visitAddValue($){if(this.append("add value "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.value),$.neighborValue)this.append($.isBefore?" before ":" after "),this.visitNode($.neighborValue)}visitRenameValue($){this.append("rename value "),this.visitNode($.oldValue),this.append(" to "),this.visitNode($.newValue)}visitExplain($){if(this.append("explain"),$.options||$.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),$.options){if(this.visitNode($.options),$.format)this.append(this.getExplainOptionsDelimiter())}if($.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append($.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue($){this.append("default")}visitAggregateFunction($){if(this.append($.func),this.append("("),$.distinct)this.append("distinct ");if(this.compileList($.aggregated),$.orderBy)this.append(" "),this.visitNode($.orderBy);if(this.append(")"),$.withinGroup)this.append(" within group ("),this.visitNode($.withinGroup),this.append(")");if($.filter)this.append(" filter("),this.visitNode($.filter),this.append(")");if($.over)this.append(" "),this.visitNode($.over)}visitOver($){if(this.append("over("),$.partitionBy){if(this.visitNode($.partitionBy),$.orderBy)this.append(" ")}if($.orderBy)this.visitNode($.orderBy);this.append(")")}visitPartitionBy($){this.append("partition by "),this.compileList($.items)}visitPartitionByItem($){this.visitNode($.partitionBy)}visitBinaryOperation($){this.visitNode($.leftOperand),this.append(" "),this.visitNode($.operator),this.append(" "),this.visitNode($.rightOperand)}visitUnaryOperation($){if(this.visitNode($.operator),!this.isMinusOperator($.operator))this.append(" ");this.visitNode($.operand)}isMinusOperator($){return HJ.is($)&&$.operator==="-"}visitUsing($){this.append("using "),this.compileList($.tables)}visitFunction($){this.append($.func),this.append("("),this.compileList($.arguments),this.append(")")}visitCase($){if(this.append("case"),$.value)this.append(" "),this.visitNode($.value);if($.when)this.append(" "),this.compileList($.when," ");if($.else)this.append(" else "),this.visitNode($.else);if(this.append(" end"),$.isStatement)this.append(" case")}visitWhen($){if(this.append("when "),this.visitNode($.condition),$.result)this.append(" then "),this.visitNode($.result)}visitJSONReference($){this.visitNode($.reference),this.visitNode($.traversal)}visitJSONPath($){if($.inOperator)this.visitNode($.inOperator);this.append("'$");for(let J of $.pathLegs)this.visitNode(J);this.append("'")}visitJSONPathLeg($){let J=$.type==="ArrayLocation",X=String($.value);if(J)this.append("["),this.append(this.sanitizeStringLiteral(X)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(X)),this.append('"')}visitJSONOperatorChain($){for(let J=0,X=$.values.length;J<X;J++){if(J===X-1)this.visitNode($.operator);else this.append("->");this.visitNode($.values[J])}}visitMergeQuery($){if($.with)this.visitNode($.with),this.append(" ");if(this.append("merge "),$.top)this.visitNode($.top),this.append(" ");if(this.append("into "),this.visitNode($.into),$.using)this.append(" "),this.visitNode($.using);if($.whens)this.append(" "),this.compileList($.whens," ");if($.returning)this.append(" "),this.visitNode($.returning);if($.output)this.append(" "),this.visitNode($.output);if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitMatched($){if($.not)this.append("not ");if(this.append("matched"),$.bySource)this.append(" by source")}visitAddIndex($){if(!this.parentNode||!zJ.is(this.parentNode))this.append("add ");if($.unique)this.append("unique ");if(this.append("index "),this.visitNode($.name),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.using)this.append(" using "),this.visitNode($.using)}visitCast($){this.append("cast("),this.visitNode($.expression),this.append(" as "),this.visitNode($.dataType),this.append(")")}visitFetch($){this.append("fetch next "),this.visitNode($.rowCount),this.append(` rows ${$.modifier}`)}visitOutput($){this.append("output "),this.compileList($.selections)}visitTop($){if(this.append(`top(${$.expression})`),$.modifiers)this.append(` ${$.modifiers}`)}visitOrAction($){this.append($.action)}visitCollate($){this.append("collate "),this.visitNode($.collation)}append($){this.#$+=$}appendValue($){this.addParameter($),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier($){let J=this.getLeftIdentifierWrapper(),X=this.getRightIdentifierWrapper(),Q="";for(let Y of $)if(Q+=Y,Y===J)Q+=J;else if(Y===X)Q+=X;return Q}sanitizeStringLiteral($){return $.replace(bD0,"''")}sanitizeJSONPathMemberValue($){return $.replace(yD0,(J)=>J==="'"?"''":"\\\"")}addParameter($){this.#J.push($)}appendImmediateValue($){if(C1($))this.appendStringLiteral($);else if(wY($)||aj($)||SU($))this.append($.toString());else if(CU($))this.append("null");else if(sB($))this.appendImmediateValue($.toISOString());else throw Error(`invalid immediate value ${$}`)}appendStringLiteral($){this.append("'"),this.append(this.sanitizeStringLiteral($)),this.append("'")}sortSelectModifiers($){return P($.toSorted((J,X)=>J.modifier&&X.modifier?hM$[J.modifier]-hM$[X.modifier]:1))}compileColumnAlterations($){this.compileList($)}announcesNewColumnDataType(){return!0}};fD0=P({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),hM$=P({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),vD0=P({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var a8;var lD=D(()=>{PX();G$();SY();a8=P({raw($,J=[]){return P({sql:$,query:v4.createWithSql($),parameters:P(J),queryId:M1()})}})});class zV{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}function L5($,J){return v4.createWithChildren([v4.createWithSql(`${$} `),U1.create(J)])}var nM=D(()=>{k6();PX()});class D1${#$;#J;#X;constructor($){this.#$=P({...$})}async init($){if(this.#J=a4(this.#$.database)?await this.#$.database($):this.#$.database,this.#X=new gM$(this.#J),this.#$.onCreateConnection)await this.#$.onCreateConnection(this.#X,$)}async acquireConnection(){return this.#X}async beginTransaction($){await $.executeQuery(a8.raw("begin"))}async commitTransaction($){await $.executeQuery(a8.raw("commit"))}async rollbackTransaction($){await $.executeQuery(a8.raw("rollback"))}async savepoint($,J,X){await $.executeQuery(X(L5("savepoint",J),M1()))}async rollbackToSavepoint($,J,X){await $.executeQuery(X(L5("rollback to",J),M1()))}async releaseSavepoint($,J,X){await $.executeQuery(X(L5("release",J),M1()))}async releaseConnection(){}async destroy(){this.#J?.close()}}class gM${#$;constructor($){this.#$=$}async executeQuery($){let{sql:J,parameters:X}=$,Q=this.#$.prepare(J);if(Q.reader)return{rows:Q.all(X)};let{changes:Y,lastInsertRowid:W}=Q.run(X);return{insertId:W!=null?BigInt(W):void 0,numAffectedRows:Y!=null?BigInt(Y):void 0,rows:[]}}async*streamQuery($,J){let{sql:X,parameters:Q,query:Y}=$,W=this.#$.prepare(X);if(!H6.is(Y))throw Error("Sqlite driver only supports streaming of select queries");let G=W.iterate(Q);for(let Z of G)yield{rows:[Z]}}}var F1$=D(()=>{ZL();nM();lD();G$();SY()});var hD0,gD0,dM;var q1$=D(()=>{BL();hD0=/"/g,gD0=/[\\'"]/g;dM=class dM extends UV{visitOrAction($){this.append("or "),this.append($.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier($){return $.replace(hD0,'""')}sanitizeJSONPathMemberValue($){return $.replace(gD0,(J)=>J==="\\"?"\\\\":J==="'"?"''":"\\\"")}visitDefaultInsertValue($){this.append("null")}}});class w1${transformQuery($){return $.node}async transformResult($){return $.result}}class A1${#$;constructor($){this.#$=P($)}async getMigrations(){let J=await this.#K(this.#Q)?await this.#$.db.withPlugin(this.#W).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#F()).map(({name:Q,...Y})=>{let W=J.find((G)=>G.name===Q);return{name:Q,migration:Y,executedAt:W?new Date(W.timestamp):void 0}})}async migrateToLatest($){return this.#J(()=>({direction:"Up",step:1/0}),$)}async migrateTo($,J){return this.#J(({migrations:X,executedMigrations:Q,pendingMigrations:Y})=>{if(L6($)&&$.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!X.find((Z)=>Z.name===$))throw Error(`migration "${$}" doesn't exist`);let W=Q.indexOf($),G=Y.findIndex((Z)=>Z.name===$);if(W!==-1)return{direction:"Down",step:Q.length-W-1};if(G!==-1)return{direction:"Up",step:G+1};throw Error(`migration "${$}" isn't executed or pending`)},J)}async migrateUp($){return this.#J(()=>({direction:"Up",step:1}),$)}async migrateDown($){return this.#J(()=>({direction:"Down",step:1}),$)}async#J($,J){try{return await this.#Z(),await this.#j(),await this.#V(),await this.#U(),await this.#L($,J)}catch(X){if(X instanceof Xf)return X.resultSet;return{error:X}}}get#X(){return this.#$.migrationTableSchema}get#Q(){return this.#$.migrationTableName??_8}get#Y(){return this.#$.migrationLockTableName??UG}get#G(){return this.#$.allowUnorderedMigrations??uD0}get#W(){if(this.#X)return new IY(this.#X);return new w1$}async#Z(){if(!this.#X)return;if(await this.#z())return;try{await this.#H(this.#$.db.schema.createSchema(this.#X))}catch(J){if(!await this.#z())throw J}}async#j(){if(await this.#K(this.#Q))return;try{await this.#H(this.#$.db.schema.withPlugin(this.#W).createTable(this.#Q).addColumn("name","varchar(255)",(J)=>J.notNull().primaryKey()).addColumn("timestamp","varchar(255)",(J)=>J.notNull()))}catch(J){if(!await this.#K(this.#Q))throw J}}async#V(){if(await this.#K(this.#Y))return;try{await this.#H(this.#$.db.schema.withPlugin(this.#W).createTable(this.#Y).addColumn("id","varchar(255)",(J)=>J.notNull().primaryKey()).addColumn("is_locked","integer",(J)=>J.notNull().defaultTo(0)))}catch(J){if(!await this.#K(this.#Y))throw J}}async#U(){if(await this.#O())return;try{await this.#$.db.withPlugin(this.#W).insertInto(this.#Y).values({id:N1$,is_locked:0}).execute()}catch(J){if(!await this.#O())throw J}}async#z(){return(await this.#$.db.introspection.getSchemas()).some((J)=>J.name===this.#X)}async#K($){let J=this.#X;return(await this.#$.db.introspection.getTables({withInternalKyselyTables:!0})).some((Q)=>Q.name===$&&(!J||Q.schema===J))}async#O(){return!!await this.#$.db.withPlugin(this.#W).selectFrom(this.#Y).where("id","=",N1$).select("id").executeTakeFirst()}async#L($,J){let X=this.#$.db.getExecutor().adapter,Q=P({lockTable:this.#$.migrationLockTableName??UG,lockRowId:N1$,lockTableSchema:this.#$.migrationTableSchema}),Y=async(Z)=>{let j=await this.#N(Z);if(j.migrations.length===0)return{results:[]};let{direction:V,step:K}=$(j);if(K<=0)return{results:[]};if(V==="Down")return await this.#q(Z,j,K);else if(V==="Up")return await this.#E(Z,j,K);return{results:[]}},W=async(Z,j)=>{try{return await X.acquireMigrationLock(Z,Q),await j(Z)}finally{await X.releaseMigrationLock(Z,Q)}},G=J?.disableTransactions??this.#$.disableTransactions;if(this.#$.db.isTransaction){if(!X.supportsTransactionalDdl)throw Error("Transactional DDL is not supported in this dialect. Passing a transaction to this migrator would result in failure or unexpected behavior.");if(G)throw Error("`disableTransactions` is true but the migrator was given a transaction. Passing a transaction to this migrator would result in failure or unexpected behavior.");return W(this.#$.db,Y)}if(X.supportsTransactionalDdl&&!G)return this.#$.db.connection().execute((Z)=>W(Z,(j)=>j.transaction().execute((V)=>Y(V))));return this.#$.db.connection().execute((Z)=>W(Z,Y))}async#N($){let J=await this.#F(),X=await this.#_($);if(this.#M(J,X),!this.#G)this.#R(J,X);let Q=this.#A(J,X);return P({migrations:J,executedMigrations:X,lastMigration:tA$(X),pendingMigrations:Q})}#A($,J){return $.filter((X)=>{return!J.includes(X.name)})}async#F(){let $=await this.#$.provider.getMigrations();return Object.keys($).sort().map((J)=>({...$[J],name:J}))}async#_($){let J=await $.withPlugin(this.#W).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute(),X=this.#$.nameComparator||((Q,Y)=>Q.localeCompare(Y));return J.sort((Q,Y)=>{if(Q.timestamp===Y.timestamp)return X(Q.name,Y.name);return new Date(Q.timestamp).getTime()-new Date(Y.timestamp).getTime()}).map((Q)=>Q.name)}#M($,J){for(let X of J)if(!$.some((Q)=>Q.name===X))throw Error(`corrupted migrations: previously executed migration ${X} is missing`)}#R($,J){for(let X=0;X<J.length;++X)if($[X].name!==J[X])throw Error(`corrupted migrations: expected previously executed migration ${J[X]} to be at index ${X} but ${$[X].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#q($,J,X){let Q=J.executedMigrations.toReversed().slice(0,X).map((W)=>{return J.migrations.find((G)=>G.name===W)}),Y=Q.map((W)=>{return{migrationName:W.name,direction:"Down",status:"NotExecuted"}});for(let W=0;W<Y.length;++W){let G=Q[W];try{if(G.down)await G.down($),await $.withPlugin(this.#W).deleteFrom(this.#Q).where("name","=",G.name).execute(),Y[W]={migrationName:G.name,direction:"Down",status:"Success"}}catch(Z){throw Y[W]={migrationName:G.name,direction:"Down",status:"Error"},new Xf({error:Z,results:Y})}}return{results:Y}}async#E($,J,X){let Y=J.pendingMigrations.slice(0,X).map((W)=>{return{migrationName:W.name,direction:"Up",status:"NotExecuted"}});for(let W=0;W<Y.length;W++){let G=J.pendingMigrations[W];try{await G.up($),await $.withPlugin(this.#W).insertInto(this.#Q).values({name:G.name,timestamp:new Date().toISOString()}).execute(),Y[W]={migrationName:G.name,direction:"Up",status:"Success"}}catch(Z){throw Y[W]={migrationName:G.name,direction:"Up",status:"Error"},new Xf({error:Z,results:Y})}}return{results:Y}}async#H($){if(this.#$.db.getExecutor().adapter.supportsCreateIfNotExists)$=$.ifNotExists();await $.execute()}}var _8="kysely_migration",UG="kysely_migration_lock",uD0=!1,N1$="migration_lock",rt1,Xf;var DL=D(()=>{wD();G$();rt1=P({__noMigrations__:!0});Xf=class Xf extends Error{#$;constructor($){super();this.#$=$}get resultSet(){return this.#$}}});class iM{#$;constructor($){this.#$=$}async getSchemas(){return[]}async getTables($={withInternalKyselyTables:!1}){return await this.#X($)}#J($,J){let X=$.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!J.withInternalKyselyTables)X=X.where("name","!=",_8).where("name","!=",UG);return X}async#X($){let J=await this.#J(this.#$,$).execute(),X=await this.#$.with("table_list",(Y)=>this.#J(Y,$)).selectFrom(["table_list as tl",$0`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),Q={};for(let Y of X)Q[Y.table]??=[],Q[Y.table].push(Y);return J.map(({name:Y,sql:W,type:G})=>{let Z=W?.split(/[\(\),]/)?.find((V)=>V.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),j=Q[Y]??[];if(!Z){let V=j.filter((K)=>K.pk>0);if(V.length===1&&V[0].type.toLowerCase()==="integer")Z=V[0].name}return{name:Y,isView:G==="view",isForeign:!1,columns:j.map((V)=>({name:V.name,dataType:V.type,isNullable:!V.notnull,isAutoIncrementing:V.name===Z,hasDefaultValue:V.dflt_value!=null,comment:void 0}))}})}}var _1$=D(()=>{DL();nU()});var oM;var M1$=D(()=>{oM=class oM extends zV{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock($,J){}async releaseMigrationLock($,J){}}});class mD0{#$;constructor($){this.#$=P({...$})}createDriver(){return new D1$(this.#$)}createQueryCompiler(){return new dM}createAdapter(){return new oM}createIntrospector($){return new iM($)}}var uM$=D(()=>{F1$();q1$();_1$();M1$();G$()});function dU($,J){if(lD0($)&&J.stack){let X=J.stack.split(`
|
|
30
30
|
`).slice(1).join(`
|
|
31
31
|
`);return $.stack+=`
|
|
32
32
|
${X}`,$}return $}function lD0($){return L6($)&&C1($.stack)}var rM=D(()=>{G$()});class R1${#$;#J=new WeakMap;#X;constructor($){this.#$=P({...$})}async init($){this.#X=a4(this.#$.pool)?await this.#$.pool($):this.#$.pool}async acquireConnection($){let J=await this.#Q(),X=this.#J.get(J);if(!X){if(X=new lM$(J,this.#$.controlConnection),this.#J.set(J,X),this.#$?.onCreateConnection)await this.#$.onCreateConnection(X,$)}if(this.#$?.onReserveConnection)await this.#$.onReserveConnection(X,$);return X}async beginTransaction($,J){if(J.isolationLevel||J.accessMode){let X=[];if(J.isolationLevel)X.push(`isolation level ${J.isolationLevel}`);if(J.accessMode)X.push(J.accessMode);let Q=`set transaction ${X.join(", ")}`;await $.executeQuery(a8.raw(Q))}await $.executeQuery(a8.raw("begin"))}async commitTransaction($){await $.executeQuery(a8.raw("commit"))}async rollbackTransaction($){await $.executeQuery(a8.raw("rollback"))}async savepoint($,J,X){await $.executeQuery(X(L5("savepoint",J),M1()))}async rollbackToSavepoint($,J,X){await $.executeQuery(X(L5("rollback to",J),M1()))}async releaseSavepoint($,J,X){await $.executeQuery(X(L5("release savepoint",J),M1()))}async releaseConnection($){$[mM$]()}async destroy(){return new Promise(($,J)=>{this.#X.end((X)=>{if(X)J(X);else $()})})}async#Q(){return new Promise(($,J)=>{this.#X.getConnection(async(X,Q)=>{if(X)J(X);else $(Q)})})}}function pD0($){return L6($)&&"insertId"in $&&"affectedRows"in $}var mM$,lM$;var E1$=D(()=>{nM();lD();G$();SY();rM();mM$=Symbol();lM$=class lM${#$;#J;#X;#Q;constructor($,J){this.#$=$,this.#J=J}async cancelQuery($){await this.#G(`kill query ${this.#X}`,$)}async collectSessionInfo(){if(this.#X)return;let{threadId:$}=this.#$;if($!=null)this.#X=$;else{let[{cid:J}]=await this.#Y(a8.raw("select connection_id() as cid"));this.#X=Number(J)}}async executeQuery($){try{this.#Q=$.queryId;let J=await this.#Y($);if(!pD0(J))return{rows:Array.isArray(J)?J:[]};let{insertId:X,affectedRows:Q,changedRows:Y}=J;return{insertId:X!=null&&X.toString()!=="0"?BigInt(X):void 0,numAffectedRows:Q!=null?BigInt(Q):void 0,numChangedRows:Y!=null?BigInt(Y):void 0,rows:[]}}catch(J){throw dU(J,Error())}finally{this.#Q=void 0}}async killSession($){try{this.#$.destroy()}catch{}await this.#G(`kill connection ${this.#X}`,$)}async*streamQuery($,J){this.#Q=$.queryId;let X=this.#$.query($.sql,$.parameters).stream({objectMode:!0});try{for await(let Q of X)yield{rows:[Q]}}catch(Q){if(L6(Q)&&"code"in Q&&Q.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw Q}finally{this.#Q=void 0}}[mM$](){this.#$.release()}#Y($){return new Promise((J,X)=>{this.#$.query($.sql,$.parameters,(Q,Y)=>{if(Q)X(Q);else J(Y)})})}async#G($,J){if(!this.#Q)return;let{config:X}=this.#$,Q=this.#Q;if(!this.#J||!X)return await J(async(j)=>{if(Q.queryId===this.#Q?.queryId)await j.executeQuery(a8.raw($,[]))});let{clientFlags:Y,maxPacketSize:W,...G}=X,Z=this.#J(G);try{await new Promise((j,V)=>{Z.connect((K)=>{if(K)return V(K);if(Q.queryId!==this.#Q?.queryId)return j();Z.query($,[],(z)=>{if(z)return V(z);j()})})})}finally{Z.destroy()}}}});var cD0,P1$,nD0,T1$;var C1$=D(()=>{BL();cD0=/[\\']/g,P1$=/`/g,nD0=/[\\'"]/g;T1$=class T1$ extends UV{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return P1$.source}getRightIdentifierWrapper(){return P1$.source}sanitizeIdentifier($){return $.replace(P1$,"``")}sanitizeStringLiteral($){return $.replace(cD0,(J)=>J==="\\"?"\\\\":"''")}sanitizeJSONPathMemberValue($){return $.replace(nD0,(J)=>J==="\\"?"\\\\\\\\":J==="'"?"''":'\\\\"')}visitCreateIndex($){if(this.append("create "),$.unique)this.append("unique ");if(this.append("index "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),$.using)this.append(" using "),this.visitNode($.using);if($.table)this.append(" on "),this.visitNode($.table);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.where)this.append(" "),this.visitNode($.where)}}});class S1${#$;constructor($){this.#$=$}async getSchemas(){return(await this.#$.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((J)=>({name:J.SCHEMA_NAME}))}async getTables($={withInternalKyselyTables:!1}){let J=this.#$.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(Q)=>Q.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","tables.ENGINE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",$0`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!$.withInternalKyselyTables)J=J.where("columns.TABLE_NAME","!=",_8).where("columns.TABLE_NAME","!=",UG);let X=await J.execute();return this.#J(X)}#J($){return $.reduce((J,X)=>{let Q=J.find((Y)=>Y.name===X.TABLE_NAME);if(!Q)Q=P({name:X.TABLE_NAME,isView:X.TABLE_TYPE==="VIEW",isForeign:X.ENGINE==="FEDERATED",schema:X.TABLE_SCHEMA,columns:[]}),J.push(Q);return Q.columns.push(P({name:X.COLUMN_NAME,dataType:X.DATA_TYPE,isNullable:X.IS_NULLABLE==="YES",isAutoIncrementing:X.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:X.COLUMN_DEFAULT!==null,comment:X.COLUMN_COMMENT===""?void 0:X.COLUMN_COMMENT})),J},[])}}var I1$=D(()=>{DL();G$();nU()});var pM$="ea586330-2c93-47c8-908d-981d9d270f9d",dD0=3600,k1$;var x1$=D(()=>{nU();k1$=class k1$ extends zV{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock($,J){await $0`select get_lock(${$0.lit(pM$)}, ${$0.lit(dD0)})`.execute($)}async releaseMigrationLock($,J){await $0`select release_lock(${$0.lit(pM$)})`.execute($)}}});class iD0{#$;constructor($){this.#$=$}createDriver(){return new R1$(this.#$)}createQueryCompiler(){return new T1$}createAdapter(){return new k1$}createIntrospector($){return new S1$($)}}var cM$=D(()=>{E1$();C1$();I1$();x1$()});class b1${#$;#J=new WeakMap;#X;constructor($){this.#$=P({...$})}async init($){this.#X=a4(this.#$.pool)?await this.#$.pool($):this.#$.pool}async acquireConnection($){let J=await this.#X.connect(),X=this.#J.get(J);if(!X){if(X=new dM$(J,{controlClient:this.#$.controlClient||this.#X.Client,cursor:this.#$.cursor??null,poolOptions:this.#X.options}),this.#J.set(J,X),this.#$.onCreateConnection)await this.#$.onCreateConnection(X,$)}if(this.#$.onReserveConnection)await this.#$.onReserveConnection(X,$);return X}async beginTransaction($,J){let X="begin";if(J.isolationLevel||J.accessMode){if(X="start transaction",J.isolationLevel)X+=` isolation level ${J.isolationLevel}`;if(J.accessMode)X+=` ${J.accessMode}`}await $.executeQuery(a8.raw(X))}async commitTransaction($){await $.executeQuery(a8.raw("commit"))}async rollbackTransaction($){await $.executeQuery(a8.raw("rollback"))}async savepoint($,J,X){await $.executeQuery(X(L5("savepoint",J),M1()))}async rollbackToSavepoint($,J,X){await $.executeQuery(X(L5("rollback to",J),M1()))}async releaseSavepoint($,J,X){await $.executeQuery(X(L5("release",J),M1()))}async releaseConnection($){$[nM$]()}async destroy(){if(this.#X){let $=this.#X;this.#X=void 0,await $.end()}}}var nM$,dM$;var y1$=D(()=>{nM();lD();G$();SY();rM();nM$=Symbol();dM$=class dM${#$;#J;#X;#Q;constructor($,J){this.#$=$,this.#J=J}async cancelQuery($){return await this.#Y(`select pg_cancel_backend(${this.#Q})`,$)}async collectSessionInfo(){if(this.#Q)return;let{processID:$}=this.#$;if($)this.#Q=$;else{let{rows:[{pid:J}]}=await this.#$.query("select pg_backend_pid() as pid",[]);this.#Q=Number(J)}}async executeQuery($){try{this.#X=$.queryId;let J=await this.#$.query($.sql,$.parameters),{command:X,rowCount:Q,rows:Y}=J;return{numAffectedRows:X==="INSERT"||X==="UPDATE"||X==="DELETE"||X==="MERGE"?BigInt(Q):void 0,rows:Y??[]}}catch(J){throw dU(J,Error())}finally{this.#X=void 0}}async killSession($){return await this.#Y(`select pg_terminate_backend(${this.#Q})`,$)}async*streamQuery($,J){if(!this.#J.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#X=$.queryId;let X=this.#$.query(new this.#J.cursor($.sql,$.parameters.slice()));try{while(!0){let Q=await X.read(J);if(Q.length===0)break;yield{rows:Q}}}finally{await X.close(),this.#X=void 0}}[nM$](){this.#$.release()}async#Y($,J){if(!this.#X)return;let{controlClient:X,poolOptions:Q}=this.#J,Y=this.#X;if(!X)return await J(async(G)=>{if(Y.queryId===this.#X?.queryId)await G.executeQuery(a8.raw($,[]))});let W=new X({...Q,password:"password"in Q?Q.password:void 0});try{if(await W.connect(),Y.queryId!==this.#X.queryId)return;await W.query($,[])}finally{W.end()}}}});class tM{#$;constructor($){this.#$=$}async getSchemas(){return(await this.#$.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((J)=>({name:J.nspname}))}async getTables($={withInternalKyselyTables:!1}){let J=this.#$.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",$0`col_description(a.attrelid, a.attnum)`.as("column_description"),$0`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p","f"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where($0`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!$.withInternalKyselyTables)J=J.where("c.relname","!=",_8).where("c.relname","!=",UG);let X=await J.execute();return this.#J(X)}#J($){let J=[],X=new Map;for(let Q of $){let Y=X.get(Q.schema);if(!Y)Y=new Map,X.set(Q.schema,Y);let W=Y.get(Q.table);if(!W)W=P({columns:[],isForeign:Q.table_type==="f",isView:Q.table_type==="v",name:Q.table,schema:Q.schema}),Y.set(Q.table,W),J.push(W);W.columns.push(P({comment:Q.column_description??void 0,dataType:Q.type,dataTypeSchema:Q.type_schema,hasDefaultValue:Q.has_default,isAutoIncrementing:Q.auto_incrementing!==null,isNullable:!Q.not_null,name:Q.column}))}return J}}var Qf=D(()=>{DL();G$();nU()});var oD0,aM;var Yf=D(()=>{BL();oD0=/"/g;aM=class aM extends UV{sanitizeIdentifier($){return $.replace(oD0,'""')}}});var iM$,rD0=3600000,sM;var Wf=D(()=>{nU();iM$=BigInt("3853314791062309107");sM=class sM extends zV{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock($,J){await $0`
|
|
@@ -46,7 +46,7 @@ ${X.join(`
|
|
|
46
46
|
`)}`),null}async enrichDeviceInfoList($){return await Promise.all($.map(async(X)=>{try{let Q=await this.avdConfigReader.readConfig(X.name);if(!Q)return X;return{...X,osVersion:Q.osVersion??X.osVersion,screenWidth:Q.screenWidth??X.screenWidth,screenHeight:Q.screenHeight??X.screenHeight,screenDensity:Q.screenDensity??X.screenDensity,formFactor:gq0(Q.deviceName)??X.formFactor}}catch(Q){return U.debug(`Failed to enrich AVD ${X.name}: ${Q}`),X}}))}async getEmulatorPath(){let $=await this.tryMultiplePaths();if($)return $;return this.getFallbackEmulatorPath()}async ensureEmulatorPath(){let $=await this.getEmulatorPath();return this.emulatorPath=$,this.emulatorPath}isResolvedEmulatorPathAvailable(){let $=this.emulatorPath.trim();if($.length===0)return!1;if(!$.includes("/")&&!$.includes("\\"))return!1;return yq0($)}describeEmulatorResolution(){return[` resolved emulator path: ${this.emulatorPath||"<unset>"}`,` ANDROID_HOME=${process.env.ANDROID_HOME??"<unset>"}`,` ANDROID_SDK_ROOT=${process.env.ANDROID_SDK_ROOT??"<unset>"}`,` ANDROID_SDK_HOME=${process.env.ANDROID_SDK_HOME??"<unset>"}`,` PATH=${process.env.PATH??"<unset>"}`].join(`
|
|
47
47
|
`)}isLikelyDaemonWorkingDirectoryFailure($){if(!this.isResolvedEmulatorPathAvailable())return!1;let J=$.toLowerCase();return J.includes("enoent")&&J.includes("spawn")||J.includes("getcwd")||J.includes("current working directory")||J.includes("current directory")}getHostArchitecture(){return vq0()}async checkArchitectureCompatibility($){let J=this.getHostArchitecture();try{let X=await this.executeCommand(["-avd",$,"-verbose"],3000),Q=X.stdout+X.stderr,Y,W=Q.match(/Found AVD target architecture: (\w+)/);if(W)Y=W[1];if(!Y)return{compatible:!0,hostArch:J,reason:"Could not determine AVD architecture, allowing attempt"};let G=this.isArchitectureCompatible(J,Y),Z=G?void 0:`Host architecture '${J}' cannot run AVD with architecture '${Y}'`;return{compatible:G,hostArch:J,avdArch:Y,reason:Z}}catch(X){return U.debug(`Could not check architecture compatibility for ${$}: ${X}`),{compatible:!0,hostArch:J,reason:"Could not verify compatibility, allowing attempt"}}}isArchitectureCompatible($,J){if(($==="arm64"||$==="aarch64")&&(J==="x86"||J==="x86_64"))return!1;return!0}detectArchitecturePanic($){let J=$.match(/PANIC: Avd's CPU Architecture '(\w+)' is not supported by the QEMU2 emulator on (\w+) host/);if(J){let X=J[1],Q=J[2];return{isPanic:!0,message:`AVD architecture '${X}' is not supported on ${Q} host`,hostArch:Q,avdArch:X}}if($.includes("PANIC:")&&($.includes("architecture")||$.includes("CPU")||$.includes("QEMU")))return{isPanic:!0,message:"Emulator PANIC detected (possibly architecture-related)"};return{isPanic:!1}}detectSandboxMprotect($){let J=/qemu_mprotect__osdep:\s*mprotect failed:\s*permission denied/i.test($),X=/hvf is not enabled on this aarch64 host|HVF error:\s*HV_(?:UNSUPPORTED|ERROR)|failed to initialize HVF:\s*Invalid argument/i.test($);if(!J&&!X)return{isSandboxError:!1};return{isSandboxError:!0,message:"Emulator hypervisor initialization failed (mprotect/HVF is unavailable)",suggestion:"Run the emulator outside the restrictive sandbox or grant the host hypervisor/JIT entitlement required by QEMU."}}sandboxFailure($){let J=this.detectSandboxMprotect($);if(!J.isSandboxError)return null;return new R([`Emulator failed to start: ${J.message}`,J.suggestion?`Suggestion: ${J.suggestion}`:""].filter(Boolean).join(`
|
|
48
48
|
|
|
49
|
-
`))}async validateAvdMemory($){let J=await this.avdConfigReader.readConfig($);if(!J)return;
|
|
49
|
+
`))}async validateAvdMemory($){let J=await this.avdConfigReader.readConfig($);if(!J)return;let X=J.tag?.toLowerCase().includes("play")&&(J.apiLevel??0)>=hq0;if(X&&J.ramSizeInvalid)throw new R(`Cannot start AVD '${$}': hw.ramSize is invalid. Use a whole number in MB or a K, M, or G size suffix and retry.`);if(X&&J.ramSizeMb!==void 0&&J.ramSizeMb<PU)throw new R(`Cannot start AVD '${$}': hw.ramSize is ${J.ramSizeMb} MB, below the minimum ${PU} MB needed for a modern system image. Increase hw.ramSize in the AVD config and retry.`)}async detectOfflineFailure($,J,X){let Q;try{Q=await this.adbFactory.create(null).getDeviceStates?.({timeoutMs:X})??[]}catch(W){return U.debug(`Offline-state probe unavailable during emulator readiness: ${W instanceof Error?W.message:String(W)}`),J.deviceId=null,J.since=null,null}let Y=$?Q.find((W)=>W.deviceId===$):void 0;if(Y?.state!=="offline")return J.deviceId=null,J.since=null,null;if(J.deviceId!==Y.deviceId)J.deviceId=Y.deviceId,J.since=this.timer.now();return null}detectCorruptImage($){let J=$.match(/qcow2:\s*(.*corrupt[^"\n]*)/i);if(J)return{isCorrupt:!0,message:`Disk image is corrupt: ${J[1].trim()}`,suggestion:`Delete the corrupt userdata overlay to force a fresh image:
|
|
50
50
|
rm ~/.android/avd/<AVD_NAME>.avd/userdata-qcow2.img
|
|
51
51
|
rm ~/.android/avd/<AVD_NAME>.avd/userdata-qcow2.img.qcow2
|
|
52
52
|
The emulator will recreate it on next boot. All emulator data (installed apps, settings) will be lost.`};let X=$.match(/(cannot open disk image|disk image .* is (?:corrupt|invalid|damaged)|failed to open .*\.img)/i);if(X)return{isCorrupt:!0,message:`Disk image error: ${X[1].trim()}`,suggestion:"Try deleting corrupt overlay files in ~/.android/avd/<AVD_NAME>.avd/ and restarting the emulator."};if($.includes("QEMU main loop exits abnormally")&&($.includes("corrupt")||$.includes("qcow2")))return{isCorrupt:!0,message:"QEMU exited abnormally due to disk image corruption",suggestion:`Delete the corrupt userdata overlay to force a fresh image:
|
|
@@ -1135,4 +1135,4 @@ ${Q.stderr}`;if(Q.exitCode!==0||!Y.includes("h264_videotoolbox"))throw new R("iO
|
|
|
1135
1135
|
|
|
1136
1136
|
`)},aE1):void 0,V=()=>{if(j)u.clearInterval(j)};J.on("close",V),J.on("finish",V);try{await Y.handleRequest($,J,W)}catch(K){U.error("Streamable HTTP request handling failed:",K),Z("Server error",K)}finally{V()}}else J.writeHead(404,{"Content-Type":"application/json"}),J.end(JSON.stringify({error:"Not found"}))}),new Promise(($,J)=>{this.httpServer.listen(this.port,this.host,()=>{U.info(`automobile:${this.host}:${this.port}${pD}`),$()}),this.httpServer.on("error",(X)=>{U.error(`HTTP server error: ${X}`),J(X)})})}async persistPidFileData($){await iE1(rE1(xJ),{recursive:!0}),await oE1(xJ,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),this.pidFileWritten=!0}async writeEarlyOwnerRecord(){let $={pid:process.pid,socketPath:i6,port:this.port,dbPath:LV(),startedAt:this.timer.now(),version:hY,assetVersion:E9(Z4()),options:this.options};await this.persistPidFileData($),U.info(`Early daemon owner record written to ${xJ} (dbPath ${$.dbPath})`)}async writePidFile(){let $=QY(),J={pid:process.pid,socketPath:i6,sockets:e20(),port:this.port,dbPath:LV(),startedAt:this.timer.now(),version:hY,assetVersion:E9(Z4()),entryScript:$.entryScript,buildId:$.buildId,options:this.options};await this.persistPidFileData(J),U.info(`PID file written to ${xJ}`)}setupDeviceDataStreamCallback(){let $=E6();if(!$){U.warn("[Daemon] Observation stream server not available for callback setup");return}$.setOnSubscriberConnected((J)=>{U.info(`[Daemon] IDE plugin subscribed to observation stream (device: ${J??"all"}), ensuring WebSocket connections...`);let X=this.devicePool.getAllDevices();if(JL0(J,X,{streamServer:$,androidClientFactory:(Q)=>E$.getInstance(Q,V$),iosClientFactory:(Q)=>this.createObservationStreamIosClient(Q)}).catch((Q)=>{U.warn(`[Daemon] Error pushing initial observation frame: ${Q}`)}),X.length===0)U.info("[Daemon] No devices in pool to connect")}),$.setOnScreenshotCadenceChanged((J)=>{let X=this.devicePool.getAllDevices().filter((Q)=>J===null||Q.id===J);for(let Q of X)if(Q.platform==="android")E$.getExistingInstance(Q.id)?.refreshObservationStreamScreenshotCadence();else if(Q.platform==="ios")_$.getExistingInstance(Q.id)?.refreshObservationStreamScreenshotCadence()}),$.setOnHierarchyCadenceChanged((J)=>{let X=this.devicePool.getAllDevices().filter((Q)=>J===null||Q.id===J);for(let Q of X)if(Q.platform==="android")E$.getExistingInstance(Q.id)?.refreshObservationStreamHierarchyCadence();else if(Q.platform==="ios"){let Y=_$.getExistingInstance(Q.id);if(!Y)continue;let W=$.getHierarchyIntervalMsForDevice(Q.id);Y.ensureConnected().then((G)=>{if(G)Y.refreshObservationStreamHierarchyCadence(W)}).catch((G)=>{U.warn(`[Daemon] Failed to refresh iOS hierarchy cadence for ${Q.id}: ${G}`)})}}),$.setOnObservationRequested(async({deviceId:J,signal:X})=>{let Q=J?[this.devicePool.getDevice(J)].filter((G)=>G!==null):this.devicePool.getAllDevices();if(Q.length===0)throw Error(J?`Device ${J} is not available`:"No devices are available");let Y=this.timer.now(),W=[];for(let G of Q){if(X.aborted)throw Error("Observation request was aborted");let Z={deviceId:G.id,name:G.name,platform:G.platform,iosVersion:G.iosVersion},V=await new B4(Z).execute({skipWaitForFresh:!1,minTimestamp:Y,signal:X});W.push({deviceId:G.id,observation:V})}return W}),U.info("[Daemon] Observation stream callback configured"),this.setupNavigationGraphStreamListener($)}createObservationStreamIosClient($){let J=_$.getInstance($);return{ensureConnected:async()=>{let X=await J.ensureConnected(),Q=E6();if(X&&Q)J.refreshObservationStreamHierarchyCadence(Q.getHierarchyIntervalMsForDevice($.deviceId));return X},getLatestHierarchy:(...X)=>J.getLatestHierarchy(...X),requestHierarchySyncWithoutObservationStreamPush:async(...X)=>{let Q=await J.requestHierarchySyncWithoutObservationStreamPush(...X);return Q?{hierarchy:Q.hierarchy,...Q.frameContext===void 0?{}:{frameContext:Q.frameContext}}:null},convertToViewHierarchyResult:(X)=>J.convertToViewHierarchyResult(X),recordInitialObservationStreamHierarchy:(X,Q)=>J.recordInitialObservationStreamHierarchy(X,Q),requestScreenshotWithoutObservationStreamPush:(...X)=>J.requestScreenshotWithoutObservationStreamPush(...X)}}setupNavigationGraphStreamListener($){if(!$)return;let J=c0.getInstance();J.setGraphUpdateListener(async()=>{U.info("[Daemon] Navigation graph listener triggered, exporting summary...");try{let X=await J.exportGraphSummary();U.info(`[Daemon] Got summary: appId=${X.appId}, nodes=${X.nodes.length}, edges=${X.edges.length}`);let Q=iq$(X);$.pushNavigationGraphUpdate(Q),U.info(`[Daemon] Pushed navigation graph update: ${X.nodes.length} nodes, ${X.edges.length} edges`)}catch(X){U.warn(`[Daemon] Failed to push navigation graph update: ${X}`)}}),$.setOnNavigationGraphRequested(WL0(J)),U.info("[Daemon] Navigation graph stream listener configured")}startHealthCheckTimer(){let X=0,Q="unknown",Y=(G)=>{if(Q!==G)X=0;Q=G,X++},W=()=>{X=0,Q="unknown"};if(this.healthCheckTimer=this.timer.setInterval(async()=>{try{if(!this.httpServer)U.warn("Health check failed: HTTP server not initialized"),Y("http");else if(!this.httpServer.listening)U.warn("Health check failed: HTTP server not listening"),Y("http");else if(!this.socketServer||!this.socketServer.isListening())U.warn("Health check failed: Socket server not listening"),Y("socket");else if(!this.observationStreamHealth.isHealthy())U.warn("Health check failed: Observation stream socket unavailable"),Y("socket");else try{await this.databaseHealthProbe.check(),W(),U.debug("Health check passed")}catch(G){U.warn(`Health check failed: Database probe failed: ${G}`),Y("database")}if(X>=3)U.error(`Health check failed ${X} times, attempting recovery...`),await this.attemptRecovery(Q),W()}catch(G){U.warn(`Health check error: ${G}`),Y("unknown")}},30000),typeof this.healthCheckTimer.unref==="function")this.healthCheckTimer.unref()}stopHealthCheckTimer(){if(this.healthCheckTimer)this.timer.clearInterval(this.healthCheckTimer),this.healthCheckTimer=null}startHeartbeatMonitor(){this.heartbeatMonitor=new QL$(this.sessionManager,($)=>PG.hasActiveSessionUuidExecutions($),($)=>this.cancelAndReleaseSession($),this.timer),this.heartbeatMonitor.start()}startDeviceDisconnectMonitor(){if(this.deviceDisconnectTimer)return;let $=new B9;this.deviceDisconnectTimer=u.setInterval(async()=>{try{if(f$.isPlanExecutionActive()){U.debug("[DisconnectMonitor] Skipping \u2014 plan execution active");return}let J=await $.getBootedDevicesDetailed("either"),X=J.devices,Q=J.succeededPlatforms,Y=new Set(X.map((z)=>z.deviceId)),W=await XO(),G=new Map,Z=new Set,j=new Map,V=new Set;for(let z of W)Z.add(z.deviceId),j.set(z.deviceId,z.platform);for(let z of this.devicePool.getAllDevices())if(Z.add(z.id),j.set(z.id,z.platform),z.status==="idle")V.add(z.id);for(let z of this.sessionManager.getAssignedDevices())Z.add(z);let K=ZL0({deviceDisconnectMisses:this.deviceDisconnectMisses,confirmedDisconnectedDeviceIds:this.confirmedDisconnectedDeviceIds,bootedDeviceIds:Y,candidateDeviceIds:Z,succeededPlatforms:Q,candidatePlatforms:j,idleCandidateIds:V,forceDisconnectedDeviceIds:this.forceDisconnectedDeviceIds,missThreshold:rs});if(K.skippedAdbUnreachable){U.warn(`[DisconnectMonitor] ADB returned 0 devices but ${Z.size} tracked \u2014 skipping miss count (ADB likely unreachable)`);return}for(let{deviceId:z,misses:L}of K.missed)U.info(`[DisconnectMonitor] Device ${z} not in booted list (miss ${L}/${rs}, booted=${Y.size})`);for(let z of K.disconnected)G.set(z,[]);for(let z of W)if(G.has(z.deviceId))G.get(z.deviceId).push(z.recordingId);for(let[z,L]of G.entries()){let H=this.devicePool.getDevice(z);if(await this.shouldSkipStaleDisconnectCleanup(H,z))continue;let O=!0;lz().stopMonitoring(z);for(let F of L){if(this.stoppingRecordings.has(F)){O=!1;continue}this.stoppingRecordings.add(F);try{await XQ(F),U.warn(`[Daemon] Stopped recording ${F} after device ${z} disconnected`)}catch(A){U.warn(`[Daemon] Failed to stop recording ${F} after device ${z} disconnected: ${A}`);try{await oa$(F),U.warn(`[Daemon] Marked recording ${F} interrupted after device ${z} disconnected`)}catch(_){O=!1,U.warn(`[Daemon] Failed to mark recording ${F} interrupted after device ${z} disconnected: ${_}`)}}finally{this.stoppingRecordings.delete(F)}}if(await this.shouldSkipStaleDisconnectCleanup(H,z))continue;let B=this.sessionManager.getSessionForDevice(z);if(B)U.warn(`[DisconnectMonitor] Device ${z} confirmed disconnected after ${rs} consecutive misses \u2014 cancelling session ${B}`),await this.cancelAndReleaseSession(B,`device-disconnected:${z}`);if(await this.devicePool.removeDisconnectedDevice(z),this.socketServer?.evictDeviceInputCache(z),this.devicePool.getDevice(z))O=!1;if(O)this.confirmedDisconnectedDeviceIds.add(z),this.deviceDisconnectMisses.delete(z),this.forceDisconnectedDeviceIds.delete(z)}}catch(J){U.warn(`[Daemon] Device disconnect monitor failed: ${J}`)}},tE1),this.deviceDisconnectTimer.unref()}async shouldSkipStaleDisconnectCleanup($,J){if(!$||await this.devicePool.isCurrentDisconnectedDevice($))return!1;return U.info(`[DisconnectMonitor] Skipping stale disconnect cleanup for recovered device ${J}`),!0}startAdbMissingDeviceListener(){if(this.unsubscribeAdbMissingDevice)return;this.unsubscribeAdbMissingDevice=kA$(($)=>{if(!this.devicePool.getDevice($.deviceId)&&!this.sessionManager.getSessionForDevice($.deviceId))return;U.warn(`[Daemon] ADB reported tracked device ${$.deviceId} missing: ${$.message}`),this.forceDisconnectedDeviceIds.add($.deviceId),this.deviceDisconnectMisses.set($.deviceId,rs)})}async cancelAndReleaseSession($,J="explicit-release"){let X=await PG.cancelSessionUuidExecutions($,J),Q=await this.sessionManager.releaseSession($,J);if(Q)await this.devicePool.releaseDevice(Q);U.info(`Cancelled session ${$} (${X} executions) and released device ${Q??"unknown"} (reason=${J})`)}async attemptRecovery($="unknown"){try{if(U.info("Attempting daemon recovery..."),$==="database"){U.error("Database health check failed repeatedly; exiting daemon for a clean restart."),this.recoverFromDatabaseHealthFailure(1);return}if(this.socketServer&&!this.socketServer.isListening()){U.info("Restarting socket server...");try{await this.socketServer.close()}catch(X){U.warn(`Error closing socket server during recovery: ${X}`)}let J=`http://${this.host}:${this.port}${pD}`;this.socketServer=new HI(i6,J,void 0,void 0,v8.getInstance());try{await this.socketServer.start(),U.info("Socket server restarted successfully")}catch(X){U.error(`Failed to restart socket server: ${X}`)}}if(!this.observationStreamHealth.isHealthy()){U.info("Restarting observation stream socket server...");try{await this.observationStreamHealth.recover(),U.info("Observation stream socket server restarted successfully")}catch(J){U.error(`Failed to restart observation stream socket server: ${J}`)}}}catch(J){U.error(`Recovery attempt failed: ${J}`)}}async initializeDevicePoolWithTimeout($){let J,X=new Promise((W)=>{if(J=u.setTimeout(()=>{U.warn(`Device pool initialization timed out after ${$}ms`),W()},$),typeof J.unref==="function")J.unref()}),Q=this.initializeDevicePool();try{await Promise.race([Q,X])}finally{if(J!==void 0)u.clearTimeout(J)}let Y=this.devicePool.getTotalDeviceCount();if(Y===0)U.warn("Device pool is empty after initialization."),U.warn("Tests will fail until devices are available."),U.warn("Start an emulator or connect a physical device, then restart the daemon.");else U.info(`Device pool ready with ${Y} device(s)`)}async initializeDevicePool(){try{let J=await new B9().getBootedDevices("either");if(J.length>0)await this.devicePool.initializeWithDevices(J),U.info(`Device pool initialized with ${J.length} devices: ${J.map((X)=>X.deviceId).join(", ")}`);else U.warn("No devices detected during daemon startup. Device pool is empty."),U.warn("Start an emulator or connect a physical device before creating sessions.")}catch($){U.error(`Failed to initialize device pool: ${$}`)}}async initializeIosServices(){let J=this.devicePool.getAllDevices().filter((Y)=>Y.platform==="ios");if(J.length===0){U.debug("[Daemon] No iOS devices to initialize CtrlProxy iOS for");return}U.info(`[Daemon] Initializing CtrlProxy iOS for ${J.length} iOS device(s)...`);let X=m6.getInstance(),Q=5000;for(let Y of J)try{U.info(`[Daemon] Setting up CtrlProxy iOS for iOS device ${Y.id}`);let W=new Promise((G,Z)=>{let j=u.setTimeout(()=>{Z(Error(`Timeout after ${Q}ms`))},Q);if(typeof j.unref==="function")j.unref()});await Promise.race([X.verifyIosDevice(Y.id,{skipCtrlProxyDownload:!0}),W]),U.info(`[Daemon] CtrlProxy iOS ready for iOS device ${Y.id}`)}catch(W){U.warn(`[Daemon] Failed to initialize CtrlProxy iOS for ${Y.id}: ${W}`)}}async initializeDatabase(){try{await this.databaseInitializer.initialize(),await this.installedAppsRepository.clearOldDaemonSessions(this.daemonSessionId),await this.deviceSessionRepository.markStaleActiveSessionsExpired(this.daemonSessionId,this.timer.now(),"daemon-restart"),U.info(`[Daemon] Cleared old daemon session caches, current session: ${this.daemonSessionId}`)}catch($){await Kr($,this.startupFailureTracker,this.timer)}}setupShutdownHandlers(){if(this.shutdownHandlersRegistered)return;this.shutdownHandlersRegistered=!0,Sb(),Ib(async(J)=>{if(this.shutdownInProgress)return;this.shutdownInProgress=!0,U.info(`Received ${J}, shutting down daemon...`),await this.stop()}),process.once("exit",()=>{Pf(this.getDaemonFileCleanupOptions())}),kb(I50(U))}async stop(){if(U.info("Stopping daemon..."),this.stopHealthCheckTimer(),this.heartbeatMonitor)this.heartbeatMonitor.stop(),this.heartbeatMonitor=null;if(this.deviceDisconnectTimer)clearInterval(this.deviceDisconnectTimer),this.deviceDisconnectTimer=null;if(this.unsubscribeAdbMissingDevice)this.unsubscribeAdbMissingDevice(),this.unsubscribeAdbMissingDevice=null;if(this.sessionManager.stopCleanupTimer(),this.socketServer)await this.socketServer.close();await HL$(),await FL$(),await AL$(),await CL$(),await c50(),await zu$(),await iQ$(),await o50(),await Iu$(),await wg$(),await lq$(),await s20(),await ax.shutdown(),RL$(),JY$();for(let[X,Q]of this.transports)try{await Q.close()}catch(Y){U.warn(`Error closing Streamable HTTP session ${X}:`,Y)}if(this.transports.clear(),this.httpServer)await new Promise((X)=>{this.httpServer.close(()=>{U.info("HTTP server stopped"),X()})});if(await FL(this.getDaemonFileCleanupOptions()),!await f6().drain(KL0))U.warn(`Timed out after ${KL0}ms draining in-flight DB writes; closing database anyway`);if(!await mf(UL0))U.warn(`Timed out after ${UL0}ms awaiting in-flight startup migration; closing database anyway`);await lf(),U.info("Daemon stopped"),U.close()}getDaemonFileCleanupOptions(){if(this.pidFileWritten)return{expectedPid:process.pid};let $=iD();return $&&$.pid!==process.pid?{expectedPid:process.pid}:{}}getSessionManager(){return this.sessionManager}getDevicePool(){return this.devicePool}}async function sE1($={}){await new rq$($).start()}var tE1=5000,rs=3,aE1=30000,KL0=1000,UL0=5000;var LL0=D(()=>{mJ0();Y2$();d();uY();N50();XL$();A50();R50();pB();SQ();SQ();f3();FJ();Vm();wP();Sl();ZL$();P50();VL$();Ur();k50();Jb();zr();Lr();Hr();Dr();IL$();Xl();fV();bL$();Ml();lm();ds();dq$();$L0();O4();P0();J4();YL0();G7();GL0();t7();uV();Gr();lG();Br();sL();zK();U$();H5();cV();t4();_0();ye();_9();TJ();hb();jL0()});var HL0={};u1(HL0,{runDirectModeStartup:()=>eE1});async function eE1($){if($.noProxy)await $.assertDbOwnership();await $.applyFeatureFlagStartup()}var FL0={};u1(FL0,{findConflictingDaemons:()=>XP1,createDefaultDirectModeGuardDeps:()=>YP1,assertDirectModeDbOwnership:()=>QP1});import{realpathSync as OL0}from"fs";import{basename as $P1,dirname as JP1,resolve as BL0}from"path";function tq$($){let J=BL0($);try{return OL0(J)}catch{try{return BL0(OL0(JP1(J)),$P1(J))}catch{return J}}}function DL0($,J){return $.filter((X)=>X.dbPath!==void 0&&tq$(X.dbPath)===J)}function XP1($){return DL0($.findLiveDaemonDbOwners(),tq$($.resolveDbPath()))}function QP1($){let J=tq$($.resolveDbPath()),X=$.findLiveDaemonDbOwners(),Q=DL0(X,J);if(Q.length>0){let W=Q.map((G)=>G.pid).join(", ");throw new R(`A live AutoMobile daemon (pid ${W}) already owns the database at ${J}. Direct mode (--no-proxy/--direct) would open a second writer on the same SQLite file, causing SQLITE_BUSY stalls and competing migrations. Resolve this by either running without --no-proxy/--direct to share the daemon, stopping the daemon, or setting AUTOMOBILE_DB_PATH (or AUTOMOBILE_DB_DIR) to an isolated database for this direct-mode instance.`)}let Y=X.filter((W)=>W.dbPath===void 0);if(Y.length>0){let W=Y.map((G)=>G.pid).join(", ");throw new R(`Cannot safely start direct mode (--no-proxy/--direct): a live AutoMobile daemon (pid ${W}) is running but its database path could not be determined (it may still be starting up, or is using a non-default PID file), so a collision on ${J} cannot be ruled out. Wait for the daemon to finish starting and retry, stop the daemon, or set AUTOMOBILE_DB_PATH (or AUTOMOBILE_DB_DIR) to an isolated database for this direct-mode instance.`)}}function YP1($={}){let J=$.manager??new Yj,X=$.readPidFileData??iD;return{resolveDbPath:$.resolveDbPath??LV,findLiveDaemonDbOwners:()=>{let Y;try{Y=J.findLiveDaemonProcesses()}catch(V){let K=V instanceof Error?V.message:String(V);throw U.warn(`Direct-mode guard: process-table scan failed; refusing direct mode because same-DB daemon ownership cannot be verified. ${K}`,V),new R(`Cannot verify daemon ownership before starting direct mode (--no-proxy/--direct): failed to inspect the process table (${K}). Retry, stop any running daemon, or set AUTOMOBILE_DB_PATH (or AUTOMOBILE_DB_DIR) to an isolated database.`)}if(Y.length===0)return[];let W=[],G=new Set,Z=X();if(Z&&typeof Z.pid==="number"&&Z.dbPath!==void 0&&Y.includes(Z.pid))W.push({pid:Z.pid,dbPath:Z.dbPath}),G.add(Z.pid);let j=Y.filter((V)=>!G.has(V));if(j.length>0){U.debug(`Direct-mode guard: ${j.length} live daemon(s) could not be mapped to a DB path (starting up or non-default PID file); direct mode will refuse to be safe: ${j.join(", ")}`);for(let V of j)W.push({pid:V,dbPath:void 0})}return W}}}var qL0=D(()=>{t$();Sl();d();jI();FJ()});var VP1=y1(ts(),1);import*as Qw$ from"fs";import*as as from"os";import*as G5 from"path";function Yw$(){CL0(),SL0()}function CL0(){let $=G5.delimiter,J=process.env.PATH??"",X=new Set(J.split($).filter(Boolean)),Q=IL0(),Y=[];for(let W of Q)if(!X.has(W)&&Ww$(W))Y.push(W),X.add(W);if(Y.length===0)return;process.env.PATH=J.length>0?`${J}${$}${Y.join($)}`:Y.join($)}function SL0(){if(process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT)return;for(let $ of kL0())if(Ww$($)){process.env.ANDROID_HOME=$;return}}function IL0(){let $=process.platform,J=as.homedir();if($==="darwin")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin","/opt/homebrew/bin","/opt/homebrew/sbin",G5.join(J,"Library/Android/sdk/platform-tools"),G5.join(J,"Library/Android/sdk/emulator"),G5.join(J,"Library/Android/sdk/cmdline-tools/latest/bin")];if($==="linux")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin",G5.join(J,"Android/Sdk/platform-tools"),G5.join(J,"Android/Sdk/emulator"),G5.join(J,"Android/Sdk/cmdline-tools/latest/bin")];if($==="win32"){let X=process.env.LOCALAPPDATA,Q=X?G5.join(X,"Android","Sdk"):"";return[...Q?[G5.join(Q,"platform-tools"),G5.join(Q,"emulator"),G5.join(Q,"cmdline-tools","latest","bin")]:[]]}return[]}function kL0(){let $=as.homedir(),J=process.platform;if(J==="darwin")return[G5.join($,"Library/Android/sdk")];if(J==="linux")return[G5.join($,"Android/Sdk")];if(J==="win32"){let X=process.env.LOCALAPPDATA;return X?[G5.join(X,"Android","Sdk")]:[]}return[]}function Ww$($){try{return Qw$.statSync($).isDirectory()}catch{}return!1}_9();S_();function yL0($){let J=$.findIndex((Q)=>Q==="--cli"||Q==="--daemon"),X=J>=0?$.slice(0,J):$;return X.includes("--version")||X.includes("-v")}function jw$($,J){return yL0($)?J:void 0}Jb();P7();Ab();_b();mB();Pb();Pb();S_();Cb();_9();import{parseArgs as uO0}from"util";var mO0=Object.fromEntries(["cli","daemon-mode","no-proxy","direct","no-daemon","debug-perf","ui-perf-debug","debug","no-ui-perf-mode","mem-perf-audit","accessibility-audit","predictive","predictive-ui","raw-element-search","embedded-sdk","network-mockable","dismiss-keyboard-after-input","mcp-recording","no-navigation-screenshots","no-waitfor-polling-overhead","no-include-not-important-views","no-report-view-ids","no-retrieve-interactive-windows","no-occlusion"].map(($)=>[$,{type:"boolean"}]));function jA$($,J){let{values:X}=uO0({args:$,options:mO0,allowPositionals:!0,strict:!1}),Q=(E0)=>X[E0]===!0,Y,W,G,Z=Q("cli"),j=Q("daemon-mode"),V=Q("no-proxy")||Q("direct"),K=Q("no-daemon"),z=$.indexOf("--daemon"),L=z>=0?$[z+1]:void 0,H=z>=0?$.slice(z+2):[],O=Q("debug-perf")||Q("ui-perf-debug")||process.env.AUTOMOBILE_DEBUG_PERF==="1",B=Q("debug")||process.env.AUTOMOBILE_DEBUG==="1",F=!Q("no-ui-perf-mode"),A=Q("mem-perf-audit"),_=Q("accessibility-audit"),q,w,M,C=!1,f=Q("predictive")||Q("predictive-ui"),I=Q("raw-element-search"),c=Yb($),h=Q("embedded-sdk"),r=Q("network-mockable"),t=Q("dismiss-keyboard-after-input"),Y$=Eb($,process.env),X$=Rb($),L$=Q("mcp-recording"),O$=!Q("no-navigation-screenshots"),u$=Q("no-waitfor-polling-overhead"),k$=Q("no-include-not-important-views"),H0=Q("no-report-view-ids"),A0=Q("no-retrieve-interactive-windows"),L1=Q("no-occlusion"),U0=Gw$($,process.env),H1=Tb($,process.env,SB()),L0="session",R0={},n=(E0,T1,j1)=>{if(!E0)return;let S8=j1?Number(E0):parseInt(E0,10);if(!Number.isFinite(S8)||S8<=0){J.warn(`Invalid ${T1}: ${E0}`);return}return j1?S8:Math.round(S8)},g=(E0,T1)=>{if(!E0)return;if(!new Set(["low","medium","high"]).has(E0)){J.warn(`Invalid video quality preset (${T1}): ${E0}`);return}R0.qualityPreset=E0},q$=(E0,T1)=>{if(!E0)return;if(E0!=="mp4"){J.warn(`Invalid video format (${T1}): ${E0}`);return}R0.format=E0};g(process.env.AUTOMOBILE_VIDEO_QUALITY_PRESET??process.env.AUTO_MOBILE_VIDEO_QUALITY_PRESET,"env");let Q$=[[process.env.AUTOMOBILE_VIDEO_TARGET_BITRATE_KBPS??process.env.AUTO_MOBILE_VIDEO_TARGET_BITRATE_KBPS,"video target bitrate",!1,"targetBitrateKbps"],[process.env.AUTOMOBILE_VIDEO_MAX_THROUGHPUT_MBPS??process.env.AUTO_MOBILE_VIDEO_MAX_THROUGHPUT_MBPS,"video max throughput",!0,"maxThroughputMbps"],[process.env.AUTOMOBILE_VIDEO_FPS??process.env.AUTO_MOBILE_VIDEO_FPS,"video fps",!1,"fps"],[process.env.AUTOMOBILE_VIDEO_MAX_ARCHIVE_MB??process.env.AUTO_MOBILE_VIDEO_MAX_ARCHIVE_MB,"video max archive size",!0,"maxArchiveSizeMb"]];for(let[E0,T1,j1,S8]of Q$){let F4=n(E0,T1,j1);if(F4!==void 0)R0[S8]=F4}q$(process.env.AUTOMOBILE_VIDEO_FORMAT??process.env.AUTO_MOBILE_VIDEO_FORMAT,"env");let D1=$.indexOf("--cli"),E4=Z?$.slice(D1+1):[];for(let E0=0;E0<$.length;E0++){let T1=$[E0];if(T1==="--cli")break;if(T1==="--port"){let j1=parseInt($[E0+1],10);if(!isNaN(j1)&&j1>0&&j1<65536)Y=j1;else J.warn(`Invalid port: ${$[E0+1]}`);E0++}else if(T1==="--host"){let j1=$[E0+1];if(j1&&!j1.startsWith("--"))W=j1;else J.warn(`Invalid host: ${j1}`);E0++}else if(T1==="--initial-session-uuid"){let j1=$[E0+1];if(j1&&!j1.startsWith("--"))G=j1;else J.warn(`Invalid initial session UUID: ${j1}`);E0++}else if(T1==="--a11y-level")q=$[++E0];else if(T1==="--a11y-failure-mode")w=$[++E0];else if(T1==="--a11y-min-severity")M=$[++E0];else if(T1==="--a11y-use-baseline")C=!0;else if(T1==="--plan-execution-lock-scope"){let j1=$[++E0];if(j1==="global"||j1==="session")L0=j1;else J.warn(`Invalid plan execution lock scope: ${j1}. Using default: ${L0}`)}else if(T1==="--video-quality"||T1==="--video-quality-preset")g($[++E0],"cli");else if(T1==="--video-target-bitrate-kbps"){let j1=n($[++E0],"video target bitrate",!1);if(j1!==void 0)R0.targetBitrateKbps=j1}else if(T1==="--video-max-throughput-mbps"){let j1=n($[++E0],"video max throughput",!0);if(j1!==void 0)R0.maxThroughputMbps=j1}else if(T1==="--video-fps"){let j1=n($[++E0],"video fps",!1);if(j1!==void 0)R0.fps=j1}else if(T1==="--video-format")q$($[++E0],"cli");else if(T1==="--video-archive-size-mb"){let j1=n($[++E0],"video max archive size",!0);if(j1!==void 0)R0.maxArchiveSizeMb=j1}}return{cliMode:Z,cliArgs:E4,daemonPort:Y,daemonHost:W,initialSessionUuid:G,debugPerf:O,debug:B,uiPerfMode:F,memPerfAuditMode:A,a11yAuditMode:_,a11yLevel:q,a11yFailureMode:w,a11yMinSeverity:M,a11yUseBaseline:C,predictiveUi:f,rawElementSearch:I,planExecutionLockScope:L0,videoRecordingDefaults:R0,daemonMode:j,daemonCommand:L,daemonArgs:H,skipCtrlProxyDownload:c,embeddedSdk:h,networkMockable:r,dismissKeyboardAfterInput:t,eventAllMarkers:Y$,eventAllMarkersCliOverride:X$,mcpRecording:L$,navigationScreenshots:O$,noWaitForPollingOverhead:u$,noProxy:V,noDaemon:K,noA11yIncludeNotImportantViews:k$,noA11yReportViewIds:H0,noA11yRetrieveInteractiveWindows:A0,noOcclusion:L1,outputReduction:U0,toolOutputsDir:H1}}ye();U$();d();var KA$=5000;function LA$($){let J=$.timer??u,X=$.logger??U;if(UA$("Android CtrlProxy prefetch cleanup",$.startAndroidSweep,J,X),$.platform==="darwin")UA$("iOS CtrlProxy runner cleanup",$.startIosReap,J,X)}function UA$($,J,X,Q){let Y;try{Y=J()}catch(G){Q.warn(`[STARTUP_MAINTENANCE] ${$} failed: ${zA$(G)}`);return}let W=X.setTimeout(()=>{Q.warn(`[STARTUP_MAINTENANCE] ${$} exceeded ${KA$}ms; continuing startup`)},KA$);W.unref?.(),Y.catch((G)=>{Q.warn(`[STARTUP_MAINTENANCE] ${$} failed: ${zA$(G)}`)}).finally(()=>{X.clearTimeout(W)})}function zA$($){return $ instanceof Error?$.message:String($)}Yw$();process.env[g2]??=C_();var ex;function wL0($,J){let X=J instanceof Error?J.stack??J.message:String(J);if(ex)ex.error(`${$}: ${X}`);else console.error(`${$}: ${X}`)}var NL0=jw$(process.argv.slice(2),M9());if(NL0!==void 0)console.log(NL0),process.exit(0);Sb();kb(($)=>{if($.type==="uncaughtException"){wL0("Uncaught exception",$.error);return}wL0("Unhandled rejection",$.reason)});async function WP1(){y4.mark("processEntry"),y4.startPhase("moduleImports");let $=process.argv.slice(2),J=$.indexOf("--boot-device");if(J>=0){let{runBootDeviceCommand:H0}=await Promise.resolve().then(() => (JP$(),$P$));y4.endPhase("moduleImports"),await H0($.slice(J+1)),process.exit(0)}let{StdioServerTransport:X}=await Promise.resolve().then(() => (hS$(),vS$)),{createMcpServer:Q}=await Promise.resolve().then(() => (Y2$(),F90)),{createProxyMcpServer:Y}=await Promise.resolve().then(() => (o90(),i90)),{logger:W,LogLevel:G}=await Promise.resolve().then(() => (d(),Cw$));ex=W;let{runCliCommand:Z}=await Promise.resolve().then(() => (AJ0(),NJ0)),{runDaemonCommand:j}=await Promise.resolve().then(() => (jI(),h90)),{startDaemon:V}=await Promise.resolve().then(() => (LL0(),zL0)),{guardDatabaseStartup:K}=await Promise.resolve().then(() => (Ur(),KL$)),{DefaultDatabaseInitializer:z}=await Promise.resolve().then(() => (ZL$(),E50)),L=await Promise.resolve().then(() => (zr(),y50)),H=await Promise.resolve().then(() => (Lr(),f50)),O=await Promise.resolve().then(() => (Hr(),v50)),B=await Promise.resolve().then(() => (Dr(),u50)),F=await Promise.resolve().then(() => (ds(),l20)),A=await Promise.resolve().then(() => (Br(),g50)),{FeatureFlagService:_}=await Promise.resolve().then(() => (cV(),sm$)),{serverConfig:q}=await Promise.resolve().then(() => (t4(),WA$)),{AndroidCtrlProxyManager:w}=await Promise.resolve().then(() => (lX(),mf$)),{IOSCtrlProxyBuilder:M}=await Promise.resolve().then(() => (RP(),Ih$)),{IOSCtrlProxyManager:C}=await Promise.resolve().then(() => (SG(),th$));y4.endPhase("moduleImports");let{startVideoRecordingSocketServer:f,stopVideoRecordingSocketServer:I}=L,{startTestRecordingSocketServer:c,stopTestRecordingSocketServer:h}=H,{startDeviceSnapshotSocketServer:r,stopDeviceSnapshotSocketServer:t}=O,{startAppearanceSocketServer:Y$,stopAppearanceSocketServer:X$}=B,{startWebRtcStreamSocketServer:L$,stopWebRtcStreamSocketServer:O$}=F,{startAppearanceSyncScheduler:u$,stopAppearanceSyncScheduler:k$}=A;Ib(async(H0)=>{W.info(`Received ${H0} signal, shutting down`),await I(),await h(),await t(),await X$(),await O$(),k$(),await w.cleanupPrefetchedApk(),W.close()});try{let{cliMode:H0,cliArgs:A0,daemonPort:L1,daemonHost:U0,initialSessionUuid:H1,debugPerf:L0,debug:R0,uiPerfMode:n,memPerfAuditMode:g,a11yAuditMode:q$,a11yLevel:Q$,a11yFailureMode:D1,a11yMinSeverity:E4,a11yUseBaseline:E0,predictiveUi:T1,rawElementSearch:j1,planExecutionLockScope:S8,videoRecordingDefaults:F4,daemonMode:WJ,daemonCommand:u5,daemonArgs:qQ,skipCtrlProxyDownload:m5,embeddedSdk:l5,networkMockable:hj,dismissKeyboardAfterInput:HY,eventAllMarkers:OY,eventAllMarkersCliOverride:gj,mcpRecording:AX,navigationScreenshots:uj,noWaitForPollingOverhead:LU,noProxy:CB,noDaemon:mj,noA11yIncludeNotImportantViews:j$,noA11yReportViewIds:B$,noA11yRetrieveInteractiveWindows:C$,noOcclusion:J0,outputReduction:$1,toolOutputsDir:A6}=jA$(process.argv.slice(2),W);if(R0)W.setLogLevel(G.DEBUG);if(q.setPlanExecutionLockScope(S8),q.setVideoRecordingDefaults(F4),q.setToolOutputsDir(A6),q.setSkipCtrlProxyDownload(m5),q.setEmbeddedSdkEnabled(l5),q.setNetworkMockableEnabled(hj),q.setDismissKeyboardAfterInputEnabled(HY),q.setEventAllMarkers(OY),LA$({platform:process.platform,startAndroidSweep:()=>w.sweepStalePrefetchDirsOnStartup(),startIosReap:()=>C.startOrphanRunnerReapOnStartup()}),m5)W.info(`CtrlProxy downloads disabled (${$e} or ${OU})`),y4.recordPhase("androidCtrlProxyPrefetch",0);else y4.startPhase("androidCtrlProxyPrefetch"),w.prefetchApk().then(()=>{y4.endPhase("androidCtrlProxyPrefetch")});if(process.platform==="darwin")if(m5)W.info(`CtrlProxy iOS prefetch disabled (${$e} or ${OU})`),y4.recordPhase("iosCtrlProxyPrefetch",0);else y4.startPhase("iosCtrlProxyPrefetch"),M.prefetchBuild().then(()=>{y4.endPhase("iosCtrlProxyPrefetch")});if(sN$(),process.platform==="darwin"&&process.env[X8.WHIP_ENDPOINT]?.trim()&&!process.env.AUTOMOBILE_IOS_SCREEN_CAPTURE_HELPER&&!process.env.AUTO_MOBILE_IOS_SCREEN_CAPTURE_HELPER)iW.getInstance().ensure().catch((w1)=>{W.warn(`[SCREEN_CAPTURE_HELPER] Background prefetch failed: ${w1 instanceof Error?w1.message:String(w1)}`)});let S6=_.getInstance(),M0=[["debug",R0,"--debug"],["debug-perf",L0,"--debug-perf/--ui-perf-debug"],["ui-perf-mode",n,"--ui-perf-mode"],["mem-perf-audit",g,"--mem-perf-audit"],["accessibility-audit",q$,"--accessibility-audit",q$?{level:Q$||"AA",failureMode:D1||"report",minSeverity:E4||(D1==="strict"?"error":"warning"),useBaseline:E0}:null],["predictive-ui",T1,"--predictive/--predictive-ui"],["raw-element-search",j1,"--raw-element-search"],["mcp-recording",AX,"--mcp-recording"],...IB.map((w1)=>[w1.featureFlagKey,$1[w1.field],w1.label,void 0])],h0=async()=>{await S6.initialize();for(let[w1,P4,z9,wQ]of M0){if(!P4)continue;await S6.setFlag(w1,!0,wQ),W.info(`Feature flag enabled (${z9})`)}if(!uj)await S6.setFlag("navigation-screenshots",!1),W.info("Navigation screenshots disabled (--no-navigation-screenshots)")};if(await y4.runPhase("databasePreflight",async()=>{if(WJ)await K(async()=>{await new z().initialize(),await h0()});else{let{runDirectModeStartup:w1}=await Promise.resolve().then(() => HL0);await w1({noProxy:CB,assertDbOwnership:async()=>{let{assertDirectModeDbOwnership:P4,createDefaultDirectModeGuardDeps:z9}=await Promise.resolve().then(() => (qL0(),FL0));P4(z9())},applyFeatureFlagStartup:h0})}}),LU)q.setWaitForPollingOverheadEnabled(!1),W.info("WaitFor polling overhead disabled (--no-waitfor-polling-overhead): screenshots and back stack skipped during observe waitFor polling");let d0=[[!n,"UI perf mode disabled (--no-ui-perf-mode): skipping selection-state visual capture on taps and UI perf auditing"],[l5,"Embedded SDK tools enabled (--embedded-sdk)"],[HY,"Dismiss keyboard after inputText enabled (--dismiss-keyboard-after-input)"],[j$,"Accessibility includeNotImportantViews disabled (--no-include-not-important-views)"],[B$,"Accessibility reportViewIds disabled (--no-report-view-ids)"],[C$,"Accessibility retrieveInteractiveWindows disabled (--no-retrieve-interactive-windows)"],[J0,"Observe occlusion pass disabled (--no-occlusion)"]];for(let[w1,P4]of d0)if(w1)W.info(P4);if(OY.length>0)W.info(`inputText eventAll auto-promotion markers configured (--event-all-markers): ${JSON.stringify(OY)}`);else if(process.argv.slice(2).some((w1)=>w1===oW||w1.startsWith(`${oW}=`)))W.warn(`${oW} was provided but resolved to no markers; inputText eventAll auto-promotion stays disabled`);let t0=OY.length>0||gj?{eventAllMarkers:OY,eventAllMarkersCliOverride:gj}:{};if(WJ){await V({port:L1,...U0!==void 0?{host:U0}:{},debug:R0,debugPerf:L0,planExecutionLockScope:S8,videoQualityPreset:F4.qualityPreset,videoTargetBitrateKbps:F4.targetBitrateKbps,videoMaxThroughputMbps:F4.maxThroughputMbps,videoFps:F4.fps,videoFormat:F4.format,videoMaxArchiveSizeMb:F4.maxArchiveSizeMb,toolOutputsDir:A6,networkMockable:hj,embeddedSdk:l5,dismissKeyboardAfterInput:HY,...t0,noUiPerfMode:!n,memPerfAudit:g,accessibilityAudit:q$,accessibilityLevel:Q$,accessibilityFailureMode:D1,accessibilityMinSeverity:E4,accessibilityUseBaseline:E0,predictiveUi:T1,rawElementSearch:j1,skipCtrlProxyDownload:m5,mcpRecording:AX,noNavigationScreenshots:!uj,noWaitForPollingOverhead:LU,noA11yIncludeNotImportantViews:j$,noA11yReportViewIds:B$,noA11yRetrieveInteractiveWindows:C$,noOcclusion:J0,...$1});return}if(u5)await j(u5,qQ),W.close(),process.exit(0);let S1={debug:R0,debugPerf:L0,planExecutionLockScope:S8,mcpRecording:AX,videoQualityPreset:F4.qualityPreset,videoTargetBitrateKbps:F4.targetBitrateKbps,videoMaxThroughputMbps:F4.maxThroughputMbps,videoFps:F4.fps,videoFormat:F4.format,videoMaxArchiveSizeMb:F4.maxArchiveSizeMb,toolOutputsDir:A6,networkMockable:hj,embeddedSdk:l5,dismissKeyboardAfterInput:HY,...t0,noUiPerfMode:!n,memPerfAudit:g,accessibilityAudit:q$,accessibilityLevel:Q$,accessibilityFailureMode:D1,accessibilityMinSeverity:E4,accessibilityUseBaseline:E0,predictiveUi:T1,rawElementSearch:j1,skipCtrlProxyDownload:m5,noNavigationScreenshots:!uj,noWaitForPollingOverhead:LU,noA11yIncludeNotImportantViews:j$,noA11yReportViewIds:B$,noA11yRetrieveInteractiveWindows:C$,noOcclusion:J0,...$1};if(H0)W.info("Running in CLI mode"),await Z(A0,S1),W.close(),process.exit(0);else{let w1=!CB;if(w1)W.info("Starting MCP server in proxy mode (connecting to daemon)");else W.info("Starting MCP server in direct mode (--no-proxy flag)"),await f(),await c(),await r(),await Y$(),await L$(),u$();let P4=()=>{W.info("stdin closed \u2014 MCP client disconnected, shutting down"),W.close(),process.exit(0)};process.stdin.on("end",P4),process.stdin.on("error",P4),process.stdin.on("close",P4);let z9=new X,wQ,HU;try{if(w1){let E7=Y({proxyConfig:{autoStartDaemon:!mj,daemonOptions:S1,initialSessionUuid:H1}});wQ=E7.server,HU=E7.proxy}else wQ=Q({debug:R0})}catch(E7){throw W.error("Failed to create MCP server:",E7),E7}try{if(W.info("Connecting MCP server to stdio transport"),y4.startPhase("serverListening"),await wQ.connect(z9),y4.endPhase("serverListening"),W.info("MCP server connected to stdio transport"),W.info(`AutoMobile MCP server running on stdio (${w1?"proxy":"direct"} mode)`),y4.emit("mcp-server",{transport:"stdio",mode:w1?"proxy":"direct"}),HU){let E7=async()=>{await HU.close()};process.on("beforeExit",E7)}}catch(E7){throw W.error("MCP server connect failed:",E7),E7}}}catch(H0){throw W.error("Error initializing server:",H0),H0}}if(import.meta.main)WP1().catch(async($)=>{console.error("Fatal error in main():",$),ex?.error("Fatal error in main():",$),ex?.close();let{resolveDaemonStartupExitCode:J}=await Promise.resolve().then(() => (Ur(),KL$));process.exit(J($))});
|
|
1137
1137
|
|
|
1138
|
-
//# debugId=
|
|
1138
|
+
//# debugId=13FF7D180430428164756E2164756E21
|