@budibase/backend-core 3.12.14 → 3.12.16
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.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
attempted value: ${s}
|
|
4
4
|
`+(o!==s?`result of cast: ${o}`:""))}return i}_cast(e,r){let n=e===void 0?e:this.transforms.reduce((i,s)=>s.call(this,i,e,this),e);return n===void 0&&(n=this.getDefault()),n}_validate(e,r={},n){let{sync:i,path:s,from:o=[],originalValue:a=e,strict:u=this.spec.strict,abortEarly:c=this.spec.abortEarly}=r,l=e;u||(l=this._cast(l,ft({assert:!1},r)));let m={value:l,path:s,options:r,originalValue:a,schema:this,label:this.spec.label,sync:i,from:o},p=[];this._typeError&&p.push(this._typeError),this._whitelistError&&p.push(this._whitelistError),this._blacklistError&&p.push(this._blacklistError),(0,Vg.default)({args:m,value:l,path:s,sync:i,tests:p,endEarly:c},f=>{if(f)return void n(f,l);(0,Vg.default)({tests:this.tests,args:m,path:s,sync:i,value:l,endEarly:c},n)})}validate(e,r,n){let i=this.resolve(ft({},r,{value:e}));return typeof n=="function"?i._validate(e,r,n):new Promise((s,o)=>i._validate(e,r,(a,u)=>{a?o(a):s(u)}))}validateSync(e,r){let n=this.resolve(ft({},r,{value:e})),i;return n._validate(e,ft({},r,{sync:!0}),(s,o)=>{if(s)throw s;i=o}),i}isValid(e,r){return this.validate(e,r).then(()=>!0,n=>{if(Wg.default.isError(n))return!1;throw n})}isValidSync(e,r){try{return this.validateSync(e,r),!0}catch(n){if(Wg.default.isError(n))return!1;throw n}}_getDefault(){let e=this.spec.default;return e==null?e:typeof e=="function"?e.call(this):(0,$g.default)(e)}getDefault(e){return this.resolve(e||{})._getDefault()}default(e){return arguments.length===0?this._getDefault():this.clone({default:e})}strict(e=!0){var r=this.clone();return r.spec.strict=e,r}_isPresent(e){return e!=null}defined(e=Ni.mixed.defined){return this.test({message:e,name:"defined",exclusive:!0,test(r){return r!==void 0}})}required(e=Ni.mixed.required){return this.clone({presence:"required"}).withMutation(r=>r.test({message:e,name:"required",exclusive:!0,test(n){return this.schema._isPresent(n)}}))}notRequired(){var e=this.clone({presence:"optional"});return e.tests=e.tests.filter(r=>r.OPTIONS.name!=="required"),e}nullable(e=!0){var r=this.clone({nullable:e!==!1});return r}transform(e){var r=this.clone();return r.transforms.push(e),r}test(...e){let r;if(e.length===1?typeof e[0]=="function"?r={test:e[0]}:r=e[0]:e.length===2?r={name:e[0],test:e[1]}:r={name:e[0],message:e[1],test:e[2]},r.message===void 0&&(r.message=Ni.mixed.default),typeof r.test!="function")throw new TypeError("`test` is a required parameters");let n=this.clone(),i=(0,mu.default)(r),s=r.exclusive||r.name&&n.exclusiveTests[r.name]===!0;if(r.exclusive&&!r.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return r.name&&(n.exclusiveTests[r.name]=!!r.exclusive),n.tests=n.tests.filter(o=>!(o.OPTIONS.name===r.name&&(s||o.OPTIONS.test===i.OPTIONS.test))),n.tests.push(i),n}when(e,r){!Array.isArray(e)&&typeof e!="string"&&(r=e,e=".");let n=this.clone(),i=(0,UR.default)(e).map(s=>new PR.default(s));return i.forEach(s=>{s.isSibling&&n.deps.push(s.key)}),n.conditions.push(new NR.default(i,r)),n}typeError(e){var r=this.clone();return r._typeError=(0,mu.default)({message:e,name:"typeError",test(n){return n!==void 0&&!this.schema.isType(n)?this.createError({params:{type:this.schema._type}}):!0}}),r}oneOf(e,r=Ni.mixed.oneOf){var n=this.clone();return e.forEach(i=>{n._whitelist.add(i),n._blacklist.delete(i)}),n._whitelistError=(0,mu.default)({message:r,name:"oneOf",test(i){if(i===void 0)return!0;let s=this.schema._whitelist;return s.has(i,this.resolve)?!0:this.createError({params:{values:s.toArray().join(", ")}})}}),n}notOneOf(e,r=Ni.mixed.notOneOf){var n=this.clone();return e.forEach(i=>{n._blacklist.add(i),n._whitelist.delete(i)}),n._blacklistError=(0,mu.default)({message:r,name:"notOneOf",test(i){let s=this.schema._blacklist;return s.has(i,this.resolve)?this.createError({params:{values:s.toArray().join(", ")}}):!0}}),n}strip(e=!0){let r=this.clone();return r.spec.strip=e,r}describe(){let e=this.clone(),{label:r,meta:n}=e.spec;return{meta:n,label:r,type:e.type,oneOf:e._whitelist.describe(),notOneOf:e._blacklist.describe(),tests:e.tests.map(s=>({name:s.OPTIONS.name,params:s.OPTIONS.params})).filter((s,o,a)=>a.findIndex(u=>u.name===s.name)===o)}}};hu.default=Rt;Rt.prototype.__isYupSchema__=!0;for(let t of["validate","validateSync"])Rt.prototype[`${t}At`]=function(e,r,n={}){let{parent:i,parentPath:s,schema:o}=(0,LR.getIn)(this,e,r,n.context);return o[t](i&&i[s],ft({},n,{parent:i,path:e}))};for(let t of["equals","is"])Rt.prototype[t]=Rt.prototype.oneOf;for(let t of["not","nope"])Rt.prototype[t]=Rt.prototype.notOneOf;Rt.prototype.optional=Rt.prototype.notRequired});var Hg=H(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.create=jg;Hs.default=void 0;var MR=FR(rr());function FR(t){return t&&t.__esModule?t:{default:t}}var pd=MR.default,kR=pd;Hs.default=kR;function jg(){return new pd}jg.prototype=pd.prototype});var Pi=H(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.default=void 0;var BR=t=>t==null;gu.default=BR});var Zg=H(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.create=zg;Ys.default=void 0;var GR=Jg(rr()),Kg=er(),Yg=Jg(Pi());function Jg(t){return t&&t.__esModule?t:{default:t}}function zg(){return new Ks}var Ks=class extends GR.default{constructor(){super({type:"boolean"}),this.withMutation(()=>{this.transform(function(e){if(!this.isType(e)){if(/^(true|1)$/i.test(String(e)))return!0;if(/^(false|0)$/i.test(String(e)))return!1}return e})})}_typeCheck(e){return e instanceof Boolean&&(e=e.valueOf()),typeof e=="boolean"}isTrue(e=Kg.boolean.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"true"},test(r){return(0,Yg.default)(r)||r===!0}})}isFalse(e=Kg.boolean.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"false"},test(r){return(0,Yg.default)(r)||r===!1}})}};Ys.default=Ks;zg.prototype=Ks.prototype});var ty=H(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.create=ey;zs.default=void 0;var qt=er(),nr=Xg(Pi()),$R=Xg(rr());function Xg(t){return t&&t.__esModule?t:{default:t}}var VR=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,qR=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,WR=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,QR=t=>(0,nr.default)(t)||t===t.trim(),jR={}.toString();function ey(){return new Js}var Js=class extends $R.default{constructor(){super({type:"string"}),this.withMutation(()=>{this.transform(function(e){if(this.isType(e)||Array.isArray(e))return e;let r=e!=null&&e.toString?e.toString():e;return r===jR?e:r})})}_typeCheck(e){return e instanceof String&&(e=e.valueOf()),typeof e=="string"}_isPresent(e){return super._isPresent(e)&&!!e.length}length(e,r=qt.string.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},test(n){return(0,nr.default)(n)||n.length===this.resolve(e)}})}min(e,r=qt.string.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},test(n){return(0,nr.default)(n)||n.length>=this.resolve(e)}})}max(e,r=qt.string.max){return this.test({name:"max",exclusive:!0,message:r,params:{max:e},test(n){return(0,nr.default)(n)||n.length<=this.resolve(e)}})}matches(e,r){let n=!1,i,s;return r&&(typeof r=="object"?{excludeEmptyString:n=!1,message:i,name:s}=r:i=r),this.test({name:s||"matches",message:i||qt.string.matches,params:{regex:e},test:o=>(0,nr.default)(o)||o===""&&n||o.search(e)!==-1})}email(e=qt.string.email){return this.matches(VR,{name:"email",message:e,excludeEmptyString:!0})}url(e=qt.string.url){return this.matches(qR,{name:"url",message:e,excludeEmptyString:!0})}uuid(e=qt.string.uuid){return this.matches(WR,{name:"uuid",message:e,excludeEmptyString:!1})}ensure(){return this.default("").transform(e=>e===null?"":e)}trim(e=qt.string.trim){return this.transform(r=>r!=null?r.trim():r).test({message:e,name:"trim",test:QR})}lowercase(e=qt.string.lowercase){return this.transform(r=>(0,nr.default)(r)?r:r.toLowerCase()).test({message:e,name:"string_case",exclusive:!0,test:r=>(0,nr.default)(r)||r===r.toLowerCase()})}uppercase(e=qt.string.uppercase){return this.transform(r=>(0,nr.default)(r)?r:r.toUpperCase()).test({message:e,name:"string_case",exclusive:!0,test:r=>(0,nr.default)(r)||r===r.toUpperCase()})}};zs.default=Js;ey.prototype=Js.prototype});var iy=H(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.create=ny;Xs.default=void 0;var Nn=er(),Pn=ry(Pi()),HR=ry(rr());function ry(t){return t&&t.__esModule?t:{default:t}}var KR=t=>t!=+t;function ny(){return new Zs}var Zs=class extends HR.default{constructor(){super({type:"number"}),this.withMutation(()=>{this.transform(function(e){let r=e;if(typeof r=="string"){if(r=r.replace(/\s/g,""),r==="")return NaN;r=+r}return this.isType(r)?r:parseFloat(r)})})}_typeCheck(e){return e instanceof Number&&(e=e.valueOf()),typeof e=="number"&&!KR(e)}min(e,r=Nn.number.min){return this.test({message:r,name:"min",exclusive:!0,params:{min:e},test(n){return(0,Pn.default)(n)||n>=this.resolve(e)}})}max(e,r=Nn.number.max){return this.test({message:r,name:"max",exclusive:!0,params:{max:e},test(n){return(0,Pn.default)(n)||n<=this.resolve(e)}})}lessThan(e,r=Nn.number.lessThan){return this.test({message:r,name:"max",exclusive:!0,params:{less:e},test(n){return(0,Pn.default)(n)||n<this.resolve(e)}})}moreThan(e,r=Nn.number.moreThan){return this.test({message:r,name:"min",exclusive:!0,params:{more:e},test(n){return(0,Pn.default)(n)||n>this.resolve(e)}})}positive(e=Nn.number.positive){return this.moreThan(0,e)}negative(e=Nn.number.negative){return this.lessThan(0,e)}integer(e=Nn.number.integer){return this.test({name:"integer",message:e,test:r=>(0,Pn.default)(r)||Number.isInteger(r)})}truncate(){return this.transform(e=>(0,Pn.default)(e)?e:e|0)}round(e){var r,n=["ceil","floor","round","trunc"];if(e=((r=e)==null?void 0:r.toLowerCase())||"round",e==="trunc")return this.truncate();if(n.indexOf(e.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+n.join(", "));return this.transform(i=>(0,Pn.default)(i)?i:Math[e](i))}};Xs.default=Zs;ny.prototype=Zs.prototype});var sy=H(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.default=JR;var YR=/^(\d{4}|[+\-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;function JR(t){var e=[1,4,5,6,7,10,11],r=0,n,i;if(i=YR.exec(t)){for(var s=0,o;o=e[s];++s)i[o]=+i[o]||0;i[2]=(+i[2]||1)-1,i[3]=+i[3]||1,i[7]=i[7]?String(i[7]).substr(0,3):0,(i[8]===void 0||i[8]==="")&&(i[9]===void 0||i[9]==="")?n=+new Date(i[1],i[2],i[3],i[4],i[5],i[6],i[7]):(i[8]!=="Z"&&i[9]!==void 0&&(r=i[10]*60+i[11],i[9]==="+"&&(r=0-r)),n=Date.UTC(i[1],i[2],i[3],i[4],i[5]+r,i[6],i[7]))}else n=Date.parse?Date.parse(t):NaN;return n}});var uy=H(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.create=hd;eo.default=void 0;var zR=yu(sy()),oy=er(),ay=yu(Pi()),ZR=yu(vn()),XR=yu(rr());function yu(t){return t&&t.__esModule?t:{default:t}}var md=new Date(""),ew=t=>Object.prototype.toString.call(t)==="[object Date]";function hd(){return new Li}var Li=class extends XR.default{constructor(){super({type:"date"}),this.withMutation(()=>{this.transform(function(e){return this.isType(e)?e:(e=(0,zR.default)(e),isNaN(e)?md:new Date(e))})})}_typeCheck(e){return ew(e)&&!isNaN(e.getTime())}prepareParam(e,r){let n;if(ZR.default.isRef(e))n=e;else{let i=this.cast(e);if(!this._typeCheck(i))throw new TypeError(`\`${r}\` must be a Date or a value that can be \`cast()\` to a Date`);n=i}return n}min(e,r=oy.date.min){let n=this.prepareParam(e,"min");return this.test({message:r,name:"min",exclusive:!0,params:{min:e},test(i){return(0,ay.default)(i)||i>=this.resolve(n)}})}max(e,r=oy.date.max){var n=this.prepareParam(e,"max");return this.test({message:r,name:"max",exclusive:!0,params:{max:e},test(i){return(0,ay.default)(i)||i<=this.resolve(n)}})}};eo.default=Li;Li.INVALID_DATE=md;hd.prototype=Li.prototype;hd.INVALID_DATE=md});var ly=H((DQ,gd)=>{"use strict";gd.exports=function(t){return cy(tw(t),t)};gd.exports.array=cy;function cy(t,e){var r=t.length,n=new Array(r),i={},s=r,o=rw(e),a=nw(t);for(e.forEach(function(c){if(!a.has(c[0])||!a.has(c[1]))throw new Error("Unknown node. There is an unknown node in the supplied edges.")});s--;)i[s]||u(t[s],s,new Set);return n;function u(c,l,m){if(m.has(c)){var p;try{p=", node was:"+JSON.stringify(c)}catch{p=""}throw new Error("Cyclic dependency"+p)}if(!a.has(c))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(c));if(!i[l]){i[l]=!0;var f=o.get(c)||new Set;if(f=Array.from(f),l=f.length){m.add(c);do{var d=f[--l];u(d,a.get(d),m)}while(l);m.delete(c)}n[--r]=c}}}function tw(t){for(var e=new Set,r=0,n=t.length;r<n;r++){var i=t[r];e.add(i[0]),e.add(i[1])}return Array.from(e)}function rw(t){for(var e=new Map,r=0,n=t.length;r<n;r++){var i=t[r];e.has(i[0])||e.set(i[0],new Set),e.has(i[1])||e.set(i[1],new Set),e.get(i[0]).add(i[1])}return e}function nw(t){for(var e=new Map,r=0,n=t.length;r<n;r++)e.set(t[r],r);return e}});var dy=H(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});yd.default=cw;var iw=Eu(require("lodash/has")),sw=Eu(ly()),ow=qs(),aw=Eu(vn()),uw=Eu(vi());function Eu(t){return t&&t.__esModule?t:{default:t}}function cw(t,e=[]){let r=[],n=[];function i(s,o){var a=(0,ow.split)(s)[0];~n.indexOf(a)||n.push(a),~e.indexOf(`${o}-${a}`)||r.push([o,a])}for(let s in t)if((0,iw.default)(t,s)){let o=t[s];~n.indexOf(s)||n.push(s),aw.default.isRef(o)&&o.isSibling?i(o.path,s):(0,uw.default)(o)&&"deps"in o&&o.deps.forEach(a=>i(a,s))}return sw.default.array(n,r).reverse()}});var fy=H(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});Ed.default=lw;function py(t,e){let r=1/0;return t.some((n,i)=>{var s;if(((s=e.path)==null?void 0:s.indexOf(n))!==-1)return r=i,!0}),r}function lw(t){return(e,r)=>py(t,e)-py(t,r)}});var Ay=H(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.create=Ty;ro.default=void 0;var my=Wt(require("lodash/has")),hy=Wt(require("lodash/snakeCase")),dw=Wt(require("lodash/camelCase")),pw=Wt(require("lodash/mapKeys")),fw=Wt(require("lodash/mapValues")),mw=qs(),gy=er(),hw=Wt(dy()),Ey=Wt(fy()),gw=Wt(cu()),yw=Wt(Dn()),Td=Wt(rr());function Wt(t){return t&&t.__esModule?t:{default:t}}function Ui(){return Ui=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},Ui.apply(this,arguments)}var yy=t=>Object.prototype.toString.call(t)==="[object Object]";function Ew(t,e){let r=Object.keys(t.fields);return Object.keys(e).filter(n=>r.indexOf(n)===-1)}var Tw=(0,Ey.default)([]),to=class extends Td.default{constructor(e){super({type:"object"}),this.fields=Object.create(null),this._sortErrors=Tw,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{this.transform(function(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}return this.isType(n)?n:null}),e&&this.shape(e)})}_typeCheck(e){return yy(e)||typeof e=="function"}_cast(e,r={}){var n;let i=super._cast(e,r);if(i===void 0)return this.getDefault();if(!this._typeCheck(i))return i;let s=this.fields,o=(n=r.stripUnknown)!=null?n:this.spec.noUnknown,a=this._nodes.concat(Object.keys(i).filter(m=>this._nodes.indexOf(m)===-1)),u={},c=Ui({},r,{parent:u,__validating:r.__validating||!1}),l=!1;for(let m of a){let p=s[m],f=(0,my.default)(i,m);if(p){let d,g=i[m];c.path=(r.path?`${r.path}.`:"")+m,p=p.resolve({value:g,context:r.context,parent:u});let E="spec"in p?p.spec:void 0,y=E?.strict;if(E?.strip){l=l||m in i;continue}d=!r.__validating||!y?p.cast(i[m],c):i[m],d!==void 0&&(u[m]=d)}else f&&!o&&(u[m]=i[m]);u[m]!==i[m]&&(l=!0)}return l?u:i}_validate(e,r={},n){let i=[],{sync:s,from:o=[],originalValue:a=e,abortEarly:u=this.spec.abortEarly,recursive:c=this.spec.recursive}=r;o=[{schema:this,value:a},...o],r.__validating=!0,r.originalValue=a,r.from=o,super._validate(e,r,(l,m)=>{if(l){if(!yw.default.isError(l)||u)return void n(l,m);i.push(l)}if(!c||!yy(m)){n(i[0]||null,m);return}a=a||m;let p=this._nodes.map(f=>(d,g)=>{let E=f.indexOf(".")===-1?(r.path?`${r.path}.`:"")+f:`${r.path||""}["${f}"]`,y=this.fields[f];if(y&&"validate"in y){y.validate(m[f],Ui({},r,{path:E,from:o,strict:!0,parent:m,originalValue:a[f]}),g);return}g(null)});(0,gw.default)({sync:s,tests:p,value:m,errors:i,endEarly:u,sort:this._sortErrors,path:r.path},n)})}clone(e){let r=super.clone(e);return r.fields=Ui({},this.fields),r._nodes=this._nodes,r._excludedEdges=this._excludedEdges,r._sortErrors=this._sortErrors,r}concat(e){let r=super.concat(e),n=r.fields;for(let[i,s]of Object.entries(this.fields)){let o=n[i];o===void 0?n[i]=s:o instanceof Td.default&&s instanceof Td.default&&(n[i]=s.concat(o))}return r.withMutation(()=>r.shape(n))}getDefaultFromShape(){let e={};return this._nodes.forEach(r=>{let n=this.fields[r];e[r]="default"in n?n.getDefault():void 0}),e}_getDefault(){if("default"in this.spec)return super._getDefault();if(this._nodes.length)return this.getDefaultFromShape()}shape(e,r=[]){let n=this.clone(),i=Object.assign(n.fields,e);if(n.fields=i,n._sortErrors=(0,Ey.default)(Object.keys(i)),r.length){Array.isArray(r[0])||(r=[r]);let s=r.map(([o,a])=>`${o}-${a}`);n._excludedEdges=n._excludedEdges.concat(s)}return n._nodes=(0,hw.default)(i,n._excludedEdges),n}pick(e){let r={};for(let n of e)this.fields[n]&&(r[n]=this.fields[n]);return this.clone().withMutation(n=>(n.fields={},n.shape(r)))}omit(e){let r=this.clone(),n=r.fields;r.fields={};for(let i of e)delete n[i];return r.withMutation(()=>r.shape(n))}from(e,r,n){let i=(0,mw.getter)(e,!0);return this.transform(s=>{if(s==null)return s;let o=s;return(0,my.default)(s,e)&&(o=Ui({},s),n||delete o[e],o[r]=i(s)),o})}noUnknown(e=!0,r=gy.object.noUnknown){typeof e=="string"&&(r=e,e=!0);let n=this.test({name:"noUnknown",exclusive:!0,message:r,test(i){if(i==null)return!0;let s=Ew(this.schema,i);return!e||s.length===0||this.createError({params:{unknown:s.join(", ")}})}});return n.spec.noUnknown=e,n}unknown(e=!0,r=gy.object.noUnknown){return this.noUnknown(!e,r)}transformKeys(e){return this.transform(r=>r&&(0,pw.default)(r,(n,i)=>e(i)))}camelCase(){return this.transformKeys(dw.default)}snakeCase(){return this.transformKeys(hy.default)}constantCase(){return this.transformKeys(e=>(0,hy.default)(e).toUpperCase())}describe(){let e=super.describe();return e.fields=(0,fw.default)(this.fields,r=>r.describe()),e}};ro.default=to;function Ty(t){return new to(t)}Ty.prototype=to.prototype});var _y=H(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.create=Sy;io.default=void 0;var Ad=Mi(Pi()),Aw=Mi(vi()),Sw=Mi(Vs()),Sd=er(),_w=Mi(cu()),Iw=Mi(Dn()),Ow=Mi(rr());function Mi(t){return t&&t.__esModule?t:{default:t}}function Tu(){return Tu=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},Tu.apply(this,arguments)}function Sy(t){return new no(t)}var no=class extends Ow.default{constructor(e){super({type:"array"}),this.innerType=e,this.withMutation(()=>{this.transform(function(r){if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}return this.isType(r)?r:null})})}_typeCheck(e){return Array.isArray(e)}get _subType(){return this.innerType}_cast(e,r){let n=super._cast(e,r);if(!this._typeCheck(n)||!this.innerType)return n;let i=!1,s=n.map((o,a)=>{let u=this.innerType.cast(o,Tu({},r,{path:`${r.path||""}[${a}]`}));return u!==o&&(i=!0),u});return i?s:n}_validate(e,r={},n){var i,s;let o=[],a=r.sync,u=r.path,c=this.innerType,l=(i=r.abortEarly)!=null?i:this.spec.abortEarly,m=(s=r.recursive)!=null?s:this.spec.recursive,p=r.originalValue!=null?r.originalValue:e;super._validate(e,r,(f,d)=>{if(f){if(!Iw.default.isError(f)||l)return void n(f,d);o.push(f)}if(!m||!c||!this._typeCheck(d)){n(o[0]||null,d);return}p=p||d;let g=new Array(d.length);for(let E=0;E<d.length;E++){let y=d[E],S=`${r.path||""}[${E}]`,O=Tu({},r,{path:S,strict:!0,parent:d,index:E,originalValue:p[E]});g[E]=(R,T)=>c.validate(y,O,T)}(0,_w.default)({sync:a,path:u,value:d,errors:o,endEarly:l,tests:g},n)})}clone(e){let r=super.clone(e);return r.innerType=this.innerType,r}concat(e){let r=super.concat(e);return r.innerType=this.innerType,e.innerType&&(r.innerType=r.innerType?r.innerType.concat(e.innerType):e.innerType),r}of(e){let r=this.clone();if(!(0,Aw.default)(e))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+(0,Sw.default)(e));return r.innerType=e,r}length(e,r=Sd.array.length){return this.test({message:r,name:"length",exclusive:!0,params:{length:e},test(n){return(0,Ad.default)(n)||n.length===this.resolve(e)}})}min(e,r){return r=r||Sd.array.min,this.test({message:r,name:"min",exclusive:!0,params:{min:e},test(n){return(0,Ad.default)(n)||n.length>=this.resolve(e)}})}max(e,r){return r=r||Sd.array.max,this.test({message:r,name:"max",exclusive:!0,params:{max:e},test(n){return(0,Ad.default)(n)||n.length<=this.resolve(e)}})}ensure(){return this.default(()=>[]).transform((e,r)=>this._typeCheck(e)?e:r==null?[]:[].concat(r))}compact(e){let r=e?(n,i,s)=>!e(n,i,s):n=>!!n;return this.transform(n=>n!=null?n.filter(r):n)}describe(){let e=super.describe();return this.innerType&&(e.innerType=this.innerType.describe()),e}nullable(e=!0){return super.nullable(e)}defined(){return super.defined()}required(e){return super.required(e)}};io.default=no;Sy.prototype=no.prototype});var Iy=H(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.create=ww;so.default=void 0;var xw=Rw(vi());function Rw(t){return t&&t.__esModule?t:{default:t}}function ww(t){return new Au(t)}var Au=class{constructor(e){this.type="lazy",this.__isYupSchema__=!0,this._resolve=(r,n={})=>{let i=this.builder(r,n);if(!(0,xw.default)(i))throw new TypeError("lazy() functions must return a valid schema");return i.resolve(n)},this.builder=e}resolve(e){return this._resolve(e.value,e)}cast(e,r){return this._resolve(e,r).cast(e,r)}validate(e,r,n){return this._resolve(e,r).validate(e,r,n)}validateSync(e,r){return this._resolve(e,r).validateSync(e,r)}validateAt(e,r,n){return this._resolve(r,n).validateAt(e,r,n)}validateSyncAt(e,r,n){return this._resolve(r,n).validateSyncAt(e,r,n)}describe(){return null}isValid(e,r){return this._resolve(e,r).isValid(e,r)}isValidSync(e,r){return this._resolve(e,r).isValidSync(e,r)}},bw=Au;so.default=bw});var Oy=H(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});_d.default=vw;var Dw=Cw(er());function Cw(t){return t&&t.__esModule?t:{default:t}}function vw(t){Object.keys(t).forEach(e=>{Object.keys(t[e]).forEach(r=>{Dw.default[e][r]=t[e][r]})})}});var Od=H(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.addMethod=kw;Object.defineProperty(fe,"MixedSchema",{enumerable:!0,get:function(){return xy.default}});Object.defineProperty(fe,"mixed",{enumerable:!0,get:function(){return xy.create}});Object.defineProperty(fe,"BooleanSchema",{enumerable:!0,get:function(){return Id.default}});Object.defineProperty(fe,"bool",{enumerable:!0,get:function(){return Id.create}});Object.defineProperty(fe,"boolean",{enumerable:!0,get:function(){return Id.create}});Object.defineProperty(fe,"StringSchema",{enumerable:!0,get:function(){return Ry.default}});Object.defineProperty(fe,"string",{enumerable:!0,get:function(){return Ry.create}});Object.defineProperty(fe,"NumberSchema",{enumerable:!0,get:function(){return wy.default}});Object.defineProperty(fe,"number",{enumerable:!0,get:function(){return wy.create}});Object.defineProperty(fe,"DateSchema",{enumerable:!0,get:function(){return by.default}});Object.defineProperty(fe,"date",{enumerable:!0,get:function(){return by.create}});Object.defineProperty(fe,"ObjectSchema",{enumerable:!0,get:function(){return Dy.default}});Object.defineProperty(fe,"object",{enumerable:!0,get:function(){return Dy.create}});Object.defineProperty(fe,"ArraySchema",{enumerable:!0,get:function(){return Cy.default}});Object.defineProperty(fe,"array",{enumerable:!0,get:function(){return Cy.create}});Object.defineProperty(fe,"ref",{enumerable:!0,get:function(){return Nw.create}});Object.defineProperty(fe,"lazy",{enumerable:!0,get:function(){return Pw.create}});Object.defineProperty(fe,"ValidationError",{enumerable:!0,get:function(){return Lw.default}});Object.defineProperty(fe,"reach",{enumerable:!0,get:function(){return Uw.default}});Object.defineProperty(fe,"isSchema",{enumerable:!0,get:function(){return vy.default}});Object.defineProperty(fe,"setLocale",{enumerable:!0,get:function(){return Mw.default}});Object.defineProperty(fe,"BaseSchema",{enumerable:!0,get:function(){return Fw.default}});var xy=Ln(Hg()),Id=Ln(Zg()),Ry=Ln(ty()),wy=Ln(iy()),by=Ln(uy()),Dy=Ln(Ay()),Cy=Ln(_y()),Nw=vn(),Pw=Iy(),Lw=oo(Dn()),Uw=oo(ld()),vy=oo(vi()),Mw=oo(Oy()),Fw=oo(rr());function oo(t){return t&&t.__esModule?t:{default:t}}function Ny(){if(typeof WeakMap!="function")return null;var t=new WeakMap;return Ny=function(){return t},t}function Ln(t){if(t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var e=Ny();if(e&&e.has(t))return e.get(t);var r={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=n?Object.getOwnPropertyDescriptor(t,i):null;s&&(s.get||s.set)?Object.defineProperty(r,i,s):r[i]=t[i]}return r.default=t,e&&e.set(t,r),r}function kw(t,e,r){if(!t||!(0,vy.default)(t.prototype))throw new TypeError("You must provide a yup schema constructor function");if(typeof e!="string")throw new TypeError("A Method name must be provided");if(typeof r!="function")throw new TypeError("Method function must be provided");t.prototype[e]=r}});var Py=H(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var xd=wd();Rd.default=()=>{(0,xd.registerOptionPreset)("npm-node-cron",{presetId:"npm-node-cron",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:0,maxValue:11},daysOfWeek:{minValue:0,maxValue:6},years:{minValue:1970,maxValue:2099}}),(0,xd.registerOptionPreset)("aws-cloud-watch",{presetId:"aws-cloud-watch",useSeconds:!1,useYears:!0,useAliases:!0,useBlankDay:!0,allowOnlyOneBlankDayField:!0,mustHaveBlankDayField:!0,useLastDayOfMonth:!0,useLastDayOfWeek:!0,useNearestWeekday:!0,useNthWeekdayOfMonth:!0,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:1,maxValue:7},years:{minValue:1970,maxValue:2199}}),(0,xd.registerOptionPreset)("npm-cron-schedule",{presetId:"npm-cron-schedule",useSeconds:!0,useYears:!1,useAliases:!0,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:1,maxValue:31},months:{minValue:1,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}})}});var wd=H(Pe=>{"use strict";var Bw=Pe&&Pe.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Gw=Pe&&Pe.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$w=Pe&&Pe.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bw(e,t,r);return Gw(e,t),e},Vw=Pe&&Pe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.validateOptions=Pe.registerOptionPreset=Pe.getOptionPresets=Pe.getOptionPreset=void 0;var w=$w(Od());Od();var ao=Ot(),qw=Vw(Py());xt();var Un={default:{presetId:"default",useSeconds:!1,useYears:!1,useAliases:!1,useBlankDay:!1,allowOnlyOneBlankDayField:!1,mustHaveBlankDayField:!1,useLastDayOfMonth:!1,useLastDayOfWeek:!1,useNearestWeekday:!1,useNthWeekdayOfMonth:!1,seconds:{minValue:0,maxValue:59},minutes:{minValue:0,maxValue:59},hours:{minValue:0,maxValue:23},daysOfMonth:{minValue:0,maxValue:31},months:{minValue:0,maxValue:12},daysOfWeek:{minValue:0,maxValue:7},years:{minValue:1970,maxValue:2099}}},Ly=w.object({presetId:w.string().required(),useSeconds:w.boolean().required(),useYears:w.boolean().required(),useAliases:w.boolean(),useBlankDay:w.boolean().required(),allowOnlyOneBlankDayField:w.boolean().required(),mustHaveBlankDayField:w.boolean(),useLastDayOfMonth:w.boolean(),useLastDayOfWeek:w.boolean(),useNearestWeekday:w.boolean(),useNthWeekdayOfMonth:w.boolean(),seconds:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),minutes:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),hours:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),daysOfMonth:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),months:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),daysOfWeek:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required(),years:w.object({minValue:w.number().min(0).required(),maxValue:w.number().min(0).required(),lowerLimit:w.number().min(0),upperLimit:w.number().min(0)}).required()}).required(),Ww=t=>Un[t]?(0,ao.valid)(Un[t]):(0,ao.err)(`Option preset '${t}' not found.`);Pe.getOptionPreset=Ww;var Qw=()=>Un;Pe.getOptionPresets=Qw;var jw=(t,e)=>{Un[t]=Ly.validateSync(e,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0})};Pe.registerOptionPreset=jw;var Hw=t=>{var e,r,n,i,s,o,a,u,c,l,m,p,f,d,g,E,y,S,O,R;try{(0,qw.default)();let T;if(t.preset)if(typeof t.preset=="string"){if(!Un[t.preset])return(0,ao.err)([`Option preset ${t.preset} does not exist.`]);T=Un[t.preset]}else T=t.preset;else T=Un.default;let _=Object.assign(Object.assign({presetId:T.presetId,preset:T},{useSeconds:T.useSeconds,useYears:T.useYears,useAliases:(e=T.useAliases)!==null&&e!==void 0?e:!1,useBlankDay:T.useBlankDay,allowOnlyOneBlankDayField:T.allowOnlyOneBlankDayField,mustHaveBlankDayField:(r=T.mustHaveBlankDayField)!==null&&r!==void 0?r:!1,useLastDayOfMonth:(n=T.useLastDayOfMonth)!==null&&n!==void 0?n:!1,useLastDayOfWeek:(i=T.useLastDayOfWeek)!==null&&i!==void 0?i:!1,useNearestWeekday:(s=T.useNearestWeekday)!==null&&s!==void 0?s:!1,useNthWeekdayOfMonth:(o=T.useNthWeekdayOfMonth)!==null&&o!==void 0?o:!1,seconds:{lowerLimit:(a=T.seconds.lowerLimit)!==null&&a!==void 0?a:T.seconds.minValue,upperLimit:(u=T.seconds.upperLimit)!==null&&u!==void 0?u:T.seconds.maxValue},minutes:{lowerLimit:(c=T.minutes.lowerLimit)!==null&&c!==void 0?c:T.minutes.minValue,upperLimit:(l=T.minutes.upperLimit)!==null&&l!==void 0?l:T.minutes.maxValue},hours:{lowerLimit:(m=T.hours.lowerLimit)!==null&&m!==void 0?m:T.hours.minValue,upperLimit:(p=T.hours.upperLimit)!==null&&p!==void 0?p:T.hours.maxValue},daysOfMonth:{lowerLimit:(f=T.daysOfMonth.lowerLimit)!==null&&f!==void 0?f:T.daysOfMonth.minValue,upperLimit:(d=T.daysOfMonth.upperLimit)!==null&&d!==void 0?d:T.daysOfMonth.maxValue},months:{lowerLimit:(g=T.months.lowerLimit)!==null&&g!==void 0?g:T.months.minValue,upperLimit:(E=T.months.upperLimit)!==null&&E!==void 0?E:T.months.maxValue},daysOfWeek:{lowerLimit:(y=T.daysOfWeek.lowerLimit)!==null&&y!==void 0?y:T.daysOfWeek.minValue,upperLimit:(S=T.daysOfWeek.upperLimit)!==null&&S!==void 0?S:T.daysOfWeek.maxValue},years:{lowerLimit:(O=T.years.lowerLimit)!==null&&O!==void 0?O:T.years.minValue,upperLimit:(R=T.years.upperLimit)!==null&&R!==void 0?R:T.years.maxValue}}),t.override),b=w.object({presetId:w.string().required(),preset:Ly.required(),useSeconds:w.boolean().required(),useYears:w.boolean().required(),useAliases:w.boolean(),useBlankDay:w.boolean().required(),allowOnlyOneBlankDayField:w.boolean().required(),mustHaveBlankDayField:w.boolean(),useLastDayOfMonth:w.boolean(),useLastDayOfWeek:w.boolean(),useNearestWeekday:w.boolean(),useNthWeekdayOfMonth:w.boolean(),seconds:w.object({lowerLimit:w.number().min(T.seconds.minValue).max(T.seconds.maxValue),upperLimit:w.number().min(T.seconds.minValue).max(T.seconds.maxValue)}).required(),minutes:w.object({lowerLimit:w.number().min(T.minutes.minValue).max(T.minutes.maxValue),upperLimit:w.number().min(T.minutes.minValue).max(T.minutes.maxValue)}).required(),hours:w.object({lowerLimit:w.number().min(T.hours.minValue).max(T.hours.maxValue),upperLimit:w.number().min(T.hours.minValue).max(T.hours.maxValue)}).required(),daysOfMonth:w.object({lowerLimit:w.number().min(T.daysOfMonth.minValue).max(T.daysOfMonth.maxValue),upperLimit:w.number().min(T.daysOfMonth.minValue).max(T.daysOfMonth.maxValue)}).required(),months:w.object({lowerLimit:w.number().min(T.months.minValue).max(T.months.maxValue),upperLimit:w.number().min(T.months.minValue).max(T.months.maxValue)}).required(),daysOfWeek:w.object({lowerLimit:w.number().min(T.daysOfWeek.minValue).max(T.daysOfWeek.maxValue),upperLimit:w.number().min(T.daysOfWeek.minValue).max(T.daysOfWeek.maxValue)}).required(),years:w.object({lowerLimit:w.number().min(T.years.minValue).max(T.years.maxValue),upperLimit:w.number().min(T.years.minValue).max(T.years.maxValue)}).required()}).required().validateSync(_,{strict:!1,abortEarly:!1,stripUnknown:!0,recursive:!0});return(0,ao.valid)(b)}catch(T){return(0,ao.err)(T.errors)}};Pe.validateOptions=Hw});var Vt=H((uo,Dd)=>{"use strict";var Fn=uo&&uo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(uo,"__esModule",{value:!0});var Mn=Ot(),Kw=Fn(cg()),Yw=Fn(lg()),Jw=Fn(dg()),zw=Fn(pg()),Zw=Fn(fg()),Xw=Fn(mg()),eb=Fn(hg()),tb=wd();xt();var rb=(t,e)=>{let r=t.trim().split(" ");if(e.useSeconds&&e.useYears&&r.length!==7)return(0,Mn.err)(`Expected 7 values, but got ${r.length}.`);if((e.useSeconds&&!e.useYears||e.useYears&&!e.useSeconds)&&r.length!==6)return(0,Mn.err)(`Expected 6 values, but got ${r.length}.`);if(!e.useSeconds&&!e.useYears&&r.length!==5)return(0,Mn.err)(`Expected 5 values, but got ${r.length}.`);let n={seconds:e.useSeconds?r[0]:void 0,minutes:r[e.useSeconds?1:0],hours:r[e.useSeconds?2:1],daysOfMonth:r[e.useSeconds?3:2],months:r[e.useSeconds?4:3],daysOfWeek:r[e.useSeconds?5:4],years:e.useYears?r[e.useSeconds?6:5]:void 0};return(0,Mn.valid)(n)},bd=(t,e={})=>{let r=(0,tb.validateOptions)(e);if(r.isError())return r;let n=r.getValue(),i=rb(t,n);if(i.isError())return(0,Mn.err)([`${i.getError()} (Input cron: '${t}')`]);let s=i.getValue(),o=[];if(n.useSeconds&&o.push((0,Kw.default)(s,n)),o.push((0,Yw.default)(s,n)),o.push((0,Jw.default)(s,n)),o.push((0,zw.default)(s,n)),o.push((0,Zw.default)(s,n)),o.push((0,Xw.default)(s,n)),n.useYears&&o.push((0,eb.default)(s,n)),o.every(u=>u.isValid()))return(0,Mn.valid)(s);let a=[];return o.forEach(u=>{u.isError()&&u.getError().forEach(c=>{a.push(c)})}),a.forEach((u,c)=>{a[c]=`${u} (Input cron: '${t}')`}),(0,Mn.err)(a)};uo.default=bd;Dd.exports=bd;Dd.exports.default=bd});var iT=H(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});var sr=class extends Error{},kd=class extends sr{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Bd=class extends sr{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Gd=class extends sr{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Gn=class extends sr{},wu=class extends sr{constructor(e){super(`Invalid unit ${e}`)}},Ke=class extends sr{},Qt=class extends sr{constructor(){super("Zone is an abstract class")}},C="numeric",Dt="short",nt="long",bu={year:C,month:C,day:C},oE={year:C,month:Dt,day:C},nb={year:C,month:Dt,day:C,weekday:Dt},aE={year:C,month:nt,day:C},uE={year:C,month:nt,day:C,weekday:nt},cE={hour:C,minute:C},lE={hour:C,minute:C,second:C},dE={hour:C,minute:C,second:C,timeZoneName:Dt},pE={hour:C,minute:C,second:C,timeZoneName:nt},fE={hour:C,minute:C,hourCycle:"h23"},mE={hour:C,minute:C,second:C,hourCycle:"h23"},hE={hour:C,minute:C,second:C,hourCycle:"h23",timeZoneName:Dt},gE={hour:C,minute:C,second:C,hourCycle:"h23",timeZoneName:nt},yE={year:C,month:C,day:C,hour:C,minute:C},EE={year:C,month:C,day:C,hour:C,minute:C,second:C},TE={year:C,month:Dt,day:C,hour:C,minute:C},AE={year:C,month:Dt,day:C,hour:C,minute:C,second:C},ib={year:C,month:Dt,day:C,weekday:Dt,hour:C,minute:C},SE={year:C,month:nt,day:C,hour:C,minute:C,timeZoneName:Dt},_E={year:C,month:nt,day:C,hour:C,minute:C,second:C,timeZoneName:Dt},IE={year:C,month:nt,day:C,weekday:nt,hour:C,minute:C,timeZoneName:nt},OE={year:C,month:nt,day:C,weekday:nt,hour:C,minute:C,second:C,timeZoneName:nt},Lr=class{get type(){throw new Qt}get name(){throw new Qt}get ianaName(){return this.name}get isUniversal(){throw new Qt}offsetName(e,r){throw new Qt}formatOffset(e,r){throw new Qt}offset(e){throw new Qt}equals(e){throw new Qt}get isValid(){throw new Qt}},Cd=null,go=class t extends Lr{static get instance(){return Cd===null&&(Cd=new t),Cd}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return RE(e,r,n)}formatOffset(e,r){return ho(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},xu={};function sb(t){return xu[t]||(xu[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),xu[t]}var ob={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ab(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,s,o,a,u,c,l]=n;return[o,i,s,a,u,c,l]}function ub(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=ob[s];s==="era"?n[a]=o:oe(a)||(n[a]=parseInt(o,10))}return n}var Su={},or=class t extends Lr{static create(e){return Su[e]||(Su[e]=new t(e)),Su[e]}static resetCache(){Su={},xu={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return RE(e,r,n,this.name)}formatOffset(e,r){return ho(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=sb(this.name),[i,s,o,a,u,c,l]=n.formatToParts?ub(n,r):ab(n,r);a==="BC"&&(i=-Math.abs(i)+1);let p=Zd({year:i,month:s,day:o,hour:u===24?0:u,minute:c,second:l,millisecond:0}),f=+r,d=f%1e3;return f-=d>=0?d:1e3+d,(p-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},Uy={};function cb(t,e={}){let r=JSON.stringify([t,e]),n=Uy[r];return n||(n=new Intl.ListFormat(t,e),Uy[r]=n),n}var $d={};function Vd(t,e={}){let r=JSON.stringify([t,e]),n=$d[r];return n||(n=new Intl.DateTimeFormat(t,e),$d[r]=n),n}var qd={};function lb(t,e={}){let r=JSON.stringify([t,e]),n=qd[r];return n||(n=new Intl.NumberFormat(t,e),qd[r]=n),n}var Wd={};function db(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=Wd[i];return s||(s=new Intl.RelativeTimeFormat(t,e),Wd[i]=s),s}var fo=null;function pb(){return fo||(fo=new Intl.DateTimeFormat().resolvedOptions().locale,fo)}function fb(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=Vd(t).resolvedOptions(),i=t}catch{let u=t.substring(0,r);n=Vd(u).resolvedOptions(),i=u}let{numberingSystem:s,calendar:o}=n;return[i,s,o]}}function mb(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function hb(t){let e=[];for(let r=1;r<=12;r++){let n=Ie.utc(2016,r,1);e.push(t(n))}return e}function gb(t){let e=[];for(let r=1;r<=7;r++){let n=Ie.utc(2016,11,13+r);e.push(t(n))}return e}function _u(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function yb(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var Qd=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:s,...o}=n;if(!r||Object.keys(o).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=lb(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):zd(e,3);return Re(r,this.padTo)}}},jd=class{constructor(e,r,n){this.opts=n;let i;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&or.create(a).valid?(i=a,this.dt=e):(i="UTC",n.timeZoneName?this.dt=e:this.dt=e.offset===0?e:Ie.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);let s={...this.opts};s.timeZone=s.timeZone||i,this.dtf=Vd(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},Hd=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&xE()&&(this.rtf=db(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):Pb(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},_e=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,r,n,i=!1){let s=e||Ee.defaultLocale,o=s||(i?"en-US":pb()),a=r||Ee.defaultNumberingSystem,u=n||Ee.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){fo=null,$d={},qd={},Wd={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=fb(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=mb(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=yb(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1,n=!0){return _u(this,e,n,DE,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=hb(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return _u(this,e,n,NE,()=>{let i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=r?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=gb(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return _u(this,void 0,e,()=>PE,()=>{if(!this.meridiemCache){let r={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Ie.utc(2016,11,13,9),Ie.utc(2016,11,13,19)].map(n=>this.extract(n,r,"dayperiod"))}return this.meridiemCache})}eras(e,r=!0){return _u(this,e,r,LE,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[Ie.utc(-40,1,1),Ie.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),s=i.formatToParts(),o=s.find(a=>a.type.toLowerCase()===n);return o?o.value:null}numberFormatter(e={}){return new Qd(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new jd(e,this.intl,r)}relFormatter(e={}){return new Hd(this.intl,this.isEnglish(),e)}listFormatter(e={}){return cb(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}},vd=null,it=class t extends Lr{static get utcInstance(){return vd===null&&(vd=new t(0)),vd}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(Lu(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ho(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ho(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return ho(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},Du=class extends Lr{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Pr(t,e){if(oe(t)||t===null)return e;if(t instanceof Lr)return t;if(Eb(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?go.instance:r==="utc"||r==="gmt"?it.utcInstance:it.parseSpecifier(r)||or.create(t)}else return Vn(t)?it.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new Du(t)}var My=()=>Date.now(),Fy="system",ky=null,By=null,Gy=null,$y=60,Vy,Ee=class{static get now(){return My}static set now(e){My=e}static set defaultZone(e){Fy=e}static get defaultZone(){return Pr(Fy,go.instance)}static get defaultLocale(){return ky}static set defaultLocale(e){ky=e}static get defaultNumberingSystem(){return By}static set defaultNumberingSystem(e){By=e}static get defaultOutputCalendar(){return Gy}static set defaultOutputCalendar(e){Gy=e}static get twoDigitCutoffYear(){return $y}static set twoDigitCutoffYear(e){$y=e%100}static get throwOnInvalid(){return Vy}static set throwOnInvalid(e){Vy=e}static resetCaches(){_e.resetCache(),or.resetCache()}};function oe(t){return typeof t>"u"}function Vn(t){return typeof t=="number"}function Pu(t){return typeof t=="number"&&t%1===0}function Eb(t){return typeof t=="string"}function Tb(t){return Object.prototype.toString.call(t)==="[object Date]"}function xE(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ab(t){return Array.isArray(t)?t:[t]}function qy(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let s=[e(i),i];return n&&r(n[0],s[0])===n[0]?n:s},null)[1]}function Sb(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function Gi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ir(t,e,r){return Pu(t)&&t>=e&&t<=r}function _b(t,e){return t-e*Math.floor(t/e)}function Re(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function Nr(t){if(!(oe(t)||t===null||t===""))return parseInt(t,10)}function kn(t){if(!(oe(t)||t===null||t===""))return parseFloat(t)}function Jd(t){if(!(oe(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function zd(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function yo(t){return t%4===0&&(t%100!==0||t%400===0)}function mo(t){return yo(t)?366:365}function Cu(t,e){let r=_b(e-1,12)+1,n=t+(e-r)/12;return r===2?yo(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function Zd(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function vu(t){let e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,r=t-1,n=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7;return e===4||n===3?53:52}function Kd(t){return t>99?t:t>Ee.twoDigitCutoffYear?1900+t:2e3+t}function RE(t,e,r,n=null){let i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(s.timeZone=n);let o={timeZoneName:e,...s},a=new Intl.DateTimeFormat(r,o).formatToParts(i).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function Lu(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function wE(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Ke(`Invalid unit value ${t}`);return e}function Nu(t,e){let r={};for(let n in t)if(Gi(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=wE(i)}return r}function ho(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Re(r,2)}:${Re(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Re(r,2)}${Re(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Uu(t){return Sb(t,["hour","minute","second","millisecond"])}var Ib=["January","February","March","April","May","June","July","August","September","October","November","December"],bE=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ob=["J","F","M","A","M","J","J","A","S","O","N","D"];function DE(t){switch(t){case"narrow":return[...Ob];case"short":return[...bE];case"long":return[...Ib];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var CE=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],vE=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],xb=["M","T","W","T","F","S","S"];function NE(t){switch(t){case"narrow":return[...xb];case"short":return[...vE];case"long":return[...CE];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var PE=["AM","PM"],Rb=["Before Christ","Anno Domini"],wb=["BC","AD"],bb=["B","A"];function LE(t){switch(t){case"narrow":return[...bb];case"short":return[...wb];case"long":return[...Rb];default:return null}}function Db(t){return PE[t.hour<12?0:1]}function Cb(t,e){return NE(e)[t.weekday-1]}function vb(t,e){return DE(e)[t.month-1]}function Nb(t,e){return LE(e)[t.year<0?0:1]}function Pb(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&s){let m=t==="days";switch(e){case 1:return m?"tomorrow":`next ${i[t][0]}`;case-1:return m?"yesterday":`last ${i[t][0]}`;case 0:return m?"today":`this ${i[t][0]}`}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,c=i[t],l=n?u?c[1]:c[2]||c[1]:u?i[t][0]:t;return o?`${a} ${l} ago`:`in ${a} ${l}`}function Wy(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var Lb={D:bu,DD:oE,DDD:aE,DDDD:uE,t:cE,tt:lE,ttt:dE,tttt:pE,T:fE,TT:mE,TTT:hE,TTTT:gE,f:yE,ff:TE,fff:SE,ffff:IE,F:EE,FF:AE,FFF:_E,FFFF:OE},tt=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,s=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="'"?(n.length>0&&s.push({literal:i,val:n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&s.push({literal:!1,val:n}),n=a,r=a)}return n.length>0&&s.push({literal:i,val:n}),s}static macroTokenToFormatOpts(e){return Lb[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTime(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTimeParts(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).formatToParts()}formatInterval(e,r={}){return this.loc.dtFormatter(e.start,{...this.opts,...r}).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return Re(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(f,d)=>this.loc.extract(e,f,d),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>n?Db(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(f,d)=>n?vb(e,f):s(d?{month:f}:{month:f,day:"numeric"},"month"),c=(f,d)=>n?Cb(e,f):s(d?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),l=f=>{let d=t.macroTokenToFormatOpts(f);return d?this.formatWithSystemDefault(e,d):f},m=f=>n?Nb(e,f):s({era:f},"era"),p=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return m("short");case"GG":return m("long");case"GGGGG":return m("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return l(f)}};return Wy(t.parseFormat(r),p)}formatDurationFromString(e,r){let n=u=>{switch(u[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=u=>c=>{let l=n(c);return l?this.num(u.get(l),c.length):c},s=t.parseFormat(r),o=s.reduce((u,{literal:c,val:l})=>c?u:u.concat(l),[]),a=e.shiftTo(...o.map(n).filter(u=>u));return Wy(s,i(a))}},rt=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},UE=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function $i(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function Vi(...t){return e=>t.reduce(([r,n,i],s)=>{let[o,a,u]=s(e,i);return[{...r,...o},a||n,u]},[{},null,1]).slice(0,2)}function qi(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function ME(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=Nr(e[r+i]);return[n,null,r+i]}}var FE=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ub=`(?:${FE.source}?(?:\\[(${UE.source})\\])?)?`,Xd=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,kE=RegExp(`${Xd.source}${Ub}`),ep=RegExp(`(?:T${kE.source})?`),Mb=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Fb=/(\d{4})-?W(\d\d)(?:-?(\d))?/,kb=/(\d{4})-?(\d{3})/,Bb=ME("weekYear","weekNumber","weekDay"),Gb=ME("year","ordinal"),$b=/(\d{4})-(\d\d)-(\d\d)/,BE=RegExp(`${Xd.source} ?(?:${FE.source}|(${UE.source}))?`),Vb=RegExp(`(?: ${BE.source})?`);function Bi(t,e,r){let n=t[e];return oe(n)?r:Nr(n)}function qb(t,e){return[{year:Bi(t,e),month:Bi(t,e+1,1),day:Bi(t,e+2,1)},null,e+3]}function Wi(t,e){return[{hours:Bi(t,e,0),minutes:Bi(t,e+1,0),seconds:Bi(t,e+2,0),milliseconds:Jd(t[e+3])},null,e+4]}function Eo(t,e){let r=!t[e]&&!t[e+1],n=Lu(t[e+1],t[e+2]),i=r?null:it.instance(n);return[{},i,e+3]}function To(t,e){let r=t[e]?or.create(t[e]):null;return[{},r,e+1]}var Wb=RegExp(`^T?${Xd.source}$`),Qb=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function jb(t){let[e,r,n,i,s,o,a,u,c]=t,l=e[0]==="-",m=u&&u[0]==="-",p=(f,d=!1)=>f!==void 0&&(d||f&&l)?-f:f;return[{years:p(kn(r)),months:p(kn(n)),weeks:p(kn(i)),days:p(kn(s)),hours:p(kn(o)),minutes:p(kn(a)),seconds:p(kn(u),u==="-0"),milliseconds:p(Jd(c),m)}]}var Hb={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function tp(t,e,r,n,i,s,o){let a={year:e.length===2?Kd(Nr(e)):Nr(e),month:bE.indexOf(r)+1,day:Nr(n),hour:Nr(i),minute:Nr(s)};return o&&(a.second=Nr(o)),t&&(a.weekday=t.length>3?CE.indexOf(t)+1:vE.indexOf(t)+1),a}var Kb=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Yb(t){let[,e,r,n,i,s,o,a,u,c,l,m]=t,p=tp(e,i,n,r,s,o,a),f;return u?f=Hb[u]:c?f=0:f=Lu(l,m),[p,new it(f)]}function Jb(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var zb=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Zb=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Xb=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Qy(t){let[,e,r,n,i,s,o,a]=t;return[tp(e,i,n,r,s,o,a),it.utcInstance]}function eD(t){let[,e,r,n,i,s,o,a]=t;return[tp(e,a,r,n,i,s,o),it.utcInstance]}var tD=$i(Mb,ep),rD=$i(Fb,ep),nD=$i(kb,ep),iD=$i(kE),GE=Vi(qb,Wi,Eo,To),sD=Vi(Bb,Wi,Eo,To),oD=Vi(Gb,Wi,Eo,To),aD=Vi(Wi,Eo,To);function uD(t){return qi(t,[tD,GE],[rD,sD],[nD,oD],[iD,aD])}function cD(t){return qi(Jb(t),[Kb,Yb])}function lD(t){return qi(t,[zb,Qy],[Zb,Qy],[Xb,eD])}function dD(t){return qi(t,[Qb,jb])}var pD=Vi(Wi);function fD(t){return qi(t,[Wb,pD])}var mD=$i($b,Vb),hD=$i(BE),gD=Vi(Wi,Eo,To);function yD(t){return qi(t,[mD,GE],[hD,gD])}var ED="Invalid Duration",$E={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},TD={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...$E},mt=146097/400,Fi=146097/4800,AD={years:{quarters:4,months:12,weeks:mt/7,days:mt,hours:mt*24,minutes:mt*24*60,seconds:mt*24*60*60,milliseconds:mt*24*60*60*1e3},quarters:{months:3,weeks:mt/28,days:mt/4,hours:mt*24/4,minutes:mt*24*60/4,seconds:mt*24*60*60/4,milliseconds:mt*24*60*60*1e3/4},months:{weeks:Fi/7,days:Fi,hours:Fi*24,minutes:Fi*24*60,seconds:Fi*24*60*60,milliseconds:Fi*24*60*60*1e3},...$E},Bn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],SD=Bn.slice(0).reverse();function vr(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new De(n)}function _D(t){return t<0?Math.floor(t):Math.ceil(t)}function VE(t,e,r,n,i){let s=t[i][r],o=e[r]/s,a=Math.sign(o)===Math.sign(n[i]),u=!a&&n[i]!==0&&Math.abs(o)<=1?_D(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function ID(t,e){SD.reduce((r,n)=>oe(e[n])?r:(r&&VE(t,e,r,e,n),n),null)}function OD(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var De=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?AD:TD;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||_e.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new Ke(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:Nu(e,t.normalizeUnit),loc:_e.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(Vn(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new Ke(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=dD(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=fD(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new Ke("need to specify a reason the Duration is invalid");let n=e instanceof rt?e:new rt(e,r);if(Ee.throwOnInvalid)throw new Gd(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new wu(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?tt.create(this.loc,n).formatDurationFromString(this,e):ED}toHuman(e={}){let r=Bn.map(n=>{let i=this.values[n];return oe(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=zd(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();if(r<0||r>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};let n=this.shiftTo("hours","minutes","seconds","milliseconds"),i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||n.seconds!==0||n.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||n.milliseconds!==0)&&(i+=".SSS"));let s=n.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of Bn)(Gi(r.values,i)||Gi(this.values,i))&&(n[i]=r.get(i)+this.get(i));return vr(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=wE(e(this.values[n],n));return vr(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...Nu(e,t.normalizeUnit)};return vr(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let o={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return vr(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ID(this.matrix,e),vr(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=OD(this.normalize().shiftToAll().toObject());return vr(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>t.normalizeUnit(o));let r={},n={},i=this.toObject(),s;for(let o of Bn)if(e.indexOf(o)>=0){s=o;let a=0;for(let c in n)a+=this.matrix[c][o]*n[c],n[c]=0;Vn(i[o])&&(a+=i[o]);let u=Math.trunc(a);r[o]=u,n[o]=(a*1e3-u*1e3)/1e3;for(let c in i)Bn.indexOf(c)>Bn.indexOf(o)&&VE(this.matrix,i,c,r,o)}else Vn(i[o])&&(n[o]=i[o]);for(let o in n)n[o]!==0&&(r[s]+=o===s?n[o]:n[o]/this.matrix[s][o]);return vr(this,{values:r},!0).normalize()}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return vr(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of Bn)if(!r(this.values[n],e.values[n]))return!1;return!0}},ki="Invalid Interval";function xD(t,e){return!t||!t.isValid?qn.invalid("missing or invalid start"):!e||!e.isValid?qn.invalid("missing or invalid end"):e<t?qn.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var qn=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new Ke("need to specify a reason the Interval is invalid");let n=e instanceof rt?e:new rt(e,r);if(Ee.throwOnInvalid)throw new Bd(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=po(e),i=po(r),s=xD(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=De.fromDurationLike(r),i=po(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=De.fromDurationLike(r),i=po(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let s,o;try{s=Ie.fromISO(n,r),o=s.isValid}catch{o=!1}let a,u;try{a=Ie.fromISO(i,r),u=a.isValid}catch{u=!1}if(o&&u)return t.fromDateTimes(s,a);if(o){let c=De.fromISO(i,r);if(c.isValid)return t.after(s,c)}else if(u){let c=De.fromISO(n,r);if(c.isValid)return t.before(a,c)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let r=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(r,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(po).filter(o=>this.contains(o)).sort(),n=[],{s:i}=this,s=0;for(;i<this.e;){let o=r[s]||this.e,a=+o>+this.e?this.e:o;n.push(t.fromDateTimes(i,a)),i=a,s+=1}return n}splitBy(e){let r=De.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,s,o=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(u=>u*i));s=+a>+this.e?this.e:a,o.push(t.fromDateTimes(n,s)),n=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],s=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...s),a=o.sort((u,c)=>u.time-c.time);for(let u of a)n+=u.type==="s"?1:-1,n===1?r=u.time:(r&&+r!=+u.time&&i.push(t.fromDateTimes(r,u.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:ki}toLocaleString(e=bu,r={}){return this.isValid?tt.create(this.s.loc.clone(r),e).formatInterval(this):ki}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:ki}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:ki}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:ki}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:ki}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):De.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},$n=class{static hasDST(e=Ee.defaultZone){let r=Ie.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return or.isValidZone(e)}static normalizeZone(e){return Pr(e,Ee.defaultZone)}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||_e.create(r,n,s)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||_e.create(r,n,s)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||_e.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||_e.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return _e.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return _e.create(r,null,"gregory").eras(e)}static features(){return{relative:xE()}}};function jy(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(De.fromMillis(n).as("days"))}function RD(t,e,r){let n=[["years",(u,c)=>c.year-u.year],["quarters",(u,c)=>c.quarter-u.quarter+(c.year-u.year)*4],["months",(u,c)=>c.month-u.month+(c.year-u.year)*12],["weeks",(u,c)=>{let l=jy(u,c);return(l-l%7)/7}],["days",jy]],i={},s=t,o,a;for(let[u,c]of n)r.indexOf(u)>=0&&(o=u,i[u]=c(t,e),a=s.plus(i),a>e?(i[u]--,t=s.plus(i)):t=a);return[t,i,a,o]}function wD(t,e,r,n){let[i,s,o,a]=RD(t,e,r),u=e-i,c=r.filter(m=>["hours","minutes","seconds","milliseconds"].indexOf(m)>=0);c.length===0&&(o<e&&(o=i.plus({[a]:1})),o!==i&&(s[a]=(s[a]||0)+u/(o-i)));let l=De.fromObject(s,n);return c.length>0?De.fromMillis(u,n).shiftTo(...c).plus(l):l}var rp={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Hy={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},bD=rp.hanidec.replace(/[\[|\]]/g,"").split("");function DD(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(rp.hanidec)!==-1)e+=bD.indexOf(t[r]);else for(let i in Hy){let[s,o]=Hy[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function wt({numberingSystem:t},e=""){return new RegExp(`${rp[t||"latn"]}${e}`)}var CD="missing Intl.DateTimeFormat.formatToParts support";function le(t,e=r=>r){return{regex:t,deser:([r])=>e(DD(r))}}var vD=String.fromCharCode(160),qE=`[ ${vD}]`,WE=new RegExp(qE,"g");function ND(t){return t.replace(/\./g,"\\.?").replace(WE,qE)}function Ky(t){return t.replace(/\./g,"").replace(WE," ").toLowerCase()}function bt(t,e){return t===null?null:{regex:RegExp(t.map(ND).join("|")),deser:([r])=>t.findIndex(n=>Ky(r)===Ky(n))+e}}function Yy(t,e){return{regex:t,deser:([,r,n])=>Lu(r,n),groups:e}}function Nd(t){return{regex:t,deser:([e])=>e}}function PD(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function LD(t,e){let r=wt(e),n=wt(e,"{2}"),i=wt(e,"{3}"),s=wt(e,"{4}"),o=wt(e,"{6}"),a=wt(e,"{1,2}"),u=wt(e,"{1,3}"),c=wt(e,"{1,6}"),l=wt(e,"{1,9}"),m=wt(e,"{2,4}"),p=wt(e,"{4,6}"),f=E=>({regex:RegExp(PD(E.val)),deser:([y])=>y,literal:!0}),g=(E=>{if(t.literal)return f(E);switch(E.val){case"G":return bt(e.eras("short",!1),0);case"GG":return bt(e.eras("long",!1),0);case"y":return le(c);case"yy":return le(m,Kd);case"yyyy":return le(s);case"yyyyy":return le(p);case"yyyyyy":return le(o);case"M":return le(a);case"MM":return le(n);case"MMM":return bt(e.months("short",!0,!1),1);case"MMMM":return bt(e.months("long",!0,!1),1);case"L":return le(a);case"LL":return le(n);case"LLL":return bt(e.months("short",!1,!1),1);case"LLLL":return bt(e.months("long",!1,!1),1);case"d":return le(a);case"dd":return le(n);case"o":return le(u);case"ooo":return le(i);case"HH":return le(n);case"H":return le(a);case"hh":return le(n);case"h":return le(a);case"mm":return le(n);case"m":return le(a);case"q":return le(a);case"qq":return le(n);case"s":return le(a);case"ss":return le(n);case"S":return le(u);case"SSS":return le(i);case"u":return Nd(l);case"uu":return Nd(a);case"uuu":return le(r);case"a":return bt(e.meridiems(),0);case"kkkk":return le(s);case"kk":return le(m,Kd);case"W":return le(a);case"WW":return le(n);case"E":case"c":return le(r);case"EEE":return bt(e.weekdays("short",!1,!1),1);case"EEEE":return bt(e.weekdays("long",!1,!1),1);case"ccc":return bt(e.weekdays("short",!0,!1),1);case"cccc":return bt(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return Yy(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return Yy(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return Nd(/[a-z_+-/]{1,256}?/i);default:return f(E)}})(t)||{invalidReason:CD};return g.token=t,g}var UD={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function MD(t,e){let{type:r,value:n}=t;if(r==="literal")return{literal:!0,val:n};let i=e[r],s=UD[r];if(typeof s=="object"&&(s=s[i]),s)return{literal:!1,val:s}}function FD(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function kD(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(Gi(r,o)){let a=r[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(s,s+u))),s+=u}return[n,i]}else return[n,{}]}function BD(t){let e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return oe(t.z)||(r=or.create(t.z)),oe(t.Z)||(r||(r=new it(t.Z)),n=t.Z),oe(t.q)||(t.M=(t.q-1)*3+1),oe(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),oe(t.u)||(t.S=Jd(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var Pd=null;function GD(){return Pd||(Pd=Ie.fromMillis(1555555555555)),Pd}function $D(t,e){if(t.literal)return t;let r=tt.macroTokenToFormatOpts(t.val),n=HE(r,e);return n==null||n.includes(void 0)?t:n}function QE(t,e){return Array.prototype.concat(...t.map(r=>$D(r,e)))}function jE(t,e,r){let n=QE(tt.parseFormat(r),t),i=n.map(o=>LD(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=FD(i),u=RegExp(o,"i"),[c,l]=kD(e,u,a),[m,p,f]=l?BD(l):[null,null,void 0];if(Gi(l,"a")&&Gi(l,"H"))throw new Gn("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:u,rawMatches:c,matches:l,result:m,zone:p,specificOffset:f}}}function VD(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=jE(t,e,r);return[n,i,s,o]}function HE(t,e){return t?tt.create(e,t).formatDateTimeParts(GD()).map(i=>MD(i,t)):null}var KE=[0,31,59,90,120,151,181,212,243,273,304,334],YE=[0,31,60,91,121,152,182,213,244,274,305,335];function ht(t,e){return new rt("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function JE(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function zE(t,e,r){return r+(yo(t)?YE:KE)[e-1]}function ZE(t,e){let r=yo(t)?YE:KE,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function Yd(t){let{year:e,month:r,day:n}=t,i=zE(e,r,n),s=JE(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=vu(a)):o>vu(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...Uu(t)}}function Jy(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=JE(e,1,4),s=mo(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=mo(a)):o>s?(a=e+1,o-=mo(e)):a=e;let{month:u,day:c}=ZE(a,o);return{year:a,month:u,day:c,...Uu(t)}}function Ld(t){let{year:e,month:r,day:n}=t,i=zE(e,r,n);return{year:e,ordinal:i,...Uu(t)}}function zy(t){let{year:e,ordinal:r}=t,{month:n,day:i}=ZE(e,r);return{year:e,month:n,day:i,...Uu(t)}}function qD(t){let e=Pu(t.weekYear),r=ir(t.weekNumber,1,vu(t.weekYear)),n=ir(t.weekday,1,7);return e?r?n?!1:ht("weekday",t.weekday):ht("week",t.week):ht("weekYear",t.weekYear)}function WD(t){let e=Pu(t.year),r=ir(t.ordinal,1,mo(t.year));return e?r?!1:ht("ordinal",t.ordinal):ht("year",t.year)}function XE(t){let e=Pu(t.year),r=ir(t.month,1,12),n=ir(t.day,1,Cu(t.year,t.month));return e?r?n?!1:ht("day",t.day):ht("month",t.month):ht("year",t.year)}function eT(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=ir(e,0,23)||e===24&&r===0&&n===0&&i===0,o=ir(r,0,59),a=ir(n,0,59),u=ir(i,0,999);return s?o?a?u?!1:ht("millisecond",i):ht("second",n):ht("minute",r):ht("hour",e)}var Ud="Invalid DateTime",Zy=864e13;function Iu(t){return new rt("unsupported zone",`the zone "${t.name}" is not supported`)}function Md(t){return t.weekData===null&&(t.weekData=Yd(t.c)),t.weekData}function co(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new Ie({...r,...e,old:r})}function tT(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let s=r.offset(n);return i===s?[n,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function Xy(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Ru(t,e,r){return tT(Zd(t),e,r)}function eE(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:n,month:i,day:Math.min(t.c.day,Cu(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=De.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Zd(s),[u,c]=tT(a,r,t.zone);return o!==0&&(u+=o,c=t.zone.offset(u)),{ts:u,o:c}}function lo(t,e,r,n,i,s){let{setZone:o,zone:a}=r;if(t&&Object.keys(t).length!==0){let u=e||a,c=Ie.fromObject(t,{...r,zone:u,specificOffset:s});return o?c:c.setZone(a)}else return Ie.invalid(new rt("unparsable",`the input "${i}" can't be parsed as ${n}`))}function Ou(t,e,r=!0){return t.isValid?tt.create(_e.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Fd(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=Re(t.c.year,r?6:4),e?(n+="-",n+=Re(t.c.month),n+="-",n+=Re(t.c.day)):(n+=Re(t.c.month),n+=Re(t.c.day)),n}function tE(t,e,r,n,i,s){let o=Re(t.c.hour);return e?(o+=":",o+=Re(t.c.minute),(t.c.second!==0||!r)&&(o+=":")):o+=Re(t.c.minute),(t.c.second!==0||!r)&&(o+=Re(t.c.second),(t.c.millisecond!==0||!n)&&(o+=".",o+=Re(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=Re(Math.trunc(-t.o/60)),o+=":",o+=Re(Math.trunc(-t.o%60))):(o+="+",o+=Re(Math.trunc(t.o/60)),o+=":",o+=Re(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}var rT={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},QD={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},jD={ordinal:1,hour:0,minute:0,second:0,millisecond:0},nT=["year","month","day","hour","minute","second","millisecond"],HD=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],KD=["year","ordinal","hour","minute","second","millisecond"];function rE(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new wu(t);return e}function nE(t,e){let r=Pr(e.zone,Ee.defaultZone),n=_e.fromObject(e),i=Ee.now(),s,o;if(oe(t.year))s=i;else{for(let c of nT)oe(t[c])&&(t[c]=rT[c]);let a=XE(t)||eT(t);if(a)return Ie.invalid(a);let u=r.offset(i);[s,o]=Ru(t,u,r)}return new Ie({ts:s,zone:r,loc:n,o})}function iE(t,e,r){let n=oe(r.round)?!0:r.round,i=(o,a)=>(o=zd(o,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(o,a)),s=o=>r.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(r.unit)return i(s(r.unit),r.unit);for(let o of r.units){let a=s(o);if(Math.abs(a)>=1)return i(a,o)}return i(t>e?-0:0,r.units[r.units.length-1])}function sE(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var Ie=class t{constructor(e){let r=e.zone||Ee.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new rt("invalid input"):null)||(r.isValid?null:Iu(r));this.ts=oe(e.ts)?Ee.now():e.ts;let i=null,s=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,s]=[e.old.c,e.old.o];else{let a=r.offset(this.ts);i=Xy(this.ts,a),n=Number.isNaN(i.year)?new rt("invalid input"):null,i=n?null:i,s=n?null:a}this._zone=r,this.loc=e.loc||_e.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=sE(arguments),[n,i,s,o,a,u,c]=r;return nE({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:c},e)}static utc(){let[e,r]=sE(arguments),[n,i,s,o,a,u,c]=r;return e.zone=it.utcInstance,nE({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:c},e)}static fromJSDate(e,r={}){let n=Tb(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Pr(r.zone,Ee.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:_e.fromObject(r)}):t.invalid(Iu(i))}static fromMillis(e,r={}){if(Vn(e))return e<-Zy||e>Zy?t.invalid("Timestamp out of range"):new t({ts:e,zone:Pr(r.zone,Ee.defaultZone),loc:_e.fromObject(r)});throw new Ke(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(Vn(e))return new t({ts:e*1e3,zone:Pr(r.zone,Ee.defaultZone),loc:_e.fromObject(r)});throw new Ke("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Pr(r.zone,Ee.defaultZone);if(!n.isValid)return t.invalid(Iu(n));let i=Ee.now(),s=oe(r.specificOffset)?n.offset(i):r.specificOffset,o=Nu(e,rE),a=!oe(o.ordinal),u=!oe(o.year),c=!oe(o.month)||!oe(o.day),l=u||c,m=o.weekYear||o.weekNumber,p=_e.fromObject(r);if((l||a)&&m)throw new Gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&a)throw new Gn("Can't mix ordinal dates with month/day");let f=m||o.weekday&&!l,d,g,E=Xy(i,s);f?(d=HD,g=QD,E=Yd(E)):a?(d=KD,g=jD,E=Ld(E)):(d=nT,g=rT);let y=!1;for(let b of d){let k=o[b];oe(k)?y?o[b]=g[b]:o[b]=E[b]:y=!0}let S=f?qD(o):a?WD(o):XE(o),O=S||eT(o);if(O)return t.invalid(O);let R=f?Jy(o):a?zy(o):o,[T,_]=Ru(R,s,n),B=new t({ts:T,zone:n,o:_,loc:p});return o.weekday&&l&&e.weekday!==B.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${B.toISO()}`):B}static fromISO(e,r={}){let[n,i]=uD(e);return lo(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=cD(e);return lo(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=lD(e);return lo(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(oe(e)||oe(r))throw new Ke("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:s=null}=n,o=_e.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[a,u,c,l]=VD(o,e,r);return l?t.invalid(l):lo(a,u,n,`format ${r}`,e,c)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=yD(e);return lo(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new Ke("need to specify a reason the DateTime is invalid");let n=e instanceof rt?e:new rt(e,r);if(Ee.throwOnInvalid)throw new kd(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=HE(e,_e.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return QE(tt.parseFormat(e),_e.fromObject(r)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Md(this).weekYear:NaN}get weekNumber(){return this.isValid?Md(this).weekNumber:NaN}get weekday(){return this.isValid?Md(this).weekday:NaN}get ordinal(){return this.isValid?Ld(this.c).ordinal:NaN}get monthShort(){return this.isValid?$n.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?$n.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?$n.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?$n.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return yo(this.year)}get daysInMonth(){return Cu(this.year,this.month)}get daysInYear(){return this.isValid?mo(this.year):NaN}get weeksInWeekYear(){return this.isValid?vu(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=tt.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(it.instance(e),r)}toLocal(){return this.setZone(Ee.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Pr(e,Ee.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let s=e.offset(this.ts),o=this.toObject();[i]=Ru(o,s,e)}return co(this,{ts:i,zone:e})}else return t.invalid(Iu(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return co(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=Nu(e,rE),n=!oe(r.weekYear)||!oe(r.weekNumber)||!oe(r.weekday),i=!oe(r.ordinal),s=!oe(r.year),o=!oe(r.month)||!oe(r.day),a=s||o,u=r.weekYear||r.weekNumber;if((a||i)&&u)throw new Gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new Gn("Can't mix ordinal dates with month/day");let c;n?c=Jy({...Yd(this.c),...r}):oe(r.ordinal)?(c={...this.toObject(),...r},oe(r.day)&&(c.day=Math.min(Cu(c.year,c.month),c.day))):c=zy({...Ld(this.c),...r});let[l,m]=Ru(c,this.o,this.zone);return co(this,{ts:l,o:m})}plus(e){if(!this.isValid)return this;let r=De.fromDurationLike(e);return co(this,eE(this,r))}minus(e){if(!this.isValid)return this;let r=De.fromDurationLike(e).negate();return co(this,eE(this,r))}startOf(e){if(!this.isValid)return this;let r={},n=De.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break}if(n==="weeks"&&(r.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,r={}){return this.isValid?tt.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):Ud}toLocaleString(e=bu,r={}){return this.isValid?tt.create(this.loc.clone(r),e).formatDateTime(this):Ud}toLocaleParts(e={}){return this.isValid?tt.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=Fd(this,o);return a+="T",a+=tE(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?Fd(this,e==="extended"):null}toISOWeekDate(){return Ou(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+tE(this,o==="extended",r,e,n,s):null}toRFC2822(){return Ou(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Ou(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Fd(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),Ou(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Ud}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return De.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},s=Ab(r).map(De.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,c=wD(a,u,s,i);return o?c.negate():c}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?qn.fromDateTimes(this,e):this}hasSame(e,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(r)<=n&&n<=i.endOf(r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),iE(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?iE(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new Ke("min requires all arguments be DateTimes");return qy(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new Ke("max requires all arguments be DateTimes");return qy(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:s=null}=n,o=_e.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return jE(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return bu}static get DATE_MED(){return oE}static get DATE_MED_WITH_WEEKDAY(){return nb}static get DATE_FULL(){return aE}static get DATE_HUGE(){return uE}static get TIME_SIMPLE(){return cE}static get TIME_WITH_SECONDS(){return lE}static get TIME_WITH_SHORT_OFFSET(){return dE}static get TIME_WITH_LONG_OFFSET(){return pE}static get TIME_24_SIMPLE(){return fE}static get TIME_24_WITH_SECONDS(){return mE}static get TIME_24_WITH_SHORT_OFFSET(){return hE}static get TIME_24_WITH_LONG_OFFSET(){return gE}static get DATETIME_SHORT(){return yE}static get DATETIME_SHORT_WITH_SECONDS(){return EE}static get DATETIME_MED(){return TE}static get DATETIME_MED_WITH_SECONDS(){return AE}static get DATETIME_MED_WITH_WEEKDAY(){return ib}static get DATETIME_FULL(){return SE}static get DATETIME_FULL_WITH_SECONDS(){return _E}static get DATETIME_HUGE(){return IE}static get DATETIME_HUGE_WITH_SECONDS(){return OE}};function po(t){if(Ie.isDateTime(t))return t;if(t&&t.valueOf&&Vn(t.valueOf()))return Ie.fromJSDate(t);if(t&&typeof t=="object")return Ie.fromObject(t);throw new Ke(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var YD="3.2.1";st.DateTime=Ie;st.Duration=De;st.FixedOffsetZone=it;st.IANAZone=or;st.Info=$n;st.Interval=qn;st.InvalidZone=Du;st.Settings=Ee;st.SystemZone=go;st.VERSION=YD;st.Zone=Lr});var oT=H((GQ,sT)=>{"use strict";var Wn=iT();z.prototype.addYear=function(){this._date=this._date.plus({years:1})};z.prototype.addMonth=function(){this._date=this._date.plus({months:1}).startOf("month")};z.prototype.addDay=function(){this._date=this._date.plus({days:1}).startOf("day")};z.prototype.addHour=function(){var t=this._date;this._date=this._date.plus({hours:1}).startOf("hour"),this._date<=t&&(this._date=this._date.plus({hours:1}))};z.prototype.addMinute=function(){var t=this._date;this._date=this._date.plus({minutes:1}).startOf("minute"),this._date<t&&(this._date=this._date.plus({hours:1}))};z.prototype.addSecond=function(){var t=this._date;this._date=this._date.plus({seconds:1}).startOf("second"),this._date<t&&(this._date=this._date.plus({hours:1}))};z.prototype.subtractYear=function(){this._date=this._date.minus({years:1})};z.prototype.subtractMonth=function(){this._date=this._date.minus({months:1}).endOf("month").startOf("second")};z.prototype.subtractDay=function(){this._date=this._date.minus({days:1}).endOf("day").startOf("second")};z.prototype.subtractHour=function(){var t=this._date;this._date=this._date.minus({hours:1}).endOf("hour").startOf("second"),this._date>=t&&(this._date=this._date.minus({hours:1}))};z.prototype.subtractMinute=function(){var t=this._date;this._date=this._date.minus({minutes:1}).endOf("minute").startOf("second"),this._date>t&&(this._date=this._date.minus({hours:1}))};z.prototype.subtractSecond=function(){var t=this._date;this._date=this._date.minus({seconds:1}).startOf("second"),this._date>t&&(this._date=this._date.minus({hours:1}))};z.prototype.getDate=function(){return this._date.day};z.prototype.getFullYear=function(){return this._date.year};z.prototype.getDay=function(){var t=this._date.weekday;return t==7?0:t};z.prototype.getMonth=function(){return this._date.month-1};z.prototype.getHours=function(){return this._date.hour};z.prototype.getMinutes=function(){return this._date.minute};z.prototype.getSeconds=function(){return this._date.second};z.prototype.getMilliseconds=function(){return this._date.millisecond};z.prototype.getTime=function(){return this._date.valueOf()};z.prototype.getUTCDate=function(){return this._getUTC().day};z.prototype.getUTCFullYear=function(){return this._getUTC().year};z.prototype.getUTCDay=function(){var t=this._getUTC().weekday;return t==7?0:t};z.prototype.getUTCMonth=function(){return this._getUTC().month-1};z.prototype.getUTCHours=function(){return this._getUTC().hour};z.prototype.getUTCMinutes=function(){return this._getUTC().minute};z.prototype.getUTCSeconds=function(){return this._getUTC().second};z.prototype.toISOString=function(){return this._date.toUTC().toISO()};z.prototype.toJSON=function(){return this._date.toJSON()};z.prototype.setDate=function(t){this._date=this._date.set({day:t})};z.prototype.setFullYear=function(t){this._date=this._date.set({year:t})};z.prototype.setDay=function(t){this._date=this._date.set({weekday:t})};z.prototype.setMonth=function(t){this._date=this._date.set({month:t+1})};z.prototype.setHours=function(t){this._date=this._date.set({hour:t})};z.prototype.setMinutes=function(t){this._date=this._date.set({minute:t})};z.prototype.setSeconds=function(t){this._date=this._date.set({second:t})};z.prototype.setMilliseconds=function(t){this._date=this._date.set({millisecond:t})};z.prototype._getUTC=function(){return this._date.toUTC()};z.prototype.toString=function(){return this.toDate().toString()};z.prototype.toDate=function(){return this._date.toJSDate()};z.prototype.isLastDayOfMonth=function(){var t=this._date.plus({days:1}).startOf("day");return this._date.month!==t.month};z.prototype.isLastWeekdayOfMonth=function(){var t=this._date.plus({days:7}).startOf("day");return this._date.month!==t.month};function z(t,e){var r={zone:e};if(t?t instanceof z?this._date=t._date:t instanceof Date?this._date=Wn.DateTime.fromJSDate(t,r):typeof t=="number"?this._date=Wn.DateTime.fromMillis(t,r):typeof t=="string"&&(this._date=Wn.DateTime.fromISO(t,r),this._date.isValid||(this._date=Wn.DateTime.fromRFC2822(t,r)),this._date.isValid||(this._date=Wn.DateTime.fromSQL(t,r)),this._date.isValid||(this._date=Wn.DateTime.fromFormat(t,"EEE, d MMM yyyy HH:mm:ss",r))):this._date=Wn.DateTime.local(),!this._date||!this._date.isValid)throw new Error("CronDate: unhandled timestamp: "+JSON.stringify(t));e&&e!==this._date.zoneName&&(this._date=this._date.setZone(e))}sT.exports=z});var cT=H(($Q,uT)=>{"use strict";function Qn(t){return{start:t,count:1}}function aT(t,e){t.end=e,t.step=e-t.start,t.count=2}function np(t,e,r){e&&(e.count===2?(t.push(Qn(e.start)),t.push(Qn(e.end))):t.push(e)),r&&t.push(r)}function JD(t){for(var e=[],r=void 0,n=0;n<t.length;n++){var i=t[n];typeof i!="number"?(np(e,r,Qn(i)),r=void 0):r?r.count===1?aT(r,i):r.step===i-r.end?(r.count++,r.end=i):r.count===2?(e.push(Qn(r.start)),r=Qn(r.end),aT(r,i)):(np(e,r),r=Qn(i)):r=Qn(i)}return np(e,r),e}uT.exports=JD});var dT=H((VQ,lT)=>{"use strict";var zD=cT();function ZD(t,e,r){var n=zD(t);if(n.length===1){var i=n[0],s=i.step;if(s===1&&i.start===e&&i.end===r)return"*";if(s!==1&&i.start===e&&i.end===r-s+1)return"*/"+s}for(var o=[],a=0,u=n.length;a<u;++a){var c=n[a];if(c.count===1){o.push(c.start);continue}var s=c.step;if(c.step===1){o.push(c.start+"-"+c.end);continue}var l=c.start==0?c.count-1:c.count;c.step*l>c.end?o=o.concat(Array.from({length:c.end-c.start+1}).map(function(p,f){var d=c.start+f;return(d-c.start)%c.step===0?d:null}).filter(function(p){return p!=null})):c.end===r-c.step+1?o.push(c.start+"/"+c.step):o.push(c.start+"-"+c.end+"/"+c.step)}return o.join(",")}lT.exports=ZD});var mT=H((qQ,fT)=>{"use strict";var jn=oT(),XD=dT(),pT=1e4;function L(t,e){this._options=e,this._utc=e.utc||!1,this._tz=this._utc?"UTC":e.tz,this._currentDate=new jn(e.currentDate,this._tz),this._startDate=e.startDate?new jn(e.startDate,this._tz):null,this._endDate=e.endDate?new jn(e.endDate,this._tz):null,this._isIterator=e.iterator||!1,this._hasIterated=!1,this._nthDayOfWeek=e.nthDayOfWeek||0,this.fields=L._freezeFields(t)}L.map=["second","minute","hour","dayOfMonth","month","dayOfWeek"];L.predefined={"@yearly":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *"};L.constraints=[{min:0,max:59,chars:[]},{min:0,max:59,chars:[]},{min:0,max:23,chars:[]},{min:1,max:31,chars:["L"]},{min:1,max:12,chars:[]},{min:0,max:7,chars:["L"]}];L.daysInMonth=[31,29,31,30,31,30,31,31,30,31,30,31];L.aliases={month:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},dayOfWeek:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}};L.parseDefaults=["0","*","*","*","*","*"];L.standardValidCharacters=/^[,*\d/-]+$/;L.dayOfWeekValidCharacters=/^[?,*\dL#/-]+$/;L.dayOfMonthValidCharacters=/^[?,*\dL/-]+$/;L.validCharacters={second:L.standardValidCharacters,minute:L.standardValidCharacters,hour:L.standardValidCharacters,dayOfMonth:L.dayOfMonthValidCharacters,month:L.standardValidCharacters,dayOfWeek:L.dayOfWeekValidCharacters};L._isValidConstraintChar=function(e,r){return typeof r!="string"?!1:e.chars.some(function(n){return r.indexOf(n)>-1})};L._parseField=function(e,r,n){switch(e){case"month":case"dayOfWeek":var i=L.aliases[e];r=r.replace(/[a-z]{3}/gi,function(u){if(u=u.toLowerCase(),typeof i[u]<"u")return i[u];throw new Error('Validation error, cannot resolve alias "'+u+'"')});break}if(!L.validCharacters[e].test(r))throw new Error("Invalid characters, got value: "+r);r.indexOf("*")!==-1?r=r.replace(/\*/g,n.min+"-"+n.max):r.indexOf("?")!==-1&&(r=r.replace(/\?/g,n.min+"-"+n.max));function s(u){var c=[];function l(d){if(d instanceof Array)for(var g=0,E=d.length;g<E;g++){var y=d[g];if(L._isValidConstraintChar(n,y)){c.push(y);continue}if(typeof y!="number"||Number.isNaN(y)||y<n.min||y>n.max)throw new Error("Constraint error, got value "+y+" expected range "+n.min+"-"+n.max);c.push(y)}else{if(L._isValidConstraintChar(n,d)){c.push(d);return}var S=+d;if(Number.isNaN(S)||S<n.min||S>n.max)throw new Error("Constraint error, got value "+d+" expected range "+n.min+"-"+n.max);e==="dayOfWeek"&&(S=S%7),c.push(S)}}var m=u.split(",");if(!m.every(function(d){return d.length>0}))throw new Error("Invalid list value format");if(m.length>1)for(var p=0,f=m.length;p<f;p++)l(o(m[p]));else l(o(u));return c.sort(L._sortCompareFn),c}function o(u){var c=1,l=u.split("/");if(l.length>2)throw new Error("Invalid repeat: "+u);return l.length>1?(l[0]==+l[0]&&(l=[l[0]+"-"+n.max,l[1]]),a(l[0],l[l.length-1])):a(u,c)}function a(u,c){var l=[],m=u.split("-");if(m.length>1){if(m.length<2)return+u;if(!m[0].length){if(!m[1].length)throw new Error("Invalid range: "+u);return+u}var p=+m[0],f=+m[1];if(Number.isNaN(p)||Number.isNaN(f)||p<n.min||f>n.max)throw new Error("Constraint error, got range "+p+"-"+f+" expected range "+n.min+"-"+n.max);if(p>f)throw new Error("Invalid range: "+u);var d=+c;if(Number.isNaN(d)||d<=0)throw new Error("Constraint error, cannot repeat at every "+d+" time.");e==="dayOfWeek"&&f%7===0&&l.push(0);for(var g=p,E=f;g<=E;g++){var y=l.indexOf(g)!==-1;!y&&d>0&&d%c===0?(d=1,l.push(g)):d++}return l}return Number.isNaN(+u)?u:+u}return s(r)};L._sortCompareFn=function(t,e){var r=typeof t=="number",n=typeof e=="number";return r&&n?t-e:!r&&n?1:r&&!n?-1:t.localeCompare(e)};L._handleMaxDaysInMonth=function(t){if(t.month.length===1){var e=L.daysInMonth[t.month[0]-1];if(t.dayOfMonth[0]>e)throw new Error("Invalid explicit day of month definition");return t.dayOfMonth.filter(function(r){return r==="L"?!0:r<=e}).sort(L._sortCompareFn)}};L._freezeFields=function(t){for(var e=0,r=L.map.length;e<r;++e){var n=L.map[e],i=t[n];t[n]=Object.freeze(i)}return Object.freeze(t)};L.prototype._applyTimezoneShift=function(t,e,r){if(r==="Month"||r==="Day"){var n=t.getTime();t[e+r]();var i=t.getTime();n===i&&(t.getMinutes()===0&&t.getSeconds()===0?t.addHour():t.getMinutes()===59&&t.getSeconds()===59&&t.subtractHour())}else{var s=t.getHours();t[e+r]();var o=t.getHours(),a=o-s;a===2?this.fields.hour.length!==24&&(this._dstStart=o):a===0&&t.getMinutes()===0&&t.getSeconds()===0&&this.fields.hour.length!==24&&(this._dstEnd=o)}};L.prototype._findSchedule=function(e){function r(y,S){for(var O=0,R=S.length;O<R;O++)if(S[O]>=y)return S[O]===y;return S[0]===y}function n(y,S){if(S<6){if(y.getDate()<8&&S===1)return!0;var O=y.getDate()%7?1:0,R=y.getDate()-y.getDate()%7,T=Math.floor(R/7)+O;return T===S}return!1}function i(y){return y.length>0&&y.some(function(S){return typeof S=="string"&&S.indexOf("L")>=0})}e=e||!1;var s=e?"subtract":"add",o=new jn(this._currentDate,this._tz),a=this._startDate,u=this._endDate,c=o.getTime(),l=0;function m(y){return y.some(function(S){if(!i([S]))return!1;var O=Number.parseInt(S[0])%7;if(Number.isNaN(O))throw new Error("Invalid last weekday of the month expression: "+S);return o.getDay()===O&&o.isLastWeekdayOfMonth()})}for(;l<pT;){if(l++,e){if(a&&o.getTime()-a.getTime()<0)throw new Error("Out of the timespan range")}else if(u&&u.getTime()-o.getTime()<0)throw new Error("Out of the timespan range");var p=r(o.getDate(),this.fields.dayOfMonth);i(this.fields.dayOfMonth)&&(p=p||o.isLastDayOfMonth());var f=r(o.getDay(),this.fields.dayOfWeek);i(this.fields.dayOfWeek)&&(f=f||m(this.fields.dayOfWeek));var d=this.fields.dayOfMonth.length>=L.daysInMonth[o.getMonth()],g=this.fields.dayOfWeek.length===L.constraints[5].max-L.constraints[5].min+1,E=o.getHours();if(!p&&(!f||g)){this._applyTimezoneShift(o,s,"Day");continue}if(!d&&g&&!p){this._applyTimezoneShift(o,s,"Day");continue}if(d&&!g&&!f){this._applyTimezoneShift(o,s,"Day");continue}if(this._nthDayOfWeek>0&&!n(o,this._nthDayOfWeek)){this._applyTimezoneShift(o,s,"Day");continue}if(!r(o.getMonth()+1,this.fields.month)){this._applyTimezoneShift(o,s,"Month");continue}if(r(E,this.fields.hour)){if(this._dstEnd===E&&!e){this._dstEnd=null,this._applyTimezoneShift(o,"add","Hour");continue}}else if(this._dstStart!==E){this._dstStart=null,this._applyTimezoneShift(o,s,"Hour");continue}else if(!r(E-1,this.fields.hour)){o[s+"Hour"]();continue}if(!r(o.getMinutes(),this.fields.minute)){this._applyTimezoneShift(o,s,"Minute");continue}if(!r(o.getSeconds(),this.fields.second)){this._applyTimezoneShift(o,s,"Second");continue}if(c===o.getTime()){s==="add"||o.getMilliseconds()===0?this._applyTimezoneShift(o,s,"Second"):o.setMilliseconds(0);continue}break}if(l>=pT)throw new Error("Invalid expression, loop limit exceeded");return this._currentDate=new jn(o,this._tz),this._hasIterated=!0,o};L.prototype.next=function(){var e=this._findSchedule();return this._isIterator?{value:e,done:!this.hasNext()}:e};L.prototype.prev=function(){var e=this._findSchedule(!0);return this._isIterator?{value:e,done:!this.hasPrev()}:e};L.prototype.hasNext=function(){var t=this._currentDate,e=this._hasIterated;try{return this._findSchedule(),!0}catch{return!1}finally{this._currentDate=t,this._hasIterated=e}};L.prototype.hasPrev=function(){var t=this._currentDate,e=this._hasIterated;try{return this._findSchedule(!0),!0}catch{return!1}finally{this._currentDate=t,this._hasIterated=e}};L.prototype.iterate=function(e,r){var n=[];if(e>=0)for(var i=0,s=e;i<s;i++)try{var o=this.next();n.push(o),r&&r(o,i)}catch{break}else for(var i=0,s=e;i>s;i--)try{var o=this.prev();n.push(o),r&&r(o,i)}catch{break}return n};L.prototype.reset=function(e){this._currentDate=new jn(e||this._options.currentDate)};L.prototype.stringify=function(e){for(var r=[],n=e?0:1,i=L.map.length;n<i;++n){var s=L.map[n],o=this.fields[s],a=L.constraints[n];s==="dayOfMonth"&&this.fields.month.length===1?a={min:1,max:L.daysInMonth[this.fields.month[0]-1]}:s==="dayOfWeek"&&(a={min:0,max:6},o=o[o.length-1]===7?o.slice(0,-1):o),r.push(XD(o,a.min,a.max))}return r.join(" ")};L.parse=function(e,r){var n=this;typeof r=="function"&&(r={});function i(s,o){o||(o={}),typeof o.currentDate>"u"&&(o.currentDate=new jn(void 0,n._tz)),L.predefined[s]&&(s=L.predefined[s]);var a=[],u=(s+"").trim().split(/\s+/);if(u.length>6)throw new Error("Invalid cron expression");for(var c=L.map.length-u.length,l=0,m=L.map.length;l<m;++l){var p=L.map[l],f=u[u.length>m?l:l-c];if(l<c||!f)a.push(L._parseField(p,L.parseDefaults[l],L.constraints[l]));else{var d=p==="dayOfWeek"?S(f):f;a.push(L._parseField(p,d,L.constraints[l]))}}for(var g={},l=0,m=L.map.length;l<m;l++){var E=L.map[l];g[E]=a[l]}var y=L._handleMaxDaysInMonth(g);return g.dayOfMonth=y||g.dayOfMonth,new L(g,o);function S(O){var R=O.split("#");if(R.length>1){var T=+R[R.length-1];if(/,/.test(O))throw new Error("Constraint error, invalid dayOfWeek `#` and `,` special characters are incompatible");if(/\//.test(O))throw new Error("Constraint error, invalid dayOfWeek `#` and `/` special characters are incompatible");if(/-/.test(O))throw new Error("Constraint error, invalid dayOfWeek `#` and `-` special characters are incompatible");if(R.length>2||Number.isNaN(T)||T<1||T>5)throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return o.nthDayOfWeek=T,R[0]}return O}}return i(e,r)};L.fieldsToExpression=function(e,r){function n(p,f,d){if(!f)throw new Error("Validation error, Field "+p+" is missing");if(f.length===0)throw new Error("Validation error, Field "+p+" contains no values");for(var g=0,E=f.length;g<E;g++){var y=f[g];if(!L._isValidConstraintChar(d,y)&&(typeof y!="number"||Number.isNaN(y)||y<d.min||y>d.max))throw new Error("Constraint error, got value "+y+" expected range "+d.min+"-"+d.max)}}for(var i={},s=0,o=L.map.length;s<o;++s){var a=L.map[s],u=e[a];n(a,u,L.constraints[s]);for(var c=[],l=-1;++l<u.length;)c[l]=u[l];if(u=c.sort(L._sortCompareFn).filter(function(p,f,d){return!f||p!==d[f-1]}),u.length!==c.length)throw new Error("Validation error, Field "+a+" contains duplicate values");i[a]=u}var m=L._handleMaxDaysInMonth(i);return i.dayOfMonth=m||i.dayOfMonth,new L(i,r||{})};fT.exports=L});var gT=H((WQ,hT)=>{"use strict";var Mu=mT();function Ur(){}Ur._parseEntry=function(e){var r=e.split(" ");if(r.length===6)return{interval:Mu.parse(e)};if(r.length>6)return{interval:Mu.parse(r.slice(0,6).join(" ")),command:r.slice(6,r.length)};throw new Error("Invalid entry: "+e)};Ur.parseExpression=function(e,r){return Mu.parse(e,r)};Ur.fieldsToExpression=function(e,r){return Mu.fieldsToExpression(e,r)};Ur.parseString=function(e){for(var r=e.split(`
|
|
5
|
-
`),n={variables:{},expressions:[],errors:{}},i=0,s=r.length;i<s;i++){var o=r[i],a=null,u=o.trim();if(u.length>0){if(u.match(/^#/))continue;if(a=u.match(/^(.*)=(.*)$/))n.variables[a[1]]=a[2];else{var c=null;try{c=Ur._parseEntry("0 "+u),n.expressions.push(c.interval)}catch(l){n.errors[u]=l}}}}return n};Ur.parseFile=function(e,r){require("fs").readFile(e,function(n,i){if(n){r(n);return}return r(null,Ur.parseString(i.toString()))})};hT.exports=Ur});var Hk={};N(Hk,{APP_DEV:()=>Qu,APP_DEV_PREFIX:()=>yt,APP_PREFIX:()=>gt,AutomationViewMode:()=>Wu,BUDIBASE_DATASOURCE_TYPE:()=>xp,BadRequestError:()=>Dc,BudibaseError:()=>ps,Config:()=>vp,Cookie:()=>Kn,DEFAULT_BB_DATASOURCE_ID:()=>Di,DEFAULT_EMPLOYEE_TABLE_ID:()=>Dp,DEFAULT_EXPENSES_TABLE_ID:()=>bp,DEFAULT_INVENTORY_TABLE_ID:()=>wp,DEFAULT_JOBS_TABLE_ID:()=>Rp,DEFAULT_TENANT_ID:()=>Ae,DeprecatedViews:()=>Hi,DesignDocuments:()=>ju,DocumentType:()=>ye,Duration:()=>be,DurationType:()=>Uf,EmailUnavailableError:()=>mr,FeatureDisabledError:()=>vc,GlobalRole:()=>Cp,HTTPError:()=>lt,Header:()=>Xe,InternalTable:()=>xr,InvalidAPIKeyError:()=>fs,MAX_VALID_DATE:()=>Ku,MIN_VALID_DATE:()=>vT,NotFoundError:()=>bc,RedisClient:()=>We,SEPARATOR:()=>v,SQLITE_DESIGN_DOC_ID:()=>Ht,SQS_DATASOURCE_INTERNAL:()=>Op,StaticDatabases:()=>Te,UNICODE_MAX:()=>Ge,UsageLimitError:()=>Cc,UserStatus:()=>Hu,ViewName:()=>kr,accounts:()=>li,auth:()=>hh,blacklist:()=>Th,cache:()=>Oa,configs:()=>tn,constants:()=>Np,context:()=>Se,db:()=>jr,docIds:()=>Of,docUpdates:()=>Sh,encryption:()=>ph,env:()=>h,errors:()=>Pc,events:()=>ys,features:()=>nh,getPublicError:()=>Nc,init:()=>jk,installation:()=>qc,locks:()=>ui,logging:()=>Rc,middleware:()=>mh,objectStore:()=>Jf,permissions:()=>eh,platform:()=>Xo,plugins:()=>yh,queue:()=>pm,redis:()=>Eh,roles:()=>Xm,security:()=>Dm,sessions:()=>Yc,setEnv:()=>Ro,sql:()=>Ch,tenancy:()=>Qk,timers:()=>$c,userUtils:()=>om,users:()=>Es,utils:()=>ss,withEnv:()=>FT});module.exports=BI(Hk);var tn={};N(tn,{analyticsEnabled:()=>Bc,generateConfigID:()=>el,getAIConfig:()=>sF,getConfig:()=>Bt,getDefaultGoogleConfig:()=>Bm,getGoogleConfig:()=>tl,getGoogleDatasourceConfig:()=>Vm,getOIDCConfig:()=>rF,getOIDCConfigById:()=>qm,getOIDCLogosDoc:()=>eF,getPlatformUrl:()=>Ca,getSCIMConfig:()=>iF,getSMTPConfig:()=>nF,getSMTPConfigDoc:()=>P_,getSettingsConfig:()=>$m,getSettingsConfigDoc:()=>Qc,save:()=>Z0});var GI=["user:created","user:updated","user:deleted","user:admin:assigned","user:admin:removed","user:builder:assigned","user:builder:removed","user_group:created","user_group:updated","user_group:deleted","user_group:user_added","user_group:users_deleted","user_group:permissions_edited"],Nh=[...GI],Ph={"user:created":'User "{{ email }}" created{{#if viaScim}} via SCIM{{/if}}',"user:updated":'User "{{ email }}" updated{{#if viaScim}} via SCIM{{/if}}',"user:deleted":'User "{{ email }}" deleted{{#if viaScim}} via SCIM{{/if}}',"user:admin:assigned":'User "{{ email }}" admin role assigned',"user:admin:removed":'User "{{ email }}" admin role removed',"user:builder:assigned":'User "{{ email }}" builder role assigned',"user:builder:removed":'User "{{ email }}" builder role removed',"user:invited":'User "{{ email }}" invited',"user:invite:accepted":'User "{{ email }}" accepted invite',"user:password:updated":'User "{{ email }}" password updated',"user:password:reset:requested":'User "{{ email }}" password reset requested',"user:password:reset":'User "{{ email }}" password reset',"user_group:created":'User group "{{ name }}" created{{#if viaScim}} via SCIM{{/if}}',"user_group:updated":'User group "{{ name }}" updated{{#if viaScim}} via SCIM{{/if}}',"user_group:deleted":'User group "{{ name }}" deleted{{#if viaScim}} via SCIM{{/if}}',"user_group:user_added":'User group "{{ name }}" {{ count }} users added{{#if viaScim}} via SCIM{{/if}}',"user_group:users_deleted":'User group "{{ name }}" {{ count }} users removed{{#if viaScim}} via SCIM{{/if}}',"user_group:permissions_edited":'User group "{{ name }}" permissions edited',"user:password:force:reset":void 0,"user_group:onboarding_added":void 0,"user:onboarding:complete":void 0,"user:data:collaboration":void 0,"email:smtp:created":"Email configuration created","email:smtp:updated":"Email configuration updated","ai:config:created":"AI configuration created","ai:config:updated":"AI configuration updated","auth:sso:created":"SSO configuration created","auth:sso:updated":"SSO configuration updated","auth:sso:activated":"SSO configuration activated","auth:sso:deactivated":"SSO configuration deactivated","auth:login":'User "{{ email }}" logged in',"auth:logout":'User "{{ email }}" logged out',"org:info:name:updated":"Organisation name updated","org:info:logo:updated":"Organisation logo updated","org:platformurl:updated":"Organisation platform URL updated","app:created":'App "{{ name }}" created',"app:updated":'App "{{ name }}" updated',"app:deleted":'App "{{ name }}" deleted',"app:duplicated":'App "{{ name }}" duplicated',"app:published":'App "{{ name }}" published',"app:unpublished":'App "{{ name }}" unpublished',"app:template:imported":'App "{{ name }}" template imported',"app:file:imported":'App "{{ name }}" file imported',"app:version:updated":'App "{{ name }}" version updated',"app:version:reverted":'App "{{ name }}" version reverted',"app:reverted":'App "{{ name }}" reverted',"app:exported":'App "{{ name }}" exported',"app:backup:restored":'App backup "{{ name }}" restored',"app:backup:triggered":'App backup "{{ name }}" triggered',"datasource:created":"Datasource created","datasource:updated":"Datasource updated","datasource:deleted":"Datasource deleted","query:created":"Query created","query:updated":"Query updated","query:deleted":"Query deleted","query:import":"Query import","queries:run":void 0,"query:previewed":void 0,"table:created":'Table "{{ name }}" created',"table:updated":'Table "{{ name }}" updated',"table:deleted":'Table "{{ name }}" deleted',"table:exported":'Table "{{ name }}" exported',"table:imported":'Table "{{ name }}" imported',"table:data:imported":"Data imported to table","rows:created":"Rows created","rows:imported":"Rows imported","automation:created":'Automation "{{ name }}" created',"automation:deleted":'Automation "{{ name }}" deleted',"automation:step:created":'Automation "{{ name }}" step added',"automation:step:deleted":'Automation "{{ name }}" step removed',"automation:tested":void 0,"automations:run":void 0,"automation:trigger:updated":void 0,"screen:created":'Screen "{{ name }}" created',"screen:deleted":'Screen "{{ name }}" deleted',"component:created":"Component created","component:deleted":"Component deleted","environment_variable:created":"Environment variable created","environment_variable:deleted":"Environment variable deleted","environment_variable:upgrade_panel_opened":void 0,"plugin:imported":"Plugin imported","plugin:deleted":"Plugin deleted","plugin:init":void 0,"action:automation_step:executed":void 0,"action:crud:executed":void 0,"action:ai_agent:executed":void 0,"role:created":void 0,"role:updated":void 0,"role:deleted":void 0,"role:assigned":void 0,"role:unassigned":void 0,"license:plan:changed":void 0,"license:activated":void 0,"license:payment:failed":void 0,"license:payment:recovered":void 0,"license:checkout:opened":void 0,"license:checkout:success":void 0,"license:portal:opened":void 0,"account:created":void 0,"account:deleted":void 0,"account:verified":void 0,"app:backfill:succeeded":void 0,"app:backfill:failed":void 0,"tenant:backfill:succeeded":void 0,"tenant:backfill:failed":void 0,"installation:backfill:succeeded":void 0,"installation:backfill:failed":void 0,"layout:created":void 0,"layout:deleted":void 0,"view:created":void 0,"view:updated":void 0,"view:deleted":void 0,"view:exported":void 0,"view:filter:created":void 0,"view:filter:updated":void 0,"view:filter:deleted":void 0,"view:calculation:created":void 0,"view:calculation:updated":void 0,"view:calculation:deleted":void 0,"view:join:created":void 0,"served:builder":void 0,"served:app":void 0,"served:app:preview":void 0,"analytics:opt:out":void 0,"analytics:opt:in":void 0,"installation:version:checked":void 0,"installation:version:upgraded":void 0,"installation:version:downgraded":void 0,"installation:firstStartup":void 0,"audit_log:filtered":void 0,"audit_log:downloaded":void 0,"row_action:created":void 0};var Rl=(n=>(n.SQL="sql",n.JSON="json",n.FIELDS="fields",n))(Rl||{}),wl=(p=>(p.STRING="string",p.CODE="code",p.LONGFORM="longForm",p.BOOLEAN="boolean",p.NUMBER="number",p.PASSWORD="password",p.LIST="list",p.OBJECT="object",p.JSON="json",p.FILE="file",p.FIELD_GROUP="fieldGroup",p.SELECT="select",p))(wl||{}),ka=(y=>(y.POSTGRES="POSTGRES",y.DYNAMODB="DYNAMODB",y.MONGODB="MONGODB",y.ELASTICSEARCH="ELASTICSEARCH",y.COUCHDB="COUCHDB",y.SQL_SERVER="SQL_SERVER",y.S3="S3",y.AIRTABLE="AIRTABLE",y.MYSQL="MYSQL",y.ARANGODB="ARANGODB",y.REST="REST",y.ORACLE="ORACLE",y.GOOGLE_SHEETS="GOOGLE_SHEETS",y.FIRESTORE="FIRESTORE",y.REDIS="REDIS",y.SNOWFLAKE="SNOWFLAKE",y.BUDIBASE="BUDIBASE",y))(ka||{});var bl=(n=>(n.CONNECTION_CHECKING="connection",n.FETCH_TABLE_NAMES="fetch_table_names",n.EXPORT_SCHEMA="export_schema",n))(bl||{});var $I=W(require("lodash")),Ir=(o=>(o.EQUAL="equal",o.NOT_EQUAL="notEqual",o.EMPTY="empty",o.NOT_EMPTY="notEmpty",o.FUZZY="fuzzy",o.STRING="string",o))(Ir||{}),Jt=(i=>(i.CONTAINS="contains",i.NOT_CONTAINS="notContains",i.CONTAINS_ANY="containsAny",i.ONE_OF="oneOf",i))(Jt||{}),dn=(e=>(e.RANGE="range",e))(dn||{}),Ti=(r=>(r.AND="$and",r.OR="$or",r))(Ti||{});function Ba(t){return Object.values(Ti).includes(t)}function Lh(t){return Object.values(Ir).includes(t)}function Uh(t){return Object.values(Jt).includes(t)}function Ga(t){return Object.values(dn).includes(t)}var Ai=(r=>(r.RETURN_ALL="all",r.RETURN_NONE="none",r))(Ai||{});var Mh=t=>typeof t=="object"&&t._id&&t._rev;var Os=(s=>(s.USER="user",s.HEADER="header",s.QUERY="query",s.SUBDOMAIN="subdomain",s.PATH="path",s))(Os||{});var Fh={USE_ZOD_VALIDATOR:!1,AI_JS_GENERATION:!0,AI_TABLE_GENERATION:!0,AI_AGENTS:!1,WORKSPACE_APPS:!1,DIRECT_LOGIN_TO_ACCOUNT_PORTAL:!1,DEBUG_UI:!1};var YB={OptOut:"analytics:opt:out",OptIn:"analytics:opt:in",SelfHostInit:"hosting:init",PluginInit:"plugin:init"};var xs=(i=>(i.READ="read",i.WRITE="write",i.EXECUTE="execute",i.ADMIN="admin",i))(xs||{});var $a=(m=>(m.APP="app",m.TABLE="table",m.USER="user",m.AUTOMATION="automation",m.WEBHOOK="webhook",m.BUILDER="builder",m.CREATOR="creator",m.GLOBAL_BUILDER="globalBuilder",m.QUERY="query",m.VIEW="view",m.LEGACY_VIEW="legacy_view",m))($a||{});var Va=t=>t.hosting==="cloud";var qa=t=>t.authType==="sso";var v="_",Ge="\uFFF0",Or=t=>`${t}${v}`,ye=(Q=>(Q.USER="us",Q.GROUP="gr",Q.WORKSPACE="workspace",Q.CONFIG="config",Q.TEMPLATE="template",Q.APP="app",Q.DEV="dev",Q.APP_DEV="app_dev",Q.APP_METADATA="app_metadata",Q.ROLE="role",Q.DEV_INFO="devinfo",Q.AUTOMATION_LOG="log_au",Q.ACCOUNT_METADATA="acc_metadata",Q.PLUGIN="plg",Q.DATASOURCE="datasource",Q.DATASOURCE_PLUS="datasource_plus",Q.APP_BACKUP="backup",Q.TABLE="ta",Q.ROW="ro",Q.AUTOMATION="au",Q.LINK="li",Q.WEBHOOK="wh",Q.INSTANCE="inst",Q.LAYOUT="layout",Q.SCREEN="screen",Q.QUERY="query",Q.DEPLOYMENTS="deployments",Q.METADATA="metadata",Q.MEM_VIEW="view",Q.USER_FLAG="flag",Q.AUTOMATION_METADATA="meta_au",Q.AUDIT_LOG="al",Q.SCIM_LOG="scimlog",Q.ROW_ACTIONS="ra",Q.OAUTH2_CONFIG="oauth2",Q.OAUTH2_CONFIG_LOG="oauth2log",Q.AGENT_CHAT="agentchat",Q.AGENT_TOOL_SOURCE="agenttoolsource",Q.WORKSPACE_APP="workspace_app",Q))(ye||{});var xr=(e=>(e.USER_METADATA="ta_users",e))(xr||{}),Dl=(r=>(r.VIEW="view",r.ROW_ACTION="row_action",r))(Dl||{});var ee=(l=>(l.OBJECT="object",l.STRING="string",l.BOOLEAN="boolean",l.NUMBER="number",l.ARRAY="array",l.JSON="json",l.DATE="date",l.DATETIME="datetime",l.ATTACHMENT="attachment",l.LONGFORM="longform",l))(ee||{}),pe=(R=>(R.TABLE="table",R.ROW="row",R.ROWS="rows",R.WIDE="wide",R.QUERY="query",R.QUERY_PARAMS="queryParams",R.QUERY_LIMIT="queryLimit",R.LOOP_OPTION="loopOption",R.ITEM="item",R.CODE="code",R.FILTERS="filters",R.COLUMN="column",R.TRIGGER_SCHEMA="triggerSchema",R.CRON="cron",R.WEBHOOK_URL="webhookUrl",R.AUTOMATION="automation",R.AUTOMATION_FIELDS="automationFields",R.MULTI_ATTACHMENTS="multi_attachments",R.TRIGGER_FILTER="trigger_filter",R.CATEGORIES="categories",R))(pe||{}),_t=(a=>(a.ROW_SAVED="ROW_SAVED",a.ROW_UPDATED="ROW_UPDATED",a.ROW_DELETED="ROW_DELETED",a.WEBHOOK="WEBHOOK",a.APP="APP",a.CRON="CRON",a.ROW_ACTION="ROW_ACTION",a))(_t||{});var ue=(I=>(I.SEND_EMAIL_SMTP="SEND_EMAIL_SMTP",I.CREATE_ROW="CREATE_ROW",I.UPDATE_ROW="UPDATE_ROW",I.DELETE_ROW="DELETE_ROW",I.EXECUTE_BASH="EXECUTE_BASH",I.OUTGOING_WEBHOOK="OUTGOING_WEBHOOK",I.EXECUTE_SCRIPT="EXECUTE_SCRIPT",I.EXECUTE_SCRIPT_V2="EXECUTE_SCRIPT_V2",I.EXECUTE_QUERY="EXECUTE_QUERY",I.SERVER_LOG="SERVER_LOG",I.DELAY="DELAY",I.FILTER="FILTER",I.API_REQUEST="API_REQUEST",I.QUERY_ROWS="QUERY_ROWS",I.LOOP="LOOP",I.COLLECT="COLLECT",I.OPENAI="OPENAI",I.TRIGGER_AUTOMATION_RUN="TRIGGER_AUTOMATION_RUN",I.BRANCH="BRANCH",I.CLASSIFY_CONTENT="CLASSIFY_CONTENT",I.PROMPT_LLM="PROMPT_LLM",I.TRANSLATE="TRANSLATE",I.SUMMARISE="SUMMARISE",I.GENERATE_TEXT="GENERATE_TEXT",I.EXTRACT_FILE_DATA="EXTRACT_FILE_DATA",I.discord="discord",I.slack="slack",I.zapier="zapier",I.integromat="integromat",I.n8n="n8n",I))(ue||{}),kh=[...Object.values(ue),...Object.values(_t)];var Cl=(a=>(a.EMAIL="email",a.DOCUMENT="document",a.BLOG_POST="blog_post",a.CHAT_MESSAGE="chat_message",a.LETTER="letter",a.PROPOSAL="proposal",a.OTHER="other",a))(Cl||{}),Bh={email:"Email",document:"Document",blog_post:"Blog post",chat_message:"Chat message",letter:"Letter",proposal:"Proposal",other:"Other"},vl=(r=>(r.URL="URL",r.ATTACHMENT="Attachment",r))(vl||{}),Nl=(i=>(i.PDF="pdf",i.JPG="jpg",i.PNG="png",i.JPEG="jpeg",i))(Nl||{});var Pl=(i=>(i.EQUAL="EQUAL",i.NOT_EQUAL="NOT_EQUAL",i.GREATER_THAN="GREATER_THAN",i.LESS_THAN="LESS_THAN",i))(Pl||{});var Ll=(o=>(o.GET="GET",o.POST="POST",o.PATCH="PATCH",o.PUT="PUT",o.HEAD="HEAD",o.DELETE="DELETE",o))(Ll||{});var Ul="bb_internal";var Gh=["attachment_single","attachment","signature_single","bb_reference","json","array"];function Wa(t){return!!t.providerType}var Ml=(n=>(n.DATASOURCE="datasource",n.COMPONENT="component",n.AUTOMATION="automation",n))(Ml||{});var X$=Object.values(Ml);var iV=["rows","queries","automations"],sV=["queries","automations"];var ie;(function(t){t.assertEqual=i=>i;function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ie||(ie={}));var kl;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(kl||(kl={}));var M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},x=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),QI=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ze=class t extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ze.create=t=>new ze(t);var Ii=(t,e)=>{let r;switch(t.code){case x.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case x.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case x.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},qh=Ii;function jI(t){qh=t}function Qa(){return qh}var ja=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}},HI=[];function P(t,e){let r=Qa(),n=ja({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ii?void 0:Ii].filter(i=>!!i)});t.common.issues.push(n)}var ke=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return J;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return J;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),_i=t=>({status:"dirty",value:t}),$e=t=>({status:"valid",value:t}),Bl=t=>t.status==="aborted",Gl=t=>t.status==="dirty",bs=t=>t.status==="valid",Ds=t=>typeof Promise<"u"&&t instanceof Promise;function Ha(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function Wh(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));var Rs,ws,pt=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$h=(t,e)=>{if(bs(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ze(t.common.issues);return this._error=r,this._error}}};function Z(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{var u,c;let{message:l}=t;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:(u=l??n)!==null&&u!==void 0?u:a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:(c=l??r)!==null&&c!==void 0?c:a.defaultError}},description:i}}var X=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Rr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ds(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;let i={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},s=this._parseSync({data:e,path:i.path,parent:i});return $h(i,s)}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Ds(i)?i:Promise.resolve(i));return $h(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:x.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Ze({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return dt.create(this,this._def)}nullable(){return $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xt.create(this,this._def)}promise(){return Dr.create(this,this._def)}or(e){return Tn.create([this,e],this._def)}and(e){return An.create(this,e,this._def)}transform(e){return new Ze({...Z(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new xn({...Z(this._def),innerType:this,defaultValue:r,typeName:K.ZodDefault})}brand(){return new Cs({typeName:K.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Rn({...Z(this._def),innerType:this,catchValue:r,typeName:K.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vs.create(this,e)}readonly(){return wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},KI=/^c[^\s-]{8,}$/i,YI=/^[0-9a-z]+$/,JI=/^[0-9A-HJKMNP-TV-Z]{26}$/,zI=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZI=/^[a-z0-9_-]{21}$/i,XI=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,eO=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fl,rO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nO=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,iO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",sO=new RegExp(`^${Qh}$`);function jh(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function oO(t){return new RegExp(`^${jh(t)}$`)}function Hh(t){let e=`${Qh}T${jh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function aO(t,e){return!!((e==="v4"||!e)&&rO.test(t)||(e==="v6"||!e)&&nO.test(t))}var wr=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.string,received:s.parsedType}),J}let n=new ke,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?P(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&P(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")eO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"email",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Fl||(Fl=new RegExp(tO,"u")),Fl.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"emoji",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")zI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"uuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ZI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"nanoid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")KI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"cuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")YI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"cuid2",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")JI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"ulid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),P(i,{validation:"url",code:x.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"regex",code:x.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Hh(s).test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?sO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?oO(s).test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?XI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"duration",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?aO(e.data,s.version)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"ip",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?iO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"base64",code:x.invalid_string,message:s.message}),n.dirty()):ie.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:x.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(r=e?.offset)!==null&&r!==void 0?r:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};wr.create=t=>{var e;return new wr({checks:[],typeName:K.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Z(t)})};function uO(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=parseInt(t.toFixed(i).replace(".","")),o=parseInt(e.toFixed(i).replace(".",""));return s%o/Math.pow(10,i)}var fn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.number,received:s.parsedType}),J}let n,i=new ke;for(let s of this._def.checks)s.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?uO(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_finite,message:s.message}),i.dirty()):ie.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};fn.create=t=>new fn({checks:[],typeName:K.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var mn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==M.bigint){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.bigint,received:s.parsedType}),J}let n,i=new ke;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ie.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};mn.create=t=>{var e;return new mn({checks:[],typeName:K.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Z(t)})};var hn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.boolean,received:n.parsedType}),J}return $e(e.data)}};hn.create=t=>new hn({typeName:K.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var gn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.date,received:s.parsedType}),J}if(isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_date}),J}let n=new ke,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ie.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};gn.create=t=>new gn({checks:[],coerce:t?.coerce||!1,typeName:K.ZodDate,...Z(t)});var Oi=class extends X{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.symbol,received:n.parsedType}),J}return $e(e.data)}};Oi.create=t=>new Oi({typeName:K.ZodSymbol,...Z(t)});var yn=class extends X{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.undefined,received:n.parsedType}),J}return $e(e.data)}};yn.create=t=>new yn({typeName:K.ZodUndefined,...Z(t)});var En=class extends X{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.null,received:n.parsedType}),J}return $e(e.data)}};En.create=t=>new En({typeName:K.ZodNull,...Z(t)});var br=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return $e(e.data)}};br.create=t=>new br({typeName:K.ZodAny,...Z(t)});var Zt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $e(e.data)}};Zt.create=t=>new Zt({typeName:K.ZodUnknown,...Z(t)});var It=class extends X{_parse(e){let r=this._getOrReturnCtx(e);return P(r,{code:x.invalid_type,expected:M.never,received:r.parsedType}),J}};It.create=t=>new It({typeName:K.ZodNever,...Z(t)});var xi=class extends X{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.void,received:n.parsedType}),J}return $e(e.data)}};xi.create=t=>new xi({typeName:K.ZodVoid,...Z(t)});var Xt=class t extends X{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==M.array)return P(r,{code:x.invalid_type,expected:M.array,received:r.parsedType}),J;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(P(r,{code:o?x.too_big:x.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(P(r,{code:x.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(P(r,{code:x.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new pt(r,o,r.path,a)))).then(o=>ke.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new pt(r,o,r.path,a)));return ke.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Xt.create=(t,e)=>new Xt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...Z(e)});function Si(t){if(t instanceof je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=dt.create(Si(n))}return new je({...t._def,shape:()=>e})}else return t instanceof Xt?new Xt({...t._def,type:Si(t.element)}):t instanceof dt?dt.create(Si(t.unwrap())):t instanceof $t?$t.create(Si(t.unwrap())):t instanceof Gt?Gt.create(t.items.map(e=>Si(e))):t}var je=class t extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==M.object){let c=this._getOrReturnCtx(e);return P(c,{code:x.invalid_type,expected:M.object,received:c.parsedType}),J}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip"))for(let c in i.data)o.includes(c)||a.push(c);let u=[];for(let c of o){let l=s[c],m=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new pt(i,m,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof It){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(P(i,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let m=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new pt(i,m,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let m=await l.key,p=await l.value;c.push({key:m,value:p,alwaysSet:l.alwaysSet})}return c}).then(c=>ke.mergeObjectSync(n,c)):ke.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var i,s,o,a;let u=(o=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,r,n).message)!==null&&o!==void 0?o:n.defaultError;return r.code==="unrecognized_keys"?{message:(a=G.errToObj(e).message)!==null&&a!==void 0?a:u}:{message:u}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:K.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};return ie.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}omit(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}deepPartial(){return Si(this)}partial(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}),new t({...this._def,shape:()=>r})}required(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof dt;)s=s._def.innerType;r[n]=s}}),new t({...this._def,shape:()=>r})}keyof(){return Kh(ie.objectKeys(this.shape))}};je.create=(t,e)=>new je({shape:()=>t,unknownKeys:"strip",catchall:It.create(),typeName:K.ZodObject,...Z(e)});je.strictCreate=(t,e)=>new je({shape:()=>t,unknownKeys:"strict",catchall:It.create(),typeName:K.ZodObject,...Z(e)});je.lazycreate=(t,e)=>new je({shape:t,unknownKeys:"strip",catchall:It.create(),typeName:K.ZodObject,...Z(e)});var Tn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new ze(a.ctx.common.issues));return P(r,{code:x.invalid_union,unionErrors:o}),J}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(u=>new ze(u));return P(r,{code:x.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};Tn.create=(t,e)=>new Tn({options:t,typeName:K.ZodUnion,...Z(e)});var zt=t=>t instanceof Sn?zt(t.schema):t instanceof Ze?zt(t.innerType()):t instanceof _n?[t.value]:t instanceof In?t.options:t instanceof On?ie.objectValues(t.enum):t instanceof xn?zt(t._def.innerType):t instanceof yn?[void 0]:t instanceof En?[null]:t instanceof dt?[void 0,...zt(t.unwrap())]:t instanceof $t?[null,...zt(t.unwrap())]:t instanceof Cs||t instanceof wn?zt(t.unwrap()):t instanceof Rn?zt(t._def.innerType):[],Ka=class t extends X{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return P(r,{code:x.invalid_type,expected:M.object,received:r.parsedType}),J;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(P(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=zt(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:K.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Z(n)})}};function $l(t,e){let r=Rr(t),n=Rr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let i=ie.objectKeys(e),s=ie.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let u=$l(t[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],u=$l(o,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var An=class extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(Bl(s)||Bl(o))return J;let a=$l(s.value,o.value);return a.valid?((Gl(s)||Gl(o))&&r.dirty(),{status:r.value,value:a.data}):(P(n,{code:x.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};An.create=(t,e,r)=>new An({left:t,right:e,typeName:K.ZodIntersection,...Z(r)});var Gt=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:x.invalid_type,expected:M.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return P(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new pt(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>ke.mergeArray(r,o)):ke.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Gt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gt({items:t,typeName:K.ZodTuple,rest:null,...Z(e)})};var Ya=class t extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:x.invalid_type,expected:M.object,received:n.parsedType}),J;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new pt(n,a,n.path,a)),value:o._parse(new pt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ke.mergeObjectAsync(r,i):ke.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof X?new t({keyType:e,valueType:r,typeName:K.ZodRecord,...Z(n)}):new t({keyType:wr.create(),valueType:e,typeName:K.ZodRecord,...Z(r)})}},Ri=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:x.invalid_type,expected:M.map,received:n.parsedType}),J;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new pt(n,a,n.path,[c,"key"])),value:s._parse(new pt(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return J;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return J;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};Ri.create=(t,e,r)=>new Ri({valueType:e,keyType:t,typeName:K.ZodMap,...Z(r)});var wi=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:x.invalid_type,expected:M.set,received:n.parsedType}),J;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(P(n,{code:x.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(P(n,{code:x.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(u){let c=new Set;for(let l of u){if(l.status==="aborted")return J;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>s._parse(new pt(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};wi.create=(t,e)=>new wi({valueType:t,minSize:null,maxSize:null,typeName:K.ZodSet,...Z(e)});var Ja=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return P(r,{code:x.invalid_type,expected:M.function,received:r.parsedType}),J;function n(a,u){return ja({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qa(),Ii].filter(c=>!!c),issueData:{code:x.invalid_arguments,argumentsError:u}})}function i(a,u){return ja({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qa(),Ii].filter(c=>!!c),issueData:{code:x.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Dr){let a=this;return $e(async function(...u){let c=new ze([]),l=await a._def.args.parseAsync(u,s).catch(f=>{throw c.addIssue(n(u,f)),c}),m=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw c.addIssue(i(m,f)),c})})}else{let a=this;return $e(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new ze([n(u,c.error)]);let l=Reflect.apply(o,this,c.data),m=a._def.returns.safeParse(l,s);if(!m.success)throw new ze([i(l,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Gt.create(e).rest(Zt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Gt.create([]).rest(Zt.create()),returns:r||Zt.create(),typeName:K.ZodFunction,...Z(n)})}},Sn=class extends X{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Sn.create=(t,e)=>new Sn({getter:t,typeName:K.ZodLazy,...Z(e)});var _n=class extends X{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return P(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};_n.create=(t,e)=>new _n({value:t,typeName:K.ZodLiteral,...Z(e)});function Kh(t,e){return new In({values:t,typeName:K.ZodEnum,...Z(e)})}var In=class t extends X{constructor(){super(...arguments),Rs.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{expected:ie.joinValues(n),received:r.parsedType,code:x.invalid_type}),J}if(Ha(this,Rs,"f")||Wh(this,Rs,new Set(this._def.values),"f"),!Ha(this,Rs,"f").has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{received:r.data,code:x.invalid_enum_value,options:n}),J}return $e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Rs=new WeakMap;In.create=Kh;var On=class extends X{constructor(){super(...arguments),ws.set(this,void 0)}_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let i=ie.objectValues(r);return P(n,{expected:ie.joinValues(i),received:n.parsedType,code:x.invalid_type}),J}if(Ha(this,ws,"f")||Wh(this,ws,new Set(ie.getValidEnumValues(this._def.values)),"f"),!Ha(this,ws,"f").has(e.data)){let i=ie.objectValues(r);return P(n,{received:n.data,code:x.invalid_enum_value,options:i}),J}return $e(e.data)}get enum(){return this._def.values}};ws=new WeakMap;On.create=(t,e)=>new On({values:t,typeName:K.ZodNativeEnum,...Z(e)});var Dr=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return P(r,{code:x.invalid_type,expected:M.promise,received:r.parsedType}),J;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return $e(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Dr.create=(t,e)=>new Dr({type:t,typeName:K.ZodPromise,...Z(e)});var Ze=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{P(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return J;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?J:u.status==="dirty"||r.value==="dirty"?_i(u.value):u});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"||r.value==="dirty"?_i(a.value):a}}if(i.type==="refinement"){let o=a=>{let u=i.refinement(a,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bs(o))return o;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>bs(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):o);ie.assertNever(i)}};Ze.create=(t,e,r)=>new Ze({schema:t,typeName:K.ZodEffects,effect:e,...Z(r)});Ze.createWithPreprocess=(t,e,r)=>new Ze({schema:e,effect:{type:"preprocess",transform:t},typeName:K.ZodEffects,...Z(r)});var dt=class extends X{_parse(e){return this._getType(e)===M.undefined?$e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(t,e)=>new dt({innerType:t,typeName:K.ZodOptional,...Z(e)});var $t=class extends X{_parse(e){return this._getType(e)===M.null?$e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:K.ZodNullable,...Z(e)});var xn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:K.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Rn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ds(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:K.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var bi=class extends X{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};bi.create=t=>new bi({typeName:K.ZodNaN,...Z(t)});var cO=Symbol("zod_brand"),Cs=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vs=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),_i(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?J:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:K.ZodPipeline})}},wn=class extends X{_parse(e){let r=this._def.innerType._parse(e),n=i=>(bs(i)&&(i.value=Object.freeze(i.value)),i);return Ds(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:K.ZodReadonly,...Z(e)});function Yh(t,e={},r){return t?br.create().superRefine((n,i)=>{var s,o;if(!t(n)){let a=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(o=(s=a.fatal)!==null&&s!==void 0?s:r)!==null&&o!==void 0?o:!0,c=typeof a=="string"?{message:a}:a;i.addIssue({code:"custom",...c,fatal:u})}}):br.create()}var lO={object:je.lazycreate},K;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(K||(K={}));var dO=(t,e={message:`Input not instance of ${t.name}`})=>Yh(r=>r instanceof t,e),Jh=wr.create,zh=fn.create,pO=bi.create,fO=mn.create,Zh=hn.create,mO=gn.create,hO=Oi.create,gO=yn.create,yO=En.create,EO=br.create,TO=Zt.create,AO=It.create,SO=xi.create,_O=Xt.create,IO=je.create,OO=je.strictCreate,xO=Tn.create,RO=Ka.create,wO=An.create,bO=Gt.create,DO=Ya.create,CO=Ri.create,vO=wi.create,NO=Ja.create,PO=Sn.create,LO=_n.create,UO=In.create,MO=On.create,FO=Dr.create,Vh=Ze.create,kO=dt.create,BO=$t.create,GO=Ze.createWithPreprocess,$O=vs.create,VO=()=>Jh().optional(),qO=()=>zh().optional(),WO=()=>Zh().optional(),QO={string:t=>wr.create({...t,coerce:!0}),number:t=>fn.create({...t,coerce:!0}),boolean:t=>hn.create({...t,coerce:!0}),bigint:t=>mn.create({...t,coerce:!0}),date:t=>gn.create({...t,coerce:!0})},jO=J,re=Object.freeze({__proto__:null,defaultErrorMap:Ii,setErrorMap:jI,getErrorMap:Qa,makeIssue:ja,EMPTY_PATH:HI,addIssueToContext:P,ParseStatus:ke,INVALID:J,DIRTY:_i,OK:$e,isAborted:Bl,isDirty:Gl,isValid:bs,isAsync:Ds,get util(){return ie},get objectUtil(){return kl},ZodParsedType:M,getParsedType:Rr,ZodType:X,datetimeRegex:Hh,ZodString:wr,ZodNumber:fn,ZodBigInt:mn,ZodBoolean:hn,ZodDate:gn,ZodSymbol:Oi,ZodUndefined:yn,ZodNull:En,ZodAny:br,ZodUnknown:Zt,ZodNever:It,ZodVoid:xi,ZodArray:Xt,ZodObject:je,ZodUnion:Tn,ZodDiscriminatedUnion:Ka,ZodIntersection:An,ZodTuple:Gt,ZodRecord:Ya,ZodMap:Ri,ZodSet:wi,ZodFunction:Ja,ZodLazy:Sn,ZodLiteral:_n,ZodEnum:In,ZodNativeEnum:On,ZodPromise:Dr,ZodEffects:Ze,ZodTransformer:Ze,ZodOptional:dt,ZodNullable:$t,ZodDefault:xn,ZodCatch:Rn,ZodNaN:bi,BRAND:cO,ZodBranded:Cs,ZodPipeline:vs,ZodReadonly:wn,custom:Yh,Schema:X,ZodSchema:X,late:lO,get ZodFirstPartyTypeKind(){return K},coerce:QO,any:EO,array:_O,bigint:fO,boolean:Zh,date:mO,discriminatedUnion:RO,effect:Vh,enum:UO,function:NO,instanceof:dO,intersection:wO,lazy:PO,literal:LO,map:CO,nan:pO,nativeEnum:MO,never:AO,null:yO,nullable:BO,number:zh,object:IO,oboolean:WO,onumber:qO,optional:kO,ostring:VO,pipeline:$O,preprocess:GO,promise:FO,record:DO,set:vO,strictObject:OO,string:Jh,symbol:hO,transformer:Vh,tuple:bO,undefined:gO,union:xO,unknown:TO,void:SO,NEVER:jO,ZodIssueCode:x,quotelessJson:QI,ZodError:ze});var bn=(r=>(r.ASCENDING="ascending",r.DESCENDING="descending",r))(bn||{}),za=(r=>(r.STRING="string",r.NUMBER="number",r))(za||{});var tu=re.string().refine(t=>t!=="_complexIdOperator",{message:"Key '_complexIdOperator' is not allowed"}),Xh=re.record(tu,re.string()),Za=re.record(tu,re.any()),Xa=re.record(tu,re.union([re.any().array(),re.string()])),eg=re.lazy(()=>re.object({conditions:re.array(re.object(tg))})),eu=re.union([re.string(),re.number()]),tg={string:Xh.optional(),fuzzy:Xh.optional(),range:re.record(tu,re.union([re.object({high:eu,low:eu}),re.object({high:eu}),re.object({low:eu})])).optional(),equal:Za.optional(),notEqual:Za.optional(),empty:Za.optional(),notEmpty:Za.optional(),oneOf:Xa.optional(),contains:Xa.optional(),notContains:Xa.optional(),containsAny:Xa.optional(),$and:eg.optional(),$or:eg.optional()},eq=re.object({query:re.object({allOr:re.boolean().optional(),onEmptyFilter:re.nativeEnum(Ai).optional(),...tg}).optional(),paginate:re.boolean().optional(),bookmark:re.union([re.string(),re.number()]).nullish(),limit:re.number().optional(),sort:re.string().nullish(),sortOrder:re.nativeEnum(bn).optional(),sortType:re.nativeEnum(za).nullish(),version:re.string().optional(),disableEscaping:re.boolean().optional(),countRows:re.boolean().optional()});var Np={};N(Np,{APP_DEV:()=>Qu,APP_DEV_PREFIX:()=>yt,APP_PREFIX:()=>gt,AutomationViewMode:()=>Wu,BUDIBASE_DATASOURCE_TYPE:()=>xp,Config:()=>vp,Cookie:()=>Kn,DEFAULT_BB_DATASOURCE_ID:()=>Di,DEFAULT_EMPLOYEE_TABLE_ID:()=>Dp,DEFAULT_EXPENSES_TABLE_ID:()=>bp,DEFAULT_INVENTORY_TABLE_ID:()=>wp,DEFAULT_JOBS_TABLE_ID:()=>Rp,DEFAULT_TENANT_ID:()=>Ae,DeprecatedViews:()=>Hi,DesignDocuments:()=>ju,DocumentType:()=>ye,GlobalRole:()=>Cp,Header:()=>Xe,InternalTable:()=>xr,MAX_VALID_DATE:()=>Ku,MIN_VALID_DATE:()=>vT,SEPARATOR:()=>v,SQLITE_DESIGN_DOC_ID:()=>Ht,SQS_DATASOURCE_INTERNAL:()=>Op,StaticDatabases:()=>Te,UNICODE_MAX:()=>Ge,UserStatus:()=>Hu,ViewName:()=>kr});var AW={SUMMARISE_TEXT:{columns:"columns"},CLEAN_DATA:{column:"column"},TRANSLATE:{column:"column",language:"prompt"},CATEGORISE_TEXT:{columns:"columns",categories:"prompt"},SENTIMENT_ANALYSIS:{column:"column"},PROMPT:{prompt:"prompt"},SEARCH_WEB:{columns:"columns"}};var Xe=(S=>(S.API_KEY="x-budibase-api-key",S.LICENSE_KEY="x-budibase-license-key",S.API_VER="x-budibase-api-version",S.APP_ID="x-budibase-app-id",S.SESSION_ID="x-budibase-session-id",S.TYPE="x-budibase-type",S.PREVIEW_ROLE="x-budibase-role",S.TENANT_ID="x-budibase-tenant-id",S.VERIFICATION_CODE="x-budibase-verification-code",S.RETURN_VERIFICATION_CODE="x-budibase-return-verification-code",S.RESET_PASSWORD_CODE="x-budibase-reset-password-code",S.RETURN_RESET_PASSWORD_CODE="x-budibase-return-reset-password-code",S.TOKEN="x-budibase-token",S.CSRF_TOKEN="x-csrf-token",S.CORRELATION_ID="x-budibase-correlation-id",S.AUTHORIZATION="authorization",S.MIGRATING_APP="x-budibase-migrating-app",S.COOKIE="cookie",S))(Xe||{});var OW={string:["string","options","longform","barcodeqr"],options:["options","string","longform","barcodeqr"],longform:["longform","string","options","barcodeqr"],barcodeqr:["barcodeqr","string","options","longform"],number:["number","boolean"],json:["json","array","attachment","attachment_single","bb_reference","signature_single"]};var CW="darkest",vW="light",YO=[{id:"light",name:"Light"},{id:"darkest",name:"Dark"},{id:"nord",name:"Nord",base:"darkest"},{id:"midnight",name:"Midnight",base:"darkest"}];var et={Equals:{value:"equal",label:"Equals"},NotEquals:{value:"notEqual",label:"Not equals"},Empty:{value:"empty",label:"Is empty"},NotEmpty:{value:"notEmpty",label:"Is not empty"},StartsWith:{value:"string",label:"Starts with"},Like:{value:"fuzzy",label:"Like"},MoreThan:{value:"rangeLow",label:"More than or equal to"},LessThan:{value:"rangeHigh",label:"Less than or equal to"},Contains:{value:"contains",label:"Contains"},NotContains:{value:"notContains",label:"Does not contain"},In:{value:"oneOf",label:"Is in"},ContainsAny:{value:"containsAny",label:"Has any"}},rg={integer:{max:2147483647,min:-2147483648},int:{max:2147483647,min:-2147483648},smallint:{max:32767,min:-32768},mediumint:{max:8388607,min:-8388608}};var Di="datasource_internal_bb_default";var Mr={};N(Mr,{ColumnSplitter:()=>lp,NoEmptyFilterStrings:()=>IT,buildQuery:()=>OT,cleanupQuery:()=>fp,fixupFilterArrays:()=>hp,getKeyNumbering:()=>mp,getValidOperatorsForType:()=>SC,hasFilters:()=>dp,limit:()=>RT,recurseLogicalOperators:()=>pp,removeKeyNumbering:()=>ru,runQuery:()=>Fu,search:()=>OC,sort:()=>xT,splitFiltersArray:()=>nu});var Qi=W(ng());var Ci={};N(Ci,{filterValueToLabel:()=>tx,hasSchema:()=>rx,isSupportedUserSearch:()=>sg,parallelForeach:()=>ex,processSearchFilters:()=>Wl,toMap:()=>ix,trimOtherProps:()=>nx,unreachable:()=>XO});var ig=W(require("lodash")),ZO=["field","operator","value","type","externalType","valueType","noValue","formulaType"];function XO(t,e){let r=e?.message||`No such case in exhaustive switch: ${t}`;if(!!!e?.doNotThrow)throw new Error(r)}async function ex(t,e,r){let n=[],i=0,s=async()=>{for(;i<t.length;){let o=i++,a=t[o];await e(a)}};for(let o=0;o<Math.min(r,t.length);o++)n.push(s());await Promise.all(n)}function tx(){return Object.keys(et).reduce((t,e)=>{let n=et[e];return t[n.value]=n.label,t},{})}function rx(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null&&!(t instanceof Date)&&Object.keys(t).length>0}function nx(t,e){return Object.keys(t).filter(n=>e.includes(n)).reduce((n,i)=>({...n,[i]:t[i]}),{})}function sg(t){let e=[{op:"string",key:"email"},{op:"equal",key:"_id"},{op:"oneOf",key:"_id"}],{allOr:r,onEmptyFilter:n,...i}=t;for(let[s,o]of Object.entries(i)){if(typeof o!="object")return!1;if(Ba(s)){for(let c of t[s].conditions)if(!sg(c))return!1;return!0}let a=Object.keys(o||{});if(a.length===0)continue;if(!e.find(c=>c.op===s&&a.length===1&&a[0]===c.key))return!1}return!0}function Wl(t){if(!t||t.length===0)return;let{allOr:e,onEmptyFilter:r,filters:n}=nu(t);return{logicalOperator:"all",onEmptyFilter:r||"all",groups:[{logicalOperator:e?"any":"all",filters:n.map(i=>{let s=ig.default.pick(i,ZO);return s.field=ru(s.field),s})}]}}function ix(t,e){return e.reduce((r,n)=>(r[n[t]]=n,r),{})}var jt={};N(jt,{cancelableTimeout:()=>og,cron:()=>ip,deepGet:()=>Ql,duplicateName:()=>yC,getSequentialName:()=>EC,getUserColor:()=>ox,getUserInitials:()=>sx,getUserLabel:()=>ax,isGoogleSheets:()=>cx,isSQL:()=>lx,lists:()=>cp,retry:()=>dx,roles:()=>up,schema:()=>Ao,views:()=>ap,wait:()=>jl,withTimeout:()=>ux});var Ql=(t,e)=>{if(!t||!e)return null;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];let r=e.split(".");for(let n=0;n<r.length;n++)t=t?.[r[n]];return t},sx=t=>{if(!t)return"?";let e="";return e+=t.firstName?t.firstName[0]:"",e+=t.lastName?t.lastName[0]:"",e!==""?e:t.email?.[0]||"U"},ox=t=>{let e=t?._id;if(!e)return"var(--spectrum-global-color-blue-400)";e=e.replace("ro_ta_users_","");let r=1;for(let n=0;n<e.length;n++)r+=e.charCodeAt(n),r=r%36;return`hsl(${r*10}, 50%, 40%)`},ax=t=>{if(!t)return"";let{firstName:e,lastName:r,email:n}=t;return e&&r?`${e} ${r}`:e||r||n};function og(t){let e;return[new Promise((r,n)=>{e=setTimeout(()=>{n({status:301,errno:"ETIME"})},t)}),()=>{clearTimeout(e)}]}async function ux(t,e){let[r,n]=og(t),i=await Promise.race([e(),r]);return n(),i}function cx(t){return t==="GOOGLE_SHEETS"}function lx(t){return!t||!t.source?!1:["POSTGRES","SQL_SERVER","MYSQL","ORACLE"].indexOf(t.source)!==-1||t.isSQL===!0}async function jl(t){return new Promise(e=>setTimeout(e,t))}async function dx(t,e){let{times:r=3}=e||{};if(r<1)throw new Error(`invalid retry count: ${r}`);let n;for(let i=0;i<r;i++){let s=1.5**i*1e3*(Math.random()+.5);await jl(s);try{return await t()}catch(o){n=o}}throw n}var ip={};N(ip,{getNextExecutionDates:()=>rC,validate:()=>nC});var ET=W(Vt()),TT=W(gT()),yT="(Input cron: ",eC={"smaller than lower limit":"less than","bigger than upper limit":"greater than",daysOfMonth:"'days of the month'",daysOfWeek:"'days of the week'",years:"'years'",months:"'months'",hours:"'hours'",minutes:"'minutes'",seconds:"'seconds'"};function tC(t){let e=[];for(let r of t){r.includes(yT)&&(r=r.split(yT)[0].trim());for(let[n,i]of Object.entries(eC))r.includes(n)&&(r=r.replace(new RegExp(n,"g"),i));e.push(r)}return e}function rC(t,e=4){let r=TT.default.parseExpression(t),n=[];for(let i=0;i<e;i++)n.push(r.next().toString());return n}function nC(t){let e=(0,ET.default)(t,{preset:"npm-cron-schedule",override:{useSeconds:!1}});return e.isValid()?{valid:!0}:{valid:!1,err:tC(e.getError())}}var Ao={};N(Ao,{decodeNonAscii:()=>sp,encodeNonAscii:()=>oC,isDeprecatedSingleUserColumn:()=>iC,isNumeric:()=>aC,isRequired:()=>sC});function iC(t){return t.type==="bb_reference"&&t.subtype==="user"&&t.constraints?.type!=="array"}function sC(t){return!!t&&(typeof t.presence!="boolean"&&t.presence?.allowEmpty===!1||t.presence===!0)}function oC(t){return t.split("").map(e=>e.charCodeAt(0)>127?"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"):e).join("")}function sp(t){return t.replace(/\\u([0-9a-fA-F]{4})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function aC(t){return t.type==="number"||t.type==="bigint"}var ap={};N(ap,{basicFields:()=>pC,calculationFields:()=>dC,hasCalculationFields:()=>lC,isBasicViewField:()=>uC,isCalculationField:()=>So,isCalculationView:()=>cC,isV2:()=>fC,isVisible:()=>AT});var op=require("lodash");function So(t){return"calculationType"in t}function uC(t){return!So(t)}function cC(t){return t.type==="calculation"}function lC(t){return Object.values(t.schema||{}).some(So)}function dC(t){return(0,op.pickBy)(t.schema||{},So)}function AT(t){return t.visible!==!1}function pC(t,e){let{visible:r=!0}=e||{};return(0,op.pickBy)(t.schema||{},n=>!So(n)&&(!r||AT(n)))}function fC(t){return t.version===2}var up={};N(up,{checkForRoleInheritanceLoops:()=>hC});function mC(t){return`role${v}${t}`}function hC(t){let e=new Map;t.forEach(s=>{e.set(s._id,s)});let r=new Set,n=new Set;function i(s){let o=mC(s);if(n.has(s)||n.has(o))return!0;if(r.has(s)||r.has(o))return!1;n.add(s);let a=e.get(o)||e.get(s);if(!a)return n.delete(s),!1;let u=Array.isArray(a.inherits)?a.inherits:[a.inherits];for(let c of u)if(c&&i(c))return!0;return n.delete(s),r.add(s),!1}return!!t.find(s=>i(s._id))}var cp={};N(cp,{punctuateList:()=>gC});function gC(t){return t.length===0?"":t.length===1?t[0]:t.length===2?t.join(" and "):t.slice(0,-1).join(", ")+" and "+t[t.length-1]}var yC=(t,e)=>{let r=new RegExp("\\s(\\d+)$"),n=t.split(r)[0],i=new RegExp(`${n}\\s(\\d+)$`),s=[];e.filter(a=>{if(a===n)return!0;let u=a.match(i);return u?(s.push(parseInt(u[1])),!0):!1}),s.sort((a,u)=>a-u);let o;if(s.length===0)o=1;else{for(let a=0;a<s.length;a++)if(s[a]!==a+1){o=a+1;break}o||(o=s.length+1)}return`${n} ${o}`},EC=(t,e,{getName:r,numberFirstItem:n,separator:i=""}={})=>{if(!e?.length)return"";let s=e.trim(),o=n?`${e}1`:s;if(!t?.length)return o;let a=0;return t.forEach(u=>{let c=r?.(u)??u;if(typeof c!="string"||!c.startsWith(s))return;let l=c.split(s);if(l.length!==2)return;l[1].trim()===""&&(l[1]="1");let m=parseInt(l[1]);m>a&&(a=m)}),a===0?o:`${e}${i}${a+1}`};var Hn=require("lodash");var TC=/{{([^{].*?)}}/g,_T=Object.values(Ti),AC=[...Object.values(Ir),...Object.values(Jt),...Object.values(dn)],SC=(t,e,r)=>{let n=et,i=[n.Equals,n.NotEquals,n.StartsWith,n.Like,n.Empty,n.NotEmpty,n.In],s=[n.Equals,n.NotEquals,n.MoreThan,n.LessThan,n.Empty,n.NotEmpty,n.In],o=[],{type:a,formulaType:u}=t;a==="string"?o=i:a==="number"||a==="bigint"?o=s:a==="options"?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty,n.In]:a==="array"?o=[n.Contains,n.NotContains,n.Empty,n.NotEmpty,n.ContainsAny]:a==="boolean"?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty]:a==="longform"?o=i:a==="datetime"?o=s:a==="formula"&&u==="static"?o=i.concat([n.MoreThan,n.LessThan]):a==="ai"?o=i.concat([n.MoreThan,n.LessThan]):a==="bb_reference_single"||Ao.isDeprecatedSingleUserColumn(t)?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty,n.In]:a==="bb_reference"?o=[n.Contains,n.NotContains,n.ContainsAny,n.Empty,n.NotEmpty]:a==="barcodeqr"&&(o=i);let c=r?.tableId?.includes("datasource_plus");return e==="_id"&&c&&(o=[n.Equals,n.NotEquals,n.In]),o},IT=[et.StartsWith.value,et.Like.value,et.Equals.value,et.NotEquals.value,et.Contains.value,et.NotContains.value,et.ContainsAny.value,et.In.value];function pp(t,e){for(let r of _T)t[r]&&(t[r].conditions=t[r].conditions.map(n=>e(n)));return t}var fp=t=>{for(let e of IT)if(t[e])for(let r of Object.keys(t)){if(r!==e)continue;if(typeof t[r]=="object")for(let[i,s]of Object.entries(t[r]))(s==null||s===""||_C(s))&&delete t[e][i]}return t=pp(t,fp),t};function _C(t){return Array.isArray(t)&&t.length===0}var ru=t=>mp(t).key,mp=t=>{if(typeof t=="string"&&t.match(/\d[0-9]*:/g)!=null){let e=t.split(":");return{prefix:`${e.shift()}:`,key:e.join(":")}}else return{key:t}},lp=class{constructor(e,r){if(this.tableNames=e.map(n=>n.name),this.tableIds=e.map(n=>n._id),this.relationshipColumnNames=e.flatMap(n=>Object.keys(n.schema).filter(i=>n.schema[i].type==="link")),this.relationships=this.tableNames.concat(this.tableIds).concat(this.relationshipColumnNames).sort((n,i)=>i.length-n.length),r?.aliases){this.aliases={};for(let[n,i]of Object.entries(r.aliases))this.aliases[i]=n}this.columnPrefix=r?.columnPrefix}run(e){let{prefix:r,key:n}=mp(e),i;if(this.aliases)for(let o of Object.keys(this.aliases||{})){let a=`${o}.`;n.startsWith(a)&&(i=this.aliases[o],n=n.slice(a.length))}let s;for(let o of this.relationships){let a=`${o}.`;if(n.startsWith(a)){let u=n.split(a);u.shift(),s=a,n=u.join(".");break}}return this.columnPrefix&&n.startsWith(this.columnPrefix)&&(n=sp(n.slice(this.columnPrefix.length))),{tableName:i,numberPrefix:r,relationshipPrefix:s,column:n}}};function IC(t){if(!t||!t?.operator||!t?.field)return;let e={},{operator:r,field:n,type:i,externalType:s}=t,{value:o}=t;(r==="empty"||r==="notEmpty")&&(o=null);let a=typeof o=="string"&&(o.match(TC)||[]).length>0;switch(i){case"datetime":if(!a&&r!=="empty"&&r!=="notEmpty"){if(!o)return;if(typeof o=="string")o=new Date(o).toISOString();else if(Ga(r))return e[r]??={},e[r][n]=o,e}break;case"number":typeof o=="string"&&!a&&(r==="oneOf"?o=o.split(",").map(parseFloat):o=parseFloat(o));break;case"boolean":o=`${o}`.toLowerCase()==="true";break;case"array":["contains","notContains","containsAny"].includes(r.toLocaleString())&&typeof o=="string"&&(o=o.split(","));break}if(Ga(r)){let c=rg[s]||{min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER};e[r]??={},e[r][n]={low:i==="number"?c.min:"0000-00-00T00:00:00.000Z",high:i==="number"?c.max:"9999-00-00T00:00:00.000Z"}}else if(r==="rangeHigh"&&o!=null&&o!=="")e.range??={},e.range[n]={...e.range[n],high:o};else if(r==="rangeLow"&&o!=null&&o!=="")e.range??={},e.range[n]={...e.range[n],low:o};else if(Lh(r)||Uh(r)||Ga(r))i==="boolean"?r==="equal"&&o===!1?(e.notEqual=e.notEqual||{},e.notEqual[n]=!0):r==="notEqual"&&o===!1?(e.equal=e.equal||{},e.equal[n]=!0):(e[r]??={},e[r][n]=o):(e[r]??={},e[r][n]=o);else throw new Error(`Unsupported operator: ${r}`);return e}function nu(t){let e={filters:[]};for(let r of t)"operator"in r&&r.operator==="allOr"?e.allOr=!0:"onEmptyFilter"in r?e.onEmptyFilter=r.onEmptyFilter:e.filters.push(r);return e}function OT(t){if(!t)return{};if(Array.isArray(t)&&(t=Wl(t),!t))return{};let e={};t.onEmptyFilter?e.onEmptyFilter=t.onEmptyFilter:e.onEmptyFilter="all";let r=ST(t.logicalOperator||"all");return e[r]={conditions:(t.groups||[]).map(n=>{if(n.groups){let u=OT(n);return delete u.onEmptyFilter,u}let{allOr:i,onEmptyFilter:s,filters:o}=nu(n.filters||[]);s&&(e.onEmptyFilter=s);let a=i?"$or":"$and";return n.logicalOperator&&(a=ST(n.logicalOperator)),{[a]:{conditions:o.map(IC).filter(u=>u)}}})},e}function ST(t){return t==="all"?"$and":"$or"}function hp(t){if(!t)return t;for(let e of Object.values(Jt)){let r=t[e];if(!(r==null||!(0,Hn.isPlainObject)(r)))for(let n of Object.keys(r)){if(Array.isArray(r[n]))continue;let i=r[n];typeof i=="string"?r[n]=i.split(",").map(s=>s.trim()):r[n]=[i]}}return pp(t,hp),t}function OC(t,e){let r=Fu(t,e.query);e.sort&&(r=xT(r,e.sort,e.sortOrder||"ascending",e.sortType));let n=r.length;e.limit&&(r=RT(r,e.limit.toString()));let i={rows:r};return e.countRows&&(i.totalRows=n),i}function Fu(t,e){if(!t||!Array.isArray(t))return[];if(!e)return t;if(e=fp(e),e=hp(e),!dp(e)&&e.onEmptyFilter==="none")return[];let r=(T,_)=>B=>{for(let[b,k]of Object.entries(e[T]||{})){let de=Ba(T)?B:Ql(B,ru(b)),un=_(de,k);if(e.allOr&&un)return!0;if(!e.allOr&&!un)return!1}return!e.allOr},n=r("string",(T,_)=>typeof T!="string"||typeof _!="string"?!1:T.toLowerCase().startsWith(_.toLowerCase())),i=r("fuzzy",(T,_)=>typeof T!="string"||typeof _!="string"?!1:T.toLowerCase().includes(_.toLowerCase())),s=r("range",(T,_)=>{if(T==null||T===""||((0,Hn.isPlainObject)(_.low)&&(0,Hn.isEmpty)(_.low)&&(_.low=void 0),(0,Hn.isPlainObject)(_.high)&&(0,Hn.isEmpty)(_.high)&&(_.high=void 0),_.low==null&&_.high==null))return!1;let B=+T;if(!isNaN(B)){let k=+_.low,de=+_.high;if(!isNaN(k)&&!isNaN(de))return B>=k&&B<=de;if(isNaN(k)){if(!isNaN(de))return B<=de}else return B>=k}let b=(0,Qi.default)(T);if(b.isValid()){let k=(0,Qi.default)(_.low||"0000-00-00T00:00:00.000Z"),de=(0,Qi.default)(_.high||"9999-00-00T00:00:00.000Z");if(k.isValid()&&de.isValid())return b.isAfter(k)&&b.isBefore(de)||b.isSame(k)||b.isSame(de);if(k.isValid())return b.isAfter(k)||b.isSame(k);if(de.isValid())return b.isBefore(de)||b.isSame(de)}return _.low!=null&&_.high!=null?T>=_.low&&T<=_.high:_.low!=null?T>=_.low:_.high!=null?T<=_.high:!1}),o=(T,_)=>{if(Array.isArray(T)){for(let b of T)if(o(b,_))return!0;return!1}if(T&&typeof T=="object"&&typeof _=="string")return T._id===_;if(T===_)return!0;if(T==null&&_!=null||T!=null&&_==null)return!1;let B=(0,Qi.default)(T);if(B.isValid()){let b=(0,Qi.default)(_);if(b.isValid())return B.isSame(b)}return!1},a=T=>(..._)=>!T(..._),u=r("equal",o),c=r("notEqual",a(o)),l=T=>typeof T=="string"?T==="":Array.isArray(T)?T.length===0:T&&typeof T=="object"?Object.keys(T).length===0:T==null,m=r("empty",l),p=r("notEmpty",a(l)),f=r("oneOf",(T,_)=>(typeof _=="string"&&(_=_.split(",")),typeof T=="number"&&(_=_.map(B=>parseFloat(B))),Array.isArray(_)?_.some(B=>o(T,B)):!1)),d=T=>(_,B)=>!Array.isArray(_)||(typeof B=="string"&&(B=B.split(","),typeof _[0]=="number"&&(B=B.map(b=>parseFloat(b)))),!Array.isArray(B))?!1:B.length===0?!0:B[T](b=>o(_,b)),g=r("contains",(T,_)=>Array.isArray(_)&&_.length===0?!0:d("every")(T,_)),E=r("notContains",(T,_)=>Array.isArray(_)&&_.length===0?!0:a(d("every"))(T,_)),y=r("containsAny",d("some")),S=r("$and",(T,_)=>{if(!_.length)return!1;for(let B of _)if(!Fu([T],B).length)return!1;return!0}),O=r("$or",(T,_)=>{if(!_.length)return!1;for(let B of _)if(Fu([T],{...B,allOr:!0}).length)return!0;return!1}),R=T=>{let _={string:n,fuzzy:i,range:s,equal:u,notEqual:c,empty:m,notEmpty:p,oneOf:f,contains:g,containsAny:y,notContains:E,$and:S,$or:O},B=Object.entries(e||{}).filter(([b,k])=>!["allOr","onEmptyFilter"].includes(b)&&k&&Object.keys(k).length>0).map(([b])=>_[b]?.(T)??!1);return dp(e)?e.allOr?B.some(b=>b===!0):B.every(b=>b===!0):!0};return t.filter(R)}function xT(t,e,r,n="string"){if(!e||!r||!n)return t;let i=s=>s==null?s:n==="string"?`${s}`:parseFloat(s);return t.slice().sort((s,o)=>{let a=i(s[e]),u=i(o[e]),c=u==null||a>u?1:-1;return r.toLowerCase()==="descending"?c*-1:c})}function RT(t,e){let r=typeof e=="number"?e:parseFloat(e);return isNaN(r)?t:t.slice(0,r)}var dp=t=>{if(!t)return!1;let e=r=>{for(let n of _T)if(r[n])for(let i of r[n]?.conditions||[]){let s=e(i);if(s)return s}for(let n of AC){let i=r[n];if(!i||typeof i!="object")continue;if(Object.entries(i).filter(o=>{let a=o[1]!==void 0||o[1]!==null||o[1]!=="";return n==="notEmpty"||a}).length!==0)return!0}return!1};return e(t)};var ot={};N(ot,{applications:()=>yp,automations:()=>Ep,screens:()=>Ip,users:()=>_p});var yp={};N(yp,{getDevAppID:()=>xC,getProdAppID:()=>ku});var gp=Or("app"),_o=Or("app_dev");function xC(t){if(!t)throw new Error("No app ID provided");if(t.startsWith(_o))return t;let e=t.split(gp);e.shift();let r=e.join(gp);return`${_o}${r}`}function ku(t){if(!t)throw new Error("No app ID provided");if(!t.startsWith(_o))return t;let e=t.split(_o);e.shift();let r=e.join(_o);return`${gp}${r}`}var Ep={};N(Ep,{isAppAction:()=>bC,isRowAction:()=>RC,isWebhookAction:()=>wC});function RC(t){return t.definition.trigger?.stepId==="ROW_ACTION"}function wC(t){return t.definition.trigger?.stepId==="WEBHOOK"}function bC(t){return t.definition.trigger?.stepId==="APP"}var _p={};N(_p,{canCreateApps:()=>DC,containsUserID:()=>UC,getGlobalUserID:()=>LC,getUserAppGroups:()=>MC,getUserGroups:()=>Sp,hasAdminPermissions:()=>Ap,hasAppBuilderPermissions:()=>$u,hasAppCreatorPermissions:()=>wT,hasBuilderPermissions:()=>NC,hasCreatorPermissions:()=>Vu,isAdmin:()=>Gu,isAdminOrBuilder:()=>CC,isAdminOrGlobalBuilder:()=>vC,isBuilder:()=>Tp,isCreator:()=>PC,isGlobalBuilder:()=>Bu,userAppAccessList:()=>FC});var Fr=W(require("lodash/fp"));function Tp(t,e){return t?t.builder?.global?!0:!!(e&&t.builder?.apps?.includes(ku(e))):!1}function Bu(t){return Tp(t)&&!$u(t)||Gu(t)}function DC(t){return Bu(t)||Vu(t)}function Gu(t){return t?Ap(t):!1}function CC(t,e){return Tp(t,e)||Gu(t)}function vC(t){return Bu(t)||Gu(t)}function $u(t){if(!t)return!1;let e=t.builder?.apps?.length;return!!!t.builder?.global&&e!=null&&e>0}function wT(t){return t?Fr.flow(Fr.get("roles"),Fr.values,Fr.find(e=>["CREATOR"].includes(e)),e=>!!e)(t):!1}function NC(t){return t?t.builder?.global||$u(t)||Vu(t):!1}function Ap(t){return t?!!t.admin?.global:!1}function Vu(t){return t?!!t.builder?.creator:!1}function PC(t){return t?Bu(t)||Ap(t)||Vu(t)||$u(t)||wT(t):!1}function LC(t){if(typeof t!="string")return t;let e=`ro${v}ta_users${v}`;return t.startsWith(e)?t.split(e)[1]:t}function UC(t){return typeof t!="string"?!1:t.includes(`us${v}`)}function Sp(t,e){return e?.filter(r=>r.users?.find(n=>n._id===t._id))||[]}function MC(t,e,r){let n=ku(t);return Sp(e,r).filter(s=>Object.keys(s.roles||{}).find(o=>o===n))}function FC(t,e){let n=Sp(t,e).flatMap(s=>Object.keys(s.roles||{})),i=[...Object.keys(t?.roles||{}),...n];return[...new Set(i)]}var Ip={};N(Ip,{findInSettings:()=>kC});function kC(t,e){let r=[];function n(i,s=""){for(let[o,a]of Object.entries(i))a&&(typeof a=="string"&&a.includes(e)?r.push({setting:s?`${s}.${o}`:o,value:a}):typeof a=="object"&&n(a,o))}return n(t.props),r}var $j={string:!0,longform:!0,options:!0,number:!0,datetime:!0,formula:!0,ai:!0,auto:!0,internal:!0,barcodeqr:!0,bigint:!0,boolean:!1,array:!1,attachment:!1,attachment_single:!1,signature_single:!1,link:!1,json:!1,bb_reference:!1,bb_reference_single:!1},Vj={string:!0,longform:!0,options:!0,number:!0,datetime:!0,auto:!0,internal:!0,barcodeqr:!0,bigint:!0,boolean:!0,json:!0,formula:!1,ai:!1,attachment:!1,attachment_single:!1,signature_single:!1,array:!1,link:!1,bb_reference:!1,bb_reference_single:!1},qj={number:!0,json:!0,datetime:!0,longform:!0,string:!0,options:!0,array:!0,bigint:!0,boolean:!0,auto:!1,internal:!1,barcodeqr:!1,formula:!1,ai:!1,attachment:!1,attachment_single:!1,signature_single:!1,link:!1,bb_reference:!0,bb_reference_single:!0};var zj={name:"Bash Scripting",tagline:"Execute a bash command",icon:"JourneyEvent",description:"Run a bash script",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"EXECUTE_BASH",inputs:{},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{stdout:{type:"string",description:"Standard output of your bash command or script"},success:{type:"boolean",description:"Whether the command was successful"}},required:["stdout"]}}};var eH={name:"Branch",icon:"Branch3",tagline:"Branch from this step",description:"Branching",stepId:"BRANCH",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{branches:{properties:{name:{type:"string"},condition:{customType:"filters"}}},children:{type:"array"}},required:["conditions"]},outputs:{properties:{branchName:{type:"string"},status:{type:"string",description:"Branch result"},branchId:{type:"string",description:"Branch ID"},success:{type:"boolean",description:"Branch success"}},required:["output"]}},type:"LOGIC"};var nH={name:"Collect Data",tagline:"Collect data to be sent to design",icon:"Collection",description:"Collects specified data so it can be provided to the design section",type:"ACTION",internal:!0,features:{},stepId:"COLLECT",inputs:{},schema:{inputs:{properties:{collection:{type:"string",title:"What to Collect"}},required:["collection"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},value:{type:"string",description:"Collected data"}},required:["success","value"]}}};var oH={name:"Create Row",tagline:"Create a {{inputs.enriched.table.name}} row",icon:"TableRowAddBottom",description:"Add a row to your database",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"CREATE_ROW",inputs:{},schema:{inputs:{properties:{row:{type:"object",properties:{tableId:{type:"string",customType:"table"}},customType:"row",title:"Table",required:["tableId"]}},required:["row"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The new row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the row creation was successful"},id:{type:"string",description:"The identifier of the new row"},revision:{type:"string",description:"The revision of the new row"}},required:["success","id","revision"]}}};var cH={name:"Delay",icon:"Clock",tagline:"Delay for {{inputs.time}} milliseconds",description:"Delay the automation until an amount of time has passed",stepId:"DELAY",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{time:{type:"number",title:"Delay in milliseconds"}},required:["time"]},outputs:{properties:{success:{type:"boolean",description:"Whether the delay was successful"}},required:["success"]}},type:"LOGIC"};var pH={description:"Delete a row from your database",icon:"TableRowRemoveCenter",name:"Delete Row",tagline:"Delete a {{inputs.enriched.table.name}} row",type:"ACTION",stepId:"DELETE_ROW",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},id:{type:"string",title:"Row ID"}},required:["tableId","id"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The deleted row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the deletion was successful"}},required:["row","success"]}}};var hH={name:"Discord Message",tagline:"Send a message to a Discord server",description:"Send a message to a Discord server",icon:"ri-discord-line",stepId:"discord",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Discord Webhook URL"},username:{type:"string",title:"Bot Name"},avatar_url:{type:"string",title:"Bot Avatar URL"},content:{type:"string",title:"Message"}},required:["url","content"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},response:{type:"string",description:"The response from the Discord Webhook"},success:{type:"boolean",description:"Whether the message sent successfully"}}}}};var EH={name:"External Data Connector",tagline:"Execute Data Connector",icon:"Data",description:"Execute a query in an external data connector",type:"ACTION",stepId:"EXECUTE_QUERY",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{query:{type:"object",properties:{queryId:{type:"string",customType:"query"}},customType:"queryParams",title:"Parameters",required:["queryId"]}},required:["query"]},outputs:{properties:{response:{type:"object",description:"The response from the datasource execution"},info:{type:"object",description:"Some query types may return extra data, like headers from a REST query"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var SH={name:"API Request",tagline:"Execute a REST request",icon:"GlobeGrid",description:"Execute a HTTP query from a REST datasource",type:"ACTION",stepId:"API_REQUEST",internal:!0,new:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{query:{type:"object",properties:{queryId:{type:"string"}},customType:"queryParams",title:"Parameters",required:["queryId"]}},required:["query"]},outputs:{properties:{response:{type:"object",description:"The response from the datasource execution"},info:{type:"object",description:"Some query types may return extra data, like headers from a REST query"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var OH={name:"JS Scripting",tagline:"Execute JavaScript Code",deprecated:!0,icon:"Code",description:"Run a piece of JavaScript code in your automation",type:"ACTION",internal:!0,stepId:"EXECUTE_SCRIPT",inputs:{},features:{LOOPING:!0},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{value:{type:"string",description:"The result of the return statement"},success:{type:"boolean",description:"Whether the action was successful"}},required:["success"]}}};var wH={name:"JavaScript",tagline:"Execute JavaScript Code",icon:"Brackets",description:"Run a piece of JavaScript code in your automation",type:"ACTION",internal:!0,new:!1,stepId:"EXECUTE_SCRIPT_V2",inputs:{},features:{LOOPING:!0},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{value:{type:"string",description:"The result of the return statement"},success:{type:"boolean",description:"Whether the action was successful"}},required:["success"]}}};var JC={EQUAL:"Equals",NOT_EQUAL:"Not equals",GREATER_THAN:"Greater than",LESS_THAN:"Less than"},CH={name:"Condition",tagline:"{{inputs.field}} {{inputs.condition}} {{inputs.value}}",icon:"Branch2",description:"Conditionally halt automations which do not meet certain conditions",type:"LOGIC",internal:!0,features:{},stepId:"FILTER",inputs:{condition:"EQUAL"},schema:{inputs:{properties:{field:{type:"string",title:"Reference Value"},condition:{type:"string",title:"Condition",enum:Object.values(Pl),pretty:Object.values(JC)},value:{type:"string",title:"Comparison Value"}},required:["field","condition","value"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},result:{type:"boolean",description:"Whether the logic block passed"}},required:["success","result"]}}};var PH={name:"Looping",icon:"Reuse",tagline:"Loop the block",description:"Loop",stepId:"LOOP",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{option:{customType:"loopOption",title:"Input type"},binding:{type:"string",title:"Binding / Value"},iterations:{type:"number",title:"Max loop iterations"},failure:{type:"string",title:"Failure Condition"}},required:["type","value","iterations","failure"]},outputs:{properties:{items:{customType:"item",description:"The item currently being executed"},success:{type:"boolean",description:"Whether the message loop was successfully"},iterations:{type:"number",description:"The amount of times the block ran"}},required:["success","items","iterations"]}},type:"LOGIC"};var MH={name:"Make Integration",stepTitle:"Make",tagline:"Trigger a Make scenario",description:"Performs a webhook call to Make and gets the response (if configured)",icon:"ri-shut-down-line",stepId:"integromat",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},body:{type:"json",title:"Payload"}},required:["url","body"]},outputs:{properties:{success:{type:"boolean",description:"Whether call was successful"},httpStatus:{type:"number",description:"The HTTP status code returned"},response:{type:"object",description:"The webhook response - this can have properties"}},required:["success","response"]}}};var BH={name:"n8n Integration",stepTitle:"n8n",tagline:"Trigger an n8n workflow",description:"Performs a webhook call to n8n and gets the response (if configured)",icon:"ri-shut-down-line",stepId:"n8n",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},method:{type:"string",title:"Method",enum:Object.values(Ll)},authorization:{type:"string",title:"Authorization"},body:{type:"json",title:"Payload"}},required:["url","method"]},outputs:{properties:{success:{type:"boolean",description:"Whether call was successful"},httpStatus:{type:"number",description:"The HTTP status code returned"},response:{type:"object",description:"The webhook response - this can have properties"}},required:["success","response"]}}};var bT=(i=>(i.GPT_4O_MINI="gpt-4o-mini",i.GPT_4O="gpt-4o",i.GPT_4="gpt-4",i.GPT_35_TURBO="gpt-3.5-turbo",i))(bT||{}),VH={name:"OpenAI",tagline:"Send prompts to ChatGPT",icon:"Algorithm",description:"Interact with the OpenAI ChatGPT API.",type:"ACTION",internal:!0,features:{},deprecated:!1,stepId:"OPENAI",inputs:{prompt:""},schema:{inputs:{properties:{prompt:{type:"string",title:"Prompt"},model:{type:"string",title:"Model",enum:Object.values(bT)}},required:["prompt","model"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was output"}},required:["success","response"]}}};var DT=(s=>(s.POST="POST",s.GET="GET",s.PUT="PUT",s.DELETE="DELETE",s.PATCH="PATCH",s))(DT||{}),QH={deprecated:!0,name:"Outgoing webhook",tagline:"Send a {{inputs.requestMethod}} request",icon:"Send",description:"Send a request of specified method to a URL",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"OUTGOING_WEBHOOK",inputs:{requestMethod:"POST",url:"http://",requestBody:"{}",headers:"{}"},schema:{inputs:{properties:{requestMethod:{type:"string",enum:Object.values(DT),title:"Request method"},url:{type:"string",title:"URL"},requestBody:{type:"string",title:"JSON Body",customType:"wide"},headers:{type:"string",title:"Headers",customType:"wide"}},required:["requestMethod","url"]},outputs:{properties:{response:{type:"object",description:"The response from the webhook"},httpStatus:{type:"number",description:"The HTTP status code returned"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var nv={ascending:"Ascending",descending:"Descending"},KH={description:"Query rows from the database",icon:"Search",name:"Query rows",tagline:"Query rows from {{inputs.enriched.table.name}} table",type:"ACTION",stepId:"QUERY_ROWS",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"filters",title:"Filtering"},sortColumn:{type:"string",title:"Sort Column",customType:"column"},sortOrder:{type:"string",title:"Sort Order",enum:Object.values(bn),pretty:Object.values(nv)},limit:{type:"number",title:"Limit",customType:"queryLimit"}},required:["tableId"]},outputs:{properties:{rows:{type:"array",customType:"rows",description:"The rows that were found"},success:{type:"boolean",description:"Whether the query was successful"}},required:["rows","success"]}}};var zH={description:"Send an email using SMTP",tagline:"Send SMTP email to {{inputs.to}}",icon:"Email",name:"Send Email (SMTP)",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"SEND_EMAIL_SMTP",inputs:{},schema:{inputs:{properties:{to:{type:"string",title:"Send To"},from:{type:"string",title:"Send From"},cc:{type:"string",title:"CC"},bcc:{type:"string",title:"BCC"},subject:{type:"string",title:"Email Subject"},contents:{type:"longform",title:"Message",description:"Use markdown or HTML for rich text formatting: **bold**, _italics_, # Headings, * Bullets, <br> for line breaks, and more."},addInvite:{type:"boolean",title:"Add calendar invite"},startTime:{type:"date",title:"Start Time",dependsOn:"addInvite"},endTime:{type:"date",title:"End Time",dependsOn:"addInvite"},summary:{type:"string",title:"Meeting Summary",dependsOn:"addInvite"},location:{type:"string",title:"Location",dependsOn:"addInvite"},attachments:{type:"attachment",customType:"multi_attachments",title:"Attachments"}},required:["to","from","subject","contents"]},outputs:{properties:{success:{type:"boolean",description:"Whether the email was sent"},response:{type:"object",description:"A response from the email client, this may be an error"}},required:["success"]}}};var eK={name:"Backend log",tagline:"Console log a value in the backend",icon:"Monitoring",description:"Logs the given text to the server (using console.log)",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"SERVER_LOG",inputs:{text:""},schema:{inputs:{properties:{text:{type:"string",title:"Log"}},required:["text"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},message:{type:"string",description:"What was output"}},required:["success","message"]}}};var nK={name:"Slack Message",tagline:"Send a message to Slack",description:"Send a message to Slack",icon:"ri-slack-line",stepId:"slack",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Incoming Webhook URL"},text:{type:"string",title:"Message"}},required:["url","text"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},success:{type:"boolean",description:"Whether the message sent successfully"},response:{type:"string",description:"The response from the Slack Webhook"}}}}};var oK={name:"Trigger an automation",tagline:"Triggers an automation synchronously",icon:"Sync",description:"Triggers an automation synchronously",type:"ACTION",internal:!0,features:{},stepId:"TRIGGER_AUTOMATION_RUN",inputs:{},schema:{inputs:{properties:{automation:{type:"object",properties:{automationId:{type:"string",customType:"automation"}},customType:"automationFields",title:"Automation Fields",required:["automationId"]},timeout:{type:"number",title:"Timeout (ms)"}},required:["automationId"]},outputs:{properties:{success:{type:"boolean",description:"Whether the automation was successful"},value:{type:"object",description:"Automation Result"}},required:["success","value"]}}};var cK={name:"Update Row",tagline:"Update a {{inputs.enriched.table.name}} row",icon:"Refresh",description:"Update a row in your database",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"UPDATE_ROW",inputs:{},schema:{inputs:{properties:{meta:{type:"object",title:"Field settings"},row:{type:"object",customType:"row",title:"Table"},rowId:{type:"string",title:"Row ID"}},required:["row","rowId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The updated row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the action was successful"},id:{type:"string",description:"The identifier of the updated row"},revision:{type:"string",description:"The revision of the updated row"}},required:["success","id","revision"]}}};var pK={name:"Zapier Webhook",stepId:"zapier",type:"ACTION",internal:!1,features:{LOOPING:!0},description:"Trigger a Zapier Zap via webhooks",tagline:"Trigger a Zapier Zap",icon:"ri-flashlight-line",inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},body:{type:"json",title:"Payload"}},required:["url"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},response:{type:"string",description:"The response from Zapier"}}}}};var hK={name:"Classify Text",icon:"PageTag",tagline:"Classify text into predefined categories using AI",description:"Analyzes text and assigns it to one of the categories you provide.",stepId:"CLASSIFY_CONTENT",internal:!0,inputs:{},schema:{inputs:{properties:{textInput:{type:"longform",title:"Text",description:"The text content you want the AI to classify."},categoryItems:{type:"array",customType:"categories",title:"Categories",description:"Add categories for the AI to use when classifying text."}},required:["textInput","categoryItems"]},outputs:{properties:{category:{type:"string",description:"The category assigned by the AI."},success:{type:"boolean",description:"Whether the classification was successful."}},required:["category","success"]}},type:"ACTION"};var EK={name:"LLM Prompt",tagline:"Send prompts to LLM",icon:"Algorithm",description:"Interact with an LLM.",type:"ACTION",internal:!0,features:{},stepId:"PROMPT_LLM",inputs:{prompt:""},schema:{inputs:{properties:{prompt:{type:"longform",title:"Prompt"}},required:["prompt","model"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was output"}},required:["success","response"]}}};var SK={name:"Translate",tagline:"Translate text to a different language",icon:"GlobeGrid",description:"Translate text to a different language.",type:"ACTION",internal:!0,features:{},stepId:"TRANSLATE",inputs:{prompt:""},schema:{inputs:{properties:{text:{type:"string",title:"Text"},language:{type:"string",title:"Language"}},required:["text","language"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was the translated text"}},required:["success","response"]}}};var CT=(n=>(n.SHORT="Short",n.MEDIUM="Medium",n.LONG="Long",n))(CT||{}),OK={name:"Summarise",tagline:"Summarise text",icon:"Summarize",description:"Summarise text.",type:"ACTION",internal:!0,features:{},stepId:"SUMMARISE",inputs:{prompt:""},schema:{inputs:{properties:{text:{type:"longform",title:"Text"},length:{type:"string",title:"Length",enum:Object.values(CT)}},required:["text","length"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was the summarised text"}},required:["success","response"]}}};var wK={name:"Generate Text",icon:"Edit",tagline:"Generate contentusing AI",description:"Uses AI to generate text content based on your instructions and chosen format",stepId:"GENERATE_TEXT",internal:!0,inputs:{contentType:"document"},schema:{inputs:{properties:{contentType:{type:"string",title:"Content type",enum:Object.values(Cl),pretty:Object.values(Bh)},instructions:{type:"longform",title:"Instructions",description:"Provide guidance to help the AI produce content in the format that you want"}},required:["contentType","instructions"]},outputs:{properties:{generatedText:{type:"string",description:"The text content generated by the AI"},success:{type:"boolean",description:"Whether the text generation was successful"}},required:["generatedText","success"]}},type:"ACTION"};var CK={name:"Extract Document Data",icon:"Document",tagline:"Extract structured data from documents using AI",description:"Extracts structured data from PDF or image according to provided schema.",stepId:"EXTRACT_FILE_DATA",internal:!0,inputs:{},schema:{inputs:{properties:{file:{type:"string",title:"Document",description:"Attachment or Link to the document to extract data from."},source:{type:"string",enum:Object.values(vl),title:"Source",description:"The source of the document to extract data from."},fileType:{dependsOn:{field:"source",value:"URL"},type:"string",enum:Object.values(Nl),title:"File Type",description:"The type of file at the URL."},schema:{customType:"triggerSchema",title:"Data schema",description:'Schema defining the structure of data to extract. Example: {"name": "string", "price": "number"}.'}},required:["file","schema"]},outputs:{properties:{data:{type:"json",description:"The structured data extracted from the document."},success:{type:"boolean",description:"Whether the extraction was successful."}},required:["data","success"]}},type:"ACTION"};var Ev={name:"App Action",event:"app:trigger",icon:"Apps",tagline:"Automation fired from the frontend",description:"Trigger an automation from an action inside your app",stepId:"APP",inputs:{},schema:{inputs:{properties:{fields:{type:"object",customType:"triggerSchema",title:"Fields"}},required:[]},outputs:{properties:{fields:{type:"object",description:"Fields submitted from the app frontend",customType:"triggerSchema"}},required:["fields"]}},type:"TRIGGER"};var Av={name:"Cron Trigger",event:"cron:trigger",icon:"Clock",tagline:"Cron Trigger (<b>{{inputs.cron}}</b>)",description:"Triggers automation on a cron schedule.",stepId:"CRON",inputs:{},schema:{inputs:{properties:{cron:{type:"string",customType:"cron",title:"Expression"}},required:["cron"]},outputs:{properties:{timestamp:{type:"number",description:"Timestamp the cron was executed"}},required:["timestamp"]}},type:"TRIGGER"};var _v={name:"Row Deleted",event:"row:delete",icon:"TableRowRemoveCenter",tagline:"Row is deleted from {{inputs.enriched.table.name}}",description:"Fired when a row is deleted from your database",stepId:"ROW_DELETED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"}},required:["tableId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The row that was deleted"}},required:["row"]}},type:"TRIGGER"};var Ov={name:"Row Created",event:"row:save",icon:"TableRowAddBottom",tagline:"Row is added to {{inputs.enriched.table.name}}",description:"Fired when a row is added to your database",stepId:"ROW_SAVED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"trigger_filter",title:"Filtering"}},required:["tableId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The new row that was created"},id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"}},required:["row","id"]}},type:"TRIGGER"};var Rv={name:"Row Updated",event:"row:update",icon:"Refresh",tagline:"Row is updated in {{inputs.enriched.table.name}}",description:"Fired when a row is updated in your database",stepId:"ROW_UPDATED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"trigger_filter",title:"Filtering"}},required:["tableId"]},outputs:{properties:{oldRow:{type:"object",customType:"row",description:"The row that was updated",title:"Old Row"},row:{type:"object",customType:"row",description:"The row before it was updated",title:"Row"},id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"}},required:["row","id"]}},type:"TRIGGER"};var bv={name:"Webhook",event:"web:trigger",icon:"Send",tagline:"Webhook endpoint is hit",description:"Trigger an automation when a HTTP POST webhook is hit",stepId:"WEBHOOK",inputs:{},schema:{inputs:{properties:{schemaUrl:{type:"string",customType:"webhookUrl",title:"Schema URL"},triggerUrl:{type:"string",customType:"webhookUrl",title:"Trigger URL"}},required:["schemaUrl","triggerUrl"]},outputs:{properties:{body:{type:"object",description:"Body of the request which hit the webhook"}},required:["body"]}},type:"TRIGGER"};var Cv={type:"TRIGGER",name:"Row Action",event:"row:action",icon:"Workflow",tagline:"Row action triggered in {{inputs.enriched.table.name}} by {{inputs.enriched.row._id}}",description:"row action workflow",stepId:"ROW_ACTION",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table",readonly:!0}},required:["tableId"]},outputs:{properties:{id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"},table:{type:"object",customType:"table",title:"The table linked to the row action"},row:{type:"object",customType:"row",description:"The row linked to the row action"}}}}};var jK=Object.values(ye).sort((t,e)=>e.length-t.length);var HK=Object.values(Dl).sort((t,e)=>e.length-t.length);var KK=new RegExp("^datasource_plus_(.+)__(.+)$"),qu=t=>e=>!!e&&e.startsWith(`${t}${v}`);var YK=qu("ta"),JK=qu("view"),zK=qu("datasource"),ZK=qu("query");var Wu=(n=>(n.ALL="all",n.AUTOMATION="automation",n.STATUS="status",n))(Wu||{}),kr=(l=>(l.USER_BY_APP="by_app",l.USER_BY_EMAIL="by_email2",l.BY_API_KEY="by_api_key",l.LINK="by_link",l.ROUTING="screen_routes",l.AUTOMATION_LOGS="automation_logs",l.ACCOUNT_BY_EMAIL="account_by_email",l.PLATFORM_USERS_LOWERCASE="platform_users_lowercase_2",l.USER_BY_GROUP="user_by_group",l.APP_BACKUP_BY_TRIGGER="by_trigger",l))(kr||{}),Hi={by_email2:["by_email"]},Te={GLOBAL:{name:"global-db",docs:{apiKeys:"apikeys",usageQuota:"usage_quota",licenseInfo:"license_info",environmentVariables:"environmentvariables"}},PLATFORM_INFO:{name:"global-info",docs:{tenants:"tenants",install:"install"}},AUDIT_LOGS:{name:"audit-logs"},SCIM_LOGS:{name:"scim-logs"},SELF_HOST_CLOUD:{name:"self-host-cloud"}},gt=Or("app"),Qu=Or("app_dev"),yt=Qu,Op="internal",xp="budibase",Ht="_design/sqlite",Rp="ta_bb_jobs",wp="ta_bb_inventory",bp="ta_bb_expenses",Dp="ta_bb_employee",ju=(r=>(r[r.SQLITE=Ht]="SQLITE",r.MIGRATIONS="_design/migrations",r))(ju||{});var Hu=(r=>(r.ACTIVE="active",r.INACTIVE="inactive",r))(Hu||{}),Kn=(o=>(o.Auth="budibase:auth",o.Init="budibase:init",o.ACCOUNT_RETURN_URL="budibase:account:returnurl",o.DatasourceAuth="budibase:datasourceauth",o.OIDC_CONFIG="budibase:oidc:config",o.FeatureFlags="budibase:featureflags",o))(Kn||{}),Cp=(i=>(i.OWNER="owner",i.ADMIN="admin",i.BUILDER="builder",i.WORKSPACE_MANAGER="workspace_manager",i))(Cp||{}),vp=(u=>(u.SETTINGS="settings",u.ACCOUNT="account",u.SMTP="smtp",u.GOOGLE="google",u.OIDC="oidc",u.OIDC_LOGOS="logos_oidc",u.SCIM="scim",u.AI="AI",u))(vp||{}),vT=new Date(-2147483647e3),Ku=new Date(2147483647e3),Ae="default";var Oa={};N(Oa,{CacheKey:()=>Ce,TTL:()=>ni,app:()=>jo,bustCache:()=>ts,destroy:()=>Vo,docWritethrough:()=>km,generic:()=>qo,get:()=>ii,invite:()=>im,keys:()=>lc,passwordReset:()=>Mm,store:()=>ur,user:()=>rn,withCache:()=>Wr,withCacheWithDynamicTTL:()=>sA,writethrough:()=>Um});var qo={};N(qo,{CacheKey:()=>Ce,TTL:()=>ni,bustCache:()=>ts,destroy:()=>Vo,get:()=>ii,keys:()=>lc,store:()=>ur,withCache:()=>Wr,withCacheWithDynamicTTL:()=>sA});var Se={};N(Se,{DEFAULT_TENANT_ID:()=>Ae,baseGlobalDBName:()=>vo,doInAppContext:()=>TN,doInAppMigrationContext:()=>SN,doInAutomationContext:()=>mN,doInContext:()=>Zp,doInEnvironmentContext:()=>IN,doInFeatureFlagOverrideContext:()=>of,doInIPContext:()=>tf,doInIdentityContext:()=>Oo,doInLicenseContext:()=>gN,doInScimContext:()=>ON,doInSelfHostTenantUsingCloud:()=>hN,doInTenant:()=>qe,ensureSnippetContext:()=>tA,getAppDB:()=>Xi,getAppId:()=>Le,getAuditLogDBName:()=>ZT,getAuditLogsDB:()=>RN,getAutomationId:()=>Xp,getCurrentContext:()=>zn,getDevAppDB:()=>bN,getEnvironmentVariables:()=>xN,getFeatureFlagOverrides:()=>sf,getFeatureFlags:()=>rf,getGlobalDB:()=>ne,getGlobalDBName:()=>Jn,getIP:()=>ef,getIdentity:()=>ar,getLicense:()=>yN,getPlatformURL:()=>zp,getProdAppDB:()=>wN,getProdAppId:()=>_N,getScimDBName:()=>lN,getSelfHostCloudDB:()=>EN,getTableForView:()=>DN,getTenantIDFromAppID:()=>Zi,getTenantId:()=>j,identity:()=>Io,isMultiTenant:()=>$r,isScim:()=>Pt,isSelfHostUsingCloud:()=>XT,isTenancyEnabled:()=>pN,isTenantIdSet:()=>dN,setFeatureFlags:()=>nf,setTableForView:()=>CN});var Io={};N(Io,{doInAccountContext:()=>Lv,doInIdentityContext:()=>Lp,doInUserContext:()=>Up,getAccountUserId:()=>NT,getIdentity:()=>Pp});function Pp(){return ar()}function Lp(t,e){return Oo(t,e)}function Up(t,e,r){let n={...t,_id:t._id,type:"user",hostInfo:{ipAddress:e.request.ip,userAgent:e.userAgent.source}};return Lp(n,r)}function Lv(t,e){let r=NT(t),n=t.tenantId,i={_id:r,type:"user",tenantId:n,account:t};return Lp(i,e)}function NT(t){let e;return Va(t)?e=t.budibaseUserId:e=t.accountId,e}var zu=require("fs");var UT=require("lodash"),Mp=require("crypto"),xo=require("path"),Uv=process.env.TOP_LEVEL_PATH||process.env.SERVER_TOP_LEVEL_PATH||(0,xo.resolve)((0,xo.join)(__dirname,"..","..","..")),PT=!1;!PT&&Ju()&&!Fp()&&(require("dotenv").config({path:(0,xo.join)(Uv,".env")}),PT=!0);function Fp(){return MT()}function MT(){return process.env.NODE_ENV==="jest"||process.env.JEST_WORKER_ID!=null&&process.env.JEST_WORKER_ID!=="null"}function Ju(){return process.env.NODE_ENV!=="production"}function Mv(t){if(t)return parseInt(t)}var Ki={BACKUPS:"backups",APPS:"prod-budi-app-assets",TEMPLATES:"templates",GLOBAL:"global",PLUGINS:"plugins",TEMP:"tmp-file-attachments"},LT=!!parseInt(process.env.SELF_HOSTED||"");function Fv(){return process.env.API_ENCRYPTION_KEY?process.env.API_ENCRYPTION_KEY:process.env.JWT_SECRET}function kv(){return process.env.HTTP_LOGGING===void 0?!0:process.env.HTTP_LOGGING}function Bv(){function t(r){function n(a,u){let c=`${u}/${a}`;if((0,zu.existsSync)(c))return c;let l=`${u}/..`;return l===u?null:n(a,l)}let i=n(r,process.cwd()),s=(0,zu.readFileSync)(i,"utf-8");return JSON.parse(s)}let e;if(Ju()&&!Fp())try{e=`${t("lerna.json").version}+local`}catch{}try{let r=t("package.json");return{VERSION:e||process.env.BUDIBASE_VERSION||r.version,SERVICE_NAME:r.name}}catch{return{VERSION:process.env.BUDIBASE_VERSION||"",SERVICE_NAME:""}}}function Gv(){return Ct.SERVICE_TYPE==="worker"}function $v(){return Ct.SERVICE_TYPE==="apps"}function Vv(){return Ct.BUDIBASE_ENVIRONMENT==="QA"}function qv(){return process.env.SERVICE?process.env.SERVICE:process.env.APPS_SERVICE?process.env.APPS_SERVICE:process.env.WORKER_SERVICE?process.env.WORKER_SERVICE:"budibase"}var Ct={isTest:Fp,isJest:MT,isDev:Ju,isWorker:Gv,isApps:$v,isQA:Vv,isProd:()=>!Ju(),BUDIBASE_ENVIRONMENT:process.env.BUDIBASE_ENVIRONMENT,JS_BCRYPT:process.env.JS_BCRYPT,JWT_SECRET:process.env.JWT_SECRET?(0,Mp.createSecretKey)(process.env.JWT_SECRET,"utf8"):void 0,JWT_SECRET_FALLBACK:process.env.JWT_SECRET_FALLBACK?(0,Mp.createSecretKey)(process.env.JWT_SECRET_FALLBACK,"utf8"):void 0,ENCRYPTION_KEY:process.env.ENCRYPTION_KEY,API_ENCRYPTION_KEY:Fv(),COUCH_DB_URL:process.env.COUCH_DB_URL||"http://localhost:4005",COUCH_DB_SQL_URL:process.env.COUCH_DB_SQL_URL,COUCH_DB_USERNAME:process.env.COUCH_DB_USER,COUCH_DB_PASSWORD:process.env.COUCH_DB_PASSWORD,GOOGLE_CLIENT_ID:process.env.GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET:process.env.GOOGLE_CLIENT_SECRET,SALT_ROUNDS:process.env.SALT_ROUNDS,REDIS_URL:process.env.REDIS_URL||"localhost:6379",REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_CLUSTERED:process.env.REDIS_CLUSTERED,MINIO_ACCESS_KEY:process.env.MINIO_ACCESS_KEY,MINIO_SECRET_KEY:process.env.MINIO_SECRET_KEY,AWS_SESSION_TOKEN:process.env.AWS_SESSION_TOKEN,AWS_REGION:process.env.AWS_REGION||"eu-west-1",MINIO_URL:process.env.MINIO_URL,MINIO_ENABLED:process.env.MINIO_ENABLED||1,INTERNAL_API_KEY:process.env.INTERNAL_API_KEY,INTERNAL_API_KEY_FALLBACK:process.env.INTERNAL_API_KEY_FALLBACK,MULTI_TENANCY:process.env.MULTI_TENANCY,ACCOUNT_PORTAL_URL:process.env.ACCOUNT_PORTAL_URL||"https://account.budibase.app",INTERNAL_ACCOUNT_PORTAL_URL:process.env.INTERNAL_ACCOUNT_PORTAL_URL||process.env.ACCOUNT_PORTAL_URL||"https://account.budibase.app",ACCOUNT_PORTAL_API_KEY:process.env.ACCOUNT_PORTAL_API_KEY||"",BUDICLOUD_URL:process.env.BUDICLOUD_URL||"https://budibase.app",DISABLE_ACCOUNT_PORTAL:process.env.DISABLE_ACCOUNT_PORTAL,SELF_HOSTED:LT,COOKIE_DOMAIN:process.env.COOKIE_DOMAIN,PLATFORM_URL:process.env.PLATFORM_URL||"",POSTHOG_TOKEN:process.env.POSTHOG_TOKEN,POSTHOG_PERSONAL_TOKEN:process.env.POSTHOG_PERSONAL_TOKEN,POSTHOG_API_HOST:process.env.POSTHOG_API_HOST||"https://us.i.posthog.com",POSTHOG_FEATURE_FLAGS_ENABLED:process.env.POSTHOG_FEATURE_FLAGS_ENABLED,ENABLE_ANALYTICS:process.env.ENABLE_ANALYTICS,TENANT_FEATURE_FLAGS:process.env.TENANT_FEATURE_FLAGS,CLOUDFRONT_CDN:process.env.CLOUDFRONT_CDN,CLOUDFRONT_PRIVATE_KEY_64:process.env.CLOUDFRONT_PRIVATE_KEY_64,CLOUDFRONT_PUBLIC_KEY_ID:process.env.CLOUDFRONT_PUBLIC_KEY_ID,BACKUPS_BUCKET_NAME:process.env.BACKUPS_BUCKET_NAME||Ki.BACKUPS,APPS_BUCKET_NAME:process.env.APPS_BUCKET_NAME||Ki.APPS,TEMPLATES_BUCKET_NAME:process.env.TEMPLATES_BUCKET_NAME||Ki.TEMPLATES,GLOBAL_BUCKET_NAME:process.env.GLOBAL_BUCKET_NAME||Ki.GLOBAL,PLUGIN_BUCKET_NAME:process.env.PLUGIN_BUCKET_NAME||Ki.PLUGINS,TEMP_BUCKET_NAME:process.env.TEMP_BUCKET_NAME||Ki.TEMP,USE_COUCH:process.env.USE_COUCH||!0,MOCK_REDIS:process.env.MOCK_REDIS,DEFAULT_LICENSE:process.env.DEFAULT_LICENSE,SERVICE:qv(),LOG_LEVEL:process.env.LOG_LEVEL||"info",SESSION_UPDATE_PERIOD:process.env.SESSION_UPDATE_PERIOD,DEPLOYMENT_ENVIRONMENT:process.env.DEPLOYMENT_ENVIRONMENT||"docker-compose",HTTP_LOGGING:kv(),ENABLE_AUDIT_LOG_IP_ADDR:process.env.ENABLE_AUDIT_LOG_IP_ADDR,SQL_LOGGING_ENABLE:process.env.SQL_LOGGING_ENABLE,SQL_MAX_ROWS:process.env.SQL_MAX_ROWS,SQL_MAX_RELATED_ROWS:process.env.MAX_RELATED_ROWS,SMTP_FALLBACK_ENABLED:process.env.SMTP_FALLBACK_ENABLED,SMTP_USER:process.env.SMTP_USER,SMTP_PASSWORD:process.env.SMTP_PASSWORD,SMTP_HOST:process.env.SMTP_HOST,SMTP_PORT:parseInt(process.env.SMTP_PORT||""),SMTP_FROM_ADDRESS:process.env.SMTP_FROM_ADDRESS,DISABLE_JWT_WARNING:process.env.DISABLE_JWT_WARNING,BLACKLIST_IPS:process.env.BLACKLIST_IPS,SERVICE_TYPE:"unknown",PASSWORD_MIN_LENGTH:process.env.PASSWORD_MIN_LENGTH,PASSWORD_MAX_LENGTH:process.env.PASSWORD_MAX_LENGTH,ENABLE_SSO_MAINTENANCE_MODE:LT?process.env.ENABLE_SSO_MAINTENANCE_MODE:!1,...Bv(),DISABLE_PINO_LOGGER:process.env.DISABLE_PINO_LOGGER,OFFLINE_MODE:process.env.OFFLINE_MODE,SESSION_EXPIRY_SECONDS:process.env.SESSION_EXPIRY_SECONDS,_set(t,e){process.env[t]=e,Ct[t]=e},ROLLING_LOG_MAX_SIZE:process.env.ROLLING_LOG_MAX_SIZE||"10M",DISABLE_SCIM_CALLS:process.env.DISABLE_SCIM_CALLS,BB_ADMIN_USER_EMAIL:process.env.BB_ADMIN_USER_EMAIL,BB_ADMIN_USER_PASSWORD:process.env.BB_ADMIN_USER_PASSWORD,OPENAI_API_KEY:process.env.OPENAI_API_KEY,MIN_VERSION_WITHOUT_POWER_ROLE:process.env.MIN_VERSION_WITHOUT_POWER_ROLE||"3.0.0",DISABLE_CONTENT_SECURITY_POLICY:process.env.DISABLE_CONTENT_SECURITY_POLICY,BSON_BUFFER_SIZE:Mv(process.env.BSON_BUFFER_SIZE)};function Ro(t){let e=(0,UT.cloneDeep)(Ct),r;for(r in t)Ct._set(r,t[r]);return()=>{for(let[n,i]of Object.entries(e))Ct._set(n,i)}}function FT(t,e){let r=Ro(t),n=e();return n instanceof Promise?n.finally(r):(r(),n)}var kT=["API_ENCRYPTION_KEY","BB_ADMIN_USER_PASSWORD","COUCH_DB_PASSWORD","COUCH_DB_SQL_URL","COUCH_DB_URL","GOOGLE_CLIENT_SECRET","INTERNAL_API_KEY_FALLBACK","INTERNAL_API_KEY","JWT_SECRET","MINIO_ACCESS_KEY","MINIO_SECRET_KEY","OPENAI_API_KEY","REDIS_PASSWORD"];for(let[t,e]of Object.entries(Ct))e==="0"&&(Ct[t]=0),e==="false"&&(Ct[t]=0);var h=Ct;var BT=require("async_hooks"),we=class t{static{this.storage=new BT.AsyncLocalStorage}static run(e,r){return t.storage.run(e,()=>r())}static get(){return t.storage.getStore()}};var kp="No app provided";function Br(t){if(!t)throw kp;return t.startsWith(yt)}function Wv(t){if(!t)throw kp;return t.startsWith(gt)&&!Br(t)}function wo(t){if(!t)throw kp;return Br(t.appId)}function Zu(t){if(!t||t.startsWith(yt))return t;let e=t.split(gt);e.shift();let r=e.join(gt);return`${yt}${r}`}var Qv=Zu;function at(t){if(!t||!t.startsWith(yt))return t;let e=t.split(yt);e.shift();let r=e.join(yt);return`${gt}${r}`}function jv(t){let e=t?.split("_")||[];return e.length?e[e.length-1]:null}var vt=t=>{let e=Bp(t),r,n;if(e.auth?.username)r=e.auth.username;else if(h.COUCH_DB_USERNAME)r=h.COUCH_DB_USERNAME;else if(!h.isTest())throw new Error("CouchDB username not set");if(e.auth?.password)n=e.auth.password;else if(h.COUCH_DB_PASSWORD)n=h.COUCH_DB_PASSWORD;else if(!h.isTest())throw new Error("CouchDB password not set");let i=Buffer.from(`${r}:${n}`).toString("base64"),s=h.COUCH_DB_SQL_URL;if(h.isDev()&&!s)s="http://localhost:4006";else if(!s&&e.url){let o=new URL(e.url);s=e.url.replace(o.port,"4984")}return{url:e.url,sqlUrl:Bp(s).url,auth:{username:r,password:n},cookie:`Basic ${i}`}},Bp=(t=h.COUCH_DB_URL)=>{let e,r,n,i;if(t){/^https?:\/\//i.test(t)||(t=`http://${t}`);let o=t.split("://"),a=o[0],u=o.slice(1).join("://");if(t.includes("@")){let c=u.split("@");i=c[c.length-1];let l=c.slice(0,-1).join("@");if(l.includes(":")){let m=l.split(":");r=m[0],n=m.slice(1).join(":")}else r=l}else i=u;e=`${a}://${i}`}return{url:e,auth:{username:r,password:n}}};var JT=W(require("@budibase/nano"));var GT=W(require("node-fetch"));function Xu(t){return t.replace(/(https?:\/\/)|(\/)+/g,"$1$2")}async function $T(t,e="GET",r){let{url:n,cookie:i}=vt(),s=`${n}/${t}`;return await bo({url:s,cookie:i,method:e,body:r})}async function bo({url:t,cookie:e,method:r,body:n}){let i={method:r,headers:{Authorization:e}};return n&&r!=="GET"&&(typeof n=="string"?(i.body=n,i.headers["Content-Type"]="text/plain"):(i.body=JSON.stringify(n),i.headers["Content-Type"]="application/json")),await(0,GT.default)(Xu(encodeURI(t)),i)}async function Gp(t,e="GET",r){let n=await $T(t,e,r);if(n.status<300)return await n.json();throw"Cannot connect to CouchDB instance"}var Yn=W(require("pouchdb"));var VT,qT=!1,$p=(t={})=>{let{url:e,cookie:r}=vt(),n={prefix:e,fetch:(i,s)=>(s.headers.set("Authorization",r),Yn.default.fetch(i,s))};if(t.inMemory){let i=require("pouchdb-adapter-memory");Yn.default.plugin(i),n={adapter:"memory"}}if(t.onDisk&&(n={adapter:"leveldb"}),t.replication){let i=require("@budibase/pouchdb-replication-stream");Yn.default.plugin(i.plugin),Yn.default.adapter("writableStream",i.adapters.writableStream)}if(t.find){let i=require("pouchdb-find");Yn.default.plugin(i)}return Yn.default.defaults(n)};function ec(t){VT=$p(t),qT=!0}var Kv=()=>{if(!qT)throw new Error("init has not been called")};function Et(t,e){Kv();let r=new VT(t,e),n=r.put;return r.put=async(i,s={})=>(i.createdAt||(i.createdAt=new Date().toISOString()),i.updatedAt=new Date().toISOString(),n(i,s)),r.exists=async()=>!(await r.info()).error,r}async function Do(t){if(!(!t||h.isTest()))try{return await t.close()}catch{}}var WT=require("uuid");function me(){return(0,WT.v4)().replace(/-/g,"")}var Oe=W(require("dd-trace")),Yi=class{constructor(e){this.db=e}get name(){return this.db.name}exists(e){return Oe.default.trace("db.exists",r=>(r.addTags({db_name:this.name,doc_id:e}),e?this.db.exists(e):this.db.exists()))}get(e){return Oe.default.trace("db.get",r=>(r.addTags({db_name:this.name,doc_id:e}),this.db.get(e)))}tryGet(e){return Oe.default.trace("db.tryGet",async r=>{r.addTags({db_name:this.name,doc_id:e});let n=await this.db.tryGet(e);return r.addTags({doc_found:n!==void 0}),n})}getMultiple(e,r){return Oe.default.trace("db.getMultiple",async n=>{n.addTags({db_name:this.name,num_docs:e?.length||0,allow_missing:r?.allowMissing});let i=await this.db.getMultiple(e,r);return n.addTags({num_docs_found:i.length}),i})}remove(e,r){return Oe.default.trace("db.remove",async n=>{n.addTags({db_name:this.name,doc_id:e,rev:r});let i=typeof e=="object",s=i?e._id:e;r=i?e._rev:r;let o=await this.db.remove(s,r);return n.addTags({ok:o.ok}),o})}bulkRemove(e,r){return Oe.default.trace("db.bulkRemove",n=>(n.addTags({db_name:this.name,num_docs:e.length,silence_errors:r?.silenceErrors}),this.db.bulkRemove(e,r)))}put(e,r){return Oe.default.trace("db.put",async n=>{n.addTags({db_name:this.name,doc_id:e._id,force:r?.force});let i=await this.db.put(e,r);return n.addTags({ok:i.ok}),i})}bulkDocs(e){return Oe.default.trace("db.bulkDocs",r=>(r.addTags({db_name:this.name,num_docs:e.length}),this.db.bulkDocs(e)))}async find(e){return Oe.default.trace("db.find",async r=>{r.addTags({db_name:this.name,...e});let n=await this.db.find(e);return r.addTags({rows_length:n.docs.length}),n})}allDocs(e){return Oe.default.trace("db.allDocs",async r=>{r.addTags({db_name:this.name,...e});let n=await this.db.allDocs(e);return r.addTags({total_rows:n.total_rows,rows_length:n.rows.length,offset:n.offset}),n})}query(e,r){return Oe.default.trace("db.query",async n=>{n.addTags({db_name:this.name,view_name:e,...r});let i=await this.db.query(e,r);return n.addTags({total_rows:i.total_rows,rows_length:i.rows.length,offset:i.offset}),i})}destroy(){return Oe.default.trace("db.destroy",async e=>{e.addTags({db_name:this.name});let r=await this.db.destroy();return e.addTags({ok:r.ok}),r})}compact(){return Oe.default.trace("db.compact",async e=>{e.addTags({db_name:this.name});let r=await this.db.compact();return e.addTags({ok:r.ok}),r})}dump(e,r){return Oe.default.trace("db.dump",n=>(n.addTags({db_name:this.name,batch_limit:r?.batch_limit,batch_size:r?.batch_size,style:r?.style,timeout:r?.timeout,num_doc_ids:r?.doc_ids?.length,view:r?.view}),this.db.dump(e,r)))}load(...e){return Oe.default.trace("db.load",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.load(...e)))}createIndex(...e){return Oe.default.trace("db.createIndex",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.createIndex(...e)))}deleteIndex(...e){return Oe.default.trace("db.deleteIndex",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.deleteIndex(...e)))}getIndexes(...e){return Oe.default.trace("db.getIndexes",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.getIndexes(...e)))}sql(e,r){return Oe.default.trace("db.sql",async n=>{n.addTags({db_name:this.name,num_bindings:r?.length});let i=await this.db.sql(e,r);return n.addTags({num_rows:i.length}),i})}sqlPurgeDocument(e){return Oe.default.trace("db.sqlPurgeDocument",r=>(r.addTags({db_name:this.name,num_docs:Array.isArray(e)?e.length:1}),this.db.sqlPurgeDocument(e)))}sqlDiskCleanup(){return Oe.default.trace("db.sqlDiskCleanup",e=>(e.addTags({db_name:this.name}),this.db.sqlDiskCleanup()))}};var Yp={};N(Yp,{breakExternalTableId:()=>Wp,breakRowIdField:()=>aN,buildExternalTableId:()=>tN,convertRowId:()=>oN,encodeTableId:()=>rN,encodeViewId:()=>nN,extractDate:()=>jp,generateRowIdField:()=>iN,getNativeSql:()=>Ji,isExternalTable:()=>qp,isExternalTableID:()=>tc,isInternalTableID:()=>eN,isRowId:()=>sN,isValidFilter:()=>nc,isValidISODateString:()=>rc,isValidISODateStringWithoutTimezone:()=>Qp,isValidTime:()=>Hp,sqlLog:()=>Co,validateManyToMany:()=>Kp});var Vp=`${v}${v}`,jT=/^\[.*]$/g,Yv=encodeURIComponent(" "),Jv=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:.\d{3})?Z)?$/,zv=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:.\d{3})?)?$/,Zv=/(\d{4}-\d{2}-\d{2})/,Xv=/^(?:\d{2}:)?(?:\d{2}:)(?:\d{2})$/;function tc(t){return t.startsWith("datasource"+v)}function eN(t){return!tc(t)}function Ji(t){let e=t.toSQL();if(Array.isArray(e))return e;let r;return e.toNative&&(r=e.toNative()),{sql:r?.sql||e.sql,bindings:r?.bindings||e.bindings}}function qp(t){return t?.sourceId&&t.sourceId.includes("datasource"+v)&&t?.sourceId!==Di||t?.sourceType==="external"?!0:!!(t?._id&&tc(t._id))}function tN(t,e){return`${t}${Vp}${encodeURIComponent(e)}`}function rN(t){return tc(t)?encodeURIComponent(t):t}function nN(t){return encodeURIComponent(t)}function Wp(t){let e=t.split(Vp),r=e.shift(),n=e.join(Vp);if(n.includes(Yv)&&(n=decodeURIComponent(n)),!r||!n)throw new Error("Unable to get datasource/table name from table ID");return{datasourceId:r,tableName:n}}function iN(t=[]){Array.isArray(t)||(t=[t]);for(let e in t)t[e]instanceof Buffer&&(t[e]=t[e].toString());return encodeURIComponent(JSON.stringify(t).replace(/"/g,"'"))}function sN(t){return Array.isArray(t)||typeof t=="string"&&t.match(jT)!=null}function oN(t){return Array.isArray(t)?t[0]:typeof t=="string"&&t.match(jT)!=null?t.substring(1,t.length-1):t}function aN(t){if(!t)return[];let e=typeof t=="string"?t:t._id,r=decodeURIComponent(e).replace(/'/g,'"');try{let n=JSON.parse(r);return Array.isArray(n)?n:[n]}catch{return[t]}}function rc(t){let e=t.trim();if(!Jv.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}function Qp(t){let e=t.trim();if(!zv.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}function jp(t){let e=t.match(Zv);if(e)return e[0]}function nc(t){return t!=null&&t!==""}function Hp(t){return Xv.test(t)}function Co(t,e,r){if(!h.SQL_LOGGING_ENABLE)return;let n=`[SQL] [${t.toUpperCase()}] query="${e}"`;r&&(n+=` values="${r.join(", ")}"`),console.log(n)}function uN(t){return!!t.through&&!!t.fromPrimary&&!!t.from&&!!t.toPrimary&&!!t.to}function Kp(t){if(uN(t))return t}var HT="Database does not exist.";function KT(t){return(0,JT.default)({url:t.url,requestDefaults:{headers:{Authorization:t.cookie}},parseUrl:!1})}var Gr=class extends Error{constructor(r,n){super(r);let i=n.status||n.statusCode||500;this.status=i,this.statusCode=i,this.reason=n.reason||"Unknown",this.name=n.name,this.errid=n.errid||"Unknown",this.description=n.description||"Unknown",this.error=n.error||"Not found"}};function cN(t,e,r){if(!t||!e)throw new Error("Unable to create database without database name or connection");let n=new zi(t,r,e);return new Yi(n)}var zi=class t{constructor(e,r,n){this.couchInfo=vt();this.name=e,this.pouchOpts=r||{},n&&(this.couchInfo=vt(n),this.instanceNano=KT(this.couchInfo)),t.nano||t.init()}static init(){let e=vt();t.nano=KT(e)}exists(e){return e===void 0?this.dbExists():this.docExists(e)}async dbExists(){return(await bo({url:`${this.couchInfo.url}/${this.name}`,method:"HEAD",cookie:this.couchInfo.cookie})).status===200}async docExists(e){try{return await this.performCall(r=>()=>r.head(e)),!0}catch{return!1}}nano(){return this.instanceNano||t.nano}getDb(){return this.nano().db.use(this.name)}async checkAndCreateDb(){let e=!this.pouchOpts?.skip_setup,r=await this.exists();if(!e&&!r)throw new Error("DB does not exist");if(!r)try{await this.nano().db.create(this.name)}catch(n){if(n.statusCode!==412)throw new Gr(n.message,n)}return this.getDb()}async performCallWithDBCreation(e){let r=this.getDb(),n=await e(r);try{return await n()}catch(i){if(i.statusCode===404&&i.reason===HT)return await this.checkAndCreateDb(),await this.performCallWithDBCreation(e);throw new Gr(`CouchDB error: ${i.message}`,i)}}async performCall(e){let r=this.getDb(),n=await e(r);try{return await n()}catch(i){throw new Gr(`CouchDB error: ${i.message}`,i)}}async get(e){return this.performCall(r=>{if(!e)throw new Error("Unable to get doc without a valid _id.");return()=>r.get(e)})}async tryGet(e){try{return await this.get(e)}catch(r){if(r.statusCode===404)return;throw r}}async getMultiple(e,r){if(!e||e.length===0)return[];e=[...new Set(e)];let n=!r?.excludeDocs,i=await this.allDocs({keys:e,include_docs:n}),s=u=>n&&u.doc==null||u.value&&"deleted"in u.value&&u.value.deleted?!0:u.error==="not_found",o=i.rows.filter(u=>!s(u)),a=o.length!==i.rows.length;if(!r?.allowMissing&&a){let c=i.rows.filter(l=>s(l)).map(l=>l.key).join(", ");throw new Error(`Unable to get bulk documents: ${c}`)}return o.map(u=>n?u.doc:u.value)}async remove(e,r){return this.performCall(n=>{let i,s;if(Mh(e)?(i=e._id,s=e._rev):(i=e,s=r),!i||!s)throw new Error("Unable to remove doc without a valid _id and _rev.");return()=>n.destroy(i,s)})}async bulkRemove(e,r){let n=await this.performCall(o=>()=>o.bulk({docs:e.map(a=>({...a,_deleted:!0}))}));if(r?.silenceErrors)return;let i=!1,s="Unable to bulk remove documents: ";for(let o of n)o.error&&(i=!0,s+=o.error);if(i)throw new Gr(s,{name:this.name,status:400})}async post(e,r){return e._id||(e._id=me()),this.put(e,r)}async put(e,r){if(!e._id)throw new Error("Cannot store document without _id field.");return this.performCallWithDBCreation(async n=>{if(e.createdAt||(e.createdAt=new Date().toISOString()),e.updatedAt=new Date().toISOString(),r?.force&&e._id)try{let i=await this.get(e._id);i&&(e._rev=i._rev)}catch(i){if(i.status!==404)throw i}return()=>n.insert(e)})}async bulkDocs(e){let r=new Date().toISOString();return this.performCallWithDBCreation(n=>()=>n.bulk({docs:e.map(i=>({createdAt:r,...i,updatedAt:r}))}))}async find(e){return this.performCall(r=>async()=>r.find(e))}async allDocs(e){return this.performCall(r=>async()=>{try{return await r.list(e)}catch(n){if(n.reason===HT)return{offset:0,total_rows:0,rows:[]};throw n}})}async _sqlQuery(e,r,n){e=Xu(`${this.couchInfo.sqlUrl}/${e}`);let i={url:e,method:r,cookie:this.couchInfo.cookie};return n&&(i.body=n),this.performCall(()=>async()=>{let s=await bo(i),o=await s.text();if(s.status>300){let a;try{a=JSON.parse(o)}catch{throw console.error(`SQS error: ${o}`),new Gr("error while running SQS query, please try again later",{name:"sqs_error",status:s.status})}throw a}return JSON.parse(o)})}async sql(e,r){let i=`/${this.name}/${Ht}`;return Co("sqlite3",e,r),await this._sqlQuery(i,"POST",{query:e,args:r})}async sqlDiskCleanup(){let r=`/${this.name}/_cleanup`;try{await this._sqlQuery(r,"POST")}catch(n){if(n.status!==500)throw n}}async sqlPurgeDocument(e){Array.isArray(e)||(e=[e]);let n=`/${this.name}/_purge`;return await this._sqlQuery(n,"POST",{docs:e})}async query(e,r){return this.performCall(n=>{let[i,s]=e.split("/");return()=>n.view(i,s,r)})}async destroy(){if(await this.exists(Ht)){let e=await this.get(Ht);e.sql.tables={},await this.put(e),await this.sqlDiskCleanup()}try{return await this.nano().db.destroy(this.name)}catch(e){if(e.statusCode===404)return{ok:!0};throw new Gr(e.message,e)}}async compact(){return this.performCall(e=>()=>e.compact())}async dump(e,r){return Et(this.name).dump(e,r)}async load(e){return Et(this.name).load(e)}async createIndex(e){return Et(this.name).createIndex(e)}async deleteIndex(e){return Et(this.name).deleteIndex(e)}async getIndexes(){return Et(this.name).getIndexes()}};function Ve(t,e){return new Yi(new zi(t,e))}async function ut(t,e,r){let n=Ve(t,r);return await e(n)}async function Jp(t){let e="/_all_dbs";return t&&(e+=`?${t}`),await Gp(e)}var zT=null;function Jn(t){return t||(t=j()),vo(t)}function ZT(t){return t||(t=j()),t===Ae?Te.AUDIT_LOGS.name:`${t}${v}${Te.AUDIT_LOGS.name}`}function lN(t){return t||(t=j()),t===Ae?Te.SCIM_LOGS.name:`${t}${v}${Te.SCIM_LOGS.name}`}function vo(t){return!t||t===Ae?Te.GLOBAL.name:`${t}${v}${Te.GLOBAL.name}`}function zp(){return h.PLATFORM_URL}function $r(){return!!h.MULTI_TENANCY}function dN(){return!!we.get()?.tenantId}function pN(){return h.MULTI_TENANCY}function Zi(t){if(!t)return;if(!$r())return Ae;let e=t.split(v),r=e[1]==="dev";if(!(r&&e.length===3||!r&&e.length===2))return r?e[2]:e[1]}function fN(t){let e;try{e=we.get()}catch{e={}}return e={...e,...t},e}async function Nt(t,e){AN();let r=fN(t);return we.run(r,e)}async function mN(t){return await tA(),await Nt({tenantId:Zi(t.appId),appId:t.appId,automationId:t.automationId},t.task)}async function Zp(t,e){let r=Zi(t);return Nt({tenantId:r,appId:t},e)}async function qe(t,e){return h.MULTI_TENANCY||(t=t||Ae),Nt(t?{tenantId:t}:{},e)}async function hN(t,e){return Nt({tenantId:t,isSelfHostUsingCloud:!0},e)}async function gN(t,e){return Nt({license:t},e)}function yN(){return we.get()?.license}function XT(){return!!we.get()?.isSelfHostUsingCloud}function EN(){let t=we.get();if(!t||!t.isSelfHostUsingCloud)throw new Error("Self-host cloud DB not found");return Ve(Te.SELF_HOST_CLOUD.name)}async function TN(t,e){return eA(t,e)}async function eA(t,e,r){if(!t)throw new Error("appId is required");let n=Zi(t),i={appId:t,...r};return n&&(i.tenantId=n),Nt(i,e)}async function Oo(t,e){if(!t)throw new Error("identity is required");let r={identity:t};return t.tenantId&&(r.tenantId=t.tenantId),Nt(r,e)}function AN(){if(we.get()?.isMigrating)throw new Error("The context cannot be changed, a migration is currently running")}async function SN(t,e){return eA(t,e,{isMigrating:!0})}function ar(){try{return we.get()?.identity}catch{}}function j(){if(!$r())return Ae;let e=we.get()?.tenantId;if(!e)throw new Error("Tenant id not found");return e}function Xp(){return we.get()?.automationId}function Le(){let e=we.get()?.appId;return!e&&h.isTest()&&zT?zT:e}function ef(){return we.get()?.ip}var _N=()=>{let t=Le();if(!t)throw new Error("Could not get appId");return at(t)};function IN(t,e){if(!t)throw new Error("Must supply environment variables.");return Nt({environmentVariables:t},e)}function ON(t){return Nt({isScim:!0},t)}function tf(t,e){return Nt({ip:t},e)}async function tA(){let t=zn();if(!t||t.snippets)return;let e,r=Xi();r&&(e=(await r.tryGet("app_metadata"))?.snippets),t.snippets=e||[]}function xN(){let t=we.get();return t.environmentVariables?t.environmentVariables:null}function ne(){let t=we.get();if(!t||h.MULTI_TENANCY&&!t.tenantId)throw new Error("Global DB not found");if(t.isSelfHostUsingCloud)throw new Error("Global DB not found - self-host users using cloud don't have a global DB");return Ve(vo(t?.tenantId))}function RN(){if(!j())throw new Error("No tenant ID found - cannot open audit log DB");return Ve(ZT())}function Xi(t){let e=Le();if(!e)throw new Error("Unable to retrieve app DB - no app ID.");if(XT())throw new Error("App DB not found - self-host users using cloud don't have app DBs");return Ve(e,t)}function wN(t){let e=Le();if(!e)throw new Error("Unable to retrieve prod DB - no app ID.");return Ve(at(e),t)}function bN(t){let e=Le();if(!e)throw new Error("Unable to retrieve dev DB - no app ID.");return Ve(Zu(e),t)}function Pt(){return!!we.get()?.isScim}function zn(){try{return we.get()}catch{return}}function rf(t){let e=zn();if(e)return e.featureFlagCache?.[t]}function nf(t,e){let r=zn();r&&(r.featureFlagCache??={},r.featureFlagCache[t]=e)}function sf(){return zn()?.featureFlagOverrides||{}}async function of(t,e){return await Nt({featureFlagOverrides:t},e)}function DN(t){let e=zn();if(e)return e.viewToTableCache?.[t]}function CN(t,e){let r=zn();r&&(r.viewToTableCache??={},r.viewToTableCache[t]=e)}var qr={};N(qr,{getAppClient:()=>cc,getCacheClient:()=>pf,getDocWritethroughClient:()=>UN,getInviteClient:()=>ei,getLockClient:()=>mf,getPasswordResetClient:()=>$o,getSessionClient:()=>Vr,getSocketClient:()=>LN,getUserClient:()=>Go,getWritethroughClient:()=>ff,init:()=>Lt,shutdown:()=>iA});var uc=W(require("ioredis"));var oc={};N(oc,{Databases:()=>af,SEPARATOR:()=>es,SelectableDatabase:()=>ic,getRedisClusterOptions:()=>uf,getRedisConnectionDetails:()=>sc,getRedisOptions:()=>Zn,removeDbPrefix:()=>cf});var es="-",af=(y=>(y.PW_RESETS="pwReset",y.VERIFICATIONS="verification",y.INVITATIONS="invitation",y.DEV_LOCKS="devLocks",y.DEBOUNCE="debounce",y.SESSIONS="session",y.USER_CACHE="users",y.FLAGS="flags",y.APP_METADATA="appMetadata",y.QUERY_VARS="queryVars",y.LICENSES="license",y.GENERIC_CACHE="data_cache",y.WRITE_THROUGH="writeThrough",y.LOCKS="locks",y.SOCKET_IO="socket_io",y.BPM_EVENTS="bpmEvents",y.DOC_WRITE_THROUGH="docWriteThrough",y))(af||{}),ic=(E=>(E[E.DEFAULT=0]="DEFAULT",E[E.SOCKET_IO=1]="SOCKET_IO",E[E.RATE_LIMITING=2]="RATE_LIMITING",E[E.UNUSED_2=3]="UNUSED_2",E[E.UNUSED_3=4]="UNUSED_3",E[E.UNUSED_4=5]="UNUSED_4",E[E.UNUSED_5=6]="UNUSED_5",E[E.UNUSED_6=7]="UNUSED_6",E[E.UNUSED_7=8]="UNUSED_7",E[E.UNUSED_8=9]="UNUSED_8",E[E.UNUSED_9=10]="UNUSED_9",E[E.UNUSED_10=11]="UNUSED_10",E[E.UNUSED_11=12]="UNUSED_11",E[E.UNUSED_12=13]="UNUSED_12",E[E.UNUSED_13=14]="UNUSED_13",E[E.UNUSED_14=15]="UNUSED_14",E))(ic||{});function sc(){let t=h.REDIS_PASSWORD,e=h.REDIS_URL.split("//");e=e.length>1?e[1]:e[0],e=e.split("@"),e.length>1?(t=e[0].split(":")[1],e=e[1]):e=e[0];let[r,n]=e.split(":"),i=parseInt(n);return{host:r,password:t,port:isNaN(i)?6379:i}}function uf(){return{slotsRefreshTimeout:2e3,dnsLookup:(t,e)=>e(null,t),redisOptions:{...Zn(),tls:{}}}}function Zn(){let{host:t,password:e,port:r}=sc();return{connectTimeout:3e4,port:r,host:t,password:e}}function cf(t){let e=t.split(es);return e.length>=2?(e.shift(),e.join(es)):e[0]}var ac=require("dd-trace"),nA=require("lodash"),rA;if(h.MOCK_REDIS)try{rA=require("ioredis-mock")}catch{console.log("Mock redis unavailable")}async function vN(t=0){return await ac.tracer.trace("Redis.init",async e=>{if(h.MOCK_REDIS)return e.addTags({mock:!0}),new rA(Zn());let r;if(h.REDIS_CLUSTERED){e.addTags({clustered:!0});let{host:n,port:i}=sc();r=new uc.Cluster([{host:n,port:i}],uf())}else r=new uc.default(Zn());return new Promise((n,i)=>{r.on("error",s=>{e.addTags({error:!0}),console.error(`failed to connect to redis (db: ${t})`,s),i(s)}),r.on("reconnecting",()=>{console.log(`Redis reconnecting... (db: ${t})`)}),r.on("ready",()=>{e.addTags({connected:!0}),console.log(`Redis ready to receive commands (db: ${t})`),n(r)})})})}function NN(t,e){return new Promise((r,n)=>{let i=new Set;t.on("data",s=>s.forEach(o=>i.add(o))),t.on("error",s=>n(s)),t.on("end",async()=>{try{let s=Array.from(i).map(async o=>{let a=await e.get(o);return a&&(a=JSON.parse(a)),{key:cf(o),value:a}});r(await Promise.all(s))}catch(s){n(s)}})})}function PN(t){return t.isCluster}var lf=class t{constructor(e,r){this.client=e,this.db=r}static async init(e,r=0){return await ac.tracer.trace("RedisWrapper.init",async n=>{let i=await vN(r);return r&&!h.isTest()&&(n.addTags({db:e}),i.select(r)),new t(i,e)})}trace(e,r){return ac.tracer.trace(e,async n=>(n.addTags({db:this.db}),await r(n)))}prefixed(e){return e.includes(this.db)?e:`${this.db}${es}${e}`}async finish(){return await this.trace("RedisWrapper.finish",async()=>{await this.client.quit()})}async scan(e=""){return await this.trace("RedisWrapper.scan",async r=>{r.addTags({key:e}),e=`${this.db}${es}${e}`;let n;PN(this.client)?n=this.client.nodes("master")[0].scanStream({match:e+"*",count:100}):n=this.client.scanStream({match:e+"*",count:100});let i=await NN(n,this.client);return r.addTags({numKeysFound:i.length}),i})}async keys(e){return await this.trace("RedisWrapper.keys",async r=>(r.addTags({pattern:e}),this.client.keys(this.prefixed(e))))}async exists(e){return await this.trace("RedisWrapper.exists",async r=>(r.addTags({key:e}),await this.client.exists(this.prefixed(e))))}async get(e){return await this.trace("RedisWrapper.get",async r=>{r.addTags({key:e});let n=await this.client.get(this.prefixed(e));n!=null&&n.key&&(n.key=e);try{return JSON.parse(n)}catch{return n}})}async bulkGet(e){return await this.trace("RedisWrapper.bulkGet",async r=>{if(r.addTags({numKeys:e.length}),e.length===0)return{};let n=await this.client.mget(e.map(i=>this.prefixed(i)));return r.addTags({numKeysFound:n.length}),(0,nA.zip)(e,n).reduce((i,[s,o])=>{if(s===void 0||o===void 0)throw new Error(`Keys and response length mismatch: ${e.length} vs ${n.length}`);try{i[s]=o?JSON.parse(o):null}catch{i[s]=o}return i},{})})}async store(e,r,n=null){return await this.trace("RedisWrapper.store",async i=>{i.addTags({key:e,expirySeconds:n}),typeof r=="object"&&(r=JSON.stringify(r)),await this.client.set(this.prefixed(e),r),n&&await this.client.expire(this.prefixed(e),n)})}async bulkStore(e,r=null){return await this.trace("RedisWrapper.bulkStore",async n=>{n.addTags({numKeys:Object.keys(e).length,expirySeconds:r});let i=Object.entries(e).reduce((o,[a,u])=>(o[this.prefixed(a)]=typeof u=="object"?JSON.stringify(u):u,o),{}),s=this.client.pipeline();if(s.mset(i),r!==null)for(let o of Object.keys(i))s.expire(o,r);await s.exec()})}async getTTL(e){return await this.trace("RedisWrapper.getTTL",async r=>(r.addTags({key:e}),await this.client.ttl(this.prefixed(e))))}async setExpiry(e,r){return await this.trace("RedisWrapper.setExpiry",async n=>(n.addTags({key:e,expirySeconds:r}),await this.client.expire(this.prefixed(e),r)))}async delete(e){return await this.trace("RedisWrapper.delete",async r=>{r.addTags({key:e}),await this.client.del(this.prefixed(e))})}async bulkDelete(e){return await this.trace("RedisWrapper.bulkDelete",async r=>{r.addTags({numKeys:e.length}),await this.client.del(e.map(n=>this.prefixed(n)))})}async clear(){return await this.trace("RedisWrapper.clear",async e=>{let r=await this.scan();e.addTags({numKeys:r.length}),await Promise.all(r.map(n=>this.delete(n.key)))})}async increment(e){return await this.trace("RedisWrapper.increment",async r=>{r.addTags({key:e});let n=await this.client.incr(this.prefixed(e));if(isNaN(n))throw new Error(`Redis ${e} does not contain a number`);return n})}async deleteIfValue(e,r){return await this.trace("RedisWrapper.deleteIfValue",async n=>{n.addTags({key:e});let i=`
|
|
5
|
+
`),n={variables:{},expressions:[],errors:{}},i=0,s=r.length;i<s;i++){var o=r[i],a=null,u=o.trim();if(u.length>0){if(u.match(/^#/))continue;if(a=u.match(/^(.*)=(.*)$/))n.variables[a[1]]=a[2];else{var c=null;try{c=Ur._parseEntry("0 "+u),n.expressions.push(c.interval)}catch(l){n.errors[u]=l}}}}return n};Ur.parseFile=function(e,r){require("fs").readFile(e,function(n,i){if(n){r(n);return}return r(null,Ur.parseString(i.toString()))})};hT.exports=Ur});var Hk={};N(Hk,{APP_DEV:()=>Qu,APP_DEV_PREFIX:()=>yt,APP_PREFIX:()=>gt,AutomationViewMode:()=>Wu,BUDIBASE_DATASOURCE_TYPE:()=>xp,BadRequestError:()=>Dc,BudibaseError:()=>ps,Config:()=>vp,Cookie:()=>Kn,DEFAULT_BB_DATASOURCE_ID:()=>Di,DEFAULT_EMPLOYEE_TABLE_ID:()=>Dp,DEFAULT_EXPENSES_TABLE_ID:()=>bp,DEFAULT_INVENTORY_TABLE_ID:()=>wp,DEFAULT_JOBS_TABLE_ID:()=>Rp,DEFAULT_TENANT_ID:()=>Ae,DeprecatedViews:()=>Hi,DesignDocuments:()=>ju,DocumentType:()=>ye,Duration:()=>be,DurationType:()=>Uf,EmailUnavailableError:()=>mr,FeatureDisabledError:()=>vc,GlobalRole:()=>Cp,HTTPError:()=>lt,Header:()=>Xe,InternalTable:()=>xr,InvalidAPIKeyError:()=>fs,MAX_VALID_DATE:()=>Ku,MIN_VALID_DATE:()=>vT,NotFoundError:()=>bc,RedisClient:()=>We,SEPARATOR:()=>v,SQLITE_DESIGN_DOC_ID:()=>Ht,SQS_DATASOURCE_INTERNAL:()=>Op,StaticDatabases:()=>Te,UNICODE_MAX:()=>Ge,UsageLimitError:()=>Cc,UserStatus:()=>Hu,ViewName:()=>kr,accounts:()=>li,auth:()=>hh,blacklist:()=>Th,cache:()=>Oa,configs:()=>tn,constants:()=>Np,context:()=>Se,db:()=>jr,docIds:()=>Of,docUpdates:()=>Sh,encryption:()=>ph,env:()=>h,errors:()=>Pc,events:()=>ys,features:()=>nh,getPublicError:()=>Nc,init:()=>jk,installation:()=>qc,locks:()=>ui,logging:()=>Rc,middleware:()=>mh,objectStore:()=>Jf,permissions:()=>eh,platform:()=>Xo,plugins:()=>yh,queue:()=>pm,redis:()=>Eh,roles:()=>Xm,security:()=>Dm,sessions:()=>Yc,setEnv:()=>Ro,sql:()=>Ch,tenancy:()=>Qk,timers:()=>$c,userUtils:()=>om,users:()=>Es,utils:()=>ss,withEnv:()=>FT});module.exports=BI(Hk);var tn={};N(tn,{analyticsEnabled:()=>Bc,generateConfigID:()=>el,getAIConfig:()=>sF,getConfig:()=>Bt,getDefaultGoogleConfig:()=>Bm,getGoogleConfig:()=>tl,getGoogleDatasourceConfig:()=>Vm,getOIDCConfig:()=>rF,getOIDCConfigById:()=>qm,getOIDCLogosDoc:()=>eF,getPlatformUrl:()=>Ca,getSCIMConfig:()=>iF,getSMTPConfig:()=>nF,getSMTPConfigDoc:()=>P_,getSettingsConfig:()=>$m,getSettingsConfigDoc:()=>Qc,save:()=>Z0});var GI=["user:created","user:updated","user:deleted","user:admin:assigned","user:admin:removed","user:builder:assigned","user:builder:removed","user_group:created","user_group:updated","user_group:deleted","user_group:user_added","user_group:users_deleted","user_group:permissions_edited"],Nh=[...GI],Ph={"user:created":'User "{{ email }}" created{{#if viaScim}} via SCIM{{/if}}',"user:updated":'User "{{ email }}" updated{{#if viaScim}} via SCIM{{/if}}',"user:deleted":'User "{{ email }}" deleted{{#if viaScim}} via SCIM{{/if}}',"user:admin:assigned":'User "{{ email }}" admin role assigned',"user:admin:removed":'User "{{ email }}" admin role removed',"user:builder:assigned":'User "{{ email }}" builder role assigned',"user:builder:removed":'User "{{ email }}" builder role removed',"user:invited":'User "{{ email }}" invited',"user:invite:accepted":'User "{{ email }}" accepted invite',"user:password:updated":'User "{{ email }}" password updated',"user:password:reset:requested":'User "{{ email }}" password reset requested',"user:password:reset":'User "{{ email }}" password reset',"user_group:created":'User group "{{ name }}" created{{#if viaScim}} via SCIM{{/if}}',"user_group:updated":'User group "{{ name }}" updated{{#if viaScim}} via SCIM{{/if}}',"user_group:deleted":'User group "{{ name }}" deleted{{#if viaScim}} via SCIM{{/if}}',"user_group:user_added":'User group "{{ name }}" {{ count }} users added{{#if viaScim}} via SCIM{{/if}}',"user_group:users_deleted":'User group "{{ name }}" {{ count }} users removed{{#if viaScim}} via SCIM{{/if}}',"user_group:permissions_edited":'User group "{{ name }}" permissions edited',"user:password:force:reset":void 0,"user_group:onboarding_added":void 0,"user:onboarding:complete":void 0,"user:data:collaboration":void 0,"email:smtp:created":"Email configuration created","email:smtp:updated":"Email configuration updated","ai:config:created":"AI configuration created","ai:config:updated":"AI configuration updated","auth:sso:created":"SSO configuration created","auth:sso:updated":"SSO configuration updated","auth:sso:activated":"SSO configuration activated","auth:sso:deactivated":"SSO configuration deactivated","auth:login":'User "{{ email }}" logged in',"auth:logout":'User "{{ email }}" logged out',"org:info:name:updated":"Organisation name updated","org:info:logo:updated":"Organisation logo updated","org:platformurl:updated":"Organisation platform URL updated","app:created":'App "{{ name }}" created',"app:updated":'App "{{ name }}" updated',"app:deleted":'App "{{ name }}" deleted',"app:duplicated":'App "{{ name }}" duplicated',"app:published":'App "{{ name }}" published',"app:unpublished":'App "{{ name }}" unpublished',"app:template:imported":'App "{{ name }}" template imported',"app:file:imported":'App "{{ name }}" file imported',"app:version:updated":'App "{{ name }}" version updated',"app:version:reverted":'App "{{ name }}" version reverted',"app:reverted":'App "{{ name }}" reverted',"app:exported":'App "{{ name }}" exported',"app:backup:restored":'App backup "{{ name }}" restored',"app:backup:triggered":'App backup "{{ name }}" triggered',"datasource:created":"Datasource created","datasource:updated":"Datasource updated","datasource:deleted":"Datasource deleted","query:created":"Query created","query:updated":"Query updated","query:deleted":"Query deleted","query:import":"Query import","queries:run":void 0,"query:previewed":void 0,"table:created":'Table "{{ name }}" created',"table:updated":'Table "{{ name }}" updated',"table:deleted":'Table "{{ name }}" deleted',"table:exported":'Table "{{ name }}" exported',"table:imported":'Table "{{ name }}" imported',"table:data:imported":"Data imported to table","rows:created":"Rows created","rows:imported":"Rows imported","automation:created":'Automation "{{ name }}" created',"automation:deleted":'Automation "{{ name }}" deleted',"automation:step:created":'Automation "{{ name }}" step added',"automation:step:deleted":'Automation "{{ name }}" step removed',"automation:tested":void 0,"automations:run":void 0,"automation:trigger:updated":void 0,"screen:created":'Screen "{{ name }}" created',"screen:deleted":'Screen "{{ name }}" deleted',"component:created":"Component created","component:deleted":"Component deleted","environment_variable:created":"Environment variable created","environment_variable:deleted":"Environment variable deleted","environment_variable:upgrade_panel_opened":void 0,"plugin:imported":"Plugin imported","plugin:deleted":"Plugin deleted","plugin:init":void 0,"action:automation_step:executed":void 0,"action:crud:executed":void 0,"action:ai_agent:executed":void 0,"role:created":void 0,"role:updated":void 0,"role:deleted":void 0,"role:assigned":void 0,"role:unassigned":void 0,"license:plan:changed":void 0,"license:activated":void 0,"license:payment:failed":void 0,"license:payment:recovered":void 0,"license:checkout:opened":void 0,"license:checkout:success":void 0,"license:portal:opened":void 0,"account:created":void 0,"account:deleted":void 0,"account:verified":void 0,"app:backfill:succeeded":void 0,"app:backfill:failed":void 0,"tenant:backfill:succeeded":void 0,"tenant:backfill:failed":void 0,"installation:backfill:succeeded":void 0,"installation:backfill:failed":void 0,"layout:created":void 0,"layout:deleted":void 0,"view:created":void 0,"view:updated":void 0,"view:deleted":void 0,"view:exported":void 0,"view:filter:created":void 0,"view:filter:updated":void 0,"view:filter:deleted":void 0,"view:calculation:created":void 0,"view:calculation:updated":void 0,"view:calculation:deleted":void 0,"view:join:created":void 0,"served:builder":void 0,"served:app":void 0,"served:app:preview":void 0,"analytics:opt:out":void 0,"analytics:opt:in":void 0,"installation:version:checked":void 0,"installation:version:upgraded":void 0,"installation:version:downgraded":void 0,"installation:firstStartup":void 0,"audit_log:filtered":void 0,"audit_log:downloaded":void 0,"row_action:created":void 0};var Rl=(n=>(n.SQL="sql",n.JSON="json",n.FIELDS="fields",n))(Rl||{}),wl=(p=>(p.STRING="string",p.CODE="code",p.LONGFORM="longForm",p.BOOLEAN="boolean",p.NUMBER="number",p.PASSWORD="password",p.LIST="list",p.OBJECT="object",p.JSON="json",p.FILE="file",p.FIELD_GROUP="fieldGroup",p.SELECT="select",p))(wl||{}),ka=(y=>(y.POSTGRES="POSTGRES",y.DYNAMODB="DYNAMODB",y.MONGODB="MONGODB",y.ELASTICSEARCH="ELASTICSEARCH",y.COUCHDB="COUCHDB",y.SQL_SERVER="SQL_SERVER",y.S3="S3",y.AIRTABLE="AIRTABLE",y.MYSQL="MYSQL",y.ARANGODB="ARANGODB",y.REST="REST",y.ORACLE="ORACLE",y.GOOGLE_SHEETS="GOOGLE_SHEETS",y.FIRESTORE="FIRESTORE",y.REDIS="REDIS",y.SNOWFLAKE="SNOWFLAKE",y.BUDIBASE="BUDIBASE",y))(ka||{});var bl=(n=>(n.CONNECTION_CHECKING="connection",n.FETCH_TABLE_NAMES="fetch_table_names",n.EXPORT_SCHEMA="export_schema",n))(bl||{});var $I=W(require("lodash")),Ir=(o=>(o.EQUAL="equal",o.NOT_EQUAL="notEqual",o.EMPTY="empty",o.NOT_EMPTY="notEmpty",o.FUZZY="fuzzy",o.STRING="string",o))(Ir||{}),Jt=(i=>(i.CONTAINS="contains",i.NOT_CONTAINS="notContains",i.CONTAINS_ANY="containsAny",i.ONE_OF="oneOf",i))(Jt||{}),dn=(e=>(e.RANGE="range",e))(dn||{}),Ti=(r=>(r.AND="$and",r.OR="$or",r))(Ti||{});function Ba(t){return Object.values(Ti).includes(t)}function Lh(t){return Object.values(Ir).includes(t)}function Uh(t){return Object.values(Jt).includes(t)}function Ga(t){return Object.values(dn).includes(t)}var Ai=(r=>(r.RETURN_ALL="all",r.RETURN_NONE="none",r))(Ai||{});var Mh=t=>typeof t=="object"&&t._id&&t._rev;var Os=(s=>(s.USER="user",s.HEADER="header",s.QUERY="query",s.SUBDOMAIN="subdomain",s.PATH="path",s))(Os||{});var Fh={USE_ZOD_VALIDATOR:!1,AI_JS_GENERATION:!0,AI_TABLE_GENERATION:!0,AI_AGENTS:!1,WORKSPACE_APPS:!1,DIRECT_LOGIN_TO_ACCOUNT_PORTAL:!1,DEBUG_UI:!1};var YB={OptOut:"analytics:opt:out",OptIn:"analytics:opt:in",SelfHostInit:"hosting:init",PluginInit:"plugin:init"};var xs=(i=>(i.READ="read",i.WRITE="write",i.EXECUTE="execute",i.ADMIN="admin",i))(xs||{});var $a=(m=>(m.APP="app",m.TABLE="table",m.USER="user",m.AUTOMATION="automation",m.WEBHOOK="webhook",m.BUILDER="builder",m.CREATOR="creator",m.GLOBAL_BUILDER="globalBuilder",m.QUERY="query",m.VIEW="view",m.LEGACY_VIEW="legacy_view",m))($a||{});var Va=t=>t.hosting==="cloud";var qa=t=>t.authType==="sso";var v="_",Ge="\uFFF0",Or=t=>`${t}${v}`,ye=(Q=>(Q.USER="us",Q.GROUP="gr",Q.WORKSPACE="workspace",Q.CONFIG="config",Q.TEMPLATE="template",Q.APP="app",Q.DEV="dev",Q.APP_DEV="app_dev",Q.APP_METADATA="app_metadata",Q.ROLE="role",Q.DEV_INFO="devinfo",Q.AUTOMATION_LOG="log_au",Q.ACCOUNT_METADATA="acc_metadata",Q.PLUGIN="plg",Q.DATASOURCE="datasource",Q.DATASOURCE_PLUS="datasource_plus",Q.APP_BACKUP="backup",Q.TABLE="ta",Q.ROW="ro",Q.AUTOMATION="au",Q.LINK="li",Q.WEBHOOK="wh",Q.INSTANCE="inst",Q.LAYOUT="layout",Q.SCREEN="screen",Q.QUERY="query",Q.DEPLOYMENTS="deployments",Q.METADATA="metadata",Q.MEM_VIEW="view",Q.USER_FLAG="flag",Q.AUTOMATION_METADATA="meta_au",Q.AUDIT_LOG="al",Q.SCIM_LOG="scimlog",Q.ROW_ACTIONS="ra",Q.OAUTH2_CONFIG="oauth2",Q.OAUTH2_CONFIG_LOG="oauth2log",Q.AGENT_CHAT="agentchat",Q.AGENT_TOOL_SOURCE="agenttoolsource",Q.WORKSPACE_APP="workspace_app",Q))(ye||{});var xr=(e=>(e.USER_METADATA="ta_users",e))(xr||{}),Dl=(r=>(r.VIEW="view",r.ROW_ACTION="row_action",r))(Dl||{});var ee=(l=>(l.OBJECT="object",l.STRING="string",l.BOOLEAN="boolean",l.NUMBER="number",l.ARRAY="array",l.JSON="json",l.DATE="date",l.DATETIME="datetime",l.ATTACHMENT="attachment",l.LONGFORM="longform",l))(ee||{}),pe=(R=>(R.TABLE="table",R.ROW="row",R.ROWS="rows",R.WIDE="wide",R.QUERY="query",R.QUERY_PARAMS="queryParams",R.QUERY_LIMIT="queryLimit",R.LOOP_OPTION="loopOption",R.ITEM="item",R.CODE="code",R.FILTERS="filters",R.COLUMN="column",R.TRIGGER_SCHEMA="triggerSchema",R.CRON="cron",R.WEBHOOK_URL="webhookUrl",R.AUTOMATION="automation",R.AUTOMATION_FIELDS="automationFields",R.MULTI_ATTACHMENTS="multi_attachments",R.TRIGGER_FILTER="trigger_filter",R.CATEGORIES="categories",R))(pe||{}),_t=(a=>(a.ROW_SAVED="ROW_SAVED",a.ROW_UPDATED="ROW_UPDATED",a.ROW_DELETED="ROW_DELETED",a.WEBHOOK="WEBHOOK",a.APP="APP",a.CRON="CRON",a.ROW_ACTION="ROW_ACTION",a))(_t||{});var ue=(I=>(I.SEND_EMAIL_SMTP="SEND_EMAIL_SMTP",I.CREATE_ROW="CREATE_ROW",I.UPDATE_ROW="UPDATE_ROW",I.DELETE_ROW="DELETE_ROW",I.EXECUTE_BASH="EXECUTE_BASH",I.OUTGOING_WEBHOOK="OUTGOING_WEBHOOK",I.EXECUTE_SCRIPT="EXECUTE_SCRIPT",I.EXECUTE_SCRIPT_V2="EXECUTE_SCRIPT_V2",I.EXECUTE_QUERY="EXECUTE_QUERY",I.SERVER_LOG="SERVER_LOG",I.DELAY="DELAY",I.FILTER="FILTER",I.API_REQUEST="API_REQUEST",I.QUERY_ROWS="QUERY_ROWS",I.LOOP="LOOP",I.COLLECT="COLLECT",I.OPENAI="OPENAI",I.TRIGGER_AUTOMATION_RUN="TRIGGER_AUTOMATION_RUN",I.BRANCH="BRANCH",I.CLASSIFY_CONTENT="CLASSIFY_CONTENT",I.PROMPT_LLM="PROMPT_LLM",I.TRANSLATE="TRANSLATE",I.SUMMARISE="SUMMARISE",I.GENERATE_TEXT="GENERATE_TEXT",I.EXTRACT_FILE_DATA="EXTRACT_FILE_DATA",I.discord="discord",I.slack="slack",I.zapier="zapier",I.integromat="integromat",I.n8n="n8n",I))(ue||{}),kh=[...Object.values(ue),...Object.values(_t)];var Cl=(a=>(a.EMAIL="email",a.DOCUMENT="document",a.BLOG_POST="blog_post",a.CHAT_MESSAGE="chat_message",a.LETTER="letter",a.PROPOSAL="proposal",a.OTHER="other",a))(Cl||{}),Bh={email:"Email",document:"Document",blog_post:"Blog post",chat_message:"Chat message",letter:"Letter",proposal:"Proposal",other:"Other"},vl=(r=>(r.URL="URL",r.ATTACHMENT="Attachment",r))(vl||{}),Nl=(i=>(i.PDF="pdf",i.JPG="jpg",i.PNG="png",i.JPEG="jpeg",i))(Nl||{});var Pl=(i=>(i.EQUAL="EQUAL",i.NOT_EQUAL="NOT_EQUAL",i.GREATER_THAN="GREATER_THAN",i.LESS_THAN="LESS_THAN",i))(Pl||{});var Ll=(o=>(o.GET="GET",o.POST="POST",o.PATCH="PATCH",o.PUT="PUT",o.HEAD="HEAD",o.DELETE="DELETE",o))(Ll||{});var Ul="bb_internal";var Gh=["attachment_single","attachment","signature_single","bb_reference","json","array"];function Wa(t){return!!t.providerType}var Ml=(n=>(n.DATASOURCE="datasource",n.COMPONENT="component",n.AUTOMATION="automation",n))(Ml||{});var X$=Object.values(Ml);var iV=["rows","queries","automations"],sV=["queries","automations"];var ie;(function(t){t.assertEqual=i=>i;function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ie||(ie={}));var kl;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(kl||(kl={}));var M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},x=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),QI=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ze=class t extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ze.create=t=>new ze(t);var Ii=(t,e)=>{let r;switch(t.code){case x.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case x.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case x.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},qh=Ii;function jI(t){qh=t}function Qa(){return qh}var ja=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}},HI=[];function P(t,e){let r=Qa(),n=ja({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ii?void 0:Ii].filter(i=>!!i)});t.common.issues.push(n)}var ke=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return J;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return J;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),_i=t=>({status:"dirty",value:t}),$e=t=>({status:"valid",value:t}),Bl=t=>t.status==="aborted",Gl=t=>t.status==="dirty",bs=t=>t.status==="valid",Ds=t=>typeof Promise<"u"&&t instanceof Promise;function Ha(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function Wh(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));var Rs,ws,pt=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$h=(t,e)=>{if(bs(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ze(t.common.issues);return this._error=r,this._error}}};function Z(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{var u,c;let{message:l}=t;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:(u=l??n)!==null&&u!==void 0?u:a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:(c=l??r)!==null&&c!==void 0?c:a.defaultError}},description:i}}var X=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Rr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ds(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;let i={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},s=this._parseSync({data:e,path:i.path,parent:i});return $h(i,s)}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Ds(i)?i:Promise.resolve(i));return $h(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:x.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Ze({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return dt.create(this,this._def)}nullable(){return $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xt.create(this,this._def)}promise(){return Dr.create(this,this._def)}or(e){return Tn.create([this,e],this._def)}and(e){return An.create(this,e,this._def)}transform(e){return new Ze({...Z(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new xn({...Z(this._def),innerType:this,defaultValue:r,typeName:K.ZodDefault})}brand(){return new Cs({typeName:K.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Rn({...Z(this._def),innerType:this,catchValue:r,typeName:K.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vs.create(this,e)}readonly(){return wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},KI=/^c[^\s-]{8,}$/i,YI=/^[0-9a-z]+$/,JI=/^[0-9A-HJKMNP-TV-Z]{26}$/,zI=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZI=/^[a-z0-9_-]{21}$/i,XI=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,eO=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fl,rO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nO=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,iO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",sO=new RegExp(`^${Qh}$`);function jh(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function oO(t){return new RegExp(`^${jh(t)}$`)}function Hh(t){let e=`${Qh}T${jh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function aO(t,e){return!!((e==="v4"||!e)&&rO.test(t)||(e==="v6"||!e)&&nO.test(t))}var wr=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.string,received:s.parsedType}),J}let n=new ke,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?P(i,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&P(i,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")eO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"email",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Fl||(Fl=new RegExp(tO,"u")),Fl.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"emoji",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")zI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"uuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ZI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"nanoid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")KI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"cuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")YI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"cuid2",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")JI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"ulid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),P(i,{validation:"url",code:x.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"regex",code:x.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Hh(s).test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?sO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?oO(s).test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{code:x.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?XI.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"duration",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?aO(e.data,s.version)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"ip",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?iO.test(e.data)||(i=this._getOrReturnCtx(e,i),P(i,{validation:"base64",code:x.invalid_string,message:s.message}),n.dirty()):ie.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:x.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(r=e?.offset)!==null&&r!==void 0?r:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};wr.create=t=>{var e;return new wr({checks:[],typeName:K.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Z(t)})};function uO(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=parseInt(t.toFixed(i).replace(".","")),o=parseInt(e.toFixed(i).replace(".",""));return s%o/Math.pow(10,i)}var fn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.number,received:s.parsedType}),J}let n,i=new ke;for(let s of this._def.checks)s.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?uO(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_finite,message:s.message}),i.dirty()):ie.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};fn.create=t=>new fn({checks:[],typeName:K.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var mn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==M.bigint){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.bigint,received:s.parsedType}),J}let n,i=new ke;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),P(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ie.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};mn.create=t=>{var e;return new mn({checks:[],typeName:K.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...Z(t)})};var hn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.boolean,received:n.parsedType}),J}return $e(e.data)}};hn.create=t=>new hn({typeName:K.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var gn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_type,expected:M.date,received:s.parsedType}),J}if(isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return P(s,{code:x.invalid_date}),J}let n=new ke,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),P(i,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ie.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};gn.create=t=>new gn({checks:[],coerce:t?.coerce||!1,typeName:K.ZodDate,...Z(t)});var Oi=class extends X{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.symbol,received:n.parsedType}),J}return $e(e.data)}};Oi.create=t=>new Oi({typeName:K.ZodSymbol,...Z(t)});var yn=class extends X{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.undefined,received:n.parsedType}),J}return $e(e.data)}};yn.create=t=>new yn({typeName:K.ZodUndefined,...Z(t)});var En=class extends X{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.null,received:n.parsedType}),J}return $e(e.data)}};En.create=t=>new En({typeName:K.ZodNull,...Z(t)});var br=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return $e(e.data)}};br.create=t=>new br({typeName:K.ZodAny,...Z(t)});var Zt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $e(e.data)}};Zt.create=t=>new Zt({typeName:K.ZodUnknown,...Z(t)});var It=class extends X{_parse(e){let r=this._getOrReturnCtx(e);return P(r,{code:x.invalid_type,expected:M.never,received:r.parsedType}),J}};It.create=t=>new It({typeName:K.ZodNever,...Z(t)});var xi=class extends X{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.void,received:n.parsedType}),J}return $e(e.data)}};xi.create=t=>new xi({typeName:K.ZodVoid,...Z(t)});var Xt=class t extends X{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==M.array)return P(r,{code:x.invalid_type,expected:M.array,received:r.parsedType}),J;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(P(r,{code:o?x.too_big:x.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(P(r,{code:x.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(P(r,{code:x.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new pt(r,o,r.path,a)))).then(o=>ke.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new pt(r,o,r.path,a)));return ke.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Xt.create=(t,e)=>new Xt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...Z(e)});function Si(t){if(t instanceof je){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=dt.create(Si(n))}return new je({...t._def,shape:()=>e})}else return t instanceof Xt?new Xt({...t._def,type:Si(t.element)}):t instanceof dt?dt.create(Si(t.unwrap())):t instanceof $t?$t.create(Si(t.unwrap())):t instanceof Gt?Gt.create(t.items.map(e=>Si(e))):t}var je=class t extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==M.object){let c=this._getOrReturnCtx(e);return P(c,{code:x.invalid_type,expected:M.object,received:c.parsedType}),J}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip"))for(let c in i.data)o.includes(c)||a.push(c);let u=[];for(let c of o){let l=s[c],m=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new pt(i,m,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof It){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(P(i,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let m=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new pt(i,m,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let m=await l.key,p=await l.value;c.push({key:m,value:p,alwaysSet:l.alwaysSet})}return c}).then(c=>ke.mergeObjectSync(n,c)):ke.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var i,s,o,a;let u=(o=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,r,n).message)!==null&&o!==void 0?o:n.defaultError;return r.code==="unrecognized_keys"?{message:(a=G.errToObj(e).message)!==null&&a!==void 0?a:u}:{message:u}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:K.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};return ie.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}omit(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}deepPartial(){return Si(this)}partial(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}),new t({...this._def,shape:()=>r})}required(e){let r={};return ie.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof dt;)s=s._def.innerType;r[n]=s}}),new t({...this._def,shape:()=>r})}keyof(){return Kh(ie.objectKeys(this.shape))}};je.create=(t,e)=>new je({shape:()=>t,unknownKeys:"strip",catchall:It.create(),typeName:K.ZodObject,...Z(e)});je.strictCreate=(t,e)=>new je({shape:()=>t,unknownKeys:"strict",catchall:It.create(),typeName:K.ZodObject,...Z(e)});je.lazycreate=(t,e)=>new je({shape:t,unknownKeys:"strip",catchall:It.create(),typeName:K.ZodObject,...Z(e)});var Tn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new ze(a.ctx.common.issues));return P(r,{code:x.invalid_union,unionErrors:o}),J}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(u=>new ze(u));return P(r,{code:x.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};Tn.create=(t,e)=>new Tn({options:t,typeName:K.ZodUnion,...Z(e)});var zt=t=>t instanceof Sn?zt(t.schema):t instanceof Ze?zt(t.innerType()):t instanceof _n?[t.value]:t instanceof In?t.options:t instanceof On?ie.objectValues(t.enum):t instanceof xn?zt(t._def.innerType):t instanceof yn?[void 0]:t instanceof En?[null]:t instanceof dt?[void 0,...zt(t.unwrap())]:t instanceof $t?[null,...zt(t.unwrap())]:t instanceof Cs||t instanceof wn?zt(t.unwrap()):t instanceof Rn?zt(t._def.innerType):[],Ka=class t extends X{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return P(r,{code:x.invalid_type,expected:M.object,received:r.parsedType}),J;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(P(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=zt(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:K.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Z(n)})}};function $l(t,e){let r=Rr(t),n=Rr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let i=ie.objectKeys(e),s=ie.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let u=$l(t[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],u=$l(o,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var An=class extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(Bl(s)||Bl(o))return J;let a=$l(s.value,o.value);return a.valid?((Gl(s)||Gl(o))&&r.dirty(),{status:r.value,value:a.data}):(P(n,{code:x.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};An.create=(t,e,r)=>new An({left:t,right:e,typeName:K.ZodIntersection,...Z(r)});var Gt=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return P(n,{code:x.invalid_type,expected:M.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return P(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new pt(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>ke.mergeArray(r,o)):ke.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Gt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gt({items:t,typeName:K.ZodTuple,rest:null,...Z(e)})};var Ya=class t extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return P(n,{code:x.invalid_type,expected:M.object,received:n.parsedType}),J;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new pt(n,a,n.path,a)),value:o._parse(new pt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ke.mergeObjectAsync(r,i):ke.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof X?new t({keyType:e,valueType:r,typeName:K.ZodRecord,...Z(n)}):new t({keyType:wr.create(),valueType:e,typeName:K.ZodRecord,...Z(r)})}},Ri=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return P(n,{code:x.invalid_type,expected:M.map,received:n.parsedType}),J;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new pt(n,a,n.path,[c,"key"])),value:s._parse(new pt(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return J;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return J;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};Ri.create=(t,e,r)=>new Ri({valueType:e,keyType:t,typeName:K.ZodMap,...Z(r)});var wi=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return P(n,{code:x.invalid_type,expected:M.set,received:n.parsedType}),J;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(P(n,{code:x.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(P(n,{code:x.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(u){let c=new Set;for(let l of u){if(l.status==="aborted")return J;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>s._parse(new pt(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};wi.create=(t,e)=>new wi({valueType:t,minSize:null,maxSize:null,typeName:K.ZodSet,...Z(e)});var Ja=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return P(r,{code:x.invalid_type,expected:M.function,received:r.parsedType}),J;function n(a,u){return ja({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qa(),Ii].filter(c=>!!c),issueData:{code:x.invalid_arguments,argumentsError:u}})}function i(a,u){return ja({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qa(),Ii].filter(c=>!!c),issueData:{code:x.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Dr){let a=this;return $e(async function(...u){let c=new ze([]),l=await a._def.args.parseAsync(u,s).catch(f=>{throw c.addIssue(n(u,f)),c}),m=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw c.addIssue(i(m,f)),c})})}else{let a=this;return $e(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new ze([n(u,c.error)]);let l=Reflect.apply(o,this,c.data),m=a._def.returns.safeParse(l,s);if(!m.success)throw new ze([i(l,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Gt.create(e).rest(Zt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Gt.create([]).rest(Zt.create()),returns:r||Zt.create(),typeName:K.ZodFunction,...Z(n)})}},Sn=class extends X{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Sn.create=(t,e)=>new Sn({getter:t,typeName:K.ZodLazy,...Z(e)});var _n=class extends X{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return P(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};_n.create=(t,e)=>new _n({value:t,typeName:K.ZodLiteral,...Z(e)});function Kh(t,e){return new In({values:t,typeName:K.ZodEnum,...Z(e)})}var In=class t extends X{constructor(){super(...arguments),Rs.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{expected:ie.joinValues(n),received:r.parsedType,code:x.invalid_type}),J}if(Ha(this,Rs,"f")||Wh(this,Rs,new Set(this._def.values),"f"),!Ha(this,Rs,"f").has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{received:r.data,code:x.invalid_enum_value,options:n}),J}return $e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Rs=new WeakMap;In.create=Kh;var On=class extends X{constructor(){super(...arguments),ws.set(this,void 0)}_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let i=ie.objectValues(r);return P(n,{expected:ie.joinValues(i),received:n.parsedType,code:x.invalid_type}),J}if(Ha(this,ws,"f")||Wh(this,ws,new Set(ie.getValidEnumValues(this._def.values)),"f"),!Ha(this,ws,"f").has(e.data)){let i=ie.objectValues(r);return P(n,{received:n.data,code:x.invalid_enum_value,options:i}),J}return $e(e.data)}get enum(){return this._def.values}};ws=new WeakMap;On.create=(t,e)=>new On({values:t,typeName:K.ZodNativeEnum,...Z(e)});var Dr=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return P(r,{code:x.invalid_type,expected:M.promise,received:r.parsedType}),J;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return $e(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Dr.create=(t,e)=>new Dr({type:t,typeName:K.ZodPromise,...Z(e)});var Ze=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{P(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return J;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?J:u.status==="dirty"||r.value==="dirty"?_i(u.value):u});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"||r.value==="dirty"?_i(a.value):a}}if(i.type==="refinement"){let o=a=>{let u=i.refinement(a,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bs(o))return o;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>bs(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):o);ie.assertNever(i)}};Ze.create=(t,e,r)=>new Ze({schema:t,typeName:K.ZodEffects,effect:e,...Z(r)});Ze.createWithPreprocess=(t,e,r)=>new Ze({schema:e,effect:{type:"preprocess",transform:t},typeName:K.ZodEffects,...Z(r)});var dt=class extends X{_parse(e){return this._getType(e)===M.undefined?$e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(t,e)=>new dt({innerType:t,typeName:K.ZodOptional,...Z(e)});var $t=class extends X{_parse(e){return this._getType(e)===M.null?$e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:K.ZodNullable,...Z(e)});var xn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:K.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Rn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ds(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:K.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var bi=class extends X{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return P(n,{code:x.invalid_type,expected:M.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};bi.create=t=>new bi({typeName:K.ZodNaN,...Z(t)});var cO=Symbol("zod_brand"),Cs=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vs=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),_i(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?J:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:K.ZodPipeline})}},wn=class extends X{_parse(e){let r=this._def.innerType._parse(e),n=i=>(bs(i)&&(i.value=Object.freeze(i.value)),i);return Ds(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:K.ZodReadonly,...Z(e)});function Yh(t,e={},r){return t?br.create().superRefine((n,i)=>{var s,o;if(!t(n)){let a=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(o=(s=a.fatal)!==null&&s!==void 0?s:r)!==null&&o!==void 0?o:!0,c=typeof a=="string"?{message:a}:a;i.addIssue({code:"custom",...c,fatal:u})}}):br.create()}var lO={object:je.lazycreate},K;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(K||(K={}));var dO=(t,e={message:`Input not instance of ${t.name}`})=>Yh(r=>r instanceof t,e),Jh=wr.create,zh=fn.create,pO=bi.create,fO=mn.create,Zh=hn.create,mO=gn.create,hO=Oi.create,gO=yn.create,yO=En.create,EO=br.create,TO=Zt.create,AO=It.create,SO=xi.create,_O=Xt.create,IO=je.create,OO=je.strictCreate,xO=Tn.create,RO=Ka.create,wO=An.create,bO=Gt.create,DO=Ya.create,CO=Ri.create,vO=wi.create,NO=Ja.create,PO=Sn.create,LO=_n.create,UO=In.create,MO=On.create,FO=Dr.create,Vh=Ze.create,kO=dt.create,BO=$t.create,GO=Ze.createWithPreprocess,$O=vs.create,VO=()=>Jh().optional(),qO=()=>zh().optional(),WO=()=>Zh().optional(),QO={string:t=>wr.create({...t,coerce:!0}),number:t=>fn.create({...t,coerce:!0}),boolean:t=>hn.create({...t,coerce:!0}),bigint:t=>mn.create({...t,coerce:!0}),date:t=>gn.create({...t,coerce:!0})},jO=J,re=Object.freeze({__proto__:null,defaultErrorMap:Ii,setErrorMap:jI,getErrorMap:Qa,makeIssue:ja,EMPTY_PATH:HI,addIssueToContext:P,ParseStatus:ke,INVALID:J,DIRTY:_i,OK:$e,isAborted:Bl,isDirty:Gl,isValid:bs,isAsync:Ds,get util(){return ie},get objectUtil(){return kl},ZodParsedType:M,getParsedType:Rr,ZodType:X,datetimeRegex:Hh,ZodString:wr,ZodNumber:fn,ZodBigInt:mn,ZodBoolean:hn,ZodDate:gn,ZodSymbol:Oi,ZodUndefined:yn,ZodNull:En,ZodAny:br,ZodUnknown:Zt,ZodNever:It,ZodVoid:xi,ZodArray:Xt,ZodObject:je,ZodUnion:Tn,ZodDiscriminatedUnion:Ka,ZodIntersection:An,ZodTuple:Gt,ZodRecord:Ya,ZodMap:Ri,ZodSet:wi,ZodFunction:Ja,ZodLazy:Sn,ZodLiteral:_n,ZodEnum:In,ZodNativeEnum:On,ZodPromise:Dr,ZodEffects:Ze,ZodTransformer:Ze,ZodOptional:dt,ZodNullable:$t,ZodDefault:xn,ZodCatch:Rn,ZodNaN:bi,BRAND:cO,ZodBranded:Cs,ZodPipeline:vs,ZodReadonly:wn,custom:Yh,Schema:X,ZodSchema:X,late:lO,get ZodFirstPartyTypeKind(){return K},coerce:QO,any:EO,array:_O,bigint:fO,boolean:Zh,date:mO,discriminatedUnion:RO,effect:Vh,enum:UO,function:NO,instanceof:dO,intersection:wO,lazy:PO,literal:LO,map:CO,nan:pO,nativeEnum:MO,never:AO,null:yO,nullable:BO,number:zh,object:IO,oboolean:WO,onumber:qO,optional:kO,ostring:VO,pipeline:$O,preprocess:GO,promise:FO,record:DO,set:vO,strictObject:OO,string:Jh,symbol:hO,transformer:Vh,tuple:bO,undefined:gO,union:xO,unknown:TO,void:SO,NEVER:jO,ZodIssueCode:x,quotelessJson:QI,ZodError:ze});var bn=(r=>(r.ASCENDING="ascending",r.DESCENDING="descending",r))(bn||{}),za=(r=>(r.STRING="string",r.NUMBER="number",r))(za||{});var tu=re.string().refine(t=>t!=="_complexIdOperator",{message:"Key '_complexIdOperator' is not allowed"}),Xh=re.record(tu,re.string()),Za=re.record(tu,re.any()),Xa=re.record(tu,re.union([re.any().array(),re.string()])),eg=re.lazy(()=>re.object({conditions:re.array(re.object(tg))})),eu=re.union([re.string(),re.number()]),tg={string:Xh.optional(),fuzzy:Xh.optional(),range:re.record(tu,re.union([re.object({high:eu,low:eu}),re.object({high:eu}),re.object({low:eu})])).optional(),equal:Za.optional(),notEqual:Za.optional(),empty:Za.optional(),notEmpty:Za.optional(),oneOf:Xa.optional(),contains:Xa.optional(),notContains:Xa.optional(),containsAny:Xa.optional(),$and:eg.optional(),$or:eg.optional()},eq=re.object({query:re.object({allOr:re.boolean().optional(),onEmptyFilter:re.nativeEnum(Ai).optional(),...tg}).optional(),paginate:re.boolean().optional(),bookmark:re.union([re.string(),re.number()]).nullish(),limit:re.number().optional(),sort:re.string().nullish(),sortOrder:re.nativeEnum(bn).optional(),sortType:re.nativeEnum(za).nullish(),version:re.string().optional(),disableEscaping:re.boolean().optional(),countRows:re.boolean().optional()});var Np={};N(Np,{APP_DEV:()=>Qu,APP_DEV_PREFIX:()=>yt,APP_PREFIX:()=>gt,AutomationViewMode:()=>Wu,BUDIBASE_DATASOURCE_TYPE:()=>xp,Config:()=>vp,Cookie:()=>Kn,DEFAULT_BB_DATASOURCE_ID:()=>Di,DEFAULT_EMPLOYEE_TABLE_ID:()=>Dp,DEFAULT_EXPENSES_TABLE_ID:()=>bp,DEFAULT_INVENTORY_TABLE_ID:()=>wp,DEFAULT_JOBS_TABLE_ID:()=>Rp,DEFAULT_TENANT_ID:()=>Ae,DeprecatedViews:()=>Hi,DesignDocuments:()=>ju,DocumentType:()=>ye,GlobalRole:()=>Cp,Header:()=>Xe,InternalTable:()=>xr,MAX_VALID_DATE:()=>Ku,MIN_VALID_DATE:()=>vT,SEPARATOR:()=>v,SQLITE_DESIGN_DOC_ID:()=>Ht,SQS_DATASOURCE_INTERNAL:()=>Op,StaticDatabases:()=>Te,UNICODE_MAX:()=>Ge,UserStatus:()=>Hu,ViewName:()=>kr});var AW={SUMMARISE_TEXT:{columns:"columns"},CLEAN_DATA:{column:"column"},TRANSLATE:{column:"column",language:"prompt"},CATEGORISE_TEXT:{columns:"columns",categories:"prompt"},SENTIMENT_ANALYSIS:{column:"column"},PROMPT:{prompt:"prompt"},SEARCH_WEB:{columns:"columns"}};var Xe=(S=>(S.API_KEY="x-budibase-api-key",S.LICENSE_KEY="x-budibase-license-key",S.API_VER="x-budibase-api-version",S.APP_ID="x-budibase-app-id",S.SESSION_ID="x-budibase-session-id",S.TYPE="x-budibase-type",S.PREVIEW_ROLE="x-budibase-role",S.TENANT_ID="x-budibase-tenant-id",S.VERIFICATION_CODE="x-budibase-verification-code",S.RETURN_VERIFICATION_CODE="x-budibase-return-verification-code",S.RESET_PASSWORD_CODE="x-budibase-reset-password-code",S.RETURN_RESET_PASSWORD_CODE="x-budibase-return-reset-password-code",S.TOKEN="x-budibase-token",S.CSRF_TOKEN="x-csrf-token",S.CORRELATION_ID="x-budibase-correlation-id",S.AUTHORIZATION="authorization",S.MIGRATING_APP="x-budibase-migrating-app",S.COOKIE="cookie",S))(Xe||{});var OW={string:["string","options","longform","barcodeqr"],options:["options","string","longform","barcodeqr"],longform:["longform","string","options","barcodeqr"],barcodeqr:["barcodeqr","string","options","longform"],number:["number","boolean"],json:["json","array","attachment","attachment_single","bb_reference","signature_single"]};var CW="darkest",vW="light",YO=[{id:"light",name:"Light"},{id:"darkest",name:"Dark"},{id:"nord",name:"Nord",base:"darkest"},{id:"midnight",name:"Midnight",base:"darkest"}];var et={Equals:{value:"equal",label:"Equals"},NotEquals:{value:"notEqual",label:"Not equals"},Empty:{value:"empty",label:"Is empty"},NotEmpty:{value:"notEmpty",label:"Is not empty"},StartsWith:{value:"string",label:"Starts with"},Like:{value:"fuzzy",label:"Like"},MoreThan:{value:"rangeLow",label:"More than or equal to"},LessThan:{value:"rangeHigh",label:"Less than or equal to"},Contains:{value:"contains",label:"Contains"},NotContains:{value:"notContains",label:"Does not contain"},In:{value:"oneOf",label:"Is in"},ContainsAny:{value:"containsAny",label:"Has any"}},rg={integer:{max:2147483647,min:-2147483648},int:{max:2147483647,min:-2147483648},smallint:{max:32767,min:-32768},mediumint:{max:8388607,min:-8388608}};var Di="datasource_internal_bb_default";var Mr={};N(Mr,{ColumnSplitter:()=>lp,NoEmptyFilterStrings:()=>IT,buildQuery:()=>OT,cleanupQuery:()=>fp,fixupFilterArrays:()=>hp,getKeyNumbering:()=>mp,getValidOperatorsForType:()=>SC,hasFilters:()=>dp,limit:()=>RT,recurseLogicalOperators:()=>pp,removeKeyNumbering:()=>ru,runQuery:()=>Fu,search:()=>OC,sort:()=>xT,splitFiltersArray:()=>nu});var Qi=W(ng());var Ci={};N(Ci,{filterValueToLabel:()=>tx,hasSchema:()=>rx,isSupportedUserSearch:()=>sg,parallelForeach:()=>ex,processSearchFilters:()=>Wl,toMap:()=>ix,trimOtherProps:()=>nx,unreachable:()=>XO});var ig=W(require("lodash")),ZO=["field","operator","value","type","externalType","valueType","noValue","formulaType"];function XO(t,e){let r=e?.message||`No such case in exhaustive switch: ${t}`;if(!!!e?.doNotThrow)throw new Error(r)}async function ex(t,e,r){let n=[],i=0,s=async()=>{for(;i<t.length;){let o=i++,a=t[o];await e(a)}};for(let o=0;o<Math.min(r,t.length);o++)n.push(s());await Promise.all(n)}function tx(){return Object.keys(et).reduce((t,e)=>{let n=et[e];return t[n.value]=n.label,t},{})}function rx(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null&&!(t instanceof Date)&&Object.keys(t).length>0}function nx(t,e){return Object.keys(t).filter(n=>e.includes(n)).reduce((n,i)=>({...n,[i]:t[i]}),{})}function sg(t){let e=[{op:"string",key:"email"},{op:"equal",key:"_id"},{op:"oneOf",key:"_id"}],{allOr:r,onEmptyFilter:n,...i}=t;for(let[s,o]of Object.entries(i)){if(typeof o!="object")return!1;if(Ba(s)){for(let c of t[s].conditions)if(!sg(c))return!1;return!0}let a=Object.keys(o||{});if(a.length===0)continue;if(!e.find(c=>c.op===s&&a.length===1&&a[0]===c.key))return!1}return!0}function Wl(t){if(!t||t.length===0)return;let{allOr:e,onEmptyFilter:r,filters:n}=nu(t);return{logicalOperator:"all",onEmptyFilter:r||"all",groups:[{logicalOperator:e?"any":"all",filters:n.map(i=>{let s=ig.default.pick(i,ZO);return s.field=ru(s.field),s})}]}}function ix(t,e){return e.reduce((r,n)=>(r[n[t]]=n,r),{})}var jt={};N(jt,{cancelableTimeout:()=>og,cron:()=>ip,deepGet:()=>Ql,duplicateName:()=>yC,getSequentialName:()=>EC,getUserColor:()=>ox,getUserInitials:()=>sx,getUserLabel:()=>ax,isGoogleSheets:()=>cx,isSQL:()=>lx,lists:()=>cp,retry:()=>dx,roles:()=>up,schema:()=>Ao,views:()=>ap,wait:()=>jl,withTimeout:()=>ux});var Ql=(t,e)=>{if(!t||!e)return null;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];let r=e.split(".");for(let n=0;n<r.length;n++)t=t?.[r[n]];return t},sx=t=>{if(!t)return"?";let e="";return e+=t.firstName?t.firstName[0]:"",e+=t.lastName?t.lastName[0]:"",e!==""?e:t.email?.[0]||"U"},ox=t=>{let e=t?._id;if(!e)return"var(--spectrum-global-color-blue-400)";e=e.replace("ro_ta_users_","");let r=1;for(let n=0;n<e.length;n++)r+=e.charCodeAt(n),r=r%36;return`hsl(${r*10}, 50%, 40%)`},ax=t=>{if(!t)return"";let{firstName:e,lastName:r,email:n}=t;return e&&r?`${e} ${r}`:e||r||n};function og(t){let e;return[new Promise((r,n)=>{e=setTimeout(()=>{n({status:301,errno:"ETIME"})},t)}),()=>{clearTimeout(e)}]}async function ux(t,e){let[r,n]=og(t),i=await Promise.race([e(),r]);return n(),i}function cx(t){return t==="GOOGLE_SHEETS"}function lx(t){return!t||!t.source?!1:["POSTGRES","SQL_SERVER","MYSQL","ORACLE"].indexOf(t.source)!==-1||t.isSQL===!0}async function jl(t){return new Promise(e=>setTimeout(e,t))}async function dx(t,e){let{times:r=3}=e||{};if(r<1)throw new Error(`invalid retry count: ${r}`);let n;for(let i=0;i<r;i++){let s=1.5**i*1e3*(Math.random()+.5);await jl(s);try{return await t()}catch(o){n=o}}throw n}var ip={};N(ip,{getNextExecutionDates:()=>rC,validate:()=>nC});var ET=W(Vt()),TT=W(gT()),yT="(Input cron: ",eC={"smaller than lower limit":"less than","bigger than upper limit":"greater than",daysOfMonth:"'days of the month'",daysOfWeek:"'days of the week'",years:"'years'",months:"'months'",hours:"'hours'",minutes:"'minutes'",seconds:"'seconds'"};function tC(t){let e=[];for(let r of t){r.includes(yT)&&(r=r.split(yT)[0].trim());for(let[n,i]of Object.entries(eC))r.includes(n)&&(r=r.replace(new RegExp(n,"g"),i));e.push(r)}return e}function rC(t,e=4){let r=TT.default.parseExpression(t),n=[];for(let i=0;i<e;i++)n.push(r.next().toString());return n}function nC(t){let e=(0,ET.default)(t,{preset:"npm-cron-schedule",override:{useSeconds:!1}});return e.isValid()?{valid:!0}:{valid:!1,err:tC(e.getError())}}var Ao={};N(Ao,{decodeNonAscii:()=>sp,encodeNonAscii:()=>oC,isDeprecatedSingleUserColumn:()=>iC,isNumeric:()=>aC,isRequired:()=>sC});function iC(t){return t.type==="bb_reference"&&t.subtype==="user"&&t.constraints?.type!=="array"}function sC(t){return!!t&&(typeof t.presence!="boolean"&&t.presence?.allowEmpty===!1||t.presence===!0)}function oC(t){return t.split("").map(e=>e.charCodeAt(0)>127?"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"):e).join("")}function sp(t){return t.replace(/\\u([0-9a-fA-F]{4})/g,(e,r)=>String.fromCharCode(parseInt(r,16)))}function aC(t){return t.type==="number"||t.type==="bigint"}var ap={};N(ap,{basicFields:()=>pC,calculationFields:()=>dC,hasCalculationFields:()=>lC,isBasicViewField:()=>uC,isCalculationField:()=>So,isCalculationView:()=>cC,isV2:()=>fC,isVisible:()=>AT});var op=require("lodash");function So(t){return"calculationType"in t}function uC(t){return!So(t)}function cC(t){return t.type==="calculation"}function lC(t){return Object.values(t.schema||{}).some(So)}function dC(t){return(0,op.pickBy)(t.schema||{},So)}function AT(t){return t.visible!==!1}function pC(t,e){let{visible:r=!0}=e||{};return(0,op.pickBy)(t.schema||{},n=>!So(n)&&(!r||AT(n)))}function fC(t){return t.version===2}var up={};N(up,{checkForRoleInheritanceLoops:()=>hC});function mC(t){return`role${v}${t}`}function hC(t){let e=new Map;t.forEach(s=>{e.set(s._id,s)});let r=new Set,n=new Set;function i(s){let o=mC(s);if(n.has(s)||n.has(o))return!0;if(r.has(s)||r.has(o))return!1;n.add(s);let a=e.get(o)||e.get(s);if(!a)return n.delete(s),!1;let u=Array.isArray(a.inherits)?a.inherits:[a.inherits];for(let c of u)if(c&&i(c))return!0;return n.delete(s),r.add(s),!1}return!!t.find(s=>i(s._id))}var cp={};N(cp,{punctuateList:()=>gC});function gC(t){return t.length===0?"":t.length===1?t[0]:t.length===2?t.join(" and "):t.slice(0,-1).join(", ")+" and "+t[t.length-1]}var yC=(t,e)=>{let r=new RegExp("\\s(\\d+)$"),n=t.split(r)[0],i=new RegExp(`${n}\\s(\\d+)$`),s=[];e.filter(a=>{if(a===n)return!0;let u=a.match(i);return u?(s.push(parseInt(u[1])),!0):!1}),s.sort((a,u)=>a-u);let o;if(s.length===0)o=1;else{for(let a=0;a<s.length;a++)if(s[a]!==a+1){o=a+1;break}o||(o=s.length+1)}return`${n} ${o}`},EC=(t,e,{getName:r,numberFirstItem:n,separator:i=""}={})=>{if(!e?.length)return"";let s=e.trim(),o=n?`${e}1`:s;if(!t?.length)return o;let a=0;return t.forEach(u=>{let c=r?.(u)??u;if(typeof c!="string"||!c.startsWith(s))return;let l=c.split(s);if(l.length!==2)return;l[1].trim()===""&&(l[1]="1");let m=parseInt(l[1]);m>a&&(a=m)}),a===0?o:`${e}${i}${a+1}`};var Hn=require("lodash");var TC=/{{([^{].*?)}}/g,_T=Object.values(Ti),AC=[...Object.values(Ir),...Object.values(Jt),...Object.values(dn)],SC=(t,e,r)=>{let n=et,i=[n.Equals,n.NotEquals,n.StartsWith,n.Like,n.Empty,n.NotEmpty,n.In],s=[n.Equals,n.NotEquals,n.MoreThan,n.LessThan,n.Empty,n.NotEmpty,n.In],o=[],{type:a,formulaType:u}=t;a==="string"?o=i:a==="number"||a==="bigint"?o=s:a==="options"?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty,n.In]:a==="array"?o=[n.Contains,n.NotContains,n.Empty,n.NotEmpty,n.ContainsAny]:a==="boolean"?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty]:a==="longform"?o=i:a==="datetime"?o=s:a==="formula"&&u==="static"?o=i.concat([n.MoreThan,n.LessThan]):a==="ai"?o=i.concat([n.MoreThan,n.LessThan]):a==="bb_reference_single"||Ao.isDeprecatedSingleUserColumn(t)?o=[n.Equals,n.NotEquals,n.Empty,n.NotEmpty,n.In]:a==="bb_reference"?o=[n.Contains,n.NotContains,n.ContainsAny,n.Empty,n.NotEmpty]:a==="barcodeqr"&&(o=i);let c=r?.tableId?.includes("datasource_plus");return e==="_id"&&c&&(o=[n.Equals,n.NotEquals,n.In]),o},IT=[et.StartsWith.value,et.Like.value,et.Equals.value,et.NotEquals.value,et.Contains.value,et.NotContains.value,et.ContainsAny.value,et.In.value];function pp(t,e){for(let r of _T)t[r]&&(t[r].conditions=t[r].conditions.map(n=>e(n)));return t}var fp=t=>{for(let e of IT)if(t[e])for(let r of Object.keys(t)){if(r!==e)continue;if(typeof t[r]=="object")for(let[i,s]of Object.entries(t[r]))(s==null||s===""||_C(s))&&delete t[e][i]}return t=pp(t,fp),t};function _C(t){return Array.isArray(t)&&t.length===0}var ru=t=>mp(t).key,mp=t=>{if(typeof t=="string"&&t.match(/\d[0-9]*:/g)!=null){let e=t.split(":");return{prefix:`${e.shift()}:`,key:e.join(":")}}else return{key:t}},lp=class{constructor(e,r){if(this.tableNames=e.map(n=>n.name),this.tableIds=e.map(n=>n._id),this.relationshipColumnNames=e.flatMap(n=>Object.keys(n.schema).filter(i=>n.schema[i].type==="link")),this.relationships=this.tableNames.concat(this.tableIds).concat(this.relationshipColumnNames).sort((n,i)=>i.length-n.length),r?.aliases){this.aliases={};for(let[n,i]of Object.entries(r.aliases))this.aliases[i]=n}this.columnPrefix=r?.columnPrefix}run(e){let{prefix:r,key:n}=mp(e),i;if(this.aliases)for(let o of Object.keys(this.aliases||{})){let a=`${o}.`;n.startsWith(a)&&(i=this.aliases[o],n=n.slice(a.length))}let s;for(let o of this.relationships){let a=`${o}.`;if(n.startsWith(a)){let u=n.split(a);u.shift(),s=a,n=u.join(".");break}}return this.columnPrefix&&n.startsWith(this.columnPrefix)&&(n=sp(n.slice(this.columnPrefix.length))),{tableName:i,numberPrefix:r,relationshipPrefix:s,column:n}}};function IC(t){if(!t||!t?.operator||!t?.field)return;let e={},{operator:r,field:n,type:i,externalType:s}=t,{value:o}=t;(r==="empty"||r==="notEmpty")&&(o=null);let a=typeof o=="string"&&(o.match(TC)||[]).length>0;switch(i){case"datetime":if(!a&&r!=="empty"&&r!=="notEmpty"){if(!o)return;if(typeof o=="string")o=new Date(o).toISOString();else if(Ga(r))return e[r]??={},e[r][n]=o,e}break;case"number":typeof o=="string"&&!a&&(r==="oneOf"?o=o.split(",").map(parseFloat):o=parseFloat(o));break;case"boolean":o=`${o}`.toLowerCase()==="true";break;case"array":["contains","notContains","containsAny"].includes(r.toLocaleString())&&typeof o=="string"&&(o=o.split(","));break}if(Ga(r)){let c=rg[s]||{min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER};e[r]??={},e[r][n]={low:i==="number"?c.min:"0000-00-00T00:00:00.000Z",high:i==="number"?c.max:"9999-00-00T00:00:00.000Z"}}else if(r==="rangeHigh"&&o!=null&&o!=="")e.range??={},e.range[n]={...e.range[n],high:o};else if(r==="rangeLow"&&o!=null&&o!=="")e.range??={},e.range[n]={...e.range[n],low:o};else if(Lh(r)||Uh(r)||Ga(r))i==="boolean"?r==="equal"&&o===!1?(e.notEqual=e.notEqual||{},e.notEqual[n]=!0):r==="notEqual"&&o===!1?(e.equal=e.equal||{},e.equal[n]=!0):(e[r]??={},e[r][n]=o):(e[r]??={},e[r][n]=o);else throw new Error(`Unsupported operator: ${r}`);return e}function nu(t){let e={filters:[]};for(let r of t)"operator"in r&&r.operator==="allOr"?e.allOr=!0:"onEmptyFilter"in r?e.onEmptyFilter=r.onEmptyFilter:e.filters.push(r);return e}function OT(t){if(!t)return{};if(Array.isArray(t)&&(t=Wl(t),!t))return{};let e={};t.onEmptyFilter?e.onEmptyFilter=t.onEmptyFilter:e.onEmptyFilter="all";let r=ST(t.logicalOperator||"all");return e[r]={conditions:(t.groups||[]).map(n=>{if(n.groups){let u=OT(n);return delete u.onEmptyFilter,u}let{allOr:i,onEmptyFilter:s,filters:o}=nu(n.filters||[]);s&&(e.onEmptyFilter=s);let a=i?"$or":"$and";return n.logicalOperator&&(a=ST(n.logicalOperator)),{[a]:{conditions:o.map(IC).filter(u=>u)}}})},e}function ST(t){return t==="all"?"$and":"$or"}function hp(t){if(!t)return t;for(let e of Object.values(Jt)){let r=t[e];if(!(r==null||!(0,Hn.isPlainObject)(r)))for(let n of Object.keys(r)){if(Array.isArray(r[n]))continue;let i=r[n];typeof i=="string"?r[n]=i.split(",").map(s=>s.trim()):r[n]=[i]}}return pp(t,hp),t}function OC(t,e){let r=Fu(t,e.query);e.sort&&(r=xT(r,e.sort,e.sortOrder||"ascending",e.sortType));let n=r.length;e.limit&&(r=RT(r,e.limit.toString()));let i={rows:r};return e.countRows&&(i.totalRows=n),i}function Fu(t,e){if(!t||!Array.isArray(t))return[];if(!e)return t;if(e=fp(e),e=hp(e),!dp(e)&&e.onEmptyFilter==="none")return[];let r=(T,_)=>B=>{for(let[b,k]of Object.entries(e[T]||{})){let de=Ba(T)?B:Ql(B,ru(b)),un=_(de,k);if(e.allOr&&un)return!0;if(!e.allOr&&!un)return!1}return!e.allOr},n=r("string",(T,_)=>typeof T!="string"||typeof _!="string"?!1:T.toLowerCase().startsWith(_.toLowerCase())),i=r("fuzzy",(T,_)=>typeof T!="string"||typeof _!="string"?!1:T.toLowerCase().includes(_.toLowerCase())),s=r("range",(T,_)=>{if(T==null||T===""||((0,Hn.isPlainObject)(_.low)&&(0,Hn.isEmpty)(_.low)&&(_.low=void 0),(0,Hn.isPlainObject)(_.high)&&(0,Hn.isEmpty)(_.high)&&(_.high=void 0),_.low==null&&_.high==null))return!1;let B=+T;if(!isNaN(B)){let k=+_.low,de=+_.high;if(!isNaN(k)&&!isNaN(de))return B>=k&&B<=de;if(isNaN(k)){if(!isNaN(de))return B<=de}else return B>=k}let b=(0,Qi.default)(T);if(b.isValid()){let k=(0,Qi.default)(_.low||"0000-00-00T00:00:00.000Z"),de=(0,Qi.default)(_.high||"9999-00-00T00:00:00.000Z");if(k.isValid()&&de.isValid())return b.isAfter(k)&&b.isBefore(de)||b.isSame(k)||b.isSame(de);if(k.isValid())return b.isAfter(k)||b.isSame(k);if(de.isValid())return b.isBefore(de)||b.isSame(de)}return _.low!=null&&_.high!=null?T>=_.low&&T<=_.high:_.low!=null?T>=_.low:_.high!=null?T<=_.high:!1}),o=(T,_)=>{if(Array.isArray(T)){for(let b of T)if(o(b,_))return!0;return!1}if(T&&typeof T=="object"&&typeof _=="string")return T._id===_;if(T===_)return!0;if(T==null&&_!=null||T!=null&&_==null)return!1;let B=(0,Qi.default)(T);if(B.isValid()){let b=(0,Qi.default)(_);if(b.isValid())return B.isSame(b)}return!1},a=T=>(..._)=>!T(..._),u=r("equal",o),c=r("notEqual",a(o)),l=T=>typeof T=="string"?T==="":Array.isArray(T)?T.length===0:T&&typeof T=="object"?Object.keys(T).length===0:T==null,m=r("empty",l),p=r("notEmpty",a(l)),f=r("oneOf",(T,_)=>(typeof _=="string"&&(_=_.split(",")),typeof T=="number"&&(_=_.map(B=>parseFloat(B))),Array.isArray(_)?_.some(B=>o(T,B)):!1)),d=T=>(_,B)=>!Array.isArray(_)||(typeof B=="string"&&(B=B.split(","),typeof _[0]=="number"&&(B=B.map(b=>parseFloat(b)))),!Array.isArray(B))?!1:B.length===0?!0:B[T](b=>o(_,b)),g=r("contains",(T,_)=>Array.isArray(_)&&_.length===0?!0:d("every")(T,_)),E=r("notContains",(T,_)=>Array.isArray(_)&&_.length===0?!0:a(d("every"))(T,_)),y=r("containsAny",d("some")),S=r("$and",(T,_)=>{if(!_.length)return!1;for(let B of _)if(!Fu([T],B).length)return!1;return!0}),O=r("$or",(T,_)=>{if(!_.length)return!1;for(let B of _)if(Fu([T],{...B,allOr:!0}).length)return!0;return!1}),R=T=>{let _={string:n,fuzzy:i,range:s,equal:u,notEqual:c,empty:m,notEmpty:p,oneOf:f,contains:g,containsAny:y,notContains:E,$and:S,$or:O},B=Object.entries(e||{}).filter(([b,k])=>!["allOr","onEmptyFilter"].includes(b)&&k&&Object.keys(k).length>0).map(([b])=>_[b]?.(T)??!1);return dp(e)?e.allOr?B.some(b=>b===!0):B.every(b=>b===!0):!0};return t.filter(R)}function xT(t,e,r,n="string"){if(!e||!r||!n)return t;let i=s=>s==null?s:n==="string"?`${s}`:parseFloat(s);return t.slice().sort((s,o)=>{let a=i(s[e]),u=i(o[e]),c=u==null||a>u?1:-1;return r.toLowerCase()==="descending"?c*-1:c})}function RT(t,e){let r=typeof e=="number"?e:parseFloat(e);return isNaN(r)?t:t.slice(0,r)}var dp=t=>{if(!t)return!1;let e=r=>{for(let n of _T)if(r[n])for(let i of r[n]?.conditions||[]){let s=e(i);if(s)return s}for(let n of AC){let i=r[n];if(!i||typeof i!="object")continue;if(Object.entries(i).filter(o=>{let a=o[1]!==void 0||o[1]!==null||o[1]!=="";return n==="notEmpty"||a}).length!==0)return!0}return!1};return e(t)};var ot={};N(ot,{applications:()=>yp,automations:()=>Ep,screens:()=>Ip,users:()=>_p});var yp={};N(yp,{getDevAppID:()=>xC,getProdAppID:()=>ku});var gp=Or("app"),_o=Or("app_dev");function xC(t){if(!t)throw new Error("No app ID provided");if(t.startsWith(_o))return t;let e=t.split(gp);e.shift();let r=e.join(gp);return`${_o}${r}`}function ku(t){if(!t)throw new Error("No app ID provided");if(!t.startsWith(_o))return t;let e=t.split(_o);e.shift();let r=e.join(_o);return`${gp}${r}`}var Ep={};N(Ep,{isAppAction:()=>bC,isRowAction:()=>RC,isWebhookAction:()=>wC});function RC(t){return t.definition.trigger?.stepId==="ROW_ACTION"}function wC(t){return t.definition.trigger?.stepId==="WEBHOOK"}function bC(t){return t.definition.trigger?.stepId==="APP"}var _p={};N(_p,{canCreateApps:()=>DC,containsUserID:()=>UC,getGlobalUserID:()=>LC,getUserAppGroups:()=>MC,getUserGroups:()=>Sp,hasAdminPermissions:()=>Ap,hasAppBuilderPermissions:()=>$u,hasAppCreatorPermissions:()=>wT,hasBuilderPermissions:()=>NC,hasCreatorPermissions:()=>Vu,isAdmin:()=>Gu,isAdminOrBuilder:()=>CC,isAdminOrGlobalBuilder:()=>vC,isBuilder:()=>Tp,isCreator:()=>PC,isGlobalBuilder:()=>Bu,userAppAccessList:()=>FC});var Fr=W(require("lodash/fp"));function Tp(t,e){return t?t.builder?.global?!0:!!(e&&t.builder?.apps?.includes(ku(e))):!1}function Bu(t){return Tp(t)&&!$u(t)||Gu(t)}function DC(t){return Bu(t)||Vu(t)}function Gu(t){return t?Ap(t):!1}function CC(t,e){return Tp(t,e)||Gu(t)}function vC(t){return Bu(t)||Gu(t)}function $u(t){if(!t)return!1;let e=t.builder?.apps?.length;return!!!t.builder?.global&&e!=null&&e>0}function wT(t){return t?Fr.flow(Fr.get("roles"),Fr.values,Fr.find(e=>["CREATOR"].includes(e)),e=>!!e)(t):!1}function NC(t){return t?t.builder?.global||$u(t)||Vu(t):!1}function Ap(t){return t?!!t.admin?.global:!1}function Vu(t){return t?!!t.builder?.creator:!1}function PC(t){return t?Bu(t)||Ap(t)||Vu(t)||$u(t)||wT(t):!1}function LC(t){if(typeof t!="string")return t;let e=`ro${v}ta_users${v}`;return t.startsWith(e)?t.split(e)[1]:t}function UC(t){return typeof t!="string"?!1:t.includes(`us${v}`)}function Sp(t,e){return e?.filter(r=>r.users?.find(n=>n._id===t._id))||[]}function MC(t,e,r){let n=ku(t);return Sp(e,r).filter(s=>Object.keys(s.roles||{}).find(o=>o===n))}function FC(t,e){let n=Sp(t,e).flatMap(s=>Object.keys(s.roles||{})),i=[...Object.keys(t?.roles||{}),...n];return[...new Set(i)]}var Ip={};N(Ip,{findInSettings:()=>kC});function kC(t,e){let r=[];function n(i,s=""){for(let[o,a]of Object.entries(i))a&&(typeof a=="string"&&a.includes(e)?r.push({setting:s?`${s}.${o}`:o,value:a}):typeof a=="object"&&n(a,o))}return n(t.props),r}var $j={string:!0,longform:!0,options:!0,number:!0,datetime:!0,formula:!0,ai:!0,auto:!0,internal:!0,barcodeqr:!0,bigint:!0,boolean:!1,array:!1,attachment:!1,attachment_single:!1,signature_single:!1,link:!1,json:!1,bb_reference:!1,bb_reference_single:!1},Vj={string:!0,longform:!0,options:!0,number:!0,datetime:!0,auto:!0,internal:!0,barcodeqr:!0,bigint:!0,boolean:!0,json:!0,formula:!1,ai:!1,attachment:!1,attachment_single:!1,signature_single:!1,array:!1,link:!1,bb_reference:!1,bb_reference_single:!1},qj={number:!0,json:!0,datetime:!0,longform:!0,string:!0,options:!0,array:!0,bigint:!0,boolean:!0,auto:!1,internal:!1,barcodeqr:!1,formula:!1,ai:!1,attachment:!1,attachment_single:!1,signature_single:!1,link:!1,bb_reference:!0,bb_reference_single:!0};var zj={name:"Bash Scripting",tagline:"Execute a bash command",icon:"git-branch",description:"Run a bash script",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"EXECUTE_BASH",inputs:{},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{stdout:{type:"string",description:"Standard output of your bash command or script"},success:{type:"boolean",description:"Whether the command was successful"}},required:["stdout"]}}};var eH={name:"Branch",icon:"git-branch",tagline:"Branch from this step",description:"Branching",stepId:"BRANCH",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{branches:{properties:{name:{type:"string"},condition:{customType:"filters"}}},children:{type:"array"}},required:["conditions"]},outputs:{properties:{branchName:{type:"string"},status:{type:"string",description:"Branch result"},branchId:{type:"string",description:"Branch ID"},success:{type:"boolean",description:"Branch success"}},required:["output"]}},type:"LOGIC"};var nH={name:"Collect Data",tagline:"Collect data to be sent to design",icon:"stack",description:"Collects specified data so it can be provided to the design section",type:"ACTION",internal:!0,features:{},stepId:"COLLECT",inputs:{},schema:{inputs:{properties:{collection:{type:"string",title:"What to Collect"}},required:["collection"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},value:{type:"string",description:"Collected data"}},required:["success","value"]}}};var oH={name:"Create Row",tagline:"Create a {{inputs.enriched.table.name}} row",icon:"rows-plus-bottom",description:"Add a row to your database",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"CREATE_ROW",inputs:{},schema:{inputs:{properties:{row:{type:"object",properties:{tableId:{type:"string",customType:"table"}},customType:"row",title:"Table",required:["tableId"]}},required:["row"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The new row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the row creation was successful"},id:{type:"string",description:"The identifier of the new row"},revision:{type:"string",description:"The revision of the new row"}},required:["success","id","revision"]}}};var cH={name:"Delay",icon:"clock",tagline:"Delay for {{inputs.time}} milliseconds",description:"Delay the automation until an amount of time has passed",stepId:"DELAY",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{time:{type:"number",title:"Delay in milliseconds"}},required:["time"]},outputs:{properties:{success:{type:"boolean",description:"Whether the delay was successful"}},required:["success"]}},type:"LOGIC"};var pH={description:"Delete a row from your database",icon:"trash-simple",name:"Delete Row",tagline:"Delete a {{inputs.enriched.table.name}} row",type:"ACTION",stepId:"DELETE_ROW",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},id:{type:"string",title:"Row ID"}},required:["tableId","id"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The deleted row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the deletion was successful"}},required:["row","success"]}}};var hH={name:"Discord Message",tagline:"Send a message to a Discord server",description:"Send a message to a Discord server",icon:"ri-discord-line",stepId:"discord",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Discord Webhook URL"},username:{type:"string",title:"Bot Name"},avatar_url:{type:"string",title:"Bot Avatar URL"},content:{type:"string",title:"Message"}},required:["url","content"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},response:{type:"string",description:"The response from the Discord Webhook"},success:{type:"boolean",description:"Whether the message sent successfully"}}}}};var EH={name:"External Data Connector",tagline:"Execute Data Connector",icon:"database",description:"Execute a query in an external data connector",type:"ACTION",stepId:"EXECUTE_QUERY",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{query:{type:"object",properties:{queryId:{type:"string",customType:"query"}},customType:"queryParams",title:"Parameters",required:["queryId"]}},required:["query"]},outputs:{properties:{response:{type:"object",description:"The response from the datasource execution"},info:{type:"object",description:"Some query types may return extra data, like headers from a REST query"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var SH={name:"API Request",tagline:"Execute a REST request",icon:"globe",description:"Execute a HTTP query from a REST datasource",type:"ACTION",stepId:"API_REQUEST",internal:!0,new:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{query:{type:"object",properties:{queryId:{type:"string"}},customType:"queryParams",title:"Parameters",required:["queryId"]}},required:["query"]},outputs:{properties:{response:{type:"object",description:"The response from the datasource execution"},info:{type:"object",description:"Some query types may return extra data, like headers from a REST query"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var OH={name:"JS Scripting",tagline:"Execute JavaScript Code",deprecated:!0,icon:"code",description:"Run a piece of JavaScript code in your automation",type:"ACTION",internal:!0,stepId:"EXECUTE_SCRIPT",inputs:{},features:{LOOPING:!0},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{value:{type:"string",description:"The result of the return statement"},success:{type:"boolean",description:"Whether the action was successful"}},required:["success"]}}};var wH={name:"JavaScript",tagline:"Execute JavaScript Code",icon:"brackets-angle",description:"Run a piece of JavaScript code in your automation",type:"ACTION",internal:!0,new:!1,stepId:"EXECUTE_SCRIPT_V2",inputs:{},features:{LOOPING:!0},schema:{inputs:{properties:{code:{type:"string",customType:"code",title:"Code"}},required:["code"]},outputs:{properties:{value:{type:"string",description:"The result of the return statement"},success:{type:"boolean",description:"Whether the action was successful"}},required:["success"]}}};var JC={EQUAL:"Equals",NOT_EQUAL:"Not equals",GREATER_THAN:"Greater than",LESS_THAN:"Less than"},CH={name:"Condition",tagline:"{{inputs.field}} {{inputs.condition}} {{inputs.value}}",icon:"git-branch",description:"Conditionally halt automations which do not meet certain conditions",type:"LOGIC",internal:!0,features:{},stepId:"FILTER",inputs:{condition:"EQUAL"},schema:{inputs:{properties:{field:{type:"string",title:"Reference Value"},condition:{type:"string",title:"Condition",enum:Object.values(Pl),pretty:Object.values(JC)},value:{type:"string",title:"Comparison Value"}},required:["field","condition","value"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},result:{type:"boolean",description:"Whether the logic block passed"}},required:["success","result"]}}};var PH={name:"Looping",icon:"recycle",tagline:"Loop the block",description:"Loop",stepId:"LOOP",internal:!0,features:{},inputs:{},schema:{inputs:{properties:{option:{customType:"loopOption",title:"Input type"},binding:{type:"string",title:"Binding / Value"},iterations:{type:"number",title:"Max loop iterations"},failure:{type:"string",title:"Failure Condition"}},required:["type","value","iterations","failure"]},outputs:{properties:{items:{customType:"item",description:"The item currently being executed"},success:{type:"boolean",description:"Whether the message loop was successfully"},iterations:{type:"number",description:"The amount of times the block ran"}},required:["success","items","iterations"]}},type:"LOGIC"};var MH={name:"Make Integration",stepTitle:"Make",tagline:"Trigger a Make scenario",description:"Performs a webhook call to Make and gets the response (if configured)",icon:"ri-shut-down-line",stepId:"integromat",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},body:{type:"json",title:"Payload"}},required:["url","body"]},outputs:{properties:{success:{type:"boolean",description:"Whether call was successful"},httpStatus:{type:"number",description:"The HTTP status code returned"},response:{type:"object",description:"The webhook response - this can have properties"}},required:["success","response"]}}};var BH={name:"n8n Integration",stepTitle:"n8n",tagline:"Trigger an n8n workflow",description:"Performs a webhook call to n8n and gets the response (if configured)",icon:"ri-shut-down-line",stepId:"n8n",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},method:{type:"string",title:"Method",enum:Object.values(Ll)},authorization:{type:"string",title:"Authorization"},body:{type:"json",title:"Payload"}},required:["url","method"]},outputs:{properties:{success:{type:"boolean",description:"Whether call was successful"},httpStatus:{type:"number",description:"The HTTP status code returned"},response:{type:"object",description:"The webhook response - this can have properties"}},required:["success","response"]}}};var bT=(i=>(i.GPT_4O_MINI="gpt-4o-mini",i.GPT_4O="gpt-4o",i.GPT_4="gpt-4",i.GPT_35_TURBO="gpt-3.5-turbo",i))(bT||{}),VH={name:"OpenAI",tagline:"Send prompts to ChatGPT",icon:"flow-arrow",description:"Interact with the OpenAI ChatGPT API.",type:"ACTION",internal:!0,features:{},deprecated:!1,stepId:"OPENAI",inputs:{prompt:""},schema:{inputs:{properties:{prompt:{type:"string",title:"Prompt"},model:{type:"string",title:"Model",enum:Object.values(bT)}},required:["prompt","model"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was output"}},required:["success","response"]}}};var DT=(s=>(s.POST="POST",s.GET="GET",s.PUT="PUT",s.DELETE="DELETE",s.PATCH="PATCH",s))(DT||{}),QH={deprecated:!0,name:"Outgoing webhook",tagline:"Send a {{inputs.requestMethod}} request",icon:"paper-plane-right",description:"Send a request of specified method to a URL",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"OUTGOING_WEBHOOK",inputs:{requestMethod:"POST",url:"http://",requestBody:"{}",headers:"{}"},schema:{inputs:{properties:{requestMethod:{type:"string",enum:Object.values(DT),title:"Request method"},url:{type:"string",title:"URL"},requestBody:{type:"string",title:"JSON Body",customType:"wide"},headers:{type:"string",title:"Headers",customType:"wide"}},required:["requestMethod","url"]},outputs:{properties:{response:{type:"object",description:"The response from the webhook"},httpStatus:{type:"number",description:"The HTTP status code returned"},success:{type:"boolean",description:"Whether the action was successful"}},required:["response","success"]}}};var nv={ascending:"Ascending",descending:"Descending"},KH={description:"Query rows from the database",icon:"magnifying-glass",name:"Query rows",tagline:"Query rows from {{inputs.enriched.table.name}} table",type:"ACTION",stepId:"QUERY_ROWS",internal:!0,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"filters",title:"Filtering"},sortColumn:{type:"string",title:"Sort Column",customType:"column"},sortOrder:{type:"string",title:"Sort Order",enum:Object.values(bn),pretty:Object.values(nv)},limit:{type:"number",title:"Limit",customType:"queryLimit"}},required:["tableId"]},outputs:{properties:{rows:{type:"array",customType:"rows",description:"The rows that were found"},success:{type:"boolean",description:"Whether the query was successful"}},required:["rows","success"]}}};var zH={description:"Send an email using SMTP",tagline:"Send SMTP email to {{inputs.to}}",icon:"envelope",name:"Send Email (SMTP)",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"SEND_EMAIL_SMTP",inputs:{},schema:{inputs:{properties:{to:{type:"string",title:"Send To"},from:{type:"string",title:"Send From"},cc:{type:"string",title:"CC"},bcc:{type:"string",title:"BCC"},subject:{type:"string",title:"Email Subject"},contents:{type:"longform",title:"Message",description:"Use markdown or HTML for rich text formatting: **bold**, _italics_, # Headings, * Bullets, <br> for line breaks, and more."},addInvite:{type:"boolean",title:"Add calendar invite"},startTime:{type:"date",title:"Start Time",dependsOn:"addInvite"},endTime:{type:"date",title:"End Time",dependsOn:"addInvite"},summary:{type:"string",title:"Meeting Summary",dependsOn:"addInvite"},location:{type:"string",title:"Location",dependsOn:"addInvite"},attachments:{type:"attachment",customType:"multi_attachments",title:"Attachments"}},required:["to","from","subject","contents"]},outputs:{properties:{success:{type:"boolean",description:"Whether the email was sent"},response:{type:"object",description:"A response from the email client, this may be an error"}},required:["success"]}}};var eK={name:"Backend log",tagline:"Console log a value in the backend",icon:"activity",description:"Logs the given text to the server (using console.log)",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"SERVER_LOG",inputs:{text:""},schema:{inputs:{properties:{text:{type:"string",title:"Log"}},required:["text"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},message:{type:"string",description:"What was output"}},required:["success","message"]}}};var nK={name:"Slack Message",tagline:"Send a message to Slack",description:"Send a message to Slack",icon:"ri-slack-line",stepId:"slack",type:"ACTION",internal:!1,features:{LOOPING:!0},inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Incoming Webhook URL"},text:{type:"string",title:"Message"}},required:["url","text"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},success:{type:"boolean",description:"Whether the message sent successfully"},response:{type:"string",description:"The response from the Slack Webhook"}}}}};var oK={name:"Trigger an automation",tagline:"Triggers an automation synchronously",icon:"arrows-clockwise",description:"Triggers an automation synchronously",type:"ACTION",internal:!0,features:{},stepId:"TRIGGER_AUTOMATION_RUN",inputs:{},schema:{inputs:{properties:{automation:{type:"object",properties:{automationId:{type:"string",customType:"automation"}},customType:"automationFields",title:"Automation Fields",required:["automationId"]},timeout:{type:"number",title:"Timeout (ms)"}},required:["automationId"]},outputs:{properties:{success:{type:"boolean",description:"Whether the automation was successful"},value:{type:"object",description:"Automation Result"}},required:["success","value"]}}};var cK={name:"Update Row",tagline:"Update a {{inputs.enriched.table.name}} row",icon:"arrow-clockwise",description:"Update a row in your database",type:"ACTION",internal:!0,features:{LOOPING:!0},stepId:"UPDATE_ROW",inputs:{},schema:{inputs:{properties:{meta:{type:"object",title:"Field settings"},row:{type:"object",customType:"row",title:"Table"},rowId:{type:"string",title:"Row ID"}},required:["row","rowId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The updated row"},response:{type:"object",description:"The response from the table"},success:{type:"boolean",description:"Whether the action was successful"},id:{type:"string",description:"The identifier of the updated row"},revision:{type:"string",description:"The revision of the updated row"}},required:["success","id","revision"]}}};var pK={name:"Zapier Webhook",stepId:"zapier",type:"ACTION",internal:!1,features:{LOOPING:!0},description:"Trigger a Zapier Zap via webhooks",tagline:"Trigger a Zapier Zap",icon:"ri-flashlight-line",inputs:{},schema:{inputs:{properties:{url:{type:"string",title:"Webhook URL"},body:{type:"json",title:"Payload"}},required:["url"]},outputs:{properties:{httpStatus:{type:"number",description:"The HTTP status code of the request"},response:{type:"string",description:"The response from Zapier"}}}}};var hK={name:"Classify Text",icon:"PageTag",tagline:"Classify text into predefined categories using AI",description:"Analyzes text and assigns it to one of the categories you provide.",stepId:"CLASSIFY_CONTENT",internal:!0,inputs:{},schema:{inputs:{properties:{textInput:{type:"longform",title:"Text",description:"The text content you want the AI to classify."},categoryItems:{type:"array",customType:"categories",title:"Categories",description:"Add categories for the AI to use when classifying text."}},required:["textInput","categoryItems"]},outputs:{properties:{category:{type:"string",description:"The category assigned by the AI."},success:{type:"boolean",description:"Whether the classification was successful."}},required:["category","success"]}},type:"ACTION"};var EK={name:"LLM Prompt",tagline:"Send prompts to LLM",icon:"Algorithm",description:"Interact with an LLM.",type:"ACTION",internal:!0,features:{},stepId:"PROMPT_LLM",inputs:{prompt:""},schema:{inputs:{properties:{prompt:{type:"longform",title:"Prompt"}},required:["prompt","model"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was output"}},required:["success","response"]}}};var SK={name:"Translate",tagline:"Translate text to a different language",icon:"globe",description:"Translate text to a different language.",type:"ACTION",internal:!0,features:{},stepId:"TRANSLATE",inputs:{prompt:""},schema:{inputs:{properties:{text:{type:"string",title:"Text"},language:{type:"string",title:"Language"}},required:["text","language"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was the translated text"}},required:["success","response"]}}};var CT=(n=>(n.SHORT="Short",n.MEDIUM="Medium",n.LONG="Long",n))(CT||{}),OK={name:"Summarise",tagline:"Summarise text",icon:"Summarize",description:"Summarise text.",type:"ACTION",internal:!0,features:{},stepId:"SUMMARISE",inputs:{prompt:""},schema:{inputs:{properties:{text:{type:"longform",title:"Text"},length:{type:"string",title:"Length",enum:Object.values(CT)}},required:["text","length"]},outputs:{properties:{success:{type:"boolean",description:"Whether the action was successful"},response:{type:"string",description:"What was the summarised text"}},required:["success","response"]}}};var wK={name:"Generate Text",icon:"Edit",tagline:"Generate contentusing AI",description:"Uses AI to generate text content based on your instructions and chosen format",stepId:"GENERATE_TEXT",internal:!0,inputs:{contentType:"document"},schema:{inputs:{properties:{contentType:{type:"string",title:"Content type",enum:Object.values(Cl),pretty:Object.values(Bh)},instructions:{type:"longform",title:"Instructions",description:"Provide guidance to help the AI produce content in the format that you want"}},required:["contentType","instructions"]},outputs:{properties:{generatedText:{type:"string",description:"The text content generated by the AI"},success:{type:"boolean",description:"Whether the text generation was successful"}},required:["generatedText","success"]}},type:"ACTION"};var CK={name:"Extract Document Data",icon:"Document",tagline:"Extract structured data from documents using AI",description:"Extracts structured data from PDF or image according to provided schema.",stepId:"EXTRACT_FILE_DATA",internal:!0,inputs:{},schema:{inputs:{properties:{file:{type:"string",title:"Document",description:"Attachment or Link to the document to extract data from."},source:{type:"string",enum:Object.values(vl),title:"Source",description:"The source of the document to extract data from."},fileType:{dependsOn:{field:"source",value:"URL"},type:"string",enum:Object.values(Nl),title:"File Type",description:"The type of file at the URL."},schema:{customType:"triggerSchema",title:"Data schema",description:'Schema defining the structure of data to extract. Example: {"name": "string", "price": "number"}.'}},required:["file","schema"]},outputs:{properties:{data:{type:"json",description:"The structured data extracted from the document."},success:{type:"boolean",description:"Whether the extraction was successful."}},required:["data","success"]}},type:"ACTION"};var Ev={name:"User action",event:"app:trigger",icon:"cursor-click",tagline:"Automation fired from the frontend",description:"Trigger an automation from an action inside your app",stepId:"APP",inputs:{},schema:{inputs:{properties:{fields:{type:"object",customType:"triggerSchema",title:"Fields"}},required:[]},outputs:{properties:{fields:{type:"object",description:"Fields submitted from the app frontend",customType:"triggerSchema"}},required:["fields"]}},type:"TRIGGER"};var Av={name:"CRON / Schedule",event:"cron:trigger",icon:"clock",tagline:"Cron Trigger (<b>{{inputs.cron}}</b>)",description:"Triggers automation on a cron schedule.",stepId:"CRON",inputs:{},schema:{inputs:{properties:{cron:{type:"string",customType:"cron",title:"Expression"}},required:["cron"]},outputs:{properties:{timestamp:{type:"number",description:"Timestamp the cron was executed"}},required:["timestamp"]}},type:"TRIGGER"};var _v={name:"Row Deleted",event:"row:delete",icon:"trash-simple",tagline:"Row is deleted from {{inputs.enriched.table.name}}",description:"Fired when a row is deleted from your database",stepId:"ROW_DELETED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"}},required:["tableId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The row that was deleted"}},required:["row"]}},type:"TRIGGER"};var Ov={name:"Row Created",event:"row:save",icon:"rows-plus-bottom",tagline:"Row is added to {{inputs.enriched.table.name}}",description:"Fired when a row is added to your database",stepId:"ROW_SAVED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"trigger_filter",title:"Filtering"}},required:["tableId"]},outputs:{properties:{row:{type:"object",customType:"row",description:"The new row that was created"},id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"}},required:["row","id"]}},type:"TRIGGER"};var Rv={name:"Row Updated",event:"row:update",icon:"arrow-clockwise",tagline:"Row is updated in {{inputs.enriched.table.name}}",description:"Fired when a row is updated in your database",stepId:"ROW_UPDATED",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table"},filters:{type:"object",customType:"trigger_filter",title:"Filtering"}},required:["tableId"]},outputs:{properties:{oldRow:{type:"object",customType:"row",description:"The row that was updated",title:"Old Row"},row:{type:"object",customType:"row",description:"The row before it was updated",title:"Row"},id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"}},required:["row","id"]}},type:"TRIGGER"};var bv={name:"Webhook",event:"web:trigger",icon:"paper-plane-right",tagline:"Webhook endpoint is hit",description:"Trigger an automation when a HTTP POST webhook is hit",stepId:"WEBHOOK",inputs:{},schema:{inputs:{properties:{schemaUrl:{type:"string",customType:"webhookUrl",title:"Schema URL"},triggerUrl:{type:"string",customType:"webhookUrl",title:"Trigger URL"}},required:["schemaUrl","triggerUrl"]},outputs:{properties:{body:{type:"object",description:"Body of the request which hit the webhook"}},required:["body"]}},type:"TRIGGER"};var Cv={type:"TRIGGER",name:"Row Action",event:"row:action",icon:"tree-structure",tagline:"Row action triggered in {{inputs.enriched.table.name}} by {{inputs.enriched.row._id}}",description:"row action workflow",stepId:"ROW_ACTION",inputs:{},schema:{inputs:{properties:{tableId:{type:"string",customType:"table",title:"Table",readonly:!0}},required:["tableId"]},outputs:{properties:{id:{type:"string",description:"Row ID - can be used for updating"},revision:{type:"string",description:"Revision of row"},table:{type:"object",customType:"table",title:"The table linked to the row action"},row:{type:"object",customType:"row",description:"The row linked to the row action"}}}}};var jK=Object.values(ye).sort((t,e)=>e.length-t.length);var HK=Object.values(Dl).sort((t,e)=>e.length-t.length);var KK=new RegExp("^datasource_plus_(.+)__(.+)$"),qu=t=>e=>!!e&&e.startsWith(`${t}${v}`);var YK=qu("ta"),JK=qu("view"),zK=qu("datasource"),ZK=qu("query");var Wu=(n=>(n.ALL="all",n.AUTOMATION="automation",n.STATUS="status",n))(Wu||{}),kr=(l=>(l.USER_BY_APP="by_app",l.USER_BY_EMAIL="by_email2",l.BY_API_KEY="by_api_key",l.LINK="by_link",l.ROUTING="screen_routes",l.AUTOMATION_LOGS="automation_logs",l.ACCOUNT_BY_EMAIL="account_by_email",l.PLATFORM_USERS_LOWERCASE="platform_users_lowercase_2",l.USER_BY_GROUP="user_by_group",l.APP_BACKUP_BY_TRIGGER="by_trigger",l))(kr||{}),Hi={by_email2:["by_email"]},Te={GLOBAL:{name:"global-db",docs:{apiKeys:"apikeys",usageQuota:"usage_quota",licenseInfo:"license_info",environmentVariables:"environmentvariables"}},PLATFORM_INFO:{name:"global-info",docs:{tenants:"tenants",install:"install"}},AUDIT_LOGS:{name:"audit-logs"},SCIM_LOGS:{name:"scim-logs"},SELF_HOST_CLOUD:{name:"self-host-cloud"}},gt=Or("app"),Qu=Or("app_dev"),yt=Qu,Op="internal",xp="budibase",Ht="_design/sqlite",Rp="ta_bb_jobs",wp="ta_bb_inventory",bp="ta_bb_expenses",Dp="ta_bb_employee",ju=(r=>(r[r.SQLITE=Ht]="SQLITE",r.MIGRATIONS="_design/migrations",r))(ju||{});var Hu=(r=>(r.ACTIVE="active",r.INACTIVE="inactive",r))(Hu||{}),Kn=(o=>(o.Auth="budibase:auth",o.Init="budibase:init",o.ACCOUNT_RETURN_URL="budibase:account:returnurl",o.DatasourceAuth="budibase:datasourceauth",o.OIDC_CONFIG="budibase:oidc:config",o.FeatureFlags="budibase:featureflags",o))(Kn||{}),Cp=(i=>(i.OWNER="owner",i.ADMIN="admin",i.BUILDER="builder",i.WORKSPACE_MANAGER="workspace_manager",i))(Cp||{}),vp=(u=>(u.SETTINGS="settings",u.ACCOUNT="account",u.SMTP="smtp",u.GOOGLE="google",u.OIDC="oidc",u.OIDC_LOGOS="logos_oidc",u.SCIM="scim",u.AI="AI",u))(vp||{}),vT=new Date(-2147483647e3),Ku=new Date(2147483647e3),Ae="default";var Oa={};N(Oa,{CacheKey:()=>Ce,TTL:()=>ni,app:()=>jo,bustCache:()=>ts,destroy:()=>Vo,docWritethrough:()=>km,generic:()=>qo,get:()=>ii,invite:()=>im,keys:()=>lc,passwordReset:()=>Mm,store:()=>ur,user:()=>rn,withCache:()=>Wr,withCacheWithDynamicTTL:()=>sA,writethrough:()=>Um});var qo={};N(qo,{CacheKey:()=>Ce,TTL:()=>ni,bustCache:()=>ts,destroy:()=>Vo,get:()=>ii,keys:()=>lc,store:()=>ur,withCache:()=>Wr,withCacheWithDynamicTTL:()=>sA});var Se={};N(Se,{DEFAULT_TENANT_ID:()=>Ae,baseGlobalDBName:()=>vo,doInAppContext:()=>TN,doInAppMigrationContext:()=>SN,doInAutomationContext:()=>mN,doInContext:()=>Zp,doInEnvironmentContext:()=>IN,doInFeatureFlagOverrideContext:()=>of,doInIPContext:()=>tf,doInIdentityContext:()=>Oo,doInLicenseContext:()=>gN,doInScimContext:()=>ON,doInSelfHostTenantUsingCloud:()=>hN,doInTenant:()=>qe,ensureSnippetContext:()=>tA,getAppDB:()=>Xi,getAppId:()=>Le,getAuditLogDBName:()=>ZT,getAuditLogsDB:()=>RN,getAutomationId:()=>Xp,getCurrentContext:()=>zn,getDevAppDB:()=>bN,getEnvironmentVariables:()=>xN,getFeatureFlagOverrides:()=>sf,getFeatureFlags:()=>rf,getGlobalDB:()=>ne,getGlobalDBName:()=>Jn,getIP:()=>ef,getIdentity:()=>ar,getLicense:()=>yN,getPlatformURL:()=>zp,getProdAppDB:()=>wN,getProdAppId:()=>_N,getScimDBName:()=>lN,getSelfHostCloudDB:()=>EN,getTableForView:()=>DN,getTenantIDFromAppID:()=>Zi,getTenantId:()=>j,identity:()=>Io,isMultiTenant:()=>$r,isScim:()=>Pt,isSelfHostUsingCloud:()=>XT,isTenancyEnabled:()=>pN,isTenantIdSet:()=>dN,setFeatureFlags:()=>nf,setTableForView:()=>CN});var Io={};N(Io,{doInAccountContext:()=>Lv,doInIdentityContext:()=>Lp,doInUserContext:()=>Up,getAccountUserId:()=>NT,getIdentity:()=>Pp});function Pp(){return ar()}function Lp(t,e){return Oo(t,e)}function Up(t,e,r){let n={...t,_id:t._id,type:"user",hostInfo:{ipAddress:e.request.ip,userAgent:e.userAgent.source}};return Lp(n,r)}function Lv(t,e){let r=NT(t),n=t.tenantId,i={_id:r,type:"user",tenantId:n,account:t};return Lp(i,e)}function NT(t){let e;return Va(t)?e=t.budibaseUserId:e=t.accountId,e}var zu=require("fs");var UT=require("lodash"),Mp=require("crypto"),xo=require("path"),Uv=process.env.TOP_LEVEL_PATH||process.env.SERVER_TOP_LEVEL_PATH||(0,xo.resolve)((0,xo.join)(__dirname,"..","..","..")),PT=!1;!PT&&Ju()&&!Fp()&&(require("dotenv").config({path:(0,xo.join)(Uv,".env")}),PT=!0);function Fp(){return MT()}function MT(){return process.env.NODE_ENV==="jest"||process.env.JEST_WORKER_ID!=null&&process.env.JEST_WORKER_ID!=="null"}function Ju(){return process.env.NODE_ENV!=="production"}function Mv(t){if(t)return parseInt(t)}var Ki={BACKUPS:"backups",APPS:"prod-budi-app-assets",TEMPLATES:"templates",GLOBAL:"global",PLUGINS:"plugins",TEMP:"tmp-file-attachments"},LT=!!parseInt(process.env.SELF_HOSTED||"");function Fv(){return process.env.API_ENCRYPTION_KEY?process.env.API_ENCRYPTION_KEY:process.env.JWT_SECRET}function kv(){return process.env.HTTP_LOGGING===void 0?!0:process.env.HTTP_LOGGING}function Bv(){function t(r){function n(a,u){let c=`${u}/${a}`;if((0,zu.existsSync)(c))return c;let l=`${u}/..`;return l===u?null:n(a,l)}let i=n(r,process.cwd()),s=(0,zu.readFileSync)(i,"utf-8");return JSON.parse(s)}let e;if(Ju()&&!Fp())try{e=`${t("lerna.json").version}+local`}catch{}try{let r=t("package.json");return{VERSION:e||process.env.BUDIBASE_VERSION||r.version,SERVICE_NAME:r.name}}catch{return{VERSION:process.env.BUDIBASE_VERSION||"",SERVICE_NAME:""}}}function Gv(){return Ct.SERVICE_TYPE==="worker"}function $v(){return Ct.SERVICE_TYPE==="apps"}function Vv(){return Ct.BUDIBASE_ENVIRONMENT==="QA"}function qv(){return process.env.SERVICE?process.env.SERVICE:process.env.APPS_SERVICE?process.env.APPS_SERVICE:process.env.WORKER_SERVICE?process.env.WORKER_SERVICE:"budibase"}var Ct={isTest:Fp,isJest:MT,isDev:Ju,isWorker:Gv,isApps:$v,isQA:Vv,isProd:()=>!Ju(),BUDIBASE_ENVIRONMENT:process.env.BUDIBASE_ENVIRONMENT,JS_BCRYPT:process.env.JS_BCRYPT,JWT_SECRET:process.env.JWT_SECRET?(0,Mp.createSecretKey)(process.env.JWT_SECRET,"utf8"):void 0,JWT_SECRET_FALLBACK:process.env.JWT_SECRET_FALLBACK?(0,Mp.createSecretKey)(process.env.JWT_SECRET_FALLBACK,"utf8"):void 0,ENCRYPTION_KEY:process.env.ENCRYPTION_KEY,API_ENCRYPTION_KEY:Fv(),COUCH_DB_URL:process.env.COUCH_DB_URL||"http://localhost:4005",COUCH_DB_SQL_URL:process.env.COUCH_DB_SQL_URL,COUCH_DB_USERNAME:process.env.COUCH_DB_USER,COUCH_DB_PASSWORD:process.env.COUCH_DB_PASSWORD,GOOGLE_CLIENT_ID:process.env.GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET:process.env.GOOGLE_CLIENT_SECRET,SALT_ROUNDS:process.env.SALT_ROUNDS,REDIS_URL:process.env.REDIS_URL||"localhost:6379",REDIS_PASSWORD:process.env.REDIS_PASSWORD,REDIS_CLUSTERED:process.env.REDIS_CLUSTERED,MINIO_ACCESS_KEY:process.env.MINIO_ACCESS_KEY,MINIO_SECRET_KEY:process.env.MINIO_SECRET_KEY,AWS_SESSION_TOKEN:process.env.AWS_SESSION_TOKEN,AWS_REGION:process.env.AWS_REGION||"eu-west-1",MINIO_URL:process.env.MINIO_URL,MINIO_ENABLED:process.env.MINIO_ENABLED||1,INTERNAL_API_KEY:process.env.INTERNAL_API_KEY,INTERNAL_API_KEY_FALLBACK:process.env.INTERNAL_API_KEY_FALLBACK,MULTI_TENANCY:process.env.MULTI_TENANCY,ACCOUNT_PORTAL_URL:process.env.ACCOUNT_PORTAL_URL||"https://account.budibase.app",INTERNAL_ACCOUNT_PORTAL_URL:process.env.INTERNAL_ACCOUNT_PORTAL_URL||process.env.ACCOUNT_PORTAL_URL||"https://account.budibase.app",ACCOUNT_PORTAL_API_KEY:process.env.ACCOUNT_PORTAL_API_KEY||"",BUDICLOUD_URL:process.env.BUDICLOUD_URL||"https://budibase.app",DISABLE_ACCOUNT_PORTAL:process.env.DISABLE_ACCOUNT_PORTAL,SELF_HOSTED:LT,COOKIE_DOMAIN:process.env.COOKIE_DOMAIN,PLATFORM_URL:process.env.PLATFORM_URL||"",POSTHOG_TOKEN:process.env.POSTHOG_TOKEN,POSTHOG_PERSONAL_TOKEN:process.env.POSTHOG_PERSONAL_TOKEN,POSTHOG_API_HOST:process.env.POSTHOG_API_HOST||"https://us.i.posthog.com",POSTHOG_FEATURE_FLAGS_ENABLED:process.env.POSTHOG_FEATURE_FLAGS_ENABLED,ENABLE_ANALYTICS:process.env.ENABLE_ANALYTICS,TENANT_FEATURE_FLAGS:process.env.TENANT_FEATURE_FLAGS,CLOUDFRONT_CDN:process.env.CLOUDFRONT_CDN,CLOUDFRONT_PRIVATE_KEY_64:process.env.CLOUDFRONT_PRIVATE_KEY_64,CLOUDFRONT_PUBLIC_KEY_ID:process.env.CLOUDFRONT_PUBLIC_KEY_ID,BACKUPS_BUCKET_NAME:process.env.BACKUPS_BUCKET_NAME||Ki.BACKUPS,APPS_BUCKET_NAME:process.env.APPS_BUCKET_NAME||Ki.APPS,TEMPLATES_BUCKET_NAME:process.env.TEMPLATES_BUCKET_NAME||Ki.TEMPLATES,GLOBAL_BUCKET_NAME:process.env.GLOBAL_BUCKET_NAME||Ki.GLOBAL,PLUGIN_BUCKET_NAME:process.env.PLUGIN_BUCKET_NAME||Ki.PLUGINS,TEMP_BUCKET_NAME:process.env.TEMP_BUCKET_NAME||Ki.TEMP,USE_COUCH:process.env.USE_COUCH||!0,MOCK_REDIS:process.env.MOCK_REDIS,DEFAULT_LICENSE:process.env.DEFAULT_LICENSE,SERVICE:qv(),LOG_LEVEL:process.env.LOG_LEVEL||"info",SESSION_UPDATE_PERIOD:process.env.SESSION_UPDATE_PERIOD,DEPLOYMENT_ENVIRONMENT:process.env.DEPLOYMENT_ENVIRONMENT||"docker-compose",HTTP_LOGGING:kv(),ENABLE_AUDIT_LOG_IP_ADDR:process.env.ENABLE_AUDIT_LOG_IP_ADDR,SQL_LOGGING_ENABLE:process.env.SQL_LOGGING_ENABLE,SQL_MAX_ROWS:process.env.SQL_MAX_ROWS,SQL_MAX_RELATED_ROWS:process.env.MAX_RELATED_ROWS,SMTP_FALLBACK_ENABLED:process.env.SMTP_FALLBACK_ENABLED,SMTP_USER:process.env.SMTP_USER,SMTP_PASSWORD:process.env.SMTP_PASSWORD,SMTP_HOST:process.env.SMTP_HOST,SMTP_PORT:parseInt(process.env.SMTP_PORT||""),SMTP_FROM_ADDRESS:process.env.SMTP_FROM_ADDRESS,DISABLE_JWT_WARNING:process.env.DISABLE_JWT_WARNING,BLACKLIST_IPS:process.env.BLACKLIST_IPS,SERVICE_TYPE:"unknown",PASSWORD_MIN_LENGTH:process.env.PASSWORD_MIN_LENGTH,PASSWORD_MAX_LENGTH:process.env.PASSWORD_MAX_LENGTH,ENABLE_SSO_MAINTENANCE_MODE:LT?process.env.ENABLE_SSO_MAINTENANCE_MODE:!1,...Bv(),DISABLE_PINO_LOGGER:process.env.DISABLE_PINO_LOGGER,OFFLINE_MODE:process.env.OFFLINE_MODE,SESSION_EXPIRY_SECONDS:process.env.SESSION_EXPIRY_SECONDS,_set(t,e){process.env[t]=e,Ct[t]=e},ROLLING_LOG_MAX_SIZE:process.env.ROLLING_LOG_MAX_SIZE||"10M",DISABLE_SCIM_CALLS:process.env.DISABLE_SCIM_CALLS,BB_ADMIN_USER_EMAIL:process.env.BB_ADMIN_USER_EMAIL,BB_ADMIN_USER_PASSWORD:process.env.BB_ADMIN_USER_PASSWORD,OPENAI_API_KEY:process.env.OPENAI_API_KEY,MIN_VERSION_WITHOUT_POWER_ROLE:process.env.MIN_VERSION_WITHOUT_POWER_ROLE||"3.0.0",DISABLE_CONTENT_SECURITY_POLICY:process.env.DISABLE_CONTENT_SECURITY_POLICY,BSON_BUFFER_SIZE:Mv(process.env.BSON_BUFFER_SIZE)};function Ro(t){let e=(0,UT.cloneDeep)(Ct),r;for(r in t)Ct._set(r,t[r]);return()=>{for(let[n,i]of Object.entries(e))Ct._set(n,i)}}function FT(t,e){let r=Ro(t),n=e();return n instanceof Promise?n.finally(r):(r(),n)}var kT=["API_ENCRYPTION_KEY","BB_ADMIN_USER_PASSWORD","COUCH_DB_PASSWORD","COUCH_DB_SQL_URL","COUCH_DB_URL","GOOGLE_CLIENT_SECRET","INTERNAL_API_KEY_FALLBACK","INTERNAL_API_KEY","JWT_SECRET","MINIO_ACCESS_KEY","MINIO_SECRET_KEY","OPENAI_API_KEY","REDIS_PASSWORD"];for(let[t,e]of Object.entries(Ct))e==="0"&&(Ct[t]=0),e==="false"&&(Ct[t]=0);var h=Ct;var BT=require("async_hooks"),we=class t{static{this.storage=new BT.AsyncLocalStorage}static run(e,r){return t.storage.run(e,()=>r())}static get(){return t.storage.getStore()}};var kp="No app provided";function Br(t){if(!t)throw kp;return t.startsWith(yt)}function Wv(t){if(!t)throw kp;return t.startsWith(gt)&&!Br(t)}function wo(t){if(!t)throw kp;return Br(t.appId)}function Zu(t){if(!t||t.startsWith(yt))return t;let e=t.split(gt);e.shift();let r=e.join(gt);return`${yt}${r}`}var Qv=Zu;function at(t){if(!t||!t.startsWith(yt))return t;let e=t.split(yt);e.shift();let r=e.join(yt);return`${gt}${r}`}function jv(t){let e=t?.split("_")||[];return e.length?e[e.length-1]:null}var vt=t=>{let e=Bp(t),r,n;if(e.auth?.username)r=e.auth.username;else if(h.COUCH_DB_USERNAME)r=h.COUCH_DB_USERNAME;else if(!h.isTest())throw new Error("CouchDB username not set");if(e.auth?.password)n=e.auth.password;else if(h.COUCH_DB_PASSWORD)n=h.COUCH_DB_PASSWORD;else if(!h.isTest())throw new Error("CouchDB password not set");let i=Buffer.from(`${r}:${n}`).toString("base64"),s=h.COUCH_DB_SQL_URL;if(h.isDev()&&!s)s="http://localhost:4006";else if(!s&&e.url){let o=new URL(e.url);s=e.url.replace(o.port,"4984")}return{url:e.url,sqlUrl:Bp(s).url,auth:{username:r,password:n},cookie:`Basic ${i}`}},Bp=(t=h.COUCH_DB_URL)=>{let e,r,n,i;if(t){/^https?:\/\//i.test(t)||(t=`http://${t}`);let o=t.split("://"),a=o[0],u=o.slice(1).join("://");if(t.includes("@")){let c=u.split("@");i=c[c.length-1];let l=c.slice(0,-1).join("@");if(l.includes(":")){let m=l.split(":");r=m[0],n=m.slice(1).join(":")}else r=l}else i=u;e=`${a}://${i}`}return{url:e,auth:{username:r,password:n}}};var JT=W(require("@budibase/nano"));var GT=W(require("node-fetch"));function Xu(t){return t.replace(/(https?:\/\/)|(\/)+/g,"$1$2")}async function $T(t,e="GET",r){let{url:n,cookie:i}=vt(),s=`${n}/${t}`;return await bo({url:s,cookie:i,method:e,body:r})}async function bo({url:t,cookie:e,method:r,body:n}){let i={method:r,headers:{Authorization:e}};return n&&r!=="GET"&&(typeof n=="string"?(i.body=n,i.headers["Content-Type"]="text/plain"):(i.body=JSON.stringify(n),i.headers["Content-Type"]="application/json")),await(0,GT.default)(Xu(encodeURI(t)),i)}async function Gp(t,e="GET",r){let n=await $T(t,e,r);if(n.status<300)return await n.json();throw"Cannot connect to CouchDB instance"}var Yn=W(require("pouchdb"));var VT,qT=!1,$p=(t={})=>{let{url:e,cookie:r}=vt(),n={prefix:e,fetch:(i,s)=>(s.headers.set("Authorization",r),Yn.default.fetch(i,s))};if(t.inMemory){let i=require("pouchdb-adapter-memory");Yn.default.plugin(i),n={adapter:"memory"}}if(t.onDisk&&(n={adapter:"leveldb"}),t.replication){let i=require("@budibase/pouchdb-replication-stream");Yn.default.plugin(i.plugin),Yn.default.adapter("writableStream",i.adapters.writableStream)}if(t.find){let i=require("pouchdb-find");Yn.default.plugin(i)}return Yn.default.defaults(n)};function ec(t){VT=$p(t),qT=!0}var Kv=()=>{if(!qT)throw new Error("init has not been called")};function Et(t,e){Kv();let r=new VT(t,e),n=r.put;return r.put=async(i,s={})=>(i.createdAt||(i.createdAt=new Date().toISOString()),i.updatedAt=new Date().toISOString(),n(i,s)),r.exists=async()=>!(await r.info()).error,r}async function Do(t){if(!(!t||h.isTest()))try{return await t.close()}catch{}}var WT=require("uuid");function me(){return(0,WT.v4)().replace(/-/g,"")}var Oe=W(require("dd-trace")),Yi=class{constructor(e){this.db=e}get name(){return this.db.name}exists(e){return Oe.default.trace("db.exists",r=>(r.addTags({db_name:this.name,doc_id:e}),e?this.db.exists(e):this.db.exists()))}get(e){return Oe.default.trace("db.get",r=>(r.addTags({db_name:this.name,doc_id:e}),this.db.get(e)))}tryGet(e){return Oe.default.trace("db.tryGet",async r=>{r.addTags({db_name:this.name,doc_id:e});let n=await this.db.tryGet(e);return r.addTags({doc_found:n!==void 0}),n})}getMultiple(e,r){return Oe.default.trace("db.getMultiple",async n=>{n.addTags({db_name:this.name,num_docs:e?.length||0,allow_missing:r?.allowMissing});let i=await this.db.getMultiple(e,r);return n.addTags({num_docs_found:i.length}),i})}remove(e,r){return Oe.default.trace("db.remove",async n=>{n.addTags({db_name:this.name,doc_id:e,rev:r});let i=typeof e=="object",s=i?e._id:e;r=i?e._rev:r;let o=await this.db.remove(s,r);return n.addTags({ok:o.ok}),o})}bulkRemove(e,r){return Oe.default.trace("db.bulkRemove",n=>(n.addTags({db_name:this.name,num_docs:e.length,silence_errors:r?.silenceErrors}),this.db.bulkRemove(e,r)))}put(e,r){return Oe.default.trace("db.put",async n=>{n.addTags({db_name:this.name,doc_id:e._id,force:r?.force});let i=await this.db.put(e,r);return n.addTags({ok:i.ok}),i})}bulkDocs(e){return Oe.default.trace("db.bulkDocs",r=>(r.addTags({db_name:this.name,num_docs:e.length}),this.db.bulkDocs(e)))}async find(e){return Oe.default.trace("db.find",async r=>{r.addTags({db_name:this.name,...e});let n=await this.db.find(e);return r.addTags({rows_length:n.docs.length}),n})}allDocs(e){return Oe.default.trace("db.allDocs",async r=>{r.addTags({db_name:this.name,...e});let n=await this.db.allDocs(e);return r.addTags({total_rows:n.total_rows,rows_length:n.rows.length,offset:n.offset}),n})}query(e,r){return Oe.default.trace("db.query",async n=>{n.addTags({db_name:this.name,view_name:e,...r});let i=await this.db.query(e,r);return n.addTags({total_rows:i.total_rows,rows_length:i.rows.length,offset:i.offset}),i})}destroy(){return Oe.default.trace("db.destroy",async e=>{e.addTags({db_name:this.name});let r=await this.db.destroy();return e.addTags({ok:r.ok}),r})}compact(){return Oe.default.trace("db.compact",async e=>{e.addTags({db_name:this.name});let r=await this.db.compact();return e.addTags({ok:r.ok}),r})}dump(e,r){return Oe.default.trace("db.dump",n=>(n.addTags({db_name:this.name,batch_limit:r?.batch_limit,batch_size:r?.batch_size,style:r?.style,timeout:r?.timeout,num_doc_ids:r?.doc_ids?.length,view:r?.view}),this.db.dump(e,r)))}load(...e){return Oe.default.trace("db.load",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.load(...e)))}createIndex(...e){return Oe.default.trace("db.createIndex",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.createIndex(...e)))}deleteIndex(...e){return Oe.default.trace("db.deleteIndex",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.deleteIndex(...e)))}getIndexes(...e){return Oe.default.trace("db.getIndexes",r=>(r.addTags({db_name:this.name,num_args:e.length}),this.db.getIndexes(...e)))}sql(e,r){return Oe.default.trace("db.sql",async n=>{n.addTags({db_name:this.name,num_bindings:r?.length});let i=await this.db.sql(e,r);return n.addTags({num_rows:i.length}),i})}sqlPurgeDocument(e){return Oe.default.trace("db.sqlPurgeDocument",r=>(r.addTags({db_name:this.name,num_docs:Array.isArray(e)?e.length:1}),this.db.sqlPurgeDocument(e)))}sqlDiskCleanup(){return Oe.default.trace("db.sqlDiskCleanup",e=>(e.addTags({db_name:this.name}),this.db.sqlDiskCleanup()))}};var Yp={};N(Yp,{breakExternalTableId:()=>Wp,breakRowIdField:()=>aN,buildExternalTableId:()=>tN,convertRowId:()=>oN,encodeTableId:()=>rN,encodeViewId:()=>nN,extractDate:()=>jp,generateRowIdField:()=>iN,getNativeSql:()=>Ji,isExternalTable:()=>qp,isExternalTableID:()=>tc,isInternalTableID:()=>eN,isRowId:()=>sN,isValidFilter:()=>nc,isValidISODateString:()=>rc,isValidISODateStringWithoutTimezone:()=>Qp,isValidTime:()=>Hp,sqlLog:()=>Co,validateManyToMany:()=>Kp});var Vp=`${v}${v}`,jT=/^\[.*]$/g,Yv=encodeURIComponent(" "),Jv=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:.\d{3})?Z)?$/,zv=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:.\d{3})?)?$/,Zv=/(\d{4}-\d{2}-\d{2})/,Xv=/^(?:\d{2}:)?(?:\d{2}:)(?:\d{2})$/;function tc(t){return t.startsWith("datasource"+v)}function eN(t){return!tc(t)}function Ji(t){let e=t.toSQL();if(Array.isArray(e))return e;let r;return e.toNative&&(r=e.toNative()),{sql:r?.sql||e.sql,bindings:r?.bindings||e.bindings}}function qp(t){return t?.sourceId&&t.sourceId.includes("datasource"+v)&&t?.sourceId!==Di||t?.sourceType==="external"?!0:!!(t?._id&&tc(t._id))}function tN(t,e){return`${t}${Vp}${encodeURIComponent(e)}`}function rN(t){return tc(t)?encodeURIComponent(t):t}function nN(t){return encodeURIComponent(t)}function Wp(t){let e=t.split(Vp),r=e.shift(),n=e.join(Vp);if(n.includes(Yv)&&(n=decodeURIComponent(n)),!r||!n)throw new Error("Unable to get datasource/table name from table ID");return{datasourceId:r,tableName:n}}function iN(t=[]){Array.isArray(t)||(t=[t]);for(let e in t)t[e]instanceof Buffer&&(t[e]=t[e].toString());return encodeURIComponent(JSON.stringify(t).replace(/"/g,"'"))}function sN(t){return Array.isArray(t)||typeof t=="string"&&t.match(jT)!=null}function oN(t){return Array.isArray(t)?t[0]:typeof t=="string"&&t.match(jT)!=null?t.substring(1,t.length-1):t}function aN(t){if(!t)return[];let e=typeof t=="string"?t:t._id,r=decodeURIComponent(e).replace(/'/g,'"');try{let n=JSON.parse(r);return Array.isArray(n)?n:[n]}catch{return[t]}}function rc(t){let e=t.trim();if(!Jv.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}function Qp(t){let e=t.trim();if(!zv.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}function jp(t){let e=t.match(Zv);if(e)return e[0]}function nc(t){return t!=null&&t!==""}function Hp(t){return Xv.test(t)}function Co(t,e,r){if(!h.SQL_LOGGING_ENABLE)return;let n=`[SQL] [${t.toUpperCase()}] query="${e}"`;r&&(n+=` values="${r.join(", ")}"`),console.log(n)}function uN(t){return!!t.through&&!!t.fromPrimary&&!!t.from&&!!t.toPrimary&&!!t.to}function Kp(t){if(uN(t))return t}var HT="Database does not exist.";function KT(t){return(0,JT.default)({url:t.url,requestDefaults:{headers:{Authorization:t.cookie}},parseUrl:!1})}var Gr=class extends Error{constructor(r,n){super(r);let i=n.status||n.statusCode||500;this.status=i,this.statusCode=i,this.reason=n.reason||"Unknown",this.name=n.name,this.errid=n.errid||"Unknown",this.description=n.description||"Unknown",this.error=n.error||"Not found"}};function cN(t,e,r){if(!t||!e)throw new Error("Unable to create database without database name or connection");let n=new zi(t,r,e);return new Yi(n)}var zi=class t{constructor(e,r,n){this.couchInfo=vt();this.name=e,this.pouchOpts=r||{},n&&(this.couchInfo=vt(n),this.instanceNano=KT(this.couchInfo)),t.nano||t.init()}static init(){let e=vt();t.nano=KT(e)}exists(e){return e===void 0?this.dbExists():this.docExists(e)}async dbExists(){return(await bo({url:`${this.couchInfo.url}/${this.name}`,method:"HEAD",cookie:this.couchInfo.cookie})).status===200}async docExists(e){try{return await this.performCall(r=>()=>r.head(e)),!0}catch{return!1}}nano(){return this.instanceNano||t.nano}getDb(){return this.nano().db.use(this.name)}async checkAndCreateDb(){let e=!this.pouchOpts?.skip_setup,r=await this.exists();if(!e&&!r)throw new Error("DB does not exist");if(!r)try{await this.nano().db.create(this.name)}catch(n){if(n.statusCode!==412)throw new Gr(n.message,n)}return this.getDb()}async performCallWithDBCreation(e){let r=this.getDb(),n=await e(r);try{return await n()}catch(i){if(i.statusCode===404&&i.reason===HT)return await this.checkAndCreateDb(),await this.performCallWithDBCreation(e);throw new Gr(`CouchDB error: ${i.message}`,i)}}async performCall(e){let r=this.getDb(),n=await e(r);try{return await n()}catch(i){throw new Gr(`CouchDB error: ${i.message}`,i)}}async get(e){return this.performCall(r=>{if(!e)throw new Error("Unable to get doc without a valid _id.");return()=>r.get(e)})}async tryGet(e){try{return await this.get(e)}catch(r){if(r.statusCode===404)return;throw r}}async getMultiple(e,r){if(!e||e.length===0)return[];e=[...new Set(e)];let n=!r?.excludeDocs,i=await this.allDocs({keys:e,include_docs:n}),s=u=>n&&u.doc==null||u.value&&"deleted"in u.value&&u.value.deleted?!0:u.error==="not_found",o=i.rows.filter(u=>!s(u)),a=o.length!==i.rows.length;if(!r?.allowMissing&&a){let c=i.rows.filter(l=>s(l)).map(l=>l.key).join(", ");throw new Error(`Unable to get bulk documents: ${c}`)}return o.map(u=>n?u.doc:u.value)}async remove(e,r){return this.performCall(n=>{let i,s;if(Mh(e)?(i=e._id,s=e._rev):(i=e,s=r),!i||!s)throw new Error("Unable to remove doc without a valid _id and _rev.");return()=>n.destroy(i,s)})}async bulkRemove(e,r){let n=await this.performCall(o=>()=>o.bulk({docs:e.map(a=>({...a,_deleted:!0}))}));if(r?.silenceErrors)return;let i=!1,s="Unable to bulk remove documents: ";for(let o of n)o.error&&(i=!0,s+=o.error);if(i)throw new Gr(s,{name:this.name,status:400})}async post(e,r){return e._id||(e._id=me()),this.put(e,r)}async put(e,r){if(!e._id)throw new Error("Cannot store document without _id field.");return this.performCallWithDBCreation(async n=>{if(e.createdAt||(e.createdAt=new Date().toISOString()),e.updatedAt=new Date().toISOString(),r?.force&&e._id)try{let i=await this.get(e._id);i&&(e._rev=i._rev)}catch(i){if(i.status!==404)throw i}return()=>n.insert(e)})}async bulkDocs(e){let r=new Date().toISOString();return this.performCallWithDBCreation(n=>()=>n.bulk({docs:e.map(i=>({createdAt:r,...i,updatedAt:r}))}))}async find(e){return this.performCall(r=>async()=>r.find(e))}async allDocs(e){return this.performCall(r=>async()=>{try{return await r.list(e)}catch(n){if(n.reason===HT)return{offset:0,total_rows:0,rows:[]};throw n}})}async _sqlQuery(e,r,n){e=Xu(`${this.couchInfo.sqlUrl}/${e}`);let i={url:e,method:r,cookie:this.couchInfo.cookie};return n&&(i.body=n),this.performCall(()=>async()=>{let s=await bo(i),o=await s.text();if(s.status>300){let a;try{a=JSON.parse(o)}catch{throw console.error(`SQS error: ${o}`),new Gr("error while running SQS query, please try again later",{name:"sqs_error",status:s.status})}throw a}return JSON.parse(o)})}async sql(e,r){let i=`/${this.name}/${Ht}`;return Co("sqlite3",e,r),await this._sqlQuery(i,"POST",{query:e,args:r})}async sqlDiskCleanup(){let r=`/${this.name}/_cleanup`;try{await this._sqlQuery(r,"POST")}catch(n){if(n.status!==500)throw n}}async sqlPurgeDocument(e){Array.isArray(e)||(e=[e]);let n=`/${this.name}/_purge`;return await this._sqlQuery(n,"POST",{docs:e})}async query(e,r){return this.performCall(n=>{let[i,s]=e.split("/");return()=>n.view(i,s,r)})}async destroy(){if(await this.exists(Ht)){let e=await this.get(Ht);e.sql.tables={},await this.put(e),await this.sqlDiskCleanup()}try{return await this.nano().db.destroy(this.name)}catch(e){if(e.statusCode===404)return{ok:!0};throw new Gr(e.message,e)}}async compact(){return this.performCall(e=>()=>e.compact())}async dump(e,r){return Et(this.name).dump(e,r)}async load(e){return Et(this.name).load(e)}async createIndex(e){return Et(this.name).createIndex(e)}async deleteIndex(e){return Et(this.name).deleteIndex(e)}async getIndexes(){return Et(this.name).getIndexes()}};function Ve(t,e){return new Yi(new zi(t,e))}async function ut(t,e,r){let n=Ve(t,r);return await e(n)}async function Jp(t){let e="/_all_dbs";return t&&(e+=`?${t}`),await Gp(e)}var zT=null;function Jn(t){return t||(t=j()),vo(t)}function ZT(t){return t||(t=j()),t===Ae?Te.AUDIT_LOGS.name:`${t}${v}${Te.AUDIT_LOGS.name}`}function lN(t){return t||(t=j()),t===Ae?Te.SCIM_LOGS.name:`${t}${v}${Te.SCIM_LOGS.name}`}function vo(t){return!t||t===Ae?Te.GLOBAL.name:`${t}${v}${Te.GLOBAL.name}`}function zp(){return h.PLATFORM_URL}function $r(){return!!h.MULTI_TENANCY}function dN(){return!!we.get()?.tenantId}function pN(){return h.MULTI_TENANCY}function Zi(t){if(!t)return;if(!$r())return Ae;let e=t.split(v),r=e[1]==="dev";if(!(r&&e.length===3||!r&&e.length===2))return r?e[2]:e[1]}function fN(t){let e;try{e=we.get()}catch{e={}}return e={...e,...t},e}async function Nt(t,e){AN();let r=fN(t);return we.run(r,e)}async function mN(t){return await tA(),await Nt({tenantId:Zi(t.appId),appId:t.appId,automationId:t.automationId},t.task)}async function Zp(t,e){let r=Zi(t);return Nt({tenantId:r,appId:t},e)}async function qe(t,e){return h.MULTI_TENANCY||(t=t||Ae),Nt(t?{tenantId:t}:{},e)}async function hN(t,e){return Nt({tenantId:t,isSelfHostUsingCloud:!0},e)}async function gN(t,e){return Nt({license:t},e)}function yN(){return we.get()?.license}function XT(){return!!we.get()?.isSelfHostUsingCloud}function EN(){let t=we.get();if(!t||!t.isSelfHostUsingCloud)throw new Error("Self-host cloud DB not found");return Ve(Te.SELF_HOST_CLOUD.name)}async function TN(t,e){return eA(t,e)}async function eA(t,e,r){if(!t)throw new Error("appId is required");let n=Zi(t),i={appId:t,...r};return n&&(i.tenantId=n),Nt(i,e)}async function Oo(t,e){if(!t)throw new Error("identity is required");let r={identity:t};return t.tenantId&&(r.tenantId=t.tenantId),Nt(r,e)}function AN(){if(we.get()?.isMigrating)throw new Error("The context cannot be changed, a migration is currently running")}async function SN(t,e){return eA(t,e,{isMigrating:!0})}function ar(){try{return we.get()?.identity}catch{}}function j(){if(!$r())return Ae;let e=we.get()?.tenantId;if(!e)throw new Error("Tenant id not found");return e}function Xp(){return we.get()?.automationId}function Le(){let e=we.get()?.appId;return!e&&h.isTest()&&zT?zT:e}function ef(){return we.get()?.ip}var _N=()=>{let t=Le();if(!t)throw new Error("Could not get appId");return at(t)};function IN(t,e){if(!t)throw new Error("Must supply environment variables.");return Nt({environmentVariables:t},e)}function ON(t){return Nt({isScim:!0},t)}function tf(t,e){return Nt({ip:t},e)}async function tA(){let t=zn();if(!t||t.snippets)return;let e,r=Xi();r&&(e=(await r.tryGet("app_metadata"))?.snippets),t.snippets=e||[]}function xN(){let t=we.get();return t.environmentVariables?t.environmentVariables:null}function ne(){let t=we.get();if(!t||h.MULTI_TENANCY&&!t.tenantId)throw new Error("Global DB not found");if(t.isSelfHostUsingCloud)throw new Error("Global DB not found - self-host users using cloud don't have a global DB");return Ve(vo(t?.tenantId))}function RN(){if(!j())throw new Error("No tenant ID found - cannot open audit log DB");return Ve(ZT())}function Xi(t){let e=Le();if(!e)throw new Error("Unable to retrieve app DB - no app ID.");if(XT())throw new Error("App DB not found - self-host users using cloud don't have app DBs");return Ve(e,t)}function wN(t){let e=Le();if(!e)throw new Error("Unable to retrieve prod DB - no app ID.");return Ve(at(e),t)}function bN(t){let e=Le();if(!e)throw new Error("Unable to retrieve dev DB - no app ID.");return Ve(Zu(e),t)}function Pt(){return!!we.get()?.isScim}function zn(){try{return we.get()}catch{return}}function rf(t){let e=zn();if(e)return e.featureFlagCache?.[t]}function nf(t,e){let r=zn();r&&(r.featureFlagCache??={},r.featureFlagCache[t]=e)}function sf(){return zn()?.featureFlagOverrides||{}}async function of(t,e){return await Nt({featureFlagOverrides:t},e)}function DN(t){let e=zn();if(e)return e.viewToTableCache?.[t]}function CN(t,e){let r=zn();r&&(r.viewToTableCache??={},r.viewToTableCache[t]=e)}var qr={};N(qr,{getAppClient:()=>cc,getCacheClient:()=>pf,getDocWritethroughClient:()=>UN,getInviteClient:()=>ei,getLockClient:()=>mf,getPasswordResetClient:()=>$o,getSessionClient:()=>Vr,getSocketClient:()=>LN,getUserClient:()=>Go,getWritethroughClient:()=>ff,init:()=>Lt,shutdown:()=>iA});var uc=W(require("ioredis"));var oc={};N(oc,{Databases:()=>af,SEPARATOR:()=>es,SelectableDatabase:()=>ic,getRedisClusterOptions:()=>uf,getRedisConnectionDetails:()=>sc,getRedisOptions:()=>Zn,removeDbPrefix:()=>cf});var es="-",af=(y=>(y.PW_RESETS="pwReset",y.VERIFICATIONS="verification",y.INVITATIONS="invitation",y.DEV_LOCKS="devLocks",y.DEBOUNCE="debounce",y.SESSIONS="session",y.USER_CACHE="users",y.FLAGS="flags",y.APP_METADATA="appMetadata",y.QUERY_VARS="queryVars",y.LICENSES="license",y.GENERIC_CACHE="data_cache",y.WRITE_THROUGH="writeThrough",y.LOCKS="locks",y.SOCKET_IO="socket_io",y.BPM_EVENTS="bpmEvents",y.DOC_WRITE_THROUGH="docWriteThrough",y))(af||{}),ic=(E=>(E[E.DEFAULT=0]="DEFAULT",E[E.SOCKET_IO=1]="SOCKET_IO",E[E.RATE_LIMITING=2]="RATE_LIMITING",E[E.UNUSED_2=3]="UNUSED_2",E[E.UNUSED_3=4]="UNUSED_3",E[E.UNUSED_4=5]="UNUSED_4",E[E.UNUSED_5=6]="UNUSED_5",E[E.UNUSED_6=7]="UNUSED_6",E[E.UNUSED_7=8]="UNUSED_7",E[E.UNUSED_8=9]="UNUSED_8",E[E.UNUSED_9=10]="UNUSED_9",E[E.UNUSED_10=11]="UNUSED_10",E[E.UNUSED_11=12]="UNUSED_11",E[E.UNUSED_12=13]="UNUSED_12",E[E.UNUSED_13=14]="UNUSED_13",E[E.UNUSED_14=15]="UNUSED_14",E))(ic||{});function sc(){let t=h.REDIS_PASSWORD,e=h.REDIS_URL.split("//");e=e.length>1?e[1]:e[0],e=e.split("@"),e.length>1?(t=e[0].split(":")[1],e=e[1]):e=e[0];let[r,n]=e.split(":"),i=parseInt(n);return{host:r,password:t,port:isNaN(i)?6379:i}}function uf(){return{slotsRefreshTimeout:2e3,dnsLookup:(t,e)=>e(null,t),redisOptions:{...Zn(),tls:{}}}}function Zn(){let{host:t,password:e,port:r}=sc();return{connectTimeout:3e4,port:r,host:t,password:e}}function cf(t){let e=t.split(es);return e.length>=2?(e.shift(),e.join(es)):e[0]}var ac=require("dd-trace"),nA=require("lodash"),rA;if(h.MOCK_REDIS)try{rA=require("ioredis-mock")}catch{console.log("Mock redis unavailable")}async function vN(t=0){return await ac.tracer.trace("Redis.init",async e=>{if(h.MOCK_REDIS)return e.addTags({mock:!0}),new rA(Zn());let r;if(h.REDIS_CLUSTERED){e.addTags({clustered:!0});let{host:n,port:i}=sc();r=new uc.Cluster([{host:n,port:i}],uf())}else r=new uc.default(Zn());return new Promise((n,i)=>{r.on("error",s=>{e.addTags({error:!0}),console.error(`failed to connect to redis (db: ${t})`,s),i(s)}),r.on("reconnecting",()=>{console.log(`Redis reconnecting... (db: ${t})`)}),r.on("ready",()=>{e.addTags({connected:!0}),console.log(`Redis ready to receive commands (db: ${t})`),n(r)})})})}function NN(t,e){return new Promise((r,n)=>{let i=new Set;t.on("data",s=>s.forEach(o=>i.add(o))),t.on("error",s=>n(s)),t.on("end",async()=>{try{let s=Array.from(i).map(async o=>{let a=await e.get(o);return a&&(a=JSON.parse(a)),{key:cf(o),value:a}});r(await Promise.all(s))}catch(s){n(s)}})})}function PN(t){return t.isCluster}var lf=class t{constructor(e,r){this.client=e,this.db=r}static async init(e,r=0){return await ac.tracer.trace("RedisWrapper.init",async n=>{let i=await vN(r);return r&&!h.isTest()&&(n.addTags({db:e}),i.select(r)),new t(i,e)})}trace(e,r){return ac.tracer.trace(e,async n=>(n.addTags({db:this.db}),await r(n)))}prefixed(e){return e.includes(this.db)?e:`${this.db}${es}${e}`}async finish(){return await this.trace("RedisWrapper.finish",async()=>{await this.client.quit()})}async scan(e=""){return await this.trace("RedisWrapper.scan",async r=>{r.addTags({key:e}),e=`${this.db}${es}${e}`;let n;PN(this.client)?n=this.client.nodes("master")[0].scanStream({match:e+"*",count:100}):n=this.client.scanStream({match:e+"*",count:100});let i=await NN(n,this.client);return r.addTags({numKeysFound:i.length}),i})}async keys(e){return await this.trace("RedisWrapper.keys",async r=>(r.addTags({pattern:e}),this.client.keys(this.prefixed(e))))}async exists(e){return await this.trace("RedisWrapper.exists",async r=>(r.addTags({key:e}),await this.client.exists(this.prefixed(e))))}async get(e){return await this.trace("RedisWrapper.get",async r=>{r.addTags({key:e});let n=await this.client.get(this.prefixed(e));n!=null&&n.key&&(n.key=e);try{return JSON.parse(n)}catch{return n}})}async bulkGet(e){return await this.trace("RedisWrapper.bulkGet",async r=>{if(r.addTags({numKeys:e.length}),e.length===0)return{};let n=await this.client.mget(e.map(i=>this.prefixed(i)));return r.addTags({numKeysFound:n.length}),(0,nA.zip)(e,n).reduce((i,[s,o])=>{if(s===void 0||o===void 0)throw new Error(`Keys and response length mismatch: ${e.length} vs ${n.length}`);try{i[s]=o?JSON.parse(o):null}catch{i[s]=o}return i},{})})}async store(e,r,n=null){return await this.trace("RedisWrapper.store",async i=>{i.addTags({key:e,expirySeconds:n}),typeof r=="object"&&(r=JSON.stringify(r)),await this.client.set(this.prefixed(e),r),n&&await this.client.expire(this.prefixed(e),n)})}async bulkStore(e,r=null){return await this.trace("RedisWrapper.bulkStore",async n=>{n.addTags({numKeys:Object.keys(e).length,expirySeconds:r});let i=Object.entries(e).reduce((o,[a,u])=>(o[this.prefixed(a)]=typeof u=="object"?JSON.stringify(u):u,o),{}),s=this.client.pipeline();if(s.mset(i),r!==null)for(let o of Object.keys(i))s.expire(o,r);await s.exec()})}async getTTL(e){return await this.trace("RedisWrapper.getTTL",async r=>(r.addTags({key:e}),await this.client.ttl(this.prefixed(e))))}async setExpiry(e,r){return await this.trace("RedisWrapper.setExpiry",async n=>(n.addTags({key:e,expirySeconds:r}),await this.client.expire(this.prefixed(e),r)))}async delete(e){return await this.trace("RedisWrapper.delete",async r=>{r.addTags({key:e}),await this.client.del(this.prefixed(e))})}async bulkDelete(e){return await this.trace("RedisWrapper.bulkDelete",async r=>{r.addTags({numKeys:e.length}),await this.client.del(e.map(n=>this.prefixed(n)))})}async clear(){return await this.trace("RedisWrapper.clear",async e=>{let r=await this.scan();e.addTags({numKeys:r.length}),await Promise.all(r.map(n=>this.delete(n.key)))})}async increment(e){return await this.trace("RedisWrapper.increment",async r=>{r.addTags({key:e});let n=await this.client.incr(this.prefixed(e));if(isNaN(n))throw new Error(`Redis ${e} does not contain a number`);return n})}async deleteIfValue(e,r){return await this.trace("RedisWrapper.deleteIfValue",async n=>{n.addTags({key:e});let i=`
|
|
6
6
|
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
7
7
|
redis.call('DEL', KEYS[1])
|
|
8
8
|
end
|