@budibase/pro 2.32.16 → 2.33.0
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 +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var types=require("@budibase/types"),backendCore=require("@budibase/backend-core"),fetch$6=require("node-fetch"),fs=require("fs"),path=require("path"),LRU=require("lru-cache"),jwt=require("jsonwebtoken"),union=require("lodash/union"),merge=require("lodash/merge"),os=require("os"),tracer=require("dd-trace"),stringTemplates=require("@budibase/string-templates"),lodashMerge=require("lodash/fp/merge"),dayjs=require("dayjs"),OpenAIClient=require("openai"),AnthropicClient=require("@anthropic-ai/sdk"),Router=require("@koa/router"),Joi=require("joi"),scim2ParseFilter=require("scim2-parse-filter"),sharedCore=require("@budibase/shared-core"),scimPatch=require("scim-patch"),groupBy=require("lodash/groupBy"),Method;function __rest(e,t){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(a[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(a[i[o]]=e[i[o]])}return a}function __awaiter(e,t,a,i){return new(a||(a=Promise))((function(o,n){function s(e){try{u(i.next(e))}catch(e){n(e)}}function r(e){try{u(i.throw(e))}catch(e){n(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(s,r)}u((i=i.apply(e,t||[])).next())}))}let client$1;exports.Method=void 0,Method=exports.Method||(exports.Method={}),Method.POST="POST",Method.GET="GET",Method.PATCH="PATCH",Method.DELETE="DELETE",Method.PUT="PUT","function"==typeof SuppressedError&&SuppressedError;const init$4=()=>__awaiter(void 0,void 0,void 0,(function*(){client$1=yield new backendCore.redis.Client(backendCore.redis.utils.Databases.LICENSES).init()})),shutdown=()=>__awaiter(void 0,void 0,void 0,(function*(){client$1&&(yield client$1.finish())}));process.on("exit",(()=>__awaiter(void 0,void 0,void 0,(function*(){yield shutdown()}))));const getClient=()=>__awaiter(void 0,void 0,void 0,(function*(){return client$1||(yield init$4()),client$1}));class API{constructor(e){this.apiCall=e=>(...t)=>__awaiter(this,[...t],void 0,(function*(t="",a={}){a.headers||(a.headers={}),a.headers["Content-Type"]||(a.headers=Object.assign({"Content-Type":"application/json",Accept:"application/json"},a.headers));const i="application/json"===a.headers["Content-Type"];backendCore.logging.correlation.setHeader(a.headers);const o={method:e,body:i?JSON.stringify(a.body):a.body,headers:a.headers,credentials:"include"};return fetch$6(`${this.host}${t}`,o)})),this.post=this.apiCall(exports.Method.POST),this.get=this.apiCall(exports.Method.GET),this.patch=this.apiCall(exports.Method.PATCH),this.del=this.apiCall(exports.Method.DELETE),this.put=this.apiCall(exports.Method.PUT),this.host=e}}const getNextQuotaReset=()=>{const e=new Date;return new Date(e.getFullYear(),e.getMonth()+1,1).toISOString()},setQuotaReset=e=>{e.quotaReset=getNextQuotaReset()},getCurrentMonthString=()=>{const e=new Date;return`${e.getMonth()+1}-${e.getFullYear()}`},generateBaseQuotaUsage=()=>({usageQuota:{[types.StaticQuotaName.APPS]:0,[types.StaticQuotaName.ROWS]:0,[types.StaticQuotaName.PLUGINS]:0,[types.StaticQuotaName.USERS]:0,[types.StaticQuotaName.CREATORS]:0,[types.StaticQuotaName.USER_GROUPS]:0,[types.StaticQuotaName.AI_CUSTOM_CONFIGS]:0,triggers:{}},monthly:{[getCurrentMonthString()]:generateNewMonthlyQuotas()}}),generateNewQuotaUsage=()=>{const e=Object.assign(Object.assign({_id:backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota,quotaReset:getNextQuotaReset()},generateBaseQuotaUsage()),{apps:{}});return setCurrentMonth(e),e},generateNewMonthlyQuotas=()=>({[types.MonthlyQuotaName.QUERIES]:0,[types.MonthlyQuotaName.AUTOMATIONS]:0,[types.MonthlyQuotaName.DAY_PASSES]:0,[types.MonthlyQuotaName.BUDIBASE_AI_CREDITS]:0,triggers:{}}),setCurrentMonth=e=>{const t=getCurrentMonthString();e.monthly||(e.monthly={}),e.monthly[t]||(e.monthly[t]=generateNewMonthlyQuotas()),e.monthly.current=e.monthly[t]},getBreakdownName=(e,t)=>{if(t&&e)switch(e){case types.MonthlyQuotaName.AUTOMATIONS:return types.BreakdownQuotaName.AUTOMATIONS;case types.MonthlyQuotaName.QUERIES:return backendCore.db.isTableId(t)?types.BreakdownQuotaName.ROW_QUERIES:backendCore.db.isDatasourceId(t)?types.BreakdownQuotaName.DATASOURCE_QUERIES:void 0}};var utils=Object.freeze({__proto__:null,generateBaseQuotaUsage:generateBaseQuotaUsage,generateNewMonthlyQuotas:generateNewMonthlyQuotas,generateNewQuotaUsage:generateNewQuotaUsage,getBreakdownName:getBreakdownName,getCurrentMonthString:getCurrentMonthString,setCurrentMonth:setCurrentMonth,setQuotaReset:setQuotaReset});const DB_WRITE_RATE_MS=backendCore.Duration.fromSeconds(60).toMs(),{Writethrough:Writethrough}=backendCore.cache.writethrough;function clearDeprecated(e){return delete e.usageLimits,delete e.usageQuota.automationRuns,delete e.usageQuota.emails,delete e.usageQuota.storage,delete e.usageQuota.views,delete e.usageQuota.publishedApps,delete e.usageQuota.developers,e}const getDB$1=()=>new Writethrough(backendCore.tenancy.getGlobalDB(),DB_WRITE_RATE_MS),bustCache=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=getDB$1();try{const t=yield e.get(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota);(null==t?void 0:t._rev)&&(yield e.remove(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota,null==t?void 0:t._rev))}catch(e){if(404!==e.status)throw e}})),getQuotaUsage=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=getDB$1();let t;try{t=yield e.get(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota),setCurrentMonth(t),setQuotaReset(t)}catch(a){if(404!==a.status)throw a;{t=generateNewQuotaUsage();const a=yield e.put(t);t._rev=a.rev}}return clearDeprecated(t)})),setUsage=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){return setAllUsage({name:t,type:a,values:{total:e}})})),setUsagePerApp=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=getDB$1();let o=yield getQuotaUsage();const n=Object.values(e).reduce(((e,t)=>e+t),0);for(let[i,s]of Object.entries(e))o=coreUsageUpdate(o,t,a,{total:n,app:s},{appId:i});const s=yield i.put(o);return o._rev=s.rev,o})),setBreakdown=(e,t,a,i)=>{const o=getBreakdownName(t,a);if(!o||!(null==i?void 0:i.breakdown))return e;e.breakdown||(e.breakdown={}),e.breakdown[o]||(e.breakdown[o]={parent:t,values:{}});return e.breakdown[o].values[a]=i.breakdown,e},setAppUsageValue=(e,t,a,i={},o)=>{var n;let s;try{s=backendCore.db.getProdAppID((null==i?void 0:i.appId)||backendCore.context.getAppId())}catch(e){}if(!s||!o.app||!types.APP_QUOTA_NAMES.includes(t))return e;(null===(n=e.apps)||void 0===n?void 0:n[s])||(e.apps=Object.assign(Object.assign({},e.apps),{[s]:generateBaseQuotaUsage()}));const r=e.apps[s];switch(a){case types.QuotaUsageType.STATIC:r.usageQuota[t]=o.app;break;case types.QuotaUsageType.MONTHLY:{const e=getCurrentMonthString(),a=t;let n=r.monthly[e];n||(r.monthly[e]=generateNewMonthlyQuotas(),n=r.monthly[e]),n[a]=o.app,types.BREAKDOWN_QUOTA_NAMES.includes(a)&&(null==i?void 0:i.id)&&(n=setBreakdown(n,a,i.id,o));break}}return e},getAppUsageValue=(e,t,a,i)=>{var o,n,s,r,u;if(!types.APP_QUOTA_NAMES.includes(a))return{};let d;try{d=backendCore.db.getProdAppID(backendCore.context.getAppId())}catch(e){}if(!d||!e.apps||!e.apps[d])return{app:0};const c=e.apps[d];switch(t){case types.QuotaUsageType.STATIC:if(null===(o=c.usageQuota)||void 0===o?void 0:o[a])return{app:c.usageQuota[a]};break;case types.QuotaUsageType.MONTHLY:{const e=getCurrentMonthString(),t=a;if(!(null===(s=null===(n=c.monthly)||void 0===n?void 0:n[e])||void 0===s?void 0:s[t]))break;const o=c.monthly[e],d=o[t];let l;const p=getBreakdownName(t,i);return p&&i&&(null===(r=o.breakdown)||void 0===r?void 0:r[p])&&(l=null===(u=o.breakdown[p])||void 0===u?void 0:u.values[i]),{app:d,breakdown:l||0}}}return{app:0}},setStaticTriggers=(e,t,a)=>{t.usageQuota.triggers||(t.usageQuota.triggers={}),a&&(t.usageQuota.triggers[e]=a)},setMonthlyTriggers=(e,t,a,i)=>{a.monthly[t].triggers||(a.monthly[t].triggers={}),i&&(a.monthly[t].triggers[e]=i)},coreUsageUpdate=(e,t,a,i,o={})=>{if(a===types.QuotaUsageType.STATIC)e.usageQuota[t]=i.total,setStaticTriggers(t,e,i.triggers);else{if(a!==types.QuotaUsageType.MONTHLY)throw new Error(`Invalid usage type: ${a}`);{const a=getCurrentMonthString();e.monthly[a][t]=i.total,setMonthlyTriggers(t,a,e,i.triggers)}}return setAppUsageValue(e,t,a,o,i)},setAllUsage=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=Array.isArray(e)?e:[e],a=getDB$1();let i=yield getQuotaUsage();for(let e of t)i=coreUsageUpdate(i,e.name,e.type,e.values,e.opts);const o=yield a.put(i,0);return i._rev=o.rev,i})),getCurrentUsageValues=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield getQuotaUsage();let o=0,n={};switch(e){case types.QuotaUsageType.STATIC:if(i.usageQuota[t]){const s=t;o=i.usageQuota[s],n=getAppUsageValue(i,e,t,a)}break;case types.QuotaUsageType.MONTHLY:{const s=getCurrentMonthString(),r=t;i.monthly[s][r]&&(o=i.monthly[s][r],n=getAppUsageValue(i,e,t,a));break}default:throw new Error(`Invalid usage type: ${e}`)}return!types.APP_QUOTA_NAMES.includes(t)||n.app||n.breakdown||(n.app=n.app||0,n.breakdown=n.breakdown||0),{total:o,app:n.app,breakdown:n.breakdown}})),newLicenseInfo=()=>({_id:backendCore.StaticDatabases.GLOBAL.docs.licenseInfo}),save$4=e=>__awaiter(void 0,void 0,void 0,(function*(){let t=yield get$6();t=Object.assign(Object.assign({},t),e);const a=backendCore.tenancy.getGlobalDB(),i=yield a.put(t);return t._rev=i.rev,t})),get$6=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB();try{return yield e.get(backendCore.StaticDatabases.GLOBAL.docs.licenseInfo)}catch(e){if(404===e.status)return newLicenseInfo();throw e}}));function createAuditLogDesignDocLucene(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getAuditLogsDB();let t;try{t=yield e.get("_design/database")}catch(e){404===e.status&&(t={_id:"_design/database"})}t.indexes={[types.SearchIndex.AUDIT]:{index:function(e){if(e._id&&!e._id.startsWith("al_"))return;const t=["_id","_rev","metadata"];let a=Object.values(e.metadata).join(" ");for(let i of Object.keys(e)){if(t.includes(i))continue;const o=e[i];"string"==typeof o&&(index(i,o.toLowerCase(),{facet:!0}),a+=` ${o}`)}if(e.fallback)for(let t of Object.values(e.fallback))t&&"string"==typeof t&&(a+=` ${t}`);index("all",a)}.toString(),analyzer:{default:"whitespace",fields:{all:"standard"},name:"perfield"}}},yield e.put(t)}))}function createAuditLogDesignDocSQL(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.sql.designDoc.base("type");e.sql.tables={[types.AUDIT_LOG_TYPE]:{fields:{appId:types.SQLiteType.TEXT,event:types.SQLiteType.TEXT,userId:types.SQLiteType.TEXT,timestamp:types.SQLiteType.TEXT,metadata:types.SQLiteType.TEXT,name:types.SQLiteType.TEXT,type:types.SQLiteType.TEXT,fallback:types.SQLiteType.TEXT}}};const t=backendCore.context.getAuditLogsDB();let a;try{a=yield t.get(backendCore.SQLITE_DESIGN_DOC_ID),a=Object.assign(Object.assign({},a),e)}catch(t){if(404!==t.status)throw t;a=e}yield t.put(a)}))}const{ViewName:ViewName$2,SEPARATOR:SEPARATOR$2,DocumentType:DocumentType$2,createView:createView$1}=backendCore.db,USER_PREFIX=DocumentType$2.USER+SEPARATOR$2;var GroupViewMode;function createGroupUserLookupView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=`function(doc) {\n if (doc._id.startsWith("${USER_PREFIX}") && Array.isArray(doc.userGroups)) {\n for (let groupId of doc.userGroups) {\n emit("${GroupViewMode.SEARCH_BY_ID}" + groupId, { email: doc.email, userId: doc._id })\n emit("${GroupViewMode.SEARCH_BY_EMAIL}" + groupId + doc.email, { email: doc.email, userId: doc._id })\n }\n }\n }`;yield createView$1(e,t,ViewName$2.USER_BY_GROUP)}))}!function(e){e.SEARCH_BY_ID="g_",e.SEARCH_BY_EMAIL="e_"}(GroupViewMode||(GroupViewMode={}));const GROUP_PREFIX=`${backendCore.DocumentType.GROUP}${backendCore.SEPARATOR}`;function getUserGroupsParams(e,t={}){e||(e="");const a=(null==e?void 0:e.startsWith(backendCore.DocumentType.GROUP))?"":GROUP_PREFIX;return Object.assign(Object.assign({},t),{startkey:`${a}${e}`,endkey:`${a}${e}${backendCore.UNICODE_MAX}`})}function getGroupUsersParams(e,t={}){e||(e="");const{emailSearch:a,bookmark:i}=t,o=__rest(t,["emailSearch","bookmark"]);if(!a)return Object.assign(Object.assign({},t),{startkey:`${GroupViewMode.SEARCH_BY_ID}${e}`,endkey:`${GroupViewMode.SEARCH_BY_ID}${e}${backendCore.UNICODE_MAX}`,startkey_docid:i});return Object.assign(Object.assign({},o),{startkey:`${GroupViewMode.SEARCH_BY_EMAIL}${e}${i||a}`,endkey:`${GroupViewMode.SEARCH_BY_EMAIL}${e}${a}${backendCore.UNICODE_MAX}`})}function generateUserGroupID(){return`${GROUP_PREFIX}${backendCore.utils.newid()}`}function getGroupUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB();return(yield backendCore.db.queryView(backendCore.db.ViewName.USER_BY_GROUP,getGroupUsersParams(e,t),a,createGroupUserLookupView,{arrayResponse:!0})).map((e=>({_id:e.userId,email:e.email})))||[]}))}function enrichGroup(e){return __awaiter(this,void 0,void 0,(function*(){return e.users=yield getGroupUsers(e._id),e}))}function cleanupUsers(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=null===(t=(yield enrichGroup(e)).users)||void 0===t?void 0:t.map((e=>e._id)),i=yield backendCore.users.bulkGetGlobalUsersById(a),o=[];for(let t of i){if(!t.userGroups)continue;const a=t.userGroups.length;t.userGroups=t.userGroups.filter((t=>t!==e._id)),t.userGroups.length!==a&&o.push(t)}o.length&&(yield backendCore.users.bulkUpdateGlobalUsers(o))}))}function fetch$5(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=(yield e.allDocs(getUserGroupsParams(null,{include_docs:!0}))).rows.map((e=>e.doc)),a=[];for(let e of t)a.push(enrichGroup(e));return yield Promise.all(a)}))}function get$5(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB(),a=yield t.get(e);return yield enrichGroup(a)}))}function getBulk$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={enriched:!0}){const a=backendCore.tenancy.getGlobalDB(),i=yield a.getMultiple(e,{allowMissing:!0});if(null==t?void 0:t.enriched){const e=[];for(let t of i)e.push(enrichGroup(t));return yield Promise.all(e)}return i}))}function save$3(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.put(e)}))}function bulkSave(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.bulkDocs(e)}))}function destroy$2(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB(),i=yield a.get(e);let o=yield a.remove(e,t);return yield cleanupUsers(i),o}))}function getByName(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield backendCore.db.directCouchFind(backendCore.tenancy.getGlobalDBName(),{selector:{name:{$regex:`^(?i)${e}$`}},limit:1}),[a]=t.rows;if(a)return yield enrichGroup(a)}))}function pagination(e,t){var a;const i=e.rows.map((e=>e.doc?e.doc:e));if(!(null==t?void 0:t.paginate))return{data:i,hasNextPage:!1};const o=i.length>(null==t?void 0:t.pageSize);return{data:i.slice(0,null==t?void 0:t.pageSize),hasNextPage:o,nextPage:o?null===(a=i[null==t?void 0:t.pageSize])||void 0===a?void 0:a._id:void 0}}const{ViewName:ViewName$1,AutomationViewMode:AutomationViewMode$1,SEPARATOR:SEPARATOR$1,DocumentType:DocumentType$1,createView:createView}=backendCore.db,LOG_PREFIX=DocumentType$1.AUTOMATION_LOG+SEPARATOR$1,APP_BACKUP_PREFIX$1=DocumentType$1.APP_BACKUP+SEPARATOR$1;function createLogByAutomationView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getProdAppDB(),t=`function(doc) {\n if (doc._id.startsWith("${LOG_PREFIX}")) {\n let autoId = doc.automationId + "${SEPARATOR$1}"\n let status = doc.status + "${SEPARATOR$1}"\n let autoKey = "${AutomationViewMode$1.AUTOMATION}${SEPARATOR$1}" + autoId + doc.createdAt\n let statusKey = "${AutomationViewMode$1.STATUS}${SEPARATOR$1}" + status + doc.createdAt\n let allKey = "${AutomationViewMode$1.ALL}${SEPARATOR$1}" + status + autoId + doc.createdAt\n emit(statusKey)\n emit(autoKey)\n emit(allKey)\n }\n }`;yield createView(e,t,ViewName$1.AUTOMATION_LOGS)}))}function createAppBackupTriggerView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=`function(doc) {\n if (doc._id.startsWith("${APP_BACKUP_PREFIX$1}") && doc.type && doc.trigger) {\n let full = doc.appId + "${SEPARATOR$1}"\n full += doc.trigger.toLowerCase() + "${SEPARATOR$1}"\n full += doc.type.toLowerCase() + "${SEPARATOR$1}"\n emit("${APP_BACKUP_PREFIX$1}" + full + doc.timestamp) \n }\n }`;yield createView(e,t,ViewName$1.APP_BACKUP_BY_TRIGGER)}))}const UNLIMITED$2=-1,rows=e=>({[types.StaticQuotaName.ROWS]:{name:"Rows",value:e,triggers:[90,100]}}),apps=e=>({[types.StaticQuotaName.APPS]:{name:"Apps",value:e,triggers:[100]}}),users$3=e=>({[types.StaticQuotaName.USERS]:{name:"Users",value:e,triggers:[80,100]}}),creators=e=>({[types.StaticQuotaName.CREATORS]:{name:"Creators",value:e,triggers:[]}}),userGroups=e=>({[types.StaticQuotaName.USER_GROUPS]:{name:"User Groups",value:e,triggers:[80,100]}}),plugins=e=>({[types.StaticQuotaName.PLUGINS]:{name:"Plugins",value:e,triggers:[90,100]}}),queries=e=>({[types.MonthlyQuotaName.QUERIES]:{name:"Queries",value:e,triggers:[]}}),automations=e=>({[types.MonthlyQuotaName.AUTOMATIONS]:{name:"Automations",value:e,triggers:[80,90,100]}}),dayPasses=e=>({[types.MonthlyQuotaName.DAY_PASSES]:{name:"Day Passes",value:e,triggers:[80,90,100]}}),budibaseAICredits=e=>({[types.MonthlyQuotaName.BUDIBASE_AI_CREDITS]:{name:"Budibase AI Credits",value:e,triggers:[80,90,100]}}),automationLogRetentionDays=e=>({[types.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS]:{name:"Automation Logs",value:e,triggers:[]}}),appBackupRetentionDays=e=>({[types.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS]:{name:"App Backups",value:e,triggers:[]}}),customAIConfigurations=e=>({[types.StaticQuotaName.AI_CUSTOM_CONFIGS]:{name:"Custom AI Configuration",value:e,triggers:[]}});var quotas$3=Object.freeze({__proto__:null,UNLIMITED:UNLIMITED$2,appBackupRetentionDays:appBackupRetentionDays,apps:apps,automationLogRetentionDays:automationLogRetentionDays,automations:automations,budibaseAICredits:budibaseAICredits,creators:creators,customAIConfigurations:customAIConfigurations,dayPasses:dayPasses,plugins:plugins,queries:queries,rows:rows,userGroups:userGroups,users:users$3});const UNLIMITED$1=-1,CLOUD_FREE_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(200)),dayPasses(UNLIMITED$1)),budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},apps(UNLIMITED$1)),rows(2e3)),users$3(5)),creators(5)),userGroups(0)),plugins(10)),customAIConfigurations(0))},constant:Object.assign(Object.assign({},automationLogRetentionDays(1)),appBackupRetentionDays(0))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}},SELF_FREE_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(UNLIMITED$1)),dayPasses(UNLIMITED$1)),budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},rows(UNLIMITED$1)),apps(UNLIMITED$1)),users$3(20)),creators(UNLIMITED$1)),userGroups(0)),plugins(10)),customAIConfigurations(0))},constant:Object.assign(Object.assign({},automationLogRetentionDays(1)),appBackupRetentionDays(0))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}},UNLIMITED_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(UNLIMITED$1)),dayPasses(UNLIMITED$1)),budibaseAICredits(UNLIMITED$1)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},apps(UNLIMITED$1)),rows(UNLIMITED$1)),users$3(UNLIMITED$1)),creators(UNLIMITED$1)),userGroups(UNLIMITED$1)),plugins(UNLIMITED$1)),customAIConfigurations(UNLIMITED$1))},constant:Object.assign(Object.assign({},automationLogRetentionDays(UNLIMITED$1)),appBackupRetentionDays(UNLIMITED$1))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}};var licenses$1=Object.freeze({__proto__:null,CLOUD_FREE_LICENSE:CLOUD_FREE_LICENSE,SELF_FREE_LICENSE:SELF_FREE_LICENSE,UNLIMITED:UNLIMITED$1,UNLIMITED_LICENSE:UNLIMITED_LICENSE});const getLicenseVersion=()=>{if(backendCore.env.isDev()){const e="dev-version.txt",t=path.join(backendCore.objectStore.budibaseTempDir(),e);if(fs.existsSync(t))return fs.readFileSync(t,"utf8");{const e=backendCore.utils.newid();return fs.writeFileSync(t,e),e}}return getProVersion()},getProVersion=()=>{const e=backendCore.env.VERSION;if(!e)throw new Error("No budibase pro version was specified");return e};var version=Object.freeze({__proto__:null,getLicenseVersion:getLicenseVersion,getProVersion:getProVersion});function searchTable(){return{type:"table",sourceType:types.TableSourceType.INTERNAL,name:types.AUDIT_LOG_TYPE,sourceId:backendCore.SQS_DATASOURCE_INTERNAL,primary:["_id"],schema:{metadata:{name:"metadata",type:types.FieldType.JSON},fallback:{name:"fallback",type:types.FieldType.JSON}}}}var auditLogs=Object.freeze({__proto__:null,searchTable:searchTable});const GENERIC_PAGE_SIZE=9;var index$j=Object.freeze({__proto__:null,GENERIC_PAGE_SIZE:GENERIC_PAGE_SIZE,auditLogs:auditLogs,licenses:licenses$1,quotas:quotas$3,versions:version});const MAX_DATE$1=new Date(864e13).toISOString(),ONE_DAY_MILLIS=864e5;function getOldestRetentionDate(e){return __awaiter(this,void 0,void 0,(function*(){var t,a,i;const o=(null===(i=null===(a=null===(t=(yield getCachedLicense()).quotas)||void 0===t?void 0:t[types.QuotaType.CONSTANT])||void 0===a?void 0:a[e])||void 0===i?void 0:i.value)||0;return o===UNLIMITED$1?new Date(MAX_DATE$1).toISOString():new Date((new Date).getTime()-ONE_DAY_MILLIS*o).toISOString()}))}function oldestBackupDate(){return __awaiter(this,void 0,void 0,(function*(){return getOldestRetentionDate(types.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS)}))}const APP_BACKUP_PREFIX=`${backendCore.db.DocumentType.APP_BACKUP}${backendCore.db.SEPARATOR}`;function getAppBackupParams(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){const i=yield oldestBackupDate(),o=backendCore.db.getProdAppID(e);let n=o,s=o;if(t.trigger&&t.type){let e=`${backendCore.db.SEPARATOR}${t.trigger}`;e+=`${backendCore.db.SEPARATOR}${t.type}`,n+=e,s+=e}return(!t.startDate||t.startDate<i)&&(t.startDate=i),t.startDate&&(s+=`${backendCore.db.SEPARATOR}${t.startDate}`),t.endDate&&(n+=`${backendCore.db.SEPARATOR}${t.endDate}`),Object.assign(Object.assign({},a),{descending:!0,startkey:`${APP_BACKUP_PREFIX}${n}${backendCore.db.UNICODE_MAX}`,endkey:`${APP_BACKUP_PREFIX}${s}`})}))}function getAppBackupsByTrigger(e,t){return __awaiter(this,void 0,void 0,(function*(){let a=[];try{const i=backendCore.db.getQueryIndex(backendCore.db.ViewName.APP_BACKUP_BY_TRIGGER);a=yield e.query(i,t)}catch(a){if(null!=a&&"not_found"===a.error)return yield createAppBackupTriggerView(),getAppBackupsByTrigger(e,t);throw a}return a}))}function generateAppBackupID(e,t){return`${APP_BACKUP_PREFIX}${e}${backendCore.db.SEPARATOR}${t}`}function fetchAppBackups$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){const a=backendCore.tenancy.getGlobalDB();let i;const o=t.limit||GENERIC_PAGE_SIZE,n=yield getAppBackupParams(e,t,{include_docs:!0,limit:o+1});t.page&&(n.startkey=t.page),i=t.trigger&&t.type?yield getAppBackupsByTrigger(a,n):yield a.allDocs(n);const s=pagination(i,{paginate:t.paginate,pageSize:o}),r=[...new Set(s.data.filter((e=>e.createdBy)).map((e=>e.createdBy)))],u=yield backendCore.users.bulkGetGlobalUsersById(r,{cleanup:!0});for(let e of u)for(let t of s.data)(null==e?void 0:e._id)===t.createdBy&&(t.createdBy=e);return s}))}function storeAppBackupMetadata$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){const a=backendCore.tenancy.getGlobalDB(),i=backendCore.db.getProdAppID(e.appId);let o=generateAppBackupID(i,e.timestamp);const n=Object.assign(Object.assign({},e),{_id:o,appId:i,name:e.name});return n._id=t.docId||n._id,n._rev=t.docRev||n._rev,t.filename&&(n.filename=t.filename),e.createdBy&&(n.createdBy=backendCore.db.getGlobalIDFromUserMetadataID(e.createdBy)),yield a.put(n)}))}function updateAppBackupMetadata(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB(),i=yield a.get(e);return i.name=t,yield a.put(i)}))}function deleteAppBackupMetadata(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB(),a=yield t.get(e);yield t.remove(a._id,a._rev)}))}function getAppBackupMetadata(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.get(e)}))}const MAX_CACHE_ITEMS=1e3,cache=new LRU({max:MAX_CACHE_ITEMS});function getEnvVarID(){return backendCore.StaticDatabases.GLOBAL.docs.environmentVariables}function getCacheEnvVarID(e){return`${backendCore.tenancy.getTenantId()}/${getEnvVarID()}/${e||""}`}function get$4(){return __awaiter(this,void 0,void 0,(function*(){const e=getEnvVarID(),t=backendCore.tenancy.getGlobalDB();let a,i=!1;try{a=yield t.get(e)}catch(e){if(404!=e.status)throw e;i=!0}const o=getCacheEnvVarID(null==a?void 0:a._rev),n=cache.get(o);if(n)return n;let s;return s=!i&&a?Object.assign(Object.assign({},a),{variables:JSON.parse(backendCore.encryption.decrypt(a.variables,backendCore.encryption.SecretOption.ENCRYPTION))}):{_id:e,variables:{}},cache.set(o,s),s}))}function update$5(e){return __awaiter(this,void 0,void 0,(function*(){const t=getEnvVarID(),a=backendCore.tenancy.getGlobalDB();return yield a.put({_id:e._id||t,_rev:e._rev||void 0,variables:backendCore.encryption.encrypt(JSON.stringify(e.variables),backendCore.encryption.SecretOption.ENCRYPTION)})}))}const api$1=new API(backendCore.env.ACCOUNT_PORTAL_URL),getResponseErrorMessage=e=>__awaiter(void 0,void 0,void 0,(function*(){try{const t=yield e.json();if(t.message)return t.message}catch(e){}try{const t=yield e.text();if(t)return t}catch(e){}})),authAware=e=>__awaiter(void 0,void 0,void 0,(function*(){let t,a;if(backendCore.env.SELF_HOSTED){if(t=yield get$6(),!t.licenseKey)return;a={[backendCore.constants.Header.LICENSE_KEY]:t.licenseKey}}else{const e=backendCore.tenancy.getTenantId();a={[backendCore.constants.Header.API_KEY]:backendCore.env.ACCOUNT_PORTAL_API_KEY,[backendCore.constants.Header.TENANT_ID]:e}}return e(a)}));let _getLicense=()=>__awaiter(void 0,void 0,void 0,(function*(){return authAware((e=>__awaiter(void 0,void 0,void 0,(function*(){const t=yield getQuotaUsage();if(null==t.usageQuota.users){const e=yield backendCore.users.getUserCount();console.info(`Syncing user count quota to ${e}`),t.usageQuota.users=e,yield setUsage(e,types.StaticQuotaName.USERS,types.QuotaUsageType.STATIC)}const a=yield backendCore.installation.getInstallFromDB(),i=backendCore.tenancy.getTenantId(),o=yield backendCore.events.identification.getUniqueTenantId(i),n=getProVersion(),s={quotaUsage:t,install:{id:a.installId,tenantId:o,version:n}},r=yield api$1.post("/api/license",{headers:Object.assign({},e),body:s});if(404!==r.status&&403!==r.status){if(200!==r.status){const e=yield getResponseErrorMessage(r);throw new backendCore.HTTPError(`Error getting license: ${e}`,r.status)}return r.json()}}))))}));backendCore.env.isJest()&&(_getLicense=jest.fn());const getLicense$1=_getLicense,triggerQuota$1=e=>authAware((t=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield api$1.post("/api/license/usage/triggered",{headers:Object.assign({},t),body:e});if(200!==a.status){const e=yield getResponseErrorMessage(a);backendCore.logging.logAlert(`Error triggering quota usage: ${e}`)}})))),activateLicenseKey$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t={installVersion:getProVersion()},a=yield api$1.post("/api/license/activate",{headers:{[backendCore.constants.Header.LICENSE_KEY]:e},body:t});if(403===a.status)throw new backendCore.HTTPError("Invalid license key",400);if(200!==a.status){const e=yield getResponseErrorMessage(a);throw new backendCore.HTTPError(`Error activating license key: ${e}`,a.status)}return a.json()}));var client=Object.freeze({__proto__:null,activateLicenseKey:activateLicenseKey$1,getLicense:getLicense$1,triggerQuota:triggerQuota$1});const PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvz3jePLCFBXZ19c8Dpkv\nXtSgOhKFOcvQdo/LV0KJRUzQWDPWuO4ILtBtnqhjtIzZH4CH0qCYBet5L6Qr4CM1\nl2HXiAD1Q2rlHNW9wDaYyKb1F5f+v4RyqCAyzlkwRdksmkLeECTboojNnmRCrE3C\n8suunQP5bEScqEY2kclqzSf8e6xqMzPUg3mL/pNa1iEv7TuLbU9nJfgR36l0WmZY\n94fWnSaT8OSXSqcxsaByf06gfS3HAoTJNc7eqz1Hf9fUORQGPUAnFK8cT3SfdA36\nd/o3ZWE1TTj1zYwlCLN5qRKr3hU8nC3xEYNEbkB9SfTRaOq9Q7P8WmfLkoCPm3pR\nmwIDAQAB\n-----END PUBLIC KEY-----\n";function verifyLicenseToken(e){return jwt.verify(e,PUBLIC_KEY,{algorithms:["RS256"]})}function sign(e,t){return jwt.sign(t,e,{encoding:"utf-8",algorithm:"RS256"})}var signing=Object.freeze({__proto__:null,sign:sign,verifyLicenseToken:verifyLicenseToken});const SELF_FEATURES={[types.PlanType.FREE]:[...SELF_FREE_LICENSE.features],[types.PlanType.PREMIUM]:void 0,[types.PlanType.PREMIUM_PLUS]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.PREMIUM_PLUS_TRIAL]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.PRO]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS],[types.PlanType.TEAM]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS],[types.PlanType.BUSINESS]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS],[types.PlanType.ENTERPRISE_BASIC]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.ENTERPRISE_BASIC_TRIAL]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.ENTERPRISE]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS]},CLOUD_FEATURES={[types.PlanType.FREE]:[...CLOUD_FREE_LICENSE.features],[types.PlanType.PREMIUM]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS],[types.PlanType.PREMIUM_PLUS]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.BUDIBASE_AI],[types.PlanType.PREMIUM_PLUS_TRIAL]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.BUDIBASE_AI],[types.PlanType.PRO]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.BRANDING],[types.PlanType.TEAM]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.BRANDING],[types.PlanType.BUSINESS]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE_BASIC]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE_BASIC_TRIAL]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI]};function getFeatures(e,t){let a=[];function i(a){const i=a[t];if(!i)throw new Error(`Features do not exist for planType=${t} and hosting=${e}`);return i}switch(e){case types.Hosting.SELF:a=i(SELF_FEATURES);break;case types.Hosting.CLOUD:a=i(CLOUD_FEATURES)}return a}var features$1=Object.freeze({__proto__:null,getFeatures:getFeatures});const quotas$1=quotas$3,licenses=licenses$1,UNLIMITED=-1,DERIVED=-2,CLOUD_QUOTAS={[types.PlanType.FREE]:Object.assign({},licenses.CLOUD_FREE_LICENSE.quotas),[types.PlanType.PREMIUM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(1e4)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.PREMIUM_PLUS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(25e3)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PREMIUM_PLUS_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(25e3)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PRO]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(5)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.TEAM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(10)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(90))},[types.PlanType.BUSINESS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e4)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(5e4)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(50)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(365)),quotas$1.appBackupRetentionDays(365))},[types.PlanType.ENTERPRISE_BASIC]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(UNLIMITED)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))},[types.PlanType.ENTERPRISE_BASIC_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(UNLIMITED)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(15)),quotas$1.appBackupRetentionDays(15))},[types.PlanType.ENTERPRISE]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))}},SELF_QUOTAS={[types.PlanType.FREE]:Object.assign({},licenses.SELF_FREE_LICENSE.quotas),[types.PlanType.PREMIUM]:void 0,[types.PlanType.PREMIUM_PLUS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PREMIUM_PLUS_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PRO]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(5)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.TEAM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(10)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(90))},[types.PlanType.BUSINESS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(50)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(90)),quotas$1.appBackupRetentionDays(365))},[types.PlanType.ENTERPRISE_BASIC]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))},[types.PlanType.ENTERPRISE_BASIC_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(15)),quotas$1.appBackupRetentionDays(15))},[types.PlanType.ENTERPRISE]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))}};function getQuotas(e,t){let a;function i(a){const i=a[t];if(!i)throw new Error(`Quotas do not exist for planType=${t} and hosting=${e}`);return i}switch(e){case types.Hosting.SELF:a=i(SELF_QUOTAS);break;case types.Hosting.CLOUD:a=i(CLOUD_QUOTAS)}return JSON.parse(JSON.stringify(a))}var quotas$2=Object.freeze({__proto__:null,UNLIMITED:UNLIMITED,getQuotas:getQuotas});function appExists(e){return __awaiter(this,void 0,void 0,(function*(){return(yield backendCore.db.getAllApps({all:!0,idsOnly:!0})).includes(e)}))}function objectToBase64(e){const t=JSON.stringify(e);return Buffer.from(t).toString("base64")}function base64ToObject(e){const t=Buffer.from(e,"base64").toString();return JSON.parse(t)}var encoding=Object.freeze({__proto__:null,base64ToObject:base64ToObject,objectToBase64:objectToBase64}),index$i=Object.freeze({__proto__:null,appExists:appExists,encoding:encoding});function activateOfflineLicenseToken(e){return __awaiter(this,void 0,void 0,(function*(){yield save$4({offlineLicenseToken:e}),yield refresh()}))}function deleteOfflineLicenseToken(){return __awaiter(this,void 0,void 0,(function*(){yield save$4({offlineLicenseToken:void 0}),yield refresh()}))}function getOfflineLicenseToken(){return __awaiter(this,void 0,void 0,(function*(){return(yield get$6()).offlineLicenseToken}))}function getIdentifier(){return __awaiter(this,void 0,void 0,(function*(){const e=(yield backendCore.installation.getInstall()).installId,t=backendCore.context.getTenantId();return{installId:e,tenantId:yield backendCore.events.identification.getUniqueTenantId(t)}}))}function getIdentifierBase64(){return __awaiter(this,void 0,void 0,(function*(){return objectToBase64(yield getIdentifier())}))}function getIdentifierFromBase64(e){return base64ToObject(e)}function verifyExpiry(e){if(Date.now()>new Date(e.expireAt).getTime())throw new Error(`Offline license has expired. expireAt=${e.expireAt}`)}function verifyInstallation(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getIdentifier();if(e.identifier.installId!==t.installId||e.identifier.tenantId!==t.tenantId)throw new Error("Invalid offline license")}))}function enrichLicense(e){const t=e.plan.type,a=types.Hosting.SELF,i=getFeatures(a,t),o=getQuotas(a,t);return e.features=union(e.features,i),e.quotas=merge(e.quotas,o),e}function getOfflineLicense$1(){return __awaiter(this,void 0,void 0,(function*(){try{const e=yield getOfflineLicenseToken();if(e){const t=yield verifyLicenseToken(e);return verifyExpiry(t),yield verifyInstallation(t),enrichLicense(t)}}catch(e){console.error("Error retrieving offline license",e)}}))}const SUB_DIRECTORY=backendCore.env.isTest()?".budibase-test":".budibase",DIRECTORY=path.join(os.tmpdir(),SUB_DIRECTORY),OFFLINE_LICENSE_FILE="dev_license.txt",LICENSE_FILE_PATH=path.join(DIRECTORY,OFFLINE_LICENSE_FILE);if(!fs.existsSync(DIRECTORY))try{fs.mkdirSync(DIRECTORY)}catch(e){}function getOfflineLicense(){try{if(fs.existsSync(LICENSE_FILE_PATH)){return verifyLicenseToken(fs.readFileSync(LICENSE_FILE_PATH,{encoding:"utf-8"}))}}catch(e){console.error("Error retrieving offline license from disk",e)}}function writeDevLicenseToDisk(e){console.log(`Writing license to: ${LICENSE_FILE_PATH}`),fs.writeFileSync(LICENSE_FILE_PATH,e,{encoding:"utf-8"})}function deleteDevLicense(){fs.rmSync(LICENSE_FILE_PATH,{force:!0})}var dev=Object.freeze({__proto__:null,deleteDevLicense:deleteDevLicense,getOfflineLicense:getOfflineLicense,writeDevLicenseToDisk:writeDevLicenseToDisk}),index$h=Object.freeze({__proto__:null,activateOfflineLicenseToken:activateOfflineLicenseToken,deleteOfflineLicenseToken:deleteOfflineLicenseToken,dev:dev,enrichLicense:enrichLicense,getIdentifier:getIdentifier,getIdentifierBase64:getIdentifierBase64,getIdentifierFromBase64:getIdentifierFromBase64,getOfflineLicense:getOfflineLicense$1,getOfflineLicenseToken:getOfflineLicenseToken,signing:signing,verifyExpiry:verifyExpiry,verifyInstallation:verifyInstallation});const getLicense=()=>__awaiter(void 0,void 0,void 0,(function*(){if(backendCore.env.OFFLINE_MODE)return getOfflineLicense$1();let e=yield getLicense$1();return e||(e=getOfflineLicense()),e})),getFreeLicense=()=>backendCore.env.SELF_HOSTED?SELF_FREE_LICENSE:CLOUD_FREE_LICENSE;function activateLicenseKey(e){return __awaiter(this,void 0,void 0,(function*(){yield activateLicenseKey$1(e),yield save$4({licenseKey:e}),yield refresh()}))}function getLicenseKey(){return __awaiter(this,void 0,void 0,(function*(){return(yield get$6()).licenseKey}))}function deleteLicenseKey(){return __awaiter(this,void 0,void 0,(function*(){yield save$4({licenseKey:void 0}),yield refresh()}))}var keys=Object.freeze({__proto__:null,activateLicenseKey:activateLicenseKey,deleteLicenseKey:deleteLicenseKey,getLicenseKey:getLicenseKey});const EXPIRY_SECONDS=3600,refresh=()=>__awaiter(void 0,void 0,void 0,(function*(){yield invalidate(),yield getCachedLicense()}));let _getCachedLicense=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const{populateLicense:a=getLicense,populateFreeLicense:i=getFreeLicense}=t||{};return yield tracer.trace("getCachedLicense",(t=>__awaiter(void 0,void 0,void 0,(function*(){const o=backendCore.tenancy.getTenantId(),n=yield getClient();let s=yield n.get(o);return t.addTags({tenantId:o,foundInCache:!!s}),s||(s=yield tracer.trace("populateLicense",(()=>__awaiter(void 0,void 0,void 0,(function*(){return yield a(o)})))),t.addTags({populatedLicense:!!s}),s||(s=tracer.trace("populateFreeLicense",(()=>i(e,o))),t.addTags({populatedFreeLicense:!!s})),s.refreshedAt=(new Date).toISOString(),t.addTags({refreshedAt:s.refreshedAt,expirySeconds:EXPIRY_SECONDS}),yield n.store(o,s,EXPIRY_SECONDS),s)}))))}));backendCore.env.isJest()&&(_getCachedLicense=jest.fn());const getCachedLicense=_getCachedLicense,invalidate=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.tenancy.getTenantId(),t=yield getClient();yield t.delete(e)}));var index$g=Object.freeze({__proto__:null,getCachedLicense:getCachedLicense,invalidate:invalidate,refresh:refresh}),index$f=Object.freeze({__proto__:null,cache:index$g,client:client,features:features$1,getFreeLicense:getFreeLicense,getLicense:getLicense,keys:keys,offline:index$h,quotas:quotas$2});function areFeaturesEnabled(e,t){return __awaiter(this,void 0,void 0,(function*(){Array.isArray(e)||(e=[e]),t||(t=yield getCachedLicense());for(let a of e)if(!(null==t?void 0:t.features.includes(a)))return!1;return!0}))}function checkFeature(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield areFeaturesEnabled(e,t)))throw new backendCore.FeatureDisabledError(`${e} is not currently enabled`,e)}))}function checkFeatures(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield areFeaturesEnabled(e,t))){const t=e.join(", ");throw new backendCore.FeatureDisabledError(`${t} are not currently enabled`,t)}}))}function checkBackups(e){return(...t)=>__awaiter(this,void 0,void 0,(function*(){return yield checkFeature(types.Feature.APP_BACKUPS),e(...t)}))}function isBackupsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.APP_BACKUPS)}))}function isBrandingEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.BRANDING)}))}function isEnforceableSSO(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.ENFORCEABLE_SSO)}))}function isSyncAutomationsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.SYNC_AUTOMATIONS)}))}function isTriggerAutomationRunEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.TRIGGER_AUTOMATION_RUN)}))}function isAppBuildersEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.APP_BUILDERS)}))}function isAuditLogsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.AUDIT_LOGS)}))}function isUserGroupsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.USER_GROUPS)}))}function isExpandedPublicApiEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.EXPANDED_PUBLIC_API)}))}function isSSOEnforced(e){return __awaiter(this,void 0,void 0,(function*(){if(backendCore.env.ENABLE_SSO_MAINTENANCE_MODE)return!1;if(!(yield isEnforceableSSO()))return!1;let t;return t=(null==e?void 0:e.config)?e.config:yield backendCore.configs.getSettingsConfig(),!!t.isSSOEnforced}))}const checkSCIM=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=types.Feature.SCIM,t=yield areFeaturesEnabled(e),a=yield backendCore.configs.getSCIMConfig();if(!t||!(null==a?void 0:a.enabled))throw new backendCore.FeatureDisabledError(`${e} is not currently enabled`,e);return!0}));function isViewPermissionEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.VIEW_PERMISSIONS)}))}function isViewReadonlyColumnsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.VIEW_READONLY_COLUMNS)}))}function isBudibaseAIEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.BUDIBASE_AI)}))}function isAICustomConfigsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.AI_CUSTOM_CONFIGS)}))}var features=Object.freeze({__proto__:null,checkBackups:checkBackups,checkFeature:checkFeature,checkFeatures:checkFeatures,checkSCIM:checkSCIM,isAICustomConfigsEnabled:isAICustomConfigsEnabled,isAppBuildersEnabled:isAppBuildersEnabled,isAuditLogsEnabled:isAuditLogsEnabled,isBackupsEnabled:isBackupsEnabled,isBrandingEnabled:isBrandingEnabled,isBudibaseAIEnabled:isBudibaseAIEnabled,isEnforceableSSO:isEnforceableSSO,isExpandedPublicApiEnabled:isExpandedPublicApiEnabled,isSSOEnforced:isSSOEnforced,isSyncAutomationsEnabled:isSyncAutomationsEnabled,isTriggerAutomationRunEnabled:isTriggerAutomationRunEnabled,isUserGroupsEnabled:isUserGroupsEnabled,isViewPermissionEnabled:isViewPermissionEnabled,isViewReadonlyColumnsEnabled:isViewReadonlyColumnsEnabled});const DEFAULT_BRANDING_CONFIG={faviconUrl:void 0,faviconUrlEtag:void 0,emailBrandingEnabled:!0,testimonialsEnabled:!0,platformTitle:void 0,loginHeading:void 0,loginButton:void 0,metaDescription:void 0,metaImageUrl:void 0,metaTitle:void 0};function getBrandingConfig(e){return __awaiter(this,void 0,void 0,(function*(){return(yield isBrandingEnabled())?{faviconUrl:e.faviconUrl,faviconUrlEtag:e.faviconUrlEtag,emailBrandingEnabled:e.emailBrandingEnabled,testimonialsEnabled:e.testimonialsEnabled,platformTitle:e.platformTitle,loginHeading:e.loginHeading,loginButton:e.loginButton,metaDescription:e.metaDescription,metaImageUrl:e.metaImageUrl,metaTitle:e.metaTitle}:DEFAULT_BRANDING_CONFIG}))}var index$e=Object.freeze({__proto__:null,getBrandingConfig:getBrandingConfig});const BUDIBASE_AI_CONFIG_ID="budibase_ai";function enrichAIConfig(e){return __awaiter(this,void 0,void 0,(function*(){return(yield isBudibaseAIEnabled())&&(e.config[BUDIBASE_AI_CONFIG_ID]={provider:"OpenAI",active:!0,isDefault:Object.keys(e.config).every((t=>!e.config[t].isDefault)),defaultModel:process.env.BUDIBASE_AI_DEFAULT_MODEL||"gpt-4o-mini",apiKey:process.env.OPENAI_API_KEY,name:"Budibase AI"}),e}))}var index$d=Object.freeze({__proto__:null,enrichAIConfig:enrichAIConfig});const increment=(e,t,a)=>tryIncrement({change:1,name:e,type:t,opts:a}),incrementMany=e=>tryIncrement(e),tryIncrement=e=>__awaiter(void 0,void 0,void 0,(function*(){var t;const a=Array.isArray(e)?e:[e];yield updateUsage(a.map((e=>{var t,a;return{usageChange:e.change,name:e.name,type:e.type,opts:{dryRun:!0,suppressErrorLog:null===(t=e.opts)||void 0===t?void 0:t.suppressErrorLog,id:null===(a=e.opts)||void 0===a?void 0:a.id}}})));const i=[];for(let e of a){let a=null===(t=e.opts)||void 0===t?void 0:t.fn;a&&i.push(yield a())}return yield updateUsage(a.map((e=>{var t,a,i;return{usageChange:e.change,name:e.name,type:e.type,opts:{dryRun:!1,valueFn:null===(t=e.opts)||void 0===t?void 0:t.valueFn,suppressErrorLog:null===(a=e.opts)||void 0===a?void 0:a.suppressErrorLog,id:null===(i=e.opts)||void 0===i?void 0:i.id}}}))),i[0]})),decrement=(e,t,a={})=>updateUsage({usageChange:-1,name:e,type:t,opts:a}),decrementMany=e=>{const t=Array.isArray(e)?e:[e];return updateUsage(t.map((e=>({usageChange:-e.change,name:e.name,type:e.type,opts:e.opts}))))},set=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){return setUsage(a,e,t)})),getExistingTriggers=(e,t,a)=>{if(e==types.QuotaUsageType.STATIC){const e=a.usageQuota.triggers;return e&&e[t]||{}}{const e=getCurrentMonthString(),i=a.monthly[e].triggers;return i&&i[t]||{}}},triggerQuota=(e,t,a,i)=>__awaiter(void 0,void 0,void 0,(function*(){try{yield backendCore.locks.doWithLock({type:types.LockType.TRY_ONCE,name:types.LockName.TRIGGER_QUOTA,resource:e,ttl:1e4},(()=>__awaiter(void 0,void 0,void 0,(function*(){const e={percentage:a,name:t.name};i&&(e.resetDate=i),yield triggerQuota$1(e)}))))}catch(e){backendCore.logging.logAlert("Error triggering quota",e)}})),checkTriggers=(e,t,a,i)=>__awaiter(void 0,void 0,void 0,(function*(){const o=yield getQuotaUsage(),n=e===types.QuotaUsageType.MONTHLY?o.quotaReset:void 0,s=yield getExistingTriggers(e,t,o),r=i.triggers;let u=a/i.value*100;u>100&&(u=100);for(const[e,a]of r.entries()){if(u>=a&&i.value!==UNLIMITED$2){if(!s[a]){s[a]=(new Date).toISOString();(!(u>=(r[e+1]||100))||u===a)&&(yield triggerQuota(t,i,u,n))}}else s[a]=void 0}return s})),updateUsage=e=>__awaiter(void 0,void 0,void 0,(function*(){var t,a,i,o,n;const s=Array.isArray(e)?e:[e];let r,u=null;const d=[];let c={},l={},p={},g={};for(let e of s){try{u=backendCore.context.getAppId()}catch(e){}if(types.APP_QUOTA_NAMES.includes(e.name)&&!u)throw new Error("App context required for quota update");try{r=yield getLicensedQuota(types.QuotaType.USAGE,e.name,e.type),d.push(r);let{total:n,app:s,breakdown:u}=yield getCurrentUsageValues(e.type,e.name,null===(t=e.opts)||void 0===t?void 0:t.id);n+=e.usageChange,null!=s&&(s+=e.usageChange),null!=u&&(u+=e.usageChange);let y={};if((null===(a=e.opts)||void 0===a?void 0:a.dryRun)||(y=yield checkTriggers(e.type,e.name,n,r),g=Object.assign(Object.assign({},g),{[e.name]:y})),r.value!==UNLIMITED$2&&n>r.value&&e.usageChange>0)throw new backendCore.UsageLimitError(`Licensed ${r.name} of ${r.value} has been exceeded`,r.name);if(n=Math.max(0,n),s&&(s=Math.max(0,s)),u&&(u=Math.max(0,u),p=Object.assign(Object.assign({},p),{[e.name]:u})),!(null===(i=e.opts)||void 0===i?void 0:i.dryRun)){let t=null===(o=e.opts)||void 0===o?void 0:o.valueFn;t&&(n=yield t(),s=n),c=Object.assign(Object.assign({},c),{[e.name]:n}),l=Object.assign(Object.assign({},l),{[e.name]:s})}}catch(t){throw(null===(n=e.opts)||void 0===n?void 0:n.suppressErrorLog)||console.error(`Error updating usage quotas for ${e.name}`,t),t}}const y=s.filter((e=>{var t;return!(null===(t=e.opts)||void 0===t?void 0:t.dryRun)})).map((e=>({name:e.name,type:e.type,values:{total:c[e.name],app:l[e.name],breakdown:p[e.name],triggers:g[e.name]},opts:e.opts})));y.length>0&&(yield setAllUsage(y))})),getLicensedQuota=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield getCachedLicense();if(!i){const e=backendCore.tenancy.getTenantId();throw new Error("License not found for tenant id "+e)}if(a&&types.isStaticQuota(e,a,t))return i.quotas[e][a][t];if(a&&types.isMonthlyQuota(e,a,t))return i.quotas[e][a][t];if(types.isConstantQuota(e,t))return i.quotas[e][t];throw new Error("Invalid quota type")})),usageLimitIsExceeded=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){try{return yield updateUsage({usageChange:1,name:e,type:t,opts:{dryRun:!0}}),!1}catch(e){if(e.code===backendCore.ErrorCode.USAGE_LIMIT_EXCEEDED)return!0;throw e}})),getDevAppsCount=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=yield backendCore.db.getAllApps({dev:!0});return e?e.length:0})),addApp=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{appId:t}={}){return increment(types.StaticQuotaName.APPS,types.QuotaUsageType.STATIC,{fn:e,valueFn:getDevAppsCount,id:t})})),removeApp=(...e)=>__awaiter(void 0,[...e],void 0,(function*({appId:e}={}){return decrement(types.StaticQuotaName.APPS,types.QuotaUsageType.STATIC,{valueFn:getDevAppsCount,id:e})})),addRow=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{tableId:t}={}){return increment(types.StaticQuotaName.ROWS,types.QuotaUsageType.STATIC,{fn:e,id:t})})),removeRow=(...e)=>__awaiter(void 0,[...e],void 0,(function*({tableId:e}={}){return decrement(types.StaticQuotaName.ROWS,types.QuotaUsageType.STATIC,{id:e})})),addRows=(e,t,...a)=>__awaiter(void 0,[e,t,...a],void 0,(function*(e,t,{tableId:a}={}){return incrementMany({change:e,name:types.StaticQuotaName.ROWS,type:types.QuotaUsageType.STATIC,opts:{fn:t,id:a}})})),removeRows=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{tableId:t}={}){return decrementMany({change:e,name:types.StaticQuotaName.ROWS,type:types.QuotaUsageType.STATIC,opts:{id:t}})})),addAutomation=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{automationId:t}={}){return increment(types.MonthlyQuotaName.AUTOMATIONS,types.QuotaUsageType.MONTHLY,{fn:e,id:t})})),ONE_DAY=864e5;function checkDayPass(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.user;if(!t||!t._id)return;let a;t.dayPassRecordedAt&&(a=new Date(t.dayPassRecordedAt));const i=new Date(Date.now()-ONE_DAY);if(!a||a.getTime()<i.getTime())try{yield recordActivityInAccountPortal(t),yield recordDayPassOnQuotas(),yield recordDayPassTimeOnUser(t)}catch(t){if("usage_limit_exceeded"!=t.code)throw t;backendCore.utils.isServingApp(e)&&e.redirect("/")}}))}function recordDayPassOnQuotas(){return __awaiter(this,void 0,void 0,(function*(){return increment(types.MonthlyQuotaName.DAY_PASSES,types.QuotaUsageType.MONTHLY,{suppressErrorLog:!0})}))}function recordDayPassTimeOnUser(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();let a=yield t.get(e._id);const i=new Date,o=(new Date).toISOString();e.dayPassRecordedAt=o,a.dayPassRecordedAt=o;try{console.log(`Recording day pass for user=${e._id}`),yield t.put(a)}catch(o){if(409!==o.status)throw o;if(console.warn(`Conflict recording day pass for user=${e._id}`),a=yield t.get(e._id),!a.dayPassRecordedAt||new Date(a.dayPassRecordedAt).getDay()!==i.getDay())throw console.error(`Day pass not recorded for user=${e._id}`),o;console.log(`Day pass already recorded for user=${e._id}`)}yield backendCore.cache.user.invalidateUser(e._id)}))}function recordActivityInAccountPortal(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;backendCore.env.SELF_HOSTED&&(null===(a=null===(t=e.license)||void 0===t?void 0:t.plan)||void 0===a?void 0:a.type)===types.PlanType.FREE||backendCore.env.isDev()&&backendCore.env.DISABLE_ACCOUNT_PORTAL||(yield createActivity(e._id))}))}const addGroup=e=>__awaiter(void 0,void 0,void 0,(function*(){return increment(types.StaticQuotaName.USER_GROUPS,types.QuotaUsageType.STATIC,{fn:e})})),removeGroup=()=>__awaiter(void 0,void 0,void 0,(function*(){return decrement(types.StaticQuotaName.USER_GROUPS,types.QuotaUsageType.STATIC)})),addPlugin=e=>__awaiter(void 0,void 0,void 0,(function*(){return increment(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,{fn:e})})),removePlugin=()=>__awaiter(void 0,void 0,void 0,(function*(){return decrement(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC)})),updatePluginCount=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,e)})),addUsers$1=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=[{change:e,name:types.StaticQuotaName.USERS,type:types.QuotaUsageType.STATIC,opts:{fn:a,valueFn:backendCore.users.getUserCount}}];t>0&&i.push({change:t,name:types.StaticQuotaName.CREATORS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getCreatorCount}});const o=yield incrementMany(i);return yield getLicense$1(),o})),removeUsers$1=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=[{change:e,name:types.StaticQuotaName.USERS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getUserCount}}];t>0&&a.push({change:t,name:types.StaticQuotaName.CREATORS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getCreatorCount}}),yield decrementMany(a),yield getLicense$1()})),setBudibaseAICredits=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.MonthlyQuotaName.BUDIBASE_AI_CREDITS,types.QuotaUsageType.MONTHLY,e)})),updateCustomAIConfigCount=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,e)}));var quotas=Object.freeze({__proto__:null,addApp:addApp,addAutomation:addAutomation,addGroup:addGroup,addPlugin:addPlugin,addRow:addRow,addRows:addRows,addUsers:addUsers$1,bustCache:bustCache,checkDayPass:checkDayPass,decrement:decrement,decrementMany:decrementMany,getCurrentUsageValues:getCurrentUsageValues,getLicensedQuota:getLicensedQuota,getQuotaUsage:getQuotaUsage,increment:increment,incrementMany:incrementMany,removeApp:removeApp,removeGroup:removeGroup,removePlugin:removePlugin,removeRow:removeRow,removeRows:removeRows,removeUsers:removeUsers$1,set:set,setAllUsage:setAllUsage,setAppUsageValue:setAppUsageValue,setBudibaseAICredits:setBudibaseAICredits,setUsage:setUsage,setUsagePerApp:setUsagePerApp,updateCustomAIConfigCount:updateCustomAIConfigCount,updatePluginCount:updatePluginCount,updateUsage:updateUsage,usageLimitIsExceeded:usageLimitIsExceeded,utils:utils});const api=new API(backendCore.env.ACCOUNT_PORTAL_URL),createActivity$1=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield send((t=>api.post(`/api/users/${e}/activity`,t)),{body:t});if(a){if(201!==a.status){const e=`Error creating account user activity: ${yield a.text()}`;throw backendCore.logging.logAlert(e),new Error(e)}return a.json()}})),send=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield authorizationHeaders(),i=Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),a)});return e(i)})),authorizationHeaders=()=>__awaiter(void 0,void 0,void 0,(function*(){if(backendCore.env.SELF_HOSTED){const e=yield get$6();if(e.licenseKey){const t=e.licenseKey;return{[backendCore.constants.Header.LICENSE_KEY]:t}}return{}}{const e=backendCore.tenancy.getTenantId();return{[backendCore.constants.Header.API_KEY]:backendCore.env.ACCOUNT_PORTAL_API_KEY,[backendCore.constants.Header.TENANT_ID]:e}}}));class GroupNameUnavailableError extends backendCore.HTTPError{constructor(e){super(`Group name "${e}" is unavailable`,409)}}function findHighestRole(e,t){return __awaiter(this,void 0,void 0,(function*(){try{let a=[];for(let i of e)if(i.roles){const e=i.roles[backendCore.db.getProdAppID(t)];e&&a.push(e)}const i=yield Promise.all(a.map((e=>__awaiter(this,void 0,void 0,(function*(){return{[e]:yield backendCore.roles.roleToNumber(e)}})))));let o,n=0;const s={};i.forEach((e=>{const[t,a]=Object.entries(e)[0];s[t]={roleId:t,roleNum:a}}));for(let{roleId:e,roleNum:t}of Object.values(s))t>n&&(n=t,o=e);return o}catch(a){throw backendCore.logging.logAlert(`Error finding higest role for ${e.length} on app ${t}`,a),a}}))}function groupList(e,t){return __awaiter(this,void 0,void 0,(function*(){return t=t?t.filter((t=>e.includes(t._id))):yield getBulk$1(e,{enriched:!1})}))}function getGroupBuilderAppIds(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!e.userGroups)return[];const i=yield groupList(e.userGroups,null==t?void 0:t.groups),o=(null==t?void 0:t.appId)?backendCore.db.getProdAppID(null==t?void 0:t.appId):null;let n=[];for(let e of i){const t=null===(a=e.builder)||void 0===a?void 0:a.apps;o&&(null==t?void 0:t.includes(o))?n.push(o):o||(n=n.concat(t||[]))}return[...new Set(n)]}))}function getGroupRoleId(e,t,a){return __awaiter(this,void 0,void 0,(function*(){var i;if(!e.userGroups)return null;let o=yield groupList(e.userGroups,null==a?void 0:a.groups);const n=backendCore.db.getProdAppID(t);return(null===(i=e.roles)||void 0===i?void 0:i[n])?e.roles[n]:(o=o.filter((e=>{if(!(null==e?void 0:e.roles))return!1;return Object.keys(e.roles).includes(n)})),yield findHighestRole(o,t))}))}function enrichUserRolesFromGroups(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;if(!e||!e.userGroups)return e;const i=yield getBulk(e.userGroups,{enriched:!1});let o=[];for(let e of i)(null==e?void 0:e.roles)&&(o=o.concat(Object.keys(e.roles)));o=[...new Set(o)];for(let t of o)yield backendCore.context.doInAppContext(t,(()=>__awaiter(this,void 0,void 0,(function*(){if(e.roles[t])return;const a=yield findHighestRole(i,t);a&&(e.roles[t]=a)}))));const n=yield getGroupBuilderAppIds(e,{groups:i});if(n.length&&!(null===(t=e.builder)||void 0===t?void 0:t.global)){const t=(null===(a=e.builder)||void 0===a?void 0:a.apps)||[];e.builder={apps:t.concat(n)}}return e}))}function fetch$4(){return __awaiter(this,void 0,void 0,(function*(){return yield fetch$5()}))}function get$3(e){return __awaiter(this,void 0,void 0,(function*(){return yield get$5(e)}))}function getBulk(e){return __awaiter(this,arguments,void 0,(function*(e,t={enriched:!0}){return yield getBulk$1(e,t)}))}function guardNameAvailability(e){return __awaiter(this,void 0,void 0,(function*(){if(yield getByName(e))throw new GroupNameUnavailableError(e)}))}function getCreatorsCountInGroup(e){return __awaiter(this,void 0,void 0,(function*(){let t=yield getGroupUsers(e._id);if(!t.length)return 0;const a=backendCore.tenancy.getGlobalDB(),i=yield Promise.all(t.map((e=>a.get(e._id))));return(yield Promise.all(i.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length}))}function save$2(e){return __awaiter(this,void 0,void 0,(function*(){var t;let a=[],i=!e._id,o=0;if(delete e.users,e._id){const i=yield get$5(e._id);if(i.name!==e.name&&(yield guardNameAvailability(e.name)),a.push(backendCore.events.group.updated(e)),JSON.stringify(i.roles)!==JSON.stringify(e.roles)){const n=(null===(t=i.users)||void 0===t?void 0:t.length)||0;let s=0;n>0&&(s=yield getCreatorsCountInGroup(i)),o=Object.values(e.roles).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)?n-s:-n,a.push(backendCore.events.group.permissionsEdited(e))}}else e._id=generateUserGroupID(),yield guardNameAvailability(e.name),a.push(backendCore.events.group.created(e));yield Promise.all(a);const n=()=>save$3(e);if(i)return yield addGroup(n);{const t=yield n();if(o>0)yield addUsers$1(0,o);else if(o<0){const t=yield getCreatorsCountInGroup(e),a=Math.abs(o)-t;a>0&&(yield removeUsers$1(0,a))}return t}}))}function remove$4(e,t){return __awaiter(this,void 0,void 0,(function*(){let a;try{a=yield get$5(e)}catch(e){throw new Error("Group not found")}let i=()=>{};if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const t=backendCore.tenancy.getGlobalDB(),a=yield getGroupUsers(e),o=(yield Promise.all(a.map((e=>t.get(e._id))))).map((t=>Object.assign(Object.assign({},t),{userGroups:t.userGroups.filter((t=>t!==e))}))),n=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,s=a.length-n;s&&(i=()=>removeUsers$1(0,s))}let o=yield destroy$2(e,t);return yield backendCore.events.group.deleted(a),yield removeGroup(),yield i(),o}))}function addUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$5(e),i=yield backendCore.users.bulkGetGlobalUsersById(t);let o=[];for(let t of i)t.userGroups||(t.userGroups=[]),t.userGroups.includes(e)||o.push(t);if(!o.length)return o;const n=o.map((t=>Object.assign(Object.assign({},t),{userGroups:[...(null==t?void 0:t.userGroups)||[],e]})));yield backendCore.users.bulkUpdateGlobalUsers(n);if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const e=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,t=o.length-e;t&&(yield addUsers$1(0,t))}let s=[];for(let e of t)s.push(backendCore.cache.user.invalidateUser(e));return yield Promise.all(s),yield backendCore.events.group.usersAdded(n.length,a),n}))}function removeUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$5(e),i=yield backendCore.users.bulkGetGlobalUsersById(t);let o=[];for(let t of i){if(!t.userGroups||!t.userGroups.includes(e))continue;const a=t.userGroups.indexOf(e);t.userGroups.splice(a,1),o.push(t)}yield backendCore.users.bulkUpdateGlobalUsers(o);if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const e=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,t=o.length-e;t&&(yield removeUsers$1(0,t))}let n=[];for(let e of t)n.push(backendCore.cache.user.invalidateUser(e));return yield Promise.all(n),o.length&&(yield backendCore.events.group.usersDeleted(o.length,a)),o}))}function updateGroupApps$1(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$3(e);if(a.roles||(a.roles={}),t.appsToAdd)for(let e of t.appsToAdd)a.roles[e.appId]=e.roleId;if(t.appsToRemove)for(let e of t.appsToRemove)delete a.roles[e.appId];return yield save$2(a)}))}function cleanupApp(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield fetch$4(),a=[];for(let i of t)i.roles&&i.roles[e]&&(delete i.roles[e],a.push(i));return yield bulkSave(a)}))}function addAppBuilder$3(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");const i=backendCore.db.getProdAppID(t),o=yield get$3(e);null!==(a=o.builder)&&void 0!==a||(o.builder={apps:[]}),o.builder.apps.includes(t)||(o.builder.apps.push(i),yield save$2(o))}))}function removeAppBuilder$3(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");const i=backendCore.db.getProdAppID(t),o=yield get$3(e);(null===(a=o.builder)||void 0===a?void 0:a.apps.includes(t))&&(o.builder.apps=o.builder.apps.filter((e=>e!==i)),yield save$2(o))}))}function adjustGroupCreatorsQuotas(){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isUserGroupsEnabled())){const e=backendCore.tenancy.getGlobalDB(),t=((yield fetch$4())||[]).filter((e=>Object.values((null==e?void 0:e.roles)||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)));for(let a of t){const t=yield getGroupUsers(a._id),i=(yield Promise.all(t.map((t=>e.get(t._id))))).map((e=>Object.assign(Object.assign({},e),{userGroups:e.userGroups.filter((e=>e!==a._id))}))),o=(yield Promise.all(i.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,n=t.length-o;yield save$3(Object.assign(Object.assign({},a),{roles:{}})),n&&(yield removeUsers$1(0,n))}}}))}var groups$2=Object.freeze({__proto__:null,addAppBuilder:addAppBuilder$3,addUsers:addUsers,adjustGroupCreatorsQuotas:adjustGroupCreatorsQuotas,cleanupApp:cleanupApp,enrichUserRolesFromGroups:enrichUserRolesFromGroups,fetch:fetch$4,get:get$3,getBulk:getBulk,getGroupBuilderAppIds:getGroupBuilderAppIds,getGroupRoleId:getGroupRoleId,remove:remove$4,removeAppBuilder:removeAppBuilder$3,removeUsers:removeUsers,save:save$2,updateGroupApps:updateGroupApps$1});backendCore.users.UserDB.init(quotas,groups$2,features);const db=backendCore.users.UserDB,createActivity=e=>__awaiter(void 0,void 0,void 0,(function*(){const t={timestamp:Date.now()};return createActivity$1(e,t)}));function addAppBuilder$2(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");yield backendCore.users.addAppBuilder(e,t)}))}function removeAppBuilder$2(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");yield backendCore.users.removeAppBuilder(e,t)}))}var index$c=Object.freeze({__proto__:null,addAppBuilder:addAppBuilder$2,createActivity:createActivity,db:db,removeAppBuilder:removeAppBuilder$2});function backOff(e,t){return __awaiter(this,void 0,void 0,(function*(){let a,i,o=5,n=!1;for(;o>0;o--)try{i=yield e(),n=!0;break}catch(e){a=e}return n||backendCore.logging.logWarn(`Failed to backoff: ${t}`,a),i}))}const{SEPARATOR:SEPARATOR,UNICODE_MAX:UNICODE_MAX,DocumentType:DocumentType,AutomationViewMode:AutomationViewMode,ViewName:ViewName,getQueryIndex:getQueryIndex}=backendCore.db,EARLIEST_DATE=new Date(0).toISOString(),EXPIRED_LIMIT=100,oldestLogDate$1=()=>__awaiter(void 0,void 0,void 0,(function*(){return getOldestRetentionDate(types.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS)}));function getAutomationLogParams(e,t,{status:a,automationId:i}={},o={}){const n=i?`${i}${SEPARATOR}`:"",s=a?`${a}${SEPARATOR}`:"";let r;return r=a&&i?`${AutomationViewMode.ALL}${SEPARATOR}${s}${n}`:a?`${AutomationViewMode.STATUS}${SEPARATOR}${s}`:i?`${AutomationViewMode.AUTOMATION}${SEPARATOR}${n}`:`${DocumentType.AUTOMATION_LOG}${SEPARATOR}`,Object.assign(Object.assign({},o),{descending:!0,startkey:`${r}${t}${UNICODE_MAX}`,endkey:`${r}${e}`})}function getStatus(e){var t,a,i;let o=types.AutomationStatus.SUCCESS,n=!0;for(let s of e.steps){const e=null===(a=null===(t=s.outputs)||void 0===t?void 0:t.status)||void 0===a?void 0:a.toLowerCase(),r="stopped_error"===e;if(!n||r){if(r){o=types.AutomationStatus.STOPPED_ERROR;break}if(!(null===(i=s.outputs)||void 0===i?void 0:i.success)){o=types.AutomationStatus.ERROR;break}if("stopped"===e){o=types.AutomationStatus.STOPPED;break}}else n=!1}return o}function generateAutomationLogID(e,t,a){return`${DocumentType.AUTOMATION_LOG}${SEPARATOR}${e}${SEPARATOR}${a}${SEPARATOR}${t}`}function getAllLogs(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={docs:!0}){let i=backendCore.context.getProdAppDB();(yield i.exists())||(i=backendCore.context.getDevAppDB());let o={status:a.status},n=(null==a?void 0:a.limit)?a.limit:(null==a?void 0:a.paginate)?GENERIC_PAGE_SIZE+1:void 0;const s=getAutomationLogParams(e,t,o,{include_docs:a.docs,limit:n});return(null==a?void 0:a.page)&&(s.startkey=a.page),pagination(yield i.allDocs(s),{paginate:null==a?void 0:a.paginate,pageSize:GENERIC_PAGE_SIZE})}))}function getLogsByView(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){let i,o=backendCore.context.getProdAppDB();(yield o.exists())||(o=backendCore.context.getDevAppDB());try{const n=getAutomationLogParams(e,t,{automationId:null==a?void 0:a.automationId,status:null==a?void 0:a.status},{include_docs:!0,limit:GENERIC_PAGE_SIZE});(null==a?void 0:a.page)&&(n.startkey=a.page),i=yield o.query(getQueryIndex(ViewName.AUTOMATION_LOGS),n)}catch(i){if(null==i||"not_found"!==i.name&&"not_found"!==i.error)throw i;return yield createLogByAutomationView(),getLogsByView(e,t,a)}return pagination(i)}))}function writeLog(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.context.getProdAppDB(),i=e._id,o=e.name,n=getStatus(t),s=(new Date).toISOString(),r=generateAutomationLogID(s,n,i),u=Object.assign(Object.assign({},t),{automationId:i,status:n,automationName:o,createdAt:s,_id:r});return yield a.put(u),r}))}function updateAppMetadataWithErrors(e){return __awaiter(this,arguments,void 0,(function*(e,{clearing:t}={clearing:!1}){const a=backendCore.context.getProdAppDB();yield backOff((()=>__awaiter(this,void 0,void 0,(function*(){const i=yield a.get(backendCore.db.DocumentType.APP_METADATA);for(let a of e){const e=a.split(backendCore.db.SEPARATOR),o=`${e[e.length-3]}${backendCore.db.SEPARATOR}${e[e.length-2]}`;let n={};i.automationErrors&&(n=i.automationErrors),Array.isArray(n[o])||(n[o]=[]);const s=n[o].indexOf(a);t&&-1!==s?n[o].splice(s,1):n[o].push(a),0===n[o].length&&delete n[o],i.automationErrors=n}yield a.put(i),yield backendCore.cache.app.invalidateAppMetadata(i.appId,i)}))),"Failed to update app metadata with automation log error")}))}function getExpiredLogs(){return __awaiter(this,void 0,void 0,(function*(){const e=yield oldestLogDate$1();try{return yield getAllLogs(EARLIEST_DATE,e,{docs:!1,paginate:!1,limit:EXPIRED_LIMIT})}catch(e){return{data:[],hasNextPage:!1}}}))}function clearOldHistory(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getProdAppDB();try{const t=yield getExpiredLogs();if(!t.data||0===t.data.length)return;const a=t.data.map((e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}))),i=t.data.filter((e=>{const t=e.id.split(backendCore.db.SEPARATOR);return t[t.length-1]===types.AutomationStatus.ERROR})).map((e=>e.id));yield e.bulkDocs(a),i.length&&(yield updateAppMetadataWithErrors(i,{clearing:!0}))}catch(t){backendCore.logging.logAlert(`Failed to cleanup automation log history - Database "${e.name}"`,t)}}))}const oldestLogDate=oldestLogDate$1;function getLogs(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){let o,n=(new Date).toISOString();const s=yield oldestLogDate();return(!e||e<s)&&(e=s),o=a||t?yield getLogsByView(e,n,{automationId:a,status:t,page:i}):yield getAllLogs(e,n,{status:t,page:i,docs:!0,paginate:!0}),o}))}function logSearch(e){return __awaiter(this,void 0,void 0,(function*(){return yield clearOldHistory(),yield getLogs(e.startDate,e.status,e.automationId,e.page)}))}function storeLog(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!backendCore.db.isProdAppID(backendCore.context.getAppId()))return;const a=getStatus(t),i=yield writeLog(e,t);a===types.AutomationStatus.ERROR&&(yield updateAppMetadataWithErrors([i])),yield clearOldHistory()}))}var index$b=Object.freeze({__proto__:null,logSearch:logSearch,oldestLogDate:oldestLogDate,storeLog:storeLog}),index$a=Object.freeze({__proto__:null,logs:index$b});function loadJSFile(e,t){return fs.readFileSync(path.join(e,t),"utf8")}function storePlugin(metadata,directory,source){return __awaiter(this,void 0,void 0,(function*(){const db=backendCore.tenancy.getGlobalDB(),version=metadata.package.version,name=metadata.package.name,description=metadata.package.description,hash=metadata.schema.hash,bucketPath=backendCore.objectStore.getPluginS3Dir(name),files=yield backendCore.objectStore.uploadDirectory(backendCore.objectStore.ObjectStoreBuckets.PLUGINS,directory,bucketPath),jsFile=files.find((e=>e.name.endsWith(".js"))),iconFile=files.find((e=>e.name.endsWith(".svg")));if(!jsFile)throw new Error("Plugin missing .js file.");if(metadata.schema.type===types.PluginType.DATASOURCE){const js=loadJSFile(directory,jsFile.name);try{eval(js)}catch(e){const t=(null==e?void 0:e.message)?e.message:JSON.stringify(e);throw new Error(`JS invalid: ${t}`)}}const iconFileName=iconFile?iconFile.name:null,pluginId=backendCore.db.generatePluginID(name);let rev;try{const e=yield db.get(pluginId);rev=e._rev}catch(e){rev=void 0}let doc=Object.assign(Object.assign({_id:pluginId,_rev:rev},metadata),{name:name,version:version,hash:hash,description:description});iconFileName&&(doc.iconFileName=iconFileName),source&&(doc=Object.assign(Object.assign({},doc),{source:source}));const write=()=>__awaiter(this,void 0,void 0,(function*(){const e=yield db.put(doc);return yield backendCore.events.plugin.imported(doc),Object.assign(Object.assign({},doc),{_rev:e.rev})}));return rev?yield write():yield addPlugin(write)}))}function deletePlugin(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();try{const a=yield t.get(e),i=backendCore.objectStore.getPluginS3Dir(a.name);yield backendCore.objectStore.deleteFolder(backendCore.objectStore.ObjectStoreBuckets.PLUGINS,i),yield t.remove(e,a._rev),yield backendCore.events.plugin.deleted(a),yield removePlugin()}catch(e){const t=(null==e?void 0:e.message)?null==e?void 0:e.message:e;throw new Error(`Failed to delete plugin: ${t}`)}}))}function checkPluginQuotas(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB();try{const t=(yield e.allDocs(backendCore.db.getPluginParams())).rows.length;console.log(`Syncing plugin count: ${t}`),yield updatePluginCount(t)}catch(e){backendCore.logging.logAlert("Unable to retrieve plugins for quota check",e)}}))}var index$9=Object.freeze({__proto__:null,checkPluginQuotas:checkPluginQuotas,deletePlugin:deletePlugin,storePlugin:storePlugin});function isEncryptionKeyAvailable(){return!!backendCore.env.ENCRYPTION_KEY}function fetch$3(){return __awaiter(this,void 0,void 0,(function*(){const e=yield get$4();return Object.keys(e.variables)}))}function fetchValues(e){return __awaiter(this,void 0,void 0,(function*(){const t=(yield get$4()).variables,a={};for(let[i,o]of Object.entries(t))switch(e){case types.AppEnvironment.DEVELOPMENT:a[i]=o.development;break;case types.AppEnvironment.PRODUCTION:default:a[i]=o.production}return a}))}function changeValues(e){return __awaiter(this,void 0,void 0,(function*(){if(!(yield getCachedLicense()).features.includes(types.Feature.ENVIRONMENT_VARIABLES))throw new Error("User does not have access to environment variables feature.");const t=yield get$4();t.variables=e(t.variables),yield update$5(t)}))}function update$4(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!isValid(e))throw new Error("Variable name has characters that are not allowed");yield changeValues((a=>(a[e]=t,a)))}))}function remove$3(e){return __awaiter(this,void 0,void 0,(function*(){yield changeValues((t=>(delete t[e],t)))}))}function isValid(e){return/^[a-zA-Z0-9-_]+$/.test(e)}var index$8=Object.freeze({__proto__:null,fetch:fetch$3,fetchValues:fetchValues,isEncryptionKeyAvailable:isEncryptionKeyAvailable,isValid:isValid,remove:remove$3,update:update$4});const MemoryStream=require("memorystream"),builder=new backendCore.sql.Sql(types.SqlClient.SQL_LITE);function getAuditLogSqlQuery(e,t,a){const i={endpoint:{datasourceId:backendCore.SQS_DATASOURCE_INTERNAL,entityId:types.AUDIT_LOG_TYPE,operation:types.Operation.READ},paginate:{limit:a,page:t},filters:e,meta:{table:searchTable()},resource:{fields:[]},sort:{timestamp:{direction:types.SortOrder.DESCENDING,type:types.SortType.STRING}}},o=builder._query(i);if(Array.isArray(o))throw new Error("Cannot execute multiple queries for audit log search");return{sql:o.sql,bindings:o.bindings}}function generateAuditLogID(e){return`${backendCore.DocumentType.AUDIT_LOG}${backendCore.SEPARATOR}${e}${backendCore.SEPARATOR}${backendCore.utils.newid()}`}function save$1(e){return __awaiter(this,void 0,void 0,(function*(){e._id||(e._id=generateAuditLogID(e.timestamp)),e.type||(e.type=types.AUDIT_LOG_TYPE);try{const t=backendCore.context.getAuditLogsDB(),a=yield t.put(e);return Object.assign(Object.assign({},e),{_rev:a.rev})}catch(e){backendCore.logging.logAlert("Failed to write audit log",e)}}))}function search$1(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.context.getAuditLogDBName();return yield backendCore.db.paginatedSearch(a,types.SearchIndex.AUDIT,e,{disableEscaping:!0,indexer:createAuditLogDesignDocLucene,limit:GENERIC_PAGE_SIZE,bookmark:t,sort:"timestamp",sortOrder:types.SortOrder.DESCENDING,sortType:types.SortType.STRING})}))}function searchSQL(e,t,a){return __awaiter(this,void 0,void 0,(function*(){t||(t=1);const i=backendCore.context.getAuditLogsDB();try{const a=GENERIC_PAGE_SIZE+1,o=getAuditLogSqlQuery(e,t,a),n=searchTable(),s=builder.convertJsonStringColumns(n,yield i.sql(o.sql,o.bindings));let r;s.length>a&&(r=s.pop());const u={rows:s,hasNextPage:!!r};return u.hasNextPage&&(u.bookmark=t+1),u}catch(i){if(404!==i.status||(null==a?void 0:a.isRetry))throw i;return yield migrate(),yield createAuditLogDesignDocSQL(),yield searchSQL(e,t,{isRetry:!0})}}))}function migrate(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getAuditLogsDB(),t=(yield e.allDocs(backendCore.db.getDocParams(backendCore.DocumentType.AUDIT_LOG,null,{include_docs:!0}))).rows.map((e=>e.doc)).filter((e=>e&&!e.type)).map((e=>Object.assign(Object.assign({},e),{type:types.AUDIT_LOG_TYPE})));yield e.bulkDocs(t)}))}function dump(e){const t=backendCore.context.getAuditLogsDB(),a=new MemoryStream,i=t.dump(a,{filter:t=>{var a;const i=t;if(!(null===(a=i._id)||void 0===a?void 0:a.startsWith(backendCore.DocumentType.AUDIT_LOG)))return!1;let o=!0;const n=(e,t)=>{e&&0!==e.length&&(o=!!(o&&t&&e.includes(t)))};if(n(e.userIds,i.userId),n(e.appIds,i.appId),n(e.events,i.event),(e.startDate||e.endDate)&&(o=o&&i.timestamp>=e.startDate&&i.timestamp<=e.endDate),e.fullSearch){const a=JSON.stringify(t);o=o&&a.includes(e.fullSearch)}return o}}),o=new MemoryStream;return a.on("data",(e=>{const t=JSON.parse(Buffer.from(e).toString());if(Array.isArray(t.docs)){let e="";for(let a of t.docs)e+=JSON.stringify(a)+"\n";o.write(e)}})),a.on("end",(()=>{o.end()})),{promise:i,stream:o}}const MIN_DATE=backendCore.constants.MIN_VALID_DATE.toISOString(),MAX_DATE=backendCore.constants.MAX_VALID_DATE.toISOString();var ResourceType;function escapeCharacter(e,t){for(let a of t)e=e.replace(new RegExp(a,"g"),`\\${a}`);return e}function fillDates(e){return(e.startDate||e.endDate)&&(e.startDate=e.startDate||MIN_DATE,e.endDate=e.endDate||MAX_DATE),e}function getSearchFilters(e){return __awaiter(this,void 0,void 0,(function*(){Array.isArray(e.appIds)&&(e.appIds=e.appIds.map((e=>backendCore.db.getProdAppID(e)))),!(yield backendCore.features.flags.isEnabled("SQS"))&&Array.isArray(e.events)&&(e.events=e.events.map((e=>escapeCharacter(e,[":"]))));const t={};function a(e,a){(null==a?void 0:a.length)&&(t.oneOf=Object.assign(Object.assign({},t.oneOf),{[e]:a}))}if(a("userId",e.userIds),a("appId",e.appIds),a("event",e.events),e.fullSearch)if(yield backendCore.features.flags.isEnabled("SQS"))t.fuzzyOr=!0,t.fuzzy={name:e.fullSearch,fallback:e.fullSearch};else{const a=escapeCharacter(e.fullSearch,[":"," "]);t.equal={all:`("${a}" OR ${a}*)`}}return(e.startDate||e.endDate)&&(e=fillDates(e),t.range={timestamp:{high:e.endDate,low:e.startDate}}),0===Object.keys(t).length&&(t.notEmpty={event:!0}),t}))}function deleted(e,t,a){const i={_id:e,status:types.AuditLogResourceStatus.DELETED};switch(t){case ResourceType.APP:i.name=null==a?void 0:a.appName;break;case ResourceType.USER:i.email=null==a?void 0:a.email}return i}function removeTemplateStrings(e){const t=stringTemplates.findHBSBlocks(e);for(let a of t){const t=` "${a}"`;e=e.replace(e.includes(t)?t:` ${a}`,""),e=stringTemplates.processStringSync(e,{})}return e}function getEventFriendlyName(e,t){const a=types.AuditedEventFriendlyName[e];if(!a)throw new Error("No friendly name found.");let i=stringTemplates.processStringSync(a,t);return i.includes('""')&&(i=removeTemplateStrings(a)),i}function write(e,t,a){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAuditLogsEnabled())||!backendCore.utils.isAudited(e))return;const i=getEventFriendlyName(e,t);let o=new Date;(null==a?void 0:a.timestamp)&&(o=new Date(a.timestamp));const n={timestamp:o.toISOString(),event:e,name:i,userId:(null==a?void 0:a.userId)||types.AuditLogSystemUser,metadata:Object.assign(Object.assign({},t),null==a?void 0:a.hostInfo)},s={};try{if(null==a?void 0:a.appId){n.appId=backendCore.db.getProdAppID(a.appId);const e=yield backendCore.cache.app.getAppMetadata(a.appId);"name"in e&&(s.appName=e.name)}if(null==a?void 0:a.userId){const e=yield backendCore.users.getById(null==a?void 0:a.userId);s.email=e.email}}catch(e){backendCore.logging.logAlert("Failed to retrieve fallback information for audit log",e)}return n.fallback=s,yield save$1(n)}))}function enrich(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.map((e=>e.userId)),a=e.filter((e=>e.appId)).map((e=>backendCore.db.getDevAppID(e.appId))),i=yield backendCore.users.bulkGetGlobalUsersById([...new Set(t)],{cleanup:!0}),o=yield backendCore.db.getAppsByIDs([...new Set(a)]);let n=[];for(let t of e){const e=i.find((e=>(null==e?void 0:e._id)===t.userId)),a=o.find((e=>backendCore.db.isSameAppID(null==e?void 0:e.appId,t.appId))),s={event:t.event,timestamp:t.timestamp,name:t.name,metadata:t.metadata,user:e||deleted(t.userId,ResourceType.USER,t.fallback)};t.appId&&(s.app=a||deleted(t.appId,ResourceType.APP,t.fallback)),n.push(s)}return n}))}function fetch$2(e){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAuditLogsEnabled()))throw new Error("Audit logs not available - license required.");const t=yield getSearchFilters(e);if("string"==typeof e.bookmark)throw new Error("String based bookmark not supported.");let a;return a=(yield backendCore.features.flags.isEnabled("SQS"))?yield searchSQL(t,e.bookmark):yield search$1(t,e.bookmark),{hasNextPage:a.hasNextPage,bookmark:a.bookmark,data:yield enrich(a.rows)}}))}function download$1(e){return dump(e=fillDates(e))}function definitions$1(){const e=Object.entries(types.AuditedEventFriendlyName).filter((e=>null!=e[1])),t={};for(let a of e)t[a[0]]=removeTemplateStrings(a[1]);return t}!function(e){e.USER="user",e.APP="app"}(ResourceType||(ResourceType={}));var index$7=Object.freeze({__proto__:null,definitions:definitions$1,download:download$1,fetch:fetch$2,write:write});function removeRoles(e,t){const a=e.request.body;return a.builder&&(a.builder=(null==t?void 0:t.builder)||void 0),a.admin&&(a.admin=(null==t?void 0:t.admin)||void 0),a.roles&&(a.roles=(null==t?void 0:t.roles)||{}),e.request.body=a,e}function roleCheck(e,t){return __awaiter(this,void 0,void 0,(function*(){return(yield isExpandedPublicApiEnabled())||removeRoles(e,t),e}))}var users$2=Object.freeze({__proto__:null,roleCheck:roleCheck});function assign(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isExpandedPublicApiEnabled()))throw new Error("Unable to assign roles - license required.");const i=yield db.bulkGet(e);for(let e of i){if(t.role&&t.role.roleId){const a=backendCore.db.getProdAppID(t.role.appId);e.roles[a]=t.role.roleId}if(t.appBuilder){const i=backendCore.db.getProdAppID(t.appBuilder.appId),o=(null===(a=e.builder)||void 0===a?void 0:a.apps)||[];e.builder={apps:o.concat([i])}}t.builder&&(e.builder={global:!0}),t.admin&&(e.admin={global:!0}),e.roles}yield db.bulkUpdate(i)}))}function unAssign(e,t){return __awaiter(this,void 0,void 0,(function*(){var a,i;if(!(yield isExpandedPublicApiEnabled()))throw new Error("Unable to un-assign roles - license required.");const o=yield db.bulkGet(e);for(let e of o){if(t.role){const i=backendCore.db.getProdAppID(null===(a=t.role)||void 0===a?void 0:a.appId);e.roles[i]===t.role.roleId&&delete e.roles[i]}if(t.appBuilder&&(null===(i=e.builder)||void 0===i?void 0:i.apps)){const a=backendCore.db.getProdAppID(t.appBuilder.appId);e.builder.apps=e.builder.apps.filter((e=>e!==a))}t.builder&&e.builder&&delete e.builder,t.admin&&e.admin&&delete e.admin}}))}var roles=Object.freeze({__proto__:null,assign:assign,unAssign:unAssign});function buildImportFn(e){return(t,a)=>__awaiter(this,void 0,void 0,(function*(){var i;(yield isExpandedPublicApiEnabled())||t.throw(403,"Endpoint unavailable, license required."),(null===(i=t.request.files)||void 0===i?void 0:i.appExport)||t.throw(400,"Must provide app export file for import."),yield backendCore.context.doInAppContext(t.params.appId,(()=>__awaiter(this,void 0,void 0,(function*(){yield e(t),t.body=void 0,t.status=204,yield a()}))))}))}function buildExportFn(e){return(t,a)=>__awaiter(this,void 0,void 0,(function*(){(yield isExpandedPublicApiEnabled())||t.throw(403,"Endpoint unavailable, license required.");const{encryptPassword:i,excludeRows:o}=t.request.body;yield backendCore.context.doInAppContext(t.params.appId,(()=>__awaiter(this,void 0,void 0,(function*(){t.request.body={encryptPassword:i,excludeRows:o},t.query.appId=t.params.appId,yield e(t),yield a()}))))}))}var applications=Object.freeze({__proto__:null,buildExportFn:buildExportFn,buildImportFn:buildImportFn}),index$6=Object.freeze({__proto__:null,applications:applications,roles:roles,users:users$2});let backupQueue;function init$3(){backupQueue=backendCore.queue.createQueue(backendCore.queue.JobQueue.APP_BACKUP,{maxStalledCount:3,jobOptions:{attempts:3,removeOnFail:!0,removeOnComplete:!0}})}function getBackupQueue(){return backupQueue}function storeAppBackupMetadata(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){return storeAppBackupMetadata$1(e,t)}))}function getTimestamps(e){const t=(new Date).toISOString();switch(e){case types.AppBackupStatus.COMPLETE:case types.AppBackupStatus.FAILED:return{timestamp:t,finishedAt:t};case types.AppBackupStatus.STARTED:return{timestamp:t,startedAt:t};case types.AppBackupStatus.PENDING:return{timestamp:t,createdAt:t}}}function updateBackupStatus(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const o=yield getAppBackup(e);return yield storeAppBackupMetadata$1(Object.assign(Object.assign(Object.assign({},o),getTimestamps(t)),{contents:a,status:t,type:types.AppBackupType.BACKUP}),{filename:i,docId:e})}))}function updateRestoreStatus(e,t,a){return __awaiter(this,void 0,void 0,(function*(){const i=yield getAppBackup(e);return yield storeAppBackupMetadata$1(Object.assign(Object.assign(Object.assign({},i),getTimestamps(a)),{status:a,type:types.AppBackupType.RESTORE,trigger:types.AppBackupTrigger.MANUAL}),{docId:e,docRev:t})}))}function getAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){return getAppBackupMetadata(e)}))}function updateAppBackup(e,t){return __awaiter(this,void 0,void 0,(function*(){return updateAppBackupMetadata(e,t)}))}function deleteAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getAppBackupMetadata(e);return t.filename&&(yield backendCore.objectStore.deleteFile(backendCore.objectStore.ObjectStoreBuckets.BACKUPS,t.filename)),deleteAppBackupMetadata(e)}))}function fetchAppBackups(e,t){return __awaiter(this,void 0,void 0,(function*(){return fetchAppBackups$1(e,t)}))}function getBackupDownloadStream(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getAppBackupMetadata(e);if(!t.filename)throw new Error("Backup incomplete - cannot download.");return{metadata:t,stream:yield backendCore.objectStore.getReadStream(backendCore.objectStore.ObjectStoreBuckets.BACKUPS,t.filename)}}))}function downloadAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){const{stream:t}=yield getBackupDownloadStream(e),a=path.join(backendCore.objectStore.budibaseTempDir(),backendCore.utils.newid()),i=fs.createWriteStream(a);return new Promise(((e,o)=>{t.on("error",o),i.on("error",o),t.pipe(i).on("close",(()=>e(a)))}))}))}function triggerAppBackup(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){let i;try{i=yield storeAppBackupMetadata(Object.assign({appId:e,trigger:t,timestamp:(new Date).toISOString(),status:types.AppBackupStatus.PENDING,type:types.AppBackupType.BACKUP},a))}catch(e){if(409===e.status)return;throw e}return yield getBackupQueue().add({docId:i.id,docRev:i.rev,appId:e,export:Object.assign({trigger:t},a)}),yield backendCore.events.backup.appBackupTriggered(e,i.id,types.AppBackupType.BACKUP,t,null==a?void 0:a.name),i.id}))}function triggerAppRestore(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const o=yield getAppBackup(t);let n;try{n=yield storeAppBackupMetadata({appId:e,timestamp:(new Date).toISOString(),status:types.AppBackupStatus.PENDING,type:types.AppBackupType.RESTORE,createdBy:i})}catch(e){if(409===(null==e?void 0:e.status))return;throw e}return yield getBackupQueue().add({appId:e,docId:n.id,docRev:n.rev,import:{nameForBackup:a,backupId:t,createdBy:i}}),{restoreId:n.id,metadata:o}}))}const pkg={isEnabled:isBackupsEnabled,triggerAppRestore:checkBackups(triggerAppRestore),triggerAppBackup:checkBackups(triggerAppBackup),getBackupDownloadStream:checkBackups(getBackupDownloadStream),downloadAppBackup:checkBackups(downloadAppBackup),fetchAppBackups:checkBackups(fetchAppBackups),storeAppBackupMetadata:checkBackups(storeAppBackupMetadata),updateBackupStatus:checkBackups(updateBackupStatus),updateRestoreStatus:checkBackups(updateRestoreStatus),getAppBackup:checkBackups(getAppBackup),updateAppBackup:checkBackups(updateAppBackup),deleteAppBackup:checkBackups(deleteAppBackup)};function init$2(e){return __awaiter(this,void 0,void 0,(function*(){yield getBackupQueue().process((t=>__awaiter(this,void 0,void 0,(function*(){const a=t.data;try{if(a.export)return exportProcessor(t,e);if(a.import)return importProcessor(t,e)}catch(e){backendCore.logging.logAlert(`Failed to perform backup for app ID: ${a.appId}`,e)}}))))}))}function removeExistingApp(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.db.getDB(e,{skip_setup:!0});yield t.destroy()}))}function runBackup(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.db.getDevAppID(a),o=backendCore.db.getProdAppID(a),n=(new Date).toISOString(),s=(t,a)=>__awaiter(this,void 0,void 0,(function*(){(null==i?void 0:i.doc)?yield pkg.updateBackupStatus(i.doc.id,t,null==a?void 0:a.contents,null==a?void 0:a.filename):yield pkg.storeAppBackupMetadata({appId:o,timestamp:n,trigger:e,status:t,name:null==i?void 0:i.name,type:types.AppBackupType.BACKUP,contents:null==a?void 0:a.contents,createdBy:null==i?void 0:i.createdBy},{filename:null==a?void 0:a.filename})}));try{const a=yield i.processing.exportAppFn(t,{tar:!0}),r=yield i.processing.statsFn(t);let u=`${o}/backup-${n}.tar.gz`;const d=backendCore.objectStore.ObjectStoreBuckets.BACKUPS,c=fs.createReadStream(a);yield backendCore.objectStore.streamUpload({bucket:d,filename:u,stream:c,extra:{type:"application/gzip",metadata:{name:null==i?void 0:i.name,trigger:e,timestamp:n,appId:o}}}),yield s(types.AppBackupStatus.COMPLETE,{filename:u,contents:r}),fs.existsSync(a)&&fs.rmSync(a)}catch(e){backendCore.logging.logAlert("App backup error",e),yield s(types.AppBackupStatus.FAILED)}}))}function importProcessor(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=e.data,i=a.appId,o=a.import.backupId,n=a.import.nameForBackup,s=a.import.createdBy,r=backendCore.tenancy.getTenantIDFromAppID(i);return backendCore.tenancy.doInTenant(r,(()=>__awaiter(this,void 0,void 0,(function*(){const e=backendCore.db.getDevAppID(i),{rev:u}=yield pkg.updateRestoreStatus(a.docId,a.docRev,types.AppBackupStatus.STARTED);yield runBackup(types.AppBackupTrigger.RESTORING,r,i,{processing:t,createdBy:s,name:n});const d=yield pkg.downloadAppBackup(o);yield removeExistingApp(e);let c=types.AppBackupStatus.COMPLETE;try{yield t.importAppFn(e,backendCore.db.getDB(e),{file:{type:"application/gzip",path:d},key:d})}catch(e){backendCore.logging.logAlert("App restore error",e),c=types.AppBackupStatus.FAILED}yield pkg.updateRestoreStatus(a.docId,u,c),fs.existsSync(d)&&fs.rmSync(d,{force:!0})}))))}))}function exportProcessor(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=e.data,i=a.appId,o=a.export.trigger,n=a.export.name,s=backendCore.tenancy.getTenantIDFromAppID(i);yield backendCore.tenancy.doInTenant(s,(()=>__awaiter(this,void 0,void 0,(function*(){try{const{rev:e}=yield pkg.updateBackupStatus(a.docId,types.AppBackupStatus.STARTED);return runBackup(o,s,i,{processing:t,doc:{id:a.docId,rev:e},name:n})}catch(e){backendCore.logging.logAlert("App backup error",e)}}))))}))}var processing=Object.freeze({__proto__:null,init:init$2});const init$1=e=>__awaiter(void 0,void 0,void 0,(function*(){init$3(),yield init$2(e.processing)}));var backups=Object.assign(Object.assign({},pkg),{processing:processing,init:init$1,getBackupQueue:getBackupQueue});const init=e=>__awaiter(void 0,void 0,void 0,(function*(){e.backups&&(yield backups.init(e.backups))}));function get$2(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;const i=backendCore.tenancy.getGlobalDB(),o=new backendCore.db.QueryBuilder(i.name,types.SearchIndex.USER);o.setIndexBuilder(backendCore.db.searchIndexes.createUserIndex),o.setLimit(e.pageSize),o.addEqual("scimInfo.isSync",!0);for(const[i,n]of Object.entries(null!==(a=null===(t=e.filters)||void 0===t?void 0:t.equal)&&void 0!==a?a:{}))o.addEqual(i,n);o.setSort("_id"),o.setSkip(e.skip);const n=yield o.run();return{users:n.rows,total:n.totalRows}}))}function find$3(e){return __awaiter(this,void 0,void 0,(function*(){return yield backendCore.users.getById(e)}))}function create$4(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=yield db.getUserByEmail(e.email);if(a){if(null===(t=a.scimInfo)||void 0===t?void 0:t.isSync)throw new backendCore.HTTPError("User is already synched",409);e=Object.assign(Object.assign({},a),{scimInfo:lodashMerge(a.scimInfo,e.scimInfo),password:void 0,firstName:e.firstName,lastName:e.lastName,updatedAt:e.updatedAt})}return yield db.save(e,{requirePassword:!1})}))}function update$3(e,t){return __awaiter(this,void 0,void 0,(function*(){return yield db.save(e,{requirePassword:!1,allowChangingEmail:null==t?void 0:t.allowChangingEmail})}))}function remove$2(e){return __awaiter(this,void 0,void 0,(function*(){return yield db.destroy(e)}))}var users$1=Object.freeze({__proto__:null,create:create$4,find:find$3,get:get$2,remove:remove$2,update:update$3});function create$3(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=yield getByName(e.name);let i;if(a){if(null===(t=a.scimInfo)||void 0===t?void 0:t.isSync)throw new backendCore.HTTPError("Group is already synched",409);i=a._id,a.users&&(yield removeUsers(i,a.users.map((e=>e._id))),delete a.users),a.scimInfo=lodashMerge(a.scimInfo,e.scimInfo),yield save$2(a)}else{i=(yield save$2(e)).id}return yield get$3(i)}))}var groups$1=Object.freeze({__proto__:null,create:create$3});const{DocWritethrough:DocWritethrough}=backendCore.cache.docWritethrough;function getLogDocId(){return`${backendCore.db.DocumentType.SCIM_LOG}${backendCore.db.SEPARATOR}${dayjs().format("YYYYMMDD")}`}const getDB=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.context.getScimDBName();return new DocWritethrough(backendCore.db.getDB(e),getLogDocId())}));function logRequest(e){return __awaiter(this,void 0,void 0,(function*(){const t=Date.now().toString(),a=yield getDB();return yield a.patch({[`${t}_request`]:Object.assign({ts:(new Date).toISOString()},e)}),t}))}function logResponse(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield getDB();yield a.patch({[`${e}_response`]:Object.assign({ts:(new Date).toISOString()},t)})}))}var logger=Object.freeze({__proto__:null,logRequest:logRequest,logResponse:logResponse}),index$5=Object.freeze({__proto__:null,ai:index$d,auditLogs:index$7,automations:index$a,backups:backups,branding:index$e,environmentVariables:index$8,features:features,groups:groups$2,init:init,licensing:index$f,logger:logger,plugins:index$9,publicApi:index$6,quotas:quotas,scimGroups:groups$1,scimUsers:users$1,users:index$c,utils:index$i});const licensing=(e={checkUsersLimit:!0})=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){if((e.licensingCheck?e.licensingCheck:()=>!!t.user)(t)){if(backendCore.env.SELF_HOSTED&&backendCore.env.DEFAULT_LICENSE)return t.user.license=SELF_FREE_LICENSE,a();t.user.license=yield getCachedLicense(t,{populateLicense:e.populateLicense,populateFreeLicense:e.populateFreeLicense}),e.checkUsersLimit&&(backendCore.utils.isServingApp(t)||backendCore.utils.isServingBuilder(t)||backendCore.utils.isServingBuilderPreview(t)||backendCore.utils.isPublicApiRequest(t))&&(yield usageLimitIsExceeded(types.StaticQuotaName.USERS,types.QuotaUsageType.STATIC))}return a()})),requireFeature=e=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkFeature(e),yield a()})),requireFeatures=(...e)=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkFeatures(e),yield a()}));var feature=Object.freeze({__proto__:null,requireFeature:requireFeature,requireFeatures:requireFeatures});const doInScimContext=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){let a;return backendCore.env.DISABLE_SCIM_CALLS||(a=yield logRequest(Object.assign(Object.assign({},e.request.toJSON()),{body:e.request.body}))),yield backendCore.context.doInScimContext((()=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield t();return a&&(yield logResponse(a,Object.assign(Object.assign({},e.response.toJSON()),{body:e.response.body}))),i}))))})),requireSCIM=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkSCIM(),yield t()})),scimUserOnly=e=>scimSyncChecks(backendCore.users.getById,e,!0),scimGroupOnly=e=>scimSyncChecks(get$5,e,!0),internalGroupOnly=e=>scimSyncChecks(get$5,e,!1);function scimSyncChecks(e,t,a){return(i,o)=>__awaiter(this,void 0,void 0,(function*(){var n;const s=i.params[t];"string"!=typeof s&&i.throw(404);return!!(null===(n=(yield e(s)).scimInfo)||void 0===n?void 0:n.isSync)!==a&&i.throw(404),o()}))}var index$4=Object.freeze({__proto__:null,doInScimContext:doInScimContext,feature:feature,internalGroupOnly:internalGroupOnly,licensing:licensing,requireSCIM:requireSCIM,scimGroupOnly:scimGroupOnly,scimUserOnly:scimUserOnly});function summarizeText(e){return`Summarize this text:\n${e}`}function generateCronExpression$1(e){return`Generate a node-cron compatible expression based on the following prompt. Return only the cron expression (without backticks), and if not possible return only 'Error generating cron' with a short explanation:\n${e}`}class OpenAI{constructor({model:e,apiKey:t,measureUsage:a}){this.model=e,this.client=new OpenAIClient({apiKey:t}),this.measureUsage=a}measureTokenUsage(e){let t=0;if(this.measureUsage&&e){const{prompt_tokens:a,completion_tokens:i}=e;t=3*i+a}return t}chatCompletion(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;try{const i=yield this.client.chat.completions.create({model:this.model,messages:[{role:"user",content:e}],max_tokens:parseInt(process.env.BUDIBASE_AI_MAX_PROMPT_TOKENS||"300")}),o=this.measureTokenUsage(i.usage);return{message:null===(a=null===(t=null==i?void 0:i.choices[0])||void 0===t?void 0:t.message)||void 0===a?void 0:a.content,tokensUsed:o}}catch(e){throw e instanceof OpenAIClient.APIError&&console.error(`OpenAI Prompt failed with error of type ${e.type} and status: ${e.status}:${e.code} - ${e.message}`),e}}))}prompt(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(e)}))}summarizeText(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(summarizeText(e))}))}}class Anthropic{constructor({model:e,apiKey:t}){this.model=e,this.client=new AnthropicClient({apiKey:t})}chatCompletion(e){return __awaiter(this,void 0,void 0,(function*(){try{const t=yield this.client.messages.create({model:this.model,messages:[{role:"user",content:e}],max_tokens:parseInt(process.env.BUDIBASE_AI_MAX_PROMPT_TOKENS||"300")});return{message:(null==t?void 0:t.content[0]).text}}catch(e){throw e instanceof AnthropicClient.APIError&&console.error(`Anthropic Prompt failed with error ${e.name} and status: ${e.status}`),e}}))}prompt(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(e)}))}summarizeText(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(summarizeText(e))}))}}const ProviderMap={OpenAI:OpenAI,Anthropic:Anthropic,TogetherAI:OpenAI,AzureOpenAI:OpenAI,Custom:OpenAI};class LargeLanguageModel{static forCurrentTenant(e){return __awaiter(this,void 0,void 0,(function*(){const t=new LargeLanguageModel(e);return yield t.init(),t}))}constructor(e){this.model=e}determineDefault(e){for(const t in e)if(e[t].isDefault)return e[t]}init(){return __awaiter(this,void 0,void 0,(function*(){var e,t;const a=yield backendCore.configs.getAIConfig();if(!a)throw Error("AI config must be defined to use Budibase AI LLM features");const i=yield enrichAIConfig(a),o=this.determineDefault(i.config);if(!o)throw Error("Error: No config selected as default AI config");const n={model:o.defaultModel||this.model,apiKey:o.apiKey,measureUsage:(null===(t=null===(e=null==a?void 0:a.config)||void 0===e?void 0:e.budibase_ai)||void 0===t?void 0:t.apiKey)===o.apiKey},s=new(0,ProviderMap[o.provider])(n);if(!s)throw Error("LLM Initialisation failed. No model configured.");this.llm=s}))}run(e){return __awaiter(this,void 0,void 0,(function*(){if(!this.llm)throw Error("No model configuration selected. You must instantiate an LLM before prompting.");const t=yield this.llm.prompt(e);return yield setBudibaseAICredits(t.tokensUsed||0),t.message}))}}var index$3=Object.freeze({__proto__:null,LargeLanguageModel:LargeLanguageModel});function generateCronExpression(e){return __awaiter(this,void 0,void 0,(function*(){const{prompt:t}=e.request.body,a=yield LargeLanguageModel.forCurrentTenant("gpt-4o-mini"),i=yield a.run(generateCronExpression$1(t));(null==i?void 0:i.startsWith("Error generating cron:"))?e.throw(400,i):e.body={message:i}}))}const router$6=new Router;function save(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body;if(t.name=t.name.trim(),delete t.roles,t._id){const e=yield get$3(t._id);t.roles=e.roles,t.scimInfo=e.scimInfo}const a=yield save$2(t);e.body={_id:a.id,_rev:a.rev}}))}function updateGroupUsers(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.groupId,a=e.request.body.add,i=e.request.body.remove;let o,n;(a&&!Array.isArray(a)||i&&!Array.isArray(i))&&e.throw(400,"Must supply a list of users to add or to remove"),a&&(o=yield addUsers(t,a)),i&&(n=yield removeUsers(t,i)),e.body={added:o,removed:n}}))}function updateGroupApps(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.groupId,a=e.request.body.add,i=e.request.body.remove;(a&&!Array.isArray(a)||i&&!Array.isArray(i))&&e.throw(400,"Must supply a list of objects, with appId and roleId to add or remove"),e.body=yield updateGroupApps$1(t,{appsToAdd:a,appsToRemove:i})}))}function fetch$1(e){return __awaiter(this,void 0,void 0,(function*(){e.body={data:yield fetch$4()}}))}function destroy$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,rev:a}=e.params;try{yield remove$4(t,a),e.body={message:"Group deleted successfully"}}catch(t){e.throw(t.status,t)}}))}function find$2(e){return __awaiter(this,void 0,void 0,(function*(){try{e.body=yield get$3(e.params.groupId)}catch(t){e.throw(t.status,t)}}))}function searchUsers(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;const{pageSize:i=10,bookmark:o,emailSearch:n}=e.request.query,s=e.params.groupId,r={limit:i+1},u=yield getGroupUsers(s,Object.assign(Object.assign({},r),{emailSearch:n,bookmark:o})),d=n?null===(t=u[i])||void 0===t?void 0:t.email:null===(a=u[i])||void 0===a?void 0:a._id,c=!!d;e.body={users:u.slice(0,i),bookmark:d,hasNextPage:c}}))}function addAppBuilder$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,appId:a}=e.params;yield addAppBuilder$3(t,a),e.body={message:"Group app builder access updated."}}))}function removeAppBuilder$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,appId:a}=e.params;yield removeAppBuilder$3(t,a),e.body={message:"group app builder access removed."}}))}router$6.post("/api/ai/cron",requireFeature(types.Feature.BUDIBASE_AI),backendCore.auth.builderOrAdmin,generateCronExpression);const router$5=new Router;function buildGroupSaveValidation(){return backendCore.auth.joiValidator.body(Joi.object({_id:Joi.string().optional(),_rev:Joi.string().optional(),color:Joi.string().required(),icon:Joi.string().required(),name:Joi.string().trim().required().max(50),role:Joi.string().optional(),users:Joi.array().optional(),apps:Joi.array().optional(),roles:Joi.object().optional(),createdAt:Joi.string().optional(),updatedAt:Joi.string().optional()}).required())}function status(e){return __awaiter(this,void 0,void 0,(function*(){e.body={encryptionKeyAvailable:isEncryptionKeyAvailable()}}))}function fetch(e){return __awaiter(this,void 0,void 0,(function*(){e.body={variables:yield fetch$3()}}))}function create$2(e){return __awaiter(this,void 0,void 0,(function*(){const{name:t,production:a,development:i}=e.request.body;yield update$4(t,{production:a,development:i});const o=[types.AppEnvironment.PRODUCTION];a!==i&&o.push(types.AppEnvironment.DEVELOPMENT),yield backendCore.events.environmentVariable.created(t,o),e.status=200}))}function update$2(e){return __awaiter(this,void 0,void 0,(function*(){const{production:t,development:a}=e.request.body,i=e.params.varName;yield update$4(i,{production:t,development:a}),e.status=200}))}function destroy(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.varName;yield remove$3(t),yield backendCore.events.environmentVariable.deleted(t),e.status=200}))}router$5.post("/api/global/groups",backendCore.auth.adminOnly,requireFeature(types.Feature.USER_GROUPS),buildGroupSaveValidation(),save).get("/api/global/groups",requireFeature(types.Feature.USER_GROUPS),fetch$1).delete("/api/global/groups/:groupId/:rev",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.adminOnly,internalGroupOnly("groupId"),destroy$1).get("/api/global/groups/:groupId",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.adminOnly,find$2).get("/api/global/groups/:groupId/users",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.builderOrAdmin,searchUsers).post("/api/global/groups/:groupId/users",backendCore.auth.adminOnly,requireFeature(types.Feature.USER_GROUPS),internalGroupOnly("groupId"),updateGroupUsers).post("/api/global/groups/:groupId/apps",backendCore.auth.builderOrAdmin,requireFeature(types.Feature.USER_GROUPS),updateGroupApps).post("/api/global/groups/:groupId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.USER_GROUPS,types.Feature.APP_BUILDERS),addAppBuilder$1).delete("/api/global/groups/:groupId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.USER_GROUPS,types.Feature.APP_BUILDERS),removeAppBuilder$1);const router$4=new Router;function buildEnvVarUpdateValidator(){return backendCore.auth.joiValidator.body(Joi.object({name:Joi.string().optional(),production:Joi.string().required(),development:Joi.string().required()}))}function search(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body,a=yield fetch$2(t);yield backendCore.events.auditLog.filtered(t),e.body=a}))}function download(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body,{stream:a}=download$1(t);yield backendCore.events.auditLog.downloaded(t),e.attachment(`audit-logs-${Date.now()}.log`),e.body=a}))}function definitions(e){return __awaiter(this,void 0,void 0,(function*(){e.body={events:definitions$1()}}))}function buildAuditLogSearchValidator(){return backendCore.auth.joiValidator.body(Joi.object({userIds:Joi.array().items(Joi.string()).optional(),appIds:Joi.array().items(Joi.string()).optional(),events:Joi.array().items(Joi.string().valid(...Object.values(types.Event))).optional(),startDate:Joi.string().optional().allow(""),endDate:Joi.string().optional().allow(""),fullSearch:Joi.string().optional().allow(""),bookmark:Joi.number()}))}router$4.get("/api/env/variables/status",backendCore.auth.builderOrAdmin,status).get("/api/env/variables",backendCore.auth.builderOrAdmin,fetch).post("/api/env/variables",backendCore.auth.builderOrAdmin,buildEnvVarUpdateValidator(),create$2).patch("/api/env/variables/:varName",backendCore.auth.builderOrAdmin,buildEnvVarUpdateValidator(),update$2).delete("/api/env/variables/:varName",backendCore.auth.builderOrAdmin,destroy);const router$3=new Router;function checkAppID(e,t){return __awaiter(this,void 0,void 0,(function*(){(yield appExists(t))||e.throw(400,`Provided app ID: ${t} - is invalid.`)}))}function manualBackup(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=e.params.appId;yield checkAppID(e,a);const i=e.request.body,o=null===(t=e.user)||void 0===t?void 0:t._id,n=yield backups.triggerAppBackup(a,types.AppBackupTrigger.MANUAL,{name:i.name,createdBy:o});n||e.throw(500,"Unable to start backup."),e.body={backupId:n,message:"Backup triggered - process starting."}}))}function importBackup(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=e.params.appId;yield checkAppID(e,a);const i=e.params.backupId,o=e.request.body.name,n=yield backups.triggerAppRestore(a,i,o,null===(t=e.user)||void 0===t?void 0:t._id);n||e.throw(500,"Unable to start restore."),yield backendCore.events.backup.appBackupRestored(n.metadata),e.body={restoredId:null==n?void 0:n.restoreId,message:"Restore triggered - process starting."}}))}function deleteBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId;yield backups.deleteAppBackup(a),e.body={message:"Backup deleted successfully."}}))}function fetchBackups(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.request.body;(null==a?void 0:a.trigger)&&(a.trigger=a.trigger.toLowerCase(),Object.values(types.AppBackupTrigger).includes(a.trigger)||e.throw(400,"Provided trigger is not a valid option.")),e.body=yield backups.fetchAppBackups(t,Object.assign({paginate:!0},a))}))}function updateBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId,i=e.request.body;e.body=yield backups.updateAppBackup(a,i.name)}))}function downloadBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId,{metadata:i,stream:o}=yield backups.getBackupDownloadStream(a);e.attachment(`backup-${i.timestamp}.tar.gz`),e.body=o}))}router$3.post("/api/global/auditlogs/search",backendCore.auth.adminOnly,buildAuditLogSearchValidator(),search).get("/api/global/auditlogs/download",backendCore.auth.adminOnly,backendCore.middleware.querystringToBody,buildAuditLogSearchValidator(),download).get("/api/global/auditlogs/definitions",backendCore.auth.adminOnly,definitions);const router$2=new Router;function validateBackupSearch(){return backendCore.auth.joiValidator.body(Joi.object({trigger:Joi.string().valid(...Object.values(types.AppBackupTrigger)),type:Joi.string().valid(...Object.values(types.AppBackupType)),startDate:Joi.date(),endDate:Joi.date(),page:Joi.string()}))}function tryGetQueryAsNumber(e,t){const a=e.request.query[t];if(void 0!==a)return+a}router$2.post("/api/apps/:appId/backups",backendCore.auth.builderOrAdmin,manualBackup).post("/api/apps/:appId/backups/search",backendCore.auth.builderOrAdmin,validateBackupSearch(),fetchBackups).get("/api/apps/:appId/backups/:backupId/file",backendCore.auth.builderOrAdmin,downloadBackup).patch("/api/apps/:appId/backups/:backupId",backendCore.auth.builderOrAdmin,updateBackup).delete("/api/apps/:appId/backups/:backupId",backendCore.auth.builderOrAdmin,deleteBackup).post("/api/apps/:appId/backups/:backupId/import",backendCore.auth.builderOrAdmin,importBackup);const get$1=e=>__awaiter(void 0,void 0,void 0,(function*(){var t;const a=null!==(t=tryGetQueryAsNumber(e,"pageSize"))&&void 0!==t?t:20,i=tryGetQueryAsNumber(e,"startIndex");let o;e.request.query.filter&&(o=userFilters(e.request.query.filter));const n=yield get$2({pageSize:a,skip:i,filters:o});e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:n.total,Resources:n.users.map(toScimUserResponse),startIndex:(i||0)+1,itemsPerPage:a}})),find$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404);const a=yield find$3(t);e.body=toScimUserResponse(a)})),create$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=fromScimUser(e.request.body);try{const a=yield create$4(t);e.body=toScimUserResponse(a)}catch(t){throw t instanceof backendCore.EmailUnavailableError&&e.throw(409,"Email already in use"),t}}));function isDeactivation(e){var t,a;const i=e.Operations.find((e=>("Replace"===e.op||"replace"===e.op)&&"active"===e.path));return!!i&&(!1===i.value||"false"===(null===(a=null===(t=i.value)||void 0===t?void 0:t.toLowerCase)||void 0===a?void 0:a.call(t)))}const update$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=yield find$3(e.params.id);t||e.throw(404);const a=toScimUserResponse(t),i=e.request.body;try{scimPatch.patchBodyValidation(i)}catch(e){}if(isDeactivation(i))return remove$1(e);let o;try{o=scimPatch.scimPatch(a,i.Operations)}catch(e){}o||e.throw(500);const n=fromScimUser(o);yield update$3(n,{allowChangingEmail:!0}),e.body=toScimUserResponse(n)})),remove$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404),yield remove$2(t),e.status=204}));function cleanResponse(e,t){for(const a of t.split(","))delete e[a]}const get=e=>__awaiter(void 0,void 0,void 0,(function*(){let t=(yield fetch$4()).filter((e=>{var t;return null===(t=e.scimInfo)||void 0===t?void 0:t.isSync})).map(toScimGroupResponse);const{filter:a,excludedAttributes:i}=e.request.query;if(a){const e=scim2ParseFilter.filter(scim2ParseFilter.parse(a));t=t.filter(e)}i&&t.forEach((e=>{cleanResponse(e,i)})),e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:t.length,Resources:t,startIndex:1,itemsPerPage:t.length}})),create=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=fromScimGroup(e.request.body),a=yield create$3(t);e.body=toScimGroupResponse(a)})),find=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t),i=toScimGroupResponse(a),{excludedAttributes:o}=e.request.query;o&&cleanResponse(i,o),e.body=i})),remove=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t);yield remove$4(t,a._rev),e.status=204})),update=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t),i=toScimGroupResponse(a),o=e.request.body;try{scimPatch.patchBodyValidation(o)}catch(t){e.throw(400)}const{true:n,false:s}=groupBy(o.Operations,(e=>"members"===e.path));if(null==s?void 0:s.length){const t=scimPatch.scimPatch(i,s);t||e.throw(500);const o=Object.assign(Object.assign({},fromScimGroup(t)),{_rev:a._rev});yield save$2(o)}if(null==n?void 0:n.length){const e=[],a=[];for(const{op:t,value:i}of n)switch(t){case"add":case"Add":for(const t of i)e.push(yield find$3(t.value));break;case"remove":case"Remove":for(const e of i)a.push(yield find$3(e.value));break;case"replace":case"Replace":throw new Error("Replacing members is not allowed");default:sharedCore.utils.unreachable(t)}e.length&&(yield addUsers(t,e.map((e=>e._id)))),a.length&&(yield removeUsers(t,a.map((e=>e._id))))}e.body=toScimGroupResponse(yield get$3(t))})),router$1=new Router({prefix:"/api/global/scim/v2"});function addAppBuilder(e){return __awaiter(this,void 0,void 0,(function*(){const{userId:t,appId:a}=e.params,i=yield db.getUser(t);backendCore.users.isGlobalBuilder(i)?e.body={message:"User already admin - no permissions updated."}:(yield addAppBuilder$2(i,a),e.body={message:`User "${i.email}" app builder access updated.`})}))}function removeAppBuilder(e){return __awaiter(this,void 0,void 0,(function*(){const{userId:t,appId:a}=e.params,i=yield db.getUser(t);backendCore.users.isGlobalBuilder(i)?e.body={message:"User already admin - no permissions removed."}:(yield removeAppBuilder$2(i,a),e.body={message:`User "${i.email}" app builder access removed.`})}))}router$1.use(requireSCIM),router$1.use(doInScimContext),router$1.get("/users",get$1),router$1.get("/users/:id",scimUserOnly("id"),find$1),router$1.post("/users",create$1),router$1.patch("/users/:id",scimUserOnly("id"),update$1),router$1.delete("/users/:id",scimUserOnly("id"),remove$1),router$1.get("/groups",get),router$1.post("/groups",requireFeature(types.Feature.USER_GROUPS),create),router$1.get("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),find),router$1.delete("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),remove),router$1.patch("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),update);const router=new Router;router.post("/api/global/users/:userId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.APP_BUILDERS),addAppBuilder).delete("/api/global/users/:userId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.APP_BUILDERS),removeAppBuilder);var index$2=Object.freeze({__proto__:null,ai:router$6,appBackups:router$2,auditLogs:router$3,environmentVariables:router$4,groups:router$5,scim:router$1,users:router});const{unreachable:unreachable}=sharedCore.utils,toScimUserResponse=e=>{const t=__rest(e.scimInfo||{},["isSync","roles"]),a=Object.assign(Object.assign({},t),{schemas:["urn:ietf:params:scim:schemas:core:2.0:User"],id:e._id,meta:{resourceType:"User",created:new Date(e.createdAt),lastModified:new Date(e.updatedAt)},active:e.status===types.UserStatus.ACTIVE});return(e.firstName||e.lastName)&&(a.name={formatted:[e.firstName,e.lastName].filter((e=>e)).join(" "),familyName:e.lastName,givenName:e.firstName}),a},isScimUserResponse=e=>!!(null==e?void 0:e.id);function tryGetEmail(e){var t,a;return backendCore.utils.validEmail(e.userName)?e.userName:e.emails?(null===(t=e.emails.find((e=>e.primary)))||void 0===t?void 0:t.value)||(null===(a=e.emails[0])||void 0===a?void 0:a.value):void 0}const fromScimUser=e=>{var t,a,i;const o=isScimUserResponse(e)?e:void 0,n=tryGetEmail(e);if(!n)throw new Error("Email is required");let s,r,u;switch(e.active){case"True":case"true":case!0:s=!0;break;case"False":case"false":case!1:s=!1;break;default:unreachable(e.active)}(null===(t=e.name)||void 0===t?void 0:t.givenName)?(r=null===(a=e.name)||void 0===a?void 0:a.givenName,u=null===(i=e.name)||void 0===i?void 0:i.familyName):r=e.displayName;return{tenantId:"",_id:null==o?void 0:o.id,userId:null==o?void 0:o.id,email:n,firstName:r,lastName:u,scimInfo:Object.assign(Object.assign({},e),{isSync:!0}),roles:{},status:s?types.UserStatus.ACTIVE:types.UserStatus.INACTIVE,createdAt:null==o?void 0:o.meta.created.getTime(),updatedAt:null==o?void 0:o.meta.lastModified.toISOString()}},userFilters=e=>{const t={equal:{}};return function e(a){switch(a.op){case"eq":{const e=a.attrPath;let i;if("emails.value"===e)i="email";else i=`scimInfo.${e}`;t.equal[i]=a.compValue;break}case"and":for(const t of a.filters)e(t);break;default:console.warn("Filter not handled",{filter:a})}}(scim2ParseFilter.parse(e)),t};var users=Object.freeze({__proto__:null,fromScimUser:fromScimUser,toScimUserResponse:toScimUserResponse,userFilters:userFilters});const toScimGroupResponse=e=>{var t;return{schemas:["urn:ietf:params:scim:schemas:core:2.0:Group"],id:e._id,externalId:e.scimInfo.externalId,meta:{resourceType:"Group",created:new Date(e.createdAt),lastModified:new Date(e.updatedAt)},displayName:e.name,members:null===(t=e.users)||void 0===t?void 0:t.map((e=>({value:e._id})))}},isScimGroup=e=>!!(null==e?void 0:e.id),fromScimGroup=e=>{const t=isScimGroup(e)?e:void 0;return{_id:null==t?void 0:t.id,name:e.displayName,scimInfo:{externalId:e.externalId,isSync:!0},icon:"UserGroup",color:"var(--spectrum-global-color-blue-600)",createdAt:null==t?void 0:t.meta.created.getTime(),updatedAt:null==t?void 0:t.meta.lastModified.toISOString()}};var groups=Object.freeze({__proto__:null,fromScimGroup:fromScimGroup,toScimGroupResponse:toScimGroupResponse}),index$1=Object.freeze({__proto__:null,group:groups,user:users});exports.ai=index$3,exports.api=index$2,exports.auditLogs=index$7,exports.automations=index$a,exports.backups=backups,exports.branding=index$e,exports.constants=index$j,exports.environmentVariables=index$8,exports.features=features,exports.groups=groups$2,exports.init=init,exports.licensing=index$f,exports.logger=logger,exports.mappers=index$1,exports.middleware=index$4,exports.plugins=index$9,exports.publicApi=index$6,exports.quotas=quotas,exports.scimGroups=groups$1,exports.scimUsers=users$1,exports.sdk=index$5,exports.users=index$c,exports.utils=index$i;
|
|
1
|
+
"use strict";var types=require("@budibase/types"),backendCore=require("@budibase/backend-core"),fetch$6=require("node-fetch"),fs=require("fs"),path=require("path"),LRU=require("lru-cache"),jwt=require("jsonwebtoken"),union=require("lodash/union"),merge=require("lodash/merge"),os=require("os"),tracer=require("dd-trace"),stringTemplates=require("@budibase/string-templates"),lodashMerge=require("lodash/fp/merge"),dayjs=require("dayjs"),OpenAIClient=require("openai"),AnthropicClient=require("@anthropic-ai/sdk"),Router=require("@koa/router"),Joi=require("joi"),scim2ParseFilter=require("scim2-parse-filter"),sharedCore=require("@budibase/shared-core"),scimPatch=require("scim-patch"),groupBy=require("lodash/groupBy"),Method;function __rest(e,t){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(a[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(a[i[o]]=e[i[o]])}return a}function __awaiter(e,t,a,i){return new(a||(a=Promise))((function(o,n){function s(e){try{u(i.next(e))}catch(e){n(e)}}function r(e){try{u(i.throw(e))}catch(e){n(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(s,r)}u((i=i.apply(e,t||[])).next())}))}let client$1;exports.Method=void 0,Method=exports.Method||(exports.Method={}),Method.POST="POST",Method.GET="GET",Method.PATCH="PATCH",Method.DELETE="DELETE",Method.PUT="PUT","function"==typeof SuppressedError&&SuppressedError;const init$4=()=>__awaiter(void 0,void 0,void 0,(function*(){client$1=yield new backendCore.redis.Client(backendCore.redis.utils.Databases.LICENSES).init()})),shutdown=()=>__awaiter(void 0,void 0,void 0,(function*(){client$1&&(yield client$1.finish())}));process.on("exit",(()=>__awaiter(void 0,void 0,void 0,(function*(){yield shutdown()}))));const getClient=()=>__awaiter(void 0,void 0,void 0,(function*(){return client$1||(yield init$4()),client$1}));class API{constructor(e){this.apiCall=e=>(...t)=>__awaiter(this,[...t],void 0,(function*(t="",a={}){a.headers||(a.headers={}),a.headers["Content-Type"]||(a.headers=Object.assign({"Content-Type":"application/json",Accept:"application/json"},a.headers));const i="application/json"===a.headers["Content-Type"];backendCore.logging.correlation.setHeader(a.headers);const o={method:e,body:i?JSON.stringify(a.body):a.body,headers:a.headers,credentials:"include"};return fetch$6(`${this.host}${t}`,o)})),this.post=this.apiCall(exports.Method.POST),this.get=this.apiCall(exports.Method.GET),this.patch=this.apiCall(exports.Method.PATCH),this.del=this.apiCall(exports.Method.DELETE),this.put=this.apiCall(exports.Method.PUT),this.host=e}}const getNextQuotaReset=()=>{const e=new Date;return new Date(e.getFullYear(),e.getMonth()+1,1).toISOString()},setQuotaReset=e=>{e.quotaReset=getNextQuotaReset()},getCurrentMonthString=()=>{const e=new Date;return`${e.getMonth()+1}-${e.getFullYear()}`},generateBaseQuotaUsage=()=>({usageQuota:{[types.StaticQuotaName.APPS]:0,[types.StaticQuotaName.ROWS]:0,[types.StaticQuotaName.PLUGINS]:0,[types.StaticQuotaName.USERS]:0,[types.StaticQuotaName.CREATORS]:0,[types.StaticQuotaName.USER_GROUPS]:0,[types.StaticQuotaName.AI_CUSTOM_CONFIGS]:0,triggers:{}},monthly:{[getCurrentMonthString()]:generateNewMonthlyQuotas()}}),generateNewQuotaUsage=()=>{const e=Object.assign(Object.assign({_id:backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota,quotaReset:getNextQuotaReset()},generateBaseQuotaUsage()),{apps:{}});return setCurrentMonth(e),e},generateNewMonthlyQuotas=()=>({[types.MonthlyQuotaName.QUERIES]:0,[types.MonthlyQuotaName.AUTOMATIONS]:0,[types.MonthlyQuotaName.DAY_PASSES]:0,[types.MonthlyQuotaName.BUDIBASE_AI_CREDITS]:0,triggers:{}}),setCurrentMonth=e=>{const t=getCurrentMonthString();e.monthly||(e.monthly={}),e.monthly[t]||(e.monthly[t]=generateNewMonthlyQuotas()),e.monthly.current=e.monthly[t]},getBreakdownName=(e,t)=>{if(t&&e)switch(e){case types.MonthlyQuotaName.AUTOMATIONS:return types.BreakdownQuotaName.AUTOMATIONS;case types.MonthlyQuotaName.QUERIES:return backendCore.db.isTableId(t)?types.BreakdownQuotaName.ROW_QUERIES:backendCore.db.isDatasourceId(t)?types.BreakdownQuotaName.DATASOURCE_QUERIES:void 0}};var utils=Object.freeze({__proto__:null,generateBaseQuotaUsage:generateBaseQuotaUsage,generateNewMonthlyQuotas:generateNewMonthlyQuotas,generateNewQuotaUsage:generateNewQuotaUsage,getBreakdownName:getBreakdownName,getCurrentMonthString:getCurrentMonthString,setCurrentMonth:setCurrentMonth,setQuotaReset:setQuotaReset});const DB_WRITE_RATE_MS=backendCore.Duration.fromSeconds(60).toMs(),{Writethrough:Writethrough}=backendCore.cache.writethrough;function clearDeprecated(e){return delete e.usageLimits,delete e.usageQuota.automationRuns,delete e.usageQuota.emails,delete e.usageQuota.storage,delete e.usageQuota.views,delete e.usageQuota.publishedApps,delete e.usageQuota.developers,e}const getDB$1=()=>new Writethrough(backendCore.tenancy.getGlobalDB(),DB_WRITE_RATE_MS),bustCache=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB();try{const t=yield e.get(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota);(null==t?void 0:t._rev)&&(yield e.remove(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota,t._rev))}catch(e){if(404!==e.status)throw e}})),getQuotaUsage=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=getDB$1();let t;try{t=yield e.get(backendCore.db.StaticDatabases.GLOBAL.docs.usageQuota),setCurrentMonth(t),setQuotaReset(t)}catch(a){if(404!==a.status)throw a;{t=generateNewQuotaUsage();const a=yield e.put(t);t._rev=a.rev}}return clearDeprecated(t)})),setUsage=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){return setAllUsage({name:t,type:a,values:{total:e}})})),setUsagePerApp=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=getDB$1();let o=yield getQuotaUsage();const n=Object.values(e).reduce(((e,t)=>e+t),0);for(let[i,s]of Object.entries(e))o=coreUsageUpdate(o,t,a,{total:n,app:s},{appId:i});const s=yield i.put(o);return o._rev=s.rev,o})),setBreakdown=(e,t,a,i)=>{const o=getBreakdownName(t,a);if(!o||!(null==i?void 0:i.breakdown))return e;e.breakdown||(e.breakdown={}),e.breakdown[o]||(e.breakdown[o]={parent:t,values:{}});return e.breakdown[o].values[a]=i.breakdown,e},setAppUsageValue=(e,t,a,i={},o)=>{var n;let s;try{s=backendCore.db.getProdAppID((null==i?void 0:i.appId)||backendCore.context.getAppId())}catch(e){}if(!s||!o.app||!types.APP_QUOTA_NAMES.includes(t))return e;(null===(n=e.apps)||void 0===n?void 0:n[s])||(e.apps=Object.assign(Object.assign({},e.apps),{[s]:generateBaseQuotaUsage()}));const r=e.apps[s];switch(a){case types.QuotaUsageType.STATIC:r.usageQuota[t]=o.app;break;case types.QuotaUsageType.MONTHLY:{const e=getCurrentMonthString(),a=t;let n=r.monthly[e];n||(r.monthly[e]=generateNewMonthlyQuotas(),n=r.monthly[e]),n[a]=o.app,types.BREAKDOWN_QUOTA_NAMES.includes(a)&&(null==i?void 0:i.id)&&(n=setBreakdown(n,a,i.id,o));break}}return e},getAppUsageValue=(e,t,a,i)=>{var o,n,s,r,u;if(!types.APP_QUOTA_NAMES.includes(a))return{};let d;try{d=backendCore.db.getProdAppID(backendCore.context.getAppId())}catch(e){}if(!d||!e.apps||!e.apps[d])return{app:0};const c=e.apps[d];switch(t){case types.QuotaUsageType.STATIC:if(null===(o=c.usageQuota)||void 0===o?void 0:o[a])return{app:c.usageQuota[a]};break;case types.QuotaUsageType.MONTHLY:{const e=getCurrentMonthString(),t=a;if(!(null===(s=null===(n=c.monthly)||void 0===n?void 0:n[e])||void 0===s?void 0:s[t]))break;const o=c.monthly[e],d=o[t];let l;const p=getBreakdownName(t,i);return p&&i&&(null===(r=o.breakdown)||void 0===r?void 0:r[p])&&(l=null===(u=o.breakdown[p])||void 0===u?void 0:u.values[i]),{app:d,breakdown:l||0}}}return{app:0}},setStaticTriggers=(e,t,a)=>{t.usageQuota.triggers||(t.usageQuota.triggers={}),a&&(t.usageQuota.triggers[e]=a)},setMonthlyTriggers=(e,t,a,i)=>{a.monthly[t].triggers||(a.monthly[t].triggers={}),i&&(a.monthly[t].triggers[e]=i)},coreUsageUpdate=(e,t,a,i,o={})=>{if(a===types.QuotaUsageType.STATIC)e.usageQuota[t]=i.total,setStaticTriggers(t,e,i.triggers);else{if(a!==types.QuotaUsageType.MONTHLY)throw new Error(`Invalid usage type: ${a}`);{const a=getCurrentMonthString();e.monthly[a][t]=i.total,setMonthlyTriggers(t,a,e,i.triggers)}}return setAppUsageValue(e,t,a,o,i)},setAllUsage=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=Array.isArray(e)?e:[e],a=getDB$1();let i=yield getQuotaUsage();for(let e of t)i=coreUsageUpdate(i,e.name,e.type,e.values,e.opts);const o=yield a.put(i,0);return i._rev=o.rev,i})),getCurrentUsageValues=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield getQuotaUsage();let o=0,n={};switch(e){case types.QuotaUsageType.STATIC:if(i.usageQuota[t]){const s=t;o=i.usageQuota[s],n=getAppUsageValue(i,e,t,a)}break;case types.QuotaUsageType.MONTHLY:{const s=getCurrentMonthString(),r=t;i.monthly[s][r]&&(o=i.monthly[s][r],n=getAppUsageValue(i,e,t,a));break}default:throw new Error(`Invalid usage type: ${e}`)}return!types.APP_QUOTA_NAMES.includes(t)||n.app||n.breakdown||(n.app=n.app||0,n.breakdown=n.breakdown||0),{total:o,app:n.app,breakdown:n.breakdown}})),newLicenseInfo=()=>({_id:backendCore.StaticDatabases.GLOBAL.docs.licenseInfo}),save$4=e=>__awaiter(void 0,void 0,void 0,(function*(){let t=yield get$6();t=Object.assign(Object.assign({},t),e);const a=backendCore.tenancy.getGlobalDB(),i=yield a.put(t);return t._rev=i.rev,t})),get$6=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB();try{return yield e.get(backendCore.StaticDatabases.GLOBAL.docs.licenseInfo)}catch(e){if(404===e.status)return newLicenseInfo();throw e}}));function createAuditLogDesignDocLucene(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getAuditLogsDB();let t;try{t=yield e.get("_design/database")}catch(e){404===e.status&&(t={_id:"_design/database"})}t.indexes={[types.SearchIndex.AUDIT]:{index:function(e){if(e._id&&!e._id.startsWith("al_"))return;const t=["_id","_rev","metadata"];let a=Object.values(e.metadata).join(" ");for(let i of Object.keys(e)){if(t.includes(i))continue;const o=e[i];"string"==typeof o&&(index(i,o.toLowerCase(),{facet:!0}),a+=` ${o}`)}if(e.fallback)for(let t of Object.values(e.fallback))t&&"string"==typeof t&&(a+=` ${t}`);index("all",a)}.toString(),analyzer:{default:"whitespace",fields:{all:"standard"},name:"perfield"}}},yield e.put(t)}))}function createAuditLogDesignDocSQL(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.sql.designDoc.base("type");e.sql.tables={[types.AUDIT_LOG_TYPE]:{fields:{appId:types.SQLiteType.TEXT,event:types.SQLiteType.TEXT,userId:types.SQLiteType.TEXT,timestamp:types.SQLiteType.TEXT,metadata:types.SQLiteType.TEXT,name:types.SQLiteType.TEXT,type:types.SQLiteType.TEXT,fallback:types.SQLiteType.TEXT}}};const t=backendCore.context.getAuditLogsDB();let a;try{a=yield t.get(backendCore.SQLITE_DESIGN_DOC_ID),a=Object.assign(Object.assign({},a),e)}catch(t){if(404!==t.status)throw t;a=e}yield t.put(a)}))}const{ViewName:ViewName$2,SEPARATOR:SEPARATOR$2,DocumentType:DocumentType$2,createView:createView$1}=backendCore.db,USER_PREFIX=DocumentType$2.USER+SEPARATOR$2;var GroupViewMode;function createGroupUserLookupView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=`function(doc) {\n if (doc._id.startsWith("${USER_PREFIX}") && Array.isArray(doc.userGroups)) {\n for (let groupId of doc.userGroups) {\n emit("${GroupViewMode.SEARCH_BY_ID}" + groupId, { email: doc.email, userId: doc._id })\n emit("${GroupViewMode.SEARCH_BY_EMAIL}" + groupId + doc.email, { email: doc.email, userId: doc._id })\n }\n }\n }`;yield createView$1(e,t,ViewName$2.USER_BY_GROUP)}))}!function(e){e.SEARCH_BY_ID="g_",e.SEARCH_BY_EMAIL="e_"}(GroupViewMode||(GroupViewMode={}));const GROUP_PREFIX=`${backendCore.DocumentType.GROUP}${backendCore.SEPARATOR}`;function getUserGroupsParams(e,t={}){e||(e="");const a=(null==e?void 0:e.startsWith(backendCore.DocumentType.GROUP))?"":GROUP_PREFIX;return Object.assign(Object.assign({},t),{startkey:`${a}${e}`,endkey:`${a}${e}${backendCore.UNICODE_MAX}`})}function getGroupUsersParams(e,t={}){e||(e="");const{emailSearch:a,bookmark:i}=t,o=__rest(t,["emailSearch","bookmark"]);if(!a)return Object.assign(Object.assign({},t),{startkey:`${GroupViewMode.SEARCH_BY_ID}${e}`,endkey:`${GroupViewMode.SEARCH_BY_ID}${e}${backendCore.UNICODE_MAX}`,startkey_docid:i});return Object.assign(Object.assign({},o),{startkey:`${GroupViewMode.SEARCH_BY_EMAIL}${e}${i||a}`,endkey:`${GroupViewMode.SEARCH_BY_EMAIL}${e}${a}${backendCore.UNICODE_MAX}`})}function generateUserGroupID(){return`${GROUP_PREFIX}${backendCore.utils.newid()}`}function getGroupUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB();return(yield backendCore.db.queryView(backendCore.db.ViewName.USER_BY_GROUP,getGroupUsersParams(e,t),a,createGroupUserLookupView,{arrayResponse:!0})).map((e=>({_id:e.userId,email:e.email})))||[]}))}function enrichGroup(e){return __awaiter(this,void 0,void 0,(function*(){return e.users=yield getGroupUsers(e._id),e}))}function cleanupUsers(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=null===(t=(yield enrichGroup(e)).users)||void 0===t?void 0:t.map((e=>e._id)),i=yield backendCore.users.bulkGetGlobalUsersById(a),o=[];for(let t of i){if(!t.userGroups)continue;const a=t.userGroups.length;t.userGroups=t.userGroups.filter((t=>t!==e._id)),t.userGroups.length!==a&&o.push(t)}o.length&&(yield backendCore.users.bulkUpdateGlobalUsers(o))}))}function fetch$5(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=(yield e.allDocs(getUserGroupsParams(null,{include_docs:!0}))).rows.map((e=>e.doc)),a=[];for(let e of t)a.push(enrichGroup(e));return yield Promise.all(a)}))}function get$5(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB(),a=yield t.get(e);return yield enrichGroup(a)}))}function getBulk$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={enriched:!0}){const a=backendCore.tenancy.getGlobalDB(),i=yield a.getMultiple(e,{allowMissing:!0});if(null==t?void 0:t.enriched){const e=[];for(let t of i)e.push(enrichGroup(t));return yield Promise.all(e)}return i}))}function save$3(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.put(e)}))}function bulkSave(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.bulkDocs(e)}))}function destroy$2(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB(),i=yield a.get(e);let o=yield a.remove(e,t);return yield cleanupUsers(i),o}))}function getByName(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield backendCore.db.directCouchFind(backendCore.tenancy.getGlobalDBName(),{selector:{name:{$regex:`^(?i)${e}$`}},limit:1}),[a]=t.rows;if(a)return yield enrichGroup(a)}))}function pagination(e,t){var a;const i=e.rows.map((e=>e.doc?e.doc:e));if(!(null==t?void 0:t.paginate))return{data:i,hasNextPage:!1};const o=i.length>(null==t?void 0:t.pageSize);return{data:i.slice(0,null==t?void 0:t.pageSize),hasNextPage:o,nextPage:o?null===(a=i[null==t?void 0:t.pageSize])||void 0===a?void 0:a._id:void 0}}const{ViewName:ViewName$1,AutomationViewMode:AutomationViewMode$1,SEPARATOR:SEPARATOR$1,DocumentType:DocumentType$1,createView:createView}=backendCore.db,LOG_PREFIX=DocumentType$1.AUTOMATION_LOG+SEPARATOR$1,APP_BACKUP_PREFIX$1=DocumentType$1.APP_BACKUP+SEPARATOR$1;function createLogByAutomationView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getProdAppDB(),t=`function(doc) {\n if (doc._id.startsWith("${LOG_PREFIX}")) {\n let autoId = doc.automationId + "${SEPARATOR$1}"\n let status = doc.status + "${SEPARATOR$1}"\n let autoKey = "${AutomationViewMode$1.AUTOMATION}${SEPARATOR$1}" + autoId + doc.createdAt\n let statusKey = "${AutomationViewMode$1.STATUS}${SEPARATOR$1}" + status + doc.createdAt\n let allKey = "${AutomationViewMode$1.ALL}${SEPARATOR$1}" + status + autoId + doc.createdAt\n emit(statusKey)\n emit(autoKey)\n emit(allKey)\n }\n }`;yield createView(e,t,ViewName$1.AUTOMATION_LOGS)}))}function createAppBackupTriggerView(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB(),t=`function(doc) {\n if (doc._id.startsWith("${APP_BACKUP_PREFIX$1}") && doc.type && doc.trigger) {\n let full = doc.appId + "${SEPARATOR$1}"\n full += doc.trigger.toLowerCase() + "${SEPARATOR$1}"\n full += doc.type.toLowerCase() + "${SEPARATOR$1}"\n emit("${APP_BACKUP_PREFIX$1}" + full + doc.timestamp) \n }\n }`;yield createView(e,t,ViewName$1.APP_BACKUP_BY_TRIGGER)}))}const UNLIMITED$2=-1,rows=e=>({[types.StaticQuotaName.ROWS]:{name:"Rows",value:e,triggers:[90,100]}}),apps=e=>({[types.StaticQuotaName.APPS]:{name:"Apps",value:e,triggers:[100]}}),users$3=e=>({[types.StaticQuotaName.USERS]:{name:"Users",value:e,triggers:[80,100]}}),creators=e=>({[types.StaticQuotaName.CREATORS]:{name:"Creators",value:e,triggers:[]}}),userGroups=e=>({[types.StaticQuotaName.USER_GROUPS]:{name:"User Groups",value:e,triggers:[80,100]}}),plugins=e=>({[types.StaticQuotaName.PLUGINS]:{name:"Plugins",value:e,triggers:[90,100]}}),queries=e=>({[types.MonthlyQuotaName.QUERIES]:{name:"Queries",value:e,triggers:[]}}),automations=e=>({[types.MonthlyQuotaName.AUTOMATIONS]:{name:"Automations",value:e,triggers:[80,90,100]}}),dayPasses=e=>({[types.MonthlyQuotaName.DAY_PASSES]:{name:"Day Passes",value:e,triggers:[80,90,100]}}),budibaseAICredits=e=>({[types.MonthlyQuotaName.BUDIBASE_AI_CREDITS]:{name:"Budibase AI Credits",value:e,triggers:[80,90,100]}}),automationLogRetentionDays=e=>({[types.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS]:{name:"Automation Logs",value:e,triggers:[]}}),appBackupRetentionDays=e=>({[types.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS]:{name:"App Backups",value:e,triggers:[]}}),customAIConfigurations=e=>({[types.StaticQuotaName.AI_CUSTOM_CONFIGS]:{name:"Custom AI Configuration",value:e,triggers:[]}});var quotas$3=Object.freeze({__proto__:null,UNLIMITED:UNLIMITED$2,appBackupRetentionDays:appBackupRetentionDays,apps:apps,automationLogRetentionDays:automationLogRetentionDays,automations:automations,budibaseAICredits:budibaseAICredits,creators:creators,customAIConfigurations:customAIConfigurations,dayPasses:dayPasses,plugins:plugins,queries:queries,rows:rows,userGroups:userGroups,users:users$3});const UNLIMITED$1=-1,CLOUD_FREE_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(200)),dayPasses(UNLIMITED$1)),budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},apps(UNLIMITED$1)),rows(2e3)),users$3(5)),creators(5)),userGroups(0)),plugins(10)),customAIConfigurations(0))},constant:Object.assign(Object.assign({},automationLogRetentionDays(1)),appBackupRetentionDays(0))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}},SELF_FREE_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(UNLIMITED$1)),dayPasses(UNLIMITED$1)),budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},rows(UNLIMITED$1)),apps(UNLIMITED$1)),users$3(20)),creators(UNLIMITED$1)),userGroups(0)),plugins(10)),customAIConfigurations(0))},constant:Object.assign(Object.assign({},automationLogRetentionDays(1)),appBackupRetentionDays(0))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}},UNLIMITED_LICENSE={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},queries(UNLIMITED$1)),automations(UNLIMITED$1)),dayPasses(UNLIMITED$1)),budibaseAICredits(UNLIMITED$1)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},apps(UNLIMITED$1)),rows(UNLIMITED$1)),users$3(UNLIMITED$1)),creators(UNLIMITED$1)),userGroups(UNLIMITED$1)),plugins(UNLIMITED$1)),customAIConfigurations(UNLIMITED$1))},constant:Object.assign(Object.assign({},automationLogRetentionDays(UNLIMITED$1)),appBackupRetentionDays(UNLIMITED$1))},plan:{type:types.PlanType.FREE,usesInvoicing:!1,model:types.PlanModel.PER_USER}};var licenses$1=Object.freeze({__proto__:null,CLOUD_FREE_LICENSE:CLOUD_FREE_LICENSE,SELF_FREE_LICENSE:SELF_FREE_LICENSE,UNLIMITED:UNLIMITED$1,UNLIMITED_LICENSE:UNLIMITED_LICENSE});const getLicenseVersion=()=>{if(backendCore.env.isDev()){const e="dev-version.txt",t=path.join(backendCore.objectStore.budibaseTempDir(),e);if(fs.existsSync(t))return fs.readFileSync(t,"utf8");{const e=backendCore.utils.newid();return fs.writeFileSync(t,e),e}}return getProVersion()},getProVersion=()=>{const e=backendCore.env.VERSION;if(!e)throw new Error("No budibase pro version was specified");return e};var version=Object.freeze({__proto__:null,getLicenseVersion:getLicenseVersion,getProVersion:getProVersion});function searchTable(){return{type:"table",sourceType:types.TableSourceType.INTERNAL,name:types.AUDIT_LOG_TYPE,sourceId:backendCore.SQS_DATASOURCE_INTERNAL,primary:["_id"],schema:{metadata:{name:"metadata",type:types.FieldType.JSON},fallback:{name:"fallback",type:types.FieldType.JSON}}}}var auditLogs=Object.freeze({__proto__:null,searchTable:searchTable});const GENERIC_PAGE_SIZE=9;var index$j=Object.freeze({__proto__:null,GENERIC_PAGE_SIZE:GENERIC_PAGE_SIZE,auditLogs:auditLogs,licenses:licenses$1,quotas:quotas$3,versions:version});const MAX_DATE$1=new Date(864e13).toISOString(),ONE_DAY_MILLIS=864e5;function getOldestRetentionDate(e){return __awaiter(this,void 0,void 0,(function*(){var t,a,i;const o=(null===(i=null===(a=null===(t=(yield getCachedLicense()).quotas)||void 0===t?void 0:t[types.QuotaType.CONSTANT])||void 0===a?void 0:a[e])||void 0===i?void 0:i.value)||0;return o===UNLIMITED$1?new Date(MAX_DATE$1).toISOString():new Date((new Date).getTime()-ONE_DAY_MILLIS*o).toISOString()}))}function oldestBackupDate(){return __awaiter(this,void 0,void 0,(function*(){return getOldestRetentionDate(types.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS)}))}const APP_BACKUP_PREFIX=`${backendCore.db.DocumentType.APP_BACKUP}${backendCore.db.SEPARATOR}`;function getAppBackupParams(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){const i=yield oldestBackupDate(),o=backendCore.db.getProdAppID(e);let n=o,s=o;if(t.trigger&&t.type){let e=`${backendCore.db.SEPARATOR}${t.trigger}`;e+=`${backendCore.db.SEPARATOR}${t.type}`,n+=e,s+=e}return(!t.startDate||t.startDate<i)&&(t.startDate=i),t.startDate&&(s+=`${backendCore.db.SEPARATOR}${t.startDate}`),t.endDate&&(n+=`${backendCore.db.SEPARATOR}${t.endDate}`),Object.assign(Object.assign({},a),{descending:!0,startkey:`${APP_BACKUP_PREFIX}${n}${backendCore.db.UNICODE_MAX}`,endkey:`${APP_BACKUP_PREFIX}${s}`})}))}function getAppBackupsByTrigger(e,t){return __awaiter(this,void 0,void 0,(function*(){let a=[];try{const i=backendCore.db.getQueryIndex(backendCore.db.ViewName.APP_BACKUP_BY_TRIGGER);a=yield e.query(i,t)}catch(a){if(null!=a&&"not_found"===a.error)return yield createAppBackupTriggerView(),getAppBackupsByTrigger(e,t);throw a}return a}))}function generateAppBackupID(e,t){return`${APP_BACKUP_PREFIX}${e}${backendCore.db.SEPARATOR}${t}`}function fetchAppBackups$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){const a=backendCore.tenancy.getGlobalDB();let i;const o=t.limit||GENERIC_PAGE_SIZE,n=yield getAppBackupParams(e,t,{include_docs:!0,limit:o+1});t.page&&(n.startkey=t.page),i=t.trigger&&t.type?yield getAppBackupsByTrigger(a,n):yield a.allDocs(n);const s=pagination(i,{paginate:t.paginate,pageSize:o}),r=[...new Set(s.data.filter((e=>e.createdBy)).map((e=>e.createdBy)))],u=yield backendCore.users.bulkGetGlobalUsersById(r,{cleanup:!0});for(let e of u)for(let t of s.data)(null==e?void 0:e._id)===t.createdBy&&(t.createdBy=e);return s}))}function storeAppBackupMetadata$1(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){const a=backendCore.tenancy.getGlobalDB(),i=backendCore.db.getProdAppID(e.appId);let o=generateAppBackupID(i,e.timestamp);const n=Object.assign(Object.assign({},e),{_id:o,appId:i,name:e.name});return n._id=t.docId||n._id,n._rev=t.docRev||n._rev,t.filename&&(n.filename=t.filename),e.createdBy&&(n.createdBy=backendCore.db.getGlobalIDFromUserMetadataID(e.createdBy)),yield a.put(n)}))}function updateAppBackupMetadata(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.tenancy.getGlobalDB(),i=yield a.get(e);return i.name=t,yield a.put(i)}))}function deleteAppBackupMetadata(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB(),a=yield t.get(e);yield t.remove(a._id,a._rev)}))}function getAppBackupMetadata(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();return yield t.get(e)}))}const MAX_CACHE_ITEMS=1e3,cache=new LRU({max:MAX_CACHE_ITEMS});function getEnvVarID(){return backendCore.StaticDatabases.GLOBAL.docs.environmentVariables}function getCacheEnvVarID(e){return`${backendCore.tenancy.getTenantId()}/${getEnvVarID()}/${e||""}`}function get$4(){return __awaiter(this,void 0,void 0,(function*(){const e=getEnvVarID(),t=backendCore.tenancy.getGlobalDB();let a,i=!1;try{a=yield t.get(e)}catch(e){if(404!=e.status)throw e;i=!0}const o=getCacheEnvVarID(null==a?void 0:a._rev),n=cache.get(o);if(n)return n;let s;return s=!i&&a?Object.assign(Object.assign({},a),{variables:JSON.parse(backendCore.encryption.decrypt(a.variables,backendCore.encryption.SecretOption.ENCRYPTION))}):{_id:e,variables:{}},cache.set(o,s),s}))}function update$5(e){return __awaiter(this,void 0,void 0,(function*(){const t=getEnvVarID(),a=backendCore.tenancy.getGlobalDB();return yield a.put({_id:e._id||t,_rev:e._rev||void 0,variables:backendCore.encryption.encrypt(JSON.stringify(e.variables),backendCore.encryption.SecretOption.ENCRYPTION)})}))}const api$1=new API(backendCore.env.ACCOUNT_PORTAL_URL),getResponseErrorMessage=e=>__awaiter(void 0,void 0,void 0,(function*(){try{const t=yield e.json();if(t.message)return t.message}catch(e){}try{const t=yield e.text();if(t)return t}catch(e){}})),authAware=e=>__awaiter(void 0,void 0,void 0,(function*(){let t,a;if(backendCore.env.SELF_HOSTED){if(t=yield get$6(),!t.licenseKey)return;a={[backendCore.constants.Header.LICENSE_KEY]:t.licenseKey}}else{const e=backendCore.tenancy.getTenantId();a={[backendCore.constants.Header.API_KEY]:backendCore.env.ACCOUNT_PORTAL_API_KEY,[backendCore.constants.Header.TENANT_ID]:e}}return e(a)}));let _getLicense=()=>__awaiter(void 0,void 0,void 0,(function*(){return authAware((e=>__awaiter(void 0,void 0,void 0,(function*(){const t=yield getQuotaUsage();if(null==t.usageQuota.users){const e=yield backendCore.users.getUserCount();console.info(`Syncing user count quota to ${e}`),t.usageQuota.users=e,yield setUsage(e,types.StaticQuotaName.USERS,types.QuotaUsageType.STATIC)}const a=yield backendCore.installation.getInstallFromDB(),i=backendCore.tenancy.getTenantId(),o=yield backendCore.events.identification.getUniqueTenantId(i),n=getProVersion(),s={quotaUsage:t,install:{id:a.installId,tenantId:o,version:n}},r=yield api$1.post("/api/license",{headers:Object.assign({},e),body:s});if(404!==r.status&&403!==r.status){if(200!==r.status){const e=yield getResponseErrorMessage(r);throw new backendCore.HTTPError(`Error getting license: ${e}`,r.status)}return r.json()}}))))}));backendCore.env.isJest()&&(_getLicense=jest.fn());const getLicense$1=_getLicense,triggerQuota$1=e=>authAware((t=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield api$1.post("/api/license/usage/triggered",{headers:Object.assign({},t),body:e});if(200!==a.status){const e=yield getResponseErrorMessage(a);backendCore.logging.logAlert(`Error triggering quota usage: ${e}`)}})))),activateLicenseKey$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t={installVersion:getProVersion()},a=yield api$1.post("/api/license/activate",{headers:{[backendCore.constants.Header.LICENSE_KEY]:e},body:t});if(403===a.status)throw new backendCore.HTTPError("Invalid license key",400);if(200!==a.status){const e=yield getResponseErrorMessage(a);throw new backendCore.HTTPError(`Error activating license key: ${e}`,a.status)}return a.json()}));var client=Object.freeze({__proto__:null,activateLicenseKey:activateLicenseKey$1,getLicense:getLicense$1,triggerQuota:triggerQuota$1});const PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvz3jePLCFBXZ19c8Dpkv\nXtSgOhKFOcvQdo/LV0KJRUzQWDPWuO4ILtBtnqhjtIzZH4CH0qCYBet5L6Qr4CM1\nl2HXiAD1Q2rlHNW9wDaYyKb1F5f+v4RyqCAyzlkwRdksmkLeECTboojNnmRCrE3C\n8suunQP5bEScqEY2kclqzSf8e6xqMzPUg3mL/pNa1iEv7TuLbU9nJfgR36l0WmZY\n94fWnSaT8OSXSqcxsaByf06gfS3HAoTJNc7eqz1Hf9fUORQGPUAnFK8cT3SfdA36\nd/o3ZWE1TTj1zYwlCLN5qRKr3hU8nC3xEYNEbkB9SfTRaOq9Q7P8WmfLkoCPm3pR\nmwIDAQAB\n-----END PUBLIC KEY-----\n";function verifyLicenseToken(e){return jwt.verify(e,PUBLIC_KEY,{algorithms:["RS256"]})}function sign(e,t){return jwt.sign(t,e,{encoding:"utf-8",algorithm:"RS256"})}var signing=Object.freeze({__proto__:null,sign:sign,verifyLicenseToken:verifyLicenseToken});const SELF_FEATURES={[types.PlanType.FREE]:[...SELF_FREE_LICENSE.features],[types.PlanType.PREMIUM]:void 0,[types.PlanType.PREMIUM_PLUS]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.PREMIUM_PLUS_TRIAL]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.PRO]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS],[types.PlanType.TEAM]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS],[types.PlanType.BUSINESS]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS],[types.PlanType.ENTERPRISE_BASIC]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.ENTERPRISE_BASIC_TRIAL]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS],[types.PlanType.ENTERPRISE]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS]},CLOUD_FEATURES={[types.PlanType.FREE]:[...CLOUD_FREE_LICENSE.features],[types.PlanType.PREMIUM]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS],[types.PlanType.PREMIUM_PLUS]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.BUDIBASE_AI],[types.PlanType.PREMIUM_PLUS_TRIAL]:[types.Feature.APP_BACKUPS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.BUDIBASE_AI],[types.PlanType.PRO]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.BRANDING],[types.PlanType.TEAM]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.BRANDING],[types.PlanType.BUSINESS]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE_BASIC]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.OFFLINE,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE_BASIC_TRIAL]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI],[types.PlanType.ENTERPRISE]:[types.Feature.USER_GROUPS,types.Feature.APP_BACKUPS,types.Feature.ENVIRONMENT_VARIABLES,types.Feature.ENFORCEABLE_SSO,types.Feature.AUDIT_LOGS,types.Feature.BRANDING,types.Feature.SYNC_AUTOMATIONS,types.Feature.APP_BUILDERS,types.Feature.EXPANDED_PUBLIC_API,types.Feature.VIEW_PERMISSIONS,types.Feature.TRIGGER_AUTOMATION_RUN,types.Feature.SCIM,types.Feature.VIEW_READONLY_COLUMNS,types.Feature.AI_CUSTOM_CONFIGS,types.Feature.BUDIBASE_AI]};function getFeatures(e,t){let a=[];function i(a){const i=a[t];if(!i)throw new Error(`Features do not exist for planType=${t} and hosting=${e}`);return i}switch(e){case types.Hosting.SELF:a=i(SELF_FEATURES);break;case types.Hosting.CLOUD:a=i(CLOUD_FEATURES)}return a}var features$1=Object.freeze({__proto__:null,getFeatures:getFeatures});const quotas$1=quotas$3,licenses=licenses$1,UNLIMITED=-1,DERIVED=-2,CLOUD_QUOTAS={[types.PlanType.FREE]:Object.assign({},licenses.CLOUD_FREE_LICENSE.quotas),[types.PlanType.PREMIUM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(1e4)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.PREMIUM_PLUS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(25e3)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PREMIUM_PLUS_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(25e3)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PRO]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(5)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.TEAM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(5e3)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(10)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(90))},[types.PlanType.BUSINESS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(1e4)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(5e4)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(50)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(365)),quotas$1.appBackupRetentionDays(365))},[types.PlanType.ENTERPRISE_BASIC]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(UNLIMITED)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))},[types.PlanType.ENTERPRISE_BASIC_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(UNLIMITED)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(15)),quotas$1.appBackupRetentionDays(15))},[types.PlanType.ENTERPRISE]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(1e4)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))}},SELF_QUOTAS={[types.PlanType.FREE]:Object.assign({},licenses.SELF_FREE_LICENSE.quotas),[types.PlanType.PREMIUM]:void 0,[types.PlanType.PREMIUM_PLUS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PREMIUM_PLUS_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(0)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(1))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(30))},[types.PlanType.PRO]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(5)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(7)),quotas$1.appBackupRetentionDays(7))},[types.PlanType.TEAM]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(10)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(30)),quotas$1.appBackupRetentionDays(90))},[types.PlanType.BUSINESS]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(50)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(0))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(90)),quotas$1.appBackupRetentionDays(365))},[types.PlanType.ENTERPRISE_BASIC]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))},[types.PlanType.ENTERPRISE_BASIC_TRIAL]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(15)),quotas$1.appBackupRetentionDays(15))},[types.PlanType.ENTERPRISE]:{usage:{monthly:Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.queries(UNLIMITED)),quotas$1.automations(UNLIMITED)),quotas$1.dayPasses(DERIVED)),quotas$1.budibaseAICredits(0)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},quotas$1.rows(UNLIMITED)),quotas$1.apps(UNLIMITED)),quotas$1.users(UNLIMITED)),quotas$1.creators(UNLIMITED)),quotas$1.userGroups(UNLIMITED)),quotas$1.plugins(UNLIMITED)),quotas$1.customAIConfigurations(UNLIMITED))},constant:Object.assign(Object.assign({},quotas$1.automationLogRetentionDays(UNLIMITED)),quotas$1.appBackupRetentionDays(UNLIMITED))}};function getQuotas(e,t){let a;function i(a){const i=a[t];if(!i)throw new Error(`Quotas do not exist for planType=${t} and hosting=${e}`);return i}switch(e){case types.Hosting.SELF:a=i(SELF_QUOTAS);break;case types.Hosting.CLOUD:a=i(CLOUD_QUOTAS)}return JSON.parse(JSON.stringify(a))}var quotas$2=Object.freeze({__proto__:null,UNLIMITED:UNLIMITED,getQuotas:getQuotas});function appExists(e){return __awaiter(this,void 0,void 0,(function*(){return(yield backendCore.db.getAllApps({all:!0,idsOnly:!0})).includes(e)}))}function objectToBase64(e){const t=JSON.stringify(e);return Buffer.from(t).toString("base64")}function base64ToObject(e){const t=Buffer.from(e,"base64").toString();return JSON.parse(t)}var encoding=Object.freeze({__proto__:null,base64ToObject:base64ToObject,objectToBase64:objectToBase64}),index$i=Object.freeze({__proto__:null,appExists:appExists,encoding:encoding});function activateOfflineLicenseToken(e){return __awaiter(this,void 0,void 0,(function*(){yield save$4({offlineLicenseToken:e}),yield refresh()}))}function deleteOfflineLicenseToken(){return __awaiter(this,void 0,void 0,(function*(){yield save$4({offlineLicenseToken:void 0}),yield refresh()}))}function getOfflineLicenseToken(){return __awaiter(this,void 0,void 0,(function*(){return(yield get$6()).offlineLicenseToken}))}function getIdentifier(){return __awaiter(this,void 0,void 0,(function*(){const e=(yield backendCore.installation.getInstall()).installId,t=backendCore.context.getTenantId();return{installId:e,tenantId:yield backendCore.events.identification.getUniqueTenantId(t)}}))}function getIdentifierBase64(){return __awaiter(this,void 0,void 0,(function*(){return objectToBase64(yield getIdentifier())}))}function getIdentifierFromBase64(e){return base64ToObject(e)}function verifyExpiry(e){if(Date.now()>new Date(e.expireAt).getTime())throw new Error(`Offline license has expired. expireAt=${e.expireAt}`)}function verifyInstallation(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getIdentifier();if(e.identifier.installId!==t.installId||e.identifier.tenantId!==t.tenantId)throw new Error("Invalid offline license")}))}function enrichLicense(e){const t=e.plan.type,a=types.Hosting.SELF,i=getFeatures(a,t),o=getQuotas(a,t);return e.features=union(e.features,i),e.quotas=merge(e.quotas,o),e}function getOfflineLicense$1(){return __awaiter(this,void 0,void 0,(function*(){try{const e=yield getOfflineLicenseToken();if(e){const t=yield verifyLicenseToken(e);return verifyExpiry(t),yield verifyInstallation(t),enrichLicense(t)}}catch(e){console.error("Error retrieving offline license",e)}}))}const SUB_DIRECTORY=backendCore.env.isTest()?".budibase-test":".budibase",DIRECTORY=path.join(os.tmpdir(),SUB_DIRECTORY),OFFLINE_LICENSE_FILE="dev_license.txt",LICENSE_FILE_PATH=path.join(DIRECTORY,OFFLINE_LICENSE_FILE);if(!fs.existsSync(DIRECTORY))try{fs.mkdirSync(DIRECTORY)}catch(e){}function getOfflineLicense(){try{if(fs.existsSync(LICENSE_FILE_PATH)){return verifyLicenseToken(fs.readFileSync(LICENSE_FILE_PATH,{encoding:"utf-8"}))}}catch(e){console.error("Error retrieving offline license from disk",e)}}function writeDevLicenseToDisk(e){console.log(`Writing license to: ${LICENSE_FILE_PATH}`),fs.writeFileSync(LICENSE_FILE_PATH,e,{encoding:"utf-8"})}function deleteDevLicense(){fs.rmSync(LICENSE_FILE_PATH,{force:!0})}var dev=Object.freeze({__proto__:null,deleteDevLicense:deleteDevLicense,getOfflineLicense:getOfflineLicense,writeDevLicenseToDisk:writeDevLicenseToDisk}),index$h=Object.freeze({__proto__:null,activateOfflineLicenseToken:activateOfflineLicenseToken,deleteOfflineLicenseToken:deleteOfflineLicenseToken,dev:dev,enrichLicense:enrichLicense,getIdentifier:getIdentifier,getIdentifierBase64:getIdentifierBase64,getIdentifierFromBase64:getIdentifierFromBase64,getOfflineLicense:getOfflineLicense$1,getOfflineLicenseToken:getOfflineLicenseToken,signing:signing,verifyExpiry:verifyExpiry,verifyInstallation:verifyInstallation});const getLicense=()=>__awaiter(void 0,void 0,void 0,(function*(){if(backendCore.env.OFFLINE_MODE)return getOfflineLicense$1();let e=yield getLicense$1();return e||(e=getOfflineLicense()),e})),getFreeLicense=()=>backendCore.env.SELF_HOSTED?SELF_FREE_LICENSE:CLOUD_FREE_LICENSE;function activateLicenseKey(e){return __awaiter(this,void 0,void 0,(function*(){yield activateLicenseKey$1(e),yield save$4({licenseKey:e}),yield refresh()}))}function getLicenseKey(){return __awaiter(this,void 0,void 0,(function*(){return(yield get$6()).licenseKey}))}function deleteLicenseKey(){return __awaiter(this,void 0,void 0,(function*(){yield save$4({licenseKey:void 0}),yield refresh()}))}var keys=Object.freeze({__proto__:null,activateLicenseKey:activateLicenseKey,deleteLicenseKey:deleteLicenseKey,getLicenseKey:getLicenseKey});const EXPIRY_SECONDS=3600,refresh=()=>__awaiter(void 0,void 0,void 0,(function*(){yield invalidate(),yield getCachedLicense()}));let _getCachedLicense=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const{populateLicense:a=getLicense,populateFreeLicense:i=getFreeLicense}=t||{};return yield tracer.trace("getCachedLicense",(t=>__awaiter(void 0,void 0,void 0,(function*(){const o=backendCore.tenancy.getTenantId(),n=yield getClient();let s=yield n.get(o);return t.addTags({tenantId:o,foundInCache:!!s}),s||(s=yield tracer.trace("populateLicense",(()=>__awaiter(void 0,void 0,void 0,(function*(){return yield a(o)})))),t.addTags({populatedLicense:!!s}),s||(s=tracer.trace("populateFreeLicense",(()=>i(e,o))),t.addTags({populatedFreeLicense:!!s})),s.refreshedAt=(new Date).toISOString(),t.addTags({refreshedAt:s.refreshedAt,expirySeconds:EXPIRY_SECONDS}),yield n.store(o,s,EXPIRY_SECONDS),s)}))))}));backendCore.env.isJest()&&(_getCachedLicense=jest.fn());const getCachedLicense=_getCachedLicense,invalidate=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.tenancy.getTenantId(),t=yield getClient();yield t.delete(e)}));var index$g=Object.freeze({__proto__:null,getCachedLicense:getCachedLicense,invalidate:invalidate,refresh:refresh}),index$f=Object.freeze({__proto__:null,cache:index$g,client:client,features:features$1,getFreeLicense:getFreeLicense,getLicense:getLicense,keys:keys,offline:index$h,quotas:quotas$2});function areFeaturesEnabled(e,t){return __awaiter(this,void 0,void 0,(function*(){Array.isArray(e)||(e=[e]),t||(t=yield getCachedLicense());for(let a of e)if(!(null==t?void 0:t.features.includes(a)))return!1;return!0}))}function checkFeature(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield areFeaturesEnabled(e,t)))throw new backendCore.FeatureDisabledError(`${e} is not currently enabled`,e)}))}function checkFeatures(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield areFeaturesEnabled(e,t))){const t=e.join(", ");throw new backendCore.FeatureDisabledError(`${t} are not currently enabled`,t)}}))}function checkBackups(e){return(...t)=>__awaiter(this,void 0,void 0,(function*(){return yield checkFeature(types.Feature.APP_BACKUPS),e(...t)}))}function isBackupsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.APP_BACKUPS)}))}function isBrandingEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.BRANDING)}))}function isEnforceableSSO(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.ENFORCEABLE_SSO)}))}function isSyncAutomationsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.SYNC_AUTOMATIONS)}))}function isTriggerAutomationRunEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.TRIGGER_AUTOMATION_RUN)}))}function isAppBuildersEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.APP_BUILDERS)}))}function isAuditLogsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.AUDIT_LOGS)}))}function isUserGroupsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.USER_GROUPS)}))}function isExpandedPublicApiEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.EXPANDED_PUBLIC_API)}))}function isSSOEnforced(e){return __awaiter(this,void 0,void 0,(function*(){if(backendCore.env.ENABLE_SSO_MAINTENANCE_MODE)return!1;if(!(yield isEnforceableSSO()))return!1;let t;return t=(null==e?void 0:e.config)?e.config:yield backendCore.configs.getSettingsConfig(),!!t.isSSOEnforced}))}const checkSCIM=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=types.Feature.SCIM,t=yield areFeaturesEnabled(e),a=yield backendCore.configs.getSCIMConfig();if(!t||!(null==a?void 0:a.enabled))throw new backendCore.FeatureDisabledError(`${e} is not currently enabled`,e);return!0}));function isViewPermissionEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.VIEW_PERMISSIONS)}))}function isViewReadonlyColumnsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.VIEW_READONLY_COLUMNS)}))}function isBudibaseAIEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.BUDIBASE_AI)}))}function isAICustomConfigsEnabled(){return __awaiter(this,void 0,void 0,(function*(){return areFeaturesEnabled(types.Feature.AI_CUSTOM_CONFIGS)}))}var features=Object.freeze({__proto__:null,checkBackups:checkBackups,checkFeature:checkFeature,checkFeatures:checkFeatures,checkSCIM:checkSCIM,isAICustomConfigsEnabled:isAICustomConfigsEnabled,isAppBuildersEnabled:isAppBuildersEnabled,isAuditLogsEnabled:isAuditLogsEnabled,isBackupsEnabled:isBackupsEnabled,isBrandingEnabled:isBrandingEnabled,isBudibaseAIEnabled:isBudibaseAIEnabled,isEnforceableSSO:isEnforceableSSO,isExpandedPublicApiEnabled:isExpandedPublicApiEnabled,isSSOEnforced:isSSOEnforced,isSyncAutomationsEnabled:isSyncAutomationsEnabled,isTriggerAutomationRunEnabled:isTriggerAutomationRunEnabled,isUserGroupsEnabled:isUserGroupsEnabled,isViewPermissionEnabled:isViewPermissionEnabled,isViewReadonlyColumnsEnabled:isViewReadonlyColumnsEnabled});const DEFAULT_BRANDING_CONFIG={faviconUrl:void 0,faviconUrlEtag:void 0,emailBrandingEnabled:!0,testimonialsEnabled:!0,platformTitle:void 0,loginHeading:void 0,loginButton:void 0,metaDescription:void 0,metaImageUrl:void 0,metaTitle:void 0};function getBrandingConfig(e){return __awaiter(this,void 0,void 0,(function*(){return(yield isBrandingEnabled())?{faviconUrl:e.faviconUrl,faviconUrlEtag:e.faviconUrlEtag,emailBrandingEnabled:e.emailBrandingEnabled,testimonialsEnabled:e.testimonialsEnabled,platformTitle:e.platformTitle,loginHeading:e.loginHeading,loginButton:e.loginButton,metaDescription:e.metaDescription,metaImageUrl:e.metaImageUrl,metaTitle:e.metaTitle}:DEFAULT_BRANDING_CONFIG}))}var index$e=Object.freeze({__proto__:null,getBrandingConfig:getBrandingConfig});const BUDIBASE_AI_CONFIG_ID="budibase_ai";function enrichAIConfig(e){return __awaiter(this,void 0,void 0,(function*(){return(yield isBudibaseAIEnabled())&&(e.config[BUDIBASE_AI_CONFIG_ID]={provider:"OpenAI",active:!0,isDefault:Object.keys(e.config).every((t=>!e.config[t].isDefault)),defaultModel:process.env.BUDIBASE_AI_DEFAULT_MODEL||"gpt-4o-mini",apiKey:process.env.OPENAI_API_KEY,name:"Budibase AI"}),e}))}var index$d=Object.freeze({__proto__:null,enrichAIConfig:enrichAIConfig});const increment=(e,t,a)=>tryIncrement({change:1,name:e,type:t,opts:a}),incrementMany=e=>tryIncrement(e),tryIncrement=e=>__awaiter(void 0,void 0,void 0,(function*(){var t;const a=Array.isArray(e)?e:[e];yield updateUsage(a.map((e=>{var t,a;return{usageChange:e.change,name:e.name,type:e.type,opts:{dryRun:!0,suppressErrorLog:null===(t=e.opts)||void 0===t?void 0:t.suppressErrorLog,id:null===(a=e.opts)||void 0===a?void 0:a.id}}})));const i=[];for(let e of a){let a=null===(t=e.opts)||void 0===t?void 0:t.fn;a&&i.push(yield a())}return yield updateUsage(a.map((e=>{var t,a,i;return{usageChange:e.change,name:e.name,type:e.type,opts:{dryRun:!1,valueFn:null===(t=e.opts)||void 0===t?void 0:t.valueFn,suppressErrorLog:null===(a=e.opts)||void 0===a?void 0:a.suppressErrorLog,id:null===(i=e.opts)||void 0===i?void 0:i.id}}}))),i[0]})),decrement=(e,t,a={})=>updateUsage({usageChange:-1,name:e,type:t,opts:a}),decrementMany=e=>{const t=Array.isArray(e)?e:[e];return updateUsage(t.map((e=>({usageChange:-e.change,name:e.name,type:e.type,opts:e.opts}))))},set=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){return setUsage(a,e,t)})),getExistingTriggers=(e,t,a)=>{if(e==types.QuotaUsageType.STATIC){const e=a.usageQuota.triggers;return e&&e[t]||{}}{const e=getCurrentMonthString(),i=a.monthly[e].triggers;return i&&i[t]||{}}},triggerQuota=(e,t,a,i)=>__awaiter(void 0,void 0,void 0,(function*(){try{yield backendCore.locks.doWithLock({type:types.LockType.TRY_ONCE,name:types.LockName.TRIGGER_QUOTA,resource:e,ttl:1e4},(()=>__awaiter(void 0,void 0,void 0,(function*(){const e={percentage:a,name:t.name};i&&(e.resetDate=i),yield triggerQuota$1(e)}))))}catch(e){backendCore.logging.logAlert("Error triggering quota",e)}})),checkTriggers=(e,t,a,i)=>__awaiter(void 0,void 0,void 0,(function*(){const o=yield getQuotaUsage(),n=e===types.QuotaUsageType.MONTHLY?o.quotaReset:void 0,s=yield getExistingTriggers(e,t,o),r=i.triggers;let u=a/i.value*100;u>100&&(u=100);for(const[e,a]of r.entries()){if(u>=a&&i.value!==UNLIMITED$2){if(!s[a]){s[a]=(new Date).toISOString();(!(u>=(r[e+1]||100))||u===a)&&(yield triggerQuota(t,i,u,n))}}else s[a]=void 0}return s})),updateUsage=e=>__awaiter(void 0,void 0,void 0,(function*(){var t,a,i,o,n;const s=Array.isArray(e)?e:[e];let r,u=null;const d=[];let c={},l={},p={},g={};for(let e of s){try{u=backendCore.context.getAppId()}catch(e){}if(types.APP_QUOTA_NAMES.includes(e.name)&&!u)throw new Error("App context required for quota update");try{r=yield getLicensedQuota(types.QuotaType.USAGE,e.name,e.type),d.push(r);let{total:n,app:s,breakdown:u}=yield getCurrentUsageValues(e.type,e.name,null===(t=e.opts)||void 0===t?void 0:t.id);n+=e.usageChange,null!=s&&(s+=e.usageChange),null!=u&&(u+=e.usageChange);let y={};if((null===(a=e.opts)||void 0===a?void 0:a.dryRun)||(y=yield checkTriggers(e.type,e.name,n,r),g=Object.assign(Object.assign({},g),{[e.name]:y})),r.value!==UNLIMITED$2&&n>r.value&&e.usageChange>0)throw new backendCore.UsageLimitError(`Licensed ${r.name} of ${r.value} has been exceeded`,r.name);if(n=Math.max(0,n),s&&(s=Math.max(0,s)),u&&(u=Math.max(0,u),p=Object.assign(Object.assign({},p),{[e.name]:u})),!(null===(i=e.opts)||void 0===i?void 0:i.dryRun)){let t=null===(o=e.opts)||void 0===o?void 0:o.valueFn;t&&(n=yield t(),s=n),c=Object.assign(Object.assign({},c),{[e.name]:n}),l=Object.assign(Object.assign({},l),{[e.name]:s})}}catch(t){throw(null===(n=e.opts)||void 0===n?void 0:n.suppressErrorLog)||console.error(`Error updating usage quotas for ${e.name}`,t),t}}const y=s.filter((e=>{var t;return!(null===(t=e.opts)||void 0===t?void 0:t.dryRun)})).map((e=>({name:e.name,type:e.type,values:{total:c[e.name],app:l[e.name],breakdown:p[e.name],triggers:g[e.name]},opts:e.opts})));y.length>0&&(yield setAllUsage(y))})),getLicensedQuota=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield getCachedLicense();if(!i){const e=backendCore.tenancy.getTenantId();throw new Error("License not found for tenant id "+e)}if(a&&types.isStaticQuota(e,a,t))return i.quotas[e][a][t];if(a&&types.isMonthlyQuota(e,a,t))return i.quotas[e][a][t];if(types.isConstantQuota(e,t))return i.quotas[e][t];throw new Error("Invalid quota type")})),usageLimitIsExceeded=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){try{return yield updateUsage({usageChange:1,name:e,type:t,opts:{dryRun:!0}}),!1}catch(e){if(e.code===backendCore.ErrorCode.USAGE_LIMIT_EXCEEDED)return!0;throw e}})),getDevAppsCount=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=yield backendCore.db.getAllApps({dev:!0});return e?e.length:0})),addApp=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{appId:t}={}){return increment(types.StaticQuotaName.APPS,types.QuotaUsageType.STATIC,{fn:e,valueFn:getDevAppsCount,id:t})})),removeApp=(...e)=>__awaiter(void 0,[...e],void 0,(function*({appId:e}={}){return decrement(types.StaticQuotaName.APPS,types.QuotaUsageType.STATIC,{valueFn:getDevAppsCount,id:e})})),addRow=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{tableId:t}={}){return increment(types.StaticQuotaName.ROWS,types.QuotaUsageType.STATIC,{fn:e,id:t})})),removeRow=(...e)=>__awaiter(void 0,[...e],void 0,(function*({tableId:e}={}){return decrement(types.StaticQuotaName.ROWS,types.QuotaUsageType.STATIC,{id:e})})),addRows=(e,t,...a)=>__awaiter(void 0,[e,t,...a],void 0,(function*(e,t,{tableId:a}={}){return incrementMany({change:e,name:types.StaticQuotaName.ROWS,type:types.QuotaUsageType.STATIC,opts:{fn:t,id:a}})})),removeRows=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{tableId:t}={}){return decrementMany({change:e,name:types.StaticQuotaName.ROWS,type:types.QuotaUsageType.STATIC,opts:{id:t}})})),addAutomation=(e,...t)=>__awaiter(void 0,[e,...t],void 0,(function*(e,{automationId:t}={}){return increment(types.MonthlyQuotaName.AUTOMATIONS,types.QuotaUsageType.MONTHLY,{fn:e,id:t})})),ONE_DAY=864e5;function checkDayPass(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.user;if(!t||!t._id)return;let a;t.dayPassRecordedAt&&(a=new Date(t.dayPassRecordedAt));const i=new Date(Date.now()-ONE_DAY);if(!a||a.getTime()<i.getTime())try{yield recordActivityInAccountPortal(t),yield recordDayPassOnQuotas(),yield recordDayPassTimeOnUser(t)}catch(t){if("usage_limit_exceeded"!=t.code)throw t;backendCore.utils.isServingApp(e)&&e.redirect("/")}}))}function recordDayPassOnQuotas(){return __awaiter(this,void 0,void 0,(function*(){return increment(types.MonthlyQuotaName.DAY_PASSES,types.QuotaUsageType.MONTHLY,{suppressErrorLog:!0})}))}function recordDayPassTimeOnUser(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();let a=yield t.get(e._id);const i=new Date,o=(new Date).toISOString();e.dayPassRecordedAt=o,a.dayPassRecordedAt=o;try{console.log(`Recording day pass for user=${e._id}`),yield t.put(a)}catch(o){if(409!==o.status)throw o;if(console.warn(`Conflict recording day pass for user=${e._id}`),a=yield t.get(e._id),!a.dayPassRecordedAt||new Date(a.dayPassRecordedAt).getDay()!==i.getDay())throw console.error(`Day pass not recorded for user=${e._id}`),o;console.log(`Day pass already recorded for user=${e._id}`)}yield backendCore.cache.user.invalidateUser(e._id)}))}function recordActivityInAccountPortal(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;backendCore.env.SELF_HOSTED&&(null===(a=null===(t=e.license)||void 0===t?void 0:t.plan)||void 0===a?void 0:a.type)===types.PlanType.FREE||backendCore.env.isDev()&&backendCore.env.DISABLE_ACCOUNT_PORTAL||(yield createActivity(e._id))}))}const addGroup=e=>__awaiter(void 0,void 0,void 0,(function*(){return increment(types.StaticQuotaName.USER_GROUPS,types.QuotaUsageType.STATIC,{fn:e})})),removeGroup=()=>__awaiter(void 0,void 0,void 0,(function*(){return decrement(types.StaticQuotaName.USER_GROUPS,types.QuotaUsageType.STATIC)})),addPlugin=e=>__awaiter(void 0,void 0,void 0,(function*(){return increment(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,{fn:e})})),removePlugin=()=>__awaiter(void 0,void 0,void 0,(function*(){return decrement(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC)})),updatePluginCount=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,e)})),addUsers$1=(e,t,a)=>__awaiter(void 0,void 0,void 0,(function*(){const i=[{change:e,name:types.StaticQuotaName.USERS,type:types.QuotaUsageType.STATIC,opts:{fn:a,valueFn:backendCore.users.getUserCount}}];t>0&&i.push({change:t,name:types.StaticQuotaName.CREATORS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getCreatorCount}});const o=yield incrementMany(i);return yield getLicense$1(),o})),removeUsers$1=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=[{change:e,name:types.StaticQuotaName.USERS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getUserCount}}];t>0&&a.push({change:t,name:types.StaticQuotaName.CREATORS,type:types.QuotaUsageType.STATIC,opts:{valueFn:backendCore.users.getCreatorCount}}),yield decrementMany(a),yield getLicense$1()})),setBudibaseAICredits=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.MonthlyQuotaName.BUDIBASE_AI_CREDITS,types.QuotaUsageType.MONTHLY,e)})),updateCustomAIConfigCount=e=>__awaiter(void 0,void 0,void 0,(function*(){return set(types.StaticQuotaName.PLUGINS,types.QuotaUsageType.STATIC,e)}));var quotas=Object.freeze({__proto__:null,addApp:addApp,addAutomation:addAutomation,addGroup:addGroup,addPlugin:addPlugin,addRow:addRow,addRows:addRows,addUsers:addUsers$1,bustCache:bustCache,checkDayPass:checkDayPass,decrement:decrement,decrementMany:decrementMany,getCurrentUsageValues:getCurrentUsageValues,getLicensedQuota:getLicensedQuota,getQuotaUsage:getQuotaUsage,increment:increment,incrementMany:incrementMany,removeApp:removeApp,removeGroup:removeGroup,removePlugin:removePlugin,removeRow:removeRow,removeRows:removeRows,removeUsers:removeUsers$1,set:set,setAllUsage:setAllUsage,setAppUsageValue:setAppUsageValue,setBudibaseAICredits:setBudibaseAICredits,setUsage:setUsage,setUsagePerApp:setUsagePerApp,updateCustomAIConfigCount:updateCustomAIConfigCount,updatePluginCount:updatePluginCount,updateUsage:updateUsage,usageLimitIsExceeded:usageLimitIsExceeded,utils:utils});const api=new API(backendCore.env.ACCOUNT_PORTAL_URL),createActivity$1=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield send((t=>api.post(`/api/users/${e}/activity`,t)),{body:t});if(a){if(201!==a.status){const e=`Error creating account user activity: ${yield a.text()}`;throw backendCore.logging.logAlert(e),new Error(e)}return a.json()}})),send=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){const a=yield authorizationHeaders(),i=Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),a)});return e(i)})),authorizationHeaders=()=>__awaiter(void 0,void 0,void 0,(function*(){if(backendCore.env.SELF_HOSTED){const e=yield get$6();if(e.licenseKey){const t=e.licenseKey;return{[backendCore.constants.Header.LICENSE_KEY]:t}}return{}}{const e=backendCore.tenancy.getTenantId();return{[backendCore.constants.Header.API_KEY]:backendCore.env.ACCOUNT_PORTAL_API_KEY,[backendCore.constants.Header.TENANT_ID]:e}}}));class GroupNameUnavailableError extends backendCore.HTTPError{constructor(e){super(`Group name "${e}" is unavailable`,409)}}function findHighestRole(e,t){return __awaiter(this,void 0,void 0,(function*(){try{let a=[];for(let i of e)if(i.roles){const e=i.roles[backendCore.db.getProdAppID(t)];e&&a.push(e)}const i=yield Promise.all(a.map((e=>__awaiter(this,void 0,void 0,(function*(){return{[e]:yield backendCore.roles.roleToNumber(e)}})))));let o,n=0;const s={};i.forEach((e=>{const[t,a]=Object.entries(e)[0];s[t]={roleId:t,roleNum:a}}));for(let{roleId:e,roleNum:t}of Object.values(s))t>n&&(n=t,o=e);return o}catch(a){throw backendCore.logging.logAlert(`Error finding higest role for ${e.length} on app ${t}`,a),a}}))}function groupList(e,t){return __awaiter(this,void 0,void 0,(function*(){return t=t?t.filter((t=>e.includes(t._id))):yield getBulk$1(e,{enriched:!1})}))}function getGroupBuilderAppIds(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!e.userGroups)return[];const i=yield groupList(e.userGroups,null==t?void 0:t.groups),o=(null==t?void 0:t.appId)?backendCore.db.getProdAppID(null==t?void 0:t.appId):null;let n=[];for(let e of i){const t=null===(a=e.builder)||void 0===a?void 0:a.apps;o&&(null==t?void 0:t.includes(o))?n.push(o):o||(n=n.concat(t||[]))}return[...new Set(n)]}))}function getGroupRoleId(e,t,a){return __awaiter(this,void 0,void 0,(function*(){var i;if(!e.userGroups)return null;let o=yield groupList(e.userGroups,null==a?void 0:a.groups);const n=backendCore.db.getProdAppID(t);return(null===(i=e.roles)||void 0===i?void 0:i[n])?e.roles[n]:(o=o.filter((e=>{if(!(null==e?void 0:e.roles))return!1;return Object.keys(e.roles).includes(n)})),yield findHighestRole(o,t))}))}function enrichUserRolesFromGroups(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;if(!e||!e.userGroups)return e;const i=yield getBulk(e.userGroups,{enriched:!1});let o=[];for(let e of i)(null==e?void 0:e.roles)&&(o=o.concat(Object.keys(e.roles)));o=[...new Set(o)];for(let t of o)yield backendCore.context.doInAppContext(t,(()=>__awaiter(this,void 0,void 0,(function*(){if(e.roles[t])return;const a=yield findHighestRole(i,t);a&&(e.roles[t]=a)}))));const n=yield getGroupBuilderAppIds(e,{groups:i});if(n.length&&!(null===(t=e.builder)||void 0===t?void 0:t.global)){const t=(null===(a=e.builder)||void 0===a?void 0:a.apps)||[];e.builder={apps:t.concat(n)}}return e}))}function fetch$4(){return __awaiter(this,void 0,void 0,(function*(){return yield fetch$5()}))}function get$3(e){return __awaiter(this,void 0,void 0,(function*(){return yield get$5(e)}))}function getBulk(e){return __awaiter(this,arguments,void 0,(function*(e,t={enriched:!0}){return yield getBulk$1(e,t)}))}function guardNameAvailability(e){return __awaiter(this,void 0,void 0,(function*(){if(yield getByName(e))throw new GroupNameUnavailableError(e)}))}function getCreatorsCountInGroup(e){return __awaiter(this,void 0,void 0,(function*(){let t=yield getGroupUsers(e._id);if(!t.length)return 0;const a=backendCore.tenancy.getGlobalDB(),i=yield Promise.all(t.map((e=>a.get(e._id))));return(yield Promise.all(i.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length}))}function save$2(e){return __awaiter(this,void 0,void 0,(function*(){var t;let a=[],i=!e._id,o=0;if(delete e.users,e._id){const i=yield get$5(e._id);if(i.name!==e.name&&(yield guardNameAvailability(e.name)),a.push(backendCore.events.group.updated(e)),JSON.stringify(i.roles)!==JSON.stringify(e.roles)){const n=(null===(t=i.users)||void 0===t?void 0:t.length)||0;let s=0;n>0&&(s=yield getCreatorsCountInGroup(i)),o=Object.values(e.roles).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)?n-s:-n,a.push(backendCore.events.group.permissionsEdited(e))}}else e._id=generateUserGroupID(),yield guardNameAvailability(e.name),a.push(backendCore.events.group.created(e));yield Promise.all(a);const n=()=>save$3(e);if(i)return yield addGroup(n);{const t=yield n();if(o>0)yield addUsers$1(0,o);else if(o<0){const t=yield getCreatorsCountInGroup(e),a=Math.abs(o)-t;a>0&&(yield removeUsers$1(0,a))}return t}}))}function remove$4(e,t){return __awaiter(this,void 0,void 0,(function*(){let a;try{a=yield get$5(e)}catch(e){throw new Error("Group not found")}let i=()=>{};if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const t=backendCore.tenancy.getGlobalDB(),a=yield getGroupUsers(e),o=(yield Promise.all(a.map((e=>t.get(e._id))))).map((t=>Object.assign(Object.assign({},t),{userGroups:t.userGroups.filter((t=>t!==e))}))),n=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,s=a.length-n;s&&(i=()=>removeUsers$1(0,s))}let o=yield destroy$2(e,t);return yield backendCore.events.group.deleted(a),yield removeGroup(),yield i(),o}))}function addUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$5(e),i=yield backendCore.users.bulkGetGlobalUsersById(t);let o=[];for(let t of i)t.userGroups||(t.userGroups=[]),t.userGroups.includes(e)||o.push(t);if(!o.length)return o;const n=o.map((t=>Object.assign(Object.assign({},t),{userGroups:[...(null==t?void 0:t.userGroups)||[],e]})));yield backendCore.users.bulkUpdateGlobalUsers(n);if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const e=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,t=o.length-e;t&&(yield addUsers$1(0,t))}let s=[];for(let e of t)s.push(backendCore.cache.user.invalidateUser(e));return yield Promise.all(s),yield backendCore.events.group.usersAdded(n.length,a),n}))}function removeUsers(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$5(e),i=yield backendCore.users.bulkGetGlobalUsersById(t);let o=[];for(let t of i){if(!t.userGroups||!t.userGroups.includes(e))continue;const a=t.userGroups.indexOf(e);t.userGroups.splice(a,1),o.push(t)}yield backendCore.users.bulkUpdateGlobalUsers(o);if(Object.values(a.roles||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)){const e=(yield Promise.all(o.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,t=o.length-e;t&&(yield removeUsers$1(0,t))}let n=[];for(let e of t)n.push(backendCore.cache.user.invalidateUser(e));return yield Promise.all(n),o.length&&(yield backendCore.events.group.usersDeleted(o.length,a)),o}))}function updateGroupApps$1(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield get$3(e);if(a.roles||(a.roles={}),t.appsToAdd)for(let e of t.appsToAdd)a.roles[e.appId]=e.roleId;if(t.appsToRemove)for(let e of t.appsToRemove)delete a.roles[e.appId];return yield save$2(a)}))}function cleanupApp(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield fetch$4(),a=[];for(let i of t)i.roles&&i.roles[e]&&(delete i.roles[e],a.push(i));return yield bulkSave(a)}))}function addAppBuilder$3(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");const i=backendCore.db.getProdAppID(t),o=yield get$3(e);null!==(a=o.builder)&&void 0!==a||(o.builder={apps:[]}),o.builder.apps.includes(t)||(o.builder.apps.push(i),yield save$2(o))}))}function removeAppBuilder$3(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");const i=backendCore.db.getProdAppID(t),o=yield get$3(e);(null===(a=o.builder)||void 0===a?void 0:a.apps.includes(t))&&(o.builder.apps=o.builder.apps.filter((e=>e!==i)),yield save$2(o))}))}function adjustGroupCreatorsQuotas(){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isUserGroupsEnabled())){const e=backendCore.tenancy.getGlobalDB(),t=((yield fetch$4())||[]).filter((e=>Object.values((null==e?void 0:e.roles)||{}).includes(backendCore.roles.BUILTIN_ROLE_IDS.ADMIN)));for(let a of t){const t=yield getGroupUsers(a._id),i=(yield Promise.all(t.map((t=>e.get(t._id))))).map((e=>Object.assign(Object.assign({},e),{userGroups:e.userGroups.filter((e=>e!==a._id))}))),o=(yield Promise.all(i.map(backendCore.userUtils.isCreator))).filter((e=>!!e)).length,n=t.length-o;yield save$3(Object.assign(Object.assign({},a),{roles:{}})),n&&(yield removeUsers$1(0,n))}}}))}var groups$2=Object.freeze({__proto__:null,addAppBuilder:addAppBuilder$3,addUsers:addUsers,adjustGroupCreatorsQuotas:adjustGroupCreatorsQuotas,cleanupApp:cleanupApp,enrichUserRolesFromGroups:enrichUserRolesFromGroups,fetch:fetch$4,get:get$3,getBulk:getBulk,getGroupBuilderAppIds:getGroupBuilderAppIds,getGroupRoleId:getGroupRoleId,remove:remove$4,removeAppBuilder:removeAppBuilder$3,removeUsers:removeUsers,save:save$2,updateGroupApps:updateGroupApps$1});backendCore.users.UserDB.init(quotas,groups$2,features);const db=backendCore.users.UserDB,createActivity=e=>__awaiter(void 0,void 0,void 0,(function*(){const t={timestamp:Date.now()};return createActivity$1(e,t)}));function addAppBuilder$2(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");yield backendCore.users.addAppBuilder(e,t)}))}function removeAppBuilder$2(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAppBuildersEnabled()))throw new Error("Feature not enabled, please check license");yield backendCore.users.removeAppBuilder(e,t)}))}var index$c=Object.freeze({__proto__:null,addAppBuilder:addAppBuilder$2,createActivity:createActivity,db:db,removeAppBuilder:removeAppBuilder$2});function backOff(e,t){return __awaiter(this,void 0,void 0,(function*(){let a,i,o=5,n=!1;for(;o>0;o--)try{i=yield e(),n=!0;break}catch(e){a=e}return n||backendCore.logging.logWarn(`Failed to backoff: ${t}`,a),i}))}const{SEPARATOR:SEPARATOR,UNICODE_MAX:UNICODE_MAX,DocumentType:DocumentType,AutomationViewMode:AutomationViewMode,ViewName:ViewName,getQueryIndex:getQueryIndex}=backendCore.db,EARLIEST_DATE=new Date(0).toISOString(),EXPIRED_LIMIT=100,oldestLogDate$1=()=>__awaiter(void 0,void 0,void 0,(function*(){return getOldestRetentionDate(types.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS)}));function getAutomationLogParams(e,t,{status:a,automationId:i}={},o={}){const n=i?`${i}${SEPARATOR}`:"",s=a?`${a}${SEPARATOR}`:"";let r;return r=a&&i?`${AutomationViewMode.ALL}${SEPARATOR}${s}${n}`:a?`${AutomationViewMode.STATUS}${SEPARATOR}${s}`:i?`${AutomationViewMode.AUTOMATION}${SEPARATOR}${n}`:`${DocumentType.AUTOMATION_LOG}${SEPARATOR}`,Object.assign(Object.assign({},o),{descending:!0,startkey:`${r}${t}${UNICODE_MAX}`,endkey:`${r}${e}`})}function getStatus(e){var t,a,i;let o=types.AutomationStatus.SUCCESS,n=!0;for(let s of e.steps){const e=null===(a=null===(t=s.outputs)||void 0===t?void 0:t.status)||void 0===a?void 0:a.toLowerCase(),r="stopped_error"===e;if(!n||r){if(r){o=types.AutomationStatus.STOPPED_ERROR;break}if(!(null===(i=s.outputs)||void 0===i?void 0:i.success)){o=types.AutomationStatus.ERROR;break}if("stopped"===e){o=types.AutomationStatus.STOPPED;break}}else n=!1}return o}function generateAutomationLogID(e,t,a){return`${DocumentType.AUTOMATION_LOG}${SEPARATOR}${e}${SEPARATOR}${a}${SEPARATOR}${t}`}function getAllLogs(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={docs:!0}){let i=backendCore.context.getProdAppDB();(yield i.exists())||(i=backendCore.context.getDevAppDB());let o={status:a.status},n=(null==a?void 0:a.limit)?a.limit:(null==a?void 0:a.paginate)?GENERIC_PAGE_SIZE+1:void 0;const s=getAutomationLogParams(e,t,o,{include_docs:a.docs,limit:n});return(null==a?void 0:a.page)&&(s.startkey=a.page),pagination(yield i.allDocs(s),{paginate:null==a?void 0:a.paginate,pageSize:GENERIC_PAGE_SIZE})}))}function getLogsByView(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){let i,o=backendCore.context.getProdAppDB();(yield o.exists())||(o=backendCore.context.getDevAppDB());try{const n=getAutomationLogParams(e,t,{automationId:null==a?void 0:a.automationId,status:null==a?void 0:a.status},{include_docs:!0,limit:GENERIC_PAGE_SIZE});(null==a?void 0:a.page)&&(n.startkey=a.page),i=yield o.query(getQueryIndex(ViewName.AUTOMATION_LOGS),n)}catch(i){if(null==i||"not_found"!==i.name&&"not_found"!==i.error)throw i;return yield createLogByAutomationView(),getLogsByView(e,t,a)}return pagination(i)}))}function writeLog(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.context.getProdAppDB(),i=e._id,o=e.name,n=getStatus(t),s=(new Date).toISOString(),r=generateAutomationLogID(s,n,i),u=Object.assign(Object.assign({},t),{automationId:i,status:n,automationName:o,createdAt:s,_id:r});return yield a.put(u),r}))}function updateAppMetadataWithErrors(e){return __awaiter(this,arguments,void 0,(function*(e,{clearing:t}={clearing:!1}){const a=backendCore.context.getProdAppDB();yield backOff((()=>__awaiter(this,void 0,void 0,(function*(){const i=yield a.get(backendCore.db.DocumentType.APP_METADATA);for(let a of e){const e=a.split(backendCore.db.SEPARATOR),o=`${e[e.length-3]}${backendCore.db.SEPARATOR}${e[e.length-2]}`;let n={};i.automationErrors&&(n=i.automationErrors),Array.isArray(n[o])||(n[o]=[]);const s=n[o].indexOf(a);t&&-1!==s?n[o].splice(s,1):n[o].push(a),0===n[o].length&&delete n[o],i.automationErrors=n}yield a.put(i),yield backendCore.cache.app.invalidateAppMetadata(i.appId,i)}))),"Failed to update app metadata with automation log error")}))}function getExpiredLogs(){return __awaiter(this,void 0,void 0,(function*(){const e=yield oldestLogDate$1();try{return yield getAllLogs(EARLIEST_DATE,e,{docs:!1,paginate:!1,limit:EXPIRED_LIMIT})}catch(e){return{data:[],hasNextPage:!1}}}))}function clearOldHistory(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getProdAppDB();try{const t=yield getExpiredLogs();if(!t.data||0===t.data.length)return;const a=t.data.map((e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}))),i=t.data.filter((e=>{const t=e.id.split(backendCore.db.SEPARATOR);return t[t.length-1]===types.AutomationStatus.ERROR})).map((e=>e.id));yield e.bulkDocs(a),i.length&&(yield updateAppMetadataWithErrors(i,{clearing:!0}))}catch(t){backendCore.logging.logAlert(`Failed to cleanup automation log history - Database "${e.name}"`,t)}}))}const oldestLogDate=oldestLogDate$1;function getLogs(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){let o,n=(new Date).toISOString();const s=yield oldestLogDate();return(!e||e<s)&&(e=s),o=a||t?yield getLogsByView(e,n,{automationId:a,status:t,page:i}):yield getAllLogs(e,n,{status:t,page:i,docs:!0,paginate:!0}),o}))}function logSearch(e){return __awaiter(this,void 0,void 0,(function*(){return yield clearOldHistory(),yield getLogs(e.startDate,e.status,e.automationId,e.page)}))}function storeLog(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!backendCore.db.isProdAppID(backendCore.context.getAppId()))return;const a=getStatus(t),i=yield writeLog(e,t);a===types.AutomationStatus.ERROR&&(yield updateAppMetadataWithErrors([i])),yield clearOldHistory()}))}var index$b=Object.freeze({__proto__:null,logSearch:logSearch,oldestLogDate:oldestLogDate,storeLog:storeLog}),index$a=Object.freeze({__proto__:null,logs:index$b});function loadJSFile(e,t){return fs.readFileSync(path.join(e,t),"utf8")}function storePlugin(metadata,directory,source){return __awaiter(this,void 0,void 0,(function*(){const db=backendCore.tenancy.getGlobalDB(),version=metadata.package.version,name=metadata.package.name,description=metadata.package.description,hash=metadata.schema.hash,bucketPath=backendCore.objectStore.getPluginS3Dir(name),files=yield backendCore.objectStore.uploadDirectory(backendCore.objectStore.ObjectStoreBuckets.PLUGINS,directory,bucketPath),jsFile=files.find((e=>e.name.endsWith(".js"))),iconFile=files.find((e=>e.name.endsWith(".svg")));if(!jsFile)throw new Error("Plugin missing .js file.");if(metadata.schema.type===types.PluginType.DATASOURCE){const js=loadJSFile(directory,jsFile.name);try{eval(js)}catch(e){const t=(null==e?void 0:e.message)?e.message:JSON.stringify(e);throw new Error(`JS invalid: ${t}`)}}const iconFileName=iconFile?iconFile.name:null,pluginId=backendCore.db.generatePluginID(name);let rev;try{const e=yield db.get(pluginId);rev=e._rev}catch(e){rev=void 0}let doc=Object.assign(Object.assign({_id:pluginId,_rev:rev},metadata),{name:name,version:version,hash:hash,description:description});iconFileName&&(doc.iconFileName=iconFileName),source&&(doc=Object.assign(Object.assign({},doc),{source:source}));const write=()=>__awaiter(this,void 0,void 0,(function*(){const e=yield db.put(doc);return yield backendCore.events.plugin.imported(doc),Object.assign(Object.assign({},doc),{_rev:e.rev})}));return rev?yield write():yield addPlugin(write)}))}function deletePlugin(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.tenancy.getGlobalDB();try{const a=yield t.get(e),i=backendCore.objectStore.getPluginS3Dir(a.name);yield backendCore.objectStore.deleteFolder(backendCore.objectStore.ObjectStoreBuckets.PLUGINS,i),yield t.remove(e,a._rev),yield backendCore.events.plugin.deleted(a),yield removePlugin()}catch(e){const t=(null==e?void 0:e.message)?null==e?void 0:e.message:e;throw new Error(`Failed to delete plugin: ${t}`)}}))}function checkPluginQuotas(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.tenancy.getGlobalDB();try{const t=(yield e.allDocs(backendCore.db.getPluginParams())).rows.length;console.log(`Syncing plugin count: ${t}`),yield updatePluginCount(t)}catch(e){backendCore.logging.logAlert("Unable to retrieve plugins for quota check",e)}}))}var index$9=Object.freeze({__proto__:null,checkPluginQuotas:checkPluginQuotas,deletePlugin:deletePlugin,storePlugin:storePlugin});function isEncryptionKeyAvailable(){return!!backendCore.env.ENCRYPTION_KEY}function fetch$3(){return __awaiter(this,void 0,void 0,(function*(){const e=yield get$4();return Object.keys(e.variables)}))}function fetchValues(e){return __awaiter(this,void 0,void 0,(function*(){const t=(yield get$4()).variables,a={};for(let[i,o]of Object.entries(t))switch(e){case types.AppEnvironment.DEVELOPMENT:a[i]=o.development;break;case types.AppEnvironment.PRODUCTION:default:a[i]=o.production}return a}))}function changeValues(e){return __awaiter(this,void 0,void 0,(function*(){if(!(yield getCachedLicense()).features.includes(types.Feature.ENVIRONMENT_VARIABLES))throw new Error("User does not have access to environment variables feature.");const t=yield get$4();t.variables=e(t.variables),yield update$5(t)}))}function update$4(e,t){return __awaiter(this,void 0,void 0,(function*(){if(!isValid(e))throw new Error("Variable name has characters that are not allowed");yield changeValues((a=>(a[e]=t,a)))}))}function remove$3(e){return __awaiter(this,void 0,void 0,(function*(){yield changeValues((t=>(delete t[e],t)))}))}function isValid(e){return/^[a-zA-Z0-9-_]+$/.test(e)}var index$8=Object.freeze({__proto__:null,fetch:fetch$3,fetchValues:fetchValues,isEncryptionKeyAvailable:isEncryptionKeyAvailable,isValid:isValid,remove:remove$3,update:update$4});const MemoryStream=require("memorystream"),builder=new backendCore.sql.Sql(types.SqlClient.SQL_LITE);function getAuditLogSqlQuery(e,t,a){const i={endpoint:{datasourceId:backendCore.SQS_DATASOURCE_INTERNAL,entityId:types.AUDIT_LOG_TYPE,operation:types.Operation.READ},paginate:{limit:a,page:t},filters:e,meta:{table:searchTable()},resource:{fields:[]},sort:{timestamp:{direction:types.SortOrder.DESCENDING,type:types.SortType.STRING}}},o=builder._query(i);if(Array.isArray(o))throw new Error("Cannot execute multiple queries for audit log search");return{sql:o.sql,bindings:o.bindings}}function generateAuditLogID(e){return`${backendCore.DocumentType.AUDIT_LOG}${backendCore.SEPARATOR}${e}${backendCore.SEPARATOR}${backendCore.utils.newid()}`}function save$1(e){return __awaiter(this,void 0,void 0,(function*(){e._id||(e._id=generateAuditLogID(e.timestamp)),e.type||(e.type=types.AUDIT_LOG_TYPE);try{const t=backendCore.context.getAuditLogsDB(),a=yield t.put(e);return Object.assign(Object.assign({},e),{_rev:a.rev})}catch(e){backendCore.logging.logAlert("Failed to write audit log",e)}}))}function search$1(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=backendCore.context.getAuditLogDBName();return yield backendCore.db.paginatedSearch(a,types.SearchIndex.AUDIT,e,{disableEscaping:!0,indexer:createAuditLogDesignDocLucene,limit:GENERIC_PAGE_SIZE,bookmark:t,sort:"timestamp",sortOrder:types.SortOrder.DESCENDING,sortType:types.SortType.STRING})}))}function searchSQL(e,t,a){return __awaiter(this,void 0,void 0,(function*(){t||(t=1);const i=backendCore.context.getAuditLogsDB();try{const a=GENERIC_PAGE_SIZE+1,o=getAuditLogSqlQuery(e,t,a),n=searchTable(),s=builder.convertJsonStringColumns(n,yield i.sql(o.sql,o.bindings));let r;s.length>a&&(r=s.pop());const u={rows:s,hasNextPage:!!r};return u.hasNextPage&&(u.bookmark=t+1),u}catch(i){if(404!==i.status||(null==a?void 0:a.isRetry))throw i;return yield migrate(),yield createAuditLogDesignDocSQL(),yield searchSQL(e,t,{isRetry:!0})}}))}function migrate(){return __awaiter(this,void 0,void 0,(function*(){const e=backendCore.context.getAuditLogsDB(),t=(yield e.allDocs(backendCore.db.getDocParams(backendCore.DocumentType.AUDIT_LOG,null,{include_docs:!0}))).rows.map((e=>e.doc)).filter((e=>e&&!e.type)).map((e=>Object.assign(Object.assign({},e),{type:types.AUDIT_LOG_TYPE})));yield e.bulkDocs(t)}))}function dump(e){const t=backendCore.context.getAuditLogsDB(),a=new MemoryStream,i=t.dump(a,{filter:t=>{var a;const i=t;if(!(null===(a=i._id)||void 0===a?void 0:a.startsWith(backendCore.DocumentType.AUDIT_LOG)))return!1;let o=!0;const n=(e,t)=>{e&&0!==e.length&&(o=!!(o&&t&&e.includes(t)))};if(n(e.userIds,i.userId),n(e.appIds,i.appId),n(e.events,i.event),(e.startDate||e.endDate)&&(o=o&&i.timestamp>=e.startDate&&i.timestamp<=e.endDate),e.fullSearch){const a=JSON.stringify(t);o=o&&a.includes(e.fullSearch)}return o}}),o=new MemoryStream;return a.on("data",(e=>{const t=JSON.parse(Buffer.from(e).toString());if(Array.isArray(t.docs)){let e="";for(let a of t.docs)e+=JSON.stringify(a)+"\n";o.write(e)}})),a.on("end",(()=>{o.end()})),{promise:i,stream:o}}const MIN_DATE=backendCore.constants.MIN_VALID_DATE.toISOString(),MAX_DATE=backendCore.constants.MAX_VALID_DATE.toISOString();var ResourceType;function escapeCharacter(e,t){for(let a of t)e=e.replace(new RegExp(a,"g"),`\\${a}`);return e}function fillDates(e){return(e.startDate||e.endDate)&&(e.startDate=e.startDate||MIN_DATE,e.endDate=e.endDate||MAX_DATE),e}function getSearchFilters(e){return __awaiter(this,void 0,void 0,(function*(){Array.isArray(e.appIds)&&(e.appIds=e.appIds.map((e=>backendCore.db.getProdAppID(e)))),!(yield backendCore.features.flags.isEnabled("SQS"))&&Array.isArray(e.events)&&(e.events=e.events.map((e=>escapeCharacter(e,[":"]))));const t={};function a(e,a){(null==a?void 0:a.length)&&(t.oneOf=Object.assign(Object.assign({},t.oneOf),{[e]:a}))}if(a("userId",e.userIds),a("appId",e.appIds),a("event",e.events),e.fullSearch)if(yield backendCore.features.flags.isEnabled("SQS"))t.fuzzyOr=!0,t.fuzzy={name:e.fullSearch,fallback:e.fullSearch};else{const a=escapeCharacter(e.fullSearch,[":"," "]);t.equal={all:`("${a}" OR ${a}*)`}}return(e.startDate||e.endDate)&&(e=fillDates(e),t.range={timestamp:{high:e.endDate,low:e.startDate}}),0===Object.keys(t).length&&(t.notEmpty={event:!0}),t}))}function deleted(e,t,a){const i={_id:e,status:types.AuditLogResourceStatus.DELETED};switch(t){case ResourceType.APP:i.name=null==a?void 0:a.appName;break;case ResourceType.USER:i.email=null==a?void 0:a.email}return i}function removeTemplateStrings(e){const t=stringTemplates.findHBSBlocks(e);for(let a of t){const t=` "${a}"`;e=e.replace(e.includes(t)?t:` ${a}`,""),e=stringTemplates.processStringSync(e,{})}return e}function getEventFriendlyName(e,t){const a=types.AuditedEventFriendlyName[e];if(!a)throw new Error("No friendly name found.");let i=stringTemplates.processStringSync(a,t);return i.includes('""')&&(i=removeTemplateStrings(a)),i}function write(e,t,a){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAuditLogsEnabled())||!backendCore.utils.isAudited(e))return;const i=getEventFriendlyName(e,t);let o=new Date;(null==a?void 0:a.timestamp)&&(o=new Date(a.timestamp));const n={timestamp:o.toISOString(),event:e,name:i,userId:(null==a?void 0:a.userId)||types.AuditLogSystemUser,metadata:Object.assign(Object.assign({},t),null==a?void 0:a.hostInfo)},s={};try{if(null==a?void 0:a.appId){n.appId=backendCore.db.getProdAppID(a.appId);const e=yield backendCore.cache.app.getAppMetadata(a.appId);"name"in e&&(s.appName=e.name)}if(null==a?void 0:a.userId){const e=yield backendCore.users.getById(null==a?void 0:a.userId);s.email=e.email}}catch(e){backendCore.logging.logAlert("Failed to retrieve fallback information for audit log",e)}return n.fallback=s,yield save$1(n)}))}function enrich(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.map((e=>e.userId)),a=e.filter((e=>e.appId)).map((e=>backendCore.db.getDevAppID(e.appId))),i=yield backendCore.users.bulkGetGlobalUsersById([...new Set(t)],{cleanup:!0}),o=yield backendCore.db.getAppsByIDs([...new Set(a)]);let n=[];for(let t of e){const e=i.find((e=>(null==e?void 0:e._id)===t.userId)),a=o.find((e=>backendCore.db.isSameAppID(null==e?void 0:e.appId,t.appId))),s={event:t.event,timestamp:t.timestamp,name:t.name,metadata:t.metadata,user:e||deleted(t.userId,ResourceType.USER,t.fallback)};t.appId&&(s.app=a||deleted(t.appId,ResourceType.APP,t.fallback)),n.push(s)}return n}))}function fetch$2(e){return __awaiter(this,void 0,void 0,(function*(){if(!(yield isAuditLogsEnabled()))throw new Error("Audit logs not available - license required.");const t=yield getSearchFilters(e);if("string"==typeof e.bookmark)throw new Error("String based bookmark not supported.");let a;return a=(yield backendCore.features.flags.isEnabled("SQS"))?yield searchSQL(t,e.bookmark):yield search$1(t,e.bookmark),{hasNextPage:a.hasNextPage,bookmark:a.bookmark,data:yield enrich(a.rows)}}))}function download$1(e){return dump(e=fillDates(e))}function definitions$1(){const e=Object.entries(types.AuditedEventFriendlyName).filter((e=>null!=e[1])),t={};for(let a of e)t[a[0]]=removeTemplateStrings(a[1]);return t}!function(e){e.USER="user",e.APP="app"}(ResourceType||(ResourceType={}));var index$7=Object.freeze({__proto__:null,definitions:definitions$1,download:download$1,fetch:fetch$2,write:write});function removeRoles(e,t){const a=e.request.body;return a.builder&&(a.builder=(null==t?void 0:t.builder)||void 0),a.admin&&(a.admin=(null==t?void 0:t.admin)||void 0),a.roles&&(a.roles=(null==t?void 0:t.roles)||{}),e.request.body=a,e}function roleCheck(e,t){return __awaiter(this,void 0,void 0,(function*(){return(yield isExpandedPublicApiEnabled())||removeRoles(e,t),e}))}var users$2=Object.freeze({__proto__:null,roleCheck:roleCheck});function assign(e,t){return __awaiter(this,void 0,void 0,(function*(){var a;if(!(yield isExpandedPublicApiEnabled()))throw new Error("Unable to assign roles - license required.");const i=yield db.bulkGet(e);for(let e of i){if(t.role&&t.role.roleId){const a=backendCore.db.getProdAppID(t.role.appId);e.roles[a]=t.role.roleId}if(t.appBuilder){const i=backendCore.db.getProdAppID(t.appBuilder.appId),o=(null===(a=e.builder)||void 0===a?void 0:a.apps)||[];e.builder={apps:o.concat([i])}}t.builder&&(e.builder={global:!0}),t.admin&&(e.admin={global:!0}),e.roles}yield db.bulkUpdate(i)}))}function unAssign(e,t){return __awaiter(this,void 0,void 0,(function*(){var a,i;if(!(yield isExpandedPublicApiEnabled()))throw new Error("Unable to un-assign roles - license required.");const o=yield db.bulkGet(e);for(let e of o){if(t.role){const i=backendCore.db.getProdAppID(null===(a=t.role)||void 0===a?void 0:a.appId);e.roles[i]===t.role.roleId&&delete e.roles[i]}if(t.appBuilder&&(null===(i=e.builder)||void 0===i?void 0:i.apps)){const a=backendCore.db.getProdAppID(t.appBuilder.appId);e.builder.apps=e.builder.apps.filter((e=>e!==a))}t.builder&&e.builder&&delete e.builder,t.admin&&e.admin&&delete e.admin}}))}var roles=Object.freeze({__proto__:null,assign:assign,unAssign:unAssign});function buildImportFn(e){return(t,a)=>__awaiter(this,void 0,void 0,(function*(){var i;(yield isExpandedPublicApiEnabled())||t.throw(403,"Endpoint unavailable, license required."),(null===(i=t.request.files)||void 0===i?void 0:i.appExport)||t.throw(400,"Must provide app export file for import."),yield backendCore.context.doInAppContext(t.params.appId,(()=>__awaiter(this,void 0,void 0,(function*(){yield e(t),t.body=void 0,t.status=204,yield a()}))))}))}function buildExportFn(e){return(t,a)=>__awaiter(this,void 0,void 0,(function*(){(yield isExpandedPublicApiEnabled())||t.throw(403,"Endpoint unavailable, license required.");const{encryptPassword:i,excludeRows:o}=t.request.body;yield backendCore.context.doInAppContext(t.params.appId,(()=>__awaiter(this,void 0,void 0,(function*(){t.request.body={encryptPassword:i,excludeRows:o},t.query.appId=t.params.appId,yield e(t),yield a()}))))}))}var applications=Object.freeze({__proto__:null,buildExportFn:buildExportFn,buildImportFn:buildImportFn}),index$6=Object.freeze({__proto__:null,applications:applications,roles:roles,users:users$2});let backupQueue;function init$3(){backupQueue=backendCore.queue.createQueue(backendCore.queue.JobQueue.APP_BACKUP,{maxStalledCount:3,jobOptions:{attempts:3,removeOnFail:!0,removeOnComplete:!0}})}function getBackupQueue(){return backupQueue}function storeAppBackupMetadata(e){return __awaiter(this,arguments,void 0,(function*(e,t={}){return storeAppBackupMetadata$1(e,t)}))}function getTimestamps(e){const t=(new Date).toISOString();switch(e){case types.AppBackupStatus.COMPLETE:case types.AppBackupStatus.FAILED:return{timestamp:t,finishedAt:t};case types.AppBackupStatus.STARTED:return{timestamp:t,startedAt:t};case types.AppBackupStatus.PENDING:return{timestamp:t,createdAt:t}}}function updateBackupStatus(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const o=yield getAppBackup(e);return yield storeAppBackupMetadata$1(Object.assign(Object.assign(Object.assign({},o),getTimestamps(t)),{contents:a,status:t,type:types.AppBackupType.BACKUP}),{filename:i,docId:e})}))}function updateRestoreStatus(e,t,a){return __awaiter(this,void 0,void 0,(function*(){const i=yield getAppBackup(e);return yield storeAppBackupMetadata$1(Object.assign(Object.assign(Object.assign({},i),getTimestamps(a)),{status:a,type:types.AppBackupType.RESTORE,trigger:types.AppBackupTrigger.MANUAL}),{docId:e,docRev:t})}))}function getAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){return getAppBackupMetadata(e)}))}function updateAppBackup(e,t){return __awaiter(this,void 0,void 0,(function*(){return updateAppBackupMetadata(e,t)}))}function deleteAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getAppBackupMetadata(e);return t.filename&&(yield backendCore.objectStore.deleteFile(backendCore.objectStore.ObjectStoreBuckets.BACKUPS,t.filename)),deleteAppBackupMetadata(e)}))}function fetchAppBackups(e,t){return __awaiter(this,void 0,void 0,(function*(){return fetchAppBackups$1(e,t)}))}function getBackupDownloadStream(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield getAppBackupMetadata(e);if(!t.filename)throw new Error("Backup incomplete - cannot download.");return{metadata:t,stream:yield backendCore.objectStore.getReadStream(backendCore.objectStore.ObjectStoreBuckets.BACKUPS,t.filename)}}))}function downloadAppBackup(e){return __awaiter(this,void 0,void 0,(function*(){const{stream:t}=yield getBackupDownloadStream(e),a=path.join(backendCore.objectStore.budibaseTempDir(),backendCore.utils.newid()),i=fs.createWriteStream(a);return new Promise(((e,o)=>{t.on("error",o),i.on("error",o),t.pipe(i).on("close",(()=>e(a)))}))}))}function triggerAppBackup(e,t){return __awaiter(this,arguments,void 0,(function*(e,t,a={}){let i;try{i=yield storeAppBackupMetadata(Object.assign({appId:e,trigger:t,timestamp:(new Date).toISOString(),status:types.AppBackupStatus.PENDING,type:types.AppBackupType.BACKUP},a))}catch(e){if(409===e.status)return;throw e}return yield getBackupQueue().add({docId:i.id,docRev:i.rev,appId:e,export:Object.assign({trigger:t},a)}),yield backendCore.events.backup.appBackupTriggered(e,i.id,types.AppBackupType.BACKUP,t,null==a?void 0:a.name),i.id}))}function triggerAppRestore(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const o=yield getAppBackup(t);let n;try{n=yield storeAppBackupMetadata({appId:e,timestamp:(new Date).toISOString(),status:types.AppBackupStatus.PENDING,type:types.AppBackupType.RESTORE,createdBy:i})}catch(e){if(409===(null==e?void 0:e.status))return;throw e}return yield getBackupQueue().add({appId:e,docId:n.id,docRev:n.rev,import:{nameForBackup:a,backupId:t,createdBy:i}}),{restoreId:n.id,metadata:o}}))}const pkg={isEnabled:isBackupsEnabled,triggerAppRestore:checkBackups(triggerAppRestore),triggerAppBackup:checkBackups(triggerAppBackup),getBackupDownloadStream:checkBackups(getBackupDownloadStream),downloadAppBackup:checkBackups(downloadAppBackup),fetchAppBackups:checkBackups(fetchAppBackups),storeAppBackupMetadata:checkBackups(storeAppBackupMetadata),updateBackupStatus:checkBackups(updateBackupStatus),updateRestoreStatus:checkBackups(updateRestoreStatus),getAppBackup:checkBackups(getAppBackup),updateAppBackup:checkBackups(updateAppBackup),deleteAppBackup:checkBackups(deleteAppBackup)};function init$2(e){return __awaiter(this,void 0,void 0,(function*(){yield getBackupQueue().process((t=>__awaiter(this,void 0,void 0,(function*(){const a=t.data;try{if(a.export)return exportProcessor(t,e);if(a.import)return importProcessor(t,e)}catch(e){backendCore.logging.logAlert(`Failed to perform backup for app ID: ${a.appId}`,e)}}))))}))}function removeExistingApp(e){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.db.getDB(e,{skip_setup:!0});yield t.destroy()}))}function runBackup(e,t,a,i){return __awaiter(this,void 0,void 0,(function*(){const t=backendCore.db.getDevAppID(a),o=backendCore.db.getProdAppID(a),n=(new Date).toISOString(),s=(t,a)=>__awaiter(this,void 0,void 0,(function*(){(null==i?void 0:i.doc)?yield pkg.updateBackupStatus(i.doc.id,t,null==a?void 0:a.contents,null==a?void 0:a.filename):yield pkg.storeAppBackupMetadata({appId:o,timestamp:n,trigger:e,status:t,name:null==i?void 0:i.name,type:types.AppBackupType.BACKUP,contents:null==a?void 0:a.contents,createdBy:null==i?void 0:i.createdBy},{filename:null==a?void 0:a.filename})}));try{const a=yield i.processing.exportAppFn(t,{tar:!0}),r=yield i.processing.statsFn(t);let u=`${o}/backup-${n}.tar.gz`;const d=backendCore.objectStore.ObjectStoreBuckets.BACKUPS,c=fs.createReadStream(a);yield backendCore.objectStore.streamUpload({bucket:d,filename:u,stream:c,extra:{type:"application/gzip",metadata:{name:null==i?void 0:i.name,trigger:e,timestamp:n,appId:o}}}),yield s(types.AppBackupStatus.COMPLETE,{filename:u,contents:r}),fs.existsSync(a)&&fs.rmSync(a)}catch(e){backendCore.logging.logAlert("App backup error",e),yield s(types.AppBackupStatus.FAILED)}}))}function importProcessor(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=e.data,i=a.appId,o=a.import.backupId,n=a.import.nameForBackup,s=a.import.createdBy,r=backendCore.tenancy.getTenantIDFromAppID(i);return backendCore.tenancy.doInTenant(r,(()=>__awaiter(this,void 0,void 0,(function*(){const e=backendCore.db.getDevAppID(i),{rev:u}=yield pkg.updateRestoreStatus(a.docId,a.docRev,types.AppBackupStatus.STARTED);yield runBackup(types.AppBackupTrigger.RESTORING,r,i,{processing:t,createdBy:s,name:n});const d=yield pkg.downloadAppBackup(o);yield removeExistingApp(e);let c=types.AppBackupStatus.COMPLETE;try{yield t.importAppFn(e,backendCore.db.getDB(e),{file:{type:"application/gzip",path:d},key:d})}catch(e){backendCore.logging.logAlert("App restore error",e),c=types.AppBackupStatus.FAILED}yield pkg.updateRestoreStatus(a.docId,u,c),fs.existsSync(d)&&fs.rmSync(d,{force:!0})}))))}))}function exportProcessor(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=e.data,i=a.appId,o=a.export.trigger,n=a.export.name,s=backendCore.tenancy.getTenantIDFromAppID(i);yield backendCore.tenancy.doInTenant(s,(()=>__awaiter(this,void 0,void 0,(function*(){try{const{rev:e}=yield pkg.updateBackupStatus(a.docId,types.AppBackupStatus.STARTED);return runBackup(o,s,i,{processing:t,doc:{id:a.docId,rev:e},name:n})}catch(e){backendCore.logging.logAlert("App backup error",e)}}))))}))}var processing=Object.freeze({__proto__:null,init:init$2});const init$1=e=>__awaiter(void 0,void 0,void 0,(function*(){init$3(),yield init$2(e.processing)}));var backups=Object.assign(Object.assign({},pkg),{processing:processing,init:init$1,getBackupQueue:getBackupQueue});const init=e=>__awaiter(void 0,void 0,void 0,(function*(){e.backups&&(yield backups.init(e.backups))}));function get$2(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;const i=backendCore.tenancy.getGlobalDB(),o=new backendCore.db.QueryBuilder(i.name,types.SearchIndex.USER);o.setIndexBuilder(backendCore.db.searchIndexes.createUserIndex),o.setLimit(e.pageSize),o.addEqual("scimInfo.isSync",!0);for(const[i,n]of Object.entries(null!==(a=null===(t=e.filters)||void 0===t?void 0:t.equal)&&void 0!==a?a:{}))o.addEqual(i,n);o.setSort("_id"),o.setSkip(e.skip);const n=yield o.run();return{users:n.rows,total:n.totalRows}}))}function find$3(e){return __awaiter(this,void 0,void 0,(function*(){return yield backendCore.users.getById(e)}))}function create$4(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=yield db.getUserByEmail(e.email);if(a){if(null===(t=a.scimInfo)||void 0===t?void 0:t.isSync)throw new backendCore.HTTPError("User is already synched",409);e=Object.assign(Object.assign({},a),{scimInfo:lodashMerge(a.scimInfo,e.scimInfo),password:void 0,firstName:e.firstName,lastName:e.lastName,updatedAt:e.updatedAt})}return yield db.save(e,{requirePassword:!1})}))}function update$3(e,t){return __awaiter(this,void 0,void 0,(function*(){return yield db.save(e,{requirePassword:!1,allowChangingEmail:null==t?void 0:t.allowChangingEmail})}))}function remove$2(e){return __awaiter(this,void 0,void 0,(function*(){return yield db.destroy(e)}))}var users$1=Object.freeze({__proto__:null,create:create$4,find:find$3,get:get$2,remove:remove$2,update:update$3});function create$3(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=yield getByName(e.name);let i;if(a){if(null===(t=a.scimInfo)||void 0===t?void 0:t.isSync)throw new backendCore.HTTPError("Group is already synched",409);i=a._id,a.users&&(yield removeUsers(i,a.users.map((e=>e._id))),delete a.users),a.scimInfo=lodashMerge(a.scimInfo,e.scimInfo),yield save$2(a)}else{i=(yield save$2(e)).id}return yield get$3(i)}))}var groups$1=Object.freeze({__proto__:null,create:create$3});const{DocWritethrough:DocWritethrough}=backendCore.cache.docWritethrough;function getLogDocId(){return`${backendCore.db.DocumentType.SCIM_LOG}${backendCore.db.SEPARATOR}${dayjs().format("YYYYMMDD")}`}const getDB=()=>__awaiter(void 0,void 0,void 0,(function*(){const e=backendCore.context.getScimDBName();return new DocWritethrough(backendCore.db.getDB(e),getLogDocId())}));function logRequest(e){return __awaiter(this,void 0,void 0,(function*(){const t=Date.now().toString(),a=yield getDB();return yield a.patch({[`${t}_request`]:Object.assign({ts:(new Date).toISOString()},e)}),t}))}function logResponse(e,t){return __awaiter(this,void 0,void 0,(function*(){const a=yield getDB();yield a.patch({[`${e}_response`]:Object.assign({ts:(new Date).toISOString()},t)})}))}var logger=Object.freeze({__proto__:null,logRequest:logRequest,logResponse:logResponse}),index$5=Object.freeze({__proto__:null,ai:index$d,auditLogs:index$7,automations:index$a,backups:backups,branding:index$e,environmentVariables:index$8,features:features,groups:groups$2,init:init,licensing:index$f,logger:logger,plugins:index$9,publicApi:index$6,quotas:quotas,scimGroups:groups$1,scimUsers:users$1,users:index$c,utils:index$i});const licensing=(e={checkUsersLimit:!0})=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){if((e.licensingCheck?e.licensingCheck:()=>!!t.user)(t)){if(backendCore.env.SELF_HOSTED&&backendCore.env.DEFAULT_LICENSE)return t.user.license=SELF_FREE_LICENSE,a();t.user.license=yield getCachedLicense(t,{populateLicense:e.populateLicense,populateFreeLicense:e.populateFreeLicense}),e.checkUsersLimit&&(backendCore.utils.isServingApp(t)||backendCore.utils.isServingBuilder(t)||backendCore.utils.isServingBuilderPreview(t)||backendCore.utils.isPublicApiRequest(t))&&(yield usageLimitIsExceeded(types.StaticQuotaName.USERS,types.QuotaUsageType.STATIC))}return a()})),requireFeature=e=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkFeature(e),yield a()})),requireFeatures=(...e)=>(t,a)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkFeatures(e),yield a()}));var feature=Object.freeze({__proto__:null,requireFeature:requireFeature,requireFeatures:requireFeatures});const doInScimContext=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){let a;return backendCore.env.DISABLE_SCIM_CALLS||(a=yield logRequest(Object.assign(Object.assign({},e.request.toJSON()),{body:e.request.body}))),yield backendCore.context.doInScimContext((()=>__awaiter(void 0,void 0,void 0,(function*(){const i=yield t();return a&&(yield logResponse(a,Object.assign(Object.assign({},e.response.toJSON()),{body:e.response.body}))),i}))))})),requireSCIM=(e,t)=>__awaiter(void 0,void 0,void 0,(function*(){yield checkSCIM(),yield t()})),scimUserOnly=e=>scimSyncChecks(backendCore.users.getById,e,!0),scimGroupOnly=e=>scimSyncChecks(get$5,e,!0),internalGroupOnly=e=>scimSyncChecks(get$5,e,!1);function scimSyncChecks(e,t,a){return(i,o)=>__awaiter(this,void 0,void 0,(function*(){var n;const s=i.params[t];"string"!=typeof s&&i.throw(404);return!!(null===(n=(yield e(s)).scimInfo)||void 0===n?void 0:n.isSync)!==a&&i.throw(404),o()}))}var index$4=Object.freeze({__proto__:null,doInScimContext:doInScimContext,feature:feature,internalGroupOnly:internalGroupOnly,licensing:licensing,requireSCIM:requireSCIM,scimGroupOnly:scimGroupOnly,scimUserOnly:scimUserOnly});function summarizeText(e){return`Summarize this text:\n${e}`}function generateCronExpression$1(e){return`Generate a node-cron compatible expression based on the following prompt. Return only the cron expression (without backticks), and if not possible return only 'Error generating cron' with a short explanation:\n${e}`}class OpenAI{constructor({model:e,apiKey:t,measureUsage:a}){this.model=e,this.client=new OpenAIClient({apiKey:t}),this.measureUsage=a}measureTokenUsage(e){let t=0;if(this.measureUsage&&e){const{prompt_tokens:a,completion_tokens:i}=e;t=3*i+a}return t}chatCompletion(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;try{const i=yield this.client.chat.completions.create({model:this.model,messages:[{role:"user",content:e}],max_tokens:parseInt(process.env.BUDIBASE_AI_MAX_PROMPT_TOKENS||"300")}),o=this.measureTokenUsage(i.usage);return{message:null===(a=null===(t=null==i?void 0:i.choices[0])||void 0===t?void 0:t.message)||void 0===a?void 0:a.content,tokensUsed:o}}catch(e){throw e instanceof OpenAIClient.APIError&&console.error(`OpenAI Prompt failed with error of type ${e.type} and status: ${e.status}:${e.code} - ${e.message}`),e}}))}prompt(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(e)}))}summarizeText(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(summarizeText(e))}))}}class Anthropic{constructor({model:e,apiKey:t}){this.model=e,this.client=new AnthropicClient({apiKey:t})}chatCompletion(e){return __awaiter(this,void 0,void 0,(function*(){try{const t=yield this.client.messages.create({model:this.model,messages:[{role:"user",content:e}],max_tokens:parseInt(process.env.BUDIBASE_AI_MAX_PROMPT_TOKENS||"300")});return{message:(null==t?void 0:t.content[0]).text}}catch(e){throw e instanceof AnthropicClient.APIError&&console.error(`Anthropic Prompt failed with error ${e.name} and status: ${e.status}`),e}}))}prompt(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(e)}))}summarizeText(e){return __awaiter(this,void 0,void 0,(function*(){return this.chatCompletion(summarizeText(e))}))}}const ProviderMap={OpenAI:OpenAI,Anthropic:Anthropic,TogetherAI:OpenAI,AzureOpenAI:OpenAI,Custom:OpenAI};class LargeLanguageModel{static forCurrentTenant(e){return __awaiter(this,void 0,void 0,(function*(){const t=new LargeLanguageModel(e);return yield t.init(),t}))}constructor(e){this.model=e}determineDefault(e){for(const t in e)if(e[t].isDefault)return e[t]}init(){return __awaiter(this,void 0,void 0,(function*(){var e,t;const a=yield backendCore.configs.getAIConfig();if(!a)throw Error("AI config must be defined to use Budibase AI LLM features");const i=yield enrichAIConfig(a),o=this.determineDefault(i.config);if(!o)throw Error("Error: No config selected as default AI config");const n={model:o.defaultModel||this.model,apiKey:o.apiKey,measureUsage:(null===(t=null===(e=null==a?void 0:a.config)||void 0===e?void 0:e.budibase_ai)||void 0===t?void 0:t.apiKey)===o.apiKey},s=new(0,ProviderMap[o.provider])(n);if(!s)throw Error("LLM Initialisation failed. No model configured.");this.llm=s}))}run(e){return __awaiter(this,void 0,void 0,(function*(){if(!this.llm)throw Error("No model configuration selected. You must instantiate an LLM before prompting.");const t=yield this.llm.prompt(e);return yield setBudibaseAICredits(t.tokensUsed||0),t.message}))}}var index$3=Object.freeze({__proto__:null,LargeLanguageModel:LargeLanguageModel});function generateCronExpression(e){return __awaiter(this,void 0,void 0,(function*(){const{prompt:t}=e.request.body,a=yield LargeLanguageModel.forCurrentTenant("gpt-4o-mini"),i=yield a.run(generateCronExpression$1(t));(null==i?void 0:i.startsWith("Error generating cron:"))?e.throw(400,i):e.body={message:i}}))}const router$6=new Router;function save(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body;if(t.name=t.name.trim(),delete t.roles,t._id){const e=yield get$3(t._id);t.roles=e.roles,t.scimInfo=e.scimInfo}const a=yield save$2(t);e.body={_id:a.id,_rev:a.rev}}))}function updateGroupUsers(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.groupId,a=e.request.body.add,i=e.request.body.remove;let o,n;(a&&!Array.isArray(a)||i&&!Array.isArray(i))&&e.throw(400,"Must supply a list of users to add or to remove"),a&&(o=yield addUsers(t,a)),i&&(n=yield removeUsers(t,i)),e.body={added:o,removed:n}}))}function updateGroupApps(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.groupId,a=e.request.body.add,i=e.request.body.remove;(a&&!Array.isArray(a)||i&&!Array.isArray(i))&&e.throw(400,"Must supply a list of objects, with appId and roleId to add or remove"),e.body=yield updateGroupApps$1(t,{appsToAdd:a,appsToRemove:i})}))}function fetch$1(e){return __awaiter(this,void 0,void 0,(function*(){e.body={data:yield fetch$4()}}))}function destroy$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,rev:a}=e.params;try{yield remove$4(t,a),e.body={message:"Group deleted successfully"}}catch(t){e.throw(t.status,t)}}))}function find$2(e){return __awaiter(this,void 0,void 0,(function*(){try{e.body=yield get$3(e.params.groupId)}catch(t){e.throw(t.status,t)}}))}function searchUsers(e){return __awaiter(this,void 0,void 0,(function*(){var t,a;const{pageSize:i=10,bookmark:o,emailSearch:n}=e.request.query,s=e.params.groupId,r={limit:i+1},u=yield getGroupUsers(s,Object.assign(Object.assign({},r),{emailSearch:n,bookmark:o})),d=n?null===(t=u[i])||void 0===t?void 0:t.email:null===(a=u[i])||void 0===a?void 0:a._id,c=!!d;e.body={users:u.slice(0,i),bookmark:d,hasNextPage:c}}))}function addAppBuilder$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,appId:a}=e.params;yield addAppBuilder$3(t,a),e.body={message:"Group app builder access updated."}}))}function removeAppBuilder$1(e){return __awaiter(this,void 0,void 0,(function*(){const{groupId:t,appId:a}=e.params;yield removeAppBuilder$3(t,a),e.body={message:"group app builder access removed."}}))}router$6.post("/api/ai/cron",requireFeature(types.Feature.BUDIBASE_AI),backendCore.auth.builderOrAdmin,generateCronExpression);const router$5=new Router;function buildGroupSaveValidation(){return backendCore.auth.joiValidator.body(Joi.object({_id:Joi.string().optional(),_rev:Joi.string().optional(),color:Joi.string().required(),icon:Joi.string().required(),name:Joi.string().trim().required().max(50),role:Joi.string().optional(),users:Joi.array().optional(),apps:Joi.array().optional(),roles:Joi.object().optional(),createdAt:Joi.string().optional(),updatedAt:Joi.string().optional()}).required())}function status(e){return __awaiter(this,void 0,void 0,(function*(){e.body={encryptionKeyAvailable:isEncryptionKeyAvailable()}}))}function fetch(e){return __awaiter(this,void 0,void 0,(function*(){e.body={variables:yield fetch$3()}}))}function create$2(e){return __awaiter(this,void 0,void 0,(function*(){const{name:t,production:a,development:i}=e.request.body;yield update$4(t,{production:a,development:i});const o=[types.AppEnvironment.PRODUCTION];a!==i&&o.push(types.AppEnvironment.DEVELOPMENT),yield backendCore.events.environmentVariable.created(t,o),e.status=200}))}function update$2(e){return __awaiter(this,void 0,void 0,(function*(){const{production:t,development:a}=e.request.body,i=e.params.varName;yield update$4(i,{production:t,development:a}),e.status=200}))}function destroy(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.varName;yield remove$3(t),yield backendCore.events.environmentVariable.deleted(t),e.status=200}))}router$5.post("/api/global/groups",backendCore.auth.adminOnly,requireFeature(types.Feature.USER_GROUPS),buildGroupSaveValidation(),save).get("/api/global/groups",requireFeature(types.Feature.USER_GROUPS),fetch$1).delete("/api/global/groups/:groupId/:rev",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.adminOnly,internalGroupOnly("groupId"),destroy$1).get("/api/global/groups/:groupId",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.adminOnly,find$2).get("/api/global/groups/:groupId/users",requireFeature(types.Feature.USER_GROUPS),backendCore.auth.builderOrAdmin,searchUsers).post("/api/global/groups/:groupId/users",backendCore.auth.adminOnly,requireFeature(types.Feature.USER_GROUPS),internalGroupOnly("groupId"),updateGroupUsers).post("/api/global/groups/:groupId/apps",backendCore.auth.builderOrAdmin,requireFeature(types.Feature.USER_GROUPS),updateGroupApps).post("/api/global/groups/:groupId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.USER_GROUPS,types.Feature.APP_BUILDERS),addAppBuilder$1).delete("/api/global/groups/:groupId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.USER_GROUPS,types.Feature.APP_BUILDERS),removeAppBuilder$1);const router$4=new Router;function buildEnvVarUpdateValidator(){return backendCore.auth.joiValidator.body(Joi.object({name:Joi.string().optional(),production:Joi.string().required(),development:Joi.string().required()}))}function search(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body,a=yield fetch$2(t);yield backendCore.events.auditLog.filtered(t),e.body=a}))}function download(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.request.body,{stream:a}=download$1(t);yield backendCore.events.auditLog.downloaded(t),e.attachment(`audit-logs-${Date.now()}.log`),e.body=a}))}function definitions(e){return __awaiter(this,void 0,void 0,(function*(){e.body={events:definitions$1()}}))}function buildAuditLogSearchValidator(){return backendCore.auth.joiValidator.body(Joi.object({userIds:Joi.array().items(Joi.string()).optional(),appIds:Joi.array().items(Joi.string()).optional(),events:Joi.array().items(Joi.string().valid(...Object.values(types.Event))).optional(),startDate:Joi.string().optional().allow(""),endDate:Joi.string().optional().allow(""),fullSearch:Joi.string().optional().allow(""),bookmark:Joi.number()}))}router$4.get("/api/env/variables/status",backendCore.auth.builderOrAdmin,status).get("/api/env/variables",backendCore.auth.builderOrAdmin,fetch).post("/api/env/variables",backendCore.auth.builderOrAdmin,buildEnvVarUpdateValidator(),create$2).patch("/api/env/variables/:varName",backendCore.auth.builderOrAdmin,buildEnvVarUpdateValidator(),update$2).delete("/api/env/variables/:varName",backendCore.auth.builderOrAdmin,destroy);const router$3=new Router;function checkAppID(e,t){return __awaiter(this,void 0,void 0,(function*(){(yield appExists(t))||e.throw(400,`Provided app ID: ${t} - is invalid.`)}))}function manualBackup(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=e.params.appId;yield checkAppID(e,a);const i=e.request.body,o=null===(t=e.user)||void 0===t?void 0:t._id,n=yield backups.triggerAppBackup(a,types.AppBackupTrigger.MANUAL,{name:i.name,createdBy:o});n||e.throw(500,"Unable to start backup."),e.body={backupId:n,message:"Backup triggered - process starting."}}))}function importBackup(e){return __awaiter(this,void 0,void 0,(function*(){var t;const a=e.params.appId;yield checkAppID(e,a);const i=e.params.backupId,o=e.request.body.name,n=yield backups.triggerAppRestore(a,i,o,null===(t=e.user)||void 0===t?void 0:t._id);n||e.throw(500,"Unable to start restore."),yield backendCore.events.backup.appBackupRestored(n.metadata),e.body={restoredId:null==n?void 0:n.restoreId,message:"Restore triggered - process starting."}}))}function deleteBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId;yield backups.deleteAppBackup(a),e.body={message:"Backup deleted successfully."}}))}function fetchBackups(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.request.body;(null==a?void 0:a.trigger)&&(a.trigger=a.trigger.toLowerCase(),Object.values(types.AppBackupTrigger).includes(a.trigger)||e.throw(400,"Provided trigger is not a valid option.")),e.body=yield backups.fetchAppBackups(t,Object.assign({paginate:!0},a))}))}function updateBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId,i=e.request.body;e.body=yield backups.updateAppBackup(a,i.name)}))}function downloadBackup(e){return __awaiter(this,void 0,void 0,(function*(){const t=e.params.appId;yield checkAppID(e,t);const a=e.params.backupId,{metadata:i,stream:o}=yield backups.getBackupDownloadStream(a);e.attachment(`backup-${i.timestamp}.tar.gz`),e.body=o}))}router$3.post("/api/global/auditlogs/search",backendCore.auth.adminOnly,buildAuditLogSearchValidator(),search).get("/api/global/auditlogs/download",backendCore.auth.adminOnly,backendCore.middleware.querystringToBody,buildAuditLogSearchValidator(),download).get("/api/global/auditlogs/definitions",backendCore.auth.adminOnly,definitions);const router$2=new Router;function validateBackupSearch(){return backendCore.auth.joiValidator.body(Joi.object({trigger:Joi.string().valid(...Object.values(types.AppBackupTrigger)),type:Joi.string().valid(...Object.values(types.AppBackupType)),startDate:Joi.date(),endDate:Joi.date(),page:Joi.string()}))}function tryGetQueryAsNumber(e,t){const a=e.request.query[t];if(void 0!==a)return+a}router$2.post("/api/apps/:appId/backups",backendCore.auth.builderOrAdmin,manualBackup).post("/api/apps/:appId/backups/search",backendCore.auth.builderOrAdmin,validateBackupSearch(),fetchBackups).get("/api/apps/:appId/backups/:backupId/file",backendCore.auth.builderOrAdmin,downloadBackup).patch("/api/apps/:appId/backups/:backupId",backendCore.auth.builderOrAdmin,updateBackup).delete("/api/apps/:appId/backups/:backupId",backendCore.auth.builderOrAdmin,deleteBackup).post("/api/apps/:appId/backups/:backupId/import",backendCore.auth.builderOrAdmin,importBackup);const get$1=e=>__awaiter(void 0,void 0,void 0,(function*(){var t;const a=null!==(t=tryGetQueryAsNumber(e,"pageSize"))&&void 0!==t?t:20,i=tryGetQueryAsNumber(e,"startIndex");let o;e.request.query.filter&&(o=userFilters(e.request.query.filter));const n=yield get$2({pageSize:a,skip:i,filters:o});e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:n.total,Resources:n.users.map(toScimUserResponse),startIndex:(i||0)+1,itemsPerPage:a}})),find$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404);const a=yield find$3(t);e.body=toScimUserResponse(a)})),create$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=fromScimUser(e.request.body);try{const a=yield create$4(t);e.body=toScimUserResponse(a)}catch(t){throw t instanceof backendCore.EmailUnavailableError&&e.throw(409,"Email already in use"),t}}));function isDeactivation(e){var t,a;const i=e.Operations.find((e=>("Replace"===e.op||"replace"===e.op)&&"active"===e.path));return!!i&&(!1===i.value||"false"===(null===(a=null===(t=i.value)||void 0===t?void 0:t.toLowerCase)||void 0===a?void 0:a.call(t)))}const update$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=yield find$3(e.params.id);t||e.throw(404);const a=toScimUserResponse(t),i=e.request.body;try{scimPatch.patchBodyValidation(i)}catch(e){}if(isDeactivation(i))return remove$1(e);let o;try{o=scimPatch.scimPatch(a,i.Operations)}catch(e){}o||e.throw(500);const n=fromScimUser(o);yield update$3(n,{allowChangingEmail:!0}),e.body=toScimUserResponse(n)})),remove$1=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404),yield remove$2(t),e.status=204}));function cleanResponse(e,t){for(const a of t.split(","))delete e[a]}const get=e=>__awaiter(void 0,void 0,void 0,(function*(){let t=(yield fetch$4()).filter((e=>{var t;return null===(t=e.scimInfo)||void 0===t?void 0:t.isSync})).map(toScimGroupResponse);const{filter:a,excludedAttributes:i}=e.request.query;if(a){const e=scim2ParseFilter.filter(scim2ParseFilter.parse(a));t=t.filter(e)}i&&t.forEach((e=>{cleanResponse(e,i)})),e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:t.length,Resources:t,startIndex:1,itemsPerPage:t.length}})),create=e=>__awaiter(void 0,void 0,void 0,(function*(){const t=fromScimGroup(e.request.body),a=yield create$3(t);e.body=toScimGroupResponse(a)})),find=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t),i=toScimGroupResponse(a),{excludedAttributes:o}=e.request.query;o&&cleanResponse(i,o),e.body=i})),remove=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t);yield remove$4(t,a._rev),e.status=204})),update=e=>__awaiter(void 0,void 0,void 0,(function*(){const{id:t}=e.params,a=yield get$3(t),i=toScimGroupResponse(a),o=e.request.body;try{scimPatch.patchBodyValidation(o)}catch(t){e.throw(400)}const{true:n,false:s}=groupBy(o.Operations,(e=>"members"===e.path));if(null==s?void 0:s.length){const t=scimPatch.scimPatch(i,s);t||e.throw(500);const o=Object.assign(Object.assign({},fromScimGroup(t)),{_rev:a._rev});yield save$2(o)}if(null==n?void 0:n.length){const e=[],a=[];for(const{op:t,value:i}of n)switch(t){case"add":case"Add":for(const t of i)e.push(yield find$3(t.value));break;case"remove":case"Remove":for(const e of i)a.push(yield find$3(e.value));break;case"replace":case"Replace":throw new Error("Replacing members is not allowed");default:sharedCore.utils.unreachable(t)}e.length&&(yield addUsers(t,e.map((e=>e._id)))),a.length&&(yield removeUsers(t,a.map((e=>e._id))))}e.body=toScimGroupResponse(yield get$3(t))})),router$1=new Router({prefix:"/api/global/scim/v2"});function addAppBuilder(e){return __awaiter(this,void 0,void 0,(function*(){const{userId:t,appId:a}=e.params,i=yield db.getUser(t);backendCore.users.isGlobalBuilder(i)?e.body={message:"User already admin - no permissions updated."}:(yield addAppBuilder$2(i,a),e.body={message:`User "${i.email}" app builder access updated.`})}))}function removeAppBuilder(e){return __awaiter(this,void 0,void 0,(function*(){const{userId:t,appId:a}=e.params,i=yield db.getUser(t);backendCore.users.isGlobalBuilder(i)?e.body={message:"User already admin - no permissions removed."}:(yield removeAppBuilder$2(i,a),e.body={message:`User "${i.email}" app builder access removed.`})}))}router$1.use(requireSCIM),router$1.use(doInScimContext),router$1.get("/users",get$1),router$1.get("/users/:id",scimUserOnly("id"),find$1),router$1.post("/users",create$1),router$1.patch("/users/:id",scimUserOnly("id"),update$1),router$1.delete("/users/:id",scimUserOnly("id"),remove$1),router$1.get("/groups",get),router$1.post("/groups",requireFeature(types.Feature.USER_GROUPS),create),router$1.get("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),find),router$1.delete("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),remove),router$1.patch("/groups/:id",requireFeature(types.Feature.USER_GROUPS),scimGroupOnly("id"),update);const router=new Router;router.post("/api/global/users/:userId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.APP_BUILDERS),addAppBuilder).delete("/api/global/users/:userId/app/:appId/builder",backendCore.auth.builderOrAdmin,requireFeatures(types.Feature.APP_BUILDERS),removeAppBuilder);var index$2=Object.freeze({__proto__:null,ai:router$6,appBackups:router$2,auditLogs:router$3,environmentVariables:router$4,groups:router$5,scim:router$1,users:router});const{unreachable:unreachable}=sharedCore.utils,toScimUserResponse=e=>{const t=__rest(e.scimInfo||{},["isSync","roles"]),a=Object.assign(Object.assign({},t),{schemas:["urn:ietf:params:scim:schemas:core:2.0:User"],id:e._id,meta:{resourceType:"User",created:new Date(e.createdAt),lastModified:new Date(e.updatedAt)},active:e.status===types.UserStatus.ACTIVE});return(e.firstName||e.lastName)&&(a.name={formatted:[e.firstName,e.lastName].filter((e=>e)).join(" "),familyName:e.lastName,givenName:e.firstName}),a},isScimUserResponse=e=>!!(null==e?void 0:e.id);function tryGetEmail(e){var t,a;return backendCore.utils.validEmail(e.userName)?e.userName:e.emails?(null===(t=e.emails.find((e=>e.primary)))||void 0===t?void 0:t.value)||(null===(a=e.emails[0])||void 0===a?void 0:a.value):void 0}const fromScimUser=e=>{var t,a,i;const o=isScimUserResponse(e)?e:void 0,n=tryGetEmail(e);if(!n)throw new Error("Email is required");let s,r,u;switch(e.active){case"True":case"true":case!0:s=!0;break;case"False":case"false":case!1:s=!1;break;default:unreachable(e.active)}(null===(t=e.name)||void 0===t?void 0:t.givenName)?(r=null===(a=e.name)||void 0===a?void 0:a.givenName,u=null===(i=e.name)||void 0===i?void 0:i.familyName):r=e.displayName;return{tenantId:"",_id:null==o?void 0:o.id,userId:null==o?void 0:o.id,email:n,firstName:r,lastName:u,scimInfo:Object.assign(Object.assign({},e),{isSync:!0}),roles:{},status:s?types.UserStatus.ACTIVE:types.UserStatus.INACTIVE,createdAt:null==o?void 0:o.meta.created.getTime(),updatedAt:null==o?void 0:o.meta.lastModified.toISOString()}},userFilters=e=>{const t={equal:{}};return function e(a){switch(a.op){case"eq":{const e=a.attrPath;let i;if("emails.value"===e)i="email";else i=`scimInfo.${e}`;t.equal[i]=a.compValue;break}case"and":for(const t of a.filters)e(t);break;default:console.warn("Filter not handled",{filter:a})}}(scim2ParseFilter.parse(e)),t};var users=Object.freeze({__proto__:null,fromScimUser:fromScimUser,toScimUserResponse:toScimUserResponse,userFilters:userFilters});const toScimGroupResponse=e=>{var t;return{schemas:["urn:ietf:params:scim:schemas:core:2.0:Group"],id:e._id,externalId:e.scimInfo.externalId,meta:{resourceType:"Group",created:new Date(e.createdAt),lastModified:new Date(e.updatedAt)},displayName:e.name,members:null===(t=e.users)||void 0===t?void 0:t.map((e=>({value:e._id})))}},isScimGroup=e=>!!(null==e?void 0:e.id),fromScimGroup=e=>{const t=isScimGroup(e)?e:void 0;return{_id:null==t?void 0:t.id,name:e.displayName,scimInfo:{externalId:e.externalId,isSync:!0},icon:"UserGroup",color:"var(--spectrum-global-color-blue-600)",createdAt:null==t?void 0:t.meta.created.getTime(),updatedAt:null==t?void 0:t.meta.lastModified.toISOString()}};var groups=Object.freeze({__proto__:null,fromScimGroup:fromScimGroup,toScimGroupResponse:toScimGroupResponse}),index$1=Object.freeze({__proto__:null,group:groups,user:users});exports.ai=index$3,exports.api=index$2,exports.auditLogs=index$7,exports.automations=index$a,exports.backups=backups,exports.branding=index$e,exports.constants=index$j,exports.environmentVariables=index$8,exports.features=features,exports.groups=groups$2,exports.init=init,exports.licensing=index$f,exports.logger=logger,exports.mappers=index$1,exports.middleware=index$4,exports.plugins=index$9,exports.publicApi=index$6,exports.quotas=quotas,exports.scimGroups=groups$1,exports.scimUsers=users$1,exports.sdk=index$5,exports.users=index$c,exports.utils=index$i;
|