@jsfsi-core/ts-nodejs 1.1.35 → 1.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,13 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("path"),W=require("url"),Q=require("fs"),H=require("os"),X=require("crypto");var U=typeof document<"u"?document.currentScript:null;function Z(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}var S={exports:{}};const ee="17.3.1",te={version:ee};var q;function re(){if(q)return S.exports;q=1;const h=Q,t=Y,n=H,c=X,N=te.version,O=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","🤖 agentic secret storage: https://dotenvx.com/as2","⚡️ secrets for agents: https://dotenvx.com/as2","🛡️ auth for agents: https://vestauth.com","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function I(){return O[Math.floor(Math.random()*O.length)]}function b(e){return typeof e=="string"?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}function D(){return process.stdout.isTTY}function A(e){return D()?`\x1B[2m${e}\x1B[0m`:e}const M=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function r(e){const a={};let l=e.toString();l=l.replace(/\r\n?/mg,`
2
- `);let d;for(;(d=M.exec(l))!=null;){const E=d[1];let g=d[2]||"";g=g.trim();const o=g[0];g=g.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(g=g.replace(/\\n/g,`
3
- `),g=g.replace(/\\r/g,"\r")),a[E]=g}return a}function u(e){e=e||{};const a=s(e);e.path=a;const l=_.configDotenv(e);if(!l.parsed){const o=new Error(`MISSING_DATA: Cannot parse ${a} for an unknown reason`);throw o.code="MISSING_DATA",o}const d=y(e).split(","),E=d.length;let g;for(let o=0;o<E;o++)try{const m=d[o].trim(),T=v(l,m);g=_.decrypt(T.ciphertext,T.key);break}catch(m){if(o+1>=E)throw m}return _.parse(g)}function p(e){console.error(`[dotenv@${N}][WARN] ${e}`)}function i(e){console.log(`[dotenv@${N}][DEBUG] ${e}`)}function f(e){console.log(`[dotenv@${N}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function v(e,a){let l;try{l=new URL(a)}catch(m){if(m.code==="ERR_INVALID_URL"){const T=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw T.code="INVALID_DOTENV_KEY",T}throw m}const d=l.password;if(!d){const m=new Error("INVALID_DOTENV_KEY: Missing key part");throw m.code="INVALID_DOTENV_KEY",m}const E=l.searchParams.get("environment");if(!E){const m=new Error("INVALID_DOTENV_KEY: Missing environment part");throw m.code="INVALID_DOTENV_KEY",m}const g=`DOTENV_VAULT_${E.toUpperCase()}`,o=e.parsed[g];if(!o){const m=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${g} in your .env.vault file.`);throw m.code="NOT_FOUND_DOTENV_ENVIRONMENT",m}return{ciphertext:o,key:d}}function s(e){let a=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const l of e.path)h.existsSync(l)&&(a=l.endsWith(".vault")?l:`${l}.vault`);else a=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else a=t.resolve(process.cwd(),".env.vault");return h.existsSync(a)?a:null}function R(e){return e[0]==="~"?t.join(n.homedir(),e.slice(1)):e}function V(e){const a=b(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),l=b(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(a||!l)&&f("Loading env from encrypted .env.vault");const d=_._parseVault(e);let E=process.env;return e&&e.processEnv!=null&&(E=e.processEnv),_.populate(E,d,e),{parsed:d}}function x(e){const a=t.resolve(process.cwd(),".env");let l="utf8",d=process.env;e&&e.processEnv!=null&&(d=e.processEnv);let E=b(d.DOTENV_CONFIG_DEBUG||e&&e.debug),g=b(d.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?l=e.encoding:E&&i("No encoding is specified. UTF-8 is used by default");let o=[a];if(e&&e.path)if(!Array.isArray(e.path))o=[R(e.path)];else{o=[];for(const L of e.path)o.push(R(L))}let m;const T={};for(const L of o)try{const $=_.parse(h.readFileSync(L,{encoding:l}));_.populate(T,$,e)}catch($){E&&i(`Failed to load ${L} ${$.message}`),m=$}const F=_.populate(d,T,e);if(E=b(d.DOTENV_CONFIG_DEBUG||E),g=b(d.DOTENV_CONFIG_QUIET||g),E||!g){const L=Object.keys(F).length,$=[];for(const K of o)try{const C=t.relative(process.cwd(),K);$.push(C)}catch(C){E&&i(`Failed to load ${K} ${C.message}`),m=C}f(`injecting env (${L}) from ${$.join(",")} ${A(`-- tip: ${I()}`)}`)}return m?{parsed:T,error:m}:{parsed:T}}function G(e){if(y(e).length===0)return _.configDotenv(e);const a=s(e);return a?_._configVault(e):(p(`You set DOTENV_KEY but you are missing a .env.vault file at ${a}. Did you forget to build it?`),_.configDotenv(e))}function k(e,a){const l=Buffer.from(a.slice(-64),"hex");let d=Buffer.from(e,"base64");const E=d.subarray(0,12),g=d.subarray(-16);d=d.subarray(12,-16);try{const o=c.createDecipheriv("aes-256-gcm",l,E);return o.setAuthTag(g),`${o.update(d)}${o.final()}`}catch(o){const m=o instanceof RangeError,T=o.message==="Invalid key length",F=o.message==="Unsupported state or unable to authenticate data";if(m||T){const L=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw L.code="INVALID_DOTENV_KEY",L}else if(F){const L=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw L.code="DECRYPTION_FAILED",L}else throw o}}function z(e,a,l={}){const d=!!(l&&l.debug),E=!!(l&&l.override),g={};if(typeof a!="object"){const o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(const o of Object.keys(a))Object.prototype.hasOwnProperty.call(e,o)?(E===!0&&(e[o]=a[o],g[o]=a[o]),d&&i(E===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(e[o]=a[o],g[o]=a[o]);return g}const _={configDotenv:x,_configVault:V,_parseVault:u,config:G,decrypt:k,parse:r,populate:z};return S.exports.configDotenv=_.configDotenv,S.exports._configVault=_._configVault,S.exports._parseVault=_._parseVault,S.exports.config=_.config,S.exports.decrypt=_.decrypt,S.exports.parse=_.parse,S.exports.populate=_.populate,S.exports=_,S.exports}var ne=re();const oe=W.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:U&&U.tagName.toUpperCase()==="SCRIPT"&&U.src||new URL("index.cjs",document.baseURI).href),ie=Y.dirname(oe),se=(h={})=>{const{env:t,configPath:n}=h,c=Y.resolve(ie,`${n??"."}/.env${t?`.${t}`:""}`),{parsed:w}=ne.config({path:c});return w};var j,B;function ce(){if(B)return j;B=1,j=N,N.default=N,N.stable=D,N.stableStringify=D;var h="[...]",t="[Circular]",n=[],c=[];function w(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function N(r,u,p,i){typeof i>"u"&&(i=w()),I(r,"",0,[],void 0,0,i);var f;try{c.length===0?f=JSON.stringify(r,u,p):f=JSON.stringify(r,M(u),p)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;n.length!==0;){var y=n.pop();y.length===4?Object.defineProperty(y[0],y[1],y[3]):y[0][y[1]]=y[2]}}return f}function O(r,u,p,i){var f=Object.getOwnPropertyDescriptor(i,p);f.get!==void 0?f.configurable?(Object.defineProperty(i,p,{value:r}),n.push([i,p,u,f])):c.push([u,p,r]):(i[p]=r,n.push([i,p,u]))}function I(r,u,p,i,f,y,v){y+=1;var s;if(typeof r=="object"&&r!==null){for(s=0;s<i.length;s++)if(i[s]===r){O(t,r,u,f);return}if(typeof v.depthLimit<"u"&&y>v.depthLimit){O(h,r,u,f);return}if(typeof v.edgesLimit<"u"&&p+1>v.edgesLimit){O(h,r,u,f);return}if(i.push(r),Array.isArray(r))for(s=0;s<r.length;s++)I(r[s],s,s,i,r,y,v);else{var R=Object.keys(r);for(s=0;s<R.length;s++){var V=R[s];I(r[V],V,s,i,r,y,v)}}i.pop()}}function b(r,u){return r<u?-1:r>u?1:0}function D(r,u,p,i){typeof i>"u"&&(i=w());var f=A(r,"",0,[],void 0,0,i)||r,y;try{c.length===0?y=JSON.stringify(f,u,p):y=JSON.stringify(f,M(u),p)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;n.length!==0;){var v=n.pop();v.length===4?Object.defineProperty(v[0],v[1],v[3]):v[0][v[1]]=v[2]}}return y}function A(r,u,p,i,f,y,v){y+=1;var s;if(typeof r=="object"&&r!==null){for(s=0;s<i.length;s++)if(i[s]===r){O(t,r,u,f);return}try{if(typeof r.toJSON=="function")return}catch{return}if(typeof v.depthLimit<"u"&&y>v.depthLimit){O(h,r,u,f);return}if(typeof v.edgesLimit<"u"&&p+1>v.edgesLimit){O(h,r,u,f);return}if(i.push(r),Array.isArray(r))for(s=0;s<r.length;s++)A(r[s],s,s,i,r,y,v);else{var R={},V=Object.keys(r).sort(b);for(s=0;s<V.length;s++){var x=V[s];A(r[x],x,s,i,r,y,v),R[x]=r[x]}if(typeof f<"u")n.push([f,u,r]),f[u]=R;else return R}i.pop()}}function M(r){return r=typeof r<"u"?r:function(u,p){return p},function(u,p){if(c.length>0)for(var i=0;i<c.length;i++){var f=c[i];if(f[1]===u&&f[0]===p){p=f[2],c.splice(i,1);break}}return r.call(this,u,p)}}return j}var ae=ce();const ue=Z(ae),J={debug:"debug",verbose:"debug",log:"log",warn:"warn",error:"error",fatal:"error"},fe={verbose:"DEFAULT",debug:"DEBUG",log:"INFO",warn:"WARNING",error:"ERROR",fatal:"CRITICAL"},le=["x-api-key","x-api-token","x-key","x-token","cookie","password","pass","psw","auth","authentication","authorization","token","access_token","client-secret","credentials","secret"];class de{constructor(t,n={}){this.module=t,n.logLevels&&(this.levels=new Set(n.logLevels))}levels=new Set(["verbose","debug","log","warn","error","fatal"]);mapLogLevelToConsoleMethod(t){return J[t]}write(t,n,c,w,N){if(!this.levels.has(t))return;const O=this.buildLog(t,n,c,w,N),I=ue(O,this.sensitiveReplacer),b=this.mapLogLevelToConsoleMethod(t);console[b](I)}buildLog(t,n,c,w,N){const{writeMetadata:O,writeContext:I,writeError:b}=this.sanitizeLog(c,w,N),D={};return typeof n=="string"&&(D.textPayload=n),!O&&typeof n!="string"&&!(n instanceof Error)&&(D.metadata=n),n instanceof Error&&(D.error=JSON.stringify(n,Object.getOwnPropertyNames(n))),I&&(D.context=I),O&&(D.metadata=O),!D.error&&b&&(D.error=JSON.stringify(b,Object.getOwnPropertyNames(b))),{severity:fe[t],module:this.module,textPayload:D.textPayload,message:D}}sanitizeLog(t,n,c){if(n instanceof Error&&(!c||typeof c=="string"))return{writeMetadata:void 0,writeContext:t||c,writeError:n};let w=n,N=t;return typeof w=="string"&&!t&&(N=w,w=void 0),{writeMetadata:w,writeContext:N,writeError:c}}sensitiveReplacer(t,n){return le.includes(t.toLowerCase())?"[HIDDEN BY LOGGER]":n}debug(t,n,c){this.write("debug",t,c,n)}verbose(t,n,c){this.write("verbose",t,c,n)}log(t,n,c){this.write("log",t,c,n)}warn(t,n,c,w){this.write("warn",t,w,n,c)}error(t,n,c,w){this.write("error",t,w,n,c)}fatal(t,n,c,w){this.write("fatal",t,w,n,c)}setLogLevels(t){this.levels=new Set(t)}}class ge{debug=()=>{};verbose=()=>{};log=()=>{};warn=()=>{};error=()=>{};fatal=()=>{};setLogLevels=()=>{}}class P{constructor(t){this.dataSource=t}em;static newInstance(t){const n=t.constructor;return new n(t.dataSource)}withEntityManager(t){return this.em=t,this}withRepositoryManager(t){return P.newInstance(this).withEntityManager(t.em)}lockInTransaction(t="pessimistic_write"){return this.em?{mode:t}:void 0}getRepository(t){return this.em?this.em.getRepository(t):this.dataSource.getRepository(t)}async withTransaction(t){let n;return await this.dataSource.transaction(async c=>{n=await t(P.newInstance(this).withEntityManager(c))}),n}}const he=h=>({...h,withTransaction:async t=>await t(h),withRepositoryManager:()=>h}),pe=(h,t)=>`unaccent(LOWER(${h})) ILIKE unaccent(LOWER(:${t}))`,ye=Object.freeze(Object.defineProperty({__proto__:null,unaccentSearch:pe},Symbol.toStringTag,{value:"Module"}));exports.GCPLogger=de;exports.LogLevelToConsoleMethodMap=J;exports.MockLogger=ge;exports.TransactionalRepository=P;exports.buildTransactionalRepositoryMock=he;exports.loadEnvConfig=se;exports.postgres=ye;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const lr=require("path"),Mi=require("url"),wi=require("fs"),Ei=require("os"),Ai=require("crypto"),pr=require("buffer");var Xe=typeof document<"u"?document.currentScript:null,Je=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Kn(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}var Oe={exports:{}};const Oi="17.3.1",Ci={version:Oi};var Ar;function Ti(){if(Ar)return Oe.exports;Ar=1;const h=wi,e=lr,t=Ei,r=Ai,i=Ci.version,s=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","🤖 agentic secret storage: https://dotenvx.com/as2","⚡️ secrets for agents: https://dotenvx.com/as2","🛡️ auth for agents: https://vestauth.com","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function a(){return s[Math.floor(Math.random()*s.length)]}function o(M){return typeof M=="string"?!["false","0","no","off",""].includes(M.toLowerCase()):!!M}function c(){return process.stdout.isTTY}function l(M){return c()?`\x1B[2m${M}\x1B[0m`:M}const p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function u(M){const U={};let H=M.toString();H=H.replace(/\r\n?/mg,`
2
+ `);let P;for(;(P=p.exec(H))!=null;){const T=P[1];let O=P[2]||"";O=O.trim();const w=O[0];O=O.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),w==='"'&&(O=O.replace(/\\n/g,`
3
+ `),O=O.replace(/\\r/g,"\r")),U[T]=O}return U}function f(M){M=M||{};const U=x(M);M.path=U;const H=k.configDotenv(M);if(!H.parsed){const w=new Error(`MISSING_DATA: Cannot parse ${U} for an unknown reason`);throw w.code="MISSING_DATA",w}const P=b(M).split(","),T=P.length;let O;for(let w=0;w<T;w++)try{const C=P[w].trim(),B=A(H,C);O=k.decrypt(B.ciphertext,B.key);break}catch(C){if(w+1>=T)throw C}return k.parse(O)}function y(M){console.error(`[dotenv@${i}][WARN] ${M}`)}function d(M){console.log(`[dotenv@${i}][DEBUG] ${M}`)}function m(M){console.log(`[dotenv@${i}] ${M}`)}function b(M){return M&&M.DOTENV_KEY&&M.DOTENV_KEY.length>0?M.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function A(M,U){let H;try{H=new URL(U)}catch(C){if(C.code==="ERR_INVALID_URL"){const B=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw B.code="INVALID_DOTENV_KEY",B}throw C}const P=H.password;if(!P){const C=new Error("INVALID_DOTENV_KEY: Missing key part");throw C.code="INVALID_DOTENV_KEY",C}const T=H.searchParams.get("environment");if(!T){const C=new Error("INVALID_DOTENV_KEY: Missing environment part");throw C.code="INVALID_DOTENV_KEY",C}const O=`DOTENV_VAULT_${T.toUpperCase()}`,w=M.parsed[O];if(!w){const C=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${O} in your .env.vault file.`);throw C.code="NOT_FOUND_DOTENV_ENVIRONMENT",C}return{ciphertext:w,key:P}}function x(M){let U=null;if(M&&M.path&&M.path.length>0)if(Array.isArray(M.path))for(const H of M.path)h.existsSync(H)&&(U=H.endsWith(".vault")?H:`${H}.vault`);else U=M.path.endsWith(".vault")?M.path:`${M.path}.vault`;else U=e.resolve(process.cwd(),".env.vault");return h.existsSync(U)?U:null}function I(M){return M[0]==="~"?e.join(t.homedir(),M.slice(1)):M}function F(M){const U=o(process.env.DOTENV_CONFIG_DEBUG||M&&M.debug),H=o(process.env.DOTENV_CONFIG_QUIET||M&&M.quiet);(U||!H)&&m("Loading env from encrypted .env.vault");const P=k._parseVault(M);let T=process.env;return M&&M.processEnv!=null&&(T=M.processEnv),k.populate(T,P,M),{parsed:P}}function L(M){const U=e.resolve(process.cwd(),".env");let H="utf8",P=process.env;M&&M.processEnv!=null&&(P=M.processEnv);let T=o(P.DOTENV_CONFIG_DEBUG||M&&M.debug),O=o(P.DOTENV_CONFIG_QUIET||M&&M.quiet);M&&M.encoding?H=M.encoding:T&&d("No encoding is specified. UTF-8 is used by default");let w=[U];if(M&&M.path)if(!Array.isArray(M.path))w=[I(M.path)];else{w=[];for(const G of M.path)w.push(I(G))}let C;const B={};for(const G of w)try{const K=k.parse(h.readFileSync(G,{encoding:H}));k.populate(B,K,M)}catch(K){T&&d(`Failed to load ${G} ${K.message}`),C=K}const V=k.populate(P,B,M);if(T=o(P.DOTENV_CONFIG_DEBUG||T),O=o(P.DOTENV_CONFIG_QUIET||O),T||!O){const G=Object.keys(V).length,K=[];for(const _ of w)try{const X=e.relative(process.cwd(),_);K.push(X)}catch(X){T&&d(`Failed to load ${_} ${X.message}`),C=X}m(`injecting env (${G}) from ${K.join(",")} ${l(`-- tip: ${a()}`)}`)}return C?{parsed:B,error:C}:{parsed:B}}function Q(M){if(b(M).length===0)return k.configDotenv(M);const U=x(M);return U?k._configVault(M):(y(`You set DOTENV_KEY but you are missing a .env.vault file at ${U}. Did you forget to build it?`),k.configDotenv(M))}function se(M,U){const H=Buffer.from(U.slice(-64),"hex");let P=Buffer.from(M,"base64");const T=P.subarray(0,12),O=P.subarray(-16);P=P.subarray(12,-16);try{const w=r.createDecipheriv("aes-256-gcm",H,T);return w.setAuthTag(O),`${w.update(P)}${w.final()}`}catch(w){const C=w instanceof RangeError,B=w.message==="Invalid key length",V=w.message==="Unsupported state or unable to authenticate data";if(C||B){const G=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw G.code="INVALID_DOTENV_KEY",G}else if(V){const G=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw G.code="DECRYPTION_FAILED",G}else throw w}}function te(M,U,H={}){const P=!!(H&&H.debug),T=!!(H&&H.override),O={};if(typeof U!="object"){const w=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw w.code="OBJECT_REQUIRED",w}for(const w of Object.keys(U))Object.prototype.hasOwnProperty.call(M,w)?(T===!0&&(M[w]=U[w],O[w]=U[w]),P&&d(T===!0?`"${w}" is already defined and WAS overwritten`:`"${w}" is already defined and was NOT overwritten`)):(M[w]=U[w],O[w]=U[w]);return O}const k={configDotenv:L,_configVault:F,_parseVault:f,config:Q,decrypt:se,parse:u,populate:te};return Oe.exports.configDotenv=k.configDotenv,Oe.exports._configVault=k._configVault,Oe.exports._parseVault=k._parseVault,Oe.exports.config=k.config,Oe.exports.decrypt=k.decrypt,Oe.exports.parse=k.parse,Oe.exports.populate=k.populate,Oe.exports=k,Oe.exports}var Pi=Ti();const Si=Mi.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Xe&&Xe.tagName.toUpperCase()==="SCRIPT"&&Xe.src||new URL("index.cjs",document.baseURI).href),Ni=lr.dirname(Si),_i=(h={})=>{const{env:e,configPath:t}=h,r=lr.resolve(Ni,`${t??"."}/.env${e?`.${e}`:""}`),{parsed:n}=Pi.config({path:r});return n};var et,Or;function Ri(){if(Or)return et;Or=1,et=i,i.default=i,i.stable=c,i.stableStringify=c;var h="[...]",e="[Circular]",t=[],r=[];function n(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function i(u,f,y,d){typeof d>"u"&&(d=n()),a(u,"",0,[],void 0,0,d);var m;try{r.length===0?m=JSON.stringify(u,f,y):m=JSON.stringify(u,p(f),y)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;t.length!==0;){var b=t.pop();b.length===4?Object.defineProperty(b[0],b[1],b[3]):b[0][b[1]]=b[2]}}return m}function s(u,f,y,d){var m=Object.getOwnPropertyDescriptor(d,y);m.get!==void 0?m.configurable?(Object.defineProperty(d,y,{value:u}),t.push([d,y,f,m])):r.push([f,y,u]):(d[y]=u,t.push([d,y,f]))}function a(u,f,y,d,m,b,A){b+=1;var x;if(typeof u=="object"&&u!==null){for(x=0;x<d.length;x++)if(d[x]===u){s(e,u,f,m);return}if(typeof A.depthLimit<"u"&&b>A.depthLimit){s(h,u,f,m);return}if(typeof A.edgesLimit<"u"&&y+1>A.edgesLimit){s(h,u,f,m);return}if(d.push(u),Array.isArray(u))for(x=0;x<u.length;x++)a(u[x],x,x,d,u,b,A);else{var I=Object.keys(u);for(x=0;x<I.length;x++){var F=I[x];a(u[F],F,x,d,u,b,A)}}d.pop()}}function o(u,f){return u<f?-1:u>f?1:0}function c(u,f,y,d){typeof d>"u"&&(d=n());var m=l(u,"",0,[],void 0,0,d)||u,b;try{r.length===0?b=JSON.stringify(m,f,y):b=JSON.stringify(m,p(f),y)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;t.length!==0;){var A=t.pop();A.length===4?Object.defineProperty(A[0],A[1],A[3]):A[0][A[1]]=A[2]}}return b}function l(u,f,y,d,m,b,A){b+=1;var x;if(typeof u=="object"&&u!==null){for(x=0;x<d.length;x++)if(d[x]===u){s(e,u,f,m);return}try{if(typeof u.toJSON=="function")return}catch{return}if(typeof A.depthLimit<"u"&&b>A.depthLimit){s(h,u,f,m);return}if(typeof A.edgesLimit<"u"&&y+1>A.edgesLimit){s(h,u,f,m);return}if(d.push(u),Array.isArray(u))for(x=0;x<u.length;x++)l(u[x],x,x,d,u,b,A);else{var I={},F=Object.keys(u).sort(o);for(x=0;x<F.length;x++){var L=F[x];l(u[L],L,x,d,u,b,A),I[L]=u[L]}if(typeof m<"u")t.push([m,f,u]),m[f]=I;else return I}d.pop()}}function p(u){return u=typeof u<"u"?u:function(f,y){return y},function(f,y){if(r.length>0)for(var d=0;d<r.length;d++){var m=r[d];if(m[1]===f&&m[0]===y){y=m[2],r.splice(d,1);break}}return u.call(this,f,y)}}return et}var Ii=Ri();const $i=Kn(Ii),zn={debug:"debug",verbose:"debug",log:"log",warn:"warn",error:"error",fatal:"error"},Bi={verbose:"DEFAULT",debug:"DEBUG",log:"INFO",warn:"WARNING",error:"ERROR",fatal:"CRITICAL"},ji=["x-api-key","x-api-token","x-key","x-token","cookie","password","pass","psw","auth","authentication","authorization","token","access_token","client-secret","credentials","secret"];class qi{constructor(e,t={}){this.module=e,t.logLevels&&(this.levels=new Set(t.logLevels))}levels=new Set(["verbose","debug","log","warn","error","fatal"]);mapLogLevelToConsoleMethod(e){return zn[e]}write(e,t,r,n,i){if(!this.levels.has(e))return;const s=this.buildLog(e,t,r,n,i),a=$i(s,this.sensitiveReplacer),o=this.mapLogLevelToConsoleMethod(e);console[o](a)}buildLog(e,t,r,n,i){const{writeMetadata:s,writeContext:a,writeError:o}=this.sanitizeLog(r,n,i),c={};return typeof t=="string"&&(c.textPayload=t),!s&&typeof t!="string"&&!(t instanceof Error)&&(c.metadata=t),t instanceof Error&&(c.error=JSON.stringify(t,Object.getOwnPropertyNames(t))),a&&(c.context=a),s&&(c.metadata=s),!c.error&&o&&(c.error=JSON.stringify(o,Object.getOwnPropertyNames(o))),{severity:Bi[e],module:this.module,textPayload:c.textPayload,message:c}}sanitizeLog(e,t,r){if(t instanceof Error&&(!r||typeof r=="string"))return{writeMetadata:void 0,writeContext:e||r,writeError:t};let n=t,i=e;return typeof n=="string"&&!e&&(i=n,n=void 0),{writeMetadata:n,writeContext:i,writeError:r}}sensitiveReplacer(e,t){return ji.includes(e.toLowerCase())?"[HIDDEN BY LOGGER]":t}debug(e,t,r){this.write("debug",e,r,t)}verbose(e,t,r){this.write("verbose",e,r,t)}log(e,t,r){this.write("log",e,r,t)}warn(e,t,r,n){this.write("warn",e,n,t,r)}error(e,t,r,n){this.write("error",e,n,t,r)}fatal(e,t,r,n){this.write("fatal",e,n,t,r)}setLogLevels(e){this.levels=new Set(e)}}class Di{debug=()=>{};verbose=()=>{};log=()=>{};warn=()=>{};error=()=>{};fatal=()=>{};setLogLevels=()=>{}}class He{constructor(e){this.dataSource=e}em;static newInstance(e){const t=e.constructor;return new t(e.dataSource)}withEntityManager(e){return this.em=e,this}withRepositoryManager(e){return He.newInstance(this).withEntityManager(e.em)}lockInTransaction(e="pessimistic_write"){return this.em?{mode:e}:void 0}getRepository(e){return this.em?this.em.getRepository(e):this.dataSource.getRepository(e)}async withTransaction(e){let t;return await this.dataSource.transaction(async r=>{t=await e(He.newInstance(this).withEntityManager(r))}),t}}const Fi=h=>({...h,withTransaction:async e=>await e(h),withRepositoryManager:()=>h}),ki=(h,e)=>`unaccent(LOWER(${h})) ILIKE unaccent(LOWER(:${e}))`,Li=Object.freeze(Object.defineProperty({__proto__:null,unaccentSearch:ki},Symbol.toStringTag,{value:"Module"}));var Cr={};var Tr;function Ui(){if(Tr)return Cr;Tr=1;var h;return(function(e){(function(t){var r=typeof globalThis=="object"?globalThis:typeof Je=="object"?Je:typeof self=="object"?self:typeof this=="object"?this:o(),n=i(e);typeof r.Reflect<"u"&&(n=i(r.Reflect,n)),t(n,r),typeof r.Reflect>"u"&&(r.Reflect=e);function i(c,l){return function(p,u){Object.defineProperty(c,p,{configurable:!0,writable:!0,value:u}),l&&l(p,u)}}function s(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function o(){return s()||a()}})(function(t,r){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",s=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",c={__proto__:[]}instanceof Array,l=!o&&!c,p={create:o?function(){return Ze(Object.create(null))}:c?function(){return Ze({__proto__:null})}:function(){return Ze({})},has:l?function(g,v){return n.call(g,v)}:function(g,v){return v in g},get:l?function(g,v){return n.call(g,v)?g[v]:void 0}:function(g,v){return g[v]}},u=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:mi(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:gi(),d=typeof WeakMap=="function"?WeakMap:bi(),m=i?Symbol.for("@reflect-metadata:registry"):void 0,b=Re(),A=di(b);function x(g,v,E,N){if(_(E)){if(!re(g))throw new TypeError;if(!xe(v))throw new TypeError;return H(g,v)}else{if(!re(g))throw new TypeError;if(!ne(v))throw new TypeError;if(!ne(N)&&!_(N)&&!X(N))throw new TypeError;return X(N)&&(N=void 0),E=Y(E),P(g,v,E,N)}}t("decorate",x);function I(g,v){function E(N,W){if(!ne(N))throw new TypeError;if(!_(W)&&!Ae(W))throw new TypeError;B(g,v,N,W)}return E}t("metadata",I);function F(g,v,E,N){if(!ne(E))throw new TypeError;return _(N)||(N=Y(N)),B(g,v,E,N)}t("defineMetadata",F);function L(g,v,E){if(!ne(v))throw new TypeError;return _(E)||(E=Y(E)),T(g,v,E)}t("hasMetadata",L);function Q(g,v,E){if(!ne(v))throw new TypeError;return _(E)||(E=Y(E)),O(g,v,E)}t("hasOwnMetadata",Q);function se(g,v,E){if(!ne(v))throw new TypeError;return _(E)||(E=Y(E)),w(g,v,E)}t("getMetadata",se);function te(g,v,E){if(!ne(v))throw new TypeError;return _(E)||(E=Y(E)),C(g,v,E)}t("getOwnMetadata",te);function k(g,v){if(!ne(g))throw new TypeError;return _(v)||(v=Y(v)),V(g,v)}t("getMetadataKeys",k);function M(g,v){if(!ne(g))throw new TypeError;return _(v)||(v=Y(v)),G(g,v)}t("getOwnMetadataKeys",M);function U(g,v,E){if(!ne(v))throw new TypeError;if(_(E)||(E=Y(E)),!ne(v))throw new TypeError;_(E)||(E=Y(E));var N=qe(v,E,!1);return _(N)?!1:N.OrdinaryDeleteMetadata(g,v,E)}t("deleteMetadata",U);function H(g,v){for(var E=g.length-1;E>=0;--E){var N=g[E],W=N(v);if(!_(W)&&!X(W)){if(!xe(W))throw new TypeError;v=W}}return v}function P(g,v,E,N){for(var W=g.length-1;W>=0;--W){var ge=g[W],ye=ge(v,E,N);if(!_(ye)&&!X(ye)){if(!ne(ye))throw new TypeError;N=ye}}return N}function T(g,v,E){var N=O(g,v,E);if(N)return!0;var W=be(v);return X(W)?!1:T(g,W,E)}function O(g,v,E){var N=qe(v,E,!1);return _(N)?!1:ie(N.OrdinaryHasOwnMetadata(g,v,E))}function w(g,v,E){var N=O(g,v,E);if(N)return C(g,v,E);var W=be(v);if(!X(W))return w(g,W,E)}function C(g,v,E){var N=qe(v,E,!1);if(!_(N))return N.OrdinaryGetOwnMetadata(g,v,E)}function B(g,v,E,N){var W=qe(E,N,!0);W.OrdinaryDefineOwnMetadata(g,v,E,N)}function V(g,v){var E=G(g,v),N=be(g);if(N===null)return E;var W=V(N,v);if(W.length<=0)return E;if(E.length<=0)return W;for(var ge=new y,ye=[],z=0,R=E;z<R.length;z++){var j=R[z],q=ge.has(j);q||(ge.add(j),ye.push(j))}for(var D=0,Z=W;D<Z.length;D++){var j=Z[D],q=ge.has(j);q||(ge.add(j),ye.push(j))}return ye}function G(g,v){var E=qe(g,v,!1);return E?E.OrdinaryOwnMetadataKeys(g,v):[]}function K(g){if(g===null)return 1;switch(typeof g){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return g===null?1:6;default:return 6}}function _(g){return g===void 0}function X(g){return g===null}function me(g){return typeof g=="symbol"}function ne(g){return typeof g=="object"?g!==null:typeof g=="function"}function Me(g,v){switch(K(g)){case 0:return g;case 1:return g;case 2:return g;case 3:return g;case 4:return g;case 5:return g}var E="string",N=Pe(g,s);if(N!==void 0){var W=N.call(g,E);if(ne(W))throw new TypeError;return W}return pe(g)}function pe(g,v){var E,N;{var W=g.toString;if(ae(W)){var N=W.call(g);if(!ne(N))return N}var E=g.valueOf;if(ae(E)){var N=E.call(g);if(!ne(N))return N}}throw new TypeError}function ie(g){return!!g}function J(g){return""+g}function Y(g){var v=Me(g);return me(v)?v:J(v)}function re(g){return Array.isArray?Array.isArray(g):g instanceof Object?g instanceof Array:Object.prototype.toString.call(g)==="[object Array]"}function ae(g){return typeof g=="function"}function xe(g){return typeof g=="function"}function Ae(g){switch(K(g)){case 3:return!0;case 4:return!0;default:return!1}}function de(g,v){return g===v||g!==g&&v!==v}function Pe(g,v){var E=g[v];if(E!=null){if(!ae(E))throw new TypeError;return E}}function Se(g){var v=Pe(g,a);if(!ae(v))throw new TypeError;var E=v.call(g);if(!ne(E))throw new TypeError;return E}function Ne(g){return g.value}function we(g){var v=g.next();return v.done?!1:v}function ue(g){var v=g.return;v&&v.call(g)}function be(g){var v=Object.getPrototypeOf(g);if(typeof g!="function"||g===u||v!==u)return v;var E=g.prototype,N=E&&Object.getPrototypeOf(E);if(N==null||N===Object.prototype)return v;var W=N.constructor;return typeof W!="function"||W===g?v:W}function _e(){var g;!_(m)&&typeof r.Reflect<"u"&&!(m in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(g=yi(r.Reflect));var v,E,N,W=new d,ge={registerProvider:ye,getProvider:R,setProvider:q};return ge;function ye(D){if(!Object.isExtensible(ge))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case g===D:break;case _(v):v=D;break;case v===D:break;case _(E):E=D;break;case E===D:break;default:N===void 0&&(N=new y),N.add(D);break}}function z(D,Z){if(!_(v)){if(v.isProviderFor(D,Z))return v;if(!_(E)){if(E.isProviderFor(D,Z))return v;if(!_(N))for(var ce=Se(N);;){var he=we(ce);if(!he)return;var Ee=Ne(he);if(Ee.isProviderFor(D,Z))return ue(ce),Ee}}}if(!_(g)&&g.isProviderFor(D,Z))return g}function R(D,Z){var ce=W.get(D),he;return _(ce)||(he=ce.get(Z)),_(he)&&(he=z(D,Z),_(he)||(_(ce)&&(ce=new f,W.set(D,ce)),ce.set(Z,he))),he}function j(D){if(_(D))throw new TypeError;return v===D||E===D||!_(N)&&N.has(D)}function q(D,Z,ce){if(!j(ce))throw new Error("Metadata provider not registered.");var he=R(D,Z);if(he!==ce){if(!_(he))return!1;var Ee=W.get(D);_(Ee)&&(Ee=new f,W.set(D,Ee)),Ee.set(Z,ce)}return!0}}function Re(){var g;return!_(m)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&(g=r.Reflect[m]),_(g)&&(g=_e()),!_(m)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:g}),g}function di(g){var v=new d,E={isProviderFor:function(j,q){var D=v.get(j);return _(D)?!1:D.has(q)},OrdinaryDefineOwnMetadata:ye,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:ge,OrdinaryOwnMetadataKeys:z,OrdinaryDeleteMetadata:R};return b.registerProvider(E),E;function N(j,q,D){var Z=v.get(j),ce=!1;if(_(Z)){if(!D)return;Z=new f,v.set(j,Z),ce=!0}var he=Z.get(q);if(_(he)){if(!D)return;if(he=new f,Z.set(q,he),!g.setProvider(j,q,E))throw Z.delete(q),ce&&v.delete(j),new Error("Wrong provider for target.")}return he}function W(j,q,D){var Z=N(q,D,!1);return _(Z)?!1:ie(Z.has(j))}function ge(j,q,D){var Z=N(q,D,!1);if(!_(Z))return Z.get(j)}function ye(j,q,D,Z){var ce=N(D,Z,!0);ce.set(j,q)}function z(j,q){var D=[],Z=N(j,q,!1);if(_(Z))return D;for(var ce=Z.keys(),he=Se(ce),Ee=0;;){var Er=we(he);if(!Er)return D.length=Ee,D;var vi=Ne(Er);try{D[Ee]=vi}catch(xi){try{ue(he)}finally{throw xi}}Ee++}}function R(j,q,D){var Z=N(q,D,!1);if(_(Z)||!Z.delete(j))return!1;if(Z.size===0){var ce=v.get(q);_(ce)||(ce.delete(D),ce.size===0&&v.delete(ce))}return!0}}function yi(g){var v=g.defineMetadata,E=g.hasOwnMetadata,N=g.getOwnMetadata,W=g.getOwnMetadataKeys,ge=g.deleteMetadata,ye=new d,z={isProviderFor:function(R,j){var q=ye.get(R);return!_(q)&&q.has(j)?!0:W(R,j).length?(_(q)&&(q=new y,ye.set(R,q)),q.add(j),!0):!1},OrdinaryDefineOwnMetadata:v,OrdinaryHasOwnMetadata:E,OrdinaryGetOwnMetadata:N,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:ge};return z}function qe(g,v,E){var N=b.getProvider(g,v);if(!_(N))return N;if(E){if(b.setProvider(g,v,A))return A;throw new Error("Illegal state.")}}function mi(){var g={},v=[],E=(function(){function z(R,j,q){this._index=0,this._keys=R,this._values=j,this._selector=q}return z.prototype["@@iterator"]=function(){return this},z.prototype[a]=function(){return this},z.prototype.next=function(){var R=this._index;if(R>=0&&R<this._keys.length){var j=this._selector(this._keys[R],this._values[R]);return R+1>=this._keys.length?(this._index=-1,this._keys=v,this._values=v):this._index++,{value:j,done:!1}}return{value:void 0,done:!0}},z.prototype.throw=function(R){throw this._index>=0&&(this._index=-1,this._keys=v,this._values=v),R},z.prototype.return=function(R){return this._index>=0&&(this._index=-1,this._keys=v,this._values=v),{value:R,done:!0}},z})(),N=(function(){function z(){this._keys=[],this._values=[],this._cacheKey=g,this._cacheIndex=-2}return Object.defineProperty(z.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),z.prototype.has=function(R){return this._find(R,!1)>=0},z.prototype.get=function(R){var j=this._find(R,!1);return j>=0?this._values[j]:void 0},z.prototype.set=function(R,j){var q=this._find(R,!0);return this._values[q]=j,this},z.prototype.delete=function(R){var j=this._find(R,!1);if(j>=0){for(var q=this._keys.length,D=j+1;D<q;D++)this._keys[D-1]=this._keys[D],this._values[D-1]=this._values[D];return this._keys.length--,this._values.length--,de(R,this._cacheKey)&&(this._cacheKey=g,this._cacheIndex=-2),!0}return!1},z.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=g,this._cacheIndex=-2},z.prototype.keys=function(){return new E(this._keys,this._values,W)},z.prototype.values=function(){return new E(this._keys,this._values,ge)},z.prototype.entries=function(){return new E(this._keys,this._values,ye)},z.prototype["@@iterator"]=function(){return this.entries()},z.prototype[a]=function(){return this.entries()},z.prototype._find=function(R,j){if(!de(this._cacheKey,R)){this._cacheIndex=-1;for(var q=0;q<this._keys.length;q++)if(de(this._keys[q],R)){this._cacheIndex=q;break}}return this._cacheIndex<0&&j&&(this._cacheIndex=this._keys.length,this._keys.push(R),this._values.push(void 0)),this._cacheIndex},z})();return N;function W(z,R){return z}function ge(z,R){return R}function ye(z,R){return[z,R]}}function gi(){var g=(function(){function v(){this._map=new f}return Object.defineProperty(v.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),v.prototype.has=function(E){return this._map.has(E)},v.prototype.add=function(E){return this._map.set(E,E),this},v.prototype.delete=function(E){return this._map.delete(E)},v.prototype.clear=function(){this._map.clear()},v.prototype.keys=function(){return this._map.keys()},v.prototype.values=function(){return this._map.keys()},v.prototype.entries=function(){return this._map.entries()},v.prototype["@@iterator"]=function(){return this.keys()},v.prototype[a]=function(){return this.keys()},v})();return g}function bi(){var g=16,v=p.create(),E=N();return(function(){function R(){this._key=N()}return R.prototype.has=function(j){var q=W(j,!1);return q!==void 0?p.has(q,this._key):!1},R.prototype.get=function(j){var q=W(j,!1);return q!==void 0?p.get(q,this._key):void 0},R.prototype.set=function(j,q){var D=W(j,!0);return D[this._key]=q,this},R.prototype.delete=function(j){var q=W(j,!1);return q!==void 0?delete q[this._key]:!1},R.prototype.clear=function(){this._key=N()},R})();function N(){var R;do R="@@WeakMap@@"+z();while(p.has(v,R));return v[R]=!0,R}function W(R,j){if(!n.call(R,E)){if(!j)return;Object.defineProperty(R,E,{value:p.create()})}return R[E]}function ge(R,j){for(var q=0;q<j;++q)R[q]=Math.random()*255|0;return R}function ye(R){if(typeof Uint8Array=="function"){var j=new Uint8Array(R);return typeof crypto<"u"?crypto.getRandomValues(j):typeof msCrypto<"u"?msCrypto.getRandomValues(j):ge(j,R),j}return ge(new Array(R),R)}function z(){var R=ye(g);R[6]=R[6]&79|64,R[8]=R[8]&191|128;for(var j="",q=0;q<g;++q){var D=R[q];(q===4||q===6||q===8)&&(j+="-"),D<16&&(j+="0"),j+=D.toString(16).toLowerCase()}return j}}function Ze(g){return g.__=void 0,delete g.__,g}})})(h||(h={})),Cr}Ui();class Vi{static getInheritanceTree(e){const t=[e],r=n=>{const i=Object.getPrototypeOf(n);i&&i.name&&(t.push(i),r(i))};return r(e),t}static isInherited(e,t){return e.prototype instanceof t}static filterByTarget(e,t){return t?e.filter(r=>r.target&&t.indexOf(r.target)!==-1):e}}class Wi{constructor(){this.tables=[],this.trees=[],this.entityRepositories=[],this.transactionEntityManagers=[],this.transactionRepositories=[],this.namingStrategies=[],this.entitySubscribers=[],this.indices=[],this.foreignKeys=[],this.uniques=[],this.checks=[],this.exclusions=[],this.columns=[],this.generations=[],this.relations=[],this.joinColumns=[],this.joinTables=[],this.entityListeners=[],this.relationCounts=[],this.relationIds=[],this.embeddeds=[],this.inheritances=[],this.discriminatorValues=[]}filterTables(e){return this.filterByTarget(this.tables,e)}filterColumns(e){return this.filterByTargetAndWithoutDuplicateProperties(this.columns,e)}findGenerated(e,t){return this.generations.find(r=>(Array.isArray(e)?e.indexOf(r.target)!==-1:r.target===e)&&r.propertyName===t)}findTree(e){return this.trees.find(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterRelations(e){return this.filterByTargetAndWithoutDuplicateRelationProperties(this.relations,e)}filterRelationIds(e){return this.filterByTargetAndWithoutDuplicateProperties(this.relationIds,e)}filterRelationCounts(e){return this.filterByTargetAndWithoutDuplicateProperties(this.relationCounts,e)}filterIndices(e){return this.indices.filter(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterForeignKeys(e){return this.foreignKeys.filter(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterUniques(e){return this.uniques.filter(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterChecks(e){return this.checks.filter(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterExclusions(e){return this.exclusions.filter(t=>Array.isArray(e)?e.indexOf(t.target)!==-1:t.target===e)}filterListeners(e){return this.filterByTarget(this.entityListeners,e)}filterEmbeddeds(e){return this.filterByTargetAndWithoutDuplicateEmbeddedProperties(this.embeddeds,e)}findJoinTable(e,t){return this.joinTables.find(r=>r.target===e&&r.propertyName===t)}filterJoinColumns(e,t){return this.joinColumns.filter(r=>r.target===e&&r.propertyName===t)}filterSubscribers(e){return this.filterByTarget(this.entitySubscribers,e)}filterNamingStrategies(e){return this.filterByTarget(this.namingStrategies,e)}filterTransactionEntityManagers(e,t){return this.transactionEntityManagers.filter(r=>(Array.isArray(e)?e.indexOf(r.target)!==-1:r.target===e)&&r.methodName===t)}filterTransactionRepository(e,t){return this.transactionRepositories.filter(r=>(Array.isArray(e)?e.indexOf(r.target)!==-1:r.target===e)&&r.methodName===t)}filterSingleTableChildren(e){return this.tables.filter(t=>typeof t.target=="function"&&typeof e=="function"&&Vi.isInherited(t.target,e)&&t.type==="entity-child")}findInheritanceType(e){return this.inheritances.find(t=>t.target===e)}findDiscriminatorValue(e){return this.discriminatorValues.find(t=>t.target===e)}filterByTarget(e,t){return e.filter(r=>Array.isArray(t)?t.indexOf(r.target)!==-1:r.target===t)}filterByTargetAndWithoutDuplicateProperties(e,t){const r=[];return e.forEach(n=>{(Array.isArray(t)?t.indexOf(n.target)!==-1:n.target===t)&&(r.find(s=>s.propertyName===n.propertyName)||r.push(n))}),r}filterByTargetAndWithoutDuplicateRelationProperties(e,t){const r=[];return e.forEach(n=>{if(Array.isArray(t)?t.indexOf(n.target)!==-1:n.target===t){const s=r.findIndex(a=>a.propertyName===n.propertyName);if(Array.isArray(t)&&s!==-1&&t.indexOf(n.target)<t.indexOf(r[s].target)){const a=Object.create(r[s]);a.type=n.type,r[s]=a}else s===-1&&r.push(n)}}),r}filterByTargetAndWithoutDuplicateEmbeddedProperties(e,t){const r=[];return e.forEach(n=>{(Array.isArray(t)?t.indexOf(n.target)!==-1:n.target===t)&&(r.find(a=>a.prefix===n.prefix&&a.propertyName===n.propertyName)||r.push(n))}),r}}class Zn{static getGlobalVariable(){return typeof window<"u"?window:typeof globalThis<"u"?globalThis:global}static load(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: require("${e}").`);return""}static pathNormalize(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: path.normalize("${e}").`);return""}static pathExtname(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: path.extname("${e}").`);return""}static pathResolve(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: path.resolve("${e}").`);return""}static fileExist(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: fs.existsSync("${e}").`);return!1}static dotenv(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: dotenv.config({ path: "${e}" }).`)}static getEnvVariable(e){}static readFileSync(e){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: fs.readFileSync("${e}").`);return null}static appendFileSync(e,t){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: fs.appendFileSync("${e}").`)}static writeFile(e,t){if(this.type==="browser")throw new Error(`This option/function is not supported in the browser environment. Failed operation: fs.writeFile("${e}").`);return Promise.reject(null)}static highlightSql(e){return e}static logInfo(e,t){console.info(e+" ",t)}static logError(e,t){console.error(e+" ",t)}static logWarn(e,t){console.warn(e+" ",t)}static log(e){console.log(e)}static warn(e){return e}}Zn.type="browser";typeof window<"u"&&(window.Buffer=pr.Buffer);typeof globalThis<"u"&&(globalThis.Buffer=pr.Buffer);typeof global<"u"&&typeof require<"u"&&(global.Buffer=require("buffer/").Buffer);class fe{static isObject(e){return e!==null&&typeof e=="object"}static isObjectWithName(e){return e!==null&&typeof e=="object"&&e.name!==void 0}static assign(e,...t){for(const r of t)for(const n of Object.getOwnPropertyNames(r))e[n]=r[n]}static mixedListToArray(e){return e!==null&&typeof e=="object"?Object.keys(e).map(t=>e[t]):e}}class S extends Error{get name(){return this.constructor.name}constructor(e){super(e),Object.setPrototypeOf?Object.setPrototypeOf(this,new.target.prototype):this.__proto__=new.target.prototype}}class $e extends S{constructor(){super("Locking not supported on given driver.")}}class ur extends S{constructor(){super('Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values.')}}class oe{static isMssqlParameter(e){return this.check(e,"MssqlParameter")}static isEntityMetadata(e){return this.check(e,"EntityMetadata")}static isColumnMetadata(e){return this.check(e,"ColumnMetadata")}static isSelectQueryBuilder(e){return this.check(e,"SelectQueryBuilder")}static isInsertQueryBuilder(e){return this.check(e,"InsertQueryBuilder")}static isDeleteQueryBuilder(e){return this.check(e,"DeleteQueryBuilder")}static isUpdateQueryBuilder(e){return this.check(e,"UpdateQueryBuilder")}static isSoftDeleteQueryBuilder(e){return this.check(e,"SoftDeleteQueryBuilder")}static isRelationQueryBuilder(e){return this.check(e,"RelationQueryBuilder")}static isBrackets(e){return this.check(e,"Brackets")||this.check(e,"NotBrackets")}static isNotBrackets(e){return this.check(e,"NotBrackets")}static isSubject(e){return this.check(e,"Subject")}static isRdbmsSchemaBuilder(e){return this.check(e,"RdbmsSchemaBuilder")}static isMongoEntityManager(e){return this.check(e,"MongoEntityManager")}static isSqljsEntityManager(e){return this.check(e,"SqljsEntityManager")}static isEntitySchema(e){return this.check(e,"EntitySchema")}static isBaseEntityConstructor(e){return typeof e=="function"&&typeof e.hasId=="function"&&typeof e.save=="function"&&typeof e.useDataSource=="function"}static isFindOperator(e){return this.check(e,"FindOperator")||this.check(e,"EqualOperator")}static isEqualOperator(e){return this.check(e,"EqualOperator")}static isQuery(e){return this.check(e,"Query")}static isTable(e){return this.check(e,"Table")}static isTableCheck(e){return this.check(e,"TableCheck")}static isTableColumn(e){return this.check(e,"TableColumn")}static isTableExclusion(e){return this.check(e,"TableExclusion")}static isTableForeignKey(e){return this.check(e,"TableForeignKey")}static isTableIndex(e){return this.check(e,"TableIndex")}static isTableUnique(e){return this.check(e,"TableUnique")}static isView(e){return this.check(e,"View")}static isDataSource(e){return this.check(e,"DataSource")}static check(e,t){return typeof e=="object"&&e!==null&&e["@instanceof"]===Symbol.for(t)}}class Qi extends S{constructor(e,t){super(),this.entityClass=e,this.criteria=t,this.message=`Could not find any entity of type "${this.stringifyTarget(e)}" matching: ${this.stringifyCriteria(t)}`}stringifyTarget(e){return oe.isEntitySchema(e)?e.options.name:typeof e=="function"||fe.isObject(e)&&"name"in e?e.name:e}stringifyCriteria(e){try{return JSON.stringify(e,null,4)}catch{}return""+e}}class Pr extends S{constructor(e,t,r){super(`The optimistic lock on entity ${e} failed, version ${t} was expected, but is actually ${r}.`)}}class Xn extends S{constructor(){super("Your database does not support LIMIT on UPDATE statements.")}}class Gi extends S{constructor(e){super(`Entity "${e.name}" does not have delete date columns.`)}}class Ye extends S{constructor(){super("OUTPUT or RETURNING clause only supported by PostgreSQL, MariaDB, Microsoft SqlServer or Google Spanner.")}}class Ce extends S{constructor(e,t){super(e),Object.setPrototypeOf(this,Ce.prototype),this.message=`Property "${e}" was not found in "${t.targetName}". Make sure your query is correct.`}}class Ji extends S{constructor(e){super(`Entity ${e} does not have version or update date columns.`)}}class Hi extends S{constructor(){super('Cannot perform insert query because values are not defined. Call "qb.values(...)" method to specify inserted values.')}}class De extends S{constructor(){super("The optimistic lock can be used only with getOne() method.")}}class Yi extends S{constructor(e){super(),e.length===1?this.message=`Relation "${e[0]}" was not found; please check if it is correct and really exists in your entity.`:this.message=`Relations ${e.map(t=>`"${t}"`).join(", ")} were not found; please check if relations are correct and they exist in your entities.`}}class Ki extends S{constructor(){super("An open transaction is required for pessimistic lock.")}}class zi extends S{constructor(){super("RDBMS does not support OFFSET without LIMIT in SELECT statements. You must use limit in conjunction with offset function (or take in conjunction with skip function if you are using pagination).")}}class Sr{constructor(e){fe.assign(this,e||{})}get target(){return this.metadata.target}get hasMetadata(){return!!this._metadata}set metadata(e){this._metadata=e}get metadata(){if(!this._metadata)throw new S(`Cannot get entity metadata for the given alias "${this.name}"`);return this._metadata}}class Te{static isAliasProperty(e){if(typeof e!="string"||e.indexOf(".")===-1)return!1;const[t,r]=e.split(".");return!(!t||!r||e.indexOf("(")!==-1||e.indexOf(")")!==-1)}}var tt={exports:{}},Ve={exports:{}},Nr;function Be(){return Nr||(Nr=1,typeof Object.create=="function"?Ve.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Ve.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),Ve.exports}var We={exports:{}};var _r;function Ie(){return _r||(_r=1,(function(h,e){var t=pr,r=t.Buffer;function n(s,a){for(var o in s)a[o]=s[o]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?h.exports=t:(n(t,e),e.Buffer=i);function i(s,a,o){return r(s,a,o)}i.prototype=Object.create(r.prototype),n(r,i),i.from=function(s,a,o){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,o)},i.alloc=function(s,a,o){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof o=="string"?c.fill(a,o):c.fill(a):c.fill(0),c},i.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},i.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}})(We,We.exports)),We.exports}var rt,Rr;function Zi(){if(Rr)return rt;Rr=1;var h={}.toString;return rt=Array.isArray||function(e){return h.call(e)=="[object Array]"},rt}var nt,Ir;function Fe(){return Ir||(Ir=1,nt=TypeError),nt}var it,$r;function ei(){return $r||($r=1,it=Object),it}var st,Br;function Xi(){return Br||(Br=1,st=Error),st}var at,jr;function es(){return jr||(jr=1,at=EvalError),at}var ot,qr;function ts(){return qr||(qr=1,ot=RangeError),ot}var ut,Dr;function rs(){return Dr||(Dr=1,ut=ReferenceError),ut}var ct,Fr;function ti(){return Fr||(Fr=1,ct=SyntaxError),ct}var lt,kr;function ns(){return kr||(kr=1,lt=URIError),lt}var pt,Lr;function is(){return Lr||(Lr=1,pt=Math.abs),pt}var ht,Ur;function ss(){return Ur||(Ur=1,ht=Math.floor),ht}var ft,Vr;function as(){return Vr||(Vr=1,ft=Math.max),ft}var dt,Wr;function os(){return Wr||(Wr=1,dt=Math.min),dt}var yt,Qr;function us(){return Qr||(Qr=1,yt=Math.pow),yt}var mt,Gr;function cs(){return Gr||(Gr=1,mt=Math.round),mt}var gt,Jr;function ls(){return Jr||(Jr=1,gt=Number.isNaN||function(e){return e!==e}),gt}var bt,Hr;function ps(){if(Hr)return bt;Hr=1;var h=ls();return bt=function(t){return h(t)||t===0?t:t<0?-1:1},bt}var vt,Yr;function hs(){return Yr||(Yr=1,vt=Object.getOwnPropertyDescriptor),vt}var xt,Kr;function ke(){if(Kr)return xt;Kr=1;var h=hs();if(h)try{h([],"length")}catch{h=null}return xt=h,xt}var Mt,zr;function Ke(){if(zr)return Mt;zr=1;var h=Object.defineProperty||!1;if(h)try{h({},"a",{value:1})}catch{h=!1}return Mt=h,Mt}var wt,Zr;function ri(){return Zr||(Zr=1,wt=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},t=Symbol("test"),r=Object(t);if(typeof t=="string"||Object.prototype.toString.call(t)!=="[object Symbol]"||Object.prototype.toString.call(r)!=="[object Symbol]")return!1;var n=42;e[t]=n;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,t);if(a.value!==n||a.enumerable!==!0)return!1}return!0}),wt}var Et,Xr;function fs(){if(Xr)return Et;Xr=1;var h=typeof Symbol<"u"&&Symbol,e=ri();return Et=function(){return typeof h!="function"||typeof Symbol!="function"||typeof h("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Et}var At,en;function ni(){return en||(en=1,At=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),At}var Ot,tn;function ii(){if(tn)return Ot;tn=1;var h=ei();return Ot=h.getPrototypeOf||null,Ot}var Ct,rn;function ds(){if(rn)return Ct;rn=1;var h="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",n=function(o,c){for(var l=[],p=0;p<o.length;p+=1)l[p]=o[p];for(var u=0;u<c.length;u+=1)l[u+o.length]=c[u];return l},i=function(o,c){for(var l=[],p=c,u=0;p<o.length;p+=1,u+=1)l[u]=o[p];return l},s=function(a,o){for(var c="",l=0;l<a.length;l+=1)c+=a[l],l+1<a.length&&(c+=o);return c};return Ct=function(o){var c=this;if(typeof c!="function"||e.apply(c)!==r)throw new TypeError(h+c);for(var l=i(arguments,1),p,u=function(){if(this instanceof p){var b=c.apply(this,n(l,arguments));return Object(b)===b?b:this}return c.apply(o,n(l,arguments))},f=t(0,c.length-l.length),y=[],d=0;d<f;d++)y[d]="$"+d;if(p=Function("binder","return function ("+s(y,",")+"){ return binder.apply(this,arguments); }")(u),c.prototype){var m=function(){};m.prototype=c.prototype,p.prototype=new m,m.prototype=null}return p},Ct}var Tt,nn;function Le(){if(nn)return Tt;nn=1;var h=ds();return Tt=Function.prototype.bind||h,Tt}var Pt,sn;function hr(){return sn||(sn=1,Pt=Function.prototype.call),Pt}var St,an;function fr(){return an||(an=1,St=Function.prototype.apply),St}var Nt,on;function ys(){return on||(on=1,Nt=typeof Reflect<"u"&&Reflect&&Reflect.apply),Nt}var _t,un;function si(){if(un)return _t;un=1;var h=Le(),e=fr(),t=hr(),r=ys();return _t=r||h.call(t,e),_t}var Rt,cn;function dr(){if(cn)return Rt;cn=1;var h=Le(),e=Fe(),t=hr(),r=si();return Rt=function(i){if(i.length<1||typeof i[0]!="function")throw new e("a function is required");return r(h,t,i)},Rt}var It,ln;function ms(){if(ln)return It;ln=1;var h=dr(),e=ke(),t;try{t=[].__proto__===Array.prototype}catch(s){if(!s||typeof s!="object"||!("code"in s)||s.code!=="ERR_PROTO_ACCESS")throw s}var r=!!t&&e&&e(Object.prototype,"__proto__"),n=Object,i=n.getPrototypeOf;return It=r&&typeof r.get=="function"?h([r.get]):typeof i=="function"?function(a){return i(a==null?a:n(a))}:!1,It}var $t,pn;function ai(){if(pn)return $t;pn=1;var h=ni(),e=ii(),t=ms();return $t=h?function(n){return h(n)}:e?function(n){if(!n||typeof n!="object"&&typeof n!="function")throw new TypeError("getProto: not an object");return e(n)}:t?function(n){return t(n)}:null,$t}var Bt,hn;function gs(){if(hn)return Bt;hn=1;var h=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Le();return Bt=t.call(h,e),Bt}var jt,fn;function oi(){if(fn)return jt;fn=1;var h,e=ei(),t=Xi(),r=es(),n=ts(),i=rs(),s=ti(),a=Fe(),o=ns(),c=is(),l=ss(),p=as(),u=os(),f=us(),y=cs(),d=ps(),m=Function,b=function(ie){try{return m('"use strict"; return ('+ie+").constructor;")()}catch{}},A=ke(),x=Ke(),I=function(){throw new a},F=A?(function(){try{return arguments.callee,I}catch{try{return A(arguments,"callee").get}catch{return I}}})():I,L=fs()(),Q=ai(),se=ii(),te=ni(),k=fr(),M=hr(),U={},H=typeof Uint8Array>"u"||!Q?h:Q(Uint8Array),P={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?h:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?h:ArrayBuffer,"%ArrayIteratorPrototype%":L&&Q?Q([][Symbol.iterator]()):h,"%AsyncFromSyncIteratorPrototype%":h,"%AsyncFunction%":U,"%AsyncGenerator%":U,"%AsyncGeneratorFunction%":U,"%AsyncIteratorPrototype%":U,"%Atomics%":typeof Atomics>"u"?h:Atomics,"%BigInt%":typeof BigInt>"u"?h:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?h:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?h:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?h:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":t,"%eval%":eval,"%EvalError%":r,"%Float16Array%":typeof Float16Array>"u"?h:Float16Array,"%Float32Array%":typeof Float32Array>"u"?h:Float32Array,"%Float64Array%":typeof Float64Array>"u"?h:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?h:FinalizationRegistry,"%Function%":m,"%GeneratorFunction%":U,"%Int8Array%":typeof Int8Array>"u"?h:Int8Array,"%Int16Array%":typeof Int16Array>"u"?h:Int16Array,"%Int32Array%":typeof Int32Array>"u"?h:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":L&&Q?Q(Q([][Symbol.iterator]())):h,"%JSON%":typeof JSON=="object"?JSON:h,"%Map%":typeof Map>"u"?h:Map,"%MapIteratorPrototype%":typeof Map>"u"||!L||!Q?h:Q(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":A,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?h:Promise,"%Proxy%":typeof Proxy>"u"?h:Proxy,"%RangeError%":n,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?h:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?h:Set,"%SetIteratorPrototype%":typeof Set>"u"||!L||!Q?h:Q(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?h:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":L&&Q?Q(""[Symbol.iterator]()):h,"%Symbol%":L?Symbol:h,"%SyntaxError%":s,"%ThrowTypeError%":F,"%TypedArray%":H,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?h:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?h:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?h:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?h:Uint32Array,"%URIError%":o,"%WeakMap%":typeof WeakMap>"u"?h:WeakMap,"%WeakRef%":typeof WeakRef>"u"?h:WeakRef,"%WeakSet%":typeof WeakSet>"u"?h:WeakSet,"%Function.prototype.call%":M,"%Function.prototype.apply%":k,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":se,"%Math.abs%":c,"%Math.floor%":l,"%Math.max%":p,"%Math.min%":u,"%Math.pow%":f,"%Math.round%":y,"%Math.sign%":d,"%Reflect.getPrototypeOf%":te};if(Q)try{null.error}catch(ie){var T=Q(Q(ie));P["%Error.prototype%"]=T}var O=function ie(J){var Y;if(J==="%AsyncFunction%")Y=b("async function () {}");else if(J==="%GeneratorFunction%")Y=b("function* () {}");else if(J==="%AsyncGeneratorFunction%")Y=b("async function* () {}");else if(J==="%AsyncGenerator%"){var re=ie("%AsyncGeneratorFunction%");re&&(Y=re.prototype)}else if(J==="%AsyncIteratorPrototype%"){var ae=ie("%AsyncGenerator%");ae&&Q&&(Y=Q(ae.prototype))}return P[J]=Y,Y},w={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},C=Le(),B=gs(),V=C.call(M,Array.prototype.concat),G=C.call(k,Array.prototype.splice),K=C.call(M,String.prototype.replace),_=C.call(M,String.prototype.slice),X=C.call(M,RegExp.prototype.exec),me=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ne=/\\(\\)?/g,Me=function(J){var Y=_(J,0,1),re=_(J,-1);if(Y==="%"&&re!=="%")throw new s("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&Y!=="%")throw new s("invalid intrinsic syntax, expected opening `%`");var ae=[];return K(J,me,function(xe,Ae,de,Pe){ae[ae.length]=de?K(Pe,ne,"$1"):Ae||xe}),ae},pe=function(J,Y){var re=J,ae;if(B(w,re)&&(ae=w[re],re="%"+ae[0]+"%"),B(P,re)){var xe=P[re];if(xe===U&&(xe=O(re)),typeof xe>"u"&&!Y)throw new a("intrinsic "+J+" exists, but is not available. Please file an issue!");return{alias:ae,name:re,value:xe}}throw new s("intrinsic "+J+" does not exist!")};return jt=function(J,Y){if(typeof J!="string"||J.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof Y!="boolean")throw new a('"allowMissing" argument must be a boolean');if(X(/^%?[^%]*%?$/,J)===null)throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=Me(J),ae=re.length>0?re[0]:"",xe=pe("%"+ae+"%",Y),Ae=xe.name,de=xe.value,Pe=!1,Se=xe.alias;Se&&(ae=Se[0],G(re,V([0,1],Se)));for(var Ne=1,we=!0;Ne<re.length;Ne+=1){var ue=re[Ne],be=_(ue,0,1),_e=_(ue,-1);if((be==='"'||be==="'"||be==="`"||_e==='"'||_e==="'"||_e==="`")&&be!==_e)throw new s("property names with quotes must have matching quotes");if((ue==="constructor"||!we)&&(Pe=!0),ae+="."+ue,Ae="%"+ae+"%",B(P,Ae))de=P[Ae];else if(de!=null){if(!(ue in de)){if(!Y)throw new a("base intrinsic for "+J+" exists, but the property is not available.");return}if(A&&Ne+1>=re.length){var Re=A(de,ue);we=!!Re,we&&"get"in Re&&!("originalValue"in Re.get)?de=Re.get:de=de[ue]}else we=B(de,ue),de=de[ue];we&&!Pe&&(P[Ae]=de)}}return de},jt}var qt,dn;function ui(){if(dn)return qt;dn=1;var h=oi(),e=dr(),t=e([h("%String.prototype.indexOf%")]);return qt=function(n,i){var s=h(n,!!i);return typeof s=="function"&&t(n,".prototype.")>-1?e([s]):s},qt}var Dt,yn;function bs(){if(yn)return Dt;yn=1;var h=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,t,r;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},e(function(){throw 42},null,t)}catch(A){A!==r&&(e=null)}else e=null;var n=/^\s*class\b/,i=function(x){try{var I=h.call(x);return n.test(I)}catch{return!1}},s=function(x){try{return i(x)?!1:(h.call(x),!0)}catch{return!1}},a=Object.prototype.toString,o="[object Object]",c="[object Function]",l="[object GeneratorFunction]",p="[object HTMLAllCollection]",u="[object HTML document.all class]",f="[object HTMLCollection]",y=typeof Symbol=="function"&&!!Symbol.toStringTag,d=!(0 in[,]),m=function(){return!1};if(typeof document=="object"){var b=document.all;a.call(b)===a.call(document.all)&&(m=function(x){if((d||!x)&&(typeof x>"u"||typeof x=="object"))try{var I=a.call(x);return(I===p||I===u||I===f||I===o)&&x("")==null}catch{}return!1})}return Dt=e?function(x){if(m(x))return!0;if(!x||typeof x!="function"&&typeof x!="object")return!1;try{e(x,null,t)}catch(I){if(I!==r)return!1}return!i(x)&&s(x)}:function(x){if(m(x))return!0;if(!x||typeof x!="function"&&typeof x!="object")return!1;if(y)return s(x);if(i(x))return!1;var I=a.call(x);return I!==c&&I!==l&&!/^\[object HTML/.test(I)?!1:s(x)},Dt}var Ft,mn;function vs(){if(mn)return Ft;mn=1;var h=bs(),e=Object.prototype.toString,t=Object.prototype.hasOwnProperty,r=function(o,c,l){for(var p=0,u=o.length;p<u;p++)t.call(o,p)&&(l==null?c(o[p],p,o):c.call(l,o[p],p,o))},n=function(o,c,l){for(var p=0,u=o.length;p<u;p++)l==null?c(o.charAt(p),p,o):c.call(l,o.charAt(p),p,o)},i=function(o,c,l){for(var p in o)t.call(o,p)&&(l==null?c(o[p],p,o):c.call(l,o[p],p,o))};function s(a){return e.call(a)==="[object Array]"}return Ft=function(o,c,l){if(!h(c))throw new TypeError("iterator must be a function");var p;arguments.length>=3&&(p=l),s(o)?r(o,c,p):typeof o=="string"?n(o,c,p):i(o,c,p)},Ft}var kt,gn;function xs(){return gn||(gn=1,kt=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),kt}var Lt,bn;function Ms(){if(bn)return Lt;bn=1;var h=xs(),e=typeof globalThis>"u"?Je:globalThis;return Lt=function(){for(var r=[],n=0;n<h.length;n++)typeof e[h[n]]=="function"&&(r[r.length]=h[n]);return r},Lt}var Ut={exports:{}},Vt,vn;function ws(){if(vn)return Vt;vn=1;var h=Ke(),e=ti(),t=Fe(),r=ke();return Vt=function(i,s,a){if(!i||typeof i!="object"&&typeof i!="function")throw new t("`obj` must be an object or a function`");if(typeof s!="string"&&typeof s!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var o=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,p=arguments.length>6?arguments[6]:!1,u=!!r&&r(i,s);if(h)h(i,s,{configurable:l===null&&u?u.configurable:!l,enumerable:o===null&&u?u.enumerable:!o,value:a,writable:c===null&&u?u.writable:!c});else if(p||!o&&!c&&!l)i[s]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Vt}var Wt,xn;function Es(){if(xn)return Wt;xn=1;var h=Ke(),e=function(){return!!h};return e.hasArrayLengthDefineBug=function(){if(!h)return null;try{return h([],"length",{value:1}).length!==1}catch{return!0}},Wt=e,Wt}var Qt,Mn;function As(){if(Mn)return Qt;Mn=1;var h=oi(),e=ws(),t=Es()(),r=ke(),n=Fe(),i=h("%Math.floor%");return Qt=function(a,o){if(typeof a!="function")throw new n("`fn` is not a function");if(typeof o!="number"||o<0||o>4294967295||i(o)!==o)throw new n("`length` must be a positive 32-bit integer");var c=arguments.length>2&&!!arguments[2],l=!0,p=!0;if("length"in a&&r){var u=r(a,"length");u&&!u.configurable&&(l=!1),u&&!u.writable&&(p=!1)}return(l||p||!c)&&(t?e(a,"length",o,!0,!0):e(a,"length",o)),a},Qt}var Gt,wn;function Os(){if(wn)return Gt;wn=1;var h=Le(),e=fr(),t=si();return Gt=function(){return t(h,e,arguments)},Gt}var En;function Cs(){return En||(En=1,(function(h){var e=As(),t=Ke(),r=dr(),n=Os();h.exports=function(s){var a=r(arguments),o=s.length-(arguments.length-1);return e(a,1+(o>0?o:0),!0)},t?t(h.exports,"apply",{value:n}):h.exports.apply=n})(Ut)),Ut.exports}var Jt,An;function Ts(){if(An)return Jt;An=1;var h=ri();return Jt=function(){return h()&&!!Symbol.toStringTag},Jt}var Ht,On;function Ps(){if(On)return Ht;On=1;var h=vs(),e=Ms(),t=Cs(),r=ui(),n=ke(),i=ai(),s=r("Object.prototype.toString"),a=Ts()(),o=typeof globalThis>"u"?Je:globalThis,c=e(),l=r("String.prototype.slice"),p=r("Array.prototype.indexOf",!0)||function(m,b){for(var A=0;A<m.length;A+=1)if(m[A]===b)return A;return-1},u={__proto__:null};a&&n&&i?h(c,function(d){var m=new o[d];if(Symbol.toStringTag in m&&i){var b=i(m),A=n(b,Symbol.toStringTag);if(!A&&b){var x=i(b);A=n(x,Symbol.toStringTag)}if(A&&A.get){var I=t(A.get);u["$"+d]=I}}}):h(c,function(d){var m=new o[d],b=m.slice||m.set;if(b){var A=t(b);u["$"+d]=A}});var f=function(m){var b=!1;return h(u,function(A,x){if(!b)try{"$"+A(m)===x&&(b=l(x,1))}catch{}}),b},y=function(m){var b=!1;return h(u,function(A,x){if(!b)try{A(m),b=l(x,1)}catch{}}),b};return Ht=function(m){if(!m||typeof m!="object")return!1;if(!a){var b=l(s(m),8,-1);return p(c,b)>-1?b:b!=="Object"?!1:y(m)}return n?f(m):null},Ht}var Yt,Cn;function Ss(){if(Cn)return Yt;Cn=1;var h=Ps();return Yt=function(t){return!!h(t)},Yt}var Kt,Tn;function Ns(){if(Tn)return Kt;Tn=1;var h=Fe(),e=ui(),t=e("TypedArray.prototype.buffer",!0),r=Ss();return Kt=t||function(i){if(!r(i))throw new h("Not a Typed Array");return i.buffer},Kt}var zt,Pn;function _s(){if(Pn)return zt;Pn=1;var h=Ie().Buffer,e=Zi(),t=Ns(),r=ArrayBuffer.isView||function(o){try{return t(o),!0}catch{return!1}},n=typeof Uint8Array<"u",i=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",s=i&&(h.prototype instanceof Uint8Array||h.TYPED_ARRAY_SUPPORT);return zt=function(o,c){if(h.isBuffer(o))return o.constructor&&!("isBuffer"in o)?h.from(o):o;if(typeof o=="string")return h.from(o,c);if(i&&r(o)){if(o.byteLength===0)return h.alloc(0);if(s){var l=h.from(o.buffer,o.byteOffset,o.byteLength);if(l.byteLength===o.byteLength)return l}var p=o instanceof Uint8Array?o:new Uint8Array(o.buffer,o.byteOffset,o.byteLength),u=h.from(p);if(u.length===o.byteLength)return u}if(n&&o instanceof Uint8Array)return h.from(o);var f=e(o);if(f)for(var y=0;y<o.length;y+=1){var d=o[y];if(typeof d!="number"||d<0||d>255||~~d!==d)throw new RangeError("Array items must be numbers in the range 0-255.")}if(f||h.isBuffer(o)&&o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o))return h.from(o);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')},zt}var Zt,Sn;function je(){if(Sn)return Zt;Sn=1;var h=Ie().Buffer,e=_s();function t(r,n){this._block=h.alloc(r),this._finalSize=n,this._blockSize=r,this._len=0}return t.prototype.update=function(r,n){r=e(r,n||"utf8");for(var i=this._block,s=this._blockSize,a=r.length,o=this._len,c=0;c<a;){for(var l=o%s,p=Math.min(a-c,s-l),u=0;u<p;u++)i[l+u]=r[c+u];o+=p,c+=p,o%s===0&&this._update(i)}return this._len+=a,this},t.prototype.digest=function(r){var n=this._len%this._blockSize;this._block[n]=128,this._block.fill(0,n+1),n>=this._finalSize&&(this._update(this._block),this._block.fill(0));var i=this._len*8;if(i<=4294967295)this._block.writeUInt32BE(i,this._blockSize-4);else{var s=(i&4294967295)>>>0,a=(i-s)/4294967296;this._block.writeUInt32BE(a,this._blockSize-8),this._block.writeUInt32BE(s,this._blockSize-4)}this._update(this._block);var o=this._hash();return r?o.toString(r):o},t.prototype._update=function(){throw new Error("_update must be implemented by subclass")},Zt=t,Zt}var Xt,Nn;function Rs(){if(Nn)return Xt;Nn=1;var h=Be(),e=je(),t=Ie().Buffer,r=[1518500249,1859775393,-1894007588,-899497514],n=new Array(80);function i(){this.init(),this._w=n,e.call(this,64,56)}h(i,e),i.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function s(c){return c<<5|c>>>27}function a(c){return c<<30|c>>>2}function o(c,l,p,u){return c===0?l&p|~l&u:c===2?l&p|l&u|p&u:l^p^u}return i.prototype._update=function(c){for(var l=this._w,p=this._a|0,u=this._b|0,f=this._c|0,y=this._d|0,d=this._e|0,m=0;m<16;++m)l[m]=c.readInt32BE(m*4);for(;m<80;++m)l[m]=l[m-3]^l[m-8]^l[m-14]^l[m-16];for(var b=0;b<80;++b){var A=~~(b/20),x=s(p)+o(A,u,f,y)+d+l[b]+r[A]|0;d=y,y=f,f=a(u),u=p,p=x}this._a=p+this._a|0,this._b=u+this._b|0,this._c=f+this._c|0,this._d=y+this._d|0,this._e=d+this._e|0},i.prototype._hash=function(){var c=t.allocUnsafe(20);return c.writeInt32BE(this._a|0,0),c.writeInt32BE(this._b|0,4),c.writeInt32BE(this._c|0,8),c.writeInt32BE(this._d|0,12),c.writeInt32BE(this._e|0,16),c},Xt=i,Xt}var er,_n;function Is(){if(_n)return er;_n=1;var h=Be(),e=je(),t=Ie().Buffer,r=[1518500249,1859775393,-1894007588,-899497514],n=new Array(80);function i(){this.init(),this._w=n,e.call(this,64,56)}h(i,e),i.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function s(l){return l<<1|l>>>31}function a(l){return l<<5|l>>>27}function o(l){return l<<30|l>>>2}function c(l,p,u,f){return l===0?p&u|~p&f:l===2?p&u|p&f|u&f:p^u^f}return i.prototype._update=function(l){for(var p=this._w,u=this._a|0,f=this._b|0,y=this._c|0,d=this._d|0,m=this._e|0,b=0;b<16;++b)p[b]=l.readInt32BE(b*4);for(;b<80;++b)p[b]=s(p[b-3]^p[b-8]^p[b-14]^p[b-16]);for(var A=0;A<80;++A){var x=~~(A/20),I=a(u)+c(x,f,y,d)+m+p[A]+r[x]|0;m=d,d=y,y=o(f),f=u,u=I}this._a=u+this._a|0,this._b=f+this._b|0,this._c=y+this._c|0,this._d=d+this._d|0,this._e=m+this._e|0},i.prototype._hash=function(){var l=t.allocUnsafe(20);return l.writeInt32BE(this._a|0,0),l.writeInt32BE(this._b|0,4),l.writeInt32BE(this._c|0,8),l.writeInt32BE(this._d|0,12),l.writeInt32BE(this._e|0,16),l},er=i,er}var tr,Rn;function ci(){if(Rn)return tr;Rn=1;var h=Be(),e=je(),t=Ie().Buffer,r=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=new Array(64);function i(){this.init(),this._w=n,e.call(this,64,56)}h(i,e),i.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function s(u,f,y){return y^u&(f^y)}function a(u,f,y){return u&f|y&(u|f)}function o(u){return(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10)}function c(u){return(u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7)}function l(u){return(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3}function p(u){return(u>>>17|u<<15)^(u>>>19|u<<13)^u>>>10}return i.prototype._update=function(u){for(var f=this._w,y=this._a|0,d=this._b|0,m=this._c|0,b=this._d|0,A=this._e|0,x=this._f|0,I=this._g|0,F=this._h|0,L=0;L<16;++L)f[L]=u.readInt32BE(L*4);for(;L<64;++L)f[L]=p(f[L-2])+f[L-7]+l(f[L-15])+f[L-16]|0;for(var Q=0;Q<64;++Q){var se=F+c(A)+s(A,x,I)+r[Q]+f[Q]|0,te=o(y)+a(y,d,m)|0;F=I,I=x,x=A,A=b+se|0,b=m,m=d,d=y,y=se+te|0}this._a=y+this._a|0,this._b=d+this._b|0,this._c=m+this._c|0,this._d=b+this._d|0,this._e=A+this._e|0,this._f=x+this._f|0,this._g=I+this._g|0,this._h=F+this._h|0},i.prototype._hash=function(){var u=t.allocUnsafe(32);return u.writeInt32BE(this._a,0),u.writeInt32BE(this._b,4),u.writeInt32BE(this._c,8),u.writeInt32BE(this._d,12),u.writeInt32BE(this._e,16),u.writeInt32BE(this._f,20),u.writeInt32BE(this._g,24),u.writeInt32BE(this._h,28),u},tr=i,tr}var rr,In;function $s(){if(In)return rr;In=1;var h=Be(),e=ci(),t=je(),r=Ie().Buffer,n=new Array(64);function i(){this.init(),this._w=n,t.call(this,64,56)}return h(i,e),i.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},i.prototype._hash=function(){var s=r.allocUnsafe(28);return s.writeInt32BE(this._a,0),s.writeInt32BE(this._b,4),s.writeInt32BE(this._c,8),s.writeInt32BE(this._d,12),s.writeInt32BE(this._e,16),s.writeInt32BE(this._f,20),s.writeInt32BE(this._g,24),s},rr=i,rr}var nr,$n;function li(){if($n)return nr;$n=1;var h=Be(),e=je(),t=Ie().Buffer,r=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],n=new Array(160);function i(){this.init(),this._w=n,e.call(this,128,112)}h(i,e),i.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function s(d,m,b){return b^d&(m^b)}function a(d,m,b){return d&m|b&(d|m)}function o(d,m){return(d>>>28|m<<4)^(m>>>2|d<<30)^(m>>>7|d<<25)}function c(d,m){return(d>>>14|m<<18)^(d>>>18|m<<14)^(m>>>9|d<<23)}function l(d,m){return(d>>>1|m<<31)^(d>>>8|m<<24)^d>>>7}function p(d,m){return(d>>>1|m<<31)^(d>>>8|m<<24)^(d>>>7|m<<25)}function u(d,m){return(d>>>19|m<<13)^(m>>>29|d<<3)^d>>>6}function f(d,m){return(d>>>19|m<<13)^(m>>>29|d<<3)^(d>>>6|m<<26)}function y(d,m){return d>>>0<m>>>0?1:0}return i.prototype._update=function(d){for(var m=this._w,b=this._ah|0,A=this._bh|0,x=this._ch|0,I=this._dh|0,F=this._eh|0,L=this._fh|0,Q=this._gh|0,se=this._hh|0,te=this._al|0,k=this._bl|0,M=this._cl|0,U=this._dl|0,H=this._el|0,P=this._fl|0,T=this._gl|0,O=this._hl|0,w=0;w<32;w+=2)m[w]=d.readInt32BE(w*4),m[w+1]=d.readInt32BE(w*4+4);for(;w<160;w+=2){var C=m[w-30],B=m[w-30+1],V=l(C,B),G=p(B,C);C=m[w-4],B=m[w-4+1];var K=u(C,B),_=f(B,C),X=m[w-14],me=m[w-14+1],ne=m[w-32],Me=m[w-32+1],pe=G+me|0,ie=V+X+y(pe,G)|0;pe=pe+_|0,ie=ie+K+y(pe,_)|0,pe=pe+Me|0,ie=ie+ne+y(pe,Me)|0,m[w]=ie,m[w+1]=pe}for(var J=0;J<160;J+=2){ie=m[J],pe=m[J+1];var Y=a(b,A,x),re=a(te,k,M),ae=o(b,te),xe=o(te,b),Ae=c(F,H),de=c(H,F),Pe=r[J],Se=r[J+1],Ne=s(F,L,Q),we=s(H,P,T),ue=O+de|0,be=se+Ae+y(ue,O)|0;ue=ue+we|0,be=be+Ne+y(ue,we)|0,ue=ue+Se|0,be=be+Pe+y(ue,Se)|0,ue=ue+pe|0,be=be+ie+y(ue,pe)|0;var _e=xe+re|0,Re=ae+Y+y(_e,xe)|0;se=Q,O=T,Q=L,T=P,L=F,P=H,H=U+ue|0,F=I+be+y(H,U)|0,I=x,U=M,x=A,M=k,A=b,k=te,te=ue+_e|0,b=be+Re+y(te,ue)|0}this._al=this._al+te|0,this._bl=this._bl+k|0,this._cl=this._cl+M|0,this._dl=this._dl+U|0,this._el=this._el+H|0,this._fl=this._fl+P|0,this._gl=this._gl+T|0,this._hl=this._hl+O|0,this._ah=this._ah+b+y(this._al,te)|0,this._bh=this._bh+A+y(this._bl,k)|0,this._ch=this._ch+x+y(this._cl,M)|0,this._dh=this._dh+I+y(this._dl,U)|0,this._eh=this._eh+F+y(this._el,H)|0,this._fh=this._fh+L+y(this._fl,P)|0,this._gh=this._gh+Q+y(this._gl,T)|0,this._hh=this._hh+se+y(this._hl,O)|0},i.prototype._hash=function(){var d=t.allocUnsafe(64);function m(b,A,x){d.writeInt32BE(b,x),d.writeInt32BE(A,x+4)}return m(this._ah,this._al,0),m(this._bh,this._bl,8),m(this._ch,this._cl,16),m(this._dh,this._dl,24),m(this._eh,this._el,32),m(this._fh,this._fl,40),m(this._gh,this._gl,48),m(this._hh,this._hl,56),d},nr=i,nr}var ir,Bn;function Bs(){if(Bn)return ir;Bn=1;var h=Be(),e=li(),t=je(),r=Ie().Buffer,n=new Array(160);function i(){this.init(),this._w=n,t.call(this,128,112)}return h(i,e),i.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},i.prototype._hash=function(){var s=r.allocUnsafe(48);function a(o,c,l){s.writeInt32BE(o,l),s.writeInt32BE(c,l+4)}return a(this._ah,this._al,0),a(this._bh,this._bl,8),a(this._ch,this._cl,16),a(this._dh,this._dl,24),a(this._eh,this._el,32),a(this._fh,this._fl,40),s},ir=i,ir}var jn;function js(){return jn||(jn=1,(function(h){h.exports=function(t){var r=t.toLowerCase(),n=h.exports[r];if(!n)throw new Error(r+" is not supported (we accept pull requests)");return new n},h.exports.sha=Rs(),h.exports.sha1=Is(),h.exports.sha224=$s(),h.exports.sha256=ci(),h.exports.sha384=Bs(),h.exports.sha512=li()})(tt)),tt.exports}var qs=js();const Ds=Kn(qs);function Fs(h,e={}){const{segmentLength:t=4,separator:r="__",termLength:n=2}=e;return h.split(r).reduce((a,o)=>{const c=o.replace(/([a-z\xE0-\xFF])([A-Z\xC0-\xDF])/g,"$1 $2").split(" "),l=c.length>1?n:t,p=c.map(u=>u.substr(0,l)).join("");return a.push(p),a},[]).join(r)}function ks(h,e={}){const t=Ds("sha1");t.update(h,"utf8");const r=t.digest("hex");return e.length&&e.length>0?r.slice(0,e.length):r}class Ls{static isGreaterOrEqual(e,t){if(!e)return!1;const r=qn(e),n=qn(t);for(let i=0;i<r.length&&i<n.length;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!0}}function qn(h){return h.split(".").map(e=>parseInt(e,10))}class ${static isSQLiteFamily(e){return["sqlite","cordova","react-native","nativescript","sqljs","expo","better-sqlite3","capacitor"].includes(e.options.type)}static isMySQLFamily(e){return["mysql","mariadb"].includes(e.options.type)}static isReleaseVersionOrGreater(e,t){return Ls.isGreaterOrEqual(e.version,t)}static isPostgresFamily(e){return["postgres","aurora-postgres","cockroachdb"].includes(e.options.type)}static buildDriverOptions(e,t){if(e.url){const r=this.parseConnectionUrl(e.url);t&&t.useSid&&r.database&&(r.sid=r.database);for(const n of Object.keys(r))typeof r[n]>"u"&&delete r[n];return Object.assign({},e,r)}return Object.assign({},e)}static buildMongoDBDriverOptions(e,t){if(e.url){const r=this.parseMongoDBConnectionUrl(e.url);t&&t.useSid&&r.database&&(r.sid=r.database);for(const n of Object.keys(r))typeof r[n]>"u"&&delete r[n];return Object.assign({},e,r)}return Object.assign({},e)}static buildAlias({maxAliasLength:e},t,...r){const n=t&&t.joiner?t.joiner:"_",i=r.length===1?r[0]:r.join(n);if(e&&e>0&&i.length>e){if(t&&t.shorten===!0){const s=Fs(i);if(s.length<e)return s}return ks(i,{length:e})}return i}static buildColumnAlias({maxAliasLength:e},t,...r){return typeof t=="string"?(r.unshift(t),t={shorten:!1,joiner:"_"}):t=Object.assign({shorten:!1,joiner:"_"},t),this.buildAlias({maxAliasLength:e},t,...r)}static parseConnectionUrl(e){const t=e.split(":")[0],r=e.indexOf("//"),n=e.substr(r+2),i=n.indexOf("/"),s=i!==-1?n.substr(0,i):n;let a=i!==-1?n.substr(i+1):void 0;a&&a.indexOf("?")!==-1&&(a=a.substr(0,a.indexOf("?")));const o=s.lastIndexOf("@"),c=s.substr(0,o),l=s.substr(o+1);let p=c,u="";const f=c.indexOf(":");f!==-1&&(p=c.substr(0,f),u=c.substr(f+1));const[y,d]=l.split(":");return{type:t,host:y,username:decodeURIComponent(p),password:decodeURIComponent(u),port:d?parseInt(d):void 0,database:a||void 0}}static parseMongoDBConnectionUrl(e){const t=e.split(":")[0],r=e.indexOf("//"),n=e.substr(r+2),i=n.indexOf("/"),s=i!==-1?n.substr(0,i):n;let a=i!==-1?n.substr(i+1):void 0,o="",c,l,p,u;const f={};if(a&&a.indexOf("?")!==-1){o=a.substr(a.indexOf("?")+1,a.length);const F=o.split("&");let L,Q;F.forEach(se=>{L=se.split("=")[0],Q=se.split("=")[1],f[L]=Q}),u=f.replicaSet,a=a.substr(0,a.indexOf("?"))}const y=s.lastIndexOf("@"),d=s.substr(0,y),m=s.substr(y+1);let b=d,A="";const x=d.indexOf(":");x!==-1&&(b=d.substr(0,x),A=d.substr(x+1)),u?p=m:[c,l]=m.split(":");const I={type:t,host:c,hostReplicaSet:p,username:decodeURIComponent(b),password:decodeURIComponent(A),port:l?parseInt(l):void 0,database:a||void 0};for(const[F,L]of Object.entries(f))I[F]=L;return I}}class pi{constructor(e,t,r){this.connection=e,this.queryExpressionMap=t,this.isSelectedEvaluated=!1,this.relationEvaluated=!1,r&&fe.assign(this,r)}get isMany(){return this.isMappingMany!==void 0?this.isMappingMany:this.relation?this.relation.isManyToMany||this.relation.isOneToMany:!1}get isSelected(){if(!this.isSelectedEvaluated){const e=()=>{for(const t of this.queryExpressionMap.selects)if(t.selection===this.alias.name||this.metadata&&this.metadata.columns.find(r=>t.selection===this.alias.name+"."+r.propertyPath))return!0;return!1};this.isSelectedCache=e(),this.isSelectedEvaluated=!0}return this.isSelectedCache}get tablePath(){return this.metadata?this.metadata.tablePath:this.entityOrProperty}get parentAlias(){if(Te.isAliasProperty(this.entityOrProperty))return this.entityOrProperty.substr(0,this.entityOrProperty.indexOf("."))}get relationPropertyPath(){if(Te.isAliasProperty(this.entityOrProperty))return this.entityOrProperty.substr(this.entityOrProperty.indexOf(".")+1)}get relation(){if(!this.relationEvaluated){const e=()=>{if(!Te.isAliasProperty(this.entityOrProperty))return;const t=this.queryExpressionMap.findAliasByName(this.parentAlias);let r=t.metadata.findRelationWithPropertyPath(this.relationPropertyPath);if(r||t.metadata.parentEntityMetadata&&(r=t.metadata.parentEntityMetadata.findRelationWithPropertyPath(this.relationPropertyPath),r))return r;throw new S(`Relation with property path ${this.relationPropertyPath} in entity was not found.`)};this.relationCache=e.bind(this)(),this.relationEvaluated=!0}return this.relationCache}get metadata(){if(this.relation)return this.relation.inverseEntityMetadata;if(this.connection.hasMetadata(this.entityOrProperty))return this.connection.getMetadata(this.entityOrProperty);if(this.mapAsEntity&&this.connection.hasMetadata(this.mapAsEntity))return this.connection.getMetadata(this.mapAsEntity)}get junctionAlias(){if(!this.relation)throw new S("Cannot get junction table for join without relation.");if(typeof this.entityOrProperty!="string")throw new S("Junction property is not defined.");const e=this.entityOrProperty.substr(0,this.entityOrProperty.indexOf("."));return this.relation.isOwning?$.buildAlias(this.connection.driver,void 0,e,this.alias.name):$.buildAlias(this.connection.driver,void 0,this.alias.name,e)}get mapToPropertyParentAlias(){if(this.mapToProperty)return this.mapToProperty.split(".")[0]}get mapToPropertyPropertyName(){if(this.mapToProperty)return this.mapToProperty.split(".")[1]}}class yr{constructor(e,t){this.queryExpressionMap=e,this.disableMixedMap=!1,fe.assign(this,t||{})}get joinInverseSideMetadata(){return this.relation.inverseEntityMetadata}get parentAlias(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value must be a string representation of alias property");return this.relationName.substr(0,this.relationName.indexOf("."))}get relationPropertyPath(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value must be a string representation of alias property");return this.relationName.substr(this.relationName.indexOf(".")+1)}get relation(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value must be a string representation of alias property");const t=this.queryExpressionMap.findAliasByName(this.parentAlias).metadata.findRelationWithPropertyPath(this.relationPropertyPath);if(!t)throw new S(`Relation with property path ${this.relationPropertyPath} in entity was not found.`);return t}get junctionAlias(){const[e,t]=this.relationName.split(".");return e+"_"+t+"_rid"}get junctionMetadata(){return this.relation.junctionEntityMetadata}get mapToPropertyParentAlias(){return this.mapToProperty.substr(0,this.mapToProperty.indexOf("."))}get mapToPropertyPropertyPath(){return this.mapToProperty.substr(this.mapToProperty.indexOf(".")+1)}}class mr{constructor(e,t){this.expressionMap=e,fe.assign(this,t||{})}get joinInverseSideMetadata(){return this.relation.inverseEntityMetadata}get parentAlias(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value must be a string representation of alias property");return this.relationName.split(".")[0]}get relationProperty(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value is a string representation of alias property");return this.relationName.split(".")[1]}get junctionAlias(){const[e,t]=this.relationName.split(".");return e+"_"+t+"_rc"}get relation(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value is a string representation of alias property");const[e,t]=this.relationName.split("."),n=this.expressionMap.findAliasByName(e).metadata.findRelationWithPropertyPath(t);if(!n)throw new S(`Relation with property path ${t} in entity was not found.`);return n}get metadata(){if(!Te.isAliasProperty(this.relationName))throw new S("Given value is a string representation of alias property");const e=this.relationName.split(".")[0];return this.expressionMap.findAliasByName(e).metadata}get mapToPropertyPropertyName(){return this.mapToProperty.split(".")[1]}}class gr{constructor(e){this.connection=e,this.relationLoadStrategy="join",this.queryEntity=!1,this.aliases=[],this.queryType="select",this.selects=[],this.maxExecutionTime=0,this.selectDistinct=!1,this.selectDistinctOn=[],this.extraReturningColumns=[],this.onConflict="",this.onIgnore=!1,this.joinAttributes=[],this.relationIdAttributes=[],this.relationCountAttributes=[],this.wheres=[],this.havings=[],this.orderBys={},this.groupBys=[],this.withDeleted=!1,this.parameters={},this.disableEscaping=!0,this.enableRelationIdValues=!1,this.extraAppendedAndWhereCondition="",this.subQuery=!1,this.aliasNamePrefixingEnabled=!0,this.options=[],this.insertColumns=[],this.whereEntities=[],this.updateEntity=!0,this.callListeners=!0,this.useTransaction=!1,this.nativeParameters={},this.locallyGenerated={},this.commonTableExpressions=[],e.options.relationLoadStrategy&&(this.relationLoadStrategy=e.options.relationLoadStrategy),this.timeTravel=e.options?.timeTravelQueries||!1}get allOrderBys(){if(!Object.keys(this.orderBys).length&&this.mainAlias.hasMetadata&&this.options.indexOf("disable-global-order")===-1){const e=this.mainAlias.metadata.orderBy||{};return Object.keys(e).reduce((t,r)=>(t[this.mainAlias.name+"."+r]=e[r],t),{})}return this.orderBys}setMainAlias(e){return this.mainAlias=e,e}createAlias(e){let t=e.name;!t&&e.tablePath&&(t=e.tablePath),!t&&typeof e.target=="function"&&(t=e.target.name),!t&&typeof e.target=="string"&&(t=e.target);const r=new Sr;return r.type=e.type,t&&(r.name=t),e.metadata&&(r.metadata=e.metadata),e.target&&!r.hasMetadata&&(r.metadata=this.connection.getMetadata(e.target)),e.tablePath&&(r.tablePath=e.tablePath),e.subQuery&&(r.subQuery=e.subQuery),this.aliases.push(r),r}findAliasByName(e){const t=this.aliases.find(r=>r.name===e);if(!t)throw new S(`"${e}" alias was not found. Maybe you forgot to join it?`);return t}findColumnByAliasExpression(e){const[t,r]=e.split(".");return this.findAliasByName(t).metadata.findColumnWithPropertyName(r)}get relationMetadata(){if(!this.mainAlias)throw new S("Entity to work with is not specified!");const e=this.mainAlias.metadata.findRelationWithPropertyPath(this.relationPropertyPath);if(!e)throw new S(`Relation ${this.relationPropertyPath} was not found in entity ${this.mainAlias.name}`);return e}clone(){const e=new gr(this.connection);return e.queryType=this.queryType,e.selects=this.selects.map(t=>t),e.maxExecutionTime=this.maxExecutionTime,e.selectDistinct=this.selectDistinct,e.selectDistinctOn=this.selectDistinctOn,this.aliases.forEach(t=>e.aliases.push(new Sr(t))),e.relationLoadStrategy=this.relationLoadStrategy,e.mainAlias=this.mainAlias,e.valuesSet=this.valuesSet,e.returning=this.returning,e.onConflict=this.onConflict,e.onIgnore=this.onIgnore,e.onUpdate=this.onUpdate,e.joinAttributes=this.joinAttributes.map(t=>new pi(this.connection,this,t)),e.relationIdAttributes=this.relationIdAttributes.map(t=>new yr(this,t)),e.relationCountAttributes=this.relationCountAttributes.map(t=>new mr(this,t)),e.wheres=this.wheres.map(t=>({...t})),e.havings=this.havings.map(t=>({...t})),e.orderBys=Object.assign({},this.orderBys),e.groupBys=this.groupBys.map(t=>t),e.limit=this.limit,e.offset=this.offset,e.skip=this.skip,e.take=this.take,e.useIndex=this.useIndex,e.lockMode=this.lockMode,e.onLocked=this.onLocked,e.lockVersion=this.lockVersion,e.lockTables=this.lockTables,e.withDeleted=this.withDeleted,e.parameters=Object.assign({},this.parameters),e.disableEscaping=this.disableEscaping,e.enableRelationIdValues=this.enableRelationIdValues,e.extraAppendedAndWhereCondition=this.extraAppendedAndWhereCondition,e.subQuery=this.subQuery,e.aliasNamePrefixingEnabled=this.aliasNamePrefixingEnabled,e.cache=this.cache,e.cacheId=this.cacheId,e.cacheDuration=this.cacheDuration,e.relationPropertyPath=this.relationPropertyPath,e.of=this.of,e.insertColumns=this.insertColumns,e.whereEntities=this.whereEntities,e.updateEntity=this.updateEntity,e.callListeners=this.callListeners,e.useTransaction=this.useTransaction,e.timeTravel=this.timeTravel,e.nativeParameters=Object.assign({},this.nativeParameters),e.comment=this.comment,e.commonTableExpressions=this.commonTableExpressions.map(t=>({alias:t.alias,queryBuilder:typeof t.queryBuilder=="string"?t.queryBuilder:t.queryBuilder.clone(),options:t.options})),e}}class Dn{constructor(e){this["@instanceof"]=Symbol.for("Brackets"),this.whereFactory=e}}class cr{static transformFrom(e,t){return Array.isArray(e)?e.slice().reverse().reduce((n,i)=>i.from(n),t):e.from(t)}static transformTo(e,t){return Array.isArray(e)?e.reduce((r,n)=>n.to(r),t):e.to(t)}}class Ue{constructor(e,t,r=!0,n=!1,i,s){this["@instanceof"]=Symbol.for("FindOperator"),this._type=e,this._value=t,this._useParameter=r,this._multipleParameters=n,this._getSql=i,this._objectLiteralParameters=s}get useParameter(){return oe.isFindOperator(this._value)?this._value.useParameter:this._useParameter}get multipleParameters(){return oe.isFindOperator(this._value)?this._value.multipleParameters:this._multipleParameters}get type(){return this._type}get value(){return oe.isFindOperator(this._value)?this._value.value:this._value}get objectLiteralParameters(){return oe.isFindOperator(this._value)?this._value.objectLiteralParameters:this._objectLiteralParameters}get child(){if(oe.isFindOperator(this._value))return this._value}get getSql(){return oe.isFindOperator(this._value)?this._value.getSql:this._getSql}transformValue(e){this._value instanceof Ue?this._value.transformValue(e):this._value=Array.isArray(this._value)&&this._multipleParameters?this._value.map(t=>e&&cr.transformTo(e,t)):cr.transformTo(e,this._value)}}function Us(h){return new Ue("in",h,!0,!0)}const Vs=/[.*+\-?^${}()|[\]\\]/g,Ws=h=>h.replace(Vs,"\\$&");class le{constructor(e,t){this["@instanceof"]=Symbol.for("QueryBuilder"),this.parameterIndex=0,oe.isDataSource(e)?(this.connection=e,this.queryRunner=t,this.expressionMap=new gr(this.connection)):(this.connection=e.connection,this.queryRunner=e.queryRunner,this.expressionMap=e.expressionMap.clone())}static registerQueryBuilderClass(e,t){le.queryBuilderRegistry[e]=t}get alias(){if(!this.expressionMap.mainAlias)throw new S("Main alias is not set");return this.expressionMap.mainAlias.name}select(e,t){return this.expressionMap.queryType="select",Array.isArray(e)?this.expressionMap.selects=e.map(r=>({selection:r})):e&&(this.expressionMap.selects=[{selection:e,aliasName:t}]),oe.isSelectQueryBuilder(this)?this:le.queryBuilderRegistry.SelectQueryBuilder(this)}insert(){return this.expressionMap.queryType="insert",oe.isInsertQueryBuilder(this)?this:le.queryBuilderRegistry.InsertQueryBuilder(this)}update(e,t){const r=t||e;if(e=oe.isEntitySchema(e)?e.options.name:e,typeof e=="function"||typeof e=="string"){const n=this.createFromAlias(e);this.expressionMap.setMainAlias(n)}return this.expressionMap.queryType="update",this.expressionMap.valuesSet=r,oe.isUpdateQueryBuilder(this)?this:le.queryBuilderRegistry.UpdateQueryBuilder(this)}delete(){return this.expressionMap.queryType="delete",oe.isDeleteQueryBuilder(this)?this:le.queryBuilderRegistry.DeleteQueryBuilder(this)}softDelete(){return this.expressionMap.queryType="soft-delete",oe.isSoftDeleteQueryBuilder(this)?this:le.queryBuilderRegistry.SoftDeleteQueryBuilder(this)}restore(){return this.expressionMap.queryType="restore",oe.isSoftDeleteQueryBuilder(this)?this:le.queryBuilderRegistry.SoftDeleteQueryBuilder(this)}relation(e,t){const r=arguments.length===2?e:void 0,n=arguments.length===2?t:e;if(this.expressionMap.queryType="relation",this.expressionMap.relationPropertyPath=n,r){const i=this.createFromAlias(r);this.expressionMap.setMainAlias(i)}return oe.isRelationQueryBuilder(this)?this:le.queryBuilderRegistry.RelationQueryBuilder(this)}hasRelation(e,t){const r=this.connection.getMetadata(e);return(Array.isArray(t)?t:[t]).every(i=>!!r.findRelationWithPropertyPath(i))}hasParameter(e){return this.parentQueryBuilder?.hasParameter(e)||e in this.expressionMap.parameters}setParameter(e,t){if(typeof t=="function")throw new S(`Function parameter isn't supported in the parameters. Please check "${e}" parameter.`);if(!e.match(/^([A-Za-z0-9_.]+)$/))throw new S("QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.");return this.parentQueryBuilder&&this.parentQueryBuilder.setParameter(e,t),this.expressionMap.parameters[e]=t,this}setParameters(e){for(const[t,r]of Object.entries(e))this.setParameter(t,r);return this}createParameter(e){let t;do t=`orm_param_${this.parameterIndex++}`;while(this.hasParameter(t));return this.setParameter(t,e),`:${t}`}setNativeParameters(e){return this.parentQueryBuilder&&this.parentQueryBuilder.setNativeParameters(e),Object.keys(e).forEach(t=>{this.expressionMap.nativeParameters[t]=e[t]}),this}getParameters(){const e=Object.assign({},this.expressionMap.parameters);if(this.expressionMap.mainAlias&&this.expressionMap.mainAlias.hasMetadata){const t=this.expressionMap.mainAlias.metadata;if(t.discriminatorColumn&&t.parentEntityMetadata){const r=t.childEntityMetadatas.filter(n=>n.discriminatorColumn).map(n=>n.discriminatorValue);r.push(t.discriminatorValue),e.discriminatorColumnValues=r}}return e}printSql(){const[e,t]=this.getQueryAndParameters();return this.connection.logger.logQuery(e,t),this}getSql(){return this.getQueryAndParameters()[0]}getQueryAndParameters(){const e=this.getQuery(),t=this.getParameters();return this.connection.driver.escapeQueryWithParameters(e,t,this.expressionMap.nativeParameters)}async execute(){const[e,t]=this.getQueryAndParameters(),r=this.obtainQueryRunner();try{return await r.query(e,t)}finally{r!==this.queryRunner&&await r.release()}}createQueryBuilder(e){return new this.constructor(this.connection,e??this.queryRunner)}clone(){return new this.constructor(this)}comment(e){return this.expressionMap.comment=e,this}disableEscaping(){return this.expressionMap.disableEscaping=!1,this}escape(e){return this.expressionMap.disableEscaping?this.connection.driver.escape(e):e}setQueryRunner(e){return this.queryRunner=e,this}callListeners(e){return this.expressionMap.callListeners=e,this}useTransaction(e){return this.expressionMap.useTransaction=e,this}addCommonTableExpression(e,t,r){return this.expressionMap.commonTableExpressions.push({queryBuilder:e,alias:t,options:r||{}}),this}getTableName(e){return e.split(".").map(t=>t===""?t:this.escape(t)).join(".")}getMainTableName(){if(!this.expressionMap.mainAlias)throw new S('Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.');return this.expressionMap.mainAlias.hasMetadata?this.expressionMap.mainAlias.metadata.tablePath:this.expressionMap.mainAlias.tablePath}createFromAlias(e,t){if(this.connection.hasMetadata(e)){const r=this.connection.getMetadata(e);return this.expressionMap.createAlias({type:"from",name:t,metadata:this.connection.getMetadata(e),tablePath:r.tablePath})}else{if(typeof e=="string"){const i=e.substr(0,1)==="("&&e.substr(-1)===")";return this.expressionMap.createAlias({type:"from",name:t,tablePath:i?void 0:e,subQuery:i?e:void 0})}const r=e(this.subQuery());this.setParameters(r.getParameters());const n=r.getQuery();return this.expressionMap.createAlias({type:"from",name:t,subQuery:n})}}replacePropertyNames(e){return e}replacePropertyNamesForTheWholeQuery(e){const t={};for(const i of this.expressionMap.aliases){if(!i.hasMetadata)continue;const s=this.expressionMap.aliasNamePrefixingEnabled&&i.name?`${i.name}.`:"";t[s]||(t[s]={});for(const a of i.metadata.relations)a.joinColumns.length>0&&(t[s][a.propertyPath]=a.joinColumns[0].databaseName);for(const a of i.metadata.relations){const o=[...a.joinColumns,...a.inverseJoinColumns];for(const c of o){const l=`${a.propertyPath}.${c.referencedColumn.propertyPath}`;t[s][l]=c.databaseName}}for(const a of i.metadata.columns)t[s][a.databaseName]=a.databaseName;for(const a of i.metadata.columns)t[s][a.propertyName]=a.databaseName;for(const a of i.metadata.columns)t[s][a.propertyPath]=a.databaseName}const r=Object.keys(t),n=r.map(i=>Ws(i)).join("|");return r.length>0&&(e=e.replace(new RegExp(`([ =(]|^.{0})${n?"("+n+")":""}([^ =(),]+)(?=[ =),]|.{0}$)`,"gm"),(...i)=>{let s,a,o;if(n){if(s=i[0],a=i[1],o=i[3],t[i[2]][o])return`${a}${this.escape(i[2].substring(0,i[2].length-1))}.${this.escape(t[i[2]][o])}`}else if(s=i[0],a=i[1],o=i[2],t[""][o])return`${a}${this.escape(t[""][o])}`;return s})),e}createComment(){return this.expressionMap.comment?`/* ${this.expressionMap.comment.replace(/\*\//g,"")} */ `:""}createTimeTravelQuery(){return this.expressionMap.queryType==="select"&&this.expressionMap.timeTravel?` AS OF SYSTEM TIME ${this.expressionMap.timeTravel}`:""}createWhereExpression(){const e=[],t=this.createWhereClausesExpression(this.expressionMap.wheres);if(t.length>0&&t!=="1=1"&&e.push(this.replacePropertyNames(t)),this.expressionMap.mainAlias.hasMetadata){const n=this.expressionMap.mainAlias.metadata;if(this.expressionMap.queryType==="select"&&!this.expressionMap.withDeleted&&n.deleteDateColumn){const i=this.expressionMap.aliasNamePrefixingEnabled?this.expressionMap.mainAlias.name+"."+n.deleteDateColumn.propertyName:n.deleteDateColumn.propertyName,s=`${this.replacePropertyNames(i)} IS NULL`;e.push(s)}if(n.discriminatorColumn&&n.parentEntityMetadata){const i=this.expressionMap.aliasNamePrefixingEnabled?this.expressionMap.mainAlias.name+"."+n.discriminatorColumn.databaseName:n.discriminatorColumn.databaseName,s=`${this.replacePropertyNames(i)} IN (:...discriminatorColumnValues)`;e.push(s)}}if(this.expressionMap.extraAppendedAndWhereCondition){const n=this.replacePropertyNames(this.expressionMap.extraAppendedAndWhereCondition);e.push(n)}let r="";return r+=this.createTimeTravelQuery(),e.length?e.length===1?r+=` WHERE ${e[0]}`:r+=` WHERE ( ${e.join(" ) AND ( ")} )`:r+="",r}createReturningExpression(e){const t=this.getReturningColumns(),r=this.connection.driver;if(typeof this.expressionMap.returning!="string"&&this.expressionMap.extraReturningColumns.length>0&&r.isReturningSqlSupported(e)&&t.push(...this.expressionMap.extraReturningColumns.filter(n=>t.indexOf(n)===-1)),t.length){let n=t.map(i=>{const s=this.escape(i.databaseName);return r.options.type==="mssql"?this.expressionMap.queryType==="insert"||this.expressionMap.queryType==="update"||this.expressionMap.queryType==="soft-delete"||this.expressionMap.queryType==="restore"?"INSERTED."+s:this.escape(this.getMainTableName())+"."+s:s}).join(", ");return r.options.type==="oracle"&&(n+=" INTO "+t.map(i=>this.createParameter({type:r.columnTypeToNativeParameter(i.type),dir:r.oracle.BIND_OUT})).join(", ")),r.options.type==="mssql"&&(this.expressionMap.queryType==="insert"||this.expressionMap.queryType==="update")&&(n+=" INTO @OutputTable"),n}else if(typeof this.expressionMap.returning=="string")return this.expressionMap.returning;return""}getReturningColumns(){const e=[];return Array.isArray(this.expressionMap.returning)&&this.expressionMap.returning.forEach(t=>{this.expressionMap.mainAlias.hasMetadata&&e.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(t))}),e}createWhereClausesExpression(e){return e.map((t,r)=>{const n=this.createWhereConditionExpression(t.condition);switch(t.type){case"and":return(r>0?"AND ":"")+`${this.connection.options.isolateWhereStatements?"(":""}${n}${this.connection.options.isolateWhereStatements?")":""}`;case"or":return(r>0?"OR ":"")+`${this.connection.options.isolateWhereStatements?"(":""}${n}${this.connection.options.isolateWhereStatements?")":""}`}return n}).join(" ").trim()}createWhereConditionExpression(e,t=!1){if(typeof e=="string")return e;if(Array.isArray(e))return e.length===0?"1=1":e.length===1&&!t?this.createWhereClausesExpression(e):"("+this.createWhereClausesExpression(e)+")";const{driver:r}=this.connection;switch(e.operator){case"lessThan":return`${e.parameters[0]} < ${e.parameters[1]}`;case"lessThanOrEqual":return`${e.parameters[0]} <= ${e.parameters[1]}`;case"arrayContains":return`${e.parameters[0]} @> ${e.parameters[1]}`;case"jsonContains":return`${e.parameters[0]} ::jsonb @> ${e.parameters[1]}`;case"arrayContainedBy":return`${e.parameters[0]} <@ ${e.parameters[1]}`;case"arrayOverlap":return`${e.parameters[0]} && ${e.parameters[1]}`;case"moreThan":return`${e.parameters[0]} > ${e.parameters[1]}`;case"moreThanOrEqual":return`${e.parameters[0]} >= ${e.parameters[1]}`;case"notEqual":return`${e.parameters[0]} != ${e.parameters[1]}`;case"equal":return`${e.parameters[0]} = ${e.parameters[1]}`;case"ilike":return r.options.type==="postgres"||r.options.type==="cockroachdb"?`${e.parameters[0]} ILIKE ${e.parameters[1]}`:`UPPER(${e.parameters[0]}) LIKE UPPER(${e.parameters[1]})`;case"like":return`${e.parameters[0]} LIKE ${e.parameters[1]}`;case"between":return`${e.parameters[0]} BETWEEN ${e.parameters[1]} AND ${e.parameters[2]}`;case"in":return e.parameters.length<=1?"0=1":`${e.parameters[0]} IN (${e.parameters.slice(1).join(", ")})`;case"any":return r.options.type==="cockroachdb"?`${e.parameters[0]}::STRING = ANY(${e.parameters[1]}::STRING[])`:`${e.parameters[0]} = ANY(${e.parameters[1]})`;case"isNull":return`${e.parameters[0]} IS NULL`;case"not":return`NOT(${this.createWhereConditionExpression(e.condition)})`;case"brackets":return`${this.createWhereConditionExpression(e.condition,!0)}`;case"and":return"("+e.parameters.join(" AND ")+")";case"or":return"("+e.parameters.join(" OR ")+")"}throw new TypeError(`Unsupported FindOperator ${Ue.constructor.name}`)}createCteExpression(){if(!this.hasCommonTableExpressions())return"";const e=this.connection.driver.cteCapabilities.requiresRecursiveHint;return"WITH "+this.expressionMap.commonTableExpressions.map(r=>{let n=typeof r.queryBuilder=="string"?r.queryBuilder:"";if(typeof r.queryBuilder!="string"){if(r.queryBuilder.hasCommonTableExpressions())throw new S(`Nested CTEs aren't supported (CTE: ${r.alias})`);if(n=r.queryBuilder.getQuery(),!this.connection.driver.cteCapabilities.writable&&!oe.isSelectQueryBuilder(r.queryBuilder))throw new S(`Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${r.alias})`);this.setParameters(r.queryBuilder.getParameters())}let i=this.escape(r.alias);if(r.options.columnNames){const o=r.options.columnNames.map(c=>this.escape(c));if(oe.isSelectQueryBuilder(r.queryBuilder)&&r.queryBuilder.expressionMap.selects.length&&r.options.columnNames.length!==r.queryBuilder.expressionMap.selects.length)throw new S(`cte.options.columnNames length (${r.options.columnNames.length}) doesn't match subquery select list length ${r.queryBuilder.expressionMap.selects.length} (CTE: ${r.alias})`);i+=`(${o.join(", ")})`}const s=r.options.recursive&&e?"RECURSIVE":"";let a="";return this.connection.driver.cteCapabilities.materializedHint&&r.options.materialized!==void 0&&(a=r.options.materialized?"MATERIALIZED":"NOT MATERIALIZED"),[s,i,"AS",a,`(${n})`].filter(Boolean).join(" ")}).join(", ")+" "}getWhereInIdsCondition(e){const t=this.expressionMap.mainAlias.metadata,r=(Array.isArray(e)?e:[e]).map(n=>t.ensureEntityIdMap(n));if(!t.hasMultiplePrimaryKeys){const n=t.primaryColumns[0];if(!n.transformer&&!n.relationMetadata&&!n.embeddedMetadata)return{[n.propertyName]:Us(r.map(i=>n.getEntityValue(i,!1)))}}return new Dn(n=>{for(const i of r)n.orWhere(new Dn(s=>s.where(i)))})}getExistsCondition(e){const t=e.clone().orderBy().groupBy().offset(void 0).limit(void 0).skip(void 0).take(void 0).select("1").setOption("disable-global-order");return[`EXISTS (${t.getQuery()})`,t.getParameters()]}findColumnsForPropertyPath(e){let t=this.expressionMap.mainAlias;const r=[],n=e.split(".");for(;n.length>1;){const a=n[0];if(!t?.hasMetadata)break;if(t.metadata.hasEmbeddedWithPropertyPath(a)){n.unshift(`${n.shift()}.${n.shift()}`);continue}if(t.metadata.hasRelationWithPropertyPath(a)){const o=this.expressionMap.joinAttributes.find(c=>c.relationPropertyPath===a);if(!o?.alias){const c=r.length>0?`${r.join(".")}.${a}`:a;throw new Error(`Cannot find alias for relation at ${c}`)}t=o.alias,r.push(...a.split(".")),n.shift();continue}break}if(!t)throw new Error(`Cannot find alias for property ${e}`);const i=n.join("."),s=t.metadata.findColumnsWithPropertyPath(i);if(!s.length)throw new Ce(e,t.metadata);return[t,r,s]}createPropertyPath(e,t,r=""){const n=[];for(const i of Object.keys(t)){const s=r?`${r}.${i}`:i;if(t[i]===null||typeof t[i]!="object"||oe.isFindOperator(t[i])){n.push(s);continue}if(e.hasEmbeddedWithPropertyPath(s)){const a=this.createPropertyPath(e,t[i],s);n.push(...a);continue}if(e.hasRelationWithPropertyPath(s)){const a=e.findRelationWithPropertyPath(s);if(a.relationType==="one-to-one"||a.relationType==="many-to-one"){const p=a.joinColumns.map(f=>f.referencedColumn).filter(f=>!!f);if(p.length>0&&p.every(f=>f.getEntityValue(t[i],!1))){n.push(s);continue}}if(a.relationType==="one-to-many"||a.relationType==="many-to-many")throw new Error(`Cannot query across ${a.relationType} for property ${s}`);const o=a.inverseEntityMetadata.primaryColumns;if(o.length>0&&o.every(p=>p.getEntityValue(t[i],!1))){const p=o.map(u=>`${s}.${u.propertyPath}`);n.push(...p);continue}const l=this.createPropertyPath(a.inverseEntityMetadata,t[i]).map(p=>`${s}.${p}`);n.push(...l);continue}n.push(s)}return n}*getPredicates(e){if(this.expressionMap.mainAlias.hasMetadata){const t=this.createPropertyPath(this.expressionMap.mainAlias.metadata,e);for(const r of t){const[n,i,s]=this.findColumnsForPropertyPath(r);for(const a of s){let o=e;for(const p of i){if(!o||!(p in o)){o={};break}o=o[p]}const c=this.expressionMap.aliasNamePrefixingEnabled?`${n.name}.${a.propertyPath}`:a.propertyPath,l=a.getEntityValue(o,!0);yield[c,l]}}}else for(const t of Object.keys(e)){const r=e[t];yield[this.expressionMap.aliasNamePrefixingEnabled?`${this.alias}.${t}`:t,r]}}getWherePredicateCondition(e,t){if(oe.isFindOperator(t)){const r=[];if(t.useParameter)if(t.objectLiteralParameters)this.setParameters(t.objectLiteralParameters);else if(t.multipleParameters)for(const n of t.value)r.push(this.createParameter(n));else r.push(this.createParameter(t.value));if(t.type==="raw")return t.getSql?t.getSql(e):{operator:"equal",parameters:[e,t.value]};if(t.type==="not")return t.child?{operator:t.type,condition:this.getWherePredicateCondition(e,t.child)}:{operator:"notEqual",parameters:[e,...r]};if(t.type==="and"){const n=t.value;return{operator:t.type,parameters:n.map(i=>this.createWhereConditionExpression(this.getWherePredicateCondition(e,i)))}}else if(t.type==="or"){const n=t.value;return{operator:t.type,parameters:n.map(i=>this.createWhereConditionExpression(this.getWherePredicateCondition(e,i)))}}else return{operator:t.type,parameters:[e,...r]}}else if(t===null){const r=this.connection.options.invalidWhereValuesBehavior?.null||"ignore";if(r==="sql-null")return{operator:"isNull",parameters:[e]};if(r==="throw")throw new S(`Null value encountered in property '${e}' of a where condition. To match with SQL NULL, the IsNull() operator must be used. Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`)}else if(t===void 0&&(this.connection.options.invalidWhereValuesBehavior?.undefined||"ignore")==="throw")throw new S(`Undefined value encountered in property '${e}' of a where condition. Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`);return{operator:"equal",parameters:[e,this.createParameter(t)]}}getWhereCondition(e){if(typeof e=="string")return e;if(oe.isBrackets(e)){const n=this.createQueryBuilder();return n.parentQueryBuilder=this,n.expressionMap.mainAlias=this.expressionMap.mainAlias,n.expressionMap.aliasNamePrefixingEnabled=this.expressionMap.aliasNamePrefixingEnabled,n.expressionMap.parameters=this.expressionMap.parameters,n.expressionMap.nativeParameters=this.expressionMap.nativeParameters,n.expressionMap.wheres=[],e.whereFactory(n),{operator:oe.isNotBrackets(e)?"not":"brackets",condition:n.expressionMap.wheres}}if(typeof e=="function")return e(this);const t=Array.isArray(e)?e:[e],r=[];for(const n of t){const i=[];for(const[s,a]of this.getPredicates(n))i.push({type:"and",condition:this.getWherePredicateCondition(s,a)});r.push({type:"or",condition:i})}return r.length===1?r[0].condition:r}obtainQueryRunner(){return this.queryRunner||this.connection.createQueryRunner()}hasCommonTableExpressions(){return this.expressionMap.commonTableExpressions.length>0}}le.queryBuilderRegistry={};class Qs{static from(e){const t=new this;return t.raw=e.records,t.affected=e.affected,t}}class Gs extends le{constructor(e,t){super(e,t),this["@instanceof"]=Symbol.for("DeleteQueryBuilder"),this.expressionMap.aliasNamePrefixingEnabled=!1}getQuery(){let e=this.createComment();return e+=this.createCteExpression(),e+=this.createDeleteExpression(),this.replacePropertyNamesForTheWholeQuery(e.trim())}async execute(){const[e,t]=this.getQueryAndParameters(),r=this.obtainQueryRunner();let n=!1;try{this.expressionMap.useTransaction===!0&&r.isTransactionActive===!1&&(await r.startTransaction(),n=!0),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&await r.broadcaster.broadcast("BeforeRemove",this.expressionMap.mainAlias.metadata);const i=await r.query(e,t,!0),s=Qs.from(i);return this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&await r.broadcaster.broadcast("AfterRemove",this.expressionMap.mainAlias.metadata),n&&await r.commitTransaction(),s}catch(i){if(n)try{await r.rollbackTransaction()}catch{}throw i}finally{r!==this.queryRunner&&await r.release()}}from(e,t){e=oe.isEntitySchema(e)?e.options.name:e;const r=this.createFromAlias(e,t);return this.expressionMap.setMainAlias(r),this}where(e,t){this.expressionMap.wheres=[];const r=this.getWhereCondition(e);return r&&(this.expressionMap.wheres=[{type:"simple",condition:r}]),t&&this.setParameters(t),this}andWhere(e,t){return this.expressionMap.wheres.push({type:"and",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}orWhere(e,t){return this.expressionMap.wheres.push({type:"or",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}whereInIds(e){return this.where(this.getWhereInIdsCondition(e))}andWhereInIds(e){return this.andWhere(this.getWhereInIdsCondition(e))}orWhereInIds(e){return this.orWhere(this.getWhereInIdsCondition(e))}output(e){return this.returning(e)}returning(e){if(!this.connection.driver.isReturningSqlSupported("delete"))throw new Ye;return this.expressionMap.returning=e,this}createDeleteExpression(){const e=this.getTableName(this.getMainTableName()),t=this.createWhereExpression(),r=this.createReturningExpression("delete");return r===""?`DELETE FROM ${e}${t}`:this.connection.driver.options.type==="mssql"?`DELETE FROM ${e} OUTPUT ${r}${t}`:this.connection.driver.options.type==="spanner"?`DELETE FROM ${e}${t} THEN RETURN ${r}`:`DELETE FROM ${e}${t} RETURNING ${r}`}}const ve=[];for(let h=0;h<256;++h)ve.push((h+256).toString(16).slice(1));function Js(h,e=0){return(ve[h[e+0]]+ve[h[e+1]]+ve[h[e+2]]+ve[h[e+3]]+"-"+ve[h[e+4]]+ve[h[e+5]]+"-"+ve[h[e+6]]+ve[h[e+7]]+"-"+ve[h[e+8]]+ve[h[e+9]]+"-"+ve[h[e+10]]+ve[h[e+11]]+ve[h[e+12]]+ve[h[e+13]]+ve[h[e+14]]+ve[h[e+15]]).toLowerCase()}let sr;const Hs=new Uint8Array(16);function Ys(){if(!sr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");sr=crypto.getRandomValues.bind(crypto)}return sr(Hs)}const Ks=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Fn={randomUUID:Ks};function zs(h,e,t){if(Fn.randomUUID&&!h)return Fn.randomUUID();h=h||{};const r=h.random??h.rng?.()??Ys();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Js(r)}class kn{constructor(){this.count=0,this.promises=[]}async wait(){return this.promises.length>0&&await Promise.all(this.promises),this}}class Ln{constructor(){this.identifiers=[],this.generatedMaps=[]}static from(e){const t=new this;return t.raw=e.raw,t}}class br{constructor(e,t){this.queryRunner=e,this.expressionMap=t}async update(e,t){const r=this.expressionMap.mainAlias.metadata;await Promise.all(t.map(async(n,i)=>{if(this.queryRunner.connection.driver.isReturningSqlSupported("update")){this.queryRunner.connection.driver.options.type==="oracle"&&Array.isArray(e.raw)&&this.expressionMap.extraReturningColumns.length>0&&(e.raw=e.raw.reduce((o,c,l)=>(o[this.expressionMap.extraReturningColumns[l].databaseName]=c[0],o),{}));const s=Array.isArray(e.raw)?e.raw[i]:e.raw,a=this.queryRunner.connection.driver.createGeneratedMap(r,s);a&&(this.queryRunner.manager.merge(r.target,n,a),e.generatedMaps.push(a))}else{const s=this.expressionMap.extraReturningColumns;if(s.length>0){const a=this.expressionMap.mainAlias.metadata.getEntityIdMap(n);if(!a)throw new S("Cannot update entity because entity id is not set in the entity.");const o=await this.queryRunner.manager.createQueryBuilder().select(r.primaryColumns.map(c=>r.targetName+"."+c.propertyPath)).addSelect(s.map(c=>r.targetName+"."+c.propertyPath)).from(r.target,r.targetName).where(a).withDeleted().setOption("create-pojo").getOne();o&&(this.queryRunner.manager.merge(r.target,n,o),e.generatedMaps.push(o))}}}))}async insert(e,t){const r=this.expressionMap.mainAlias.metadata;let n=r.getInsertionReturningColumns();const i=this.queryRunner.connection.driver.isReturningSqlSupported("insert");n=n.filter(a=>a.isGenerated?i===!0:!0);const s=t.map((a,o)=>{Array.isArray(e.raw)&&this.expressionMap.extraReturningColumns.length>0&&(this.queryRunner.connection.driver.options.type==="oracle"?e.raw=e.raw.reduce((p,u,f)=>(p[this.expressionMap.extraReturningColumns[f].databaseName]=u[0],p),{}):this.queryRunner.connection.driver.options.type==="spanner"&&(e.raw=e.raw[0]));const c=Array.isArray(e.raw)?e.raw[o]:e.raw,l=this.queryRunner.connection.driver.createGeneratedMap(r,c,o,t.length)||{};return o in this.expressionMap.locallyGenerated&&this.queryRunner.manager.merge(r.target,l,this.expressionMap.locallyGenerated[o]),this.queryRunner.manager.merge(r.target,a,l),l});if(n.length>0&&!this.queryRunner.connection.driver.isReturningSqlSupported("insert")){const a=t.map(c=>{const l=r.getEntityIdMap(c);if(!l)throw new S("Cannot update entity because entity id is not set in the entity.");return l}),o=await this.queryRunner.manager.createQueryBuilder().select(r.primaryColumns.map(c=>r.targetName+"."+c.propertyPath)).addSelect(n.map(c=>r.targetName+"."+c.propertyPath)).from(r.target,r.targetName).where(a).setOption("create-pojo").getMany();t.forEach((c,l)=>{this.queryRunner.manager.merge(r.target,s[l],o[l]),this.queryRunner.manager.merge(r.target,c,o[l])})}t.forEach((a,o)=>{const c=r.getEntityIdMap(a);e.identifiers.push(c),e.generatedMaps.push(s[o])})}getUpdationReturningColumns(){return this.expressionMap.mainAlias.metadata.columns.filter(e=>e.asExpression!==void 0||e.isUpdateDate||e.isVersion)}getSoftDeletionReturningColumns(){return this.expressionMap.mainAlias.metadata.columns.filter(e=>e.asExpression!==void 0||e.isUpdateDate||e.isVersion||e.isDeleteDate)}}class Zs extends le{constructor(){super(...arguments),this["@instanceof"]=Symbol.for("InsertQueryBuilder")}getQuery(){let e=this.createComment();return e+=this.createCteExpression(),e+=this.createInsertExpression(),this.replacePropertyNamesForTheWholeQuery(e.trim())}async execute(){const e=this.getValueSets();if(e.length===0)return new Ln;const t=this.obtainQueryRunner();let r=!1;try{if(this.expressionMap.useTransaction===!0&&t.isTransactionActive===!1&&(await t.startTransaction(),r=!0),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata){const y=new kn;e.forEach(d=>{t.broadcaster.broadcastBeforeInsertEvent(y,this.expressionMap.mainAlias.metadata,d)}),await y.wait()}let n=null,i=null;const s=new br(t,this.expressionMap),a=[];if(Array.isArray(this.expressionMap.returning)&&this.expressionMap.mainAlias.hasMetadata)for(const y of this.expressionMap.returning)a.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(y));this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&(e.length>1&&this.connection.driver.options.type==="oracle"||(this.expressionMap.extraReturningColumns=this.expressionMap.mainAlias.metadata.getInsertionReturningColumns()),a.push(...this.expressionMap.extraReturningColumns.filter(y=>!a.includes(y)))),a.length>0&&this.connection.driver.options.type==="mssql"&&(n=this.connection.driver.buildTableVariableDeclaration("@OutputTable",a),i="SELECT * FROM @OutputTable");const[o,c]=this.getQueryAndParameters(),p=[n,o,i].filter(y=>y!=null).join(`;
4
+
5
+ `),u=await t.query(p,c,!0),f=Ln.from(u);if(this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&await s.insert(f,e),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata){const y=new kn;e.forEach(d=>{t.broadcaster.broadcastAfterInsertEvent(y,this.expressionMap.mainAlias.metadata,d)}),await y.wait()}return r&&await t.commitTransaction(),f}catch(n){if(r)try{await t.rollbackTransaction()}catch{}throw n}finally{t!==this.queryRunner&&await t.release()}}into(e,t){e=oe.isEntitySchema(e)?e.options.name:e;const r=this.createFromAlias(e);return this.expressionMap.setMainAlias(r),this.expressionMap.insertColumns=t||[],this}values(e){return this.expressionMap.valuesSet=e,this}output(e){return this.returning(e)}returning(e){if(!this.connection.driver.isReturningSqlSupported("insert"))throw new Ye;return this.expressionMap.returning=e,this}updateEntity(e){return this.expressionMap.updateEntity=e,this}onConflict(e){return this.expressionMap.onConflict=e,this}orIgnore(e=!0){return this.expressionMap.onIgnore=!!e,this}orUpdate(e,t,r){const{where:n,parameters:i}=r?.overwriteCondition??{};let s;if(n){const a=this.getWhereCondition(n);(Array.isArray(a)?a.length!==0:a)&&(s=[{type:"simple",condition:a}])}return i&&this.setParameters(i),Array.isArray(e)?(this.expressionMap.onUpdate={overwrite:e,conflict:t,skipUpdateIfNoValuesChanged:r?.skipUpdateIfNoValuesChanged,indexPredicate:r?.indexPredicate,upsertType:r?.upsertType,overwriteCondition:s},this):(this.expressionMap.onUpdate={conflict:e?.conflict_target,columns:e?.columns,overwrite:e?.overwrite,skipUpdateIfNoValuesChanged:r?.skipUpdateIfNoValuesChanged,upsertType:r?.upsertType,overwriteCondition:s},this)}createInsertExpression(){if((this.expressionMap.onUpdate||this.expressionMap.onIgnore)&&(this.expressionMap.onUpdate?.upsertType??"merge-into")==="merge-into"&&this.connection.driver.supportedUpsertTypes.includes("merge-into"))return this.createMergeExpression();const e=this.getTableName(this.getMainTableName()),t=this.alias!==this.getMainTableName()?this.escape(this.alias):e,r=this.createValuesExpression(),n=this.connection.driver.options.type==="oracle"&&this.getValueSets().length>1?null:this.createReturningExpression("insert"),i=this.createColumnNamesExpression();let s="INSERT ";if(this.expressionMap.onUpdate?.upsertType==="primary-key"&&(s="UPSERT "),($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")&&(s+=`${this.expressionMap.onIgnore?" IGNORE ":""}`),s+=`INTO ${e}`,this.alias!==this.getMainTableName()&&$.isPostgresFamily(this.connection.driver)&&(s+=` AS "${this.alias}"`),i?s+=`(${i})`:!r&&($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")&&(s+="()"),n&&this.connection.driver.options.type==="mssql"&&(s+=` OUTPUT ${n}`),r?(this.connection.driver.options.type==="oracle"||this.connection.driver.options.type==="sap")&&this.getValueSets().length>1?s+=` ${r}`:s+=` VALUES ${r}`:$.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql"?s+=" VALUES ()":s+=" DEFAULT VALUES",this.expressionMap.onUpdate?.upsertType!=="primary-key"){if(this.connection.driver.supportedUpsertTypes.includes("on-conflict-do-update")){if(this.expressionMap.onIgnore)s+=" ON CONFLICT DO NOTHING ";else if(this.expressionMap.onConflict)s+=` ON CONFLICT ${this.expressionMap.onConflict} `;else if(this.expressionMap.onUpdate){const{overwrite:a,columns:o,conflict:c,skipUpdateIfNoValuesChanged:l,indexPredicate:p}=this.expressionMap.onUpdate;let u="ON CONFLICT";if(Array.isArray(c)){if(u+=` ( ${c.map(y=>this.escape(y)).join(", ")} )`,p&&!$.isPostgresFamily(this.connection.driver))throw new S("indexPredicate option is not supported by the current database driver");p&&$.isPostgresFamily(this.connection.driver)&&(u+=` WHERE ( ${p} )`)}else c&&(u+=` ON CONSTRAINT ${this.escape(c)}`);const f=[];if(Array.isArray(a)?f.push(...a.map(y=>`${this.escape(y)} = EXCLUDED.${this.escape(y)}`)):o&&f.push(...o.map(y=>`${this.escape(y)} = :${y}`)),f.length>0&&(s+=` ${u} DO UPDATE SET `,f.push(...this.expressionMap.mainAlias.metadata.columns.filter(y=>y.isUpdateDate&&!a?.includes(y.databaseName)&&!(this.connection.driver.options.type==="oracle"&&this.getValueSets().length>1||$.isSQLiteFamily(this.connection.driver)||this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner")).map(y=>`${this.escape(y.databaseName)} = DEFAULT`)),s+=f.join(", ")),Array.isArray(a)&&l){this.expressionMap.onUpdate.overwriteCondition??=[];const y=a.map(d=>({type:"or",condition:`${t}.${this.escape(d)} IS DISTINCT FROM EXCLUDED.${this.escape(d)}`}));this.expressionMap.onUpdate.overwriteCondition.push({type:"and",condition:y})}$.isPostgresFamily(this.connection.driver)&&this.expressionMap.onUpdate.overwriteCondition&&this.expressionMap.onUpdate.overwriteCondition.length>0&&(s+=` WHERE ${this.createUpsertConditionExpression()}`)}}else if(this.connection.driver.supportedUpsertTypes.includes("on-duplicate-key-update")){if(this.expressionMap.onUpdate){const{overwrite:a,columns:o}=this.expressionMap.onUpdate;Array.isArray(a)?(s+=" ON DUPLICATE KEY UPDATE ",s+=a.map(c=>`${this.escape(c)} = VALUES(${this.escape(c)})`).join(", "),s+=" "):Array.isArray(o)&&(s+=" ON DUPLICATE KEY UPDATE ",s+=o.map(c=>`${this.escape(c)} = :${c}`).join(", "),s+=" ")}}else if(this.expressionMap.onUpdate)throw new S("onUpdate is not supported by the current database driver")}return n&&($.isPostgresFamily(this.connection.driver)||this.connection.driver.options.type==="oracle"||this.connection.driver.options.type==="cockroachdb"||$.isMySQLFamily(this.connection.driver))&&(s+=` RETURNING ${n}`),n&&this.connection.driver.options.type==="spanner"&&(s+=` THEN RETURN ${n}`),this.connection.driver.options.type==="mssql"&&this.expressionMap.mainAlias.hasMetadata&&this.expressionMap.mainAlias.metadata.columns.filter(a=>this.expressionMap.insertColumns.length>0?this.expressionMap.insertColumns.indexOf(a.propertyPath)!==-1:a.isInsert).some(a=>this.isOverridingAutoIncrementBehavior(a))&&(s=`SET IDENTITY_INSERT ${e} ON; ${s}; SET IDENTITY_INSERT ${e} OFF`),s}getInsertedColumns(){return this.expressionMap.mainAlias.hasMetadata?this.expressionMap.mainAlias.metadata.columns.filter(e=>this.expressionMap.insertColumns.length?this.expressionMap.insertColumns.indexOf(e.propertyPath)!==-1:!(!e.isInsert||e.isGenerated&&e.generationStrategy==="increment"&&this.connection.driver.options.type!=="spanner"&&this.connection.driver.options.type!=="oracle"&&!$.isSQLiteFamily(this.connection.driver)&&!$.isMySQLFamily(this.connection.driver)&&this.connection.driver.options.type!=="aurora-mysql"&&!(this.connection.driver.options.type==="mssql"&&this.isOverridingAutoIncrementBehavior(e)))):[]}createColumnNamesExpression(){const e=this.getInsertedColumns();if(e.length>0)return e.map(t=>this.escape(t.databaseName)).join(", ");if(!this.expressionMap.mainAlias.hasMetadata&&!this.expressionMap.insertColumns.length){const t=this.getValueSets();if(t.length===1)return Object.keys(t[0]).map(r=>this.escape(r)).join(", ")}return this.expressionMap.insertColumns.map(t=>this.escape(t)).join(", ")}createValuesExpression(){const e=this.getValueSets(),t=this.getInsertedColumns();if(t.length>0){let r="";return e.forEach((n,i)=>{t.forEach((s,a)=>{a===0&&(this.connection.driver.options.type==="oracle"&&e.length>1||this.connection.driver.options.type==="sap"&&e.length>1?r+=" SELECT ":r+="("),r+=this.createColumnValueExpression(e,i,s),a===t.length-1?i===e.length-1?["oracle","sap"].includes(this.connection.driver.options.type)&&e.length>1?r+=" FROM "+this.connection.driver.dummyTableName:r+=")":["oracle","sap"].includes(this.connection.driver.options.type)&&e.length>1?r+=" FROM "+this.connection.driver.dummyTableName+" UNION ALL ":r+="), ":r+=", "})}),r==="()"?"":r}else{let r="";return e.forEach((n,i)=>{Object.keys(n).forEach((a,o)=>{o===0&&(r+="(");const c=n[a];typeof c=="function"?r+=c():c===void 0?this.connection.driver.options.type==="oracle"&&e.length>1||$.isSQLiteFamily(this.connection.driver)||this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner"?r+="NULL":r+="DEFAULT":c===null&&this.connection.driver.options.type==="spanner"||(r+=this.createParameter(c)),o===Object.keys(n).length-1?i===e.length-1?r+=")":r+="), ":r+=", "})}),r==="()"?"":r}}getValueSets(){if(Array.isArray(this.expressionMap.valuesSet))return this.expressionMap.valuesSet;if(fe.isObject(this.expressionMap.valuesSet))return[this.expressionMap.valuesSet];throw new Hi}isOverridingAutoIncrementBehavior(e){return e.isPrimary&&e.isGenerated&&e.generationStrategy==="increment"&&this.getValueSets().some(t=>e.getEntityValue(t)!==void 0&&e.getEntityValue(t)!==null)}createMergeExpression(){if(!this.connection.driver.supportedUpsertTypes.includes("merge-into"))throw new S('Upsert type "merge-into" is not supported by current database driver');if(this.expressionMap.onUpdate?.upsertType&&this.expressionMap.onUpdate.upsertType!=="merge-into")throw new S(`Upsert type "${this.expressionMap.onUpdate.upsertType}" is not supported by current database driver`);const e=this.getTableName(this.getMainTableName()),t=this.escape(this.alias),r=this.getInsertedColumns(),n=this.createColumnNamesExpression();let i=`MERGE INTO ${e} ${this.escape(this.alias)}`;const s=this.escape("mergeIntoSource"),a=this.createMergeIntoSourceExpression(s);if(i+=` ${a}`,this.expressionMap.onIgnore){const l=r.find(p=>p.isPrimary);l?i+=` ON (${t}.${this.escape(l.databaseName)} = ${s}.${this.escape(l.databaseName)})`:i+=`ON (${this.expressionMap.mainAlias.metadata.uniques.map(p=>`(${p.columns.map(u=>`${t}.${this.escape(u.databaseName)} = ${s}.${this.escape(u.databaseName)}`).join(" AND ")})`).join(" OR ")})`}else if(this.expressionMap.onUpdate){const{conflict:l,indexPredicate:p}=this.expressionMap.onUpdate;if(p)throw new S('indexPredicate option is not supported by upsert type "merge-into"');Array.isArray(l)?i+=` ON (${l.map(u=>`${t}.${this.escape(u)} = ${s}.${this.escape(u)}`).join(" AND ")})`:l?i+=` ON (${t}.${this.escape(l)} = ${s}.${this.escape(l)})`:i+=`ON (${this.expressionMap.mainAlias.metadata.uniques.map(u=>`(${u.columns.map(f=>`${t}.${this.escape(f.databaseName)} = ${s}.${this.escape(f.databaseName)}`).join(" AND ")})`).join(" OR ")})`}if(this.expressionMap.onUpdate){const{overwrite:l,columns:p,conflict:u,skipUpdateIfNoValuesChanged:f}=this.expressionMap.onUpdate;let y="";if(Array.isArray(l)&&(y+=(l||p)?.filter(m=>!u?.includes(m)).map(m=>`${t}.${this.escape(m)} = ${s}.${this.escape(m)}`).join(", ")),Array.isArray(l)&&f){this.expressionMap.onUpdate.overwriteCondition??=[];const m=l.map(b=>({type:"or",condition:{operator:"notEqual",parameters:[`${t}.${this.escape(b)}`,`${s}.${this.escape(b)}`]}}));this.expressionMap.onUpdate.overwriteCondition.push({type:"and",condition:m})}const d=this.createUpsertConditionExpression();y.trim()&&((this.connection.driver.options.type==="mssql"||this.connection.driver.options.type==="sap")&&d!=""?i+=` WHEN MATCHED AND ${d} THEN UPDATE SET ${y}`:(i+=` WHEN MATCHED THEN UPDATE SET ${y}`,d!=""&&(i+=` WHERE ${d}`)))}const o=this.createMergeIntoInsertValuesExpression(s),c=this.connection.driver.options.type==="mssql"?this.createReturningExpression("insert"):null;return i+=" WHEN NOT MATCHED THEN INSERT",n&&(i+=`(${n})`),o&&(i+=` VALUES ${o}`),c&&this.connection.driver.options.type==="mssql"&&(i+=` OUTPUT ${c}`),this.connection.driver.options.type==="mssql"&&(i+=";"),i}createMergeIntoSourceExpression(e){const t=this.getValueSets(),r=this.getInsertedColumns();let n="USING (";if(r.length>0)this.connection.driver.options.type==="mssql"&&(n+="VALUES "),t.forEach((i,s)=>{r.forEach((a,o)=>{o===0&&(this.connection.driver.options.type==="mssql"?n+="(":n+="SELECT ");const c=a.getEntityValue(i);c===void 0&&!(a.isGenerated&&a.generationStrategy==="uuid"&&!this.connection.driver.isUUIDGenerationSupported())?a.default!==void 0&&a.default!==null?n+=this.connection.driver.normalizeDefault(a):n+="NULL":c===null?n+="NULL":n+=this.createColumnValueExpression(t,s,a),this.connection.driver.options.type!=="mssql"&&(n+=` AS ${this.escape(a.databaseName)}`),o===r.length-1?s===t.length-1?["oracle","sap"].includes(this.connection.driver.options.type)?n+=" FROM "+this.connection.driver.dummyTableName:this.connection.driver.options.type==="mssql"&&(n+=")"):["oracle","sap"].includes(this.connection.driver.options.type)&&t.length>1?n+=" FROM "+this.connection.driver.dummyTableName+" UNION ALL ":this.connection.driver.options.type==="mssql"?n+="), ":n+=" UNION ALL ":n+=", "})});else throw new S('Upsert type "merge-into" is not supported without metadata tables');return n+=`) ${e}`,this.connection.driver.options.type==="mssql"&&(n+=` (${r.map(i=>this.escape(i.databaseName)).join(", ")})`),n}createMergeIntoInsertValuesExpression(e){const t=this.getInsertedColumns();let r="";if(t.length>0)t.forEach((n,i)=>{i===0&&(r+="("),n.isGenerated&&n.generationStrategy==="uuid"&&this.connection.driver.isUUIDGenerationSupported()||n.isGenerated&&n.generationStrategy!=="uuid"?r+="DEFAULT":r+=`${e}.${this.escape(n.databaseName)}`,i===t.length-1?r+=")":r+=", "});else throw new S('Upsert type "merge-into" is not supported without metadata tables');return r==="()"?"":r}createUpsertConditionExpression(){if(!this.expressionMap.onUpdate.overwriteCondition)return"";const e=[],t=this.createWhereClausesExpression(this.expressionMap.onUpdate.overwriteCondition);if(t.length>0&&t!=="1=1"&&e.push(t),this.expressionMap.mainAlias.hasMetadata){const n=this.expressionMap.mainAlias.metadata;if(this.expressionMap.queryType==="select"&&!this.expressionMap.withDeleted&&n.deleteDateColumn){const s=`${this.expressionMap.aliasNamePrefixingEnabled?this.expressionMap.mainAlias.name+"."+n.deleteDateColumn.propertyName:n.deleteDateColumn.propertyName} IS NULL`;e.push(s)}if(n.discriminatorColumn&&n.parentEntityMetadata){const s=`${this.expressionMap.aliasNamePrefixingEnabled?this.expressionMap.mainAlias.name+"."+n.discriminatorColumn.databaseName:n.discriminatorColumn.databaseName} IN (:...discriminatorColumnValues)`;e.push(s)}}if(this.expressionMap.extraAppendedAndWhereCondition){const n=this.expressionMap.extraAppendedAndWhereCondition;e.push(n)}let r="";return e.length?e.length===1?r+=`${e[0]}`:r+=`( ${e.join(" ) AND ( ")} )`:r+="",r}createColumnValueExpression(e,t,r){const n=e[t];let i="",s=r.getEntityValue(n);if(typeof s!="function"&&(s=this.connection.driver.preparePersistentValue(s,r)),r.isVersion&&s===void 0)i+="1";else if(r.isDiscriminator)i+=this.createParameter(this.expressionMap.mainAlias.metadata.discriminatorValue);else if(r.isGenerated&&r.generationStrategy==="uuid"&&!this.connection.driver.isUUIDGenerationSupported()&&s===void 0)s=zs(),i+=this.createParameter(s),t in this.expressionMap.locallyGenerated||(this.expressionMap.locallyGenerated[t]={}),r.setEntityValue(this.expressionMap.locallyGenerated[t],s);else if(s===void 0)this.connection.driver.options.type==="oracle"&&e.length>1||$.isSQLiteFamily(this.connection.driver)||this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner"?r.default!==void 0&&r.default!==null?i+=this.connection.driver.normalizeDefault(r):this.connection.driver.options.type==="spanner"&&r.isGenerated&&r.generationStrategy==="uuid"?i+="GENERATE_UUID()":i+="NULL":i+="DEFAULT";else if(s===null&&(this.connection.driver.options.type==="spanner"||this.connection.driver.options.type==="oracle"))i+="NULL";else if(typeof s=="function")i+=s();else{this.connection.driver.options.type==="mssql"&&(s=this.connection.driver.parametrizeValue(r,s));const a=this.createParameter(s);if(($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")&&this.connection.driver.spatialTypes.includes(r.type)){const c=this.connection.driver.options.legacySpatialSupport?"GeomFromText":"ST_GeomFromText";r.srid!=null?i+=`${c}(${a}, ${r.srid})`:i+=`${c}(${a})`}else $.isPostgresFamily(this.connection.driver)&&this.connection.driver.spatialTypes.includes(r.type)?r.srid!=null?i+=`ST_SetSRID(ST_GeomFromGeoJSON(${a}), ${r.srid})::${r.type}`:i+=`ST_GeomFromGeoJSON(${a})::${r.type}`:this.connection.driver.options.type==="mssql"&&this.connection.driver.spatialTypes.includes(r.type)?i+=r.type+"::STGeomFromText("+a+", "+(r.srid||"0")+")":i+=a}return i}}class Un{constructor(e,t){this.queryBuilder=e,this.expressionMap=t}async update(e){const t=this.expressionMap.relationMetadata;if(t.isManyToOne||t.isOneToOneOwner){const r=t.joinColumns.reduce((n,i)=>{const s=fe.isObject(e)?i.referencedColumn.getEntityValue(e):e;return i.setEntityValue(n,s),n},{});if(!this.expressionMap.of||Array.isArray(this.expressionMap.of)&&!this.expressionMap.of.length)return;await this.queryBuilder.createQueryBuilder().update(t.entityMetadata.target).set(r).whereInIds(this.expressionMap.of).execute()}else if((t.isOneToOneNotOwner||t.isOneToMany)&&e===null){const r={};t.inverseRelation.joinColumns.forEach(o=>{r[o.propertyName]=null});const n=Array.isArray(this.expressionMap.of)?this.expressionMap.of:[this.expressionMap.of],i={},s=[];n.forEach((o,c)=>{t.inverseRelation.joinColumns.map((l,p)=>{const u="joinColumn_"+c+"_"+p;i[u]=fe.isObject(o)?l.referencedColumn.getEntityValue(o):o,s.push(`${l.propertyPath} = :${u}`)})});const a=s.map(o=>"("+o+")").join(" OR ");if(!a)return;await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(r).where(a).setParameters(i).execute()}else if(t.isOneToOneNotOwner||t.isOneToMany){if(Array.isArray(this.expressionMap.of))throw new S("You cannot update relations of multiple entities with the same related object. Provide a single entity into .of method.");const r=this.expressionMap.of,n=t.inverseRelation.joinColumns.reduce((i,s)=>{const a=fe.isObject(r)?s.referencedColumn.getEntityValue(r):r;return s.setEntityValue(i,a),i},{});if(!e||Array.isArray(e)&&!e.length)return;await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(n).whereInIds(e).execute()}else{const r=t.junctionEntityMetadata,n=Array.isArray(this.expressionMap.of)?this.expressionMap.of:[this.expressionMap.of],i=Array.isArray(e)?e:[e],s=t.isManyToManyOwner?n:i,a=t.isManyToManyOwner?i:n,o=[];if(s.forEach(c=>{a.forEach(l=>{const p={};r.ownerColumns.forEach(u=>{p[u.databaseName]=fe.isObject(c)?u.referencedColumn.getEntityValue(c):c}),r.inverseColumns.forEach(u=>{p[u.databaseName]=fe.isObject(l)?u.referencedColumn.getEntityValue(l):l}),o.push(p)})}),!o.length)return;this.queryBuilder.connection.driver.options.type==="oracle"||this.queryBuilder.connection.driver.options.type==="sap"?await Promise.all(o.map(c=>this.queryBuilder.createQueryBuilder().insert().into(r.tableName).values(c).execute())):await this.queryBuilder.createQueryBuilder().insert().into(r.tableName).values(o).execute()}}}class Xs{constructor(e,t){this.queryBuilder=e,this.expressionMap=t}async remove(e){const t=this.expressionMap.relationMetadata;if(t.isOneToMany){const r=Array.isArray(this.expressionMap.of)?this.expressionMap.of:[this.expressionMap.of],n=Array.isArray(e)?e:[e],i={};t.inverseRelation.joinColumns.forEach(c=>{i[c.propertyName]=null});const s={},a=[];r.forEach((c,l)=>{a.push(...n.map((p,u)=>[...t.inverseRelation.joinColumns.map((f,y)=>{const d="joinColumn_"+l+"_"+u+"_"+y;return s[d]=fe.isObject(c)?f.referencedColumn.getEntityValue(c):c,`${f.propertyPath} = :${d}`}),...t.inverseRelation.entityMetadata.primaryColumns.map((f,y)=>{const d="primaryColumn_"+u+"_"+u+"_"+y;return s[d]=fe.isObject(p)?f.getEntityValue(p):p,`${f.propertyPath} = :${d}`})].join(" AND ")))});const o=a.map(c=>"("+c+")").join(" OR ");if(!o)return;await this.queryBuilder.createQueryBuilder().update(t.inverseEntityMetadata.target).set(i).where(o).setParameters(s).execute()}else{const r=t.junctionEntityMetadata,n=Array.isArray(this.expressionMap.of)?this.expressionMap.of:[this.expressionMap.of],i=Array.isArray(e)?e:[e],s=t.isManyToManyOwner?n:i,a=t.isManyToManyOwner?i:n,o={},c=[];s.forEach((p,u)=>{c.push(...a.map((f,y)=>[...r.ownerColumns.map((d,m)=>{const b="firstValue_"+u+"_"+y+"_"+m;return o[b]=fe.isObject(p)?d.referencedColumn.getEntityValue(p):p,`${d.databaseName} = :${b}`}),...r.inverseColumns.map((d,m)=>{const b="secondValue_"+u+"_"+y+"_"+m;return o[b]=fe.isObject(f)?d.referencedColumn.getEntityValue(f):f,`${d.databaseName} = :${b}`})].join(" AND ")))});const l=c.map(p=>"("+p+")").join(" OR ");await this.queryBuilder.createQueryBuilder().delete().from(r.tableName).where(l).setParameters(o).execute()}}}class ea extends le{constructor(){super(...arguments),this["@instanceof"]=Symbol.for("RelationQueryBuilder")}getQuery(){return""}of(e){return this.expressionMap.of=e,this}async set(e){const t=this.expressionMap.relationMetadata;if(!this.expressionMap.of)throw new S("Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.");if(t.isManyToMany||t.isOneToMany)throw new S(`Set operation is only supported for many-to-one and one-to-one relations. However given "${t.propertyPath}" has ${t.relationType} relation. Use .add() method instead.`);if(t.joinColumns&&t.joinColumns.length>1&&(!fe.isObject(e)||Object.keys(e).length<t.joinColumns.length))throw new S('Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })');return new Un(this,this.expressionMap).update(e)}async add(e){if(Array.isArray(e)&&e.length===0)return;const t=this.expressionMap.relationMetadata;if(!this.expressionMap.of)throw new S("Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.");if(t.isManyToOne||t.isOneToOne)throw new S(`Add operation is only supported for many-to-many and one-to-many relations. However given "${t.propertyPath}" has ${t.relationType} relation. Use .set() method instead.`);if(t.joinColumns&&t.joinColumns.length>1&&(!fe.isObject(e)||Object.keys(e).length<t.joinColumns.length))throw new S('Value to be set into the relation must be a map of relation ids, for example: .set({ firstName: "...", lastName: "..." })');return new Un(this,this.expressionMap).update(e)}async remove(e){if(Array.isArray(e)&&e.length===0)return;const t=this.expressionMap.relationMetadata;if(!this.expressionMap.of)throw new S("Entity whose relation needs to be set is not set. Use .of method to define whose relation you want to set.");if(t.isManyToOne||t.isOneToOne)throw new S(`Add operation is only supported for many-to-many and one-to-many relations. However given "${t.propertyPath}" has ${t.relationType} relation. Use .set(null) method instead.`);return new Xs(this,this.expressionMap).remove(e)}async addAndRemove(e,t){await this.remove(t),await this.add(e)}async loadOne(){return this.loadMany().then(e=>e[0])}async loadMany(){let e=this.expressionMap.of;if(!fe.isObject(e)){const t=this.expressionMap.mainAlias.metadata;if(t.hasMultiplePrimaryKeys)throw new S("Cannot load entity because only one primary key was specified, however entity contains multiple primary keys");e=t.primaryColumns[0].createValueMap(e)}return this.connection.relationLoader.load(this.expressionMap.relationMetadata,e,this.queryRunner)}}class ee{static chunk(e,t){return Array.from(Array(Math.ceil(e.length/t)),(r,n)=>e.slice(n*t,n*t+t))}static splitClassesAndStrings(e){return[e.filter(t=>typeof t!="string"),e.filter(t=>typeof t=="string")]}static groupBy(e,t){return e.reduce((r,n)=>{const i=t(n);let s=r.find(a=>a.id===i);return s||(s={id:i,items:[]},r.push(s)),s.items.push(n),r},[])}static uniq(e,t){return e.reduce((r,n)=>{let i=!1;if(typeof t=="function"){const s=t(n);i=!!r.find(a=>t(a)===s)}else typeof t=="string"?i=!!r.find(s=>s[t]===n[t]):i=r.indexOf(n)!==-1;return i||r.push(n),r},[])}static mergeDeep(e,...t){if(!t.length)return e;for(const r of t)ee.merge(e,r);return e}static cloneObject(e){return e==null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e)}static deepCompare(...e){let t,r,n,i;if(e.length<1)return!0;for(t=1,r=e.length;t<r;t++)if(n=[],i=[],!ee.compare2Objects(n,i,e[0],e[t]))return!1;return!0}static deepValue(e,t){const r=t.split(".");for(let n=0,i=r.length;n<i;n++)e=e[r[n]];return e}static replaceEmptyObjectsWithBooleans(e){for(const t in e)e[t]&&typeof e[t]=="object"&&(Object.keys(e[t]).length===0?e[t]=!0:ee.replaceEmptyObjectsWithBooleans(e[t]))}static propertyPathsToTruthyObject(e){const t={};for(const r of e){const n=r.split(".");if(!n.length)continue;(!t[n[0]]||t[n[0]]===!0)&&(t[n[0]]={});let i=t[n[0]];for(const[s,a]of n.entries())s!==0&&(i[a]?i=i[a]:s===n.length-1?(i[a]={},i=null):(i[a]={},i=i[a]))}return ee.replaceEmptyObjectsWithBooleans(t),t}static compareIds(e,t){return e==null||t===void 0||t===null?!1:(typeof e.id=="string"&&typeof t.id=="string"||typeof e.id=="number"&&typeof t.id=="number")&&Object.keys(e).length===1&&Object.keys(t).length===1?e.id===t.id:ee.deepCompare(e,t)}static toBoolean(e){return typeof e=="boolean"?e:typeof e=="string"?e==="true"||e==="1":typeof e=="number"?e>0:!1}static isArraysEqual(e,t){return e.length!==t.length?!1:e.every(r=>t.includes(r))}static areMutuallyExclusive(...e){return!e.some(r=>{const n=e.filter(i=>i!==r);return r.some(i=>n.some(s=>s.includes(i)))})}static parseSqlCheckExpression(e,t){const r=e.match(new RegExp(`"${t}" varchar CHECK\\s*\\(\\s*"${t}"\\s+IN\\s*`));if(r&&r.index){const i=e.substring(r.index+r[0].length);let s="",a="";const o=[];for(let c=0;c<i.length;c++){const l=i[c];switch(l){case",":s==""?(o.push(a),a=""):a+=l;break;case"'":s==l?i[c+1]===l?(a+=l,c+=1):s="":s=l;break;case")":if(s=="")return o.push(a),o;a+=l;break;default:s!=""&&(a+=l)}}}}static isCriteriaNullOrEmpty(e){return e==null||e===""||Array.isArray(e)&&e.length===0||ee.isPlainObject(e)&&Object.keys(e).length===0}static isSinglePrimitiveCriteria(e){return typeof e=="string"||typeof e=="number"||e instanceof Date}static isPrimitiveCriteria(e){return Array.isArray(e)?e.every(t=>ee.isSinglePrimitiveCriteria(t)):ee.isSinglePrimitiveCriteria(e)}static compare2Objects(e,t,r,n){let i;if(Number.isNaN(r)&&Number.isNaN(n)||r===n)return!0;if(r===null||n===null||r===void 0||n===void 0)return!1;if((typeof r.equals=="function"||typeof r.equals=="function")&&r.equals(n))return!0;if(typeof r=="function"&&typeof n=="function"||r instanceof Date&&n instanceof Date||r instanceof RegExp&&n instanceof RegExp||typeof r=="string"&&typeof n=="string"||typeof r=="number"&&typeof n=="number")return r.toString()===n.toString();if(!(typeof r=="object"&&typeof n=="object")||Object.prototype.isPrototypeOf.call(r,n)||Object.prototype.isPrototypeOf.call(n,r)||r.constructor!==n.constructor||r.prototype!==n.prototype||e.indexOf(r)>-1||t.indexOf(n)>-1)return!1;for(i in n){if(n.hasOwnProperty(i)!==r.hasOwnProperty(i))return!1;if(typeof n[i]!=typeof r[i])return!1}for(i in r){if(n.hasOwnProperty(i)!==r.hasOwnProperty(i))return!1;if(typeof n[i]!=typeof r[i])return!1;switch(typeof r[i]){case"object":case"function":if(e.push(r),t.push(n),!ee.compare2Objects(e,t,r[i],n[i]))return!1;e.pop(),t.pop();break;default:if(r[i]!==n[i])return!1;break}}return!0}static isPlainObject(e){return e==null?!1:!e.constructor||e.constructor===Object}static mergeArrayKey(e,t,r,n){if(n.has(r)){e[t]=n.get(r);return}if(!(r instanceof Promise)){if(!ee.isPlainObject(r)&&!Array.isArray(r)){e[t]=r;return}e[t]||(e[t]=Array.isArray(r)?[]:{}),n.set(r,e[t]),ee.merge(e[t],r,n),n.delete(r)}}static mergeObjectKey(e,t,r,n){if(n.has(r)){Object.assign(e,{[t]:n.get(r)});return}if(!(r instanceof Promise)){if(!ee.isPlainObject(r)&&!Array.isArray(r)){Object.assign(e,{[t]:r});return}e[t]||Object.assign(e,{[t]:Array.isArray(r)?[]:{}}),n.set(r,e[t]),ee.merge(e[t],r,n),n.delete(r)}}static merge(e,t,r=new Map){if(ee.isPlainObject(e)&&ee.isPlainObject(t))for(const[n,i]of Object.entries(t))n!=="__proto__"&&ee.mergeObjectKey(e,n,i,r);if(Array.isArray(e)&&Array.isArray(t))for(let n=0;n<t.length;n++)ee.mergeArrayKey(e,n,t[n],r)}}class ta{constructor(e,t,r,n,i){this.expressionMap=e,this.driver=t,this.rawRelationIdResults=r,this.rawRelationCountResults=n,this.queryRunner=i,this.pojo=this.expressionMap.options.includes("create-pojo"),this.selections=new Set(this.expressionMap.selects.map(s=>s.selection)),this.aliasCache=new Map,this.columnsCache=new Map}transform(e,t){const r=this.group(e,t),n=[];for(const i of r.values()){const s=this.transformRawResultsGroup(i,t);s!==void 0&&n.push(s)}return n}buildAlias(e,t){let r=this.aliasCache.get(e);r||(r=new Map,this.aliasCache.set(e,r));let n=r.get(t);return n||(n=$.buildAlias(this.driver,void 0,e,t),r.set(t,n)),n}group(e,t){const r=new Map,n=[];t.metadata.tableType==="view"?n.push(...t.metadata.columns.map(i=>this.buildAlias(t.name,i.databaseName))):n.push(...t.metadata.primaryColumns.map(i=>this.buildAlias(t.name,i.databaseName)));for(const i of e){const s=n.map(o=>{const c=i[o];return Buffer.isBuffer(c)?c.toString("hex"):fe.isObject(c)?JSON.stringify(c):c}).join("_"),a=r.get(s);a?a.push(i):r.set(s,[i])}return r}transformRawResultsGroup(e,t){let r=t.metadata;if(r.discriminatorColumn){const l=e.map(u=>u[this.buildAlias(t.name,t.metadata.discriminatorColumn.databaseName)]),p=r.childEntityMetadatas.find(u=>typeof l.find(f=>f===u.discriminatorValue)<"u");p&&(r=p)}const n=r.create(this.queryRunner,{fromDeserializer:!0,pojo:this.pojo}),i=this.transformColumns(e,t,n,r),s=this.transformJoins(e,n,t,r),a=this.transformRelationIds(e,t,n,r),o=this.transformRelationCounts(e,t,n);if(i||r.primaryColumns.every(l=>l.isVirtual===!0)&&(s||a||o))return n}transformColumns(e,t,r,n){let i=!1;const s=e[0];for(const[a,o]of this.getColumnsToProcess(t.name,n)){const c=s[a];c!==void 0&&(c!==null&&!o.isVirtualProperty&&(i=!0),o.setEntityValue(r,this.driver.prepareHydratedValue(c,o)))}return i}transformJoins(e,t,r,n){let i=!1;for(const s of this.expressionMap.joinAttributes){if(!s.metadata||!s.isSelected||s.relation&&!n.relations.find(o=>o===s.relation))continue;if(s.mapToProperty){if(s.mapToPropertyParentAlias!==r.name)continue}else if(!s.relation||s.parentAlias!==r.name||s.relationPropertyPath!==s.relation.propertyPath)continue;let a=this.transform(e,s.alias);a=s.isMany?a:a[0],a=!s.isMany&&a===void 0?null:a,a!==void 0&&(s.mapToPropertyPropertyName?t[s.mapToPropertyPropertyName]=a:s.relation.setEntityValue(t,a),i=!0)}return i}transformRelationIds(e,t,r,n){let i=!1;for(const[s,a]of this.rawRelationIdResults.entries()){if(a.relationIdAttribute.parentAlias!==t.name)continue;const o=a.relationIdAttribute.relation,c=this.createValueMapFromJoinColumns(o,a.relationIdAttribute.parentAlias,e);if(c==null)continue;this.prepareDataForTransformRelationIds();const l=this.hashEntityIds(o,c),p=this.relationIdMaps[s][l]||[],u=a.relationIdAttribute.mapToPropertyPropertyPath.split("."),f=(y,d,m)=>{const b=y.shift();if(b&&y.length===0)return d[b]=m,d;if(b&&y.length>0)f(y,d[b],m);else return d};o.isOneToOne||o.isManyToOne?p[0]!==void 0&&(f(u,r,p[0]),i=!0):(f(u,r,p),i=i||p.length>0)}return i}transformRelationCounts(e,t,r){let n=!1;for(const i of this.rawRelationCountResults){if(i.relationCountAttribute.parentAlias!==t.name)continue;const s=i.relationCountAttribute.relation;let a;s.isOneToMany?a=s.inverseRelation.joinColumns[0].referencedColumn.databaseName:a=s.isOwning?s.joinColumns[0].referencedColumn.databaseName:s.inverseRelation.joinColumns[0].referencedColumn.databaseName;const o=e[0][this.buildAlias(t.name,a)];if(o!=null){r[i.relationCountAttribute.mapToPropertyPropertyName]=0;for(const c of i.results)c.parentId===o&&(r[i.relationCountAttribute.mapToPropertyPropertyName]=parseInt(c.cnt),n=!0)}}return n}getColumnsToProcess(e,t){let r=this.columnsCache.get(e);r||(r=new Map,this.columnsCache.set(e,r));let n=r.get(t);return n||(n=t.columns.filter(i=>!i.isVirtual&&(this.selections.has(e)||this.selections.has(`${e}.${i.propertyPath}`))&&!t.childEntityMetadatas.some(s=>s.target===i.target)).map(i=>[this.buildAlias(e,i.databaseName),i]),r.set(t,n)),n}createValueMapFromJoinColumns(e,t,r){let n;return e.isManyToOne||e.isOneToOneOwner?n=e.entityMetadata.primaryColumns.map(i=>i):e.isOneToMany||e.isOneToOneNotOwner?n=e.inverseRelation.joinColumns.map(i=>i):e.isOwning?n=e.joinColumns.map(i=>i):n=e.inverseRelation.inverseJoinColumns.map(i=>i),n.reduce((i,s)=>{for(const a of r)e.isManyToOne||e.isOneToOneOwner?i[s.databaseName]=this.driver.prepareHydratedValue(a[this.buildAlias(t,s.databaseName)],s):i[s.databaseName]=this.driver.prepareHydratedValue(a[this.buildAlias(t,s.referencedColumn.databaseName)],s.referencedColumn);return i},{})}extractEntityPrimaryIds(e,t){let r;return e.isManyToOne||e.isOneToOneOwner?r=e.entityMetadata.primaryColumns.map(n=>n):e.isOneToMany||e.isOneToOneNotOwner?r=e.inverseRelation.joinColumns.map(n=>n):e.isOwning?r=e.joinColumns.map(n=>n):r=e.inverseRelation.inverseJoinColumns.map(n=>n),r.reduce((n,i)=>(n[i.databaseName]=t[i.databaseName],n),{})}prepareDataForTransformRelationIds(){this.relationIdMaps||(this.relationIdMaps=this.rawRelationIdResults.map(e=>{const t=e.relationIdAttribute.relation;let r;return t.isManyToOne||t.isOneToOneOwner?r=t.joinColumns:t.isOneToMany||t.isOneToOneNotOwner?r=t.inverseEntityMetadata.primaryColumns:t.isOwning?r=t.inverseJoinColumns:r=t.inverseRelation.joinColumns,e.results.reduce((n,i)=>{let s=r.reduce((a,o)=>{let c=i[o.databaseName];return t.isOneToMany||t.isOneToOneNotOwner?(o.isVirtual&&o.referencedColumn&&o.referencedColumn.propertyName!==o.propertyName&&(c=o.referencedColumn.createValueMap(c)),ee.mergeDeep(a,o.createValueMap(c))):(!o.isPrimary&&o.referencedColumn.referencedColumn&&(c=o.referencedColumn.referencedColumn.createValueMap(c)),ee.mergeDeep(a,o.referencedColumn.createValueMap(c)))},{});if(r.length===1&&!e.relationIdAttribute.disableMixedMap&&(t.isOneToMany||t.isOneToOneNotOwner?s=r[0].getEntityValue(s):s=r[0].referencedColumn.getEntityValue(s)),s!==void 0){const a=this.hashEntityIds(t,i);n[a]?n[a].push(s):n[a]=[s]}return n},{})}))}hashEntityIds(e,t){const r=this.extractEntityPrimaryIds(e,t);return JSON.stringify(r)}}let ra=class{constructor(e,t,r){this.connection=e,this.queryRunner=t,this.relationIdAttributes=r}async load(e){const t=this.relationIdAttributes.map(async r=>{if(r.relation.isManyToOne||r.relation.isOneToOneOwner){if(r.queryBuilderFactory)throw new S("Additional condition can not be used with ManyToOne or OneToOne owner relations.");const n={},i=e.map(s=>{const a={},o=[];r.relation.joinColumns.forEach(l=>{a[l.databaseName]=this.connection.driver.prepareHydratedValue(s[$.buildAlias(this.connection.driver,void 0,r.parentAlias,l.databaseName)],l.referencedColumn);const p=`${l.databaseName}:${a[l.databaseName]}`;o.indexOf(p)===-1&&o.push(p)}),r.relation.entityMetadata.primaryColumns.forEach(l=>{a[l.databaseName]=this.connection.driver.prepareHydratedValue(s[$.buildAlias(this.connection.driver,void 0,r.parentAlias,l.databaseName)],l);const p=`${l.databaseName}:${a[l.databaseName]}`;o.indexOf(p)===-1&&o.push(p)}),o.sort();const c=o.join("::");return n[c]?null:(n[c]=!0,a)}).filter(s=>s);return{relationIdAttribute:r,results:i}}else if(r.relation.isOneToMany||r.relation.isOneToOneNotOwner){const n=r.relation,i=n.isOwning?n.joinColumns:n.inverseRelation.joinColumns,s=n.inverseEntityMetadata.target,a=n.inverseEntityMetadata.tableName,o=r.alias||a,c={},l={},p=e.map((d,m)=>{const b=[],A={},x=i.map(F=>{const L=F.databaseName+m,Q=d[$.buildAlias(this.connection.driver,void 0,r.parentAlias,F.referencedColumn.databaseName)],se=`${o}:${F.propertyPath}:${Q}`;return b.indexOf(se)!==-1?"":(b.push(se),A[L]=Q,o+"."+F.propertyPath+" = :"+L)}).filter(F=>F).join(" AND ");b.sort();const I=b.join("::");return c[I]?"":(c[I]=!0,Object.assign(l,A),x)}).filter(d=>d).map(d=>"("+d+")").join(" OR ");if(!p)return{relationIdAttribute:r,results:[]};const u=this.connection.createQueryBuilder(this.queryRunner);ee.uniq([...i,...n.inverseRelation.entityMetadata.primaryColumns],d=>d.propertyPath).forEach(d=>{u.addSelect(o+"."+d.propertyPath,d.databaseName)}),u.from(s,o).where("("+p+")").setParameters(l),r.queryBuilderFactory&&r.queryBuilderFactory(u);const y=await u.getRawMany();return y.forEach(d=>{i.forEach(m=>{d[m.databaseName]=this.connection.driver.prepareHydratedValue(d[m.databaseName],m.referencedColumn)}),n.inverseRelation.entityMetadata.primaryColumns.forEach(m=>{d[m.databaseName]=this.connection.driver.prepareHydratedValue(d[m.databaseName],m)})}),{relationIdAttribute:r,results:y}}else{const n=r.relation,i=n.isOwning?n.joinColumns:n.inverseRelation.inverseJoinColumns,s=n.isOwning?n.inverseJoinColumns:n.inverseRelation.joinColumns,a=r.junctionAlias,o=r.joinInverseSideMetadata.tableName,c=r.alias||o,l=n.isOwning?n.junctionEntityMetadata.tableName:n.inverseRelation.junctionEntityMetadata.tableName,p=e.map(x=>i.reduce((I,F)=>(I[F.propertyPath]=x[$.buildAlias(this.connection.driver,void 0,r.parentAlias,F.referencedColumn.databaseName)],I),{}));if(p.length===0)return{relationIdAttribute:r,results:[]};const u={},f={},y=p.map((x,I)=>{const F=[],L={},Q=Object.keys(x).map(te=>{const k=te+I,M=x[te],U=`${a}:${te}:${M}`;return F.indexOf(U)!==-1?"":(F.push(U),L[k]=M,a+"."+te+" = :"+k)}).filter(te=>te).join(" AND ");F.sort();const se=F.join("::");return f[se]?"":(f[se]=!0,Object.assign(u,L),Q)}).filter(x=>x),d=s.map(x=>a+"."+x.propertyPath+" = "+c+"."+x.referencedColumn.propertyPath).join(" AND "),m=y.map(x=>"("+x+" AND "+d+")").join(" OR "),b=this.connection.createQueryBuilder(this.queryRunner);s.forEach(x=>{b.addSelect(a+"."+x.propertyPath,x.databaseName).addOrderBy(a+"."+x.propertyPath)}),i.forEach(x=>{b.addSelect(a+"."+x.propertyPath,x.databaseName).addOrderBy(a+"."+x.propertyPath)}),b.from(o,c).innerJoin(l,a,m).setParameters(u),r.queryBuilderFactory&&r.queryBuilderFactory(b);const A=await b.getRawMany();return A.forEach(x=>{[...i,...s].forEach(I=>{x[I.databaseName]=this.connection.driver.prepareHydratedValue(x[I.databaseName],I.referencedColumn)})}),{relationIdAttribute:r,results:A}}});return Promise.all(t)}};class na{constructor(e,t){this.connection=e,this.queryRunner=t}load(e,t,r){const n=Array.isArray(t)?t:[t],i=Array.isArray(r)?r:r?[r]:void 0;return e.isManyToMany?this.loadForManyToMany(e,n,i):e.isManyToOne||e.isOneToOneOwner?this.loadForManyToOneAndOneToOneOwner(e,n,i):this.loadForOneToManyAndOneToOneNotOwner(e,n,i)}async loadManyToManyRelationIdsAndGroup(e,t,r,n){const i=e.isManyToMany||e.isOneToMany,s=Array.isArray(t)?t:[t];if(!r&&(r=await this.connection.relationLoader.load(e,t,this.queryRunner,n),!r.length))return s.map(p=>({entity:p,related:i?[]:void 0}));const a=await this.load(e,t,r),o=Array.isArray(r)?r:[r];let c=[],l=[];return e.isManyToManyOwner?(c=e.junctionEntityMetadata.inverseColumns.map(p=>p.referencedColumn),l=e.junctionEntityMetadata.ownerColumns.map(p=>p.referencedColumn)):e.isManyToManyNotOwner?(c=e.junctionEntityMetadata.ownerColumns.map(p=>p.referencedColumn),l=e.junctionEntityMetadata.inverseColumns.map(p=>p.referencedColumn)):e.isManyToOne||e.isOneToOneOwner?(c=e.joinColumns.map(p=>p.referencedColumn),l=e.entityMetadata.primaryColumns):(e.isOneToMany||e.isOneToOneNotOwner)&&(c=e.inverseRelation.entityMetadata.primaryColumns,l=e.inverseRelation.joinColumns.map(p=>p.referencedColumn)),s.map(p=>{const u={entity:p,related:i?[]:void 0},f=a.filter(y=>l.every(d=>d.compareEntityValue(p,y[d.entityMetadata.name+"_"+d.propertyAliasName])));return f.length&&o.forEach(y=>{f.forEach(d=>{c.every(b=>b.compareEntityValue(y,d[$.buildAlias(this.connection.driver,void 0,b.entityMetadata.name+"_"+e.propertyPath.replace(".","_")+"_"+b.propertyPath.replace(".","_"))]))&&(i?u.related.push(y):u.related=y)})}),u})}loadForManyToMany(e,t,r){const n=e.junctionEntityMetadata,i=n.name,s=e.isOwning?n.ownerColumns:n.inverseColumns,a=e.isOwning?n.inverseColumns:n.ownerColumns,o=this.connection.createQueryBuilder(this.queryRunner);s.forEach(u=>{const f=$.buildAlias(this.connection.driver,void 0,u.referencedColumn.entityMetadata.name+"_"+u.referencedColumn.propertyPath.replace(".","_"));o.addSelect(i+"."+u.propertyPath,f)}),a.forEach(u=>{const f=$.buildAlias(this.connection.driver,void 0,u.referencedColumn.entityMetadata.name+"_"+e.propertyPath.replace(".","_")+"_"+u.referencedColumn.propertyPath.replace(".","_"));o.addSelect(i+"."+u.propertyPath,f)});let c="";if(s.length===1){const u=t.map(y=>s[0].referencedColumn.getEntityValue(y));u.every(y=>typeof y=="number")?c=`${i}.${s[0].propertyPath} IN (${u.join(", ")})`:(o.setParameter("values1",u),c=i+"."+s[0].propertyPath+" IN (:...values1)")}else c="("+t.map((u,f)=>s.map(y=>{const d="entity1_"+f+"_"+y.propertyName;return o.setParameter(d,y.referencedColumn.getEntityValue(u)),i+"."+y.propertyPath+" = :"+d}).join(" AND ")).map(u=>"("+u+")").join(" OR ")+")";let l="";if(r)if(a.length===1){const u=r.map(y=>a[0].referencedColumn.getEntityValue(y));u.every(y=>typeof y=="number")?l=`${i}.${a[0].propertyPath} IN (${u.join(", ")})`:(o.setParameter("values2",u),l=i+"."+a[0].propertyPath+" IN (:...values2)")}else l="("+r.map((u,f)=>a.map(y=>{const d="entity2_"+f+"_"+y.propertyName;return o.setParameter(d,y.referencedColumn.getEntityValue(u)),i+"."+y.propertyPath+" = :"+d}).join(" AND ")).map(u=>"("+u+")").join(" OR ")+")";const p=[c,l].filter(u=>u.length>0).join(" AND ");return o.from(n.target,i).where(p).getRawMany()}loadForManyToOneAndOneToOneOwner(e,t,r){const n=e.entityMetadata.targetName,i=e.joinColumns.every(o=>!!e.entityMetadata.nonVirtualColumns.find(c=>c===o));if(r&&i){const o=[];if(t.forEach(c=>{const l={};e.entityMetadata.primaryColumns.forEach(p=>{const u=p.entityMetadata.name+"_"+p.propertyPath.replace(".","_");l[u]=p.getEntityValue(c)}),r.forEach(p=>{e.joinColumns.forEach(u=>{const f=u.getEntityValue(c),y=u.referencedColumn.getEntityValue(p);if(!(f===void 0||y===void 0)&&f===y){const d=u.referencedColumn.entityMetadata.name+"_"+e.propertyPath.replace(".","_")+"_"+u.referencedColumn.propertyPath.replace(".","_");l[d]=y}})}),Object.keys(l).length===e.entityMetadata.primaryColumns.length+e.joinColumns.length&&o.push(l)}),o.length===t.length)return Promise.resolve(o)}const s=this.connection.createQueryBuilder(this.queryRunner);e.entityMetadata.primaryColumns.forEach(o=>{const c=$.buildAlias(this.connection.driver,void 0,o.entityMetadata.name+"_"+o.propertyPath.replace(".","_"));s.addSelect(n+"."+o.propertyPath,c)}),e.joinColumns.forEach(o=>{const c=$.buildAlias(this.connection.driver,void 0,o.referencedColumn.entityMetadata.name+"_"+e.propertyPath.replace(".","_")+"_"+o.referencedColumn.propertyPath.replace(".","_"));s.addSelect(n+"."+o.propertyPath,c)});let a="";if(e.entityMetadata.primaryColumns.length===1){const o=t.map(l=>e.entityMetadata.primaryColumns[0].getEntityValue(l));o.every(l=>typeof l=="number")?a=`${n}.${e.entityMetadata.primaryColumns[0].propertyPath} IN (${o.join(", ")})`:(s.setParameter("values",o),a=n+"."+e.entityMetadata.primaryColumns[0].propertyPath+" IN (:...values)")}else a=t.map((o,c)=>e.entityMetadata.primaryColumns.map((l,p)=>{const u="entity"+c+"_"+p;return s.setParameter(u,l.getEntityValue(o)),n+"."+l.propertyPath+" = :"+u}).join(" AND ")).map(o=>"("+o+")").join(" OR ");return s.from(e.entityMetadata.target,n).where(a).getRawMany()}loadForOneToManyAndOneToOneNotOwner(e,t,r){const n=e;if(e=e.inverseRelation,e.entityMetadata.primaryColumns.length===e.joinColumns.length&&e.entityMetadata.primaryColumns.every(c=>e.joinColumns.indexOf(c)!==-1))return Promise.resolve(t.map(c=>{const l={};return e.joinColumns.forEach(function(p){const u=p.referencedColumn.getEntityValue(c),f=p.referencedColumn.entityMetadata.name+"_"+p.referencedColumn.propertyPath.replace(".","_"),y=p.entityMetadata.name+"_"+n.propertyPath.replace(".","_")+"_"+p.propertyPath.replace(".","_");l[f]=u,l[y]=u}),l}));const i=e.entityMetadata.targetName,s=this.connection.createQueryBuilder(this.queryRunner);e.entityMetadata.primaryColumns.forEach(o=>{const c=$.buildAlias(this.connection.driver,void 0,o.entityMetadata.name+"_"+n.propertyPath.replace(".","_")+"_"+o.propertyPath.replace(".","_"));s.addSelect(i+"."+o.propertyPath,c)}),e.joinColumns.forEach(o=>{const c=$.buildAlias(this.connection.driver,void 0,o.referencedColumn.entityMetadata.name+"_"+o.referencedColumn.propertyPath.replace(".","_"));s.addSelect(i+"."+o.propertyPath,c)});let a="";if(e.joinColumns.length===1){const o=t.map(l=>e.joinColumns[0].referencedColumn.getEntityValue(l));o.every(l=>typeof l=="number")?a=`${i}.${e.joinColumns[0].propertyPath} IN (${o.join(", ")})`:(s.setParameter("values",o),a=i+"."+e.joinColumns[0].propertyPath+" IN (:...values)")}else a=t.map((o,c)=>e.joinColumns.map((l,p)=>{const u="entity"+c+"_"+p;return s.setParameter(u,l.referencedColumn.getEntityValue(o)),i+"."+l.propertyPath+" = :"+u}).join(" AND ")).map(o=>"("+o+")").join(" OR ");return s.from(e.entityMetadata.target,i).where(a).getRawMany()}}class ia{constructor(e){this.expressionMap=e}transform(){this.expressionMap.mainAlias&&this.expressionMap.mainAlias.metadata.relationIds.forEach(e=>{const t=this.metadataToAttribute(this.expressionMap.mainAlias.name,e);this.expressionMap.relationIdAttributes.push(t)}),this.expressionMap.joinAttributes.forEach(e=>{!e.metadata||e.metadata.isJunction||e.metadata.relationIds.forEach(t=>{const r=this.metadataToAttribute(e.alias.name,t);this.expressionMap.relationIdAttributes.push(r)})})}metadataToAttribute(e,t){return new yr(this.expressionMap,{relationName:e+"."+t.relation.propertyName,mapToProperty:e+"."+t.propertyName,alias:t.alias,queryBuilderFactory:t.queryBuilderFactory})}}class sa{constructor(e,t,r){this.connection=e,this.queryRunner=t,this.relationCountAttributes=r}async load(e){const t=(n,i,s)=>s.indexOf(n)===i,r=this.relationCountAttributes.map(async n=>{if(n.relation.isOneToMany){const i=n.relation,s=i.inverseRelation,a=s.joinColumns[0].referencedColumn.propertyName,o=i.inverseEntityMetadata.target,c=i.inverseEntityMetadata.tableName,l=n.alias||c,p=s.propertyName;let u=e.map(y=>y[n.parentAlias+"_"+a]).filter(y=>!!y);if(u=u.filter(t),u.length===0)return{relationCountAttribute:n,results:[]};const f=this.connection.createQueryBuilder(this.queryRunner);return f.select(l+"."+p,"parentId").addSelect("COUNT(*)","cnt").from(o,l).where(l+"."+p+" IN (:...ids)").addGroupBy(l+"."+p).setParameter("ids",u),n.queryBuilderFactory&&n.queryBuilderFactory(f),{relationCountAttribute:n,results:await f.getRawMany()}}else{let i,s,a,o;n.relation.isOwning?(i=n.relation.joinColumns[0].referencedColumn.databaseName,s=n.relation.inverseJoinColumns[0].referencedColumn.databaseName,a=n.relation.junctionEntityMetadata.columns[0],o=n.relation.junctionEntityMetadata.columns[1]):(i=n.relation.inverseRelation.inverseJoinColumns[0].referencedColumn.databaseName,s=n.relation.inverseRelation.joinColumns[0].referencedColumn.databaseName,a=n.relation.junctionEntityMetadata.columns[1],o=n.relation.junctionEntityMetadata.columns[0]);let c=e.map(m=>m[n.parentAlias+"_"+i]).filter(m=>!!m);if(c=c.filter(t),c.length===0)return{relationCountAttribute:n,results:[]};const l=n.junctionAlias,p=n.joinInverseSideMetadata.tableName,u=n.alias||p,f=n.relation.junctionEntityMetadata.tableName,y=l+"."+a.propertyName+" IN ("+c.map(m=>isNaN(m)?"'"+m+"'":m)+") AND "+l+"."+o.propertyName+" = "+u+"."+s,d=this.connection.createQueryBuilder(this.queryRunner);return d.select(l+"."+a.propertyName,"parentId").addSelect("COUNT("+d.escape(u)+"."+d.escape(s)+")","cnt").from(p,u).innerJoin(f,l,y).addGroupBy(l+"."+a.propertyName),n.queryBuilderFactory&&n.queryBuilderFactory(d),{relationCountAttribute:n,results:await d.getRawMany()}}});return Promise.all(r)}}class aa{constructor(e){this.expressionMap=e}transform(){this.expressionMap.mainAlias&&this.expressionMap.mainAlias.metadata.relationCounts.forEach(e=>{const t=this.metadataToAttribute(this.expressionMap.mainAlias.name,e);this.expressionMap.relationCountAttributes.push(t)}),this.expressionMap.joinAttributes.forEach(e=>{!e.metadata||e.metadata.isJunction||e.metadata.relationCounts.forEach(t=>{const r=this.metadataToAttribute(e.alias.name,t);this.expressionMap.relationCountAttributes.push(r)})})}metadataToAttribute(e,t){return new mr(this.expressionMap,{relationName:e+"."+t.relation.propertyName,mapToProperty:e+"."+t.propertyName,alias:t.alias,queryBuilderFactory:t.queryBuilderFactory})}}class vr{static isFindOneOptions(e){const t=e;return t&&(Array.isArray(t.select)||Array.isArray(t.relations)||typeof t.select=="object"||typeof t.relations=="object"||typeof t.where=="object"||typeof t.join=="object"||typeof t.order=="object"||typeof t.cache=="object"||typeof t.cache=="boolean"||typeof t.cache=="number"||typeof t.comment=="string"||typeof t.lock=="object"||typeof t.loadRelationIds=="object"||typeof t.loadRelationIds=="boolean"||typeof t.loadEagerRelations=="boolean"||typeof t.withDeleted=="boolean"||typeof t.relationLoadStrategy=="string"||typeof t.transaction=="boolean")}static isFindManyOptions(e){const t=e;return t&&(this.isFindOneOptions(t)||typeof t.skip=="number"||typeof t.take=="number"||typeof t.skip=="string"||typeof t.take=="string")}static extractFindManyOptionsAlias(e){if(this.isFindManyOptions(e)&&e.join)return e.join.alias}static applyOptionsToTreeQueryBuilder(e,t){if(t?.relations){const r=[...t.relations];if(vr.applyRelationsRecursively(e,r,e.expressionMap.mainAlias.name,e.expressionMap.mainAlias.metadata,""),r.length>0)throw new Yi(r)}return e}static applyRelationsRecursively(e,t,r,n,i){let s=[];if(i){const a=new RegExp("^"+i.replace(".","\\.")+"\\.");s=t.filter(o=>o.match(a)).map(o=>n.findRelationWithPropertyPath(o.replace(a,""))).filter(o=>o)}else s=t.map(a=>n.findRelationWithPropertyPath(a)).filter(a=>a);s.forEach(a=>{const o=$.buildAlias(e.connection.driver,{joiner:"__"},r,a.propertyPath),c=r+"."+a.propertyPath;e.expressionMap.relationLoadStrategy==="query"?e.concatRelationMetadata(a):e.leftJoinAndSelect(c,o),t.splice(t.indexOf(i?i+"."+a.propertyPath:a.propertyPath),1);let l,p;if(e.expressionMap.relationLoadStrategy==="query")l=a.inverseEntityMetadata,p=o;else{const u=e.expressionMap.joinAttributes.find(f=>f.entityOrProperty===c);l=u.metadata,p=u.alias.name}if(!p||!l)throw new Ce(a.propertyPath,n);if(this.applyRelationsRecursively(e,t,p,l,i?i+"."+a.propertyPath:a.propertyPath),e.expressionMap.relationLoadStrategy==="join"){const u=n.relations.find(f=>f.propertyName===a.propertyPath);u&&this.joinEagerRelations(e,o,u.inverseEntityMetadata)}})}static joinEagerRelations(e,t,r){r.eagerRelations.forEach(n=>{let i=$.buildAlias(e.connection.driver,{joiner:"__"},t,n.propertyName),s=!0;for(const c of e.expressionMap.joinAttributes)if(!(c.condition!==void 0||c.mapToProperty!==void 0||c.isMappingMany!==void 0||c.direction!=="LEFT"||c.entityOrProperty!==`${t}.${n.propertyPath}`)){s=!1,i=c.alias.name;break}const a=!!e.expressionMap.joinAttributes.find(c=>c.alias.name===i);s&&!a&&e.leftJoin(t+"."+n.propertyPath,i);let o=!0;for(const c of e.expressionMap.selects)if(!(c.aliasName!==void 0||c.virtual!==void 0||c.selection!==i)){o=!1;break}o&&e.addSelect(i),this.joinEagerRelations(e,i,n.inverseEntityMetadata)})}}class xr extends le{constructor(){super(...arguments),this["@instanceof"]=Symbol.for("SelectQueryBuilder"),this.findOptions={},this.selects=[],this.joins=[],this.conditions="",this.orderBys=[],this.relationMetadatas=[]}getQuery(){let e=this.createComment();return e+=this.createCteExpression(),e+=this.createSelectExpression(),e+=this.createJoinExpression(),e+=this.createWhereExpression(),e+=this.createGroupByExpression(),e+=this.createHavingExpression(),e+=this.createOrderByExpression(),e+=this.createLimitOffsetExpression(),e+=this.createLockExpression(),e=e.trim(),this.expressionMap.subQuery&&(e="("+e+")"),this.replacePropertyNamesForTheWholeQuery(e)}setFindOptions(e){return this.findOptions=e,this.applyFindOptions(),this}subQuery(){const e=this.createQueryBuilder();return e.expressionMap.subQuery=!0,e.parentQueryBuilder=this,e}select(e,t){if(this.expressionMap.queryType="select",Array.isArray(e))this.expressionMap.selects=e.map(r=>({selection:r}));else if(typeof e=="function"){const r=e(this.subQuery());this.setParameters(r.getParameters()),this.expressionMap.selects.push({selection:r.getQuery(),aliasName:t})}else e&&(this.expressionMap.selects=[{selection:e,aliasName:t}]);return this}addSelect(e,t){if(!e)return this;if(Array.isArray(e))this.expressionMap.selects=this.expressionMap.selects.concat(e.map(r=>({selection:r})));else if(typeof e=="function"){const r=e(this.subQuery());this.setParameters(r.getParameters()),this.expressionMap.selects.push({selection:r.getQuery(),aliasName:t})}else e&&this.expressionMap.selects.push({selection:e,aliasName:t});return this}maxExecutionTime(e){return this.expressionMap.maxExecutionTime=e,this}distinct(e=!0){return this.expressionMap.selectDistinct=e,this}distinctOn(e){return this.expressionMap.selectDistinctOn=e,this}fromDummy(){return this.from(this.connection.driver.dummyTableName??"(SELECT 1 AS dummy_column)","dummy_table")}from(e,t){const r=this.createFromAlias(e,t);return this.expressionMap.setMainAlias(r),this}addFrom(e,t){const r=this.createFromAlias(e,t);return this.expressionMap.mainAlias||this.expressionMap.setMainAlias(r),this}innerJoin(e,t,r,n){return this.join("INNER",e,t,r,n),this}leftJoin(e,t,r,n){return this.join("LEFT",e,t,r,n),this}innerJoinAndSelect(e,t,r,n){return this.addSelect(t),this.innerJoin(e,t,r,n),this}leftJoinAndSelect(e,t,r,n){return this.addSelect(t),this.leftJoin(e,t,r,n),this}innerJoinAndMapMany(e,t,r,n,i){return this.addSelect(r),this.join("INNER",t,r,n,i,e,!0),this}innerJoinAndMapOne(e,t,r,n,i,s){return this.addSelect(r),this.join("INNER",t,r,n,i,e,!1,s),this}leftJoinAndMapMany(e,t,r,n,i){return this.addSelect(r),this.join("LEFT",t,r,n,i,e,!0),this}leftJoinAndMapOne(e,t,r,n,i,s){return this.addSelect(r),this.join("LEFT",t,r,n,i,e,!1,s),this}loadRelationIdAndMap(e,t,r,n){const i=new yr(this.expressionMap);return i.mapToProperty=e,i.relationName=t,typeof r=="string"&&(i.alias=r),typeof r=="object"&&r.disableMixedMap&&(i.disableMixedMap=!0),i.queryBuilderFactory=n,this.expressionMap.relationIdAttributes.push(i),i.relation.junctionEntityMetadata&&this.expressionMap.createAlias({type:"other",name:i.junctionAlias,metadata:i.relation.junctionEntityMetadata}),this}loadRelationCountAndMap(e,t,r,n){const i=new mr(this.expressionMap);return i.mapToProperty=e,i.relationName=t,i.alias=r,i.queryBuilderFactory=n,this.expressionMap.relationCountAttributes.push(i),this.expressionMap.createAlias({type:"other",name:i.junctionAlias}),i.relation.junctionEntityMetadata&&this.expressionMap.createAlias({type:"other",name:i.junctionAlias,metadata:i.relation.junctionEntityMetadata}),this}loadAllRelationIds(e){return this.expressionMap.mainAlias.metadata.relations.forEach(t=>{e!==void 0&&e.relations!==void 0&&e.relations.indexOf(t.propertyPath)===-1||this.loadRelationIdAndMap(this.expressionMap.mainAlias.name+"."+t.propertyPath,this.expressionMap.mainAlias.name+"."+t.propertyPath,e)}),this}where(e,t){this.expressionMap.wheres=[];const r=this.getWhereCondition(e);return r&&(this.expressionMap.wheres=[{type:"simple",condition:r}]),t&&this.setParameters(t),this}andWhere(e,t){return this.expressionMap.wheres.push({type:"and",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}orWhere(e,t){return this.expressionMap.wheres.push({type:"or",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}whereExists(e){return this.where(...this.getExistsCondition(e))}andWhereExists(e){return this.andWhere(...this.getExistsCondition(e))}orWhereExists(e){return this.orWhere(...this.getExistsCondition(e))}whereInIds(e){return this.where(this.getWhereInIdsCondition(e))}andWhereInIds(e){return this.andWhere(this.getWhereInIdsCondition(e))}orWhereInIds(e){return this.orWhere(this.getWhereInIdsCondition(e))}having(e,t){return this.expressionMap.havings.push({type:"simple",condition:e}),t&&this.setParameters(t),this}andHaving(e,t){return this.expressionMap.havings.push({type:"and",condition:e}),t&&this.setParameters(t),this}orHaving(e,t){return this.expressionMap.havings.push({type:"or",condition:e}),t&&this.setParameters(t),this}groupBy(e){return e?this.expressionMap.groupBys=[e]:this.expressionMap.groupBys=[],this}addGroupBy(e){return this.expressionMap.groupBys.push(e),this}timeTravelQuery(e){return this.connection.driver.options.type==="cockroachdb"&&(e===void 0?this.expressionMap.timeTravel="follower_read_timestamp()":this.expressionMap.timeTravel=e),this}orderBy(e,t="ASC",r){if(t!==void 0&&t!=="ASC"&&t!=="DESC")throw new S('SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.');if(r!==void 0&&r!=="NULLS FIRST"&&r!=="NULLS LAST")throw new S('SelectQueryBuilder.addOrderBy "nulls" can accept only "NULLS FIRST" and "NULLS LAST" values.');return e?typeof e=="object"?this.expressionMap.orderBys=e:r?this.expressionMap.orderBys={[e]:{order:t,nulls:r}}:this.expressionMap.orderBys={[e]:t}:this.expressionMap.orderBys={},this}addOrderBy(e,t="ASC",r){if(t!==void 0&&t!=="ASC"&&t!=="DESC")throw new S('SelectQueryBuilder.addOrderBy "order" can accept only "ASC" and "DESC" values.');if(r!==void 0&&r!=="NULLS FIRST"&&r!=="NULLS LAST")throw new S('SelectQueryBuilder.addOrderBy "nulls" can accept only "NULLS FIRST" and "NULLS LAST" values.');return r?this.expressionMap.orderBys[e]={order:t,nulls:r}:this.expressionMap.orderBys[e]=t,this}limit(e){if(this.expressionMap.limit=this.normalizeNumber(e),this.expressionMap.limit!==void 0&&isNaN(this.expressionMap.limit))throw new S('Provided "limit" value is not a number. Please provide a numeric value.');return this}offset(e){if(this.expressionMap.offset=this.normalizeNumber(e),this.expressionMap.offset!==void 0&&isNaN(this.expressionMap.offset))throw new S('Provided "offset" value is not a number. Please provide a numeric value.');return this}take(e){if(this.expressionMap.take=this.normalizeNumber(e),this.expressionMap.take!==void 0&&isNaN(this.expressionMap.take))throw new S('Provided "take" value is not a number. Please provide a numeric value.');return this}skip(e){if(this.expressionMap.skip=this.normalizeNumber(e),this.expressionMap.skip!==void 0&&isNaN(this.expressionMap.skip))throw new S('Provided "skip" value is not a number. Please provide a numeric value.');return this}useIndex(e){return this.expressionMap.useIndex=e,this}setLock(e,t,r){return this.expressionMap.lockMode=e,this.expressionMap.lockVersion=t,this.expressionMap.lockTables=r,this}setOnLocked(e){return this.expressionMap.onLocked=e,this}withDeleted(){return this.expressionMap.withDeleted=!0,this}async getRawOne(){return(await this.getRawMany())[0]}async getRawMany(){if(this.expressionMap.lockMode==="optimistic")throw new De;this.expressionMap.queryEntity=!1;const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0);const r=await this.loadRawResults(e);return t&&await e.commitTransaction(),r}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}async getRawAndEntities(){const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.queryEntity=!0;const r=await this.executeEntitiesAndRawResults(e);return t&&await e.commitTransaction(),r}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}async getOne(){const t=(await this.getRawAndEntities()).entities[0];if(t&&this.expressionMap.lockMode==="optimistic"&&this.expressionMap.lockVersion){const r=this.expressionMap.mainAlias.metadata;if(this.expressionMap.lockVersion instanceof Date){const n=r.updateDateColumn.getEntityValue(t);if(n.getTime()!==this.expressionMap.lockVersion.getTime())throw new Pr(r.name,this.expressionMap.lockVersion,n)}else{const n=r.versionColumn.getEntityValue(t);if(n!==this.expressionMap.lockVersion)throw new Pr(r.name,this.expressionMap.lockVersion,n)}}return t===void 0?null:t}async getOneOrFail(){const e=await this.getOne();if(!e)throw new Qi(this.expressionMap.mainAlias.target,this.expressionMap.parameters);return e}async getMany(){if(this.expressionMap.lockMode==="optimistic")throw new De;return(await this.getRawAndEntities()).entities}async getCount(){if(this.expressionMap.lockMode==="optimistic")throw new De;const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.queryEntity=!1;const r=await this.executeCountQuery(e);return t&&await e.commitTransaction(),r}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}async getExists(){if(this.expressionMap.lockMode==="optimistic")throw new De;const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.queryEntity=!1;const r=await this.executeExistsQuery(e);return t&&await e.commitTransaction(),r}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}async getManyAndCount(){if(this.expressionMap.lockMode==="optimistic")throw new De;const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.queryEntity=!0;const r=await this.executeEntitiesAndRawResults(e);this.expressionMap.queryEntity=!1;let n=this.lazyCount(r);if(n===void 0){const s=this.expressionMap.cacheId;s&&(this.expressionMap.cacheId=`${s}-count`),n=await this.executeCountQuery(e)}const i=[r.entities,n];return t&&await e.commitTransaction(),i}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}lazyCount(e){const t=this.expressionMap.limit!==void 0&&this.expressionMap.limit!==null;if(this.expressionMap.joinAttributes.length>0&&t)return;const r=this.expressionMap.take!==void 0&&this.expressionMap.take!==null,n=t?this.expressionMap.limit:r?this.expressionMap.take:void 0;if(n!==void 0&&e.entities.length===n)return;const i=this.expressionMap.skip!==void 0&&this.expressionMap.skip!==null&&this.expressionMap.skip>0,s=this.expressionMap.offset!==void 0&&this.expressionMap.offset!==null&&this.expressionMap.offset>0;if(e.entities.length===0&&(i||s))return;const a=s?this.expressionMap.offset:i?this.expressionMap.skip:0;return e.entities.length+a}async stream(){this.expressionMap.queryEntity=!1;const[e,t]=this.getQueryAndParameters(),r=this.obtainQueryRunner();let n=!1;try{this.expressionMap.useTransaction===!0&&r.isTransactionActive===!1&&(await r.startTransaction(),n=!0);const i=()=>{if(r!==this.queryRunner)return r.release()},s=r.stream(e,t,i,i);return n&&await r.commitTransaction(),s}catch(i){if(n)try{await r.rollbackTransaction()}catch{}throw i}}cache(e,t){return typeof e=="boolean"?this.expressionMap.cache=e:typeof e=="number"?(this.expressionMap.cache=!0,this.expressionMap.cacheDuration=e):(typeof e=="string"||typeof e=="number")&&(this.expressionMap.cache=!0,this.expressionMap.cacheId=e),t&&(this.expressionMap.cacheDuration=t),this}setOption(e){return this.expressionMap.options.push(e),this}join(e,t,r,n,i,s,a,o){i&&this.setParameters(i);const c=new pi(this.connection,this.expressionMap);c.direction=e,c.mapAsEntity=o,c.mapToProperty=s,c.isMappingMany=a,c.entityOrProperty=t,c.condition=n,this.expressionMap.joinAttributes.push(c);const l=c.metadata;if(l){if(l.deleteDateColumn&&!this.expressionMap.withDeleted){const p=`${r}.${l.deleteDateColumn.propertyName} IS NULL`;c.condition=c.condition?` ${c.condition} AND ${p}`:`${p}`}c.alias=this.expressionMap.createAlias({type:"join",name:r,metadata:l}),c.relation&&c.relation.junctionEntityMetadata&&this.expressionMap.createAlias({type:"join",name:c.junctionAlias,metadata:c.relation.junctionEntityMetadata})}else{let p="";if(typeof t=="function"){const f=t(this.subQuery());this.setParameters(f.getParameters()),p=f.getQuery()}else p=t;const u=typeof t=="function"||t.substr(0,1)==="("&&t.substr(-1)===")";c.alias=this.expressionMap.createAlias({type:"join",name:r,tablePath:u===!1?t:void 0,subQuery:u===!0?p:void 0})}}createSelectExpression(){if(!this.expressionMap.mainAlias)throw new S("Cannot build query because main alias is not set (call qb#from method)");const e=[],t=[];if(this.expressionMap.mainAlias.hasMetadata){const a=this.expressionMap.mainAlias.metadata;e.push(...this.buildEscapedEntityColumnSelects(this.expressionMap.mainAlias.name,a)),t.push(...this.findEntityColumnSelects(this.expressionMap.mainAlias.name,a))}this.expressionMap.joinAttributes.forEach(a=>{if(a.metadata)e.push(...this.buildEscapedEntityColumnSelects(a.alias.name,a.metadata)),t.push(...this.findEntityColumnSelects(a.alias.name,a.metadata));else if(this.expressionMap.selects.some(c=>c.selection===a.alias.name)){e.push({selection:this.escape(a.alias.name)+".*"});const c=this.expressionMap.selects.find(l=>l.selection===a.alias.name);t.push(c)}}),this.expressionMap.selects.filter(a=>t.indexOf(a)===-1).forEach(a=>e.push({selection:this.replacePropertyNames(a.selection),aliasName:a.aliasName})),e.length===0&&e.push({selection:"*"});let r="";this.expressionMap.useIndex&&$.isMySQLFamily(this.connection.driver)&&(r=` USE INDEX (${this.expressionMap.useIndex})`);const n=this.expressionMap.aliases.filter(a=>a.type==="from"&&(a.tablePath||a.subQuery)).map(a=>a.subQuery?a.subQuery+" "+this.escape(a.name):this.getTableName(a.tablePath)+" "+this.escape(a.name)),i=this.createSelectDistinctExpression(),s=e.map(a=>a.selection+(a.aliasName?" AS "+this.escape(a.aliasName):"")).join(", ");return i+s+" FROM "+n.join(", ")+this.createTableLockExpression()+r}createSelectDistinctExpression(){const{selectDistinct:e,selectDistinctOn:t,maxExecutionTime:r}=this.expressionMap,{driver:n}=this.connection;let i="SELECT ";return r>0&&$.isMySQLFamily(n)&&(i+=`/*+ MAX_EXECUTION_TIME(${this.expressionMap.maxExecutionTime}) */ `),$.isPostgresFamily(n)&&t.length>0?i=`SELECT DISTINCT ON (${t.map(a=>this.replacePropertyNames(a)).join(", ")}) `:e&&(i="SELECT DISTINCT "),i}createJoinExpression(){return this.expressionMap.joinAttributes.map(t=>{const r=t.relation,n=t.tablePath,i=t.alias.name;let s=t.condition?" AND ("+t.condition+")":"";const a=t.parentAlias;if(!a||!r){const o=t.alias.subQuery?t.alias.subQuery:this.getTableName(n);return" "+t.direction+" JOIN "+o+" "+this.escape(i)+this.createTableLockExpression()+(t.condition?" ON "+this.replacePropertyNames(t.condition):"")}if(r.isManyToOne||r.isOneToOneOwner){const o=r.joinColumns.map(c=>i+"."+c.referencedColumn.propertyPath+"="+a+"."+r.propertyPath+"."+c.referencedColumn.propertyPath).join(" AND ");return" "+t.direction+" JOIN "+this.getTableName(n)+" "+this.escape(i)+this.createTableLockExpression()+" ON "+this.replacePropertyNames(o+s)}else if(r.isOneToMany||r.isOneToOneNotOwner){const o=r.inverseRelation.joinColumns.map(c=>(r.inverseEntityMetadata.tableType==="entity-child"&&r.inverseEntityMetadata.discriminatorColumn&&(s+=" AND "+i+"."+r.inverseEntityMetadata.discriminatorColumn.databaseName+"='"+r.inverseEntityMetadata.discriminatorValue+"'"),i+"."+r.inverseRelation.propertyPath+"."+c.referencedColumn.propertyPath+"="+a+"."+c.referencedColumn.propertyPath)).join(" AND ");if(!o)throw new S(`Relation ${r.entityMetadata.name}.${r.propertyName} does not have join columns.`);return" "+t.direction+" JOIN "+this.getTableName(n)+" "+this.escape(i)+this.createTableLockExpression()+" ON "+this.replacePropertyNames(o+s)}else{const o=r.junctionEntityMetadata.tablePath,c=t.junctionAlias;let l="",p="";return r.isOwning?(l=r.joinColumns.map(u=>c+"."+u.propertyPath+"="+a+"."+u.referencedColumn.propertyPath).join(" AND "),p=r.inverseJoinColumns.map(u=>i+"."+u.referencedColumn.propertyPath+"="+c+"."+u.propertyPath).join(" AND ")):(l=r.inverseRelation.inverseJoinColumns.map(u=>c+"."+u.propertyPath+"="+a+"."+u.referencedColumn.propertyPath).join(" AND "),p=r.inverseRelation.joinColumns.map(u=>i+"."+u.referencedColumn.propertyPath+"="+c+"."+u.propertyPath).join(" AND "))," "+t.direction+" JOIN "+this.getTableName(o)+" "+this.escape(c)+this.createTableLockExpression()+" ON "+this.replacePropertyNames(l)+" "+t.direction+" JOIN "+this.getTableName(n)+" "+this.escape(i)+this.createTableLockExpression()+" ON "+this.replacePropertyNames(p+s)}}).join(" ")}createGroupByExpression(){return!this.expressionMap.groupBys||!this.expressionMap.groupBys.length?"":" GROUP BY "+this.replacePropertyNames(this.expressionMap.groupBys.join(", "))}createOrderByExpression(){const e=this.expressionMap.allOrderBys;return Object.keys(e).length===0?"":" ORDER BY "+Object.keys(e).map(t=>{const r=typeof e[t]=="string"?e[t]:e[t].order+" "+e[t].nulls,n=this.expressionMap.selects.find(i=>i.selection===t);if(n&&!n.aliasName&&t.indexOf(".")!==-1){const i=t.split("."),s=i[0],a=i.slice(1).join("."),o=this.expressionMap.aliases.find(c=>c.name===s);if(o){const c=o.metadata.findColumnWithPropertyPath(a);if(c){const l=$.buildAlias(this.connection.driver,void 0,s,c.databaseName);return this.escape(l)+" "+r}}}return this.replacePropertyNames(t)+" "+r}).join(", ")}createLimitOffsetExpression(){let e=this.expressionMap.offset,t=this.expressionMap.limit;e===void 0&&t===void 0&&this.expressionMap.joinAttributes.length===0&&(e=this.expressionMap.skip,t=this.expressionMap.take);const r=t!=null,n=e!=null;if(this.connection.driver.options.type==="mssql"){let i="";if((r||n)&&Object.keys(this.expressionMap.allOrderBys).length<=0&&(i=" ORDER BY (SELECT NULL)"),r&&n)return i+" OFFSET "+e+" ROWS FETCH NEXT "+t+" ROWS ONLY";if(r)return i+" OFFSET 0 ROWS FETCH NEXT "+t+" ROWS ONLY";if(n)return i+" OFFSET "+e+" ROWS"}else if($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql"||this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner"){if(r&&n)return" LIMIT "+t+" OFFSET "+e;if(r)return" LIMIT "+t;if(n)throw new zi}else if($.isSQLiteFamily(this.connection.driver)){if(r&&n)return" LIMIT "+t+" OFFSET "+e;if(r)return" LIMIT "+t;if(n)return" LIMIT -1 OFFSET "+e}else if(this.connection.driver.options.type==="oracle"){if(r&&n)return" OFFSET "+e+" ROWS FETCH NEXT "+t+" ROWS ONLY";if(r)return" FETCH NEXT "+t+" ROWS ONLY";if(n)return" OFFSET "+e+" ROWS"}else{if(r&&n)return" LIMIT "+t+" OFFSET "+e;if(r)return" LIMIT "+t;if(n)return" OFFSET "+e}return""}createTableLockExpression(){if(this.connection.driver.options.type==="mssql")switch(this.expressionMap.lockMode){case"pessimistic_read":return" WITH (HOLDLOCK, ROWLOCK)";case"pessimistic_write":return" WITH (UPDLOCK, ROWLOCK)";case"dirty_read":return" WITH (NOLOCK)"}return""}createLockExpression(){const e=this.connection.driver;let t="";if(this.expressionMap.lockTables){if(!($.isPostgresFamily(e)||e.options.type==="cockroachdb"))throw new S("Lock tables not supported in selected driver");if(this.expressionMap.lockTables.length<1)throw new S("lockTables cannot be an empty array");t=" OF "+this.expressionMap.lockTables.join(", ")}let r="";switch(this.expressionMap.onLocked==="nowait"?r=" NOWAIT":this.expressionMap.onLocked==="skip_locked"&&(r=" SKIP LOCKED"),this.expressionMap.lockMode){case"pessimistic_read":if(e.options.type==="mysql"||e.options.type==="aurora-mysql")return $.isReleaseVersionOrGreater(e,"8.0.0")?" FOR SHARE"+t+r:" LOCK IN SHARE MODE";if(e.options.type==="mariadb")return" LOCK IN SHARE MODE";if($.isPostgresFamily(e))return" FOR SHARE"+t+r;if(e.options.type==="oracle")return" FOR UPDATE";if(e.options.type==="mssql")return"";throw new $e;case"pessimistic_write":if($.isMySQLFamily(e)||e.options.type==="aurora-mysql"||e.options.type==="oracle")return" FOR UPDATE"+r;if($.isPostgresFamily(e)||e.options.type==="cockroachdb")return" FOR UPDATE"+t+r;if(e.options.type==="mssql")return"";throw new $e;case"pessimistic_partial_write":if($.isPostgresFamily(e))return" FOR UPDATE"+t+" SKIP LOCKED";if($.isMySQLFamily(e))return" FOR UPDATE SKIP LOCKED";throw new $e;case"pessimistic_write_or_fail":if($.isPostgresFamily(e)||e.options.type==="cockroachdb")return" FOR UPDATE"+t+" NOWAIT";if($.isMySQLFamily(e))return" FOR UPDATE NOWAIT";throw new $e;case"for_no_key_update":if($.isPostgresFamily(e)||e.options.type==="cockroachdb")return" FOR NO KEY UPDATE"+t+r;throw new $e;case"for_key_share":if($.isPostgresFamily(e))return" FOR KEY SHARE"+t+r;throw new $e;default:return""}}createHavingExpression(){if(!this.expressionMap.havings||!this.expressionMap.havings.length)return"";const e=this.expressionMap.havings.map((t,r)=>{switch(t.type){case"and":return(r>0?"AND ":"")+this.replacePropertyNames(t.condition);case"or":return(r>0?"OR ":"")+this.replacePropertyNames(t.condition);default:return this.replacePropertyNames(t.condition)}}).join(" ");return e.length?" HAVING "+e:""}buildEscapedEntityColumnSelects(e,t){const r=this.expressionMap.selects.some(c=>c.selection===e),n=[];if(r&&n.push(...t.columns.filter(c=>c.isSelect===!0)),n.push(...t.columns.filter(c=>this.expressionMap.selects.some(l=>l.selection===e+"."+c.propertyPath))),n.length===0)return[];const i=this.expressionMap.queryEntity?t.primaryColumns.filter(c=>n.indexOf(c)===-1):[],s=[...n,...i],a=[],o=this.escape(e);return s.forEach(c=>{let l=o+"."+this.escape(c.databaseName);c.isVirtualProperty&&c.query&&(l=`(${c.query(o)})`),this.connection.driver.spatialTypes.indexOf(c.type)!==-1&&(($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")&&(l=`${this.connection.driver.options.legacySpatialSupport?"AsText":"ST_AsText"}(${l})`),$.isPostgresFamily(this.connection.driver)&&(c.precision?l=`ST_AsGeoJSON(${l}, ${c.precision})::json`:l=`ST_AsGeoJSON(${l})::json`),this.connection.driver.options.type==="mssql"&&(l=`${l}.ToString()`));const p=this.expressionMap.selects.filter(u=>u.selection===e+"."+c.propertyPath);p.length?p.forEach(u=>{a.push({selection:l,aliasName:u.aliasName?u.aliasName:$.buildAlias(this.connection.driver,void 0,e,c.databaseName),virtual:u.virtual})}):a.push({selection:l,aliasName:$.buildAlias(this.connection.driver,void 0,e,c.databaseName),virtual:r})}),a}findEntityColumnSelects(e,t){return this.expressionMap.selects.filter(r=>r.selection===e||t.columns.some(n=>r.selection===e+"."+n.propertyPath))}computeCountExpression(){const e=this.expressionMap.mainAlias.name,r=this.expressionMap.mainAlias.metadata.primaryColumns,n=this.escape(e);if(this.expressionMap.joinAttributes.length===0&&this.expressionMap.relationIdAttributes.length===0&&this.expressionMap.relationCountAttributes.length===0)return"COUNT(1)";if(this.connection.driver.options.type==="cockroachdb"||$.isPostgresFamily(this.connection.driver))return"COUNT(DISTINCT("+r.map(i=>`${n}.${this.escape(i.databaseName)}`).join(", ")+"))";if($.isMySQLFamily(this.connection.driver))return"COUNT(DISTINCT "+r.map(i=>`${n}.${this.escape(i.databaseName)}`).join(", ")+")";if(this.connection.driver.options.type==="mssql"){const i=r.map(s=>`${n}.${this.escape(s.databaseName)}`).join(", '|;|', ");return r.length===1?`COUNT(DISTINCT(${i}))`:`COUNT(DISTINCT(CONCAT(${i})))`}return this.connection.driver.options.type==="spanner"?r.length===1?`COUNT(DISTINCT(${n}.${this.escape(r[0].databaseName)}))`:`COUNT(DISTINCT(CONCAT(${r.map(s=>`CAST(${n}.${this.escape(s.databaseName)} AS STRING)`).join(", '|;|', ")})))`:"COUNT(DISTINCT("+r.map(i=>`${n}.${this.escape(i.databaseName)}`).join(" || '|;|' || ")+"))"}async executeCountQuery(e){const t=this.computeCountExpression(),r=await this.clone().orderBy().groupBy().offset(void 0).limit(void 0).skip(void 0).take(void 0).select(t,"cnt").setOption("disable-global-order").loadRawResults(e);return!r||!r[0]||!r[0].cnt?0:parseInt(r[0].cnt)}async executeExistsQuery(e){return(await this.connection.createQueryBuilder().fromDummy().select("1","row_exists").whereExists(this).limit(1).loadRawResults(e)).length>0}applyFindOptions(){if(this.expressionMap.mainAlias.metadata){if(this.findOptions.relationLoadStrategy&&(this.expressionMap.relationLoadStrategy=this.findOptions.relationLoadStrategy),this.findOptions.comment&&this.comment(this.findOptions.comment),this.findOptions.withDeleted&&this.withDeleted(),this.findOptions.select){const e=Array.isArray(this.findOptions.select)?ee.propertyPathsToTruthyObject(this.findOptions.select):this.findOptions.select;this.buildSelect(e,this.expressionMap.mainAlias.metadata,this.expressionMap.mainAlias.name)}if(this.selects.length&&this.select(this.selects),this.selects=[],this.findOptions.relations){const e=Array.isArray(this.findOptions.relations)?ee.propertyPathsToTruthyObject(this.findOptions.relations):this.findOptions.relations;this.buildRelations(e,typeof this.findOptions.select=="object"?this.findOptions.select:void 0,this.expressionMap.mainAlias.metadata,this.expressionMap.mainAlias.name),this.findOptions.loadEagerRelations!==!1&&this.expressionMap.relationLoadStrategy==="join"&&this.buildEagerRelations(e,typeof this.findOptions.select=="object"?this.findOptions.select:void 0,this.expressionMap.mainAlias.metadata,this.expressionMap.mainAlias.name)}if(this.selects.length&&this.addSelect(this.selects),this.findOptions.where&&(this.conditions=this.buildWhere(this.findOptions.where,this.expressionMap.mainAlias.metadata,this.expressionMap.mainAlias.name),this.conditions.length&&this.andWhere(this.conditions.substr(0,1)!=="("?"("+this.conditions+")":this.conditions)),this.findOptions.order&&this.buildOrder(this.findOptions.order,this.expressionMap.mainAlias.metadata,this.expressionMap.mainAlias.name),this.joins.length&&this.joins.forEach(e=>{e.select&&!e.selection?e.type==="inner"?this.innerJoinAndSelect(`${e.parentAlias}.${e.relationMetadata.propertyPath}`,e.alias):this.leftJoinAndSelect(`${e.parentAlias}.${e.relationMetadata.propertyPath}`,e.alias):e.type==="inner"?this.innerJoin(`${e.parentAlias}.${e.relationMetadata.propertyPath}`,e.alias):this.leftJoin(`${e.parentAlias}.${e.relationMetadata.propertyPath}`,e.alias)}),this.findOptions.skip!==void 0&&this.skip(this.findOptions.skip),this.findOptions.take!==void 0&&this.take(this.findOptions.take),typeof this.findOptions.cache=="number"?this.cache(this.findOptions.cache):typeof this.findOptions.cache=="boolean"?this.cache(this.findOptions.cache):typeof this.findOptions.cache=="object"&&this.cache(this.findOptions.cache.id,this.findOptions.cache.milliseconds),this.findOptions.join&&(this.findOptions.join.leftJoin&&Object.keys(this.findOptions.join.leftJoin).forEach(e=>{this.leftJoin(this.findOptions.join.leftJoin[e],e)}),this.findOptions.join.innerJoin&&Object.keys(this.findOptions.join.innerJoin).forEach(e=>{this.innerJoin(this.findOptions.join.innerJoin[e],e)}),this.findOptions.join.leftJoinAndSelect&&Object.keys(this.findOptions.join.leftJoinAndSelect).forEach(e=>{this.leftJoinAndSelect(this.findOptions.join.leftJoinAndSelect[e],e)}),this.findOptions.join.innerJoinAndSelect&&Object.keys(this.findOptions.join.innerJoinAndSelect).forEach(e=>{this.innerJoinAndSelect(this.findOptions.join.innerJoinAndSelect[e],e)})),this.findOptions.lock){if(this.findOptions.lock.mode==="optimistic")this.setLock(this.findOptions.lock.mode,this.findOptions.lock.version);else if(this.findOptions.lock.mode==="pessimistic_read"||this.findOptions.lock.mode==="pessimistic_write"||this.findOptions.lock.mode==="dirty_read"||this.findOptions.lock.mode==="pessimistic_partial_write"||this.findOptions.lock.mode==="pessimistic_write_or_fail"||this.findOptions.lock.mode==="for_no_key_update"||this.findOptions.lock.mode==="for_key_share"){const e=this.findOptions.lock.tables?this.findOptions.lock.tables.map(t=>{const r=this.expressionMap.aliases.find(n=>n.metadata.tableNameWithoutPrefix===t);if(!r)throw new S(`"${t}" is not part of this query`);return this.escape(r.name)}):void 0;this.setLock(this.findOptions.lock.mode,void 0,e),this.findOptions.lock.onLocked&&this.setOnLocked(this.findOptions.lock.onLocked)}}this.findOptions.loadRelationIds===!0?this.loadAllRelationIds():typeof this.findOptions.loadRelationIds=="object"&&this.loadAllRelationIds(this.findOptions.loadRelationIds),this.findOptions.loadEagerRelations!==!1&&vr.joinEagerRelations(this,this.expressionMap.mainAlias.name,this.expressionMap.mainAlias.metadata),this.findOptions.transaction===!0&&(this.expressionMap.useTransaction=!0)}}concatRelationMetadata(e){this.relationMetadatas.push(e)}async executeEntitiesAndRawResults(e){if(!this.expressionMap.mainAlias)throw new S('Alias is not set. Use "from" method to set an alias.');if((this.expressionMap.lockMode==="pessimistic_read"||this.expressionMap.lockMode==="pessimistic_write"||this.expressionMap.lockMode==="pessimistic_partial_write"||this.expressionMap.lockMode==="pessimistic_write_or_fail"||this.expressionMap.lockMode==="for_no_key_update"||this.expressionMap.lockMode==="for_key_share")&&!e.isTransactionActive)throw new Ki;if(this.expressionMap.lockMode==="optimistic"){const o=this.expressionMap.mainAlias.metadata;if(!o.versionColumn&&!o.updateDateColumn)throw new Ji(o.name)}const t=new ra(this.connection,e,this.expressionMap.relationIdAttributes),r=new sa(this.connection,e,this.expressionMap.relationCountAttributes);new ia(this.expressionMap).transform(),new aa(this.expressionMap).transform();let s=[],a=[];if((this.expressionMap.skip||this.expressionMap.take)&&this.expressionMap.joinAttributes.length>0){const[o,c]=this.createOrderByCombinedWithSelectExpression("distinctAlias"),l=this.expressionMap.mainAlias.metadata,p=this.expressionMap.mainAlias.name,u=l.primaryColumns.map(d=>{const m=this.escape("distinctAlias"),b=this.escape($.buildAlias(this.connection.driver,void 0,p,d.databaseName));c[b]||(c[b]="ASC");const A=$.buildAlias(this.connection.driver,void 0,"ids_"+p,d.databaseName);return`${m}.${b} AS ${this.escape(A)}`}),f=this.clone(),y=f.expressionMap.timeTravel;if(s=await new xr(this.connection,e).select(`DISTINCT ${u.join(", ")}`).addSelect(o).from(`(${f.orderBy().timeTravelQuery(!1).getQuery()})`,"distinctAlias").timeTravelQuery(y).offset(this.expressionMap.skip).limit(this.expressionMap.take).orderBy(c).cache(this.expressionMap.cache&&this.expressionMap.cacheId?`${this.expressionMap.cacheId}-pagination`:this.expressionMap.cache,this.expressionMap.cacheDuration).setParameters(this.getParameters()).setNativeParameters(this.expressionMap.nativeParameters).getRawMany(),s.length>0){let d="";const m={};if(l.hasMultiplePrimaryKeys)d=s.map((b,A)=>l.primaryColumns.map(x=>{const I=`orm_distinct_ids_${A}_${x.databaseName}`,F=$.buildAlias(this.connection.driver,void 0,"ids_"+p,x.databaseName);return m[I]=b[F],`${p}.${x.propertyPath}=:${I}`}).join(" AND ")).join(" OR ");else{const b=$.buildAlias(this.connection.driver,void 0,"ids_"+p,l.primaryColumns[0].databaseName),A=s.map(I=>I[b]);A.every(I=>typeof I=="number")?d=`${p}.${l.primaryColumns[0].propertyPath} IN (${A.join(", ")})`:(m.orm_distinct_ids=A,d=p+"."+l.primaryColumns[0].propertyPath+" IN (:...orm_distinct_ids)")}s=await this.clone().mergeExpressionMap({extraAppendedAndWhereCondition:d}).setParameters(m).loadRawResults(e)}}else s=await this.loadRawResults(e);if(s.length>0){const o=await t.load(s),c=await r.load(s);a=new ta(this.expressionMap,this.connection.driver,o,c,this.queryRunner).transform(s,this.expressionMap.mainAlias),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&await e.broadcaster.broadcast("Load",this.expressionMap.mainAlias.metadata,a)}if(this.expressionMap.relationLoadStrategy==="query"){const o=new na(this.connection,e);await Promise.all(this.relationMetadatas.map(async c=>{const l=c.inverseEntityMetadata.target,p=c.inverseEntityMetadata.targetName,u=Array.isArray(this.findOptions.select)?ee.propertyPathsToTruthyObject(this.findOptions.select):this.findOptions.select,f=Array.isArray(this.findOptions.relations)?ee.propertyPathsToTruthyObject(this.findOptions.relations):this.findOptions.relations,y=this.createQueryBuilder(e).select(p).from(l,p).setFindOptions({select:u?ee.deepValue(u,c.propertyPath):void 0,order:this.findOptions.order?ee.deepValue(this.findOptions.order,c.propertyPath):void 0,relations:f?ee.deepValue(f,c.propertyPath):void 0,withDeleted:this.findOptions.withDeleted,relationLoadStrategy:this.findOptions.relationLoadStrategy});if(a.length>0){const d=await o.loadManyToManyRelationIdsAndGroup(c,a,void 0,y);a.forEach(m=>{const b=d.find(A=>A.entity===m);if(b){const A=b.related===void 0?null:b.related;c.setEntityValue(m,A)}})}}))}return{raw:s,entities:a}}createOrderByCombinedWithSelectExpression(e){const t=this.expressionMap.allOrderBys,r=Object.keys(t).map(i=>{if(i.indexOf(".")!==-1){const s=i.split("."),a=s[0],o=s.slice(1).join("."),l=this.expressionMap.findAliasByName(a).metadata.findColumnWithPropertyPath(o);return this.escape(e)+"."+this.escape($.buildAlias(this.connection.driver,void 0,a,l.databaseName))}else return this.expressionMap.selects.find(s=>s.selection===i||s.aliasName===i)?this.escape(e)+"."+this.escape(i):""}).join(", "),n={};return Object.keys(t).forEach(i=>{if(i.indexOf(".")!==-1){const s=i.split("."),a=s[0],o=s.slice(1).join("."),l=this.expressionMap.findAliasByName(a).metadata.findColumnWithPropertyPath(o);n[this.escape(e)+"."+this.escape($.buildAlias(this.connection.driver,void 0,a,l.databaseName))]=t[i]}else this.expressionMap.selects.find(s=>s.selection===i||s.aliasName===i)?n[this.escape(e)+"."+this.escape(i)]=t[i]:n[i]=t[i]}),[r,n]}async loadRawResults(e){const[t,r]=this.getQueryAndParameters(),n=t+" -- PARAMETERS: "+JSON.stringify(r,(l,p)=>typeof p=="bigint"?p.toString():p),i=typeof this.connection.options.cache=="object"?this.connection.options.cache:{};let s;const a=i.alwaysEnabled&&this.expressionMap.cache!==!1||this.expressionMap.cache===!0;let o=!1;if(this.connection.queryResultCache&&a)try{if(s=await this.connection.queryResultCache.getFromCache({identifier:this.expressionMap.cacheId,query:n,duration:this.expressionMap.cacheDuration||i.duration||1e3},e),s&&!this.connection.queryResultCache.isExpired(s))return JSON.parse(s.result)}catch(l){if(!i.ignoreErrors)throw l;o=!0}const c=await e.query(t,r,!0);if(!o&&this.connection.queryResultCache&&a)try{await this.connection.queryResultCache.storeInCache({identifier:this.expressionMap.cacheId,query:n,time:Date.now(),duration:this.expressionMap.cacheDuration||i.duration||1e3,result:JSON.stringify(c.records)},s,e)}catch(l){if(!i.ignoreErrors)throw l}return c.records}mergeExpressionMap(e){return fe.assign(this.expressionMap,e),this}normalizeNumber(e){return typeof e=="number"||e===void 0||e===null?e:Number(e)}obtainQueryRunner(){return this.queryRunner||this.connection.createQueryRunner(this.connection.defaultReplicationModeForReads())}buildSelect(e,t,r,n){for(const i in e){if(e[i]===void 0||e[i]===!1)continue;const s=n?n+"."+i:i,a=t.findColumnWithPropertyPathStrict(s),o=t.findEmbeddedWithPropertyPath(s),c=t.findRelationWithPropertyPath(s);if(!o&&!a&&!c)throw new Ce(s,t);a?this.selects.push(r+"."+s):o&&this.buildSelect(e[i],t,r,s)}}buildRelations(e,t,r,n,i){e&&Object.keys(e).forEach(s=>{const a=e[s],o=i?i+"."+s:s,c=r.findEmbeddedWithPropertyPath(o),l=r.findRelationWithPropertyPath(o);if(!c&&!l)throw new Ce(o,r);if(c)this.buildRelations(a,typeof t=="object"?ee.deepValue(t,c.propertyPath):void 0,r,n,o);else if(l){let p=n+"_"+o.replace(".","_");p=$.buildAlias(this.connection.driver,{joiner:"__"},n,p),(a===!0||typeof a=="object")&&(this.expressionMap.relationLoadStrategy==="query"?this.concatRelationMetadata(l):(this.joins.push({type:"left",select:!0,selection:t&&typeof t[s]=="object"?t[s]:void 0,alias:p,parentAlias:n,relationMetadata:l}),t&&typeof t[s]=="object"&&this.buildSelect(t[s],l.inverseEntityMetadata,p))),typeof a=="object"&&this.expressionMap.relationLoadStrategy==="join"&&this.buildRelations(a,typeof t=="object"?ee.deepValue(t,l.propertyPath):void 0,l.inverseEntityMetadata,p,void 0)}})}buildEagerRelations(e,t,r,n,i){e&&Object.keys(e).forEach(s=>{const a=e[s],o=i?i+"."+s:s,c=r.findEmbeddedWithPropertyPath(o),l=r.findRelationWithPropertyPath(o);if(!c&&!l)throw new Ce(o,r);if(c)this.buildEagerRelations(a,typeof t=="object"?ee.deepValue(t,c.propertyPath):void 0,r,n,o);else if(l){let p=n+"_"+o.replace(".","_");p=$.buildAlias(this.connection.driver,{joiner:"__"},n,p),(a===!0||typeof a=="object")&&l.inverseEntityMetadata.eagerRelations.forEach(u=>{let f=p+"_"+u.propertyPath.replace(".","_");f=$.buildAlias(this.connection.driver,{joiner:"__"},p,f),this.joins.find(d=>d.alias===f)||this.joins.push({type:"left",select:!0,alias:f,parentAlias:p,selection:void 0,relationMetadata:u}),t&&typeof t[s]=="object"&&this.buildSelect(t[s],l.inverseEntityMetadata,p)}),typeof a=="object"&&this.buildEagerRelations(a,typeof t=="object"?ee.deepValue(t,l.propertyPath):void 0,l.inverseEntityMetadata,p,void 0)}})}buildOrder(e,t,r,n){for(const i in e){if(e[i]===void 0)continue;const s=n?n+"."+i:i,a=t.findColumnWithPropertyPathStrict(s),o=t.findEmbeddedWithPropertyPath(s),c=t.findRelationWithPropertyPath(s);if(!o&&!a&&!c)throw new Ce(s,t);if(a){let l=typeof e[i]=="object"?e[i].direction:e[i];l=l==="DESC"||l==="desc"||l===-1?"DESC":"ASC";let p=typeof e[i]=="object"?e[i].nulls:void 0;p=p?.toLowerCase()==="first"?"NULLS FIRST":p?.toLowerCase()==="last"?"NULLS LAST":void 0;const u=`${r}.${s}`;this.addOrderBy(u,l,p)}else if(o)this.buildOrder(e[i],t,r,s);else if(c){let l=r+"_"+s.replace(".","_");l=$.buildAlias(this.connection.driver,{joiner:"__"},r,l),this.joins.find(u=>u.alias===l)||this.joins.push({type:"left",select:!1,alias:l,parentAlias:r,selection:void 0,relationMetadata:c}),this.buildOrder(e[i],c.inverseEntityMetadata,l)}}}buildWhere(e,t,r,n){let i="";if(Array.isArray(e))e.length&&(i=e.map(s=>this.buildWhere(s,t,r,n)).filter(s=>!!s).map(s=>"("+s+")").join(" OR "));else{const s=[];for(const a in e){let o=e[a];const c=n?n+"."+a:a,l=t.findColumnWithPropertyPathStrict(c),p=t.findEmbeddedWithPropertyPath(c),u=t.findRelationWithPropertyPath(c);if(!p&&!l&&!u)throw new Ce(c,t);if(o===void 0){if((this.connection.options.invalidWhereValuesBehavior?.undefined||"ignore")==="throw")throw new S(`Undefined value encountered in property '${r}.${a}' of a where condition. Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`);continue}if(o===null){const f=this.connection.options.invalidWhereValuesBehavior?.null||"ignore";if(f==="ignore")continue;if(f==="throw")throw new S(`Null value encountered in property '${r}.${a}' of a where condition. To match with SQL NULL, the IsNull() operator must be used. Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`)}if(l){let f=`${r}.${c}`;if(l.isVirtualProperty&&l.query&&(f=`(${l.query(this.escape(r))})`),o===null){s.push(`${f} IS NULL`);continue}oe.isEqualOperator(e[a])&&(o=e[a].value),l.transformer&&(o instanceof Ue?o.transformValue(l.transformer):o=cr.transformTo(l.transformer,o)),this.connection.driver.options.type==="mssql"&&(o=this.connection.driver.parametrizeValues(l,o)),s.push(this.createWhereConditionExpression(this.getWherePredicateCondition(f,o)))}else if(p){const f=this.buildWhere(e[a],t,r,c);f&&s.push(f)}else if(u){if(e[a]===null){const f=this.connection.options.invalidWhereValuesBehavior?.null||"ignore";if(f==="sql-null")s.push(`${r}.${c} IS NULL`);else if(f==="throw")throw new S(`Null value encountered in property '${r}.${a}' of a where condition. Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`);continue}if(typeof e[a]=="object"&&Object.keys(e[a]).every(y=>e[a][y]===void 0))continue;if(oe.isFindOperator(e[a]))if(e[a].type==="moreThan"||e[a].type==="lessThan"||e[a].type==="moreThanOrEqual"||e[a].type==="lessThanOrEqual"){let f="";e[a].type==="moreThan"?f=">":e[a].type==="lessThan"?f="<":e[a].type==="moreThanOrEqual"?f=">=":e[a].type==="lessThanOrEqual"&&(f="<=");const y=this.subQuery();if(u.isManyToManyOwner)y.select("COUNT(*)").from(u.joinTableName,u.joinTableName).where(u.joinColumns.map(d=>`${u.joinTableName}.${d.propertyName} = ${r}.${d.referencedColumn.propertyName}`).join(" AND "));else if(u.isManyToManyNotOwner)y.select("COUNT(*)").from(u.inverseRelation.joinTableName,u.inverseRelation.joinTableName).where(u.inverseRelation.inverseJoinColumns.map(d=>`${u.inverseRelation.joinTableName}.${d.propertyName} = ${r}.${d.referencedColumn.propertyName}`).join(" AND "));else if(u.isOneToMany)y.select("COUNT(*)").from(u.inverseEntityMetadata.target,u.inverseEntityMetadata.tableName).where(u.inverseRelation.joinColumns.map(d=>`${u.inverseEntityMetadata.tableName}.${d.propertyName} = ${r}.${d.referencedColumn.propertyName}`).join(" AND "));else throw new Error("This relation isn't supported by given find operator");this.andWhere(y.getSql()+" "+f+" "+parseInt(e[a].value))}else if(u.isManyToOne||u.isOneToOne&&u.isOneToOneOwner){const f=`${r}.${c}`;s.push(this.createWhereConditionExpression(this.getWherePredicateCondition(f,e[a])))}else throw new Error("This relation isn't supported by given find operator");else{let f=r+"_"+u.propertyPath.replace(".","_");f=$.buildAlias(this.connection.driver,{joiner:"__"},r,f),this.joins.find(m=>m.alias===f)||this.joins.push({type:"left",select:!1,selection:void 0,alias:f,parentAlias:r,relationMetadata:u});const d=this.buildWhere(e[a],u.inverseEntityMetadata,f);d&&s.push(d)}}}i=s.length?"("+s.join(") AND (")+")":s.join(" AND ")}return i.length?"("+i+")":i}}class hi{constructor(){this.generatedMaps=[]}static from(e){const t=new this;return t.raw=e.records,t.affected=e.affected,t}}class oa extends le{constructor(e,t){super(e,t),this["@instanceof"]=Symbol.for("SoftDeleteQueryBuilder"),this.expressionMap.aliasNamePrefixingEnabled=!1}getQuery(){let e=this.createUpdateExpression();return e+=this.createCteExpression(),e+=this.createOrderByExpression(),e+=this.createLimitExpression(),this.replacePropertyNamesForTheWholeQuery(e.trim())}async execute(){const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&(this.expressionMap.queryType==="soft-delete"?await e.broadcaster.broadcast("BeforeSoftRemove",this.expressionMap.mainAlias.metadata):this.expressionMap.queryType==="restore"&&await e.broadcaster.broadcast("BeforeRecover",this.expressionMap.mainAlias.metadata));const r=new br(e,this.expressionMap);this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&this.expressionMap.whereEntities.length>0&&(this.expressionMap.extraReturningColumns=r.getSoftDeletionReturningColumns());const[n,i]=this.getQueryAndParameters(),s=await e.query(n,i,!0),a=hi.from(s);return this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&this.expressionMap.whereEntities.length>0&&await r.update(a,this.expressionMap.whereEntities),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&(this.expressionMap.queryType==="soft-delete"?await e.broadcaster.broadcast("AfterSoftRemove",this.expressionMap.mainAlias.metadata):this.expressionMap.queryType==="restore"&&await e.broadcaster.broadcast("AfterRecover",this.expressionMap.mainAlias.metadata)),t&&await e.commitTransaction(),a}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}from(e,t){e=oe.isEntitySchema(e)?e.options.name:e;const r=this.createFromAlias(e,t);return this.expressionMap.setMainAlias(r),this}where(e,t){this.expressionMap.wheres=[];const r=this.getWhereCondition(e);return r&&(this.expressionMap.wheres=[{type:"simple",condition:r}]),t&&this.setParameters(t),this}andWhere(e,t){return this.expressionMap.wheres.push({type:"and",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}orWhere(e,t){return this.expressionMap.wheres.push({type:"or",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}whereInIds(e){return this.where(this.getWhereInIdsCondition(e))}andWhereInIds(e){return this.andWhere(this.getWhereInIdsCondition(e))}orWhereInIds(e){return this.orWhere(this.getWhereInIdsCondition(e))}output(e){return this.returning(e)}returning(e){if(!this.connection.driver.isReturningSqlSupported("update"))throw new Ye;return this.expressionMap.returning=e,this}orderBy(e,t="ASC",r){return e?typeof e=="object"?this.expressionMap.orderBys=e:r?this.expressionMap.orderBys={[e]:{order:t,nulls:r}}:this.expressionMap.orderBys={[e]:t}:this.expressionMap.orderBys={},this}addOrderBy(e,t="ASC",r){return r?this.expressionMap.orderBys[e]={order:t,nulls:r}:this.expressionMap.orderBys[e]=t,this}limit(e){return this.expressionMap.limit=e,this}whereEntity(e){if(!this.expressionMap.mainAlias.hasMetadata)throw new S(".whereEntity method can only be used on queries which update real entity table.");this.expressionMap.wheres=[];const t=Array.isArray(e)?e:[e];return t.forEach(r=>{const n=this.expressionMap.mainAlias.metadata.getEntityIdMap(r);if(!n)throw new S("Provided entity does not have ids set, cannot perform operation.");this.orWhereInIds(n)}),this.expressionMap.whereEntities=t,this}updateEntity(e){return this.expressionMap.updateEntity=e,this}createUpdateExpression(){const e=this.expressionMap.mainAlias.hasMetadata?this.expressionMap.mainAlias.metadata:void 0;if(!e)throw new S(`Cannot get entity metadata for the given alias "${this.expressionMap.mainAlias}"`);if(!e.deleteDateColumn)throw new Gi(e);const t=[];switch(this.expressionMap.queryType){case"soft-delete":t.push(this.escape(e.deleteDateColumn.databaseName)+" = CURRENT_TIMESTAMP");break;case"restore":t.push(this.escape(e.deleteDateColumn.databaseName)+" = NULL");break;default:throw new S('The queryType must be "soft-delete" or "restore"')}if(e.versionColumn&&t.push(this.escape(e.versionColumn.databaseName)+" = "+this.escape(e.versionColumn.databaseName)+" + 1"),e.updateDateColumn&&t.push(this.escape(e.updateDateColumn.databaseName)+" = CURRENT_TIMESTAMP"),t.length<=0)throw new ur;const r=this.createWhereExpression(),n=this.createReturningExpression("update");return n===""?`UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")}${r}`:this.connection.driver.options.type==="mssql"?`UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")} OUTPUT ${n}${r}`:`UPDATE ${this.getTableName(this.getMainTableName())} SET ${t.join(", ")}${r} RETURNING ${n}`}createOrderByExpression(){const e=this.expressionMap.orderBys;return Object.keys(e).length>0?" ORDER BY "+Object.keys(e).map(t=>typeof e[t]=="string"?this.replacePropertyNames(t)+" "+e[t]:this.replacePropertyNames(t)+" "+e[t].order+" "+e[t].nulls).join(", "):""}createLimitExpression(){const e=this.expressionMap.limit;if(e){if($.isMySQLFamily(this.connection.driver))return" LIMIT "+e;throw new Xn}return""}}class ua extends le{constructor(e,t){super(e,t),this["@instanceof"]=Symbol.for("UpdateQueryBuilder"),this.expressionMap.aliasNamePrefixingEnabled=!1}getQuery(){let e=this.createComment();return e+=this.createCteExpression(),e+=this.createUpdateExpression(),e+=this.createOrderByExpression(),e+=this.createLimitExpression(),this.replacePropertyNamesForTheWholeQuery(e.trim())}async execute(){const e=this.obtainQueryRunner();let t=!1;try{this.expressionMap.useTransaction===!0&&e.isTransactionActive===!1&&(await e.startTransaction(),t=!0),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&await e.broadcaster.broadcast("BeforeUpdate",this.expressionMap.mainAlias.metadata,this.expressionMap.valuesSet);let r=null,n=null;const i=new br(e,this.expressionMap),s=[];if(Array.isArray(this.expressionMap.returning)&&this.expressionMap.mainAlias.hasMetadata)for(const u of this.expressionMap.returning)s.push(...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(u));this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&this.expressionMap.whereEntities.length>0&&(this.expressionMap.extraReturningColumns=i.getUpdationReturningColumns(),s.push(...this.expressionMap.extraReturningColumns.filter(u=>!s.includes(u)))),s.length>0&&this.connection.driver.options.type==="mssql"&&(r=this.connection.driver.buildTableVariableDeclaration("@OutputTable",s),n="SELECT * FROM @OutputTable");const[a,o]=this.getQueryAndParameters(),c=[r,a,n],l=await e.query(c.filter(u=>u!=null).join(`;
6
+
7
+ `),o,!0),p=hi.from(l);return this.expressionMap.updateEntity===!0&&this.expressionMap.mainAlias.hasMetadata&&this.expressionMap.whereEntities.length>0&&await i.update(p,this.expressionMap.whereEntities),this.expressionMap.callListeners===!0&&this.expressionMap.mainAlias.hasMetadata&&await e.broadcaster.broadcast("AfterUpdate",this.expressionMap.mainAlias.metadata,this.expressionMap.valuesSet),t&&await e.commitTransaction(),p}catch(r){if(t)try{await e.rollbackTransaction()}catch{}throw r}finally{e!==this.queryRunner&&await e.release()}}set(e){return this.expressionMap.valuesSet=e,this}where(e,t){this.expressionMap.wheres=[];const r=this.getWhereCondition(e);return r&&(this.expressionMap.wheres=[{type:"simple",condition:r}]),t&&this.setParameters(t),this}andWhere(e,t){return this.expressionMap.wheres.push({type:"and",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}orWhere(e,t){return this.expressionMap.wheres.push({type:"or",condition:this.getWhereCondition(e)}),t&&this.setParameters(t),this}whereInIds(e){return this.where(this.getWhereInIdsCondition(e))}andWhereInIds(e){return this.andWhere(this.getWhereInIdsCondition(e))}orWhereInIds(e){return this.orWhere(this.getWhereInIdsCondition(e))}output(e){return this.returning(e)}returning(e){if(!this.connection.driver.isReturningSqlSupported("update"))throw new Ye;return this.expressionMap.returning=e,this}orderBy(e,t="ASC",r){return e?typeof e=="object"?this.expressionMap.orderBys=e:r?this.expressionMap.orderBys={[e]:{order:t,nulls:r}}:this.expressionMap.orderBys={[e]:t}:this.expressionMap.orderBys={},this}addOrderBy(e,t="ASC",r){return r?this.expressionMap.orderBys[e]={order:t,nulls:r}:this.expressionMap.orderBys[e]=t,this}limit(e){return this.expressionMap.limit=e,this}whereEntity(e){if(!this.expressionMap.mainAlias.hasMetadata)throw new S(".whereEntity method can only be used on queries which update real entity table.");this.expressionMap.wheres=[];const t=Array.isArray(e)?e:[e];return t.forEach(r=>{const n=this.expressionMap.mainAlias.metadata.getEntityIdMap(r);if(!n)throw new S("Provided entity does not have ids set, cannot perform operation.");this.orWhereInIds(n)}),this.expressionMap.whereEntities=t,this}updateEntity(e){return this.expressionMap.updateEntity=e,this}createUpdateExpression(){const e=this.getValueSet(),t=this.expressionMap.mainAlias.hasMetadata?this.expressionMap.mainAlias.metadata:void 0,r={};for(const o in e)e[o]!==void 0&&(r[o]=e[o]);const n=[],i=[];if(t?(this.createPropertyPath(t,r).forEach(o=>{const c=t.findColumnsWithPropertyPath(o);if(c.length<=0)throw new Ce(o,t);c.forEach(l=>{if(!l.isUpdate||i.includes(l))return;i.push(l);let p=l.getEntityValue(r);if(l.referencedColumn&&typeof p=="object"&&!(p instanceof Date)&&p!==null&&!Buffer.isBuffer(p)?p=l.referencedColumn.getEntityValue(p):typeof p!="function"&&(p=this.connection.driver.preparePersistentValue(p,l)),typeof p=="function")n.push(this.escape(l.databaseName)+" = "+p());else if((this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner")&&p===null)n.push(this.escape(l.databaseName)+" = NULL");else{this.connection.driver.options.type==="mssql"&&(p=this.connection.driver.parametrizeValue(l,p));const u=this.createParameter(p);let f=null;if(($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")&&this.connection.driver.spatialTypes.indexOf(l.type)!==-1){const d=this.connection.driver.options.legacySpatialSupport?"GeomFromText":"ST_GeomFromText";l.srid!=null?f=`${d}(${u}, ${l.srid})`:f=`${d}(${u})`}else $.isPostgresFamily(this.connection.driver)&&this.connection.driver.spatialTypes.indexOf(l.type)!==-1?l.srid!=null?f=`ST_SetSRID(ST_GeomFromGeoJSON(${u}), ${l.srid})::${l.type}`:f=`ST_GeomFromGeoJSON(${u})::${l.type}`:this.connection.driver.options.type==="mssql"&&this.connection.driver.spatialTypes.indexOf(l.type)!==-1?f=l.type+"::STGeomFromText("+u+", "+(l.srid||"0")+")":f=u;n.push(this.escape(l.databaseName)+" = "+f)}})}),(n.length>0||Object.keys(r).length===0)&&(t.versionColumn&&i.indexOf(t.versionColumn)===-1&&n.push(this.escape(t.versionColumn.databaseName)+" = "+this.escape(t.versionColumn.databaseName)+" + 1"),t.updateDateColumn&&i.indexOf(t.updateDateColumn)===-1&&n.push(this.escape(t.updateDateColumn.databaseName)+" = CURRENT_TIMESTAMP"))):Object.keys(r).map(o=>{const c=r[o];if(typeof c=="function")n.push(this.escape(o)+" = "+c());else if((this.connection.driver.options.type==="sap"||this.connection.driver.options.type==="spanner")&&c===null)n.push(this.escape(o)+" = NULL");else{const l=this.createParameter(c);n.push(this.escape(o)+" = "+l)}}),n.length<=0)throw new ur;const s=this.createWhereExpression(),a=this.createReturningExpression("update");return a===""?`UPDATE ${this.getTableName(this.getMainTableName())} SET ${n.join(", ")}${s}`:this.connection.driver.options.type==="mssql"?`UPDATE ${this.getTableName(this.getMainTableName())} SET ${n.join(", ")} OUTPUT ${a}${s}`:this.connection.driver.options.type==="spanner"?`UPDATE ${this.getTableName(this.getMainTableName())} SET ${n.join(", ")}${s} THEN RETURN ${a}`:`UPDATE ${this.getTableName(this.getMainTableName())} SET ${n.join(", ")}${s} RETURNING ${a}`}createOrderByExpression(){const e=this.expressionMap.orderBys;return Object.keys(e).length>0?" ORDER BY "+Object.keys(e).map(t=>typeof e[t]=="string"?this.replacePropertyNames(t)+" "+e[t]:this.replacePropertyNames(t)+" "+e[t].order+" "+e[t].nulls).join(", "):""}createLimitExpression(){const e=this.expressionMap.limit;if(e){if($.isMySQLFamily(this.connection.driver)||this.connection.driver.options.type==="aurora-mysql")return" LIMIT "+e;throw new Xn}return""}getValueSet(){if(typeof this.expressionMap.valuesSet=="object")return this.expressionMap.valuesSet;throw new ur}}function ca(){le.registerQueryBuilderClass("DeleteQueryBuilder",h=>new Gs(h)),le.registerQueryBuilderClass("InsertQueryBuilder",h=>new Zs(h)),le.registerQueryBuilderClass("RelationQueryBuilder",h=>new ea(h)),le.registerQueryBuilderClass("SelectQueryBuilder",h=>new xr(h)),le.registerQueryBuilderClass("SoftDeleteQueryBuilder",h=>new oa(h)),le.registerQueryBuilderClass("UpdateQueryBuilder",h=>new ua(h))}function Vn(h,e){var t=Object.keys(h);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(h);e&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(h,n).enumerable})),t.push.apply(t,r)}return t}function Wn(h){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Vn(Object(t),!0).forEach(function(r){la(h,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(h,Object.getOwnPropertyDescriptors(t)):Vn(Object(t)).forEach(function(r){Object.defineProperty(h,r,Object.getOwnPropertyDescriptor(t,r))})}return h}function la(h,e,t){return e=pa(e),e in h?Object.defineProperty(h,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):h[e]=t,h}function pa(h){var e=ha(h,"string");return typeof e=="symbol"?e:String(e)}function ha(h,e){if(typeof h!="object"||h===null)return h;var t=h[Symbol.toPrimitive];if(t!==void 0){var r=t.call(h,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(h)}fi({});function fi(h){return e.withOptions=t=>fi(Wn(Wn({},h),t)),e;function e(t,...r){const n=typeof t=="string"?[t]:t.raw,{alignValues:i=!1,escapeSpecialCharacters:s=Array.isArray(t),trimWhitespace:a=!0}=h;let o="";for(let p=0;p<n.length;p++){let u=n[p];if(s&&(u=u.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),o+=u,p<r.length){const f=i?fa(r[p],o):r[p];o+=f}}const c=o.split(`
8
+ `);let l=null;for(const p of c){const u=p.match(/^(\s+)\S+/);if(u){const f=u[1].length;l?l=Math.min(l,f):l=f}}if(l!==null){const p=l;o=c.map(u=>u[0]===" "||u[0]===" "?u.slice(p):u).join(`
9
+ `)}return a&&(o=o.trim()),s&&(o=o.replace(/\\n/g,`
10
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(p,u)=>String.fromCharCode(parseInt(u,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(p,u)=>String.fromCodePoint(parseInt(u,16))).replace(/\\u([\da-fA-F]{4})/g,(p,u)=>String.fromCharCode(parseInt(u,16)))),typeof Bun<"u"&&(o=o.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(p,u,f)=>{var y;const d=(y=u??f)!==null&&y!==void 0?y:"";return String.fromCodePoint(parseInt(d,16))})),o}}function fa(h,e){if(typeof h!="string"||!h.includes(`
11
+ `))return h;const r=e.slice(e.lastIndexOf(`
12
+ `)+1).match(/^(\s+)/);if(r){const n=r[1];return h.replace(/\n/g,`
13
+ ${n}`)}return h}var Ge={exports:{}},da=Ge.exports,Qn;function ya(){return Qn||(Qn=1,(function(h,e){(function(t,r){h.exports=r()})(da,(function(){var t=1e3,r=6e4,n=36e5,i="millisecond",s="second",a="minute",o="hour",c="day",l="week",p="month",u="quarter",f="year",y="date",d="Invalid Date",m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,b=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,A={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(P){var T=["th","st","nd","rd"],O=P%100;return"["+P+(T[(O-20)%10]||T[O]||T[0])+"]"}},x=function(P,T,O){var w=String(P);return!w||w.length>=T?P:""+Array(T+1-w.length).join(O)+P},I={s:x,z:function(P){var T=-P.utcOffset(),O=Math.abs(T),w=Math.floor(O/60),C=O%60;return(T<=0?"+":"-")+x(w,2,"0")+":"+x(C,2,"0")},m:function P(T,O){if(T.date()<O.date())return-P(O,T);var w=12*(O.year()-T.year())+(O.month()-T.month()),C=T.clone().add(w,p),B=O-C<0,V=T.clone().add(w+(B?-1:1),p);return+(-(w+(O-C)/(B?C-V:V-C))||0)},a:function(P){return P<0?Math.ceil(P)||0:Math.floor(P)},p:function(P){return{M:p,y:f,w:l,d:c,D:y,h:o,m:a,s,ms:i,Q:u}[P]||String(P||"").toLowerCase().replace(/s$/,"")},u:function(P){return P===void 0}},F="en",L={};L[F]=A;var Q="$isDayjsObject",se=function(P){return P instanceof U||!(!P||!P[Q])},te=function P(T,O,w){var C;if(!T)return F;if(typeof T=="string"){var B=T.toLowerCase();L[B]&&(C=B),O&&(L[B]=O,C=B);var V=T.split("-");if(!C&&V.length>1)return P(V[0])}else{var G=T.name;L[G]=T,C=G}return!w&&C&&(F=C),C||!w&&F},k=function(P,T){if(se(P))return P.clone();var O=typeof T=="object"?T:{};return O.date=P,O.args=arguments,new U(O)},M=I;M.l=te,M.i=se,M.w=function(P,T){return k(P,{locale:T.$L,utc:T.$u,x:T.$x,$offset:T.$offset})};var U=(function(){function P(O){this.$L=te(O.locale,null,!0),this.parse(O),this.$x=this.$x||O.x||{},this[Q]=!0}var T=P.prototype;return T.parse=function(O){this.$d=(function(w){var C=w.date,B=w.utc;if(C===null)return new Date(NaN);if(M.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var V=C.match(m);if(V){var G=V[2]-1||0,K=(V[7]||"0").substring(0,3);return B?new Date(Date.UTC(V[1],G,V[3]||1,V[4]||0,V[5]||0,V[6]||0,K)):new Date(V[1],G,V[3]||1,V[4]||0,V[5]||0,V[6]||0,K)}}return new Date(C)})(O),this.init()},T.init=function(){var O=this.$d;this.$y=O.getFullYear(),this.$M=O.getMonth(),this.$D=O.getDate(),this.$W=O.getDay(),this.$H=O.getHours(),this.$m=O.getMinutes(),this.$s=O.getSeconds(),this.$ms=O.getMilliseconds()},T.$utils=function(){return M},T.isValid=function(){return this.$d.toString()!==d},T.isSame=function(O,w){var C=k(O);return this.startOf(w)<=C&&C<=this.endOf(w)},T.isAfter=function(O,w){return k(O)<this.startOf(w)},T.isBefore=function(O,w){return this.endOf(w)<k(O)},T.$g=function(O,w,C){return M.u(O)?this[w]:this.set(C,O)},T.unix=function(){return Math.floor(this.valueOf()/1e3)},T.valueOf=function(){return this.$d.getTime()},T.startOf=function(O,w){var C=this,B=!!M.u(w)||w,V=M.p(O),G=function(ie,J){var Y=M.w(C.$u?Date.UTC(C.$y,J,ie):new Date(C.$y,J,ie),C);return B?Y:Y.endOf(c)},K=function(ie,J){return M.w(C.toDate()[ie].apply(C.toDate("s"),(B?[0,0,0,0]:[23,59,59,999]).slice(J)),C)},_=this.$W,X=this.$M,me=this.$D,ne="set"+(this.$u?"UTC":"");switch(V){case f:return B?G(1,0):G(31,11);case p:return B?G(1,X):G(0,X+1);case l:var Me=this.$locale().weekStart||0,pe=(_<Me?_+7:_)-Me;return G(B?me-pe:me+(6-pe),X);case c:case y:return K(ne+"Hours",0);case o:return K(ne+"Minutes",1);case a:return K(ne+"Seconds",2);case s:return K(ne+"Milliseconds",3);default:return this.clone()}},T.endOf=function(O){return this.startOf(O,!1)},T.$set=function(O,w){var C,B=M.p(O),V="set"+(this.$u?"UTC":""),G=(C={},C[c]=V+"Date",C[y]=V+"Date",C[p]=V+"Month",C[f]=V+"FullYear",C[o]=V+"Hours",C[a]=V+"Minutes",C[s]=V+"Seconds",C[i]=V+"Milliseconds",C)[B],K=B===c?this.$D+(w-this.$W):w;if(B===p||B===f){var _=this.clone().set(y,1);_.$d[G](K),_.init(),this.$d=_.set(y,Math.min(this.$D,_.daysInMonth())).$d}else G&&this.$d[G](K);return this.init(),this},T.set=function(O,w){return this.clone().$set(O,w)},T.get=function(O){return this[M.p(O)]()},T.add=function(O,w){var C,B=this;O=Number(O);var V=M.p(w),G=function(X){var me=k(B);return M.w(me.date(me.date()+Math.round(X*O)),B)};if(V===p)return this.set(p,this.$M+O);if(V===f)return this.set(f,this.$y+O);if(V===c)return G(1);if(V===l)return G(7);var K=(C={},C[a]=r,C[o]=n,C[s]=t,C)[V]||1,_=this.$d.getTime()+O*K;return M.w(_,this)},T.subtract=function(O,w){return this.add(-1*O,w)},T.format=function(O){var w=this,C=this.$locale();if(!this.isValid())return C.invalidDate||d;var B=O||"YYYY-MM-DDTHH:mm:ssZ",V=M.z(this),G=this.$H,K=this.$m,_=this.$M,X=C.weekdays,me=C.months,ne=C.meridiem,Me=function(J,Y,re,ae){return J&&(J[Y]||J(w,B))||re[Y].slice(0,ae)},pe=function(J){return M.s(G%12||12,J,"0")},ie=ne||function(J,Y,re){var ae=J<12?"AM":"PM";return re?ae.toLowerCase():ae};return B.replace(b,(function(J,Y){return Y||(function(re){switch(re){case"YY":return String(w.$y).slice(-2);case"YYYY":return M.s(w.$y,4,"0");case"M":return _+1;case"MM":return M.s(_+1,2,"0");case"MMM":return Me(C.monthsShort,_,me,3);case"MMMM":return Me(me,_);case"D":return w.$D;case"DD":return M.s(w.$D,2,"0");case"d":return String(w.$W);case"dd":return Me(C.weekdaysMin,w.$W,X,2);case"ddd":return Me(C.weekdaysShort,w.$W,X,3);case"dddd":return X[w.$W];case"H":return String(G);case"HH":return M.s(G,2,"0");case"h":return pe(1);case"hh":return pe(2);case"a":return ie(G,K,!0);case"A":return ie(G,K,!1);case"m":return String(K);case"mm":return M.s(K,2,"0");case"s":return String(w.$s);case"ss":return M.s(w.$s,2,"0");case"SSS":return M.s(w.$ms,3,"0");case"Z":return V}return null})(J)||V.replace(":","")}))},T.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},T.diff=function(O,w,C){var B,V=this,G=M.p(w),K=k(O),_=(K.utcOffset()-this.utcOffset())*r,X=this-K,me=function(){return M.m(V,K)};switch(G){case f:B=me()/12;break;case p:B=me();break;case u:B=me()/3;break;case l:B=(X-_)/6048e5;break;case c:B=(X-_)/864e5;break;case o:B=X/n;break;case a:B=X/r;break;case s:B=X/t;break;default:B=X}return C?B:M.a(B)},T.daysInMonth=function(){return this.endOf(p).$D},T.$locale=function(){return L[this.$L]},T.locale=function(O,w){if(!O)return this.$L;var C=this.clone(),B=te(O,w,!0);return B&&(C.$L=B),C},T.clone=function(){return M.w(this.$d,this)},T.toDate=function(){return new Date(this.valueOf())},T.toJSON=function(){return this.isValid()?this.toISOString():null},T.toISOString=function(){return this.$d.toISOString()},T.toString=function(){return this.$d.toUTCString()},P})(),H=U.prototype;return k.prototype=H,[["$ms",i],["$s",s],["$m",a],["$H",o],["$W",c],["$M",p],["$y",f],["$D",y]].forEach((function(P){H[P[1]]=function(T){return this.$g(T,P[0],P[1])}})),k.extend=function(P,T){return P.$i||(P(T,U,k),P.$i=!0),k},k.locale=te,k.isDayjs=se,k.unix=function(P){return k(1e3*P)},k.en=L[F],k.Ls=L,k.p={},k}))})(Ge)),Ge.exports}ya();var Gn;(function(h){h.VIEW="VIEW",h.MATERIALIZED_VIEW="MATERIALIZED_VIEW",h.GENERATED_COLUMN="GENERATED_COLUMN"})(Gn||(Gn={}));var Qe={exports:{}},ar,Jn;function ma(){if(Jn)return ar;Jn=1;var h=1e3,e=h*60,t=e*60,r=t*24,n=r*7,i=r*365.25;ar=function(l,p){p=p||{};var u=typeof l;if(u==="string"&&l.length>0)return s(l);if(u==="number"&&isFinite(l))return p.long?o(l):a(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(p){var u=parseFloat(p[1]),f=(p[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return u*i;case"weeks":case"week":case"w":return u*n;case"days":case"day":case"d":return u*r;case"hours":case"hour":case"hrs":case"hr":case"h":return u*t;case"minutes":case"minute":case"mins":case"min":case"m":return u*e;case"seconds":case"second":case"secs":case"sec":case"s":return u*h;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}}}function a(l){var p=Math.abs(l);return p>=r?Math.round(l/r)+"d":p>=t?Math.round(l/t)+"h":p>=e?Math.round(l/e)+"m":p>=h?Math.round(l/h)+"s":l+"ms"}function o(l){var p=Math.abs(l);return p>=r?c(l,p,r,"day"):p>=t?c(l,p,t,"hour"):p>=e?c(l,p,e,"minute"):p>=h?c(l,p,h,"second"):l+" ms"}function c(l,p,u,f){var y=p>=u*1.5;return Math.round(l/u)+" "+f+(y?"s":"")}return ar}var or,Hn;function ga(){if(Hn)return or;Hn=1;function h(e){r.debug=r,r.default=r,r.coerce=c,r.disable=a,r.enable=i,r.enabled=o,r.humanize=ma(),r.destroy=l,Object.keys(e).forEach(p=>{r[p]=e[p]}),r.names=[],r.skips=[],r.formatters={};function t(p){let u=0;for(let f=0;f<p.length;f++)u=(u<<5)-u+p.charCodeAt(f),u|=0;return r.colors[Math.abs(u)%r.colors.length]}r.selectColor=t;function r(p){let u,f=null,y,d;function m(...b){if(!m.enabled)return;const A=m,x=Number(new Date),I=x-(u||x);A.diff=I,A.prev=u,A.curr=x,u=x,b[0]=r.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let F=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(Q,se)=>{if(Q==="%%")return"%";F++;const te=r.formatters[se];if(typeof te=="function"){const k=b[F];Q=te.call(A,k),b.splice(F,1),F--}return Q}),r.formatArgs.call(A,b),(A.log||r.log).apply(A,b)}return m.namespace=p,m.useColors=r.useColors(),m.color=r.selectColor(p),m.extend=n,m.destroy=r.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(y!==r.namespaces&&(y=r.namespaces,d=r.enabled(p)),d),set:b=>{f=b}}),typeof r.init=="function"&&r.init(m),m}function n(p,u){const f=r(this.namespace+(typeof u>"u"?":":u)+p);return f.log=this.log,f}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];const u=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of u)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function s(p,u){let f=0,y=0,d=-1,m=0;for(;f<p.length;)if(y<u.length&&(u[y]===p[f]||u[y]==="*"))u[y]==="*"?(d=y,m=f,y++):(f++,y++);else if(d!==-1)y=d+1,m++,f=m;else return!1;for(;y<u.length&&u[y]==="*";)y++;return y===u.length}function a(){const p=[...r.names,...r.skips.map(u=>"-"+u)].join(",");return r.enable(""),p}function o(p){for(const u of r.skips)if(s(p,u))return!1;for(const u of r.names)if(s(p,u))return!0;return!1}function c(p){return p instanceof Error?p.stack||p.message:p}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return or=h,or}var Yn;function ba(){return Yn||(Yn=1,(function(h,e){e.formatArgs=r,e.save=n,e.load=i,e.useColors=t,e.storage=s(),e.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+h.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;o.splice(1,0,c,"color: inherit");let l=0,p=0;o[0].replace(/%[a-zA-Z%]/g,u=>{u!=="%%"&&(l++,u==="%c"&&(p=l))}),o.splice(p,0,c)}e.log=console.debug||console.log||(()=>{});function n(o){try{o?e.storage.setItem("debug",o):e.storage.removeItem("debug")}catch{}}function i(){let o;try{o=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!o&&typeof process<"u"&&"env"in process&&(o=process.env.DEBUG),o}function s(){try{return localStorage}catch{}}h.exports=ga()(e);const{formatters:a}=h.exports;a.j=function(o){try{return JSON.stringify(o)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(Qe,Qe.exports)),Qe.exports}ba();ca();function Mr(){const h=Zn.getGlobalVariable();return h.typeormMetadataArgsStorage||(h.typeormMetadataArgsStorage=new Wi),h.typeormMetadataArgsStorage}function va(h){return function(e,t){Mr().columns.push({target:e.constructor,propertyName:t,mode:"createDate",options:{}})}}function xa(h){return function(e,t){Mr().columns.push({target:e.constructor,propertyName:t,mode:"deleteDate",options:h||{}})}}function Ma(h){return function(e,t){Mr().columns.push({target:e.constructor,propertyName:t,mode:"updateDate",options:h||{}})}}class wa{hasId(){return this.constructor.getRepository().hasId(this)}save(e){return this.constructor.getRepository().save(this,e)}remove(e){return this.constructor.getRepository().remove(this,e)}softRemove(e){return this.constructor.getRepository().softRemove(this,e)}recover(e){return this.constructor.getRepository().recover(this,e)}async reload(){const e=this.constructor,t=e.getRepository().metadata.getEntityIdMap(this);if(!t)throw new Error("Entity doesn't have id-s set, cannot reload entity");const r=await e.getRepository().findOneByOrFail(t);fe.assign(this,r)}static useDataSource(e){this.dataSource=e}static getRepository(){const e=this.dataSource;if(!e)throw new Error("DataSource is not set for this entity.");return e.getRepository(this)}static get target(){return this.getRepository().target}static hasId(e){return this.getRepository().hasId(e)}static getId(e){return this.getRepository().getId(e)}static createQueryBuilder(e){return this.getRepository().createQueryBuilder(e)}static create(e){return this.getRepository().create(e)}static merge(e,...t){return this.getRepository().merge(e,...t)}static preload(e){return this.getRepository().preload(e)}static save(e,t){return this.getRepository().save(e,t)}static remove(e,t){return this.getRepository().remove(e,t)}static softRemove(e,t){return this.getRepository().softRemove(e,t)}static insert(e){return this.getRepository().insert(e)}static update(e,t){return this.getRepository().update(e,t)}static upsert(e,t){return this.getRepository().upsert(e,t)}static delete(e){return this.getRepository().delete(e)}static exists(e){return this.getRepository().exists(e)}static existsBy(e){return this.getRepository().existsBy(e)}static count(e){return this.getRepository().count(e)}static countBy(e){return this.getRepository().countBy(e)}static sum(e,t){return this.getRepository().sum(e,t)}static average(e,t){return this.getRepository().average(e,t)}static minimum(e,t){return this.getRepository().minimum(e,t)}static maximum(e,t){return this.getRepository().maximum(e,t)}static find(e){return this.getRepository().find(e)}static findBy(e){return this.getRepository().findBy(e)}static findAndCount(e){return this.getRepository().findAndCount(e)}static findAndCountBy(e){return this.getRepository().findAndCountBy(e)}static findByIds(e){return this.getRepository().findByIds(e)}static findOne(e){return this.getRepository().findOne(e)}static findOneBy(e){return this.getRepository().findOneBy(e)}static findOneById(e){return this.getRepository().findOneById(e)}static findOneOrFail(e){return this.getRepository().findOneOrFail(e)}static findOneByOrFail(e){return this.getRepository().findOneByOrFail(e)}static query(e,t){return this.getRepository().query(e,t)}static clear(){return this.getRepository().clear()}}var Ea=Object.defineProperty,wr=(h,e,t,r)=>{for(var n=void 0,i=h.length-1,s;i>=0;i--)(s=h[i])&&(n=s(e,t,n)||n);return n&&Ea(e,t,n),n};class ze extends wa{created;updated;deleted}wr([va()],ze.prototype,"created");wr([Ma({nullable:!0})],ze.prototype,"updated");wr([xa({nullable:!0})],ze.prototype,"deleted");exports.GCPLogger=qi;exports.LogLevelToConsoleMethodMap=zn;exports.MockLogger=Di;exports.SimpleEntity=ze;exports.TransactionalRepository=He;exports.buildTransactionalRepositoryMock=Fi;exports.loadEnvConfig=_i;exports.postgres=Li;