/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/dobo@2.19.1/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import nql from"@tryghost/nql";import collectConnections from"./lib/collect-connections.js";import collectDrivers from"./lib/collect-drivers.js";import collectFeatures from"./lib/collect-features.js";import collectModels from"./lib/collect-models.js";const propertyType={integer:{validator:"number",rules:[]},smallint:{validator:"number",rules:[]},text:{validator:"string",textType:"text",rules:[]},string:{validator:"string",maxLength:50,minLength:0,rules:[]},float:{validator:"number",rules:[]},double:{validator:"number",rules:[]},boolean:{validator:"boolean",rules:[]},datetime:{validator:"date",rules:[]},object:{validator:null,rules:[]},array:{validator:null,rules:[]}},commonPropertyTypes=["name","type","required","rules","validator","ref","default","values","rulesMsg","immutable","feature","format"];async function factory(t){const e=this,{breakNsPath:r}=this.app.bajo,{find:s,filter:i,isString:n,map:a,pick:o,groupBy:l,isEmpty:c}=this.app.lib._;class p extends this.app.baseClass.Base{static aggregateTypes=["count","avg","min","max","sum"];static idTypes=["string","integer","smallint"];static histogramTypes=["daily","monthly","yearly"];static propertyType=propertyType;static indexTypes=["index","unique","primary","fulltext"];constructor(){super(t,e.app),this.config={connections:[],validationParams:{abortEarly:!1,convert:!1,allowUnknown:!0},default:{filter:{limit:25,maxLimit:200,maxPage:400,sort:["dt:-1","updatedAt:-1","createdAt:-1","ts:-1","username","name"]},cache:{ttlDur:"10s"},hardCap:1e4,warnings:!0},memDb:{autoSaveDur:"1s"},applet:{confirmation:!1}},this.drivers=[],this.connections=[],this.features=[],this.models=[]}getPropertyKeysByType=t=>{const e=[...commonPropertyTypes];return["string"].includes(t)&&e.push("minLength","maxLength","values"),["text"].includes(t)&&e.push("textType"),["smallint","integer"].includes(t)&&e.push("autoInc","values"),["float","double"].includes(t)&&e.push("values"),e};getAllPropertyKeys=t=>{const{uniq:e,isEmpty:r}=this.app.lib._,s=[...commonPropertyTypes];for(const t in propertyType)s.push(...Object.keys(propertyType[t]));return t&&!r(t.constructor.propertyKeys)&&s.push(...t.constructor.propertyKeys),e(s)};init=async()=>{const{getPluginDataDir:t}=this.app.bajo,{fs:e}=this.app.lib;await collectDrivers.call(this),await collectConnections.call(this),await collectFeatures.call(this),await collectModels.call(this);const r=`${t("dobo")}/attachment`;e.ensureDirSync(r)};start=async(t="all",e=!0)=>{t="all"===t?this.connections:n(t)?i(this.connections,{name:t}):a(t,(t=>s(this.connections,{name:t}))),this.log.debug("dbInit");for(const r of t)await r.connect(e),this.log.trace("dbInit%s%s%s",r.driver.plugin.ns,r.driver.name,r.name)};getConnection=(t,e)=>{const r=s(this.connections,{name:t});if(!r&&!e)throw this.error("unknown%s%s",this.t("connection"),t);return r};getDriver=(t,e)=>{const{breakNsPath:r}=this.app.bajo;let n;if(!t.includes(":")){if(n=s(this.drivers,{name:t}),n)return n;if(n=i(this.drivers,(e=>e.plugin.ns===t)),1===n.length)return n[0];if(!e)throw this.error("unknown%s%s",this.t("driver"),t);return}const{ns:a,path:o}=r(t);if(n=s(this.drivers,(t=>t.name===o&&t.plugin.ns===a)),!n&&!e)throw this.error("unknown%s%s",this.t("driver"),t);return n};getFeature=t=>{if(!t.includes(":"))return s(this.features,{name:t});const{ns:e,path:i}=r(t),n=s(this.features,(t=>t.name===i&&t.plugin.ns===e));if(!n)throw this.error("unknown%s%s",this.t("feature"),t);return n};getModel=(t,e)=>{const{pascalCase:r}=this.app.lib.aneka;let i=s(this.models,{name:t});if(i||(i=s(this.models,{name:r(t)})),!i&&!e)throw this.error("unknown%s%s",this.t("model"),t);return i};getModelsByConnection=t=>{const e=this.getConnection(t);return this.models.filter((t=>t.connection.name===e.name))};validationErrorMessage=t=>{let e=t.message;return t.details&&(e+=" -> ",e+=this.app.bajo.join(t.details.map(((e,r)=>`${e.field}@${t.model}: ${e.error} (${e.value})`)))),e};sanitizeDate=(t,{inputFormat:e,outputFormat:r,silent:s=!0}={})=>{const{dayjs:i}=this.app.lib;if(0===t)return null;r||(r=e);const n=i(t,e);if(!n.isValid()){if(s)return null;throw this.error("invalidDate")}return"native"!==r&&r?n.format(r):n.toDate()};sanitizeFloat=(t,{strict:e=!1}={})=>{const{isNumber:r}=this.app.lib._;return r(t)?t:e?Number(t):parseFloat(t)||null};sanitizeInt=(t,{strict:e=!1}={})=>{const{isNumber:r}=this.app.lib._;return r(t)?t:e?Number(t):parseInt(t)||null};sanitizeObject=(t,{strict:e=!1,action:r,model:s}={})=>{const{isString:i}=this.app.lib._;let n=null;if(i(t))try{n=JSON.parse(t)}catch(t){if(e)throw t}else try{n=JSON.parse(JSON.stringify(t))}catch(t){if(e)throw t}return n};sanitizeBoolean=t=>null===t?null:["true",!0].includes(t);sanitizeTimestamp=t=>{const{isNumber:e}=this.app.lib._,{dayjs:r}=this.app.lib;if(!e(t))return-1;const s=r.unix(t);return s.isValid()?s.unix():-1};sanitizeString=t=>t+"";_calcStats=(t,e,r)=>{const{generateId:s,isSet:i}=this.app.lib.aneka,n={id:s,count:0,avg:null,min:null,max:null};let a=0;for(const s of t){const t=Number(s[e])??0;r.includes("count")&&n.count++,r.includes("avg")&&(a+=t),r.includes("min")&&(!i(n.min)||t<n.min)&&(n.min=t),r.includes("max")&&(!i(n.max)||t>n.max)&&(n.max=t)}return n.avg=a/t.length,n};calcAggregate=({data:t=[],group:e="",field:r="",aggregates:s=["count"]}={})=>{this.checkAggregateParams({group:e,field:r,aggregates:s});const{pick:i,groupBy:n}=this.app.lib._,a=n(t,e),o=[];for(const t in a){const n=a[t],l=this._calcStats(n,r,s);l[e]=t,o.push(i(l,["id",e,...s]))}return o};calcHistogram=({data:t=[],type:e="",group:r="",field:s="",aggregates:i=["count"]}={})=>{this.checkHistogramParams({group:r,field:s,type:e,aggregates:i});const{dayjs:n}=this.app.lib,a={daily:["YYYY-MM-DD","date"],monthly:["YYYY-MM","month"],yearly:["YYYY","year"]};for(const s of t)s._group=n(s[r]).format(a[e][0]);const c=l(t,"_group"),p=[];for(const t in c){const r=c[t],n=this._calcStats(r,s,i),l=a[e][1];n[l]=t,p.push(o(n,["id",l,...i]))}return p};checkAggregateParams=(t={})=>{let{group:e,field:r,aggregates:s}=t;if(n(s)&&(s=[s]),t.aggregates=s,c(e))throw this.error("fieldGroupMissing");if(c(r))throw this.error("fieldCalcMissing");for(const t of s)if(!this.constructor.aggregateTypes.includes(t))throw this.error("unsupportedAggregateType%s",t)};checkHistogramParams=(t={})=>{this.checkAggregateParams(t);const{type:e}=t;if(c(e))throw this.error("histogramTypeMissing");if(!this.constructor.histogramTypes.includes(e))throw this.error("unsupportedHistogramType%s",e)};runModelHook=async(t,e,...r)=>{const{orderBy:s}=this.app.lib._,i=s(t.hooks.filter((t=>t.name===e)),["level"]);for(const e of i)e.noWait?e.handler.call(t,...r):await e.handler.call(t,...r)};getDefaultValues=(t={})=>{const{defaultsDeep:e}=this.app.lib.aneka;let r=this.getConfig("default.filter");r.hardCap=this.config.default.hardCap,r.warnings=this.config.default.warnings,t.req&&(r=e({},t.req.getSetting("dobo:default"),r));const{limit:s,maxLimit:i,maxPage:n,hardCap:a,warnings:o}=r;return{limit:s,maxLimit:i,hardCap:a,maxPage:n,warnings:o,t:t.req?t.req.t:this.t}};handleLastPage=(t={},e={})=>{const{count:r,limit:s,page:i}=t,{hardCap:n}=this.getDefaultValues(e);if(r>n){if(i>Math.floor(n/s)){return{data:[],count:n,warnings:[this.t("hardCapWarning%s%s",r,n)]}}}};parseNql=t=>{const e=t.split("+").map((t=>{const[e,...r]=t.split(":").map((t=>t.trim()));let s=r.join(":");const i="-"===s[1]?"-":"";if(("{"===s[0]||"{"===s[1])&&"}"===s[s.length-1]){"-"===s[0]&&(s=s.slice(1));const t=s.slice(1,-1).split(",");s=`${i}>=${t[0]}+${e}:${i}<=${t[1]}`}return`${e}:${s}`})).join("+");return nql(e).parse()};parseAny=(t,e)=>{const{isEmpty:r}=this.app.lib._;let i={};if(!e)throw this.error("invalidQuery");let n=[...e.scanables];0===n.length&&(n=[...e.sortables]);const a=n.filter((t=>!!s(e.properties,{name:t,type:"string"}))).map((e=>"*"===t[0]?`${e}:~$'${t.replaceAll("*","")}'`:"*"===t[t.length-1]?`${e}:~^'${t.replaceAll("*","")}'`:`${e}:~'${t.replaceAll("*","")}'`));if(1===a.length?i=this.parseNql(a[0]):a.length>1&&(i=this.parseNql(a.join(","))),r(i))throw this.error("invalidQuery");return i};parseQuery=(t,e,r=!0)=>{const{isEmpty:s,isPlainObject:i,trim:n}=this.app.lib._;let a={};if(i(t))a=t;else{if(s(t=n(t)))return a;try{a=t.startsWith("{")?JSON.parse(t):t.includes(":")?this.parseNql(t):this.parseAny(t,e)}catch(t){if(r)return{};throw t}}let o=this.replaceRegexInJson(a);e&&"id"!==e.driver.idField.name&&(o=o.replaceAll('"id"',`"${e.driver.idField.name}"`));try{a=this.reviveRegexInJson(o)}catch(t){}return a};replaceRegexInJson=(t={},e=!0)=>{const{isString:r}=this.app.lib._;r(t)&&(t=JSON.parse(t)??{});const s=JSON.stringify(t,((t,e)=>e instanceof RegExp?["__REGEXP__",e.source,e.flags]:e));return e?s:JSON.parse(s)};reviveRegexInJson=(t,e=!0)=>{const{isPlainObject:r}=this.app.lib._;r(t)&&(t=JSON.stringify(t));const s=JSON.parse(t,((t,e)=>Array.isArray(e)&&"__REGEXP__"===e[0]?new RegExp(e[1],e[2]):e));return e?s:JSON.stringify(s)}}return p}export default factory;
//# sourceMappingURL=/sm/05008afbafd89f09ea0c537acfba1fb238c7f7562715e5b2946a618481aa945e.map