diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e0f9cd1..0cf82d87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,18 +4,20 @@ - Slightly adjusted the dark theme colors for better readability ([#7648](https://github.com/pocketbase/pocketbase/discussions/7648)). +- Removed unnecessery tags stripping from the displayed log attributes ([#7649](https://github.com/pocketbase/pocketbase/issues/7649)). + ## v0.37.1 - Minor UI bugfixes: - Fixed `number` field input values normalization ([#7646](https://github.com/pocketbase/pocketbase/issues/7646)). - - Allow opening collections in new tab on middle click. + - Allow opening collections in new tab with middle click. - Show collection name in the page title on initial load. ## v0.37.0 -- New UI rewritten from scratch and with support for external customizations in mind. +- New UI rewritten from scratch and with support for external customization in mind. > Note that as explained in [#7612](https://github.com/pocketbase/pocketbase/discussions/7612) the new UI kit and extensions APIs will intentionally remain undocumented until "Stage 2 completion" _(there no ETAs)_. The new UI also introduced several other small improvements: diff --git a/ui/dist/assets/index-CqTYCBEi.js b/ui/dist/assets/index-BNqjqJMs.js similarity index 91% rename from ui/dist/assets/index-CqTYCBEi.js rename to ui/dist/assets/index-BNqjqJMs.js index c2e2c871..2c2e389f 100644 --- a/ui/dist/assets/index-CqTYCBEi.js +++ b/ui/dist/assets/index-BNqjqJMs.js @@ -1,5 +1,5 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./docsList-BAfVNUIM.js","./expandInfo-DGS0CLSa.js","./fieldsInfo-Bz62125-.js","./filterSyntax-Df6AnI5x.js","./docsView-Be6Uhvcf.js","./docsCreate-Be3S3y5K.js","./docsUpdate-LtD8DbWI.js","./docsListAuthMethods-9feSopQX.js","./docsAuthWithPassword-DEWj8Jyn.js","./docsAuthWithOAuth2-DUIE4EoY.js","./docsAuthWithOTP-B7z2VJzp.js","./docsAuthRefresh-UjveHHwo.js","./pageInstaller-CboSj8bL.js","./pocketbase.es-B_4DUNUU.js","./pageConfirmPasswordReset-xSsXQyFi.js","./pageConfirmVerification-BSn_UexA.js","./pageConfirmEmailChange-DWXtM27Q.js"])))=>i.map(i=>d[i]); -import{a as e,n,r,t as i}from"./pocketbase.es-B_4DUNUU.js";var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports),f=(e,n,r,i)=>{if(n&&typeof n==`object`||typeof n==`function`)for(var a=c(n),l=0,d=a.length,f;ln[e]).bind(null,f),enumerable:!(i=s(n,f))||i.enumerable});return e},p=(e,n,r)=>(r=e==null?{}:a(l(e)),f(n||!e||!e.__esModule?o(r,`default`,{value:e,enumerable:!0}):r,e));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))r(e);new MutationObserver(e=>{for(let n of e)if(n.type===`childList`)for(let e of n.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&r(e)}).observe(document,{childList:!0,subtree:!0});function n(e){let n={};return e.integrity&&(n.integrity=e.integrity),e.referrerPolicy&&(n.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?n.credentials=`include`:e.crossOrigin===`anonymous`?n.credentials=`omit`:n.credentials=`same-origin`,n}function r(e){if(e.ep)return;e.ep=!0;let r=n(e);fetch(e.href,r)}})();var m=`abcdefghijklmnopqrstuvwxyz0123456789`,h=`pb_redirect`,g=store({hash:window.location.hash});window.addEventListener(`hashchange`,()=>{g.hash=window.location.hash}),Prism.languages.pbrule={string:Prism.languages.js.string,number:Prism.languages.js.number,function:Prism.languages.js.function,boolean:/\b(?:true|false)\b/i,constant:/\b(?:null)\b/i,comment:{pattern:/\/\/.*/,greedy:!0},italic:/_via_|\:\w+/,keyword:/&&|\|\||\??(?:!~|!=|>=|<=|=|~|>|>|<)(?=[@\w\s]|$)/};var _={isObject(e){return typeof e==`object`&&!!e&&e.constructor===Object},isEmpty(e){return e==null||e===``||Array.isArray(e)&&e.length===0||typeof e==`object`&&app.utils.isEmptyObject(e)},isEmptyObject(e){for(let n in e)return!1;return!0},toArray(e,n=!1){return Array.isArray(e)?e.slice():(n||!_.isEmpty(e))&&e!==void 0?[e]:[]},removeByValue(e,n){if(!Array.isArray(e)){console.warn(`[removeByValue] not an array:`,e);return}for(let r=e.length-1;r>=0;r--)if(e[r]==n){e.splice(r,1);break}},removeByKey(e,n,r){if(!Array.isArray(e)){console.warn(`[removeByKey] not an array:`,e);return}for(let i in e)if(e[i][n]==r){e.splice(i,1);break}},pushUnique(e,n){if(!Array.isArray(e)){console.warn(`[pushUnique] not an array:`,e);return}e.includes(n)||e.push(n)},mergeUnique(e,n){for(let r of n)app.utils.pushUnique(e,r);return e},pushOrReplaceObject(e,n,r=`id`){for(let i=e.length-1;i>=0;i--)if(e[i][r]==n[r]){e[i]=n;return}e.push(n)},filterDuplicatesByKey(e,n=`id`){e=Array.isArray(e)?e:[];let r={};for(let i of e)r[i[n]]=i;return Object.values(r)},filterRedactedProps(e,n=`******`){let r=JSON.parse(JSON.stringify(e||{}));for(let e in r)typeof r[e]==`object`&&r[e]!==null?r[e]=_.filterRedactedProps(r[e],n):r[e]===n&&delete r[e];return r},getByPath(e,n,r=null,i=`.`){let a=e||{},o=(n||``).split(i);for(let e of o){if(!_.isObject(a)&&!Array.isArray(a)||a[e]===void 0)return r;a=a[e]}return a},setByPath(e,n,r,i=`.`){if(typeof e!=`object`||!e){console.warn(`setByPath: data not an object or array.`);return}let a=e,o=n.split(i),s=o.pop();for(let e of o)(!_.isObject(a)&&!Array.isArray(a)||!_.isObject(a[e])&&!Array.isArray(a[e]))&&(a[e]={}),a=a[e];a[s]=r},deleteByPath(e,n,r=`.`){let i=e||{},a=(n||``).split(r),o=a.pop();for(let e of a)(!_.isObject(i)&&!Array.isArray(i)||!_.isObject(i[e])&&!Array.isArray(i[e]))&&(i[e]={}),i=i[e];Array.isArray(i)?i.splice(o,1):_.isObject(i)&&delete i[o],a.length>0&&(Array.isArray(i)&&!i.length||_.isObject(i)&&!Object.keys(i).length)&&(Array.isArray(e)&&e.length>0||_.isObject(e)&&Object.keys(e).length>0)&&_.deleteByPath(e,a.join(r),r)},emptyClone(e,n=[]){let r=JSON.parse(JSON.stringify(e));for(let e in r)n.includes(e)||(typeof r[e]==`string`?r[e]=``:typeof r[e]==`number`?r[e]=0:Array.isArray(r[e])?r[e]=[]:app.utils.isObject(r[e])&&(r[e]={}));return r},randomString(e=8,n=m){let r=``;for(let i=0;i`u`)return app.utils.randomString(e);let n=new Uint8Array(e);crypto.getRandomValues(n);let r=``;for(let i=0;i`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`):``},plainText(e){return e?(new DOMParser().parseFromString(e,`text/html`).body.textContent||``).trim():``},truncate(e,n=150,r=!0){if(e=``+e,e.length<=n)return e;if(e=e.slice(0,n),r){for(;e.endsWith(`.`);)e=e.slice(0,-1);e+=`...`}return e},truncateObject(e,n=150,r=!0){let i=Array.isArray(e)?[]:{};for(let a in e){let o=e[a];typeof o==`string`?o=app.utils.truncate(o,n,r):(Array.isArray(o)||app.utils.isObject(o))&&(o=app.utils.truncateObject(o,n,r)),i[a]=o}return i},stringifyValue(e,n=`N/A`,r=150){if(_.isEmpty(e))return n;if(typeof e==`number`)return``+e;if(typeof e==`boolean`)return e?`True`:`False`;if(typeof e==`string`)return e=e.indexOf(`<`)>=0?_.plainText(e):e,_.truncate(e,r)||n;if(Array.isArray(e)&&typeof e[0]!=`object`)return _.truncate(e.join(`,`),r);if(typeof e==`object`)try{return _.truncate(JSON.stringify(e),r)||n}catch{return n}return e},splitNonEmpty(e,n=`,`){let r=(e||``).split(n),i=[];for(let e of r)e=e.trim(),_.isEmpty(e)||i.push(e);return i},joinNonEmpty(e,n=`, `){e||=[];let r=[];for(let n of e)n=typeof n==`string`?n.trim():n,_.isEmpty(n)||r.push(``+n);return r.join(n)},formattedFileSize(e){let n=e?Math.floor(Math.log(e)/Math.log(1024)):0;return(e/1024**n).toFixed(2)*1+` `+[`B`,`KB`,`MB`,`GB`,`TB`][n]},toRFC3339Datetime(e){if(!e)return``;let n;return n=e instanceof Date?e:typeof e==`string`?new Date(e.replace(` `,`T`)):new Date(e),n.toISOString().replace(`T`,` `)},toLocalDatetime(e){if(!e)return``;let n;n=e instanceof Date?e:typeof e==`string`?new Date(e.replace(` `,`T`)):new Date(e);let r=n.getFullYear();return isNaN(r)?``:`${r}-${(n.getMonth()+1).toString().padStart(2,`0`)}-${n.getDate().toString().padStart(2,`0`)} ${n.getHours().toString().padStart(2,`0`)}:${n.getMinutes().toString().padStart(2,`0`)}:${n.getSeconds().toString().padStart(2,`0`)}.${n.getMilliseconds().toString().padStart(3,`0`)}`},toDatetimeLocalInputValue(e){if(!e)return``;let n;n=e instanceof Date?e:typeof e==`string`?new Date(e.replaceAll(` `,`T`)):new Date(e);let r=n.getFullYear();return isNaN(r)?``:`${r}-${(n.getMonth()+1).toString().padStart(2,`0`)}-${n.getDate().toString().padStart(2,`0`)}T${n.getHours().toString().padStart(2,`0`)}:${n.getMinutes().toString().padStart(2,`0`)}:${n.getSeconds().toString().padStart(2,`0`)}`},async copyToClipboard(e){if(e=e==null?``:e instanceof Date?e.toISOString():typeof e==`object`?JSON.stringify(e):``+e,!(!e.length||!window.navigator?.clipboard))return window.navigator.clipboard.writeText(e).catch(e=>{console.warn(`Failed to copy.`,e)})},download(e,n){let r=document.createElement(`a`);r.setAttribute(`href`,e),r.setAttribute(`download`,n),r.setAttribute(`target`,`_blank`),r.setAttribute(`rel`,`noopener noreferrer`),r.click(),r=null},downloadJSON(e,n){n=n.endsWith(`.json`)?n:n+`.json`;let r=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=window.URL.createObjectURL(r);_.download(i,n)},getApiExampleURL(){let e;if(app.pb.baseURL.startsWith(`http://`)||app.pb.baseURL.startsWith(`https://`))e=app.pb.baseURL;else{e=window.location.href;let n=e.indexOf(`/_/`);e=n>=0?e.substring(0,n):window.location.origin}return e.replace(`//localhost`,`//127.0.0.1`)},isActivePath(e,n=!0,r=``){r||=g.hash;let i;return i=RegExp(n?`^`+RegExp.escape(e)+`\\/?.*$`:`^`+RegExp.escape(e)+`\\/?(?:\\?.+)?$`),i.test(r)},getHashQueryParams(e=``){e||=g.hash;let n=``,r=e.indexOf(`?`);return r>-1&&(n=window.location.hash.substring(r+1)),Object.fromEntries(new URLSearchParams(n))},replaceHashQueryParams(e,n=null){e||={};let r=``,i=window.location.hash,a=i.indexOf(`?`);a>-1&&(r=i.substring(a+1),i=i.substring(0,a));let o=new URLSearchParams(r);for(let n in e){let r=e[n];_.isEmpty(r)?o.delete(n):o.set(n,r)}r=o.toString(),r!=``&&(i+=`?`+r);let s=window.location.href,c=s.indexOf(`#`);c>-1&&(s=s.substring(0,c));let l=s+i;return n===!1||(n===!0?window.history.pushState(null,``,l):window.history.replaceState(null,``,l)),l},rememberPath(){window.localStorage.setItem(h,window.location.hash)},toRememberedPath(e=`#/collections`){let n=window.localStorage.getItem(h);n&&window.localStorage.removeItem(h),window.location.hash=n||e},getLocalHistory(e,n=null){try{let r=window.localStorage.getItem(e);if(r)return JSON.parse(r)||n}catch(n){console.log(`failed to load local history:`,e,n)}return n},saveLocalHistory(e,n){try{app.utils.isEmpty(n)?window.localStorage.removeItem(e):typeof n==`string`?window.localStorage.setItem(e,n):window.localStorage.setItem(e,JSON.stringify(n))}catch(n){console.log(`failed to save local history:`,e,n)}},generateThumb(e,n=100,r=100){return new Promise(i=>{let a=new FileReader;a.onload=function(a){let o=new Image;o.onload=function(){let a=document.createElement(`canvas`),s=a.getContext(`2d`),c=o.width,l=o.height;return a.width=n,a.height=r,s.drawImage(o,c>l?(c-l)/2:0,0,c>l?l:c,c>l?l:c,0,0,n,r),i(a.toDataURL(e.type))},o.src=a.target.result},a.readAsDataURL(e)})},normalizeSearchFilter(e,n=[]){if(e=(e||``).trim(),!e||!n.length)return e;for(let n of[`=`,`!=`,`~`,`!~`,`>`,`>=`,`<`,`<=`])if(e.includes(n))return e;return e=isNaN(e)&&e!=`true`&&e!=`false`?`"${e.replace(/^[\"\'\`]|[\"\'\`]$/gm,``)}"`:e,n.map(n=>`${n}~${e}`).join(`||`)},logLevels:{[-4]:{label:`DEBUG`,class:``},0:{label:`INFO`,class:`success`},4:{label:`WARN`,class:`warning`},8:{label:`ERROR`,class:`danger`}},logDataFormatters:{execTime:function(e){return e?.data?.execTime===void 0?`N/A`:e.data.execTime+`ms`}},extendStore(e,n={},...r){let i=[];for(let a in n){let o=n[a];typeof e.__raw?.[a]==`function`||typeof o!=`function`||a.length>2&&a.startsWith(`on`)||r.includes(a)?e[a]=o:i.push(watch(o,n=>{e[a]=n}))}return i},cssTimeToMs(e){return e?(e=e.toLowerCase(),e.endsWith(`ms`)?Number(e.substring(0,e.length-2)):e.endsWith(`s`)?Number(e.substring(0,e.length-1)):Number(e)||0):0},isDarkEnoughForWhiteText(e){if(e=e?.startsWith(`#`)?e.substring(1):e,e?.length!=6)return!1;let n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16);return(n*299+r*587+i*114)/1e3<128},imageExtensions:[`.jpg`,`.jpeg`,`.png`,`.svg`,`.gif`,`.jfif`,`.webp`,`.avif`],videoExtensions:[`.mp4`,`.avi`,`.mov`,`.3gp`,`.wmv`],audioExtensions:[`.aa`,`.aac`,`.m4v`,`.mp3`,`.ogg`,`.oga`,`.mogg`,`.amr`],documentExtensions:[`.pdf`,`.doc`,`.docx`,`.xls`,`.xlsx`,`.ppt`,`.pptx`,`.odp`,`.odt`,`.ods`,`.txt`],hasImageExtension(e){return e=(e||``).toLowerCase(),!!app.utils.imageExtensions.find(n=>e.endsWith(n))},hasVideoExtension(e){return e=(e||``).toLowerCase(),!!app.utils.videoExtensions.find(n=>e.endsWith(n))},hasAudioExtension(e){return e=(e||``).toLowerCase(),!!app.utils.audioExtensions.find(n=>e.endsWith(n))},hasDocumentExtension(e){return e=(e||``).toLowerCase(),!!app.utils.documentExtensions.find(n=>e.endsWith(n))},getFileType(e){return app.utils.hasImageExtension(e)?`image`:app.utils.hasVideoExtension(e)?`video`:app.utils.hasAudioExtension(e)?`audio`:app.utils.hasDocumentExtension(e)?`document`:`file`},fileTypeIcons:{image:`ri-image-line`,video:`ri-movie-line`,audio:`ri-music-2-line`,document:`ri-file-line`,file:`ri-file-line`},fallbackFieldIcon:`ri-puzzle-line`,fallbackCollectionIcon:`ri-puzzle-line`,fallbackProviderIcon:`ri-puzzle-line`,fallbackPresentableProps:[`title`,`name`,`slug`,`email`,`username`,`nickname`,`displayName`,`label`,`subject`,`topic`,`message`,`heading`,`headline`,`header`,`caption`,`key`,`identifier`,`id`],sortedCollections(e=[]){let n,r;function i(e,i){return n=e.name.startsWith(`_`),r=i.name.startsWith(`_`),n&&!r?1:!n&&r?-1:e.name>i.name?1:e.namee?.id&&!a.find(n=>n.id==e.id)),s=a.filter(e=>e?.id&&!i.find(n=>n.id==e.id)),c=a.filter(e=>{let n=app.utils.isObject(e)&&i.find(n=>n.id==e.id);if(!n)return!1;for(let r in n)if(JSON.stringify(e[r])!=JSON.stringify(n[r]))return!0;return!1});return!!(s.length||c.length||r&&o.length)},extractColumnsFromQuery(e){let n=`__PBGROUP__`;e=(e||``).replace(/\([\s\S]+?\)/gm,n).replace(/[\t\r\n]|(?:\s\s)+/g,` `);let r=e.match(/select\s+([\s\S]+)\s+from/)?.[1]?.split(`,`)||[],i=[];for(let e of r){let r=e.trim().split(` `).pop();r!=``&&r!=n&&i.push(r.replace(/[\'\"\`\[\]\s]/g,``))}return i},getAllCollectionIdentifiers(e,n=``){if(!e)return[];let r=[n+`id`],i=e.type==`auth`;if(e.type===`view`)for(let i of app.utils.extractColumnsFromQuery(e.viewQuery))app.utils.pushUnique(r,n+i);let a=e.fields||[];for(let e of a)if(!(e.type==`password`||i&&e.name==`tokenKey`))if(app.fieldTypes[e.type]?.identifierExtractor){let i=app.utils.toArray(app.fieldTypes[e.type]?.identifierExtractor(e,n));for(let e of i)app.utils.pushUnique(r,e)}else app.utils.pushUnique(r,n+e.name);return r},getDummyFieldsData(e,n=!1){let r=e?.fields||[],i={};for(let e of r)if(!e.hidden)if(app.fieldTypes[e.type]?.dummyData){let r=app.fieldTypes[e.type].dummyData(e,n);r!==void 0&&(i[e.name]=r)}else i[e.name]=`[[DATA]]`;return i},parseIndex(e){let n={unique:!1,optional:!1,schemaName:``,indexName:``,tableName:``,columns:[],where:``},r=/create\s+(unique\s+)?\s*index\s*(if\s+not\s+exists\s+)?(\S*)\s+on\s+(\S*)\s*\(([\s\S]*)\)(?:\s*where\s+([\s\S]*))?/gim.exec((e||``).trim());if(r?.length!=7)return n;let i=/^[\"\'\`\[\{}]|[\"\'\`\]\}]$/gm;n.unique=r[1]?.trim().toLowerCase()===`unique`,n.optional=!app.utils.isEmpty(r[2]?.trim());let a=(r[3]||``).split(`.`);a.length==2?(n.schemaName=a[0].replace(i,``),n.indexName=a[1].replace(i,``)):(n.schemaName=``,n.indexName=a[0].replace(i,``)),n.tableName=(r[4]||``).replace(i,``);let o=(r[5]||``).replace(/,(?=[^\(]*\))/gim,`{PB_TEMP}`).split(`,`);for(let e of o){e=e.trim().replaceAll(`{PB_TEMP}`,`,`);let r=/^([\s\S]+?)(?:\s+collate\s+([\w]+))?(?:\s+(asc|desc))?$/gim.exec(e);if(r?.length!=4)continue;let a=r[1]?.trim()?.replace(i,``);a&&n.columns.push({name:a,collate:r[2]||``,sort:r[3]?.toUpperCase()||``})}return n.where=r[6]||``,n},buildIndex(e){let n=`CREATE `;e.unique&&(n+=`UNIQUE `),n+=`INDEX `,e.optional&&(n+=`IF NOT EXISTS `),e.schemaName&&(n+=`\`${e.schemaName}\`.`),n+=`\`${e.indexName||`idx_`+app.utils.randomString(10)}\` `,n+=`ON \`${e.tableName}\` (`;let r=e.columns.filter(e=>!!e?.name);return r.length>1&&(n+=` +import{a as e,n,r,t as i}from"./pocketbase.es-B_4DUNUU.js";var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports),f=(e,n,r,i)=>{if(n&&typeof n==`object`||typeof n==`function`)for(var a=c(n),l=0,d=a.length,f;ln[e]).bind(null,f),enumerable:!(i=s(n,f))||i.enumerable});return e},p=(e,n,r)=>(r=e==null?{}:a(l(e)),f(n||!e||!e.__esModule?o(r,`default`,{value:e,enumerable:!0}):r,e));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))r(e);new MutationObserver(e=>{for(let n of e)if(n.type===`childList`)for(let e of n.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&r(e)}).observe(document,{childList:!0,subtree:!0});function n(e){let n={};return e.integrity&&(n.integrity=e.integrity),e.referrerPolicy&&(n.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?n.credentials=`include`:e.crossOrigin===`anonymous`?n.credentials=`omit`:n.credentials=`same-origin`,n}function r(e){if(e.ep)return;e.ep=!0;let r=n(e);fetch(e.href,r)}})();var m=`abcdefghijklmnopqrstuvwxyz0123456789`,h=`pb_redirect`,g=store({hash:window.location.hash});window.addEventListener(`hashchange`,()=>{g.hash=window.location.hash}),Prism.languages.pbrule={string:Prism.languages.js.string,number:Prism.languages.js.number,function:Prism.languages.js.function,boolean:/\b(?:true|false)\b/i,constant:/\b(?:null)\b/i,comment:{pattern:/\/\/.*/,greedy:!0},italic:/_via_|\:\w+/,keyword:/&&|\|\||\??(?:!~|!=|>=|<=|=|~|>|>|<)(?=[@\w\s]|$)/};var _={isObject(e){return typeof e==`object`&&!!e&&e.constructor===Object},isEmpty(e){return e==null||e===``||Array.isArray(e)&&e.length===0||typeof e==`object`&&app.utils.isEmptyObject(e)},isEmptyObject(e){for(let n in e)return!1;return!0},toArray(e,n=!1){return Array.isArray(e)?e.slice():(n||!_.isEmpty(e))&&e!==void 0?[e]:[]},removeByValue(e,n){if(!Array.isArray(e)){console.warn(`[removeByValue] not an array:`,e);return}for(let r=e.length-1;r>=0;r--)if(e[r]==n){e.splice(r,1);break}},removeByKey(e,n,r){if(!Array.isArray(e)){console.warn(`[removeByKey] not an array:`,e);return}for(let i in e)if(e[i][n]==r){e.splice(i,1);break}},pushUnique(e,n){if(!Array.isArray(e)){console.warn(`[pushUnique] not an array:`,e);return}e.includes(n)||e.push(n)},mergeUnique(e,n){for(let r of n)app.utils.pushUnique(e,r);return e},pushOrReplaceObject(e,n,r=`id`){for(let i=e.length-1;i>=0;i--)if(e[i][r]==n[r]){e[i]=n;return}e.push(n)},filterDuplicatesByKey(e,n=`id`){e=Array.isArray(e)?e:[];let r={};for(let i of e)r[i[n]]=i;return Object.values(r)},filterRedactedProps(e,n=`******`){let r=JSON.parse(JSON.stringify(e||{}));for(let e in r)typeof r[e]==`object`&&r[e]!==null?r[e]=_.filterRedactedProps(r[e],n):r[e]===n&&delete r[e];return r},getByPath(e,n,r=null,i=`.`){let a=e||{},o=(n||``).split(i);for(let e of o){if(!_.isObject(a)&&!Array.isArray(a)||a[e]===void 0)return r;a=a[e]}return a},setByPath(e,n,r,i=`.`){if(typeof e!=`object`||!e){console.warn(`setByPath: data not an object or array.`);return}let a=e,o=n.split(i),s=o.pop();for(let e of o)(!_.isObject(a)&&!Array.isArray(a)||!_.isObject(a[e])&&!Array.isArray(a[e]))&&(a[e]={}),a=a[e];a[s]=r},deleteByPath(e,n,r=`.`){let i=e||{},a=(n||``).split(r),o=a.pop();for(let e of a)(!_.isObject(i)&&!Array.isArray(i)||!_.isObject(i[e])&&!Array.isArray(i[e]))&&(i[e]={}),i=i[e];Array.isArray(i)?i.splice(o,1):_.isObject(i)&&delete i[o],a.length>0&&(Array.isArray(i)&&!i.length||_.isObject(i)&&!Object.keys(i).length)&&(Array.isArray(e)&&e.length>0||_.isObject(e)&&Object.keys(e).length>0)&&_.deleteByPath(e,a.join(r),r)},emptyClone(e,n=[]){let r=JSON.parse(JSON.stringify(e));for(let e in r)n.includes(e)||(typeof r[e]==`string`?r[e]=``:typeof r[e]==`number`?r[e]=0:Array.isArray(r[e])?r[e]=[]:app.utils.isObject(r[e])&&(r[e]={}));return r},randomString(e=8,n=m){let r=``;for(let i=0;i`u`)return app.utils.randomString(e);let n=new Uint8Array(e);crypto.getRandomValues(n);let r=``;for(let i=0;i`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`):``},plainText(e){return e?(new DOMParser().parseFromString(e,`text/html`).body.textContent||``).trim():``},truncate(e,n=150,r=!0){if(e=``+e,e.length<=n)return e;if(e=e.slice(0,n),r){for(;e.endsWith(`.`);)e=e.slice(0,-1);e+=`...`}return e},truncateObject(e,n=150,r=!0){let i=Array.isArray(e)?[]:{};for(let a in e){let o=e[a];typeof o==`string`?o=app.utils.truncate(o,n,r):(Array.isArray(o)||app.utils.isObject(o))&&(o=app.utils.truncateObject(o,n,r)),i[a]=o}return i},displayValue(e,n=150,r=`N/A`){if(_.isEmpty(e))return r;if(typeof e!=`string`)if(typeof e==`boolean`)e=e?`True`:`False`;else if(Array.isArray(e)&&typeof e[0]!=`object`)e=e.map(e=>_.displayValue(e,n,r)).join(`, `);else try{e=JSON.stringify(e)||``}catch{e=``+e}return e?_.truncate(e,n):r},splitNonEmpty(e,n=`,`){let r=(e||``).split(n),i=[];for(let e of r)e=e.trim(),_.isEmpty(e)||i.push(e);return i},joinNonEmpty(e,n=`, `){e||=[];let r=[];for(let n of e)n=typeof n==`string`?n.trim():n,_.isEmpty(n)||r.push(``+n);return r.join(n)},formattedFileSize(e){let n=e?Math.floor(Math.log(e)/Math.log(1024)):0;return(e/1024**n).toFixed(2)*1+` `+[`B`,`KB`,`MB`,`GB`,`TB`][n]},toRFC3339Datetime(e){if(!e)return``;let n;return n=e instanceof Date?e:typeof e==`string`?new Date(e.replace(` `,`T`)):new Date(e),n.toISOString().replace(`T`,` `)},toLocalDatetime(e){if(!e)return``;let n;n=e instanceof Date?e:typeof e==`string`?new Date(e.replace(` `,`T`)):new Date(e);let r=n.getFullYear();return isNaN(r)?``:`${r}-${(n.getMonth()+1).toString().padStart(2,`0`)}-${n.getDate().toString().padStart(2,`0`)} ${n.getHours().toString().padStart(2,`0`)}:${n.getMinutes().toString().padStart(2,`0`)}:${n.getSeconds().toString().padStart(2,`0`)}.${n.getMilliseconds().toString().padStart(3,`0`)}`},toDatetimeLocalInputValue(e){if(!e)return``;let n;n=e instanceof Date?e:typeof e==`string`?new Date(e.replaceAll(` `,`T`)):new Date(e);let r=n.getFullYear();return isNaN(r)?``:`${r}-${(n.getMonth()+1).toString().padStart(2,`0`)}-${n.getDate().toString().padStart(2,`0`)}T${n.getHours().toString().padStart(2,`0`)}:${n.getMinutes().toString().padStart(2,`0`)}:${n.getSeconds().toString().padStart(2,`0`)}`},async copyToClipboard(e){if(e=e==null?``:e instanceof Date?e.toISOString():typeof e==`object`?JSON.stringify(e):``+e,!(!e.length||!window.navigator?.clipboard))return window.navigator.clipboard.writeText(e).catch(e=>{console.warn(`Failed to copy.`,e)})},download(e,n){let r=document.createElement(`a`);r.setAttribute(`href`,e),r.setAttribute(`download`,n),r.setAttribute(`target`,`_blank`),r.setAttribute(`rel`,`noopener noreferrer`),r.click(),r=null},downloadJSON(e,n){n=n.endsWith(`.json`)?n:n+`.json`;let r=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=window.URL.createObjectURL(r);_.download(i,n)},getApiExampleURL(){let e;if(app.pb.baseURL.startsWith(`http://`)||app.pb.baseURL.startsWith(`https://`))e=app.pb.baseURL;else{e=window.location.href;let n=e.indexOf(`/_/`);e=n>=0?e.substring(0,n):window.location.origin}return e.replace(`//localhost`,`//127.0.0.1`)},isActivePath(e,n=!0,r=``){r||=g.hash;let i;return i=RegExp(n?`^`+RegExp.escape(e)+`\\/?.*$`:`^`+RegExp.escape(e)+`\\/?(?:\\?.+)?$`),i.test(r)},getHashQueryParams(e=``){e||=g.hash;let n=``,r=e.indexOf(`?`);return r>-1&&(n=window.location.hash.substring(r+1)),Object.fromEntries(new URLSearchParams(n))},replaceHashQueryParams(e,n=null){e||={};let r=``,i=window.location.hash,a=i.indexOf(`?`);a>-1&&(r=i.substring(a+1),i=i.substring(0,a));let o=new URLSearchParams(r);for(let n in e){let r=e[n];_.isEmpty(r)?o.delete(n):o.set(n,r)}r=o.toString(),r!=``&&(i+=`?`+r);let s=window.location.href,c=s.indexOf(`#`);c>-1&&(s=s.substring(0,c));let l=s+i;return n===!1||(n===!0?window.history.pushState(null,``,l):window.history.replaceState(null,``,l)),l},rememberPath(){window.localStorage.setItem(h,window.location.hash)},toRememberedPath(e=`#/collections`){let n=window.localStorage.getItem(h);n&&window.localStorage.removeItem(h),window.location.hash=n||e},getLocalHistory(e,n=null){try{let r=window.localStorage.getItem(e);if(r)return JSON.parse(r)||n}catch(n){console.log(`failed to load local history:`,e,n)}return n},saveLocalHistory(e,n){try{app.utils.isEmpty(n)?window.localStorage.removeItem(e):typeof n==`string`?window.localStorage.setItem(e,n):window.localStorage.setItem(e,JSON.stringify(n))}catch(n){console.log(`failed to save local history:`,e,n)}},generateThumb(e,n=100,r=100){return new Promise(i=>{let a=new FileReader;a.onload=function(a){let o=new Image;o.onload=function(){let a=document.createElement(`canvas`),s=a.getContext(`2d`),c=o.width,l=o.height;return a.width=n,a.height=r,s.drawImage(o,c>l?(c-l)/2:0,0,c>l?l:c,c>l?l:c,0,0,n,r),i(a.toDataURL(e.type))},o.src=a.target.result},a.readAsDataURL(e)})},normalizeSearchFilter(e,n=[]){if(e=(e||``).trim(),!e||!n.length)return e;for(let n of[`=`,`!=`,`~`,`!~`,`>`,`>=`,`<`,`<=`])if(e.includes(n))return e;return e=isNaN(e)&&e!=`true`&&e!=`false`?`"${e.replace(/^[\"\'\`]|[\"\'\`]$/gm,``)}"`:e,n.map(n=>`${n}~${e}`).join(`||`)},logLevels:{[-4]:{label:`DEBUG`,class:``},0:{label:`INFO`,class:`success`},4:{label:`WARN`,class:`warning`},8:{label:`ERROR`,class:`danger`}},logDataFormatters:{execTime:function(e){return e?.data?.execTime===void 0?`N/A`:e.data.execTime+`ms`}},extendStore(e,n={},...r){let i=[];for(let a in n){let o=n[a];typeof e.__raw?.[a]==`function`||typeof o!=`function`||a.length>2&&a.startsWith(`on`)||r.includes(a)?e[a]=o:i.push(watch(o,n=>{e[a]=n}))}return i},cssTimeToMs(e){return e?(e=e.toLowerCase(),e.endsWith(`ms`)?Number(e.substring(0,e.length-2)):e.endsWith(`s`)?Number(e.substring(0,e.length-1)):Number(e)||0):0},isDarkEnoughForWhiteText(e){if(e=e?.startsWith(`#`)?e.substring(1):e,e?.length!=6)return!1;let n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16);return(n*299+r*587+i*114)/1e3<128},imageExtensions:[`.jpg`,`.jpeg`,`.png`,`.svg`,`.gif`,`.jfif`,`.webp`,`.avif`],videoExtensions:[`.mp4`,`.avi`,`.mov`,`.3gp`,`.wmv`],audioExtensions:[`.aa`,`.aac`,`.m4v`,`.mp3`,`.ogg`,`.oga`,`.mogg`,`.amr`],documentExtensions:[`.pdf`,`.doc`,`.docx`,`.xls`,`.xlsx`,`.ppt`,`.pptx`,`.odp`,`.odt`,`.ods`,`.txt`],hasImageExtension(e){return e=(e||``).toLowerCase(),!!app.utils.imageExtensions.find(n=>e.endsWith(n))},hasVideoExtension(e){return e=(e||``).toLowerCase(),!!app.utils.videoExtensions.find(n=>e.endsWith(n))},hasAudioExtension(e){return e=(e||``).toLowerCase(),!!app.utils.audioExtensions.find(n=>e.endsWith(n))},hasDocumentExtension(e){return e=(e||``).toLowerCase(),!!app.utils.documentExtensions.find(n=>e.endsWith(n))},getFileType(e){return app.utils.hasImageExtension(e)?`image`:app.utils.hasVideoExtension(e)?`video`:app.utils.hasAudioExtension(e)?`audio`:app.utils.hasDocumentExtension(e)?`document`:`file`},fileTypeIcons:{image:`ri-image-line`,video:`ri-movie-line`,audio:`ri-music-2-line`,document:`ri-file-line`,file:`ri-file-line`},fallbackFieldIcon:`ri-puzzle-line`,fallbackCollectionIcon:`ri-puzzle-line`,fallbackProviderIcon:`ri-puzzle-line`,fallbackPresentableProps:[`title`,`name`,`slug`,`email`,`username`,`nickname`,`displayName`,`label`,`subject`,`topic`,`message`,`heading`,`headline`,`header`,`caption`,`key`,`identifier`,`id`],sortedCollections(e=[]){let n,r;function i(e,i){return n=e.name.startsWith(`_`),r=i.name.startsWith(`_`),n&&!r?1:!n&&r?-1:e.name>i.name?1:e.namee?.id&&!a.find(n=>n.id==e.id)),s=a.filter(e=>e?.id&&!i.find(n=>n.id==e.id)),c=a.filter(e=>{let n=app.utils.isObject(e)&&i.find(n=>n.id==e.id);if(!n)return!1;for(let r in n)if(JSON.stringify(e[r])!=JSON.stringify(n[r]))return!0;return!1});return!!(s.length||c.length||r&&o.length)},extractColumnsFromQuery(e){let n=`__PBGROUP__`;e=(e||``).replace(/\([\s\S]+?\)/gm,n).replace(/[\t\r\n]|(?:\s\s)+/g,` `);let r=e.match(/select\s+([\s\S]+)\s+from/)?.[1]?.split(`,`)||[],i=[];for(let e of r){let r=e.trim().split(` `).pop();r!=``&&r!=n&&i.push(r.replace(/[\'\"\`\[\]\s]/g,``))}return i},getAllCollectionIdentifiers(e,n=``){if(!e)return[];let r=[n+`id`],i=e.type==`auth`;if(e.type===`view`)for(let i of app.utils.extractColumnsFromQuery(e.viewQuery))app.utils.pushUnique(r,n+i);let a=e.fields||[];for(let e of a)if(!(e.type==`password`||i&&e.name==`tokenKey`))if(app.fieldTypes[e.type]?.identifierExtractor){let i=app.utils.toArray(app.fieldTypes[e.type]?.identifierExtractor(e,n));for(let e of i)app.utils.pushUnique(r,e)}else app.utils.pushUnique(r,n+e.name);return r},getDummyFieldsData(e,n=!1){let r=e?.fields||[],i={};for(let e of r)if(!e.hidden)if(app.fieldTypes[e.type]?.dummyData){let r=app.fieldTypes[e.type].dummyData(e,n);r!==void 0&&(i[e.name]=r)}else i[e.name]=`[[DATA]]`;return i},parseIndex(e){let n={unique:!1,optional:!1,schemaName:``,indexName:``,tableName:``,columns:[],where:``},r=/create\s+(unique\s+)?\s*index\s*(if\s+not\s+exists\s+)?(\S*)\s+on\s+(\S*)\s*\(([\s\S]*)\)(?:\s*where\s+([\s\S]*))?/gim.exec((e||``).trim());if(r?.length!=7)return n;let i=/^[\"\'\`\[\{}]|[\"\'\`\]\}]$/gm;n.unique=r[1]?.trim().toLowerCase()===`unique`,n.optional=!app.utils.isEmpty(r[2]?.trim());let a=(r[3]||``).split(`.`);a.length==2?(n.schemaName=a[0].replace(i,``),n.indexName=a[1].replace(i,``)):(n.schemaName=``,n.indexName=a[0].replace(i,``)),n.tableName=(r[4]||``).replace(i,``);let o=(r[5]||``).replace(/,(?=[^\(]*\))/gim,`{PB_TEMP}`).split(`,`);for(let e of o){e=e.trim().replaceAll(`{PB_TEMP}`,`,`);let r=/^([\s\S]+?)(?:\s+collate\s+([\w]+))?(?:\s+(asc|desc))?$/gim.exec(e);if(r?.length!=4)continue;let a=r[1]?.trim()?.replace(i,``);a&&n.columns.push({name:a,collate:r[2]||``,sort:r[3]?.toUpperCase()||``})}return n.where=r[6]||``,n},buildIndex(e){let n=`CREATE `;e.unique&&(n+=`UNIQUE `),n+=`INDEX `,e.optional&&(n+=`IF NOT EXISTS `),e.schemaName&&(n+=`\`${e.schemaName}\`.`),n+=`\`${e.indexName||`idx_`+app.utils.randomString(10)}\` `,n+=`ON \`${e.tableName}\` (`;let r=e.columns.filter(e=>!!e?.name);return r.length>1&&(n+=` `),n+=r.map(e=>{let n=``;return e.name.includes(`(`)||e.name.includes(` `)?n+=e.name:n+="`"+e.name+"`",e.collate&&(n+=` COLLATE `+e.collate),e.sort&&(n+=` `+e.sort.toUpperCase()),n}).join(`, `),r.length>1&&(n+=` `),n+=`)`,e.where&&(n+=` WHERE ${e.where}`),n},replaceIndexFields(e,n){let r=app.utils.parseIndex(e);return typeof n==`function`?Object.assign(r,n(r)||{}):Object.assign(r,n||{}),app.utils.buildIndex(r)},replaceIndexColumn(e,n,r){if(n===r)return e;let i=app.utils.parseIndex(e),a=!1;for(let e of i.columns)e.name===n&&(e.name=r,a=!0);return a?app.utils.buildIndex(i):e}};window.app=window.app||{},window.app.utils=_,window.app=window.app||{},window.app.utils=window.app.utils||{},window.app.utils.mimeTypes=[{ext:``,mimeType:`application/octet-stream`},{ext:`.xpm`,mimeType:`image/x-xpixmap`},{ext:`.7z`,mimeType:`application/x-7z-compressed`},{ext:`.zip`,mimeType:`application/zip`},{ext:`.xlsx`,mimeType:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},{ext:`.docx`,mimeType:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`},{ext:`.pptx`,mimeType:`application/vnd.openxmlformats-officedocument.presentationml.presentation`},{ext:`.epub`,mimeType:`application/epub+zip`},{ext:`.apk`,mimeType:`application/vnd.android.package-archive`},{ext:`.jar`,mimeType:`application/jar`},{ext:`.odt`,mimeType:`application/vnd.oasis.opendocument.text`},{ext:`.ott`,mimeType:`application/vnd.oasis.opendocument.text-template`},{ext:`.ods`,mimeType:`application/vnd.oasis.opendocument.spreadsheet`},{ext:`.ots`,mimeType:`application/vnd.oasis.opendocument.spreadsheet-template`},{ext:`.odp`,mimeType:`application/vnd.oasis.opendocument.presentation`},{ext:`.otp`,mimeType:`application/vnd.oasis.opendocument.presentation-template`},{ext:`.odg`,mimeType:`application/vnd.oasis.opendocument.graphics`},{ext:`.otg`,mimeType:`application/vnd.oasis.opendocument.graphics-template`},{ext:`.odf`,mimeType:`application/vnd.oasis.opendocument.formula`},{ext:`.odc`,mimeType:`application/vnd.oasis.opendocument.chart`},{ext:`.sxc`,mimeType:`application/vnd.sun.xml.calc`},{ext:`.pdf`,mimeType:`application/pdf`},{ext:`.fdf`,mimeType:`application/vnd.fdf`},{ext:``,mimeType:`application/x-ole-storage`},{ext:`.msi`,mimeType:`application/x-ms-installer`},{ext:`.aaf`,mimeType:`application/octet-stream`},{ext:`.msg`,mimeType:`application/vnd.ms-outlook`},{ext:`.xls`,mimeType:`application/vnd.ms-excel`},{ext:`.pub`,mimeType:`application/vnd.ms-publisher`},{ext:`.ppt`,mimeType:`application/vnd.ms-powerpoint`},{ext:`.doc`,mimeType:`application/msword`},{ext:`.ps`,mimeType:`application/postscript`},{ext:`.psd`,mimeType:`image/vnd.adobe.photoshop`},{ext:`.p7s`,mimeType:`application/pkcs7-signature`},{ext:`.ogg`,mimeType:`application/ogg`},{ext:`.oga`,mimeType:`audio/ogg`},{ext:`.ogv`,mimeType:`video/ogg`},{ext:`.png`,mimeType:`image/png`},{ext:`.png`,mimeType:`image/vnd.mozilla.apng`},{ext:`.jpg`,mimeType:`image/jpeg`},{ext:`.jxl`,mimeType:`image/jxl`},{ext:`.jp2`,mimeType:`image/jp2`},{ext:`.jpf`,mimeType:`image/jpx`},{ext:`.jpm`,mimeType:`image/jpm`},{ext:`.jxs`,mimeType:`image/jxs`},{ext:`.gif`,mimeType:`image/gif`},{ext:`.webp`,mimeType:`image/webp`},{ext:`.exe`,mimeType:`application/vnd.microsoft.portable-executable`},{ext:``,mimeType:`application/x-elf`},{ext:``,mimeType:`application/x-object`},{ext:``,mimeType:`application/x-executable`},{ext:`.so`,mimeType:`application/x-sharedlib`},{ext:``,mimeType:`application/x-coredump`},{ext:`.a`,mimeType:`application/x-archive`},{ext:`.deb`,mimeType:`application/vnd.debian.binary-package`},{ext:`.tar`,mimeType:`application/x-tar`},{ext:`.xar`,mimeType:`application/x-xar`},{ext:`.bz2`,mimeType:`application/x-bzip2`},{ext:`.fits`,mimeType:`application/fits`},{ext:`.tiff`,mimeType:`image/tiff`},{ext:`.bmp`,mimeType:`image/bmp`},{ext:`.ico`,mimeType:`image/x-icon`},{ext:`.mp3`,mimeType:`audio/mpeg`},{ext:`.flac`,mimeType:`audio/flac`},{ext:`.midi`,mimeType:`audio/midi`},{ext:`.ape`,mimeType:`audio/ape`},{ext:`.mpc`,mimeType:`audio/musepack`},{ext:`.amr`,mimeType:`audio/amr`},{ext:`.wav`,mimeType:`audio/wav`},{ext:`.aiff`,mimeType:`audio/aiff`},{ext:`.au`,mimeType:`audio/basic`},{ext:`.mpeg`,mimeType:`video/mpeg`},{ext:`.mov`,mimeType:`video/quicktime`},{ext:`.mp4`,mimeType:`video/mp4`},{ext:`.avif`,mimeType:`image/avif`},{ext:`.3gp`,mimeType:`video/3gpp`},{ext:`.3g2`,mimeType:`video/3gpp2`},{ext:`.mp4`,mimeType:`audio/mp4`},{ext:`.mqv`,mimeType:`video/quicktime`},{ext:`.m4a`,mimeType:`audio/x-m4a`},{ext:`.m4v`,mimeType:`video/x-m4v`},{ext:`.heic`,mimeType:`image/heic`},{ext:`.heic`,mimeType:`image/heic-sequence`},{ext:`.heif`,mimeType:`image/heif`},{ext:`.heif`,mimeType:`image/heif-sequence`},{ext:`.mj2`,mimeType:`video/mj2`},{ext:`.dvb`,mimeType:`video/vnd.dvb.file`},{ext:`.webm`,mimeType:`video/webm`},{ext:`.avi`,mimeType:`video/x-msvideo`},{ext:`.flv`,mimeType:`video/x-flv`},{ext:`.mkv`,mimeType:`video/x-matroska`},{ext:`.asf`,mimeType:`video/x-ms-asf`},{ext:`.asf`,mimeType:`video/x-ms-wmv`},{ext:`.asf`,mimeType:`video/asf`},{ext:`.aac`,mimeType:`audio/aac`},{ext:`.voc`,mimeType:`audio/x-unknown`},{ext:`.m3u`,mimeType:`application/vnd.apple.mpegurl`},{ext:`.rmvb`,mimeType:`application/vnd.rn-realmedia-vbr`},{ext:`.gz`,mimeType:`application/gzip`},{ext:`.class`,mimeType:`application/x-java-applet`},{ext:`.swf`,mimeType:`application/x-shockwave-flash`},{ext:`.crx`,mimeType:`application/x-chrome-extension`},{ext:`.ttf`,mimeType:`font/ttf`},{ext:`.woff`,mimeType:`font/woff`},{ext:`.woff2`,mimeType:`font/woff2`},{ext:`.otf`,mimeType:`font/otf`},{ext:`.ttc`,mimeType:`font/collection`},{ext:`.eot`,mimeType:`application/vnd.ms-fontobject`},{ext:`.wasm`,mimeType:`application/wasm`},{ext:`.shx`,mimeType:`application/vnd.shx`},{ext:`.shp`,mimeType:`application/vnd.shp`},{ext:`.dbf`,mimeType:`application/x-dbf`},{ext:`.dcm`,mimeType:`application/dicom`},{ext:`.rar`,mimeType:`application/x-rar-compressed`},{ext:`.djvu`,mimeType:`image/vnd.djvu`},{ext:`.mobi`,mimeType:`application/x-mobipocket-ebook`},{ext:`.lit`,mimeType:`application/x-ms-reader`},{ext:`.bpg`,mimeType:`image/bpg`},{ext:`.cbor`,mimeType:`application/cbor`},{ext:`.sqlite`,mimeType:`application/vnd.sqlite3`},{ext:`.dwg`,mimeType:`image/vnd.dwg`},{ext:`.nes`,mimeType:`application/vnd.nintendo.snes.rom`},{ext:`.lnk`,mimeType:`application/x-ms-shortcut`},{ext:`.macho`,mimeType:`application/x-mach-binary`},{ext:`.qcp`,mimeType:`audio/qcelp`},{ext:`.icns`,mimeType:`image/x-icns`},{ext:`.hdr`,mimeType:`image/vnd.radiance`},{ext:`.mrc`,mimeType:`application/marc`},{ext:`.mdb`,mimeType:`application/x-msaccess`},{ext:`.accdb`,mimeType:`application/x-msaccess`},{ext:`.zst`,mimeType:`application/zstd`},{ext:`.cab`,mimeType:`application/vnd.ms-cab-compressed`},{ext:`.rpm`,mimeType:`application/x-rpm`},{ext:`.xz`,mimeType:`application/x-xz`},{ext:`.lz`,mimeType:`application/lzip`},{ext:`.torrent`,mimeType:`application/x-bittorrent`},{ext:`.cpio`,mimeType:`application/x-cpio`},{ext:``,mimeType:`application/tzif`},{ext:`.xcf`,mimeType:`image/x-xcf`},{ext:`.pat`,mimeType:`image/x-gimp-pat`},{ext:`.gbr`,mimeType:`image/x-gimp-gbr`},{ext:`.glb`,mimeType:`model/gltf-binary`},{ext:`.cab`,mimeType:`application/x-installshield`},{ext:`.jxr`,mimeType:`image/jxr`},{ext:`.parquet`,mimeType:`application/vnd.apache.parquet`},{ext:`.txt`,mimeType:`text/plain`},{ext:`.html`,mimeType:`text/html`},{ext:`.svg`,mimeType:`image/svg+xml`},{ext:`.xml`,mimeType:`text/xml`},{ext:`.rss`,mimeType:`application/rss+xml`},{ext:`.atom`,mimeType:`application/atom+xml`},{ext:`.x3d`,mimeType:`model/x3d+xml`},{ext:`.kml`,mimeType:`application/vnd.google-earth.kml+xml`},{ext:`.xlf`,mimeType:`application/x-xliff+xml`},{ext:`.dae`,mimeType:`model/vnd.collada+xml`},{ext:`.gml`,mimeType:`application/gml+xml`},{ext:`.gpx`,mimeType:`application/gpx+xml`},{ext:`.tcx`,mimeType:`application/vnd.garmin.tcx+xml`},{ext:`.amf`,mimeType:`application/x-amf`},{ext:`.3mf`,mimeType:`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`},{ext:`.xfdf`,mimeType:`application/vnd.adobe.xfdf`},{ext:`.owl`,mimeType:`application/owl+xml`},{ext:`.php`,mimeType:`text/x-php`},{ext:`.js`,mimeType:`text/javascript`},{ext:`.lua`,mimeType:`text/x-lua`},{ext:`.pl`,mimeType:`text/x-perl`},{ext:`.py`,mimeType:`text/x-python`},{ext:`.json`,mimeType:`application/json`},{ext:`.geojson`,mimeType:`application/geo+json`},{ext:`.har`,mimeType:`application/json`},{ext:`.ndjson`,mimeType:`application/x-ndjson`},{ext:`.rtf`,mimeType:`text/rtf`},{ext:`.srt`,mimeType:`application/x-subrip`},{ext:`.tcl`,mimeType:`text/x-tcl`},{ext:`.csv`,mimeType:`text/csv`},{ext:`.tsv`,mimeType:`text/tab-separated-values`},{ext:`.vcf`,mimeType:`text/vcard`},{ext:`.ics`,mimeType:`text/calendar`},{ext:`.warc`,mimeType:`application/warc`},{ext:`.vtt`,mimeType:`text/vtt`},{ext:`.pbm`,mimeType:`image/x-portable-bitmap`},{ext:`.pgm`,mimeType:`image/x-portable-graymap`},{ext:`.ppm`,mimeType:`image/x-portable-pixmap`},{ext:`.eml`,mimeType:`message/rfc822`}];var v=new BroadcastChannel(`tabsSync`),ee=`pbSettings`,te=`pbColorScheme`;window.app=window.app||{},window.app.store=store({_ready:!1,superuser:null,showHeader:!0,page:t.div({className:`page`},()=>{if(!app.store._ready)return t.span({className:`loader lg m-auto`,title:`Loading plugins...`})}),mainLogo:`./images/logo.svg`,headerLogo:`./images/logo_white.svg`,favicon:``,title:``,_mediaColorScheme:``,userColorScheme:window.localStorage.getItem(te)||``,get activeColorScheme(){return app.store.userColorScheme?app.store.userColorScheme:app.store._mediaColorScheme||`light`},errors:null,creditLinks:[{href:`https://pocketbase.io/docs`,icon:`ri-book-open-line`,label:`Docs`},{href:`https://github.com/pocketbase/pocketbase/releases`,icon:`ri-github-line`,label:`PocketBase v0.37.2-dev`}],headerLinks:[{href:`#/collections`,icon:`ri-database-2-line`,label:`Collections`},{href:`#/logs`,icon:`ri-bar-chart-box-line`,label:`Logs`},{href:`#/settings`,icon:`ri-settings-3-line`,label:`Settings`}],settingsNavGroups:{System:[{href:`#/settings`,icon:`ri-home-gear-line`,label:`Application`},{href:`#/settings/mail`,icon:`ri-send-plane-2-line`,label:`Mail settings`},{href:`#/settings/storage`,icon:`ri-archive-drawer-line`,label:`Files storage`},{href:`#/settings/backups`,icon:`ri-archive-line`,label:`Backups`},{href:`#/settings/crons`,icon:`ri-time-line`,label:`Crons`}],Sync:[{href:`#/settings/export-collections`,icon:`ri-uninstall-line`,label:`Export collections`},{href:`#/settings/import-collections`,icon:`ri-install-line`,label:`Import collections`}]},predefinedAccentColors:[`#1055c9`,`#a3142a`,`#096d5c`,`#e6620a`,`#007d9c`,`#3f3da9`],settings:app.utils.getLocalHistory(ee,{}),isLoadingSettings:!1,async loadSettings(){app.store.isLoadingSettings=!0;try{let e=await app.pb.settings.getAll({requestKey:`appStore.loadSettings`});app.store.settings=e,app.store.isLoadingSettings=!1}catch(e){e.isAbort||(app.store.isLoadingSettings=!1,app.checkApiError(e))}},collections:[],collectionScaffolds:{},isLoadingCollections:!1,_activeCollectionIdOrName:``,get activeCollection(){let e=app.store._activeCollectionIdOrName;return app.store.collections.find(n=>n.id==e||n.name==e)||app.store.collections[0]},set activeCollection(e){typeof e==`string`?app.store._activeCollectionIdOrName=e:app.store._activeCollectionIdOrName=e?.id},async silentlyReloadCollections(){try{let e=await app.pb.collections.getFullList({requestKey:`appStore.silentlyReloadCollections`});e=app.utils.sortedCollectionsByType(e),JSON.stringify(e)!=JSON.stringify(app.store.collections)&&(app.store.collections=e)}catch(e){e.isAbort||console.warn(`failed to reload app store collections:`,e)}},async loadCollections(e=null){app.store.isLoadingCollections=!0;try{let[n,r]=await Promise.all([app.pb.collections.getScaffolds({requestKey:`appStore.loadCollections.getScaffolds`}),app.pb.collections.getFullList({requestKey:`appStore.loadCollections.getFullList`})]);r=app.utils.sortedCollectionsByType(r),JSON.stringify(app.store.collections)!=JSON.stringify(r)&&(app.store.collections=r),app.store.collectionScaffolds=n,app.store._activeCollectionIdOrName=e||app.store._activeCollectionIdOrName||app.store.collections[0]?.id||``,app.store.isLoadingCollections=!1}catch(e){e.isAbort||(app.store.isLoadingCollections=!1,app.checkApiError(e))}},addOrUpdateCollection(e){let n=app.store.collections.findIndex(n=>n.id==e.id);n>=0?(app.store.activeCollection.id==e.id&&(app.store._activeCollectionIdOrName=e.id),app.store.collections[n]=e):app.store.collections.push(e),app.store.collections=app.utils.sortedCollectionsByType(app.store.collections)},oauth2Providers:[],isLoadingOAuth2Providers:!1,async loadOAuth2Providers(){app.store.isLoadingOAuth2Providers=!0;try{app.store.oauth2Providers=await app.pb.send(`/api/collections/meta/oauth2-providers`),app.store.isLoadingOAuth2Providers=!1}catch(e){e.isAbort||(app.checkApiError(e),app.store.isLoadingOAuth2Providers=!1)}}}),window.addEventListener(`hashchange`,()=>{app.store.title=``,app.store.errors=null}),watch(()=>{let e=app.utils.toArray(app.store.title),n=app.store.settings?.meta?.appName||``;n&&e.push(n),document.title=e.join(` - `)});var ne;watch(()=>app.store.settings?.meta?.accentColor,e=>{ne||(ne=t.meta({name:`theme-color`}),document.head.appendChild(ne)),e?(ne?.setAttribute(`content`,e),document.documentElement.style.setProperty(`--accentColor`,e)):(ne?.removeAttribute(`content`),document.documentElement.style.removeProperty(`--accentColor`))});var re;watch(()=>app.store.favicon,e=>{re||(re=t.link({rel:`icon`}),document.head.appendChild(re)),e?re.href=e:re.href=window.location.href.startsWith(`https://`)?`./images/favicon_prod.png`:`./images/favicon.png`});var ie=window.matchMedia(`(prefers-color-scheme: dark)`);app.store._mediaColorScheme=ie.matches?`dark`:`light`,ie.addEventListener(`change`,({matches:e})=>{app.store._mediaColorScheme=e?`dark`:`light`}),watch(()=>app.store.userColorScheme,e=>{e?window.localStorage.setItem(te,e):window.localStorage.removeItem(te),v?.postMessage({colorScheme:e})});var ae;watch(()=>app.store.activeColorScheme,e=>{clearTimeout(ae),document.documentElement.style.setProperty(`--animationSpeed`,`0`),document.documentElement.setAttribute(`data-color-scheme`,e),ae=setTimeout(()=>{document.documentElement.style.removeProperty(`--animationSpeed`)},100)});function oe(e,n){e.__errListener&&=(e.removeEventListener(`input`,e.__errListener),e.removeEventListener(`change`,e.__errListener),null),e.setCustomValidity&&(e.setCustomValidity(``),e._oldTitle?e.setAttribute(`title`,e._oldTitle):e.removeAttribute(`title`)),e.removeAttribute(`data-error`);let r=n.nextSibling;r&&r.classList?.contains(`generated-error`)&&r.getAttribute(`data-input-name`)==e.getAttribute(`name`)&&r.remove(),n.querySelector(`[data-error]`)||n.classList.remove(`error`)}watch(()=>JSON.stringify(app.store.errors)&&app.store.errors,e=>{let n=document.querySelectorAll(`[name]`);for(let r of n){if(r.classList.contains(`no-error`))continue;let n=r.closest(`.fields`)||r.closest(`.field`);if(!n)continue;let i=r.getAttribute(`name`);oe(r,n);let a=app.utils.getByPath(e,i)?.message;a&&(n.classList.add(`error`),r.__errListener=function(){oe(r,n),app.utils.deleteByPath(app.store.errors,i)},r.addEventListener(`input`,r.__errListener),r.addEventListener(`change`,r.__errListener),r.setAttribute(`data-error`,!0),r.setCustomValidity&&r.reportValidity&&r.classList.contains(`inline-error`)?(r.setCustomValidity(a),r.reportValidity(),r._oldTitle=r.title,r.title=a):n.after(t.div({"html-data-input-name":i,className:`field-help error generated-error`,textContent:a})))}}),v.onmessage=e=>{e.data?.collections&&JSON.stringify(app.store.collections)!=JSON.stringify(e.data.collections)&&(app.store.collections=e.data.collections),e.data?.settings&&JSON.stringify(app.store.settings)!=JSON.stringify(e.data.settings)&&(app.store.settings=e.data.settings),e.data?.colorScheme&&(app.store.userColorScheme=e.data.colorScheme)},watch(()=>JSON.stringify(app.store.collections),(e,n)=>{e&&e!=`[]`&&n&&n!=`[]`&&e!=n&&v?.postMessage({collections:JSON.parse(e)})}),watch(()=>JSON.stringify(app.store.settings),(e,n)=>{e&&e!=`{}`&&n&&n!=`{}`&&e!=n&&v?.postMessage({settings:JSON.parse(e)}),window.localStorage.setItem(ee,e)});var y=`#/login`,b=window.location.pathname.endsWith(`/`)?window.location.pathname.substring(0,window.location.pathname.length-1):window.location.pathname;window.app=window.app||{},window.app.pb=new i(`../`,new r(`__pb_superusers__`+b)),app.pb.beforeSend=function(e,n){return n.headers[`x-request-source`]=`pbui`,{url:e,options:n}},app.store.superuser=app.pb.authStore.record,app.pb.authStore.onChange((e,n)=>{!n&&window.location.hash!=y&&(app.modals.close(),window.location.hash=y),app.store.superuser=n}),app.pb.authStore.isValid&&app.pb.collection(app.pb.authStore.record?.collectionName||`_superusers`).authRefresh().catch(e=>{console.warn(`Failed to refresh the existing auth token:`,e);let n=e?.status<<0;(n==401||n==403)&&(app.utils.rememberPath(),app.pb.cancelAllRequests(),app.pb.authStore.clear())}),app.pb.authStore.onChange((e,n)=>{n?.id&&(app.store.loadCollections(),app.store.loadSettings(),app.store.loadOAuth2Providers())});var se=app.pb.collection;app.pb.collection=function(e){let n=se.call(this,e);return ce(n),n};function ce(e){if(e.__customUIEvents)return;e.__customUIEvents=!0;let n=e.create;e.create=function(){return n.apply(e,arguments).then(e=>(setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:create`,{detail:e})),document.dispatchEvent(new CustomEvent(`record:save`,{detail:e}))},0),e))};let r=e.update;e.update=function(){return r.apply(e,arguments).then(e=>(setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:update`,{detail:e})),document.dispatchEvent(new CustomEvent(`record:save`,{detail:e}))},0),e))};let i=e.delete;e.delete=function(){return i.apply(e,arguments).then(n=>{let r={id:arguments[0],collectionId:e.collectionIdOrName,collectionName:e.collectionIdOrName};return setTimeout(()=>{document.dispatchEvent(new CustomEvent(`record:delete`,{detail:r}))},0),n})}}var le=`pbLastFileToken`,x=!1,ue=[];app.pb.authStore.onChange((e,n)=>{n?.id||window.localStorage.removeItem(le)}),window.app.getFileToken=async function(n=``){let r=n&&app.store.collections?.find(e=>e.id==n||e.name==n);if(r&&!r.fields?.find(e=>e.type==`file`&&e.protected))return;let i=window.localStorage.getItem(le);return(!i||e(i,60))&&(i=await S()),i};async function S(){return new Promise(async(e,n)=>{if(ue.push({resolve:e,reject:n}),!x){x=!0;try{let e=await app.pb.files.getToken();window.localStorage.setItem(le,e),ue.forEach(n=>n.resolve(e))}catch(e){ue.forEach(n=>n.reject(e))}x=!1,ue=[]}})}window.app.checkApiError=function(e,n=!0){if(!e||!(e instanceof Error)||e.isAbort){console.warn(`checkApiError - unexpected error type:`,e);return}let r=e?.status<<0,i=e?.response||{},a=n&&(i.message||e.message||`Something went wrong!`);if(a&&app.toasts.error(a),r==0&&console.log(e),app.utils.isEmpty(i.data)||(app.store.errors=i.data),r===401&&window.location.hash!=y)return app.utils.rememberPath(),app.pb.cancelAllRequests(),app.pb.authStore.clear();r===403&&(app.pb.cancelAllRequests(),window.location.hash!=y&&(window.location.hash=y))};function de(){return()=>{if(!(!app.store._ready||!app.store.showHeader||!app.store.superuser?.id))return t.header({pbEvent:`appHeader`,rid:`appHeader`,className:`app-header accent-surface`,onmount:async e=>{await new Promise(e=>setTimeout(e,0)),e._scrollToActiveMenuItem=function(){e?.querySelector(`.app-main-nav .header-link.active`)?.scrollIntoView()},e._scrollToActiveMenuItem(),window.addEventListener(`hashchange`,e._scrollToActiveMenuItem)},onunmount:e=>{window.removeEventListener(`hashchange`,e?._scrollToActiveMenuItem)}},t.a({href:`#/`,className:`logo`},t.img({src:()=>app.store.headerLogo,alt:`App logo`})),t.nav({pbEvent:`mainNav`,className:`app-main-nav`},()=>app.store.headerLinks.map(e=>{let n=e.href.startsWith(`#/`);return t.a({href:()=>e.href,target:()=>n?void 0:`_blank`,rel:()=>n?void 0:`noopener noreferrer`,className:n=>`header-link ${e.isActive?.(n)||app.utils.isActivePath(e.href)?`active`:``}`},()=>{if(e.icon)return t.i({className:e.icon,ariaHidden:!0})},t.span({className:`txt`},()=>e.label))})),t.div({className:`flex-fill app-header-separator`}),C(),t.button({className:`header-link logged-user txt-normal`,"html-popovertarget":`logged-user-dropdown`},t.span({className:`superuser-name txt-ellipsis`},()=>app.store.superuser?.email),t.i({className:`ri-arrow-drop-down-line`,ariaHidden:!0})),t.div({pbEvent:`loggedUserDropdown`,id:`logged-user-dropdown`,className:`dropdown sm nowrap logged-user-dropdown`,popover:`auto`},t.a({className:`dropdown-item dropdown-item-manage`,href:`#/collections?collection=_superusers`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover()}},t.i({className:`ri-group-line`,ariaHidden:!0}),t.span({className:`txt`},`Manage superusers`)),t.hr(),t.button({type:`button`,className:`dropdown-item txt-danger dropdown-item-logout`,onclick:()=>app.pb.authStore.clear()},t.i({className:`ri-logout-circle-line`,ariaHidden:!0}),t.span({className:`txt`},`Logout`))))}}function C(){let e=[{value:`light`,icon:`ri-sun-line`,label:`Light`},{value:`dark`,icon:`ri-moon-line`,label:`Dark`},{value:``,icon:`ri-subtract-line`,label:`Auto`}];return[t.button({className:`header-link color-scheme-picker`,"html-popovertarget":`color-scheme-dropdown`,title:`Color scheme`},t.i({className:()=>app.store.activeColorScheme==`dark`?`ri-moon-line`:`ri-sun-line`,ariaHidden:!0})),t.div({pbEvent:`colorSchemeDropdown`,id:`color-scheme-dropdown`,className:`dropdown sm nowrap color-scheme-dropdown`,popover:`auto`},()=>e.map(e=>t.button({type:`button`,className:()=>`dropdown-item dropdown-item-light ${app.store.userColorScheme==e.value?`active`:``}`,onclick:n=>{n.target.closest(`.dropdown`).hidePopover(),app.store.userColorScheme=e.value}},t.i({className:e.icon,ariaHidden:!0}),t.span({className:`txt`},e.label))))]}document.addEventListener(`invalid`,e=>{let n=e.target.closest(`details`);n&&!n.open&&!e.target.closest(`summary`)&&(n.open=!0,e.target.reportValidity&&e.target.reportValidity())},!0);var w=`dropdown-item`;document.addEventListener(`toggle`,e=>{if(e.newState!=`open`||!e.target?.matches(`.dropdown`)||e.target.__keyboardNavRegistered)return;e.target.__keyboardNavRegistered=!0;let n=e.target;function r(e){if(!n.isConnected){document.removeEventListener(`keydown`,r);return}let i;if(i=document.activeElement&&document.activeElement.classList.contains(w)?document.activeElement:n.querySelector(`.`+w+`:not([hidden]):not(.disabled)`),i){if(e.key==`ArrowUp`){e.preventDefault();let n=E(i,-1);i==document.activeElement&&n?.classList?.contains(w)?n?.focus():i.focus()}else if(e.key==`ArrowDown`){e.preventDefault();let n=E(i,1);i==document.activeElement&&n?.classList?.contains(w)?n?.focus():i.focus()}else if(e.keyCode>=65&&e.keyCode<=90||e.keyCode>=48&&e.keyCode<=57){let e=n.querySelectorAll(`input,textare,select`);e.length==1&&e[0].focus()}}}n.addEventListener(`toggle`,e=>{e.newState==`open`?(T(e.target.id,!0),document.addEventListener(`keydown`,r)):(T(e.target.id,!1),document.removeEventListener(`keydown`,r))})},!0);function T(e,n=!1){e&&document.querySelectorAll(`[popovertarget='`+e+`']`)?.forEach(e=>e.setAttribute(`data-popover-state`,n))}function E(e,n=-1){let r=n<0?e.previousElementSibling:e.nextElementSibling;return r&&(r.hidden||r.classList.contains(`disabled`)||!r.classList.contains(w))?E(r,n):r}var D=5,O=t.div({ariaHidden:!0,popover:`manual`,className:`pb-tooltip`});document.body.appendChild(O);function k(e,n){let r=e.getBoundingClientRect();O.setAttribute(`data-position`,n),O.style.top=`0px`,O.style.left=`0px`;let i=O.offsetHeight,a=O.offsetWidth,o=0,s=0;n==`left`?(o=r.top+r.height/2-i/2,s=r.left-a-D):n==`right`?(o=r.top+r.height/2-i/2,s=r.right+D):n==`top`?(o=r.top-i-D,s=r.left+r.width/2-a/2):n==`top-left`?(o=r.top-i-D,s=r.left):n==`top-right`?(o=r.top-i-D,s=r.right-a):n==`bottom-left`?(o=r.top+r.height+D,s=r.left):n==`bottom-right`?(o=r.top+r.height+D,s=r.right-a):(o=r.top+r.height+D,s=r.left+r.width/2-a/2),s+a>document.documentElement.clientWidth&&(s=document.documentElement.clientWidth-a),s=s>=0?s:0,o+i>document.documentElement.clientHeight&&(o=document.documentElement.clientHeight-i),o=o>=0?o:0,O.style.top=o+`px`,O.style.left=s+`px`}function A(){O.hidePopover()}function fe(e,n,r){if(!e||!n){A();return}O.showPopover(),O.textContent=n,k(e,r)}document.body.addEventListener(`mouseleave`,()=>{A()});function pe(e,n=`top`){return r=>{if(!r._tooltipText){r._tooltipText=store({value:``});let e;function i(){e?.unwatch(),e=watch(()=>r._tooltipText.value,async e=>{fe(r,e,n)})}async function a(){e?.unwatch(),e=null,A()}r.addEventListener(`mouseenter`,i),r.addEventListener(`focusin`,i),r.addEventListener(`mouseleave`,a),r.addEventListener(`focusout`,a),r.addEventListener(`blur`,a);let o=r.onunmount;r.onunmount=n=>{e?.unwatch(),n._tooltipText=null,n?.removeEventListener(`mouseenter`,i),n?.removeEventListener(`focusin`,i),n?.removeEventListener(`mouseleave`,a),n?.removeEventListener(`focusout`,a),n?.removeEventListener(`blur`,a),o(n)}}return typeof e==`function`?r._tooltipText.value=e():r._tooltipText.value=e,r._tooltipText.value}}window.app=window.app||{},window.app.attrs=window.app.attrs||{},window.app.attrs.tooltip=pe,window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.confirm=function(e,n,r,i={className:void 0,yesButton:``,noButton:``}){j.textOrElem=e,j.yesCallback=n,j.yesCallbackWaiting=!1,j.noCallback=r,j.noCallbackWaiting=!1,j.className=typeof i.className==`string`?i.className:`sm`,j.yesButton=i.yesButton||`Yes`,j.noButton=i.noButton||`No`,me.isConnected||document.body.appendChild(me),window.app.modals.open(me)};var j=store({className:``,textOrElem:null,yesButton:``,yesCallback:null,yesCallbackWaiting:!1,noButton:``,noCallback:null,noCallbackWaiting:!1,get isBusy(){return j.yesCallbackWaiting||j.noCallbackWaiting}}),me=t.div({className:()=>`modal popup manual ${j.className||``}`},t.div({className:`modal-content`},e=>typeof j.textOrElem==`string`?t.h6({className:`block txt-center`},j.textOrElem):typeof j.textOrElem==`function`?j.textOrElem(e):j.textOrElem),t.footer({className:`modal-footer p-sm`},t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.button({type:`button`,className:()=>`btn lg block secondary ${j.noCallbackWaiting?`loading`:``}`,disabled:()=>j.isBusy,onclick:async()=>{if(j.noCallback){j.noCallbackWaiting=!0;try{if(await j.noCallback()===!1)return}catch(e){console.log(`confirm noCallback error:`,e)}finally{j.noCallbackWaiting=!1}}window.app.modals.close(me)}},()=>typeof j.noButton==`string`?t.span({className:`txt`},j.noButton):typeof j.noButton==`function`?j.noButton(el):j.noButton)),t.div({className:`col-sm-6`},t.button({type:`button`,className:()=>`btn lg block warning ${j.yesCallbackWaiting?`loading`:``}`,disabled:()=>j.isBusy,onclick:async()=>{if(j.yesCallback){j.yesCallbackWaiting=!0;try{if(await j.yesCallback()===!1)return}catch(e){console.log(`confirm yesCallback error:`,e)}finally{j.yesCallbackWaiting=!1}}window.app.modals.close(me)}},()=>typeof j.yesButton==`string`?t.span({className:`txt`},j.yesButton):typeof j.yesButton==`function`?j.yesButton(el):j.yesButton)))));window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.dragline=function(e={}){let n,r=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,tolerance:0,ondragstart:function(e){},ondragstop:function(e){},ondragging:function(e,n,r){}}),i=app.utils.extendStore(r,e),a=store({dragStarted:!1}),o,s,c,l;function u(){document.addEventListener(`touchmove`,m),document.addEventListener(`mousemove`,m),document.addEventListener(`touchend`,p),document.addEventListener(`mouseup`,p)}function d(){document.removeEventListener(`touchmove`,m),document.removeEventListener(`mousemove`,m),document.removeEventListener(`touchend`,p),document.removeEventListener(`mouseup`,p)}function f(e){e.stopPropagation(),o=e.clientX,s=e.clientY,c=e.clientX-n.offsetLeft,l=e.clientY-n.offsetTop,u()}function p(e){a.dragStarted&&(e.preventDefault(),a.dragStarted=!1,r.ondragstop?.(e)),d()}function m(e){let i=e.clientX-o,u=e.clientY-s,d=e.clientX-c,f=e.clientY-l;!a.dragStarted&&Math.abs(d-n.offsetLeft)r.id,hidden:()=>r.hidden,inert:()=>r.inert,className:()=>`dragline ${a.dragStarted?`dragging`:``} ${r.className}`,onmousedown:e=>{e.button==0&&f(e)},ontouchstart:f,onunmount:()=>{d(),i.forEach(e=>e?.unwatch())}}),n},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.slide=function(e,...n){let r;return t.div({className:n=>`block slide-block ${e?.(n)?``:`hidden`}`,onmount:e=>{r=setTimeout(()=>{e?.setAttribute(`data-slide`,`1`)},200)},onunmount:()=>{clearTimeout(r)}},...n)},window.app=window.app||{},window.app.modals=window.app.modals||{};var M=`data-modal-state`,he=`manual`,ge;window.app.modals.open=async function(e){if(!e?.isConnected){console.error(`modals.open requies an active DOM element`,e);return}let n;if(e.onbeforeopen&&(n=await e.onbeforeopen(e)),n===!1)return;if(e.onafteropen){let n=new ResizeObserver(r=>{for(let i of r)i.contentRect.height>0&&e?.onafteropen&&(e.onafteropen(e),n.disconnect(),n=null)});n.observe(e)}ge=document.activeElement,_e(e),e._forceClose=()=>app.modals.close(e,!0),window.addEventListener(`popstate`,e._forceClose);let r=Math.max(ve(e)?.style.zIndex<<0,1e3);e.style.zIndex=r+1,e.setAttribute(M,`open`)},window.app.modals.close=async function(e=null,n=!1){if(e||=ve(),e){if(window.removeEventListener(`popstate`,e._forceClose),n)e.onbeforeclose?.(e,!0),e.setAttribute(M,`close`),e.onafterclose?.(e,!0);else{if(e.onbeforeclose&&await e.onbeforeclose(e,!1)===!1)return;if(e.onafterclose){let n=new ResizeObserver(r=>{for(let i of r)i.contentRect.height<=0&&e?.onafterclose&&(e.onafterclose(e,!1),n.disconnect(),n=null)});n.observe(e)}e.setAttribute(M,`close`)}ge&&(ge.focus?.(),setTimeout(()=>{ge?.blur?.(),ge=null},0))}};function _e(e){if(e.getAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),setTimeout(()=>{let n=e?.querySelector(`[autofocus]`);n?n.focus():e?.focus()},0),e.getAttribute(M))return;e.setAttribute(M,``),e.addEventListener(`keydown`,n=>{n.key!=`Escape`||e.classList.contains(he)||n.target!==e&&e.contains(n.target)||window.app.modals.close(e)});let n=!1,r=r=>{n=r.target!==e&&e.contains(r.target)};e.addEventListener(`mousedown`,r),e.addEventListener(`touchstart`,r);let i=!1,a=n=>{i=n.target!==e&&e.contains(n.target)};e.addEventListener(`mouseup`,a),e.addEventListener(`touchend`,a),e.addEventListener(`click`,r=>{n||i||e.classList.contains(he)||r.target!==e&&e.contains(r.target)||window.app.modals.close(e)})}function ve(e){let n=document.querySelectorAll(`[${M}="open"]`),r=0,i=0,a;for(let o of n)e&&o==e||(r=o.style.zIndex<<0,r>i&&(i=r,a=o));return a}var ye=new Map,be=t.div({className:`toasts-container`});function xe(e,n=!0){let r=ye.get(e);!r||!r.isConnected||(ye.delete(e),clearTimeout(r._removeTimeout),n?(r.classList.add(`removing`),setTimeout(()=>{r.remove()},300)):r.remove())}function Se(e=!0){ye.forEach((n,r)=>{window.app.toasts.remove(r,e)})}function Ce(e,n={}){n.type=`info`,n.duration=n.duration||3e3,Ee(e,n)}function we(e,n={}){n.type=`success`,n.duration=n.duration||3e3,Ee(e,n)}function Te(e,n={}){n.type=`error`,n.duration=n.duration||3500,Ee(e,n)}function Ee(e,n={}){n=Object.assign({duration:3e3,key:void 0,type:`info`},n),be.isConnected||document.body.appendChild(be);let r=n.key||e;ye.has(r)&&xe(r,!1);function i(e){e?._removeTimeout&&clearTimeout(e?._removeTimeout),e._removeTimeout=setTimeout(()=>{xe(r)},n.duration)}let a=t.div({className:`toast ${n.type||``}`,onmount:e=>{i(e)},onunmount:e=>{e?._removeTimeout&&(clearTimeout(e?._removeTimeout),a=null)},onmouseover:()=>{clearTimeout(a?._removeTimeout)},onmouseout:()=>{i(a)}},t.div({className:`toast-container`},t.div({className:`toast-icon`}),t.div({className:`toast-content`},e,t.button({className:`m-l-auto btn circle sm transparent secondary toast-remove`,title:`Clear`,onclick:()=>xe(r)},t.i({className:`ri-close-line`,ariaHidden:!0})))));ye.set(r,a),be.prepend(a)}window.app=window.app||{},window.app.toasts=window.app.toasts||{},window.app.toasts.info=Ce,window.app.toasts.error=Te,window.app.toasts.success=we,window.app.toasts.remove=xe,window.app.toasts.removeAll=Se,window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.sortable=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,data:[],dataItem:function(e,n,r){return t.span(null,`Item `+n)},onchange:function(e,n,r){},handle:``,before:void 0,after:void 0}),r=app.utils.extendStore(n,e);function i(e){function r(){e.querySelectorAll(`:scope > [data-dragstart="true"]`)?.forEach(e=>{e.dataset.dragstart=!1}),e.querySelectorAll(`:scope > [data-dragover="true"]`)?.forEach(e=>{e.dataset.dragover=!1})}e.addEventListener(`dragstart`,r=>{if(n.handle&&!r.target.closest(n.handle)){r.preventDefault();return}let i=o(e,r.target);i&&(i.dataset.dragstart=!0)}),e.addEventListener(`dragenter`,n=>{for(let n of e.children)n.dataset.dragover&&(n.dataset.dragover=!1);let r=o(e,n.target);r&&(r.dataset.dragover=!0)}),e.addEventListener(`dragend`,e=>{r()}),e.addEventListener(`dragover`,e=>{e.preventDefault()}),e.addEventListener(`drop`,i=>{if(!n.onchange){r();return}let s=e.querySelector(`:scope > [data-dragstart="true"]`),c=o(e,i.target);if(r(),!s||!c||c==s)return;let l=a(s),u=a(c),d=n.data.slice(),f=d.splice(l,1);d.splice(u,0,f[0]),n.onchange(d,l,u)})}function a(e){if(!e?.parentNode)return-1;for(let n=0;nn.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>n.className,onmount:e=>{i(e)},onunmount:e=>{r.forEach(e=>e?.unwatch())}},e=>typeof n.before==`function`?n.before(e):n.before,e=>{let r=[];for(let i=0;itypeof n.after==`function`?n.after(e):n.after)},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.copyButton=function(e,...n){let r=store({active:!1}),i;function a(){let n=e;typeof n==`function`&&(n=e()),app.utils.copyToClipboard(n),r.active=!0,clearTimeout(i),i=setTimeout(()=>{r.active=!1},500)}return t.button({tabIndex:-1,type:`button`,className:()=>`copy-to-clipboard ${r.active?`active`:``}`,title:`Copy`,ariaDescription:app.attrs.tooltip(()=>r.active?`Copied`:null),onclick:e=>{e.preventDefault(),e.stopPropagation(),a()}},t.i({hidden:n?.length,ariaHidden:!0,className:()=>`copy-icon ${r.active?`ri-check-double-line`:`ri-file-copy-line`}`}),...n)},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeBlock=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,language:`js`,value:void 0,footnote:void 0}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`code-wrapper ${n.className}`,tabIndex:-1,onmount:e=>{e.addEventListener(`keydown`,n=>{(n.ctrlKey||n.metaKey)&&(n.key==`a`||n.key==`A`)&&(n.preventDefault(),window.getSelection().selectAllChildren(e))})},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.code({className:`block`,innerHTML:()=>De(n.value,n.language)}),t.div({className:`footnote`},e=>typeof n.footnote==`function`?n.footnote(e):n.footnote))};function De(e,n){return e=typeof e==`string`?e:``,e=Prism.plugins.NormalizeWhitespace.normalize(e,{"remove-trailing":!0,"remove-indent":!0,"left-trim":!0,"right-trim":!0}),Prism.highlight(e,Prism.languages[n]||Prism.languages.js,n)}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeEditor=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,name:void 0,className:``,value:``,language:`js`,placeholder:``,disabled:!1,required:!1,singleLine:!1,autocomplete:void 0,oninput:function(e,n){},onfocus:function(e,n){},onblur:function(e,n){}}),r=app.utils.extendStore(n,e,`autocomplete`),i,a,o=!0;function s(e){c(),i=t.div({className:`dropdown autocomplete code-editor-dropdown`,onmount:e=>{e._updatePosition=()=>{o?Fe(i):c()},e._closeOnEsc=e=>{e.key==`Escape`&&(e.preventDefault(),c())},window.addEventListener(`scroll`,e._updatePosition,!0),window.addEventListener(`resize`,e._updatePosition),window.addEventListener(`keydown`,e._closeOnEsc),e._updatePosition()},onunmount:e=>{e&&(window.removeEventListener(`scroll`,e._updatePosition,!0),window.removeEventListener(`resize`,e._updatePosition),window.removeEventListener(`keydown`,e._closeOnEsc))}},e),document.body.appendChild(i),d&&(a?.disconnect(),a=new IntersectionObserver(([e])=>{o=e.isIntersecting},{root:null,threshold:.1}),a.observe(d))}function c(){i&&=(i.remove(),null),a&&=(a.disconnect(),null),o=!0}let l=!1,u,d=t.div({contentEditable:()=>n.disabled?!1:`plaintext-only`,tabIndex:0,spellcheck:!1,autocorrect:!1,autocomplete:`off`,autocapitalize:`off`,role:`textbox`,className:`editor-content`,"html-data-placeholder":()=>n.placeholder,onmount:e=>{u?.unwatch(),u=watch(()=>n.value,e=>{e!=d.textContent&&(d.textContent=e,c())})},onunmount:e=>{u?.unwatch(),c()},onfocus:e=>{n.onfocus?.(n.value,e)},onblur:e=>{i&&!i.contains(e.relatedTarget)&&c(),n.onblur?.(n.value,e)},oninput:e=>{if(c(),n.value=d.textContent,n.oninput?.(n.value,e),d.dispatchEvent(new CustomEvent(`change`,{detail:n.value})),!n.value?.length){d.textContent=``;return}if(!d?.isConnected)return;let r=Pe(d),i=je(n.value,r);if(!i.word.length||r==i.start)return;let a=[];if(typeof n.autocomplete==`function`)a=n.autocomplete(i.word)||[];else if(!app.utils.isEmpty(n.autocomplete)){let e=i.word.toLowerCase();a=n.autocomplete.filter(n=>(typeof n==`object`&&(n=n?.value),n=n?.toLowerCase(),n&&n!=e&&n.includes(e)))}a?.length&&s(()=>a.map((e,r)=>t.button({type:`button`,className:`dropdown-item ${r==0?`active`:``}`,textContent:e.label||e.value||e,onclick:r=>{r.preventDefault(),d.focus();let a=e.value||e;d.textContent=d.textContent.substring(0,i.start)+a+d.textContent.substring(i.end+1),n.value=d.textContent;try{window.getSelection().setPosition(d.childNodes[0],i.start+a.length)}catch(e){console.warn(`failed to set caret position`,e)}c()}})))},onkeydown:e=>{if(l=e.ctrlKey||e.metaKey,(e.key==`Enter`||e.key==`Tab`)&&i?.isConnected){e.preventDefault(),i.querySelector(`.dropdown-item.active`)?.click();return}if(e.key==`ArrowUp`&&i?.isConnected){e.preventDefault();let n=i.querySelector(`.dropdown-item.active`);n?.previousElementSibling&&(n.classList.remove(`active`),n.previousElementSibling.classList.add(`active`),n.previousElementSibling.scrollIntoView(!1));return}if(e.key==`ArrowDown`&&i?.isConnected){e.preventDefault();let n=i.querySelector(`.dropdown-item.active`);n?.nextElementSibling&&(n.classList.remove(`active`),n.nextElementSibling.classList.add(`active`),n.nextElementSibling.scrollIntoView(!1));return}if(l&&e.key.toLowerCase()==`l`){e.preventDefault(),Me(d);return}if(l&&e.key.toLowerCase()==`d`){e.preventDefault(),Ne(d);return}if(!n.singleLine&&e.key==`Tab`){e.preventDefault();let r=window.getSelection();if(!r)return;if(e.shiftKey){r.modify(`extend`,`backward`,`character`),r.toString()[0]==` `?(r.deleteFromDocument(),n.value=d.textContent):(r.modify(`extend`,`forward`,`character`),r.toString()[0]==` `&&(r.deleteFromDocument(),n.value=d.textContent));return}let i=r.getRangeAt(0);i&&(i.deleteContents(),i.insertNode(document.createTextNode(` `)),i.collapse(),n.value=d.textContent);return}if(n.singleLine&&e.key==`Enter`){e.preventDefault(),p.click();return}},onscroll:()=>{c(),f&&(f.scrollLeft=d.scrollLeft,f.scrollTop=d.scrollTop)}}),f=t.div({className:`highlight-overlay`,innerHTML:()=>ke(n.value,n.language),onscroll:()=>{d&&(d.scrollLeft=f.scrollLeft,d.scrollTop=f.scrollTop)}}),p=t.button({type:`submit`,className:`hidden`});return t.div({rid:n.rid,id:()=>n.id,inert:()=>n.inert,hidden:()=>n.hidden,"html-name":()=>n.name,"html-required":()=>n.required||void 0,className:()=>`input code-editor ${n.className} ${n.disabled?`disabled`:``} ${n.singleLine?`single-line`:``}`,onclick:()=>{d?.focus()},onunmount:()=>{r?.forEach(e=>e?.unwatch())}},t.div({className:`code-editor-container`},d,f,p))};var Oe=500;function ke(e,n){return e=typeof e==`string`?e:``,e?((!Prism.languages[n]||e.length>Oe)&&(n=`plain`),Prism.highlight(e,Prism.languages[n],n)):``}var Ae=new RegExp(/[\p{Alphabetic}\p{Number}_@:\."'{}]/,`u`);function je(e,n){let r=n;for(let i=n-1;i>=0&&Ae.test(e[i]);i--)r=i;let i=r;for(let r=n-1;rdocument.documentElement.clientHeight&&(o=Math.max(n.top-r,0)),a+i>document.documentElement.clientWidth&&(a=Math.max(document.documentElement.clientWidth-i,0)),e.style.left=a+`px`,e.style.top=o+`px`}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.codeBlockTabs=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,activeTabIndex:0,historyKey:``,tabs:[],get activeTab(){return n.tabs[n.activeTabIndex]||n.tabs[0]}}),r=app.utils.extendStore(n,e);return r.push(watch(()=>n.activeTabIndex,(e,r)=>{r!=null&&n.historyKey&&localStorage.setItem(n.historyKey,e)})),t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden||!n.tabs.length,inert:()=>n.inert,className:()=>`code-block-tabs ${n.className}`,onmount:()=>{n.historyKey&&(n.activeTabIndex=localStorage.getItem(n.historyKey)<<0)},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.header({className:`tabs-header`},()=>n.tabs.map((e,r)=>t.button({type:`button`,className:()=>`tab-item ${n.activeTabIndex==r?`active`:``}`,onclick:()=>n.activeTabIndex=r},n=>typeof e.title==`function`?e.title(n):e.title))),t.div({className:`code-block-tabs-content`},()=>{if(n.activeTab)return app.components.codeBlock(n.activeTab)}))},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.select=function(e={}){let n=store({rid:void 0,id:void 0,name:void 0,hidden:void 0,inert:void 0,className:``,value:void 0,options:[],before:null,after:null,max:1,searchThreshold:6,required:!1,disabled:!1,placeholder:`- Select -`,noItemsFoundText:`No items found`,onchange:function(e){},ondropdowntoggle:function(e){}}),r=app.utils.extendStore(n,e);n.max<=0&&(n.max=1);let i=store({selected:[],search:``,get hasSearch(){return i.search?.length>0},get allowRemove(){return!n.disabled&&(!n.required||n.max>1)}});function a(){if(n.value===void 0)return;let e=app.utils.toArray(n.value,!0),r=e.slice(0,n.max||1);e.length!=r.length&&(console.warn(`[select] the provided select values (${e.length}) are more than the allowed max selected options (${r.length}):`,e),n.value=n.max>1?r:r[0]),i.selected=e.map(e=>n.options.find(n=>n.value===e)).filter(Boolean)}r.push(watch(()=>n.value,()=>a()));async function o(e){let r=i.selected.findIndex(n=>n.value===e.value);if(r>=0){if(!i.allowRemove){f?.hidePopover();return}i.selected.splice(r,1)}else{let r=i.selected.length-n.max;for(;r>=0;)i.selected.pop(),r--;i.selected.push(e)}n.max<=1&&f?.hidePopover(),n.onchange&&(await n.onchange(i.selected),a()),p?.isConnected&&p.dispatchEvent(new CustomEvent(`change`,{detail:i.selected,bubbles:!0}))}function s(e){return i.selected.findIndex(n=>n.value===e.value)>=0}let c=t.input({type:`text`,placeholder:`Search...`,value:()=>i.search,oninput:e=>i.search=e.target.value});function l(e=!1){i.search=``,e&&c?.focus()}let u=t.div({className:`txt-hint txt-center m-0 p-5`,hidden:!0},n.noItemsFoundText);async function d(){f&&(await new Promise(e=>setTimeout(e,0)),f.querySelector(`.select-option:not([hidden])`)?u.hidden=!0:u.hidden=!1)}let f=t.div({tabIndex:-1,popover:`auto`,className:`dropdown`,onbeforetoggle:e=>(e.newState==`closed`&&l(),n.ondropdowntoggle?.(e))},t.div({className:`fields dropdown-search`,hidden:()=>n.options.length!i.hasSearch},t.button({type:`button`,title:`Clear`,className:`btn sm secondary transparent circle`,onclick:()=>l(!0)},t.i({className:`ri-close-line`,ariaHidden:!0})))),()=>n.before?.__raw||n.before,()=>n.options.map(e=>t.button({type:`button`,className:()=>`dropdown-item select-option ${s(e)?`active`:``}`,onclick:()=>(o(e),!1)},e.label||e.value)),u,()=>n.after?.__raw||n.after),p=t.button({type:`button`,id:()=>n.id,name:()=>n.name,disabled:()=>n.disabled,className:()=>`selected-container ${n.className}`,popoverTargetElement:f,onclick:e=>{e.stopPropagation()}},()=>i.selected.length?i.selected.map(e=>t.div({className:`selected-item`},e.selected||e.label||e.value,()=>{if(i.allowRemove)return t.i({tabIndex:-1,role:`button`,className:`ri-close-line link-hint btn-option-unset`,ariaLabel:app.attrs.tooltip(`Unset`,`left`),onclick:()=>(o(e),!1)})})):t.span({rid:`selected-placeholder`,className:`placeholder`},()=>n.placeholder));r.push(watch(()=>n.options,()=>{d()}));let m;return r.push(watch(()=>i.search,()=>{let e=i.search.toLowerCase().replaceAll(` `,``);clearTimeout(m),m=setTimeout(()=>{let n=f.querySelectorAll(`.select-option`);e.length?n.forEach(n=>{n.textContent.toLowerCase().replaceAll(` `,``).includes(e)?n.hidden=!1:n.hidden=!0}):n.forEach(e=>e.hidden=!1),d()},100)})),t.div({rid:n.rid,hidden:()=>n.hidden,inert:()=>n.inert,onmount:e=>{e.addEventListener(`focusout`,function(n){(!n.relatedTarget||!e.contains(n.relatedTarget))&&f?.hidePopover()})},onunmount:()=>{clearTimeout(m),r.forEach(e=>e.unwatch())},className:()=>[`input`,`select`,n.max>1?`multiple`:`single`,n.disabled?`disabled`:``,n.required?`required`:``].join(` `)},p,f)},window.app=window.app||{},window.app.components=window.app.components||{};var Ie=Intl.DateTimeFormat().resolvedOptions().timeZone;window.app.components.formattedDate=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,value:``,short:!1}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,ariaDescription:app.attrs.tooltip(()=>n.short&&n.value?app.utils.toLocalDatetime(n.value)+` @@ -25,7 +25,7 @@ import{a as e,n,r,t as i}from"./pocketbase.es-B_4DUNUU.js";var a=Object.create,o `;let _=g.querySelector(`.paths-group`);return a=t.div({tabIndex:-1,rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`erd ${n.className} ${i.isUpdating?`updating`:``} ${i.isPanning?`panning`:``} ${i.activeCollection?`active`:``}`,onkeydown:e=>{(e.ctrlKey||e.metaKey)&&e.key==`0`&&f()},onmount:async e=>{e.addEventListener(`wheel`,r=>{r.preventDefault();let a=e.getBoundingClientRect(),o=r.clientX-a.left,s=r.clientY-a.top,c=(o-i.viewX)/n.scale,l=(s-i.viewY)/n.scale,u=Math.min(Math.max(-r.deltaY*.001+n.scale,$e),Qe);i.viewX=o-c*u,i.viewY=s-l*u,n.scale=u}),e.addEventListener(`pointerdown`,e=>{e.buttons==1&&(i.isPanning=!0,i.panStartX=e.clientX-i.viewX,i.panStartY=e.clientY-i.viewY)}),e._ondragging=function(e){i.isPanning&&(i.viewX=e.clientX-i.panStartX,i.viewY=e.clientY-i.panStartY)},e._ondragstop=function(){i.isPanning=!1},window.addEventListener(`pointermove`,e._ondragging),window.addEventListener(`pointerup`,e._ondragstop),c()},onunmount:e=>{window.removeEventListener(`pointermove`,e._ondragging),window.removeEventListener(`pointerup`,e._ondragstop),r.forEach(e=>e?.unwatch())}},t.div({className:`erd-area`,style:()=>`transform: translate(${i.viewX}px, ${i.viewY}px) scale(${n.scale});`},m,t.div({className:`erd-tables`},()=>n.collections.map(e=>t.div({style:()=>`left:${i.positions[e.id]?.x||0}px;top:${i.positions[e.id]?.y||0}px`,className:()=>`erd-table type-${e.type} ${p(e)?`active`:``} ${e.system?`system`:``}`,"html-data-collection-id":()=>e.id,"html-data-collection-name":()=>e.name,onmouseenter:()=>{h.querySelectorAll(`[data-to="${e.id}"]`)?.forEach(e=>{e.classList.add(`active-to`),_.append(e)}),h.querySelectorAll(`[data-from="${e.id}"]`)?.forEach(e=>{e.classList.add(`active-from`),_.append(e)}),i.activeCollection=e},onmouseleave:()=>{for(let e of _.children)e.classList.remove(`active-from`,`active-to`);h.append(..._.children),i.activeCollection=null}},t.div({className:`erd-table-row header`},()=>e.name),()=>e.fields?.map(e=>t.div({className:`erd-table-row type-${e.type} ${e.primaryKey?`primary-key`:``}`,"html-data-field-id":()=>e.id,"html-data-field-name":()=>e.name},t.i({ariaHidden:!0,title:()=>e.type,className:()=>`field-icon ${app.fieldTypes[e.type].icon||app.utils.fallbackFieldIcon}`}),t.span({className:`field-name`},()=>e.name),()=>{if(e.hidden)return t.span({className:`label danger field-hidden-label`},`Hidden`)},()=>{if(e.maxSelect!==void 0)return t.span({className:`meta`},e.maxSelect>1?`multiple`:`single`)}))))),g),t.nav({className:`erd-nav`,onmousedown:e=>{e.stopImmediatePropagation()}},t.button({type:`button`,className:`btn sm circle secondary`,title:`Zoom in`,onclick:()=>{n.scale+=.05}},t.i({className:`ri-add-line`,ariaHidden:!0})),t.button({type:`button`,className:`btn sm circle secondary`,title:`Zoom out`,onclick:()=>{n.scale-=.05}},t.i({className:`ri-subtract-line`,ariaHidden:!0})))),a};function tt(e,n,r=1,i=``,a=``,o=2){if(!e||!n)return;let s=e.closest(`.erd-area`).getBoundingClientRect(),c=e.getBoundingClientRect(),l=n.getBoundingClientRect();o*=r;let u=c.top-s.top+c.height/2,d=l.top-s.top+l.height/2,f,p;c.leftl.left?(f=c.left-s.left-o,p=l.left-s.left+l.width+o):(f=c.left-s.left-o,p=l.left-s.left-o),f/=r,p/=r,u/=r,d/=r;let m=f+(p-f)/2;f==p&&(m-=20);let h=`M ${f} ${u} L ${m} ${u} L ${m} ${d} - L ${p} ${d}`,g=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return g.setAttribute(`class`,`relation-path`),g.setAttribute(`data-from`,i||``),g.setAttribute(`data-to`,a||``),g.setAttribute(`d`,h),g}window.app=window.app||{},window.app.components=window.app.components||{};var N=1e3;window.app.components.pageSidebar=function(e={},...n){let r,i=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,widthHistoryKey:`pbPageSidebarWidth`,onmount:void 0,onunmount:void 0}),a=app.utils.extendStore(i,e),o=store({responsiveShow:!1}),s;function c(){if(r){if(window.innerWidth>N){o.responsiveShow=!1,r.dataset.responsive=!1,s?.remove(),s=null;return}r.dataset.responsive=!0,s||(s=t.button({type:`button`,className:`btn transparent secondary responsive-sidebar-btn`,title:`Toggle sidebar`,onclick:e=>{e.stopPropagation(),o.responsiveShow=!o.responsiveShow}},t.i({className:`ri-menu-2-line`,ariaHidden:!0})),document.body.querySelector(`.page-header .breadcrumbs`).before(s))}}function l(e){if(e.target.closest(`.responsive-close`)){o.responsiveShow=!1;return}if(!(e.target.closest(`.page-sidebar`)||e.target.closest(`.app-header`)||e.target.closest(`.modal`)))return e.preventDefault(),e.stopImmediatePropagation(),o.responsiveShow=!1,!1}return a.push(watch(()=>o.responsiveShow,e=>{e?window.addEventListener(`click`,l,!0):window.removeEventListener(`click`,l,!0)})),r=t.aside({pbEvent:`pageSidebar`,rid:i.rid,id:()=>i.id,hidden:()=>i.hidden,inert:()=>i.inert,className:()=>`page-sidebar ${i.className} ${o.responsiveShow?`active`:``}`,onmount:e=>{c(e),window.addEventListener(`resize`,c),i.onmount?.(e)},onunmount:e=>{i.onunmount?.(e),window.removeEventListener(`click`,l,!0),window.removeEventListener(`resize`,c),s?.remove(),a.forEach(e=>e?.unwatch())}},e=>{let n;return i.widthHistoryKey&&(n=localStorage.getItem(i.widthHistoryKey),n&&(e.style.width=n)),app.components.dragline({ondragstart:n=>{e._startWidth=e.offsetWidth},ondragging:(r,a,o)=>{n=e._startWidth+a+`px`,e.style.width=n,i.widthHistoryKey&&localStorage.setItem(i.widthHistoryKey,n)}})},...n),r};var P=`modulepreload`,nt=function(e,n){return new URL(e,n).href},rt={},F=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){let e=document.getElementsByTagName(`link`),a=document.querySelector(`meta[property=csp-nonce]`),o=a?.nonce||a?.getAttribute(`nonce`);function s(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}i=s(n.map(n=>{if(n=nt(n,r),n in rt)return;rt[n]=!0;let i=n.endsWith(`.css`),a=i?`[rel="stylesheet"]`:``;if(r)for(let r=e.length-1;r>=0;r--){let a=e[r];if(a.href===n&&(!i||a.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${n}"]${a}`))return;let s=document.createElement(`link`);if(s.rel=i?`stylesheet`:P,i||(s.as=`script`),s.crossOrigin=``,s.href=n,o&&s.setAttribute(`nonce`,o),document.head.appendChild(s),i)return new Promise((e,r)=>{s.addEventListener(`load`,e),s.addEventListener(`error`,()=>r(Error(`Unable to preload CSS for ${n}`)))})}))}function a(e){let n=new Event(`vite:preloadError`,{cancelable:!0});if(n.payload=e,window.dispatchEvent(n),!n.defaultPrevented)throw e}return i.then(n=>{for(let e of n||[])e.status===`rejected`&&a(e.reason);return e().catch(a)})};window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openApiPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=it(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};function it(e,n){if(!e){console.warn(`[apiPreviewModal] missing required collection`);return}let r,i=store({activeTab:`List/Search`,tabEl:null,isLoading:!1}),a={"List/Search":async e=>{let{docsList:n}=await F(async()=>{let{docsList:e}=await import(`./docsList-BAfVNUIM.js`);return{docsList:e}},__vite__mapDeps([0,1,2,3]),import.meta.url);return i.tabEl=n(e)},View:async e=>{let{docsView:n}=await F(async()=>{let{docsView:e}=await import(`./docsView-Be6Uhvcf.js`);return{docsView:e}},__vite__mapDeps([4,1,2]),import.meta.url);return i.tabEl=n(e)}};e.type!=`view`&&(a.Create=async e=>{let{docsCreate:n}=await F(async()=>{let{docsCreate:e}=await import(`./docsCreate-Be3S3y5K.js`);return{docsCreate:e}},__vite__mapDeps([5,1,2]),import.meta.url);return i.tabEl=n(e)},a.Update=async e=>{let{docsUpdate:n}=await F(async()=>{let{docsUpdate:e}=await import(`./docsUpdate-LtD8DbWI.js`);return{docsUpdate:e}},__vite__mapDeps([6,5,1,2]),import.meta.url);return i.tabEl=n(e)},a.Delete=async e=>{let{docsDelete:n}=await F(async()=>{let{docsDelete:e}=await import(`./docsDelete-CybOn5jy.js`);return{docsDelete:e}},[],import.meta.url);return i.tabEl=n(e)},a.Realtime=async e=>{let{docsRealtime:n}=await F(async()=>{let{docsRealtime:e}=await import(`./docsRealtime-PMESvmJN.js`);return{docsRealtime:e}},[],import.meta.url);return i.tabEl=n(e)},a.Batch=async e=>{let{docsBatch:n}=await F(async()=>{let{docsBatch:e}=await import(`./docsBatch-DNJl1NTn.js`);return{docsBatch:e}},[],import.meta.url);return i.tabEl=n(e)}),e.type==`auth`&&(a[``]=null,a[`List auth methods`]=async e=>{let{docsListAuthMethods:n}=await F(async()=>{let{docsListAuthMethods:e}=await import(`./docsListAuthMethods-9feSopQX.js`);return{docsListAuthMethods:e}},__vite__mapDeps([7,2]),import.meta.url);return i.tabEl=n(e)},a[`Auth with password`]=e.passwordAuth?.enabled?async e=>{let{docsAuthWithPassword:n}=await F(async()=>{let{docsAuthWithPassword:e}=await import(`./docsAuthWithPassword-DEWj8Jyn.js`);return{docsAuthWithPassword:e}},__vite__mapDeps([8,1,2]),import.meta.url);return i.tabEl=n(e)}:null,e.name!=`_superusers`&&(a[`Auth with OAuth2`]=e.oauth2?.enabled?async e=>{let{docsAuthWithOAuth2:n}=await F(async()=>{let{docsAuthWithOAuth2:e}=await import(`./docsAuthWithOAuth2-DUIE4EoY.js`);return{docsAuthWithOAuth2:e}},__vite__mapDeps([9,1,2]),import.meta.url);return i.tabEl=n(e)}:null),a[`Auth with OTP`]=e.otp?.enabled?async e=>{let{docsAuthWithOTP:n}=await F(async()=>{let{docsAuthWithOTP:e}=await import(`./docsAuthWithOTP-B7z2VJzp.js`);return{docsAuthWithOTP:e}},__vite__mapDeps([10,1,2]),import.meta.url);return i.tabEl=n(e)}:null,a[`Auth refresh`]=async e=>{let{docsAuthRefresh:n}=await F(async()=>{let{docsAuthRefresh:e}=await import(`./docsAuthRefresh-UjveHHwo.js`);return{docsAuthRefresh:e}},__vite__mapDeps([11,1,2]),import.meta.url);return i.tabEl=n(e)},e.name!=`_superusers`&&(a.Verification=async e=>{let{docsVerification:n}=await F(async()=>{let{docsVerification:e}=await import(`./docsVerification-B_Nb90xU.js`);return{docsVerification:e}},[],import.meta.url);return i.tabEl=n(e)}),a[`Password reset`]=async e=>{let{docsPasswordReset:n}=await F(async()=>{let{docsPasswordReset:e}=await import(`./docsPasswordReset-vLO_ZWrq.js`);return{docsPasswordReset:e}},[],import.meta.url);return i.tabEl=n(e)},a[`Email change`]=async e=>{let{docsEmailChange:n}=await F(async()=>{let{docsEmailChange:e}=await import(`./docsEmailChange-B---6FKV.js`);return{docsEmailChange:e}},[],import.meta.url);return i.tabEl=n(e)});let o=[watch(()=>i.activeTab,async()=>{i.isLoading=!0,await a[i.activeTab]?.(e),i.isLoading=!1})];return r=t.div({pbEvent:`apiPreviewModal`,className:`modal api-preview-modal`,onbeforeopen:e=>n.onbeforeopen?.(e),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),o.forEach(e=>e?.unwatch()),e?.remove()},onmount:e=>{},onunmount:e=>{o.forEach(e=>e?.unwatch())}},t.div({className:`modal-content`},t.aside({className:`api-preview-sidebar`},t.nav({className:`api-preview-nav`},()=>{let e=[];for(let n in a){if(!n){e.push(t.hr());continue}let r=!a[n];e.push(t.button({type:`button`,className:()=>`nav-item ${i.activeTab==n?`active`:``}`,disabled:r,ariaDescription:app.attrs.tooltip(()=>r?`Not enabled for the collection`:``,`left`),onclick:()=>{r||(i.activeTab=n)}},n))}return e})),t.div({className:()=>`api-preview-content ${i.isLoading?`faded`:``}`,scrollTop:()=>i.activeTab?0:null},t.header({className:`api-preview-content-header`},t.h6(null,()=>i.activeTab+` (${e.name})`),t.button({type:`button`,className:()=>`btn sm circle transparent secondary m-l-auto preview-close-btn ${i.isLoading?`loading`:``}`,title:`Close`,onclick:()=>app.modals.close(r)},t.i({className:`ri-close-line`,ariaHidden:!0}))),()=>i.tabEl))),r}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openMailTest=function(e=``,n=``){let r=at(e,n);document.body.appendChild(r),app.modals.open(r)};function at(e=``,n=``){let r=`mail_test_`+app.utils.randomString(),i=`pbLastTestEmail`,a=`email_test_request`,o=[{label:`Verification`,value:`verification`},{label:`Password reset`,value:`password-reset`},{label:`Confirm email change`,value:`email-change`},{label:`OTP`,value:`otp`},{label:`Login alert`,value:`login-alert`}],s=store({email:localStorage.getItem(i)||app.store.superuser?.email||``,template:n||o[0].value,isSending:!1,collectionIdOrName:e,get isAuthCollectionsLoading(){return app.store.isCollectionsLoading},get authCollections(){return app.utils.sortedCollections(app.store.collections.filter(e=>e.type==`auth`))},get canSubmit(){return!!s.email&&!!s.template&&!!s.collectionIdOrName}}),c;async function l(){if(!(s.isSending||!s.canSubmit)){s.isSending=!0,clearTimeout(c),c=setTimeout(()=>{s.isSending=!1,app.pb.cancelRequest(a),app.modals.close(),app.toasts.error(`Test email send timeout.`)},15e3);try{s.email!=app.pb.authStore.record?.email&&localStorage.setItem(i,s.email),await app.pb.settings.testEmail(s.collectionIdOrName,s.email,s.template,{requestKey:a}),app.toasts.success(`Successfully sent test email.`),app.modals.close()}catch(e){app.checkApiError(e)}s.isSending=!1,clearTimeout(c)}}let u=[];return t.div({className:`modal popup sm`,onbeforeopen:e=>{u.push(watch(()=>s.isAuthCollectionsLoading,e=>{!e&&!s.collectionIdOrName&&(s.collectionIdOrName=s.authCollections[0]?.id||``)}))},onafterclose:e=>{clearTimeout(c),e?.remove()},onunmount:()=>{clearTimeout(c),u.forEach(e=>e?.unwatch())}},t.header({className:`modal-header`},t.h5({className:`m-auto`},`Send test email`)),t.form({id:r,className:`modal-content mail-settings-test-form`,onsubmit:e=>{e.preventDefault(),l()}},t.div({className:`grid`},t.div({className:`col-lg-12`},()=>o.map((e,n)=>t.field({className:()=>`field ${n>0?`m-t-10`:``}`},t.input({type:`radio`,id:r+`.template.`+e.value,name:`template`,checked:()=>s.template==e.value,onchange:n=>s.template=e.value}),t.label({htmlFor:r+`.template.`+e.value},e.label||e.value)))),()=>{if(!e)return t.div({className:`col-lg-12`},t.div({className:`field`},t.label({htmlFor:r+`.collection`},`Auth collection`),app.components.select({id:r+`.collection`,name:`collection`,required:!0,placeholder:()=>s.isAuthCollectionsLoading?`Loading auth collections...`:`Select auth collection`,options:()=>s.authCollections.map(e=>({value:e.id,label:e.name})),value:()=>s.collectionIdOrName||``,onchange:e=>{s.collectionIdOrName=e?.[0]?.value}})))},t.div({className:`col-lg-12`},t.div({className:`field`},t.label({htmlFor:r+`.email`},`To email address`),t.input({id:r+`.email`,name:`email`,type:`email`,required:!0,value:()=>s.email||``,oninput:e=>s.email=e.target.value}))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(),disabled:()=>s.isSending},t.span({className:`txt`},`Close`)),t.button({"html-form":r,type:`submit`,className:()=>`btn expanded ${s.isSending?`loading`:``}`,disabled:()=>s.isSending||!s.canSubmit},t.i({className:`ri-mail-send-line`,ariaHidden:!0}),t.span({className:`txt`},`Send`))))}function ot(e={}){let n=store({rid:void 0,collectionA:null,collectionB:null,deleteMissing:!1,className:``}),r=app.utils.extendStore(n,e),i=store({hasAnyChange:!1,get isDeleteDiff(){return!n.collectionB?.id&&!n.collectionB?.name},get isCreateDiff(){return!i.isDeleteDiff&&!n.collectionA?.id},get hasAnyChange(){return app.utils.hasCollectionChanges(n.collectionA,n.collectionB,n.deleteMissing)},get fieldsListA(){return Array.isArray(n.collectionA?.fields)?n.collectionA?.fields:[]},get fieldsListB(){let e=Array.isArray(n.collectionB?.fields)?n.collectionB?.fields:[];return n.deleteMissing||(e=e.concat(n.collectionA?.fields?.filter(n=>!e.find(e=>n.id==e.id))||[])),e},get mainModelProps(){return app.utils.mergeUnique(Object.keys(n.collectionA||{}),Object.keys(n.collectionB||{})).filter(e=>![`fields`,`created`,`updated`].includes(e))},get removedFields(){return i.fieldsListA.filter(e=>!i.fieldsListB.find(n=>e.id==n.id))},get sharedFields(){return i.fieldsListB.filter(e=>i.fieldsListA.find(n=>n.id==e.id))},get addedFields(){return i.fieldsListB.filter(e=>!i.fieldsListA.find(n=>n.id==e.id))}});function a(e){return e===void 0?``:app.utils.isObject(e)?JSON.stringify(e,null,4):``+e}function o(e,n){return e===n?!1:JSON.stringify(e)!=JSON.stringify(n)}function s(e,n){return(e||[]).find(e=>e.id==n)}return t.div({rid:n.rid,pbEvent:`collectionsDiffTableWrapper`,className:()=>`collections-diff-table-wrapper ${n.className}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.div({className:`collections-diff-table-title`},()=>n.collectionA?.id?n.collectionB?.id?[t.span({hidden:()=>!i.hasAnyChange,className:`label import-change-label warning`,textContent:`Changed`}),t.div({className:`inline-flex gap-5`},()=>{if(n.collectionA?.name!=n.collectionB?.name)return[t.strong({className:`txt-strikethrough txt-hint`,textContent:n.collectionA?.name}),t.i({className:`ri-arrow-right-line txt-sm`,ariaHidden:!0})]},t.strong({textContent:()=>n.collectionB?.name}))]:[t.span({className:`label import-change-label danger`,textContent:`Deleted`}),t.strong({textContent:()=>n.collectionA?.name})]:[t.span({className:`label import-change-label success`,textContent:`Added`}),t.strong({textContent:()=>n.collectionB?.name})]),t.table({className:`collections-diff-table`},t.thead(null,t.tr(null,t.th({className:`min-width`},`Props`),t.th({width:`40%`},`Old`),t.th({width:`40%`},`New`))),t.tbody(null,()=>i.mainModelProps.map(e=>{let r=o(n.collectionA?.[e],n.collectionB?.[e]);return t.tr({className:r?`txt-primary`:``},t.td({className:`min-width`},e),t.td({className:()=>i.isCreateDiff?`changed-non-col`:r?`changed-old-col`:``},t.pre({className:`txt diff-value`},a(n.collectionA?.[e]))),t.td({className:()=>i.isDeleteDiff?`changed-non-col`:r?`changed-new-col`:``},t.pre({className:`txt diff-value`},a(n.collectionB?.[e]))))}),()=>{if(!n.deleteMissing&&!i.isDeleteDiff)return;let e=[];for(let n of i.removedFields){e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label danger m-l-5`},`Deleted - `,t.small(null,`All stored data related to '${n.name}' will be deleted!`)))));for(let r in n){let i=n[r];e.push(t.tr(null,t.td({className:`min-width field-key-col`},r),t.td({className:`changed-old-col`},t.pre({className:`txt`},a(i))),t.td({className:`changed-none-col`})))}}return e},()=>{let e=[];for(let n of i.sharedFields){let r=s(i.fieldsListA,n.id),c=o(r,s(i.fieldsListB,n.id));e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label warning m-l-5 ${c?``:`hidden`}`,textContent:`Changed`}))));for(let i in n){let s=n[i],c=o(r?.[i],s);e.push(t.tr({className:c?`txt-primary`:``},t.td({className:`min-width field-key-col`},i),t.td({className:c?`changed-old-col`:``},t.pre({className:`txt`},a(r?.[i]))),t.td({className:c?`changed-new-col`:``},t.pre({className:`txt`},a(s)))))}}return e},()=>{let e=[];for(let n of i.addedFields){e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label success m-l-5`},`Added`))));for(let r in n){let i=n[r];e.push(t.tr({className:`txt-primary`},t.td({className:`min-width field-key-col`},r),t.td({className:`changed-none-col`}),t.td({className:`changed-new-col`},t.pre({className:`txt`},a(i)))))}}return e})))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openImportCollectionsReview=function(e,n,r={deleteMissing:!1,onsubmit:null}){let i=st(e,n,r);i&&(document.body.appendChild(i),app.modals.open(i))};function st(e,n,r){let i,a=store({deleteMissing:!1,onsubmit:function(e){}}),o=app.utils.extendStore(a,r),s=store({isImporting:!1,pairs:[]});function c(){let r=[];for(let i of e){let e=n.find(e=>e.id==i.id);(a.deleteMissing&&!e?.id||e?.id&&app.utils.hasCollectionChanges(i,e,a.deleteMissing))&&r.push({old:i,new:e})}for(let i of n){let n=e.find(e=>e.id==i.id);n?.id||r.push({old:n,new:i})}s.pairs=r}function l(){let r=[];if(a.deleteMissing)for(let i of e){let e=n.find(e=>e.id==i.id);if(!e)r.push(i.name+`.*`);else{let n=Array.isArray(i.fields)?i.fields:[];for(let a of n)e.fields.find(e=>e.id==a.id)||r.push(`${i.name}.${a.name} (${a.id})`)}}r.length?app.modals.confirm([t.h6(null,`Do you really want to delete the following collection fields and their related records data:`),t.ul(null,()=>r.map(e=>t.li(null,e)))],()=>u()):u()}async function u(){if(!s.isImporting){s.isImporting=!0;try{await app.pb.collections.import(n,a.deleteMissing),await app.store.loadCollections(),a.onsubmit?.(JSON.parse(JSON.stringify(app.store.collections))),app.toasts.success(`Successfully imported collections configuration.`)}catch(e){app.checkApiError(e)}s.isImporting=!1,app.modals.close(i)}}return i=t.div({pbEvent:`importCollectionsReviewModal`,className:`modal popup full import-collections-review-modal`,onbeforeopen:()=>{c()},onbeforeclose:()=>!s.isImporting,onafterclose:e=>{e?.remove()},onunmount:()=>{o.forEach(e=>e?.unwatch())}},t.header({className:`modal-header`},t.h5(null,`Side-by-side diff`)),t.div({className:`modal-content`},()=>s.pairs.map(e=>ot({collectionA:e.old,collectionB:e.new,deleteMissing:a.deleteMissing}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,disabled:()=>s.isImporting,onclick:()=>app.modals.close(i)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:()=>`btn expanded ${s.isImporting?`loading`:``}`,disabled:()=>s.isImporting,onclick:()=>l()},t.span({className:`txt`},`Confirm and import`)))),i}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.recordSummary=function(e,n=null){let r=store({get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)},get presentableFields(){if(!r.collection?.id)return[];let e=r.collection.fields.filter(e=>e.presentable).sort((e,n)=>{let r=app.fieldTypes[e.type].summaryPriority||0,i=app.fieldTypes[n.type].summaryPriority||0;return r>i?1:re.name==n);if(i){e.push(i);break}}return e}});return t.div({className:`label record-summary`},t.i({ariaHidden:!0,className:`ri-eye-line link-hint record-preview-icon`,onclick:e=>{e.stopImmediatePropagation(),e.preventDefault()},onmouseenter:n=>{lt(n.target,e,100)},onmouseleave:e=>{ct(e.target,100)},onunmount:e=>{ct(e,0)}}),()=>{let i=[];function a(e){(e==null||e==``)&&(e=t.span({className:`missing-value`})),i.push(e)}for(let i of r.presentableFields){let r=app.fieldTypes[i.type]?.view;if(r)a(r({short:!0,get record(){return e},get field(){return i},get meta(){return n}}));else{let n=app.utils.toArray(e[i.name]).splice(0,3);for(let e of n)a(e)}}return i})};function ct(e,n=150){if(e){if(clearTimeout(e._summaryDropdownTimeoutId),n<=0){e?._summaryDropdown?.hidePopover?.();return}e._summaryDropdownTimeoutId=setTimeout(()=>{e?._summaryDropdown?.hidePopover?.()},n)}}function lt(e,n,r=150){if(e){if(clearTimeout(e._summaryDropdownTimeoutId),r<=0){ut(e,n);return}e._summaryDropdownTimeoutId=setTimeout(()=>{ut(e,n)},r)}}var ut=function(e,n){e&&(e._summaryDropdown||(e._summaryDropdown=t.div({className:`dropdown record-summary-dropdown`,popover:`manual`,onclick:e=>{e.stopImmediatePropagation(),e.preventDefault()}},t.div({className:`record-header`},t.a({className:`link-hint txt-bold m-r-auto`,target:`_blank`,href:`#/collections?collection=${n.collectionName}&record=${n.id}`,onclick:e=>{e.stopImmediatePropagation()}},t.span({className:`txt`},`Edit relation record`),t.i({className:`ri-external-link-line`,ariaHidden:!0})),t.button({type:`button`,className:`link-hint`,title:`Close`,onclick:()=>ct(e,0)},t.i({className:`ri-close-line`,ariaHidden:!0}))),t.hr(),t.pre({className:`record-json`},()=>{let e=app.store.collections.find(e=>e.id==n.collectionId||e.name==n.collectionName)?.fields||[];if(!e.length)return;let r={collectionId:n.collectionId,collectionName:n.collectionName};for(let i of e)r[i.name]=n[i.name];return JSON.stringify(app.utils.truncateObject(r,27),null,2)})),e.appendChild(e._summaryDropdown)),e._summaryDropdown?.showPopover({source:e}))};window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.recordsSearchbar=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,disabled:void 0,value:``,className:``,collection:void 0,onsubmit:e=>{}}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`full-width records-searchbar-wrapper ${n.className}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},app.components.searchbar({placeholder:()=>!n.disabled&&!n.collection?.id?`Loading...`:`Search term or filter...`,historyKey:()=>`pbRecordsSearchHistory_`+n.collection?.id,disabled:()=>n.disabled||!n.collection,value:()=>n.value,autocomplete:e=>app.utils.collectionAutocompleteKeys(n.collection,e,{requestKeys:!1,collectionJoinKeys:!1}),onsubmit:n.onsubmit}))},window.app=window.app||{},window.app.components=window.app.components||{};var I={max:10,pending:new Set,processing:new Set};function dt(e){return I.pending.add(e),I.processing.size<=I.max&&ft(),()=>{I.pending.delete(e),I.processing.delete(e),I.processing.sizen.id,hidden:()=>n.hidden,inert:()=>n.inert,type:`button`,draggable:!1,className:()=>`thumb ${n.extraClasses} ${i.isPreviewLoading?`loading`:``}`,title:()=>(i.hasPreview?`Preview`:`Download`)+` `+n.filename,onclick:async e=>{e.stopPropagation();async function r(){let e=await app.getFileToken(n.record.collectionId);return app.pb.files.getURL(n.record,n.filename,{token:e})}if(i.hasPreview)app.modals.openFilePreview(r);else{let e=await r();app.utils.download(e,n.filename)}},onunmount:()=>{r.forEach(e=>e?.unwatch())}},()=>{if(i.fileType==`image`){let e=t.img({draggable:!1,alt:()=>`Thumb of `+n.filename,src:()=>i.previewURL,onerror:n=>{console.warn(`[recordFileThumb] load err:`,n),i.isPreviewLoading=!1,e?._semaphoreRelease?.()},onload:()=>{i.isPreviewLoading=!1,e?._semaphoreRelease?.()},onmount:e=>{i.isPreviewLoading=!0,e._semaphoreRelease=dt(async()=>{try{i.previewToken=await app.getFileToken(n.record.collectionId),i.previewURL=app.pb.files.getURL(n.record,n.filename,{thumb:`100x100`,token:i.previewToken})}catch(e){console.warn(e)}})},onunmount:e=>{i.isPreviewLoading=!1,e._semaphoreRelease?.()}});return e}return t.i({className:app.utils.fileTypeIcons[i.fileType]||`ri-file-line`,ariaHidden:!0})})},window.app=window.app||{},window.app.modals=window.app.modals||{};var pt=100,mt={btnText:`Insert`,fileTypes:[],onselect:function(e){}},ht=`pbLastRecordFilePickerCollection`,gt=`listFilePickerRecords`;window.app.modals.openRecordFilePicker=function(e={}){e=Object.assign({},mt,e);let n=_t(e);document.body.appendChild(n),app.modals.open(n)};function _t(e=mt){let n,r=`file_picker_`+app.utils.randomString(),i=store({selectedFile:{},records:[],activeCollectionId:``,searchTerm:``,lastRecordsPage:1,lastTotalRecords:0,isLoadingRecords:!1,get collections(){return app.utils.sortedCollections(app.store.collections.filter(e=>e.type==`view`?!1:!!e.fields?.find(e=>e.type===`file`&&!e.protected)))},get activeCollection(){return i.collections.find(e=>e.id==i.activeCollectionId)||i.collections[0]},get activeCollectionFileFields(){return i.activeCollection?.fields?.filter(e=>e.type===`file`&&!e.protected)||[]},get isLoading(){return app.store.isLoadingCollections||i.isLoadingRecords},get canLoadMore(){return!i.isLoadingRecords&&i.lastTotalRecords==pt},get hasAtleastOneFile(){return!!i.records.find(e=>c(e).length>0)}}),a=[];a.push(watch(()=>{i.activeCollectionId?(window.localStorage.setItem(ht,i.activeCollectionId),i.searchTerm=``):i.activeCollectionId=window.localStorage.getItem(ht)})),a.push(watch(()=>[i.activeCollection,i.searchTerm],()=>s(!0)));function o(){app.pb.cancelRequest(gt),i.isLoadingRecords=!1,i.records=[],i.lastTotalRecords=0,i.lastRecordsPage=1,i.selectedFile={}}async function s(e=!1){if(!i.activeCollection){o();return}e&&o(),i.isLoadingRecords=!0;try{let n=e?1:i.lastRecordsPage+1,r=app.utils.getAllCollectionIdentifiers(i.activeCollection),a=app.utils.normalizeSearchFilter(i.searchTerm,r)||``;a&&(a+=` && `),a+=`(`+i.activeCollectionFileFields.map(e=>`${e.name}:length>0`).join(`||`)+`)`;let o=await app.pb.collection(i.activeCollection.id).getList(n,pt,{requestKey:gt,filter:a,skipTotal:1,sort:i.activeCollection.type==`view`?``:`-@rowid`});i.lastRecordsPage=o.page,i.lastTotalRecords=o.items.length,i.records=app.utils.filterDuplicatesByKey(i.records.concat(o.items)),i.isLoadingRecords=!1}catch(e){e.isAbort||(i.isLoadingRecords=!1,app.checkApiError(e))}}function c(n){let r=[];for(let a of i.activeCollectionFileFields){let i=app.utils.toArray(n[a.name]);for(let n of i)(app.utils.isEmpty(e.fileTypes)||e.fileTypes?.includes(app.utils.getFileType(n)))&&r.push(n)}return r}function l(e,n){i.selectedFile={record:e,name:n,thumb:``}}function u(e,n){return i.selectedFile?.name==n&&i.selectedFile?.record?.id==e?.id}let d={"record:create":e=>{e.detail.collectionId==i.activeCollection?.id&&(i.selectedFile?.record?.id==e.detail.id&&(i.selectedFile.record=e.detail),s(!0))},"record:delete":e=>{e.detail.collectionId!=i.activeCollection?.id&&e.detail.collectionName!=i.activeCollection?.name||(i.selectedFile?.record?.id==e.detail.id&&(i.selectedFile={}),s(!0))}};return n=t.div({className:`modal popup record-file-picker-modal`,onafterclose:e=>{e?.remove()},onmount:e=>{for(let e in d)document.addEventListener(e,d[e])},onunmount:e=>{a.forEach(e=>e?.unwatch());for(let e in d)document.removeEventListener(e,d[e])}},t.header({className:`modal-header`},t.button({className:()=>`btn primary outline record-file-picker-collection-select-btn ${app.store.isLoadingCollections?`loading`:``}`,disabled:()=>app.store.isLoadingCollections,"html-popovertarget":`collections_dropdown`+r},t.span({className:`txt-lg collection-name m-r-auto`},()=>i.activeCollection?.name||`Select collection`),t.i({className:`ri-arrow-drop-down-line`,ariaHidden:!0})),t.div({id:`collections_dropdown`+r,className:`dropdown`,popover:`hint`},()=>i.collections.map(e=>t.button({type:`button`,className:()=>`dropdown-item ${i.activeCollectionId==e.id?`active`:``}`,onclick:n=>{i.activeCollectionId=e.id,n.target?.closest(`.dropdown`)?.hidePopover()}},e.name))),app.components.recordsSearchbar({disabled:()=>!i.activeCollection?.id,collection:()=>i.activeCollection,value:()=>i.searchTerm,onsubmit:e=>i.searchTerm=e}),t.button({type:`button`,className:`btn circle transparent`,ariaLabel:app.attrs.tooltip(`Add new record`),onclick:()=>app.modals.openRecordUpsert(i.activeCollection)},t.i({className:`ri-add-line txt-hint`,ariaHidden:!0}))),t.div({className:`modal-content`},t.div({className:`block txt-center`,hidden:()=>i.hasAtleastOneFile||!i.isLoading},t.span({className:`loader`})),t.div({className:`record-file-picker-list`},()=>{let e=[];for(let n of i.records){let r=c(n);for(let i of r)e.push(t.button({rid:n.id+`:`+i,className:()=>`list-item thumb ${u(n,i)?`success`:``}`,ariaDescription:app.attrs.tooltip(i,`bottom`),onclick:()=>l(n,i)},()=>{if(app.utils.hasImageExtension(i))return t.img({loading:`lazy`,src:app.pb.files.getURL(n,i,{thumb:`100x100`}),alt:i});let e=app.utils.getFileType(i);return t.i({className:app.utils.fileTypeIcons[e]||`ri-file-line`,ariaHidden:!0})}))}return e}),t.div({hidden:()=>!i.canLoadMore||!i.hasAtleastOneFile,className:`block txt-center`},t.button({className:()=>`btn secondary expanded-lg m-t-base ${i.isLoadingRecords?`loading`:``}`,disabled:()=>i.isLoadingRecords,onclick:()=>s()},t.span({className:`txt`},`Load more`))),t.div({className:`block txt-center txt-hint p-t-10 p-b-10`,hidden:()=>i.hasAtleastOneFile||i.isLoading},()=>app.utils.isEmpty(e.fileTypes)?t.p(null,`No records with selectable files found.`):t.p(null,`No "${e.fileTypes.join(`", "`)}" files found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,hidden:()=>!i.searchTerm?.length,onclick:()=>{i.searchTerm=``}}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n)},t.span({className:`txt`},`Close`)),()=>{if(!i.selectedFile?.name||!app.utils.hasImageExtension(i.selectedFile.name))return;let e=[{value:``,label:`Original size`},{value:`100x100`,label:`100x100 thumb`}],n=i.activeCollectionFileFields.find(e=>i.selectedFile.record[e.name].includes(i.selectedFile.name)),r=app.utils.toArray(n.thumbs);for(let n of r)e.push({value:n,label:`${n} thumb`});return t.div({className:`record-file-picker-thumb-select`},app.components.select({required:!0,value:i.selectedFile.thumb||``,options:e,onchange:e=>{i.selectedFile.thumb=e?.[0].value}}))},t.button({type:`button`,className:`btn expanded`,disabled:()=>i.isLoading||!i.selectedFile?.name,onclick:()=>{let r=JSON.parse(JSON.stringify(i.selectedFile));if(e.onselect&&e.onselect(r)===!1)return!1;app.modals.close(n)}},t.span({className:`txt`},()=>e.btnText||mt.btnText)))),n}window.app=window.app||{},window.app.modals=window.app.modals||{};var vt=50,yt=100,bt=`listRelationPickerRecords`,xt={collection:``,selectedIds:[],maxSelect:1,btnText:`Set selection`,onselect:function(e){}};window.app.modals.openRecordsPicker=function(e={}){e=Object.assign({},xt,e);let n=St(e);document.body.appendChild(n),app.modals.open(n)};function St(e=xt){let n,r=store({searchTerm:``,selected:[],preselected:[],isLoadingPreselected:!1,records:[],isLoadingRecords:!1,lastRecordsPage:1,lastRecordsTotal:0,get collection(){let n=e.collection;return typeof e.collection==`object`&&e.collection?.id&&(n=e.collection?.id),app.store.collections.find(e=>e.id==n||e.name==n)},get isLoading(){return r.isLoadingPreselected||r.isLoadingRecords},get canLoadMore(){return!r.isLoadingRecords&&r.lastRecordsTotal==vt}}),i=[watch(()=>[e.collection,e.selectedIds],()=>{o()}),watch(()=>[r.collection,r.searchTerm],()=>{s(!0)})];function a(){setTimeout(()=>app.modals.close(n),0)}async function o(){let n=app.utils.toArray(e.selectedIds),i=e.collection?.id||e.collection;if(!i||!n.length)return;r.isLoadingSelected=!0;let a=[],o=n.slice(),s=[];for(;o.length>0;){let e=[],n=o.splice(0,yt);for(let r of n)e.push(`id="${r}"`);s.push(app.pb.collection(i).getFullList({requestKey:null,filter:e.join(`||`)}))}try{await Promise.all(s).then(e=>{a=a.concat(...e)});let e=[];for(let r of n){let n=a.find(e=>e.id==r);n&&e.push(n)}r.searchTerm.trim()||(r.records=app.utils.filterDuplicatesByKey(e.concat(r.records))),r.selected=e,r.isLoadingSelected=!1}catch(e){e.isAbort||(app.checkApiError(e),r.isLoadingSelected=!1)}}async function s(e=!1){if(r.collection?.id){e&&(c(),r.searchTerm.trim()||(r.records=r.selected.slice())),r.isLoadingRecords=!0;try{let n=e?1:r.lastRecordsPage+1,i=app.utils.getAllCollectionIdentifiers(r.collection),a=app.utils.normalizeSearchFilter(r.searchTerm,i)||``,o=await app.pb.collection(r.collection.id).getList(n,vt,{requestKey:bt,filter:a,skipTotal:1,sort:r.collection.type==`view`?``:`-@rowid`});r.lastRecordsPage=o.page,r.lastRecordsTotal=o.items.length,r.records=app.utils.filterDuplicatesByKey(r.records.concat(o.items)),r.isLoadingRecords=!1}catch(e){e.isAbort||(r.isLoadingRecords=!1,app.checkApiError(e))}}}function c(){app.pb.cancelRequest(bt),r.isLoadingRecords=!1,r.records=[],r.lastTotalRecords=0,r.lastRecordsPage=1}function l(e){e.target.scrollHeight-e.target.clientHeight-e.target.scrollTop<=100&&r.canLoadMore&&s()}function u(n){let i=r.selected.findIndex(e=>e.id==n.id);if(i>=0)r.selected.splice(i,1);else{let i=e.maxSelect||1,a=r.selected.length-i;for(;a>=0;)r.selected.pop(),a--;r.selected.push(n)}}function d(e){return r.selected.findIndex(n=>n.id==e.id)>=0}let f={"record:save":e=>{if(e.detail.collectionId!=r.collection?.id)return;let n=r.selected?.findIndex(n=>n.id==e.detail.id);n>=0&&(r.selected[n]=e.detail),app.utils.pushOrReplaceObject(r.records,e.detail),s(!0)},"record:delete":e=>{e.detail.collectionId!=r.collection?.id&&e.detail.collectionName!=r.collection?.name||(d(e.detail)&&u(e.detail),app.utils.removeByKey(r.records,`id`,e.detail.id),s(!0))}};return n=t.div({className:`modal popup lg records-picker-modal`,onafterclose:e=>{e.remove()},onmount:e=>{for(let e in f)document.addEventListener(e,f[e])},onunmount:e=>{i.forEach(e=>e?.unwatch());for(let e in f)document.removeEventListener(e,f[e])}},t.header({className:`modal-header`},t.h6({className:`collection-name`},()=>r.collection.name),app.components.recordsSearchbar({disabled:()=>!r.collection?.id,collection:()=>r.collection,value:()=>r.searchTerm,onsubmit:e=>r.searchTerm=e}),t.button({type:`button`,className:`btn circle transparent`,ariaLabel:app.attrs.tooltip(`Add new record`),onclick:()=>{app.modals.openRecordUpsert(r.collection)}},t.i({className:`ri-add-line txt-hint`,ariaHidden:!0}))),t.div({className:`modal-content`,hidden:()=>r.isLoadingCollection},t.div({className:`list records-picker-list`,onscroll:l,onresize:l},()=>r.records.map(e=>t.div({tabIndex:0,className:`list-item handle`,onclick:()=>{u(e),document.activeElement?.blur()}},t.div({className:`content`},t.span({className:`state-icon`},t.i({ariaHidden:!0,className:()=>d(e)?`ri-checkbox-circle-fill txt-success`:`ri-checkbox-blank-circle-line txt-disabled`})),()=>app.components.recordSummary(e)),t.div({className:`actions autohide`},t.button({className:`btn sm secondary transparent circle`,ariaLabel:app.attrs.tooltip(`Edit`),onclick:n=>{n.stopPropagation(),app.modals.openRecordUpsert(r.collection,e)}},t.i({className:`ri-pencil-line`,ariaHidden:!0}))))),t.div({className:`list-item`,hidden:()=>!r.isLoading},t.div({className:`skeleton-loader`})),t.div({className:`list-item`,hidden:()=>r.records.length||r.isLoading},t.div({className:`content txt-hint`},t.span({className:`txt`},`No records found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,hidden:()=>!r.searchTerm.trim().length,onclick:()=>{r.searchTerm=``}})))),t.div({className:`block m-t-base`},t.p({className:`txt-bold`},()=>`Selected (${r.selected.length} of max ${e.maxSelect||1})`),t.span({className:`txt-hint`,hidden:()=>r.selected},`No selected records.`),app.components.sortable({className:`records-picker-selected-list`,data:()=>r.selected,dataItem:(e,n)=>t.div({rid:e,className:`label handle`},()=>app.components.recordSummary(e,[],!0),t.span({className:`link-hint`,title:`Remove`,role:`button`,onclick:()=>u(e)},t.i({className:`ri-close-line`,ariaHidden:!0}))),onchange:(e,n,i)=>{r.selected=e}}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>a()},t.span({className:`txt`},`Close`)),()=>{if(!r.selectedFile?.name||!app.utils.hasImageExtension(r.selectedFile.name))return;let e=[{value:``,label:`Original size`},{value:`100x100`,label:`100x100 thumb`}],n=r.activeCollectionFileFields.find(e=>r.selectedFile.record[e.name].includes(r.selectedFile.name)),i=app.utils.toArray(n.thumbs);for(let n of i)e.push({value:n,label:`${n} thumb`});return t.div({className:`record-file-picker-thumb-select`},app.components.select({required:!0,value:r.selectedFile.thumb||``,options:e,onchange:e=>{r.selectedFile.thumb=e?.[0].value}}))},t.button({type:`button`,className:`btn expanded`,disabled:()=>r.isLoadingCollection,onclick:()=>{let n=JSON.parse(JSON.stringify(r.selected));if(e.onselect&&e.onselect(n)===!1)return!1;a()}},t.span({className:`txt`},e.btnText||xt.btnText)))),n}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openRecordPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=R(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};function Ct(e){e.expand&&(e=Object.assign({},e),delete e.expand),app.utils.downloadJSON(e,e.collectionName+`_`+e.id+`.json`)}function wt(e){e.expand&&(e=Object.assign({},e),delete e.expand),app.utils.copyToClipboard(JSON.stringify(e,null,2)),app.toasts.success(`Record copied to clipboard!`)}function R(e,n){let r,i=app.utils.randomString(),a=store({isLoading:!1,record:null,get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)}});async function o(){if(!e?.id){app.toasts.error(`Failed to load record.`),setTimeout(()=>app.modals.close(r),0),console.warn(`[recordPreviewModal] missing required record id field:`,e);return}if(!e.collectionId&&!e.collectionName){app.toasts.error(`Failed to load record.`),setTimeout(()=>app.modals.close(r),0),console.warn(`[recordPreviewModal] missing required collectionId or collectionName field:`,e);return}a.isLoading=!0;try{let n=[],r=a.collection?.fields?.filter(e=>!e.hidden&&e.presentable&&e.type==`relation`)||[];for(let e of r)n.push(e.name);a.record=await app.pb.collection(e.collectionId||e.collectionName).getOne(e.id,{requestKey:`record_preview_`+e.id,expand:n.join(`,`)||void 0}),a.isLoading=!1}catch(e){e?.isAbort||(a.isLoading=!1,app.checkApiError(e),setTimeout(()=>app.modals.close(r),0))}}return r=t.div({pbEvent:`recordPreviewModal`,className:`modal record-preview-modal`,onbeforeopen:e=>(o(),n.onbeforeopen?.(e)),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()},onmount:e=>{},onunmount:e=>{}},t.header({className:`modal-header`},t.h6(null,t.strong(null,()=>e?.collectionName||a.collection?.name),` record preview`),t.button({title:`More options`,className:`btn sm circle transparent m-l-auto`,"html-popovertarget":i+`preview-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:i+`preview-dropdown`,className:`dropdown`,popover:`auto`},e=>t.button({className:`dropdown-item`,onclick:()=>{wt(a.record),e.hidePopover()}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)))),t.div({className:`modal-content`},()=>a.isLoading||!a.record?.id||!a.collection?.id?t.table(null,t.tbody(null,()=>{let e=a.collection?.fields?.filter(e=>e.type!=`password`).length||1,n=[];for(let r=0;r(a.collection?.fields?.filter(e=>e.type!=`password`)||[]).map(e=>t.tr(null,t.th({className:()=>`min-width p-r-0 col-field-name-${e.name}`},e.name),t.td({className:()=>`col-field-name-${e.name}`},()=>app.fieldTypes[e.type]?.view?app.fieldTypes[e.type].view({short:!1,get record(){return a.record},get field(){return e}}):app.utils.stringifyValue(a.record[e.name]))))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:`btn`,onclick:()=>Ct(a.record)},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`Download JSON`)))),r}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openRecordImpersontate=function(e){let n=z(e);document.body.appendChild(n),app.modals.open(n)};function z(e){let n=`impersonate_`+app.utils.randomString(),r=store({isLoading:!1,token:``,duration:0,get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)}}),i=app.utils.getApiExampleURL();async function a(){if(!r.isLoading){r.isLoading=!0;try{r.token=(await app.pb.collection(r.collection.name).impersonate(e.id,r.duration)).authStore.token}catch(e){app.checkApiError(e)}r.isLoading=!1}}function o(){r.token=``,r.duration=0}return t.div({className:`modal popup record-impersonate-auth-modal`,onbeforeclose:()=>!r.isLoading,onafterclose:e=>{e?.remove()}},t.header({className:`modal-header`},t.h6(null,`Generate nonrenewable auth token for `,t.strong(null,()=>e.email||e.id))),t.div({className:`modal-content`},t.form({id:n+`_form`,hidden:()=>r.token,className:`block`,onsubmit:e=>{e.preventDefault(),a()}},t.div({className:`field`},t.label({htmlFor:n+`_duration`},`Token duration (in seconds)`),t.input({id:n+`_duration`,type:`number`,name:`duration`,min:0,step:1,placeholder:()=>`Default to the collection settings (${r.collection?.authToken?.duration||0}s)`,value:e=>r.duration||``,oninput:e=>r.duration=parseInt(e.target.value,10)}))),t.div({hidden:()=>!r.token,className:`alert success impersonate-success`},t.strong(null,()=>r.token),` `,app.components.copyButton(()=>r.token)),app.components.codeBlockTabs({hidden:()=>!r.token,className:`sdk-examples m-t-base`,tabs:[{title:`JS SDK`,language:`js`,value:` + L ${p} ${d}`,g=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return g.setAttribute(`class`,`relation-path`),g.setAttribute(`data-from`,i||``),g.setAttribute(`data-to`,a||``),g.setAttribute(`d`,h),g}window.app=window.app||{},window.app.components=window.app.components||{};var N=1e3;window.app.components.pageSidebar=function(e={},...n){let r,i=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,className:``,widthHistoryKey:`pbPageSidebarWidth`,onmount:void 0,onunmount:void 0}),a=app.utils.extendStore(i,e),o=store({responsiveShow:!1}),s;function c(){if(r){if(window.innerWidth>N){o.responsiveShow=!1,r.dataset.responsive=!1,s?.remove(),s=null;return}r.dataset.responsive=!0,s||(s=t.button({type:`button`,className:`btn transparent secondary responsive-sidebar-btn`,title:`Toggle sidebar`,onclick:e=>{e.stopPropagation(),o.responsiveShow=!o.responsiveShow}},t.i({className:`ri-menu-2-line`,ariaHidden:!0})),document.body.querySelector(`.page-header .breadcrumbs`).before(s))}}function l(e){if(e.target.closest(`.responsive-close`)){o.responsiveShow=!1;return}if(!(e.target.closest(`.page-sidebar`)||e.target.closest(`.app-header`)||e.target.closest(`.modal`)))return e.preventDefault(),e.stopImmediatePropagation(),o.responsiveShow=!1,!1}return a.push(watch(()=>o.responsiveShow,e=>{e?window.addEventListener(`click`,l,!0):window.removeEventListener(`click`,l,!0)})),r=t.aside({pbEvent:`pageSidebar`,rid:i.rid,id:()=>i.id,hidden:()=>i.hidden,inert:()=>i.inert,className:()=>`page-sidebar ${i.className} ${o.responsiveShow?`active`:``}`,onmount:e=>{c(e),window.addEventListener(`resize`,c),i.onmount?.(e)},onunmount:e=>{i.onunmount?.(e),window.removeEventListener(`click`,l,!0),window.removeEventListener(`resize`,c),s?.remove(),a.forEach(e=>e?.unwatch())}},e=>{let n;return i.widthHistoryKey&&(n=localStorage.getItem(i.widthHistoryKey),n&&(e.style.width=n)),app.components.dragline({ondragstart:n=>{e._startWidth=e.offsetWidth},ondragging:(r,a,o)=>{n=e._startWidth+a+`px`,e.style.width=n,i.widthHistoryKey&&localStorage.setItem(i.widthHistoryKey,n)}})},...n),r};var P=`modulepreload`,nt=function(e,n){return new URL(e,n).href},rt={},F=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){let e=document.getElementsByTagName(`link`),a=document.querySelector(`meta[property=csp-nonce]`),o=a?.nonce||a?.getAttribute(`nonce`);function s(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}i=s(n.map(n=>{if(n=nt(n,r),n in rt)return;rt[n]=!0;let i=n.endsWith(`.css`),a=i?`[rel="stylesheet"]`:``;if(r)for(let r=e.length-1;r>=0;r--){let a=e[r];if(a.href===n&&(!i||a.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${n}"]${a}`))return;let s=document.createElement(`link`);if(s.rel=i?`stylesheet`:P,i||(s.as=`script`),s.crossOrigin=``,s.href=n,o&&s.setAttribute(`nonce`,o),document.head.appendChild(s),i)return new Promise((e,r)=>{s.addEventListener(`load`,e),s.addEventListener(`error`,()=>r(Error(`Unable to preload CSS for ${n}`)))})}))}function a(e){let n=new Event(`vite:preloadError`,{cancelable:!0});if(n.payload=e,window.dispatchEvent(n),!n.defaultPrevented)throw e}return i.then(n=>{for(let e of n||[])e.status===`rejected`&&a(e.reason);return e().catch(a)})};window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openApiPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=it(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};function it(e,n){if(!e){console.warn(`[apiPreviewModal] missing required collection`);return}let r,i=store({activeTab:`List/Search`,tabEl:null,isLoading:!1}),a={"List/Search":async e=>{let{docsList:n}=await F(async()=>{let{docsList:e}=await import(`./docsList-BAfVNUIM.js`);return{docsList:e}},__vite__mapDeps([0,1,2,3]),import.meta.url);return i.tabEl=n(e)},View:async e=>{let{docsView:n}=await F(async()=>{let{docsView:e}=await import(`./docsView-Be6Uhvcf.js`);return{docsView:e}},__vite__mapDeps([4,1,2]),import.meta.url);return i.tabEl=n(e)}};e.type!=`view`&&(a.Create=async e=>{let{docsCreate:n}=await F(async()=>{let{docsCreate:e}=await import(`./docsCreate-Be3S3y5K.js`);return{docsCreate:e}},__vite__mapDeps([5,1,2]),import.meta.url);return i.tabEl=n(e)},a.Update=async e=>{let{docsUpdate:n}=await F(async()=>{let{docsUpdate:e}=await import(`./docsUpdate-LtD8DbWI.js`);return{docsUpdate:e}},__vite__mapDeps([6,5,1,2]),import.meta.url);return i.tabEl=n(e)},a.Delete=async e=>{let{docsDelete:n}=await F(async()=>{let{docsDelete:e}=await import(`./docsDelete-CybOn5jy.js`);return{docsDelete:e}},[],import.meta.url);return i.tabEl=n(e)},a.Realtime=async e=>{let{docsRealtime:n}=await F(async()=>{let{docsRealtime:e}=await import(`./docsRealtime-PMESvmJN.js`);return{docsRealtime:e}},[],import.meta.url);return i.tabEl=n(e)},a.Batch=async e=>{let{docsBatch:n}=await F(async()=>{let{docsBatch:e}=await import(`./docsBatch-DNJl1NTn.js`);return{docsBatch:e}},[],import.meta.url);return i.tabEl=n(e)}),e.type==`auth`&&(a[``]=null,a[`List auth methods`]=async e=>{let{docsListAuthMethods:n}=await F(async()=>{let{docsListAuthMethods:e}=await import(`./docsListAuthMethods-9feSopQX.js`);return{docsListAuthMethods:e}},__vite__mapDeps([7,2]),import.meta.url);return i.tabEl=n(e)},a[`Auth with password`]=e.passwordAuth?.enabled?async e=>{let{docsAuthWithPassword:n}=await F(async()=>{let{docsAuthWithPassword:e}=await import(`./docsAuthWithPassword-DEWj8Jyn.js`);return{docsAuthWithPassword:e}},__vite__mapDeps([8,1,2]),import.meta.url);return i.tabEl=n(e)}:null,e.name!=`_superusers`&&(a[`Auth with OAuth2`]=e.oauth2?.enabled?async e=>{let{docsAuthWithOAuth2:n}=await F(async()=>{let{docsAuthWithOAuth2:e}=await import(`./docsAuthWithOAuth2-DUIE4EoY.js`);return{docsAuthWithOAuth2:e}},__vite__mapDeps([9,1,2]),import.meta.url);return i.tabEl=n(e)}:null),a[`Auth with OTP`]=e.otp?.enabled?async e=>{let{docsAuthWithOTP:n}=await F(async()=>{let{docsAuthWithOTP:e}=await import(`./docsAuthWithOTP-B7z2VJzp.js`);return{docsAuthWithOTP:e}},__vite__mapDeps([10,1,2]),import.meta.url);return i.tabEl=n(e)}:null,a[`Auth refresh`]=async e=>{let{docsAuthRefresh:n}=await F(async()=>{let{docsAuthRefresh:e}=await import(`./docsAuthRefresh-UjveHHwo.js`);return{docsAuthRefresh:e}},__vite__mapDeps([11,1,2]),import.meta.url);return i.tabEl=n(e)},e.name!=`_superusers`&&(a.Verification=async e=>{let{docsVerification:n}=await F(async()=>{let{docsVerification:e}=await import(`./docsVerification-B_Nb90xU.js`);return{docsVerification:e}},[],import.meta.url);return i.tabEl=n(e)}),a[`Password reset`]=async e=>{let{docsPasswordReset:n}=await F(async()=>{let{docsPasswordReset:e}=await import(`./docsPasswordReset-vLO_ZWrq.js`);return{docsPasswordReset:e}},[],import.meta.url);return i.tabEl=n(e)},a[`Email change`]=async e=>{let{docsEmailChange:n}=await F(async()=>{let{docsEmailChange:e}=await import(`./docsEmailChange-B---6FKV.js`);return{docsEmailChange:e}},[],import.meta.url);return i.tabEl=n(e)});let o=[watch(()=>i.activeTab,async()=>{i.isLoading=!0,await a[i.activeTab]?.(e),i.isLoading=!1})];return r=t.div({pbEvent:`apiPreviewModal`,className:`modal api-preview-modal`,onbeforeopen:e=>n.onbeforeopen?.(e),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),o.forEach(e=>e?.unwatch()),e?.remove()},onmount:e=>{},onunmount:e=>{o.forEach(e=>e?.unwatch())}},t.div({className:`modal-content`},t.aside({className:`api-preview-sidebar`},t.nav({className:`api-preview-nav`},()=>{let e=[];for(let n in a){if(!n){e.push(t.hr());continue}let r=!a[n];e.push(t.button({type:`button`,className:()=>`nav-item ${i.activeTab==n?`active`:``}`,disabled:r,ariaDescription:app.attrs.tooltip(()=>r?`Not enabled for the collection`:``,`left`),onclick:()=>{r||(i.activeTab=n)}},n))}return e})),t.div({className:()=>`api-preview-content ${i.isLoading?`faded`:``}`,scrollTop:()=>i.activeTab?0:null},t.header({className:`api-preview-content-header`},t.h6(null,()=>i.activeTab+` (${e.name})`),t.button({type:`button`,className:()=>`btn sm circle transparent secondary m-l-auto preview-close-btn ${i.isLoading?`loading`:``}`,title:`Close`,onclick:()=>app.modals.close(r)},t.i({className:`ri-close-line`,ariaHidden:!0}))),()=>i.tabEl))),r}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openMailTest=function(e=``,n=``){let r=at(e,n);document.body.appendChild(r),app.modals.open(r)};function at(e=``,n=``){let r=`mail_test_`+app.utils.randomString(),i=`pbLastTestEmail`,a=`email_test_request`,o=[{label:`Verification`,value:`verification`},{label:`Password reset`,value:`password-reset`},{label:`Confirm email change`,value:`email-change`},{label:`OTP`,value:`otp`},{label:`Login alert`,value:`login-alert`}],s=store({email:localStorage.getItem(i)||app.store.superuser?.email||``,template:n||o[0].value,isSending:!1,collectionIdOrName:e,get isAuthCollectionsLoading(){return app.store.isCollectionsLoading},get authCollections(){return app.utils.sortedCollections(app.store.collections.filter(e=>e.type==`auth`))},get canSubmit(){return!!s.email&&!!s.template&&!!s.collectionIdOrName}}),c;async function l(){if(!(s.isSending||!s.canSubmit)){s.isSending=!0,clearTimeout(c),c=setTimeout(()=>{s.isSending=!1,app.pb.cancelRequest(a),app.modals.close(),app.toasts.error(`Test email send timeout.`)},15e3);try{s.email!=app.pb.authStore.record?.email&&localStorage.setItem(i,s.email),await app.pb.settings.testEmail(s.collectionIdOrName,s.email,s.template,{requestKey:a}),app.toasts.success(`Successfully sent test email.`),app.modals.close()}catch(e){app.checkApiError(e)}s.isSending=!1,clearTimeout(c)}}let u=[];return t.div({className:`modal popup sm`,onbeforeopen:e=>{u.push(watch(()=>s.isAuthCollectionsLoading,e=>{!e&&!s.collectionIdOrName&&(s.collectionIdOrName=s.authCollections[0]?.id||``)}))},onafterclose:e=>{clearTimeout(c),e?.remove()},onunmount:()=>{clearTimeout(c),u.forEach(e=>e?.unwatch())}},t.header({className:`modal-header`},t.h5({className:`m-auto`},`Send test email`)),t.form({id:r,className:`modal-content mail-settings-test-form`,onsubmit:e=>{e.preventDefault(),l()}},t.div({className:`grid`},t.div({className:`col-lg-12`},()=>o.map((e,n)=>t.field({className:()=>`field ${n>0?`m-t-10`:``}`},t.input({type:`radio`,id:r+`.template.`+e.value,name:`template`,checked:()=>s.template==e.value,onchange:n=>s.template=e.value}),t.label({htmlFor:r+`.template.`+e.value},e.label||e.value)))),()=>{if(!e)return t.div({className:`col-lg-12`},t.div({className:`field`},t.label({htmlFor:r+`.collection`},`Auth collection`),app.components.select({id:r+`.collection`,name:`collection`,required:!0,placeholder:()=>s.isAuthCollectionsLoading?`Loading auth collections...`:`Select auth collection`,options:()=>s.authCollections.map(e=>({value:e.id,label:e.name})),value:()=>s.collectionIdOrName||``,onchange:e=>{s.collectionIdOrName=e?.[0]?.value}})))},t.div({className:`col-lg-12`},t.div({className:`field`},t.label({htmlFor:r+`.email`},`To email address`),t.input({id:r+`.email`,name:`email`,type:`email`,required:!0,value:()=>s.email||``,oninput:e=>s.email=e.target.value}))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(),disabled:()=>s.isSending},t.span({className:`txt`},`Close`)),t.button({"html-form":r,type:`submit`,className:()=>`btn expanded ${s.isSending?`loading`:``}`,disabled:()=>s.isSending||!s.canSubmit},t.i({className:`ri-mail-send-line`,ariaHidden:!0}),t.span({className:`txt`},`Send`))))}function ot(e={}){let n=store({rid:void 0,collectionA:null,collectionB:null,deleteMissing:!1,className:``}),r=app.utils.extendStore(n,e),i=store({hasAnyChange:!1,get isDeleteDiff(){return!n.collectionB?.id&&!n.collectionB?.name},get isCreateDiff(){return!i.isDeleteDiff&&!n.collectionA?.id},get hasAnyChange(){return app.utils.hasCollectionChanges(n.collectionA,n.collectionB,n.deleteMissing)},get fieldsListA(){return Array.isArray(n.collectionA?.fields)?n.collectionA?.fields:[]},get fieldsListB(){let e=Array.isArray(n.collectionB?.fields)?n.collectionB?.fields:[];return n.deleteMissing||(e=e.concat(n.collectionA?.fields?.filter(n=>!e.find(e=>n.id==e.id))||[])),e},get mainModelProps(){return app.utils.mergeUnique(Object.keys(n.collectionA||{}),Object.keys(n.collectionB||{})).filter(e=>![`fields`,`created`,`updated`].includes(e))},get removedFields(){return i.fieldsListA.filter(e=>!i.fieldsListB.find(n=>e.id==n.id))},get sharedFields(){return i.fieldsListB.filter(e=>i.fieldsListA.find(n=>n.id==e.id))},get addedFields(){return i.fieldsListB.filter(e=>!i.fieldsListA.find(n=>n.id==e.id))}});function a(e){return e===void 0?``:app.utils.isObject(e)?JSON.stringify(e,null,4):``+e}function o(e,n){return e===n?!1:JSON.stringify(e)!=JSON.stringify(n)}function s(e,n){return(e||[]).find(e=>e.id==n)}return t.div({rid:n.rid,pbEvent:`collectionsDiffTableWrapper`,className:()=>`collections-diff-table-wrapper ${n.className}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.div({className:`collections-diff-table-title`},()=>n.collectionA?.id?n.collectionB?.id?[t.span({hidden:()=>!i.hasAnyChange,className:`label import-change-label warning`,textContent:`Changed`}),t.div({className:`inline-flex gap-5`},()=>{if(n.collectionA?.name!=n.collectionB?.name)return[t.strong({className:`txt-strikethrough txt-hint`,textContent:n.collectionA?.name}),t.i({className:`ri-arrow-right-line txt-sm`,ariaHidden:!0})]},t.strong({textContent:()=>n.collectionB?.name}))]:[t.span({className:`label import-change-label danger`,textContent:`Deleted`}),t.strong({textContent:()=>n.collectionA?.name})]:[t.span({className:`label import-change-label success`,textContent:`Added`}),t.strong({textContent:()=>n.collectionB?.name})]),t.table({className:`collections-diff-table`},t.thead(null,t.tr(null,t.th({className:`min-width`},`Props`),t.th({width:`40%`},`Old`),t.th({width:`40%`},`New`))),t.tbody(null,()=>i.mainModelProps.map(e=>{let r=o(n.collectionA?.[e],n.collectionB?.[e]);return t.tr({className:r?`txt-primary`:``},t.td({className:`min-width`},e),t.td({className:()=>i.isCreateDiff?`changed-non-col`:r?`changed-old-col`:``},t.pre({className:`txt diff-value`},a(n.collectionA?.[e]))),t.td({className:()=>i.isDeleteDiff?`changed-non-col`:r?`changed-new-col`:``},t.pre({className:`txt diff-value`},a(n.collectionB?.[e]))))}),()=>{if(!n.deleteMissing&&!i.isDeleteDiff)return;let e=[];for(let n of i.removedFields){e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label danger m-l-5`},`Deleted - `,t.small(null,`All stored data related to '${n.name}' will be deleted!`)))));for(let r in n){let i=n[r];e.push(t.tr(null,t.td({className:`min-width field-key-col`},r),t.td({className:`changed-old-col`},t.pre({className:`txt`},a(i))),t.td({className:`changed-none-col`})))}}return e},()=>{let e=[];for(let n of i.sharedFields){let r=s(i.fieldsListA,n.id),c=o(r,s(i.fieldsListB,n.id));e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label warning m-l-5 ${c?``:`hidden`}`,textContent:`Changed`}))));for(let i in n){let s=n[i],c=o(r?.[i],s);e.push(t.tr({className:c?`txt-primary`:``},t.td({className:`min-width field-key-col`},i),t.td({className:c?`changed-old-col`:``},t.pre({className:`txt`},a(r?.[i]))),t.td({className:c?`changed-new-col`:``},t.pre({className:`txt`},a(s)))))}}return e},()=>{let e=[];for(let n of i.addedFields){e.push(t.tr(null,t.th({className:`min-width`,colSpan:3},t.span({className:`txt`},`field: `,n.name),t.span({className:`label success m-l-5`},`Added`))));for(let r in n){let i=n[r];e.push(t.tr({className:`txt-primary`},t.td({className:`min-width field-key-col`},r),t.td({className:`changed-none-col`}),t.td({className:`changed-new-col`},t.pre({className:`txt`},a(i)))))}}return e})))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openImportCollectionsReview=function(e,n,r={deleteMissing:!1,onsubmit:null}){let i=st(e,n,r);i&&(document.body.appendChild(i),app.modals.open(i))};function st(e,n,r){let i,a=store({deleteMissing:!1,onsubmit:function(e){}}),o=app.utils.extendStore(a,r),s=store({isImporting:!1,pairs:[]});function c(){let r=[];for(let i of e){let e=n.find(e=>e.id==i.id);(a.deleteMissing&&!e?.id||e?.id&&app.utils.hasCollectionChanges(i,e,a.deleteMissing))&&r.push({old:i,new:e})}for(let i of n){let n=e.find(e=>e.id==i.id);n?.id||r.push({old:n,new:i})}s.pairs=r}function l(){let r=[];if(a.deleteMissing)for(let i of e){let e=n.find(e=>e.id==i.id);if(!e)r.push(i.name+`.*`);else{let n=Array.isArray(i.fields)?i.fields:[];for(let a of n)e.fields.find(e=>e.id==a.id)||r.push(`${i.name}.${a.name} (${a.id})`)}}r.length?app.modals.confirm([t.h6(null,`Do you really want to delete the following collection fields and their related records data:`),t.ul(null,()=>r.map(e=>t.li(null,e)))],()=>u()):u()}async function u(){if(!s.isImporting){s.isImporting=!0;try{await app.pb.collections.import(n,a.deleteMissing),await app.store.loadCollections(),a.onsubmit?.(JSON.parse(JSON.stringify(app.store.collections))),app.toasts.success(`Successfully imported collections configuration.`)}catch(e){app.checkApiError(e)}s.isImporting=!1,app.modals.close(i)}}return i=t.div({pbEvent:`importCollectionsReviewModal`,className:`modal popup full import-collections-review-modal`,onbeforeopen:()=>{c()},onbeforeclose:()=>!s.isImporting,onafterclose:e=>{e?.remove()},onunmount:()=>{o.forEach(e=>e?.unwatch())}},t.header({className:`modal-header`},t.h5(null,`Side-by-side diff`)),t.div({className:`modal-content`},()=>s.pairs.map(e=>ot({collectionA:e.old,collectionB:e.new,deleteMissing:a.deleteMissing}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,disabled:()=>s.isImporting,onclick:()=>app.modals.close(i)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:()=>`btn expanded ${s.isImporting?`loading`:``}`,disabled:()=>s.isImporting,onclick:()=>l()},t.span({className:`txt`},`Confirm and import`)))),i}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.recordSummary=function(e,n=null){let r=store({get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)},get presentableFields(){if(!r.collection?.id)return[];let e=r.collection.fields.filter(e=>e.presentable).sort((e,n)=>{let r=app.fieldTypes[e.type].summaryPriority||0,i=app.fieldTypes[n.type].summaryPriority||0;return r>i?1:re.name==n);if(i){e.push(i);break}}return e}});return t.div({className:`label record-summary`},t.i({ariaHidden:!0,className:`ri-eye-line link-hint record-preview-icon`,onclick:e=>{e.stopImmediatePropagation(),e.preventDefault()},onmouseenter:n=>{lt(n.target,e,100)},onmouseleave:e=>{ct(e.target,100)},onunmount:e=>{ct(e,0)}}),()=>{let i=[];function a(e){(e==null||e==``)&&(e=t.span({className:`missing-value`})),i.push(e)}for(let i of r.presentableFields){let r=app.fieldTypes[i.type]?.view;if(r)a(r({short:!0,get record(){return e},get field(){return i},get meta(){return n}}));else{let n=app.utils.toArray(e[i.name]).splice(0,3);for(let e of n)a(e)}}return i})};function ct(e,n=150){if(e){if(clearTimeout(e._summaryDropdownTimeoutId),n<=0){e?._summaryDropdown?.hidePopover?.();return}e._summaryDropdownTimeoutId=setTimeout(()=>{e?._summaryDropdown?.hidePopover?.()},n)}}function lt(e,n,r=150){if(e){if(clearTimeout(e._summaryDropdownTimeoutId),r<=0){ut(e,n);return}e._summaryDropdownTimeoutId=setTimeout(()=>{ut(e,n)},r)}}var ut=function(e,n){e&&(e._summaryDropdown||(e._summaryDropdown=t.div({className:`dropdown record-summary-dropdown`,popover:`manual`,onclick:e=>{e.stopImmediatePropagation(),e.preventDefault()}},t.div({className:`record-header`},t.a({className:`link-hint txt-bold m-r-auto`,target:`_blank`,href:`#/collections?collection=${n.collectionName}&record=${n.id}`,onclick:e=>{e.stopImmediatePropagation()}},t.span({className:`txt`},`Edit relation record`),t.i({className:`ri-external-link-line`,ariaHidden:!0})),t.button({type:`button`,className:`link-hint`,title:`Close`,onclick:()=>ct(e,0)},t.i({className:`ri-close-line`,ariaHidden:!0}))),t.hr(),t.pre({className:`record-json`},()=>{let e=app.store.collections.find(e=>e.id==n.collectionId||e.name==n.collectionName)?.fields||[];if(!e.length)return;let r={collectionId:n.collectionId,collectionName:n.collectionName};for(let i of e)r[i.name]=n[i.name];return JSON.stringify(app.utils.truncateObject(r,27),null,2)})),e.appendChild(e._summaryDropdown)),e._summaryDropdown?.showPopover({source:e}))};window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.recordsSearchbar=function(e={}){let n=store({rid:void 0,id:void 0,hidden:void 0,inert:void 0,disabled:void 0,value:``,className:``,collection:void 0,onsubmit:e=>{}}),r=app.utils.extendStore(n,e);return t.div({rid:n.rid,id:()=>n.id,hidden:()=>n.hidden,inert:()=>n.inert,className:()=>`full-width records-searchbar-wrapper ${n.className}`,onunmount:()=>{r.forEach(e=>e?.unwatch())}},app.components.searchbar({placeholder:()=>!n.disabled&&!n.collection?.id?`Loading...`:`Search term or filter...`,historyKey:()=>`pbRecordsSearchHistory_`+n.collection?.id,disabled:()=>n.disabled||!n.collection,value:()=>n.value,autocomplete:e=>app.utils.collectionAutocompleteKeys(n.collection,e,{requestKeys:!1,collectionJoinKeys:!1}),onsubmit:n.onsubmit}))},window.app=window.app||{},window.app.components=window.app.components||{};var I={max:10,pending:new Set,processing:new Set};function dt(e){return I.pending.add(e),I.processing.size<=I.max&&ft(),()=>{I.pending.delete(e),I.processing.delete(e),I.processing.sizen.id,hidden:()=>n.hidden,inert:()=>n.inert,type:`button`,draggable:!1,className:()=>`thumb ${n.extraClasses} ${i.isPreviewLoading?`loading`:``}`,title:()=>(i.hasPreview?`Preview`:`Download`)+` `+n.filename,onclick:async e=>{e.stopPropagation();async function r(){let e=await app.getFileToken(n.record.collectionId);return app.pb.files.getURL(n.record,n.filename,{token:e})}if(i.hasPreview)app.modals.openFilePreview(r);else{let e=await r();app.utils.download(e,n.filename)}},onunmount:()=>{r.forEach(e=>e?.unwatch())}},()=>{if(i.fileType==`image`){let e=t.img({draggable:!1,alt:()=>`Thumb of `+n.filename,src:()=>i.previewURL,onerror:n=>{console.warn(`[recordFileThumb] load err:`,n),i.isPreviewLoading=!1,e?._semaphoreRelease?.()},onload:()=>{i.isPreviewLoading=!1,e?._semaphoreRelease?.()},onmount:e=>{i.isPreviewLoading=!0,e._semaphoreRelease=dt(async()=>{try{i.previewToken=await app.getFileToken(n.record.collectionId),i.previewURL=app.pb.files.getURL(n.record,n.filename,{thumb:`100x100`,token:i.previewToken})}catch(e){console.warn(e)}})},onunmount:e=>{i.isPreviewLoading=!1,e._semaphoreRelease?.()}});return e}return t.i({className:app.utils.fileTypeIcons[i.fileType]||`ri-file-line`,ariaHidden:!0})})},window.app=window.app||{},window.app.modals=window.app.modals||{};var pt=100,mt={btnText:`Insert`,fileTypes:[],onselect:function(e){}},ht=`pbLastRecordFilePickerCollection`,gt=`listFilePickerRecords`;window.app.modals.openRecordFilePicker=function(e={}){e=Object.assign({},mt,e);let n=_t(e);document.body.appendChild(n),app.modals.open(n)};function _t(e=mt){let n,r=`file_picker_`+app.utils.randomString(),i=store({selectedFile:{},records:[],activeCollectionId:``,searchTerm:``,lastRecordsPage:1,lastTotalRecords:0,isLoadingRecords:!1,get collections(){return app.utils.sortedCollections(app.store.collections.filter(e=>e.type==`view`?!1:!!e.fields?.find(e=>e.type===`file`&&!e.protected)))},get activeCollection(){return i.collections.find(e=>e.id==i.activeCollectionId)||i.collections[0]},get activeCollectionFileFields(){return i.activeCollection?.fields?.filter(e=>e.type===`file`&&!e.protected)||[]},get isLoading(){return app.store.isLoadingCollections||i.isLoadingRecords},get canLoadMore(){return!i.isLoadingRecords&&i.lastTotalRecords==pt},get hasAtleastOneFile(){return!!i.records.find(e=>c(e).length>0)}}),a=[];a.push(watch(()=>{i.activeCollectionId?(window.localStorage.setItem(ht,i.activeCollectionId),i.searchTerm=``):i.activeCollectionId=window.localStorage.getItem(ht)})),a.push(watch(()=>[i.activeCollection,i.searchTerm],()=>s(!0)));function o(){app.pb.cancelRequest(gt),i.isLoadingRecords=!1,i.records=[],i.lastTotalRecords=0,i.lastRecordsPage=1,i.selectedFile={}}async function s(e=!1){if(!i.activeCollection){o();return}e&&o(),i.isLoadingRecords=!0;try{let n=e?1:i.lastRecordsPage+1,r=app.utils.getAllCollectionIdentifiers(i.activeCollection),a=app.utils.normalizeSearchFilter(i.searchTerm,r)||``;a&&(a+=` && `),a+=`(`+i.activeCollectionFileFields.map(e=>`${e.name}:length>0`).join(`||`)+`)`;let o=await app.pb.collection(i.activeCollection.id).getList(n,pt,{requestKey:gt,filter:a,skipTotal:1,sort:i.activeCollection.type==`view`?``:`-@rowid`});i.lastRecordsPage=o.page,i.lastTotalRecords=o.items.length,i.records=app.utils.filterDuplicatesByKey(i.records.concat(o.items)),i.isLoadingRecords=!1}catch(e){e.isAbort||(i.isLoadingRecords=!1,app.checkApiError(e))}}function c(n){let r=[];for(let a of i.activeCollectionFileFields){let i=app.utils.toArray(n[a.name]);for(let n of i)(app.utils.isEmpty(e.fileTypes)||e.fileTypes?.includes(app.utils.getFileType(n)))&&r.push(n)}return r}function l(e,n){i.selectedFile={record:e,name:n,thumb:``}}function u(e,n){return i.selectedFile?.name==n&&i.selectedFile?.record?.id==e?.id}let d={"record:create":e=>{e.detail.collectionId==i.activeCollection?.id&&(i.selectedFile?.record?.id==e.detail.id&&(i.selectedFile.record=e.detail),s(!0))},"record:delete":e=>{e.detail.collectionId!=i.activeCollection?.id&&e.detail.collectionName!=i.activeCollection?.name||(i.selectedFile?.record?.id==e.detail.id&&(i.selectedFile={}),s(!0))}};return n=t.div({className:`modal popup record-file-picker-modal`,onafterclose:e=>{e?.remove()},onmount:e=>{for(let e in d)document.addEventListener(e,d[e])},onunmount:e=>{a.forEach(e=>e?.unwatch());for(let e in d)document.removeEventListener(e,d[e])}},t.header({className:`modal-header`},t.button({className:()=>`btn primary outline record-file-picker-collection-select-btn ${app.store.isLoadingCollections?`loading`:``}`,disabled:()=>app.store.isLoadingCollections,"html-popovertarget":`collections_dropdown`+r},t.span({className:`txt-lg collection-name m-r-auto`},()=>i.activeCollection?.name||`Select collection`),t.i({className:`ri-arrow-drop-down-line`,ariaHidden:!0})),t.div({id:`collections_dropdown`+r,className:`dropdown`,popover:`hint`},()=>i.collections.map(e=>t.button({type:`button`,className:()=>`dropdown-item ${i.activeCollectionId==e.id?`active`:``}`,onclick:n=>{i.activeCollectionId=e.id,n.target?.closest(`.dropdown`)?.hidePopover()}},e.name))),app.components.recordsSearchbar({disabled:()=>!i.activeCollection?.id,collection:()=>i.activeCollection,value:()=>i.searchTerm,onsubmit:e=>i.searchTerm=e}),t.button({type:`button`,className:`btn circle transparent`,ariaLabel:app.attrs.tooltip(`Add new record`),onclick:()=>app.modals.openRecordUpsert(i.activeCollection)},t.i({className:`ri-add-line txt-hint`,ariaHidden:!0}))),t.div({className:`modal-content`},t.div({className:`block txt-center`,hidden:()=>i.hasAtleastOneFile||!i.isLoading},t.span({className:`loader`})),t.div({className:`record-file-picker-list`},()=>{let e=[];for(let n of i.records){let r=c(n);for(let i of r)e.push(t.button({rid:n.id+`:`+i,className:()=>`list-item thumb ${u(n,i)?`success`:``}`,ariaDescription:app.attrs.tooltip(i,`bottom`),onclick:()=>l(n,i)},()=>{if(app.utils.hasImageExtension(i))return t.img({loading:`lazy`,src:app.pb.files.getURL(n,i,{thumb:`100x100`}),alt:i});let e=app.utils.getFileType(i);return t.i({className:app.utils.fileTypeIcons[e]||`ri-file-line`,ariaHidden:!0})}))}return e}),t.div({hidden:()=>!i.canLoadMore||!i.hasAtleastOneFile,className:`block txt-center`},t.button({className:()=>`btn secondary expanded-lg m-t-base ${i.isLoadingRecords?`loading`:``}`,disabled:()=>i.isLoadingRecords,onclick:()=>s()},t.span({className:`txt`},`Load more`))),t.div({className:`block txt-center txt-hint p-t-10 p-b-10`,hidden:()=>i.hasAtleastOneFile||i.isLoading},()=>app.utils.isEmpty(e.fileTypes)?t.p(null,`No records with selectable files found.`):t.p(null,`No "${e.fileTypes.join(`", "`)}" files found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,hidden:()=>!i.searchTerm?.length,onclick:()=>{i.searchTerm=``}}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n)},t.span({className:`txt`},`Close`)),()=>{if(!i.selectedFile?.name||!app.utils.hasImageExtension(i.selectedFile.name))return;let e=[{value:``,label:`Original size`},{value:`100x100`,label:`100x100 thumb`}],n=i.activeCollectionFileFields.find(e=>i.selectedFile.record[e.name].includes(i.selectedFile.name)),r=app.utils.toArray(n.thumbs);for(let n of r)e.push({value:n,label:`${n} thumb`});return t.div({className:`record-file-picker-thumb-select`},app.components.select({required:!0,value:i.selectedFile.thumb||``,options:e,onchange:e=>{i.selectedFile.thumb=e?.[0].value}}))},t.button({type:`button`,className:`btn expanded`,disabled:()=>i.isLoading||!i.selectedFile?.name,onclick:()=>{let r=JSON.parse(JSON.stringify(i.selectedFile));if(e.onselect&&e.onselect(r)===!1)return!1;app.modals.close(n)}},t.span({className:`txt`},()=>e.btnText||mt.btnText)))),n}window.app=window.app||{},window.app.modals=window.app.modals||{};var vt=50,yt=100,bt=`listRelationPickerRecords`,xt={collection:``,selectedIds:[],maxSelect:1,btnText:`Set selection`,onselect:function(e){}};window.app.modals.openRecordsPicker=function(e={}){e=Object.assign({},xt,e);let n=St(e);document.body.appendChild(n),app.modals.open(n)};function St(e=xt){let n,r=store({searchTerm:``,selected:[],preselected:[],isLoadingPreselected:!1,records:[],isLoadingRecords:!1,lastRecordsPage:1,lastRecordsTotal:0,get collection(){let n=e.collection;return typeof e.collection==`object`&&e.collection?.id&&(n=e.collection?.id),app.store.collections.find(e=>e.id==n||e.name==n)},get isLoading(){return r.isLoadingPreselected||r.isLoadingRecords},get canLoadMore(){return!r.isLoadingRecords&&r.lastRecordsTotal==vt}}),i=[watch(()=>[e.collection,e.selectedIds],()=>{o()}),watch(()=>[r.collection,r.searchTerm],()=>{s(!0)})];function a(){setTimeout(()=>app.modals.close(n),0)}async function o(){let n=app.utils.toArray(e.selectedIds),i=e.collection?.id||e.collection;if(!i||!n.length)return;r.isLoadingSelected=!0;let a=[],o=n.slice(),s=[];for(;o.length>0;){let e=[],n=o.splice(0,yt);for(let r of n)e.push(`id="${r}"`);s.push(app.pb.collection(i).getFullList({requestKey:null,filter:e.join(`||`)}))}try{await Promise.all(s).then(e=>{a=a.concat(...e)});let e=[];for(let r of n){let n=a.find(e=>e.id==r);n&&e.push(n)}r.searchTerm.trim()||(r.records=app.utils.filterDuplicatesByKey(e.concat(r.records))),r.selected=e,r.isLoadingSelected=!1}catch(e){e.isAbort||(app.checkApiError(e),r.isLoadingSelected=!1)}}async function s(e=!1){if(r.collection?.id){e&&(c(),r.searchTerm.trim()||(r.records=r.selected.slice())),r.isLoadingRecords=!0;try{let n=e?1:r.lastRecordsPage+1,i=app.utils.getAllCollectionIdentifiers(r.collection),a=app.utils.normalizeSearchFilter(r.searchTerm,i)||``,o=await app.pb.collection(r.collection.id).getList(n,vt,{requestKey:bt,filter:a,skipTotal:1,sort:r.collection.type==`view`?``:`-@rowid`});r.lastRecordsPage=o.page,r.lastRecordsTotal=o.items.length,r.records=app.utils.filterDuplicatesByKey(r.records.concat(o.items)),r.isLoadingRecords=!1}catch(e){e.isAbort||(r.isLoadingRecords=!1,app.checkApiError(e))}}}function c(){app.pb.cancelRequest(bt),r.isLoadingRecords=!1,r.records=[],r.lastTotalRecords=0,r.lastRecordsPage=1}function l(e){e.target.scrollHeight-e.target.clientHeight-e.target.scrollTop<=100&&r.canLoadMore&&s()}function u(n){let i=r.selected.findIndex(e=>e.id==n.id);if(i>=0)r.selected.splice(i,1);else{let i=e.maxSelect||1,a=r.selected.length-i;for(;a>=0;)r.selected.pop(),a--;r.selected.push(n)}}function d(e){return r.selected.findIndex(n=>n.id==e.id)>=0}let f={"record:save":e=>{if(e.detail.collectionId!=r.collection?.id)return;let n=r.selected?.findIndex(n=>n.id==e.detail.id);n>=0&&(r.selected[n]=e.detail),app.utils.pushOrReplaceObject(r.records,e.detail),s(!0)},"record:delete":e=>{e.detail.collectionId!=r.collection?.id&&e.detail.collectionName!=r.collection?.name||(d(e.detail)&&u(e.detail),app.utils.removeByKey(r.records,`id`,e.detail.id),s(!0))}};return n=t.div({className:`modal popup lg records-picker-modal`,onafterclose:e=>{e.remove()},onmount:e=>{for(let e in f)document.addEventListener(e,f[e])},onunmount:e=>{i.forEach(e=>e?.unwatch());for(let e in f)document.removeEventListener(e,f[e])}},t.header({className:`modal-header`},t.h6({className:`collection-name`},()=>r.collection.name),app.components.recordsSearchbar({disabled:()=>!r.collection?.id,collection:()=>r.collection,value:()=>r.searchTerm,onsubmit:e=>r.searchTerm=e}),t.button({type:`button`,className:`btn circle transparent`,ariaLabel:app.attrs.tooltip(`Add new record`),onclick:()=>{app.modals.openRecordUpsert(r.collection)}},t.i({className:`ri-add-line txt-hint`,ariaHidden:!0}))),t.div({className:`modal-content`,hidden:()=>r.isLoadingCollection},t.div({className:`list records-picker-list`,onscroll:l,onresize:l},()=>r.records.map(e=>t.div({tabIndex:0,className:`list-item handle`,onclick:()=>{u(e),document.activeElement?.blur()}},t.div({className:`content`},t.span({className:`state-icon`},t.i({ariaHidden:!0,className:()=>d(e)?`ri-checkbox-circle-fill txt-success`:`ri-checkbox-blank-circle-line txt-disabled`})),()=>app.components.recordSummary(e)),t.div({className:`actions autohide`},t.button({className:`btn sm secondary transparent circle`,ariaLabel:app.attrs.tooltip(`Edit`),onclick:n=>{n.stopPropagation(),app.modals.openRecordUpsert(r.collection,e)}},t.i({className:`ri-pencil-line`,ariaHidden:!0}))))),t.div({className:`list-item`,hidden:()=>!r.isLoading},t.div({className:`skeleton-loader`})),t.div({className:`list-item`,hidden:()=>r.records.length||r.isLoading},t.div({className:`content txt-hint`},t.span({className:`txt`},`No records found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,hidden:()=>!r.searchTerm.trim().length,onclick:()=>{r.searchTerm=``}})))),t.div({className:`block m-t-base`},t.p({className:`txt-bold`},()=>`Selected (${r.selected.length} of max ${e.maxSelect||1})`),t.span({className:`txt-hint`,hidden:()=>r.selected},`No selected records.`),app.components.sortable({className:`records-picker-selected-list`,data:()=>r.selected,dataItem:(e,n)=>t.div({rid:e,className:`label handle`},()=>app.components.recordSummary(e,[],!0),t.span({className:`link-hint`,title:`Remove`,role:`button`,onclick:()=>u(e)},t.i({className:`ri-close-line`,ariaHidden:!0}))),onchange:(e,n,i)=>{r.selected=e}}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>a()},t.span({className:`txt`},`Close`)),()=>{if(!r.selectedFile?.name||!app.utils.hasImageExtension(r.selectedFile.name))return;let e=[{value:``,label:`Original size`},{value:`100x100`,label:`100x100 thumb`}],n=r.activeCollectionFileFields.find(e=>r.selectedFile.record[e.name].includes(r.selectedFile.name)),i=app.utils.toArray(n.thumbs);for(let n of i)e.push({value:n,label:`${n} thumb`});return t.div({className:`record-file-picker-thumb-select`},app.components.select({required:!0,value:r.selectedFile.thumb||``,options:e,onchange:e=>{r.selectedFile.thumb=e?.[0].value}}))},t.button({type:`button`,className:`btn expanded`,disabled:()=>r.isLoadingCollection,onclick:()=>{let n=JSON.parse(JSON.stringify(r.selected));if(e.onselect&&e.onselect(n)===!1)return!1;a()}},t.span({className:`txt`},e.btnText||xt.btnText)))),n}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openRecordPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=R(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};function Ct(e){e.expand&&(e=Object.assign({},e),delete e.expand),app.utils.downloadJSON(e,e.collectionName+`_`+e.id+`.json`)}function wt(e){e.expand&&(e=Object.assign({},e),delete e.expand),app.utils.copyToClipboard(JSON.stringify(e,null,2)),app.toasts.success(`Record copied to clipboard!`)}function R(e,n){let r,i=app.utils.randomString(),a=store({isLoading:!1,record:null,get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)}});async function o(){if(!e?.id){app.toasts.error(`Failed to load record.`),setTimeout(()=>app.modals.close(r),0),console.warn(`[recordPreviewModal] missing required record id field:`,e);return}if(!e.collectionId&&!e.collectionName){app.toasts.error(`Failed to load record.`),setTimeout(()=>app.modals.close(r),0),console.warn(`[recordPreviewModal] missing required collectionId or collectionName field:`,e);return}a.isLoading=!0;try{let n=[],r=a.collection?.fields?.filter(e=>!e.hidden&&e.presentable&&e.type==`relation`)||[];for(let e of r)n.push(e.name);a.record=await app.pb.collection(e.collectionId||e.collectionName).getOne(e.id,{requestKey:`record_preview_`+e.id,expand:n.join(`,`)||void 0}),a.isLoading=!1}catch(e){e?.isAbort||(a.isLoading=!1,app.checkApiError(e),setTimeout(()=>app.modals.close(r),0))}}return r=t.div({pbEvent:`recordPreviewModal`,className:`modal record-preview-modal`,onbeforeopen:e=>(o(),n.onbeforeopen?.(e)),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()},onmount:e=>{},onunmount:e=>{}},t.header({className:`modal-header`},t.h6(null,t.strong(null,()=>e?.collectionName||a.collection?.name),` record preview`),t.button({title:`More options`,className:`btn sm circle transparent m-l-auto`,"html-popovertarget":i+`preview-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:i+`preview-dropdown`,className:`dropdown`,popover:`auto`},e=>t.button({className:`dropdown-item`,onclick:()=>{wt(a.record),e.hidePopover()}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)))),t.div({className:`modal-content`},()=>a.isLoading||!a.record?.id||!a.collection?.id?t.table(null,t.tbody(null,()=>{let e=a.collection?.fields?.filter(e=>e.type!=`password`).length||1,n=[];for(let r=0;r(a.collection?.fields?.filter(e=>e.type!=`password`)||[]).map(e=>t.tr(null,t.th({className:()=>`min-width p-r-0 col-field-name-${e.name}`},e.name),t.td({className:()=>`col-field-name-${e.name}`},()=>app.fieldTypes[e.type]?.view?app.fieldTypes[e.type].view({short:!1,get record(){return a.record},get field(){return e}}):app.utils.displayValue(a.record[e.name],1e3))))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:`btn`,onclick:()=>Ct(a.record)},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`Download JSON`)))),r}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openRecordImpersontate=function(e){let n=z(e);document.body.appendChild(n),app.modals.open(n)};function z(e){let n=`impersonate_`+app.utils.randomString(),r=store({isLoading:!1,token:``,duration:0,get collection(){return app.store.collections.find(n=>n.id==e.collectionId||n.name==e.collectionName)}}),i=app.utils.getApiExampleURL();async function a(){if(!r.isLoading){r.isLoading=!0;try{r.token=(await app.pb.collection(r.collection.name).impersonate(e.id,r.duration)).authStore.token}catch(e){app.checkApiError(e)}r.isLoading=!1}}function o(){r.token=``,r.duration=0}return t.div({className:`modal popup record-impersonate-auth-modal`,onbeforeclose:()=>!r.isLoading,onafterclose:e=>{e?.remove()}},t.header({className:`modal-header`},t.h6(null,`Generate nonrenewable auth token for `,t.strong(null,()=>e.email||e.id))),t.div({className:`modal-content`},t.form({id:n+`_form`,hidden:()=>r.token,className:`block`,onsubmit:e=>{e.preventDefault(),a()}},t.div({className:`field`},t.label({htmlFor:n+`_duration`},`Token duration (in seconds)`),t.input({id:n+`_duration`,type:`number`,name:`duration`,min:0,step:1,placeholder:()=>`Default to the collection settings (${r.collection?.authToken?.duration||0}s)`,value:e=>r.duration||``,oninput:e=>r.duration=parseInt(e.target.value,10)}))),t.div({hidden:()=>!r.token,className:`alert success impersonate-success`},t.strong(null,()=>r.token),` `,app.components.copyButton(()=>r.token)),app.components.codeBlockTabs({hidden:()=>!r.token,className:`sdk-examples m-t-base`,tabs:[{title:`JS SDK`,language:`js`,value:` import PocketBase from 'pocketbase'; const pb = new PocketBase('${i}'); @@ -42,7 +42,7 @@ import{a as e,n,r,t as i}from"./pocketbase.es-B_4DUNUU.js";var a=Object.create,o final token = '...'; pb.authStore.save(token, null); `,footnote:t.div({className:`txt-right`},t.a({href:`https://github.com/pocketbase/dart-sdk`,target:`_blank`,rel:`noopener noreferrer`,textContent:`Dart SDK docs`}))}]})),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,disabled:()=>r.isLoading,onclick:()=>app.modals.close()},t.span({className:`txt`},`Close`)),t.button({hidden:()=>r.token,type:`submit`,"html-form":n+`_form`,className:()=>`btn expanded-lg ${r.isLoading?`loading`:``}`,disabled:()=>r.isLoading},t.span({className:`txt`},`Generate token`)),t.button({hidden:()=>!r.token,type:`button`,className:()=>`btn secondary expanded-lg ${r.isLoading?`loading`:``}`,onclick:()=>o()},t.span({className:`txt`},`Generate new one`))))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openRecordUpsert=function(e,n=null,r={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,onsave:null,ondelete:null,onduplicate:null,ontokensreset:null,onpasswordresetsend:null,onverificationsend:null}){app.store.errors=null;let i=kt(e,n,r);i&&(document.body.appendChild(i),app.modals.open(i))};var Tt=[`expand`];function Et(e,n=Tt){if(n.find(n=>e[n]!==void 0)){e=Object.assign({},e);for(let r of n)delete e[r]}return e}function Dt(e){e=Et(e),app.utils.copyToClipboard(JSON.stringify(e,null,2)),app.toasts.success(`Record copied to clipboard!`)}function Ot(e){return e?JSON.stringify(e):``}var B=`main`,V=`authProviders`;function kt(e,n,r){if(!e?.id){console.warn(`[recordUpsertModal] missing required collection`);return}let i,a=`record_upsert_`+app.utils.randomString(),o=app.utils.getLocalHistory(app.consts.COLUMNS_STORAGE_PREFIX+e.id,{}),s=store({isLoading:!0,isSaving:!1,isLocked:!1,originalRecord:{},record:{},initialDraft:null,activeTab:B,get isNew(){return app.utils.isEmpty(s.originalRecord?.id)},get isAuthCollection(){return e.type==`auth`},get isSuperusersCollection(){return e.name==`_superusers`},get showTabs(){return!s.isNew&&s.isAuthCollection&&!s.isSuperusersCollection},get excludedFields(){let e=[`id`];return s.isAuthCollection&&e.push(`email`,`emailVisibility`,`verified`,`password`,`tokenKey`),e},get initialDraftHash(){return Ot(s.initialDraft)},get recordHash(){return Ot(s.record)},get originalRecordHash(){return Ot(s.originalRecord)},get hasChanges(){return s.originalRecordHash!=s.recordHash},get isFormDisabled(){return s.isLoading||s.isSaving||!s.isNew&&!s.hasChanges}});function c(){return`draft_`+e.id+`_`+(s.originalRecord?.id||``)}function l(){return window.localStorage.getItem(c())||``}function u(){try{let e=l();if(e)return JSON.parse(e)}catch(e){console.warn(`getDraft failure:`,e),f()}return null}function d(e){try{window.localStorage.setItem(c(),e)}catch(e){console.warn(`saveDraft failure:`,e),f()}}function f(){window.localStorage.removeItem(c()),s.initialDraft=null}function p(){if(!s.initialDraft)return;app.store.errors&&(app.store.errors=null);let e=JSON.parse(JSON.stringify(s.initialDraft));f(),s.record=e}async function m(n){s.isLoading=!0;let r=typeof n==`string`?n:n?.id;if(!r){let e=app.utils.isObject(n)?JSON.parse(JSON.stringify(n)):{};s.originalRecord=app.utils.emptyClone(e,[`collectionId`,`collectionName`]),s.initialDraft=u(),s.record=e,s.isLoading=!1,s.isLocked=!1;return}s.isLocked=!!app.store.settings?.meta?.hideControls;try{s.originalRecord={id:r};let n=await app.pb.collection(e.name).getOne(r,{requestKey:`upsert_load_`+r});s.originalRecord=n,s.initialDraft=u(),s.record=JSON.parse(JSON.stringify(n)),s.isLoading=!1}catch(e){e?.isAbort||(app.checkApiError(e),s.isLoading=!1,setTimeout(()=>app.modals.close(i,!0),0))}}async function h(){let n={};for(let e in s.record){if(e==`expand`||e.startsWith(`@@`))continue;let r=s.record[e]?.__raw||s.record[e];r===void 0&&(r=null),n[e]=r}for(let r of e.fields){let i=app.fieldTypes[r.type]?.onrecordsave;i&&await i({collection:e,originalRecord:s.originalRecord,record:s.record,field:r,payload:n})}return n}async function g(n=!0){if(!(s.isLocked||s.isSaving||!s.isNew&&!s.hasChanges)){s.isSaving=!0;try{let a=await h(),o=app.utils.isEmpty(s.originalRecord?.id),c;c=o?await app.pb.collection(e.name).create(a):await app.pb.collection(e.name).update(s.originalRecord.id,a),f(),o?(s.originalRecord=structuredClone(c),s.record=structuredClone(c)):(Object.assign(s.originalRecord,structuredClone(c)),Object.assign(s.record,structuredClone(c))),r.onsave?.(structuredClone(c),o),app.store.errors=null;let l;l=o?`Successfully created ${e.name} "${c.id}".`:`Successfully updated ${e.name} "${c.id}".`,app.toasts.success(l,{key:`recordSave`}),s.isSaving=!1,n&&app.modals.close(i,!0)}catch(e){e?.isAbort||(s.isSaving=!1,app.checkApiError(e,!1),app.toasts.error(e.message||`Failed to save record.`,{key:`recordSave`}))}}}function _(){f(),s.record=JSON.parse(JSON.stringify(s.originalRecord))}async function v(){let n=s.originalRecord?JSON.parse(JSON.stringify(s.originalRecord)):{};n.id=``;for(let r of e.fields){let i=app.fieldTypes[r.type]?.onrecordduplicate;i&&await i({collection:e,field:r,originalRecord:s.originalRecord,clone:n})}f(),r.onduplicate?.(n),m(n)}let ee=[];function te(){return[t.div({className:`modal-content`},t.form({id:a+`form`,className:`grid`,inert:()=>s.isLoading||s.isSaving,onsubmit:e=>{e.preventDefault()},onmount:e=>{e._quickSaveHandler=e=>{(e.ctrlKey||e.metaKey)&&e.code==`KeyS`&&(e.preventDefault(),g(!1))},window.addEventListener(`keydown`,e._quickSaveHandler)},onunmount:e=>{e?._quickSaveHandler&&window.removeEventListener(`keydown`,e?._quickSaveHandler)}},()=>{if(!(s.isLoading||s.hasChanges||app.utils.isEmpty(s.initialDraft)||s.initialDraftHash==s.recordHash))return t.div({className:`col-12`},t.div({className:`alert warning flex gap-sm`},t.div({className:`content`},`The record has previous unsaved changes.`),t.button({type:`button`,className:`btn sm outline`,onclick:()=>p()},t.span({className:`txt`},`Restore draft`)),t.button({type:`button`,className:`btn sm secondary transparent circle m-l-auto`,ariaLabel:app.attrs.tooltip(`Discard draft`,`left`),onclick:()=>{f()}},t.i({className:`ri-close-line`,ariaHidden:!0}))))},()=>{let n=e.fields?.find(e=>e.primaryKey);return t.div({className:`col-12`},app.fieldTypes[n.type].input({get collection(){return e},get originalRecord(){return s.originalRecord},get record(){return s.record},get field(){return n}}))},()=>{if(!s.isAuthCollection)return;let n=[t.div({className:`col-12`},U(e,s)),t.div({className:`col-12`},Ft(e,s))];return s.isSuperusersCollection||n.push(t.div({className:`col-12`},Pt(e,s))),n},()=>{let n=[],r=s.excludedFields;for(let i of e.fields)!app.fieldTypes[i.type]?.input||r.includes(i.name)||n.push(t.div({className:()=>`col-12 ${i.hidden&&!o[i.id]?`hidden-field-blur`:``}`},()=>app.fieldTypes[i.type].input({get collection(){return e},get originalRecord(){return s.originalRecord},get record(){return s.record},get field(){return i}})));return n.length&&s.isAuthCollection&&n.unshift(t.div({className:`col-12`},t.hr({className:`m-0`}))),n})),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,disabled:()=>s.isSaving,onclick:()=>app.modals.close(i)},t.span({className:`txt`},`Close`)),t.button({hidden:()=>!s.isLocked,type:`button`,className:`btn outline`,disabled:()=>s.isFormDisabled,onclick:()=>s.isLocked=!1},t.i({className:`ri-lock-unlock-line`,ariaHidden:!0}),t.span({className:`txt`},`Unlock to save`)),t.div({hidden:()=>s.isLocked,className:`btns`},t.button({type:`button`,className:()=>`btn expanded-lg ${s.isLoading||s.isSaving?`loading`:``}`,disabled:()=>s.isLocked||s.isFormDisabled,onclick:()=>g()},t.span({className:`txt`},()=>s.isNew?`Create`:`Save changes`)),t.button({type:`button`,className:()=>`btn p-5`,title:`Save options`,disabled:()=>s.isLocked||s.isFormDisabled,"html-popovertarget":a+`save_options`},t.i({className:`ri-arrow-up-s-line`,ariaHidden:!0})),t.div({id:a+`save_options`,className:`dropdown nowrap`,popover:`auto`},t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),g(!1)}},t.span({className:`txt`},`Save and continue`),t.small({className:`txt-hint`},`(Ctrl+S)`)),t.hr(),t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),_()}},t.span({className:`txt`},`Reset form`)))))]}return i=t.div({pbEvent:`recordUpsertModal`,className:`modal record-upsert-modal`,onbeforeopen:()=>(m(n),ee.push(watch(()=>s.recordHash,(e,n)=>{!n||!e||e==`{}`||n==`{}`||d(e)})),r.onbeforeopen?.(el)),onafteropen:e=>{r.onafteropen?.(e)},onbeforeclose:(e,n)=>(!s.hasChanges&&s.initialDraftHash!=l()&&f(),n?r.onbeforeclose?.(e):s.isLoading||s.isSaving?!1:s.hasChanges?new Promise(n=>{app.modals.confirm(`You have unsaved changes. Do you really want to discard them?`,()=>(f(),n(r.onbeforeclose?.(e))),()=>n(!1),{yesButton:`Yes, discard`})}):r.onbeforeclose?.(e)),onafterclose:e=>{r.onafterclose?.(e),ee.forEach(e=>e?.unwatch()),e?.remove()},onunmount:()=>{ee.forEach(e=>e?.unwatch())}},t.header({className:()=>`modal-header ${s.showTabs?`isolated`:``}`},t.div({className:`grid`},t.div({className:`col-12 flex`},t.h6({className:`modal-title`},()=>s.isLoading?t.span({className:`loader sm`}):[t.span(null,()=>s.isNew?`Create `:`Edit `),t.strong({className:`txt-ellipsis collection-name`,style:`max-width: 220px`},()=>e.name),t.span(null,` record`)]),t.div({className:`flex-fill`}),()=>{if(!app.utils.isEmpty(s.originalRecord?.id))return[t.button({type:`button`,className:`btn sm circle transparent`,title:`More options`,disabled:()=>s.isLoading,"html-popovertarget":a+`modal-header-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:a+`modal-header-dropdown`,className:`dropdown nowrap modal-header-dropdown`,popover:`auto`},()=>{if(!s.isAuthCollection)return;let n=[];return!s.originalRecord.verified&&s.originalRecord.email&&!s.isSuperusersCollection&&n.push(jt(e,s,r)),s.originalRecord.email&&n.push(H(e,s,r)),n.push(Mt(e,s,r)),n.push(At(e,s,r)),n.push(t.hr()),n},t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),Dt(s.originalRecord)}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)),()=>{if(e.type!=`view`)return[t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),s.hasChanges?app.modals.confirm(`You have unsaved changes. Do you really want to discard them?`,v,null,{yesButton:`Yes, discard`}):v()}},t.i({className:`ri-file-copy-line`,ariaHidden:!0}),t.span({className:`txt`},`Duplicate`)),t.hr(),Nt(e,s,r)]})]}),()=>{if(s.showTabs)return t.div({className:`col-12`},t.nav({className:`tabs-header equal-width`},t.button({type:`button`,disabled:()=>s.isLoading||s.isSaving,className:()=>`tab-item ${s.activeTab==B?`active`:s.hasChanges?`txt-warning`:``}`,ariaDescription:app.attrs.tooltip(()=>s.hasChanges&&s.activeTab!=B?`Has unsaved changes`:``),onclick:()=>s.activeTab=B},t.span({className:`txt`},()=>s.isAuthCollection?`Account`:`Main`)),t.button({type:`button`,disabled:()=>s.isLoading||s.isSaving,className:()=>`tab-item ${s.activeTab==V?`active`:``}`,onclick:()=>s.activeTab=V},t.span({className:`txt`},`Auth providers`))))})),()=>!s.isNew&&!s.isSuperusersCollection&&s.activeTab==V?It(e,s):te()),i}function At(e,n,r){let i=store({isSubmitting:!1});async function a(){if(!(i.isSubmitting||!n.record.id)){i.isSubmitting=!0;try{let i={},a=e.fields.find(e=>e.name==`tokenKey`);a.autogeneratePattern?i[`tokenKey:autogenerate`]=``:i.tokenKey=app.utils.randomSecret(a.max<<0||Math.max(2*a.min<<0,50));let o=await app.pb.collection(e.name).update(n.record.id,i);r.ontokensreset?.(o);let s=e.fields?.filter(e=>e.type==`autodate`)||[];for(let e of s){let r=o[e.name];n.initialDraft&&(n.initialDraft[e.name]=r),n.originalRecord[e.name]=r,n.record[e.name]=r}app.toasts.success(`Successfully reset all tokens for the selected record.`)}catch(e){app.checkApiError(e)}i.isSubmitting=!1}}return t.button({type:`button`,className:`dropdown-item`,disabled:()=>i.isSubmitting,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.modals.confirm(`Do you really want to reset all issued tokens for the selected auth record?`,a,null,{yesButton:`Reset all tokens`})}},t.i({className:`ri-reset-left-line`,ariaHidden:!0}),t.span({className:`txt`},`Reset issued tokens`))}function H(e,n,r){let i=store({isSubmitting:!1});async function a(){if(!(i.isSubmitting||!n.originalRecord?.email)){i.isSubmitting=!0;try{await app.pb.collection(e.name).requestPasswordReset(n.originalRecord.email),r.onpasswordresetsend?.(JSON.parse(JSON.stringify(n.originalRecord))),app.toasts.success(`Successfully sent password reset email to ${n.originalRecord.email}.`)}catch(e){app.checkApiError(e)}i.isSubmitting=!1}}return t.button({type:`button`,className:`dropdown-item`,disabled:()=>i.isSubmitting,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.modals.confirm(`Do you really want to send password reset email to ${n.originalRecord?.email}?`,a,null,{yesButton:`Send`})}},t.i({className:`ri-mail-lock-line`,ariaHidden:!0}),t.span({className:`txt`},`Send password reset email`))}function jt(e,n,r){let i=store({isSubmitting:!1});async function a(){if(!(i.isSubmitting||!n.originalRecord?.email||n.originalRecord?.verified)){i.isSubmitting=!0;try{await app.pb.collection(e.name).requestVerification(n.originalRecord.email),r.onverificationsend?.(JSON.parse(JSON.stringify(n.originalRecord))),app.toasts.success(`Successfully sent verification email to ${n.originalRecord.email}.`)}catch(e){app.checkApiError(e)}i.isSubmitting=!1}}return t.button({type:`button`,className:`dropdown-item`,disabled:()=>i.isSubmitting,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.modals.confirm(`Do you really want to send verification email to ${n.originalRecord?.email}?`,a,null,{yesButton:`Send`})}},t.i({className:`ri-mail-check-line`,ariaHidden:!0}),t.span({className:`txt`},`Send verification email`))}function Mt(e,n,r){return t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.modals.openRecordImpersontate(n.originalRecord)}},t.i({className:`ri-id-card-line`,ariaHidden:!0}),t.span({className:`txt`},`Impersonate`))}function Nt(e,n,r){let i=store({isSubmitting:!1});async function a(){if(!(i.isSubmitting||!n.originalRecord?.id)){i.isSubmitting=!0;try{await app.pb.collection(e.name).delete(n.originalRecord.id),r.ondelete?.(JSON.parse(JSON.stringify(n.originalRecord))),app.toasts.success(`Successfully deleted record "${n.originalRecord.id}".`)}catch(e){app.checkApiError(e)}i.isSubmitting=!1}}return t.button({type:`button`,className:`dropdown-item txt-danger`,disabled:()=>i.isSubmitting,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.modals.confirm(`Do you really want to delete the selected record?`,async()=>{await a(),app.modals.close(e.target.closest(`.modal`))},null,{yesButton:`Delete record`})}},t.i({className:`ri-delete-bin-7-line`,ariaHidden:!0}),t.span({className:`txt`},`Delete`))}function U(e,n){let r=e.fields.find(e=>e.name==`email`);if(!r){console.warn(`missing expected email field`);return}let i=`auth_email_`+app.utils.randomString();return t.div({className:`record-field-input field-type-email field-type-auth-email`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:i},t.i({className:app.fieldTypes.email.icon,ariaHidden:!0}),t.span({className:`txt`},()=>r.name)),t.input({type:`email`,id:i,spellcheck:!1,name:()=>r.name,required:()=>r.required,value:()=>n.record[r.name]||``,oninput:e=>n.record[r.name]=e.target.value})),t.div({className:`field addon`},t.button({type:`button`,className:()=>`btn sm transparent ${n.record.emailVisibility?`success`:`secondary`}`,ariaDescription:app.attrs.tooltip(`Make email public or private`,`top-right`),onclick:()=>{n.record.emailVisibility=!n.record.emailVisibility}},t.span({className:`txt`},`Public: `,()=>n.record.emailVisibility?`On`:`Off`)))),()=>{if(r.help)return t.div({className:`field-help`},r.help)})}function Pt(e,n){let r=e.fields.find(e=>e.name==`verified`);if(!r){console.warn(`missing expected verified field`);return}let i=app.fieldTypes.bool.input({get field(){return r},get collection(){return e},get record(){return n.record},get originalRecord(){return n.originalRecord}});return i.addEventListener(`change`,e=>{n.originalRecord.verified!=n.record.verified&&app.modals.confirm(`Do you really want to manually change the verified account state from "${!n.record.verified}" to "${n.record.verified}"?`,null,()=>{n.record.verified=!n.record.verified},{yesButton:`Yes, `+(n.record.verified?`verify`:`unverify`)})}),i}function Ft(e,n){let r=`auth_pass_`+app.utils.randomString(),i=store({changePassword:!1,get isNew(){return app.utils.isEmpty(n.originalRecord?.id)}});function a(){delete n.record.password,delete n.record.passwordConfirm,app.store.errors&&(delete app.store.errors.password,delete app.store.errors.passwordConfirm)}return t.div({className:`record-field-input field-type-password field-type-auth-password`,onmount:e=>{e._watchers?.forEach(e=>e?.unwatch()),e._watchers=[watch(()=>{i.changePassword||(app.store.errors?.password||app.store.errors?.passwordConfirm||n.record.password||n.record.passwordConfirm)&&(i.changePassword=!0)})]},onunmount:e=>{e._watchers?.forEach(e=>e?.unwatch())}},t.div({hidden:()=>i.isNew,className:`field`},t.input({type:`checkbox`,id:r+`_change`,className:`switch`,checked:()=>i.changePassword,onchange:e=>{i.changePassword=e.target.checked,e.target.checked||a()}}),t.label({htmlFor:r+`_change`},t.span({className:`txt`},`change password`))),app.components.slide(()=>i.isNew||i.changePassword,t.div({className:()=>`fields ${i.isNew?``:`m-t-sm`}`},t.div({className:`field`},t.label({htmlFor:r+`_password`},t.i({className:`ri-lock-line`,ariaHidden:!0}),t.span({className:`txt`},`Password`)),t.input({type:`password`,id:r+`_password`,spellcheck:!1,name:`password`,className:`inline-error`,autocomplete:`new-password`,required:()=>i.isNew||i.changePassword,value:()=>n.record.password||``,oninput:e=>{e.target.value?n.record.password=e.target.value:delete n.record.password}})),t.div({className:`delimiter`}),t.div({className:`field`},t.label({htmlFor:r+`_password_confirm`},t.i({className:`ri-lock-line`,ariaHidden:!0}),t.span({className:`txt`},`Confirm`)),t.input({type:`password`,id:r+`_password_confirm`,spellcheck:!1,name:`passwordConfirm`,className:`inline-error`,autocomplete:`new-password`,required:()=>i.isNew||i.changePassword,value:()=>n.record.passwordConfirm||``,oninput:e=>{e.target.value?n.record.passwordConfirm=e.target.value:delete n.record.passwordConfirm}}))),()=>{let n=e.fields?.find(e=>e.name==`password`)?.help||``;if(n)return t.div({className:`field-help`},n)},t.div({className:`field-help`},t.span({className:`txt link-hint`,role:`button`,onclick:e=>{e.preventDefault();let r=app.utils.randomSecret(20);n.record.password=r,n.record.passwordConfirm=r,app.utils.copyToClipboard(r),app.toasts.info(`Generated and copied random password to clipboard.`)}},`Generate and set random password`))))}function It(e,n){let r=store({isLoading:!1,externalAuths:[]});async function i(){r.isLoading=!0;try{r.externalAuths=await app.pb.collection(`_externalAuths`).getFullList({filter:app.pb.filter(`collectionRef={:collectionId} && recordRef={:recordId}`,{collectionId:n.record.collectionId,recordId:n.record.id})}),r.isLoading=!1}catch(e){e?.isAbort&&(app.pb.checkApiError(e),r.isLoading=!1)}}function a(e){let n=(app.store.oauth2Providers?.find(n=>n.name==e.provider)||{}).displayName||e.provider;app.modals.confirm(`Do you really want to unlink the ${n} provider?`,()=>app.pb.collection(`_externalAuths`).delete(e.id).then(()=>{app.toasts.success(`Successfully unlinked ${n}.`),i()}).catch(e=>{app.checkApiError(e)}),null,{yesButton:`Unlink`})}return[t.div({className:`modal-content`},t.div({className:`list`,onmount:()=>{i()}},()=>r.isLoading?t.div({className:`list-item`},t.div({className:`skeleton-loader`})):r.externalAuths.length?r.externalAuths.map(e=>{let n=app.store.oauth2Providers?.find(n=>n.name==e.provider)||{};return t.div({className:`list-item`},t.figure({className:`provider-logo`},()=>n.logo?t.img({src:`data:image/svg+xml;base64,`+btoa(n.logo),alt:e.provider+` logo`}):t.i({className:app.utils.fallbackProviderIcon,ariaHidden:!0})),t.div({className:`content`},t.span({className:`txt-nowrap`},()=>n.displayName||e.provider),t.small({className:`txt-hint`},`ID: `,()=>e.providerId)),t.div({className:`actions`},t.button({type:`button`,className:`btn sm secondary transparent circle`,ariaLabel:app.attrs.tooltip(`Unlink`,`left`),onclick:()=>a(e)},t.i({className:`ri-close-line`,ariaHidden:!0}))))}):t.div({className:`list-item`},t.div({className:`block txt-hint txt-center`},`No external auth providers found.`)))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close()},t.span({className:`txt`},`Close`)))]}var Lt=10,Rt=500,zt=`pb:lazyExpandSummaryRels`,Bt={},Vt={};function Ht(e){let n=new Set;return t.div({className:`record-field-view field-type-relation`,onunmount:()=>{for(let e of n)document.removeEventListener(zt,e);n.clear(),n=null}},()=>{let r=app.utils.toArray(e.record[e.field.name]);if(!r.length)return t.span({className:`missing-value`});let i=e.meta||{},a=app.utils.toArray(i.parents);if(a.includes(e.record.id))return t.span({className:`marker recursive`},`(recursive)`);let o=JSON.parse(JSON.stringify(i));o.parents=a.concat(e.record.id);let s=[],c=e.short?3:1e3,l=app.utils.toArray(e.record.expand?.[e.field.name]);for(let i=0;i=c){s.push(t.span({className:`marker more`},`(`,r.length-c,` more)`));break}let a=r[i],u=l.find(e=>e?.id==a);if(u)s.push(app.components.recordSummary(u,o));else if(s.push(t.span({className:`label relation-id animate-delayed-fadeIn`},app.components.copyButton(a),a)),o.parents.length{i.detail.id==a&&i.detail.collectionId==e.field.collectionId&&(Ut(e.record,e.field,structuredClone(i.detail),r),document.removeEventListener(zt,o),n.delete(o))};n.add(o),document.addEventListener(zt,o)}}return Wt(e.field.collectionId),s})}function Ut(e,n,r,i=0){if(e.expand=e.expand||{},n.maxSelect>1){e.expand[n.name]=app.utils.toArray(e.expand[n.name]);let a=e.expand[n.name].findIndex(e=>e?.id==r.id);a>=0?e.expand[n.name][a]=r:e.expand[n.name][i]?e.expand[n.name].push(r):e.expand[n.name][i]=r}else e.expand[n.name]=r}function Wt(e){e&&(clearTimeout(Vt[e]),Vt[e]=setTimeout(()=>{let n=Array.from(Bt[e]||[]);if(n.length)for(Bt[e].clear(),Bt[e]=null,Vt[e]=null;n.length;){let r=n.splice(0,Rt),i=[],a=app.store.collections.find(n=>n.id==e)?.fields?.filter(e=>!e.hidden&&e.presentable&&e.type==`relation`)||[];for(let e of a)i.push(e.name);i=i.join(`,`)||void 0;let o=Gt(e,a),s;s=r.length==1?app.pb.collection(e).getOne(r[0],{requestKey:null,expand:i,fields:o}):app.pb.collection(e).getFullList({requestKey:null,expand:i,filter:r.map(e=>app.pb.filter(`id={:id}`,{id:e})).join(`||`),fields:o}),s.then(e=>{if(e=app.utils.toArray(e),e.length)for(let n of e)document.dispatchEvent(new CustomEvent(zt,{detail:n}))}).catch(e=>{console.warn(`failed to lazily expand presentable relation`,e)})}},0))}function Gt(e,n=[],r=200){let i=app.store.collections.find(n=>n.id==e)?.fields?.filter(e=>e.type==`editor`).map(e=>`${e.name}:excerpt(${r},true)`)||[];for(let e of n){let n=app.store.collections?.find(n=>n.id==e.collectionId)?.fields?.filter(e=>e.type==`editor`)?.map(n=>`expand.${e.name}.${n.name}:excerpt(${r},true)`);n?.length&&(i.push(`expand.${e.name}.*`),i=i.concat(n))}if(i.length>0)return[`*`,`expand.*`].concat(i).join(`,`)}window.app=window.app||{},window.app.components=window.app.components||{};var Kt=40,qt=/^([\+\-])?(\w+)$/;window.app.consts=window.app.consts||{},window.app.consts.COLUMNS_STORAGE_PREFIX=`pbColumns_`,window.app.components.recordsList=function(e={}){let n=`records_list_`+app.utils.randomString(),r=store({collection:{},filter:``,sort:``,reset:void 0,rid:void 0,id:void 0,hidden:void 0,className:``,onchange:(e,n)=>{},onselect:e=>{}}),i=app.utils.extendStore(r,e),a=store({isLoading:!1,records:[],lastPage:0,lastTotalItems:0,bulkSelected:{},columnsPreferences:{},get canLoadMore(){return a.lastTotalItems>=Kt},get totalSelected(){return Object.keys(a.bulkSelected).length},get areAllSelected(){return a.records.length&&a.records.length==a.totalSelected},get firstAutoUpdatedField(){return r.collection?.fields?.find(e=>e.type==`autodate`&&e.onUpdate)},get isSuperusersCollection(){return r.collection?.type==`auth`&&r.collection?.name==`_superusers`}});async function o(){a.records=[],a.lastPage=0,a.lastTotalItems=0,a.bulkSelected={}}function s(){r.onchange?.(r.filter,r.sort)}async function c(e=!1){if(r.collection?.id){a.isLoading=!0;try{let i=app.utils.normalizeSearchFilter(r.filter,r.collection.fields.filter(e=>!e.hidden).map(e=>e.name)),s=[],c=r.collection.fields.filter(e=>!e.hidden&&e.type==`relation`);for(let e of c)s.push(e.name);let l=Gt(r.collection.id,c),u=r.sort||void 0,d=u?.match(qt),f=d?r.collection.fields.find(e=>!e.hidden&&e.name===d[2]):null;f?f?.type==`relation`&&(u=app.store.collections?.find(e=>e.id==f.collectionId)?.fields?.filter(e=>e.presentable)?.map(e=>(d[1]||``)+d[2]+`.`+e.name)?.join(`,`)):u=r.collection.type==`view`?void 0:`-@rowid`;let p=e?1:a.lastPage+1,m=await app.pb.collection(r.collection.name).getList(p,Kt,{requestKey:n,skipTotal:1,filter:i,sort:u,expand:s.join(`,`)||void 0,fields:l});m.page==1&&o(),a.lastPage=m.page,a.lastTotalItems=m.items.length;for(let e=0;e1&&e%15==0&&await new Promise(e=>setTimeout(e,20));a.isLoading=!1}catch(e){e.isAbort||(a.isLoading=!1,o(),app.checkApiError(e))}}}function l(e=!0){let n={};if(e)for(let e of a.records)n[e.id]=e;a.bulkSelected=n}function u(){let e=JSON.parse(JSON.stringify(Object.values(a.bulkSelected)));if(e.length){for(let n of e)n.expand&&delete n.expand;return e.length==1?app.utils.downloadJSON(e[0],r.collection.name+`_`+e[0].id+`.json`):app.utils.downloadJSON(e,`${e.length}_${r.collection.name}_records.json`)}}async function d(){let e=Object.keys(a.bulkSelected);if(!e.length)return;let n=e.slice();for(;n.length;){let e=n.splice(0,100),i=[];for(let n of e)i.push(app.pb.collection(r.collection.name).delete(n));try{await Promise.all(i)}catch(e){app.checkApiError(e),l(!1),c(!0);return}}l(!1),app.toasts.success(`Successfully deleted ${e.length} ${e.length==1?`record`:`records`}.`)}function f(e){return a.firstAutoUpdatedField?e.id+e[a.firstAutoUpdatedField.name]+r.collection?.updated+Object.keys(e):JSON.stringify(e)+r.collection?.updated}function p(e){return a.columnsPreferences[e.id]===void 0?e.hidden:!a.columnsPreferences[e.id]}let m,h={"record:save":e=>{if(e.detail.collectionId!=r.collection?.id)return;let n=a.records.find(n=>n.id==e.detail.id);n&&Object.assign(n,JSON.parse(JSON.stringify(e.detail))),c(!0)},"record:delete":e=>{e.detail.collectionId!=r.collection?.id&&e.detail.collectionName!=r.collection?.name||(delete a.bulkSelected[e.detail.id],app.utils.removeByKey(a.records,`id`,e.detail.id),clearTimeout(m),m=setTimeout(()=>{a.records?.length||c(!0)},100))}};return t.div({pbEvent:`recordsList`,rid:r.rid,id:()=>r.id,hidden:()=>r.hidden,className:()=>`page-table-wrapper ${r.className}`,onmount:e=>{for(let e in h)document.addEventListener(e,h[e]);i.push(watch(()=>r.collection?.id,(e,n)=>{a.columnsPreferences=app.utils.getLocalHistory(app.consts.COLUMNS_STORAGE_PREFIX+e,{}),n&&n!=e&&o()})),i.push(watch(()=>(r.collection?.id||``)+(r.filter||``)+(r.sort||``)+(r.reset||``),(e,n)=>{e!=n&&c(!0)})),i.push(watch(()=>a.lastPage,n=>{n==1&&e&&(e.scrollTop=0)})),i.push(watch(()=>JSON.stringify(a.columnsPreferences),(e,n)=>{r.collection?.id&&n&&app.utils.saveLocalHistory(app.consts.COLUMNS_STORAGE_PREFIX+r.collection.id,a.columnsPreferences)}))},onunmount:()=>{app.pb.cancelRequest(n),clearTimeout(m),i.forEach(e=>e?.unwatch());for(let e in h)document.removeEventListener(e,h[e])}},t.table({pbEvent:`recordsListTable`,className:()=>`records-table responsive-table ${a.records.length>Kt?`optimize`:``}`},t.thead({className:`sticky`},t.tr(null,t.th({className:`col-bulk-select`},t.div({className:`field`,hidden:()=>a.isLoading},t.input({id:`all_`+n,type:`checkbox`,disabled:()=>!a.records.length,checked:()=>a.areAllSelected,onchange:e=>l(e.target.checked)}),t.label({htmlFor:`all_`+n})),t.span({className:`loader`,hidden:()=>!a.isLoading})),()=>{let e=r.collection?.fields||[],n=[];for(let i of e)!app.fieldTypes[i.type]?.view||a.isSuperusersCollection&&i.name==`verified`||n.push(t.th({hidden:()=>p(i),className:()=>{let e=``;return r.sort==i.name||r.sort==`+`+i.name?e=`asc`:r.sort==`-`+i.name&&(e=`desc`),`sort-handle ${e} col-field-type-${i.type} col-field-name-${i.name}`},onclick:e=>{let n=`-`+i.name;r.sort==n&&(n=i.name),r.sort=n,s()}},t.div({className:`inline-flex gap-5`},t.i({ariaHidden:!0,className:()=>i.primaryKey?`ri-key-line`:app.fieldTypes[i.type]?.icon||app.utils.fallbackFieldIcon}),t.span({className:`txt`,textContent:i.name}))));return n},t.th({className:`col-meta`},()=>W(r,a)))),t.tbody(null,()=>a.records.length?a.records.map((e,i)=>t.tr({rid:f(e),tabIndex:0,className:`handle`,onclick:n=>{n.preventDefault(),r.onselect(e)},onkeypress:n=>{(n.key==`Enter`||n.key==` `)&&(n.preventDefault(),r.onselect(e))}},t.td({className:`col-bulk-select`,onclick:e=>e.stopPropagation(),onkeypress:e=>e.stopPropagation()},t.div({className:`field`},t.input({type:`checkbox`,id:()=>n+e.id,checked:()=>!!a.bulkSelected[e.id],onchange:n=>{let r=JSON.parse(JSON.stringify(a.bulkSelected));n.target.checked?r[e.id]=e:delete r[e.id],a.bulkSelected=r}}),t.label({htmlFor:n+e.id}))),()=>{let n=[],i=r.collection?.fields||[];for(let r of i){let i=app.fieldTypes[r.type]?.view;i&&(a.isSuperusersCollection&&r.name==`verified`||n.push(t.td({"html-data-name":r.name,hidden:()=>p(r),className:`col-field-type-${r.type} col-field-name-${r.name}`},()=>i({short:!0,get record(){return e},get field(){return r}}))))}return n},t.td({className:`col-meta`},t.i({className:`ri-arrow-right-line m-r-10`,ariaHidden:!0})))):t.tr(null,t.td({colSpan:99,style:`height:59px`},()=>a.isLoading?t.span({className:`skeleton-loader`}):t.div({className:`sticky-content txt-center txt-hint`},t.p({className:`txt-bold`},`No records found.`),t.button({hidden:()=>r.filter?.length||r.collection?.type==`view`,type:`button`,className:`btn secondary expanded-lg`,onclick(){app.modals.openRecordUpsert(r.collection)}},t.i({className:`ri-add-line`}),t.span({className:`txt`},`New record`)),t.button({hidden:()=>!r.filter?.length,type:`button`,className:`btn secondary expanded-lg`,onclick(){r.filter=``,s()}},t.span({className:`txt`},`Clear search`))))),t.tr({hidden:()=>!a.canLoadMore},t.td({colSpan:99},t.button({className:()=>`btn lg secondary load-more-btn ${a.isLoading?`transparent loading`:``}`,disabled:()=>a.isLoading,onclick:()=>c()},t.span({className:`txt`},`Load more`)))))),t.div({className:`bulkbar-wrapper`},t.div({hidden:()=>!a.totalSelected,className:`bulkbar records-bulkbar`},t.span({className:`txt`},`Selected `,t.strong(null,()=>a.totalSelected),()=>` ${a.totalSelected==1?`record`:`records`}`),t.button({type:`button`,className:`btn sm secondary pill m-r-auto`,onclick:()=>l(!1)},t.span({className:`txt`},`Reset`)),()=>{if(r.collection?.type!=`view`)return t.button({type:`button`,className:`btn sm pill outline danger`,onclick:()=>{app.modals.confirm(`Do you really want to delete the selected records?`,d)}},t.i({className:`ri-delete-bin-7-line`,ariaHidden:!0}),t.span({className:`txt`},`Delete`))},t.button({type:`button`,className:`btn sm pill`,onclick:()=>u()},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`JSON`)))))};function W(e,n){let r=`cols_`+app.utils.randomString(),i=t.div({className:`dropdown sm nowrap records-list-columns-dropdown gap-0`,popover:`auto`},()=>{if(!e.collection?.fields)return;let i=[],a=e.collection.type==`auth`;for(let o of e.collection.fields)o.primaryKey||!app.fieldTypes[o.type].view||a&&o.name==`tokenKey`||i.push(t.div({className:`dropdown-item`,onclick:e=>{e.target.querySelector(`label`)?.click()}},t.div({className:`field`},t.input({type:`checkbox`,className:`switch sm`,id:()=>r+o.name,checked:()=>n.columnsPreferences[o.id]===void 0?!o.hidden:!!n.columnsPreferences[o.id],onchange:e=>{n.columnsPreferences[o.id]=e.target.checked}}),t.label({htmlFor:()=>r+o.name},o.name))));return i});return t.button({hidden:()=>e.collection?.fields.length<=1,type:`button`,title:`Toggle columns`,className:`btn sm secondary transparent circle`,popoverTargetElement:i},t.i({className:`ri-more-2-line`,ariaHidden:!0}),i)}window.app=window.app||{},window.app.components=window.app.components||{};var G=`@toDelete`;window.app.components.fieldSettings=function(e,n={}){let r=`base_`+app.utils.randomString(),i=store({showHidden:!0,showPresentable:!0,showDuplicate:!0,showRemove:!0,header:e=>null,content:e=>null,footer:e=>null}),a=app.utils.extendStore(i,n);function o(){let n=JSON.parse(JSON.stringify(e.field));n.id=``,n.system=!1,n.name=K(e.collection.fields,n.name+`_copy`),n.__detailsOpen=!0,n.primaryKey&&=!1,n[`@toDelete`]&&delete n[G],e.collection.fields.splice(e.fieldIndex+1,0,n)}function s(){e.field.id?e.field[G]=!0:e.collection.fields.splice(e.fieldIndex,1)}return t.details({"html-class":`accordion record-field-settings`,className:()=>`accordion record-field-settings field-type-${e.field.type} ${e.field[`@toDelete`]?`deleted`:``}`,name:`collection_field`,onmount:n=>{e.field.__detailsOpen&&(delete e.field.__detailsOpen,n.open=!0),a.push(watch(()=>e.field.name,(n,r)=>{n=app.utils.slugify(n),e.field.name=n,r!==void 0&&(Yt(e.collection,r,n),Jt(e.collection,r,n))})),a.push(watch(()=>e.field[G],n=>{n&&e.originalField?.name&&e.field.name!=e.originalField.name&&(e.field.name=e.originalField.name)})),a.push(watch(()=>{e.field.presentable&&e.field.hidden&&(e.field.presentable=!1,app.toasts.info(`The field cannot be presentable if hidden.`))})),a.push(watch(()=>{(e.field.name==`id`||e.collection.type==`auth`&&[`password`,`tokenKey`].includes(e.field.name))&&e.originalField&&e.field.required!=e.originalField.required&&(e.field.required=e.originalField.required,app.toasts.info(`The option cannot be changed for field "${e.field.name}".`))})),a.push(watch(()=>{(e.field.name==`id`||e.collection.type==`auth`&&[`password`,`tokenKey`,`email`].includes(e.field.name))&&e.originalField&&e.field.hidden!=e.originalField.hidden&&(e.field.hidden=e.originalField.hidden,app.toasts.info(`The option cannot be changed for field "${e.field.name}".`))}))},onunmount:e=>{a.forEach(e=>e?.unwatch())}},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},t.span({className:`sort-handle`},t.i({className:`ri-draggable`})),t.header({className:`header-fields`,inert:()=>e.field[G],onclick:e=>{e.stopPropagation(),e.preventDefault()}},t.div({className:`fields`},t.label({htmlFor:r+`.name`,className:()=>`field addon ${e.field.system?`txt-disabled`:``}`},t.i({className:app.fieldTypes[e.field.type]?.icon||app.utils.fallbackFieldIcon,ariaDescription:app.attrs.tooltip(()=>e.field.system?e.field.type+` (system)`:e.field.type)})),t.div({className:`field prop-name`},t.input({type:`text`,id:r+`.name`,name:()=>`fields.${e.fieldIndex}.name`,required:!0,spellcheck:!1,placeholder:`Field name*`,className:`inline-error`,disabled:()=>e.field[`@toDelete`]||e.field.system,value:()=>e.field.name||``,oninput:n=>{n.isComposing||(e.field.name=n.target.value)},onmount:n=>{n.addEventListener(`compositionend`,n=>{e.field.name=n.target.value}),setTimeout(()=>{n&&e.field.__focus&&(n.select(),delete e.field.__focus)},0)}}),t.div({className:`field-labels`},()=>{let n=[];return e.field.required&&n.push(t.span({className:`label success`},`Required`)),e.field.hidden?n.push(t.span({className:`label danger`},`Hidden`)):e.field.presentable&&n.push(t.span({className:`label info`},`Presentable`)),n}))),e=>typeof i.header==`function`?i.header(e):i.header),t.button({type:`button`,className:()=>`btn sm circle transparent secondary ${app.utils.isEmpty(app.utils.getByPath(app.store.errors,`fields.${e.fieldIndex}`))?``:`txt-danger`}`,title:`Field options`,hidden:()=>e.field[G],onclick:e=>{let n=e.target.closest(`details`);n&&(n.open=!n.open)}},t.i({className:`ri-settings-3-line`,ariaHidden:!0})),t.button({type:`button`,className:`btn sm circle transparent warning`,hidden:()=>!e.field[G],onclick:()=>delete e.field[G],ariaLabel:app.attrs.tooltip(`Restore`)},t.i({className:`ri-restart-line`,ariaHidden:!0}))),e=>typeof i.content==`function`?i.content(e):i.content,t.footer({className:`record-field-settings-footer`},e=>typeof i.footer==`function`?i.footer(e):i.footer,()=>{if(i.showPresentable)return t.div({className:`field prop-presentable`},t.input({type:`checkbox`,id:r+`.presentable`,name:()=>`fields.${e.fieldIndex}.presentable`,className:`sm`,disabled:()=>e.field.hidden,checked:()=>!!e.field.presentable,onchange:n=>e.field.presentable=n.target.checked}),t.label({htmlFor:r+`.presentable`},t.span({className:`txt`},`Presentable`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(()=>{let n=`Whether the field should be preferred in the Superuser UI relation listings (default to auto).`;return e.field.hidden&&(n+=` -The field cannot be presentable if hidden.`),n})})))},()=>{if(i.showHidden)return t.div({className:`field prop-hidden`},t.input({type:`checkbox`,id:r+`.hidden`,className:`sm`,name:()=>`fields.${e.fieldIndex}.hidden`,checked:()=>!!e.field.hidden,onchange:n=>e.field.hidden=n.target.checked}),t.label({htmlFor:r+`.hidden`},t.span({className:`txt`},`Hidden`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Hide from the JSON API response and filters.`)})))},t.button({hidden:()=>!i.showDuplicate&&(!i.showRemove||e.field.system),type:`button`,title:`More options`,className:`btn sm circle transparent secondary more-btn m-l-auto`,"html-popovertarget":r+`_options_dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:r+`_options_dropdown`,className:`dropdown sm field-options-dropdown`,popover:`auto`},()=>{if(i.showDuplicate)return t.button({type:`button`,className:`dropdown-item`,role:`menuitem`,textContent:`Duplicate`,onclick:e=>{o(),e.target.closest(`.dropdown`).hidePopover()}})},()=>{if(!(!i.showRemove||e.field.system))return t.button({type:`button`,className:`dropdown-item`,role:`menuitem`,textContent:`Remove`,onclick:e=>{s(),e.target.closest(`.dropdown`).hidePopover(),e.target.closest(`details`).open=!1}})})))};function K(e,n=`field`){let r=n,i=2,a=n.match(/\d+$/)?.[0]||``,o=a?n.substring(0,n.length-a.length):n;for(;e?.find(e=>e.name.toLowerCase()==r.toLowerCase());)r=o+((a<<0)+i),i++;return r}function Jt(e,n,r){if(!r||n===void 0||n===r||!e?.passwordAuth?.identityFields?.length)return;let i=e.passwordAuth.identityFields;for(let e=0;e!e[`@toDelete`]&&e.name==n)||(e.indexes=e.indexes.map(e=>app.utils.replaceIndexColumn(e,n,r)))}function Xt(e){let n=`text_`+app.utils.randomString(),r=store({get hasAutogenerate(){return!app.utils.isEmpty(e.field.autogeneratePattern)&&app.utils.isEmpty(e.originalRecord?.id)},get isDisabled(){return!app.utils.isEmpty(e.originalRecord?.id)&&e.field.primaryKey},get isRequired(){return e.field.required&&!r.hasAutogenerate&&!r.isDisabled}});return t.div({className:`record-field-input field-type-text`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:n},t.i({ariaHidden:!0,className:()=>e.field.primaryKey?`ri-key-line`:app.fieldTypes.text.icon}),t.span({className:`txt`},()=>e.field.name)),t.div({className:`autoexpand-wrapper`},t.textarea({id:n,rows:1,name:()=>e.field.name,required:()=>r.isRequired,disabled:()=>r.isDisabled,placeholder:()=>r.hasAutogenerate?`Leave empty to autogenerate...`:``,value:()=>e.record[e.field.name]||``,oninput:n=>e.record[e.field.name]=n.target.value||``}),t.div({className:`input`},()=>e.record[e.field.name],` `))),()=>{if(!e.field.primaryKey||!e.originalRecord?.id)return;let n=e.collection?.fields?.filter(e=>e.type==`autodate`)||[];if(!n.length)return;let r=[];for(let i of n)r.push(`${i.name}: ${app.utils.stringifyValue(e.record[i.name])}`);return t.div({className:`field addon`},t.i({className:`ri-information-line txt-hint link-faded`,ariaDescription:app.attrs.tooltip(r.join(` +The field cannot be presentable if hidden.`),n})})))},()=>{if(i.showHidden)return t.div({className:`field prop-hidden`},t.input({type:`checkbox`,id:r+`.hidden`,className:`sm`,name:()=>`fields.${e.fieldIndex}.hidden`,checked:()=>!!e.field.hidden,onchange:n=>e.field.hidden=n.target.checked}),t.label({htmlFor:r+`.hidden`},t.span({className:`txt`},`Hidden`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Hide from the JSON API response and filters.`)})))},t.button({hidden:()=>!i.showDuplicate&&(!i.showRemove||e.field.system),type:`button`,title:`More options`,className:`btn sm circle transparent secondary more-btn m-l-auto`,"html-popovertarget":r+`_options_dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:r+`_options_dropdown`,className:`dropdown sm field-options-dropdown`,popover:`auto`},()=>{if(i.showDuplicate)return t.button({type:`button`,className:`dropdown-item`,role:`menuitem`,textContent:`Duplicate`,onclick:e=>{o(),e.target.closest(`.dropdown`).hidePopover()}})},()=>{if(!(!i.showRemove||e.field.system))return t.button({type:`button`,className:`dropdown-item`,role:`menuitem`,textContent:`Remove`,onclick:e=>{s(),e.target.closest(`.dropdown`).hidePopover(),e.target.closest(`details`).open=!1}})})))};function K(e,n=`field`){let r=n,i=2,a=n.match(/\d+$/)?.[0]||``,o=a?n.substring(0,n.length-a.length):n;for(;e?.find(e=>e.name.toLowerCase()==r.toLowerCase());)r=o+((a<<0)+i),i++;return r}function Jt(e,n,r){if(!r||n===void 0||n===r||!e?.passwordAuth?.identityFields?.length)return;let i=e.passwordAuth.identityFields;for(let e=0;e!e[`@toDelete`]&&e.name==n)||(e.indexes=e.indexes.map(e=>app.utils.replaceIndexColumn(e,n,r)))}function Xt(e){let n=`text_`+app.utils.randomString(),r=store({get hasAutogenerate(){return!app.utils.isEmpty(e.field.autogeneratePattern)&&app.utils.isEmpty(e.originalRecord?.id)},get isDisabled(){return!app.utils.isEmpty(e.originalRecord?.id)&&e.field.primaryKey},get isRequired(){return e.field.required&&!r.hasAutogenerate&&!r.isDisabled}});return t.div({className:`record-field-input field-type-text`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:n},t.i({ariaHidden:!0,className:()=>e.field.primaryKey?`ri-key-line`:app.fieldTypes.text.icon}),t.span({className:`txt`},()=>e.field.name)),t.div({className:`autoexpand-wrapper`},t.textarea({id:n,rows:1,name:()=>e.field.name,required:()=>r.isRequired,disabled:()=>r.isDisabled,placeholder:()=>r.hasAutogenerate?`Leave empty to autogenerate...`:``,value:()=>e.record[e.field.name]||``,oninput:n=>e.record[e.field.name]=n.target.value||``}),t.div({className:`input`},()=>e.record[e.field.name],` `))),()=>{if(!e.field.primaryKey||!e.originalRecord?.id)return;let n=e.collection?.fields?.filter(e=>e.type==`autodate`)||[];if(!n.length)return;let r=[];for(let i of n)r.push(`${i.name}: ${app.utils.displayValue(e.record[i.name])}`);return t.div({className:`field addon`},t.i({className:`ri-information-line txt-hint link-faded`,ariaDescription:app.attrs.tooltip(r.join(` `),`left`)}))}),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function Zt(e){let n=`f_`+app.utils.randomString();return app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.min`},t.span({className:`txt`},`Min length`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Clear the field or set it to 0 for no limit.`)})),t.input({type:`number`,id:n+`.min`,name:()=>`fields.${e.fieldIndex}.min`,step:1,min:0,max:2**53-1,placeholder:`No min limit`,value:()=>e.field.min||``,oninput:n=>{e.field.min=parseInt(n.target.value,10)}}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.max`},t.span({className:`txt`},`Max length`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Clear the field or set it to 0 to fallback to the default limit.`)})),t.input({type:`number`,id:n+`.max`,name:()=>`fields.${e.fieldIndex}.max`,step:1,min:()=>e.field.min||0,max:2**53-1,placeholder:`Default to max 5000 characters`,value:()=>e.field.max||``,oninput:n=>{e.field.max=parseInt(n.target.value,10)}}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.pattern`},t.span({className:`txt`},`Validation pattern`),()=>{if(e.field.primaryKey)return t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`All record ids have forbidden characters and unique case-insensitive (ASCII) validations in addition to the user defined regex pattern.`)})}),t.input({type:`text`,id:n+`.pattern`,name:()=>`fields.${e.fieldIndex}.pattern`,value:()=>e.field.pattern||``,oninput:n=>e.field.pattern=n.target.value})),t.div({className:`field-help`},`Ex. `,t.code(null,`^[a-z0-9]+$`))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.autogeneratePattern`},t.span({className:`txt`},`Autogenerate pattern`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Set and autogenerate text matching the pattern on missing record create value.`)})),t.input({type:`text`,id:n+`.autogeneratePattern`,name:()=>`fields.${e.fieldIndex}.autogeneratePattern`,value:()=>e.field.autogeneratePattern||``,oninput:n=>e.field.autogeneratePattern=n.target.value})),t.div({className:`field-help`},`Ex. `,t.code(null,`[a-z0-9]{30}`))),t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.help`},`Help text`),t.input({type:`text`,id:n+`.help`,name:()=>`fields.${e.fieldIndex}.help`,value:()=>e.field.help||``,oninput:n=>e.field.help=n.target.value})))),footer:()=>[t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.required`,name:()=>`fields.${e.fieldIndex}.required`,checked:()=>!!e.field.required,onchange:n=>e.field.required=n.target.checked}),t.label({htmlFor:n+`.required`},t.span({className:`txt`},`Required`),t.small({className:`txt-hint`},`(!='')`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Requires the field value to be nonempty string`)})))]})}function Qt(e){return t.div({className:`record-field-view field-type-text`},()=>{let n=e.record[e.field.name]||``;if(n==``)return t.span({className:`missing-value`});if(e.field.primaryKey){let r=null;return e.record?.collectionName==`_superusers`&&app.store.superuser?.id==e.record?.id&&(r=t.strong({className:`txt`,textContent:` (you)`})),t.span({className:`label`},app.components.copyButton(n),t.span({className:`txt-ellipsis`},app.utils.truncate(n),r))}return e.short?t.span({className:`txt txt-ellipsis`,textContent:app.utils.truncate(n)}):n})}window.app=window.app||{},window.app.fieldTypes=window.app.fieldTypes||{},window.app.fieldTypes.text={icon:`ri-text`,label:`Plain text`,settings:Zt,input:Xt,view:Qt,filterModifiers:e=>[`lower`],dummyData:(e,n=!1)=>e.primaryKey?app.utils.randomString(15):`example text`};function $t(e){let n=`editor_`+app.utils.randomString(),r=store({lazyEditor:null});return t.div({className:`record-field-input field-type-editor large-modal`,onmount:()=>{requestAnimationFrame(()=>{r.lazyEditor=app.components.tinymce({id:n,required:()=>e.field.required,convertURLs:()=>e.field.convertURLs,name:()=>e.field.name,value:()=>e.record[e.field.name]||``,onchange:n=>{e.record[e.field.name]=n}})})}},t.div({className:`field`},t.label({htmlFor:n},t.i({className:app.fieldTypes.editor.icon,ariaHidden:!0}),t.span({className:`txt`},()=>e.field.name)),()=>r.lazyEditor),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function en(e){let n=`f_`+app.utils.randomString();return store({showInfo:!1}),app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.maxSize`},t.span(null,`Max size `),t.small(null,`(bytes)`)),t.input({type:`number`,id:n+`.maxSize`,name:()=>`fields.${e.fieldIndex}.maxSize`,min:0,step:1,max:2**53-1,placeholder:`Default to max ~5MB`,value:()=>e.field.maxSize||``,oninput:n=>{e.field.maxSize=parseInt(n.target.value,10)}}))),t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.help`},`Help text`),t.input({type:`text`,id:n+`.help`,name:()=>`fields.${e.fieldIndex}.help`,value:()=>e.field.help||``,oninput:n=>e.field.help=n.target.value})))),footer:()=>[t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.required`,name:()=>`fields.${e.fieldIndex}.required`,checked:()=>!!e.field.required,onchange:n=>e.field.required=n.target.checked}),t.label({htmlFor:n+`.required`},t.span({className:`txt`},`Required`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Requires the field value to be nonempty string`)}))),t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.convertURLs`,name:()=>`fields.${e.fieldIndex}.convertURLs`,checked:()=>!!e.field.convertURLs,onchange:n=>e.field.convertURLs=n.target.checked}),t.label({htmlFor:n+`.convertURLs`},t.span({className:`txt`},`Strip URLs domain`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`This could help making the editor content more portable between environments since there will be no local base url to replace.`)})))]})}function q(e){return t.div({className:`record-field-view field-type-editor`},()=>{if(e.short){let n=e.record[e.field.name];return n?t.span({className:`txt`,textContent:app.utils.truncate(app.utils.plainText(n),200)}):t.span({className:`missing-value`})}return app.components.tinymce({readonly:!0,className:`large-modal`,value:()=>e.record[e.field.name]||``})})}window.app=window.app||{},window.app.fieldTypes=window.app.fieldTypes||{},window.app.fieldTypes.editor={icon:`ri-edit-2-line`,label:`Rich editor`,settings:en,input:$t,view:q,filterModifiers:e=>[`lower`],dummyData:(e,n=!1)=>`Lorem ipsum dolor sit amet...`};function tn(e){let n=`number_`+app.utils.randomString();return t.div({className:`record-field-input field-type-number`},t.div({className:`field`},t.label({htmlFor:n},t.i({className:app.fieldTypes.number.icon,ariaHidden:!0}),t.span({className:`txt`},()=>e.field.name)),t.input({type:`number`,id:n,step:`any`,name:()=>e.field.name,required:()=>e.field.required,min:()=>e.field.min,max:()=>e.field.max,value:()=>e.record[e.field.name]||0,oninput:n=>e.record[e.field.name]=Number(n.target.value)})),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function nn(e){let n=`f_`+app.utils.randomString();return app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.min`},`Min`),t.input({type:`text`,id:n+`.min`,name:()=>`fields.${e.fieldIndex}.min`,value:()=>typeof e.field.min==`number`?e.field.min:``,oninput:n=>{n.target.value?e.field.min=Number(n.target.value):e.field.min=null}}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.max`},`Max`),t.input({type:`text`,id:n+`.max`,min:()=>e.field.min,name:()=>`fields.${e.fieldIndex}.max`,value:()=>typeof e.field.max==`number`?e.field.max:``,oninput:n=>{n.target.value?e.field.max=Number(n.target.value):e.field.max=null}}))),t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.help`},`Help text`),t.input({type:`text`,id:n+`.help`,name:()=>`fields.${e.fieldIndex}.help`,value:()=>e.field.help||``,oninput:n=>e.field.help=n.target.value})))),footer:()=>[t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.onlyInt`,name:()=>`fields.${e.fieldIndex}.onlyInt`,checked:()=>!!e.field.onlyInt,onchange:n=>e.field.onlyInt=n.target.checked}),t.label({htmlFor:n+`.onlyInt`},t.span({className:`txt`},`No decimals`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Existing decimal numbers will not be affected.`)}))),t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.required`,name:()=>`fields.${e.fieldIndex}.required`,checked:()=>!!e.field.required,onchange:n=>e.field.required=n.target.checked}),t.label({htmlFor:n+`.required`},t.span({className:`txt`},`Required`),t.small({className:`txt-hint`},`(!=0)`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Requires the field value to be not 0.`)})))]})}function rn(e){return t.div({className:`record-field-view field-type-number`},t.span({className:`txt`},()=>e.record[e.field.name]))}window.app=window.app||{},window.app.fieldTypes=window.app.fieldTypes||{},window.app.fieldTypes.number={icon:`ri-hashtag`,label:`Number`,settings:nn,input:tn,view:rn,dummyData:(e,n=!1)=>123.456};function an(e){let n=`bool_`+app.utils.randomString();return t.div({className:`record-field-input field-type-bool`},t.div({className:`field`},t.input({type:`checkbox`,id:n,className:`switch`,name:()=>e.field.name,required:()=>e.field.required,checked:()=>e.record[e.field.name]||!1,onchange:n=>e.record[e.field.name]=n.target.checked||!1}),t.label({htmlFor:n},()=>e.field.name)),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function on(e){let n=`f_`+app.utils.randomString();return app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.help`},`Help text`),t.input({type:`text`,id:n+`.help`,name:()=>`fields.${e.fieldIndex}.help`,value:()=>e.field.help||``,oninput:n=>e.field.help=n.target.value})))),footer:()=>[t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.required`,name:()=>`fields.${e.fieldIndex}.required`,checked:()=>!!e.field.required,onchange:n=>e.field.required=n.target.checked}),t.label({htmlFor:n+`.required`},t.span({className:`txt`},`Required`),t.small({className:`txt-hint`},`(=true)`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Requires the field value to be true.`)})))]})}function sn(e){return t.div({className:`record-field-view field-type-bool`},t.span({className:()=>`label ${e.record[e.field.name]?`success`:``}`},()=>e.record[e.field.name]?`True`:`False`))}window.app=window.app||{},window.app.fieldTypes=window.app.fieldTypes||{},window.app.fieldTypes.bool={icon:`ri-toggle-line`,label:`Bool`,settings:on,input:an,view:sn,dummyData:(e,n=!1)=>[!0,!1][Math.floor(Math.random()*2)]};function cn(e){let n=`email_`+app.utils.randomString();return t.div({className:`record-field-input field-type-email`},t.div({className:`field`},t.label({htmlFor:n},t.i({className:app.fieldTypes.email.icon,ariaHidden:!0}),t.span({className:`txt`},()=>e.field.name)),t.input({type:`email`,id:n,spellcheck:!1,autocomplete:!1,name:()=>e.field.name,required:()=>e.field.required,value:()=>e.record[e.field.name]||``,oninput:n=>e.record[e.field.name]=n.target.value})),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function ln(e){let n=`f_`+app.utils.randomString();return app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.exceptDomains`},t.span({className:`txt`},`Except domains`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`List of domains that are NOT allowed. This field is disabled if "Only domains" is set.`)})),t.input({type:`text`,id:n+`.exceptDomains`,disabled:()=>!app.utils.isEmpty(e.field.onlyDomains),name:()=>`fields.${e.fieldIndex}.exceptDomains`,value:()=>app.utils.joinNonEmpty(e.field.exceptDomains),onchange:n=>e.field.exceptDomains=app.utils.splitNonEmpty(n.target.value,`,`)})),t.div({className:`field-help`},`Use comma as separator.`)),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.onlyDomains`},t.span({className:`txt`},`Only domains`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`List of domains that are ONLY allowed. This field is disabled if "Except domains" is set.`)})),t.input({type:`text`,id:n+`.onlyDomains`,disabled:()=>!app.utils.isEmpty(e.field.exceptDomains),name:()=>`fields.${e.fieldIndex}.onlyDomains`,value:()=>app.utils.joinNonEmpty(e.field.onlyDomains),onchange:n=>e.field.onlyDomains=app.utils.splitNonEmpty(n.target.value,`,`)})),t.div({className:`field-help`},`Use comma as separator.`)),t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:n+`.help`},`Help text`),t.input({type:`text`,id:n+`.help`,name:()=>`fields.${e.fieldIndex}.help`,value:()=>e.field.help||``,oninput:n=>e.field.help=n.target.value})))),footer:()=>[t.div({className:`field`},t.input({className:`sm`,type:`checkbox`,id:n+`.required`,name:()=>`fields.${e.fieldIndex}.required`,checked:()=>!!e.field.required,onchange:n=>e.field.required=n.target.checked}),t.label({htmlFor:n+`.required`},t.span({className:`txt`},`Required`),t.small({className:`txt-hint`},`(!='')`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Requires the field value to be nonempty string`)})))]})}function J(e){return t.div({className:`record-field-view field-type-email`},()=>{let n=e.record[e.field.name]||``;return n?e.short?t.span({className:`txt txt-ellipsis`,textContent:app.utils.truncate(n)}):n:t.span({className:`missing-value`})})}window.app=window.app||{},window.app.fieldTypes=window.app.fieldTypes||{},window.app.fieldTypes.email={icon:`ri-mail-line`,label:`Email`,settings:ln,input:cn,view:J,filterModifiers:e=>[`lower`],dummyData:(e,n=!1)=>`test_${app.utils.randomString(3,`123567890`)}@example.com`};function un(e){let n=`url_`+app.utils.randomString();return t.div({className:`record-field-input field-type-url`},t.div({className:`field`},t.label({htmlFor:n},t.i({className:app.fieldTypes.url.icon,ariaHidden:!0}),t.span({className:`txt`},()=>e.field.name)),t.input({type:`url`,id:n,spellcheck:!1,name:()=>e.field.name,required:()=>e.field.required,value:()=>e.record[e.field.name]||``,oninput:n=>e.record[e.field.name]=n.target.value})),()=>{if(e.field.help)return t.div({className:`field-help`},e.field.help)})}function Y(e){let n=`f_`+app.utils.randomString();return app.components.fieldSettings(e,{content:()=>t.div({className:`grid sm`},t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:n+`.exceptDomains`},t.span({className:`txt`},`Except domains`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`List of domains that are NOT allowed. @@ -58,11 +58,11 @@ This field is disabled if "Except domains" is set.`)})),t.input({type:`text`,id: To target the newly submitted ones you can use @request.body.*.`)})],name:`updateRule`,autocomplete:i,disabled:()=>e.originalCollection?.system,value:()=>e.collection.updateRule,oninput:n=>e.collection.updateRule=n})),t.div({className:`col-12`,ariaDescription:r()},app.components.ruleField({label:`Delete rule`,name:`deleteRule`,autocomplete:i,disabled:()=>e.originalCollection?.system,value:()=>e.collection.deleteRule,oninput:n=>e.collection.deleteRule=n}))]}),()=>{if(e.collection.type==`auth`)return[t.hr({className:`m-t-base m-b-base`}),t.button({type:`button`,onmount:()=>{n.showAuthRules=e.collection.manageRule!==null||e.collection.authRule!==``},className:()=>`btn secondary sm ${n.showAuthRules?``:`transparent`}`,onclick:()=>{n.showAuthRules=!n.showAuthRules}},t.span({className:`txt`},`Additional auth collection rules`),t.i({ariaHidden:!0,className:()=>n.showAuthRules?`ri-arrow-drop-up-line`:`ri-arrow-drop-down-line`})),app.components.slide(()=>n.showAuthRules,t.div({className:`grid sm m-t-sm`},t.div({className:`col-12`,ariaDescription:r()},app.components.ruleField({label:`Authentication rule`,name:`authRule`,placeholder:``,autocomplete:i,disabled:()=>e.originalCollection?.system,value:()=>e.collection.authRule,oninput:n=>e.collection.authRule=n}),t.div({className:`field-help`},t.p(null,`This rule is executed every time `,t.strong(null,`before authentication`),` allowing you to restrict who can authenticate.`),t.p(null,`For example, to allow only verified users you can set it to `,t.code(null,`verified = true`),`.`),t.p(null,`Leave it empty to allow anyone with an account to authenticate.`),t.p(null,`To disable authentication entirely you can change it to "Set superusers only".`))),t.div({className:`col-12`,ariaDescription:r()},app.components.ruleField({label:`Manage rule`,name:`manageRule`,autocomplete:i,disabled:()=>e.originalCollection?.system,value:()=>e.collection.manageRule,oninput:n=>e.collection.manageRule=n}),t.div({className:`field-help`},t.p(null,`This rule is executed in addition to the `,t.strong(null,`create`),` and `,t.strong(null,`update`),` API rules.`),t.p(null,`It enables superuser-like permissions to allow fully managing the auth record(s), eg. changing the password without requiring to enter the old one, directly updating the verified state or email, etc.`)))))]})}var Jn=`test_view_query`;function Yn(e){let n=`query_`+app.utils.randomString(),r=[`SELECT`,`FROM`,`WHERE`,`LEFT JOIN`,`INNER JOIN`,`ON`,`GROUP BY`,`HAVING`,`ORDER BY`,`LIMIT`,`OFFSET`,`AS`,`WITH`,`NOT`,`IN`,`EXISTS`,`LIKE`,`CAST`],i=store({testRecords:[],testError:``,isTesting:!1});async function a(n){if(i.isTesting=!0,i.testRecords=[],(app.store.errors?.viewQuery||app.store.errors?.fields)&&(delete app.store.errors.viewQuery,delete app.store.errors.fields),!n){i.testError=``,i.isTesting=!1;return}try{let r=await app.pb.send(`/api/collections/meta/dry-run-view`,{method:`POST`,body:{query:n},requestKey:Jn});e.collection?.id?i.testRecords=r.sample.map(n=>(n.collectionId=e.collection?.id,n.collectionName=e.collection?.name,n)):i.testRecords=r.sample,i.testError=``,i.isTesting=!1}catch(e){e.isAbort||(i.testError=e.message||`Invalid query.`,i.isTesting=!1)}}let o,s=[watch(()=>e.collection?.viewQuery,e=>{clearTimeout(o),o=setTimeout(()=>a(e),200)})];return t.div({pbEvent:`collectionViewQueryTabContent`,className:`collection-tab-content collection-view-query-tab-content`,onunmount:()=>{clearTimeout(o),app.pb.cancelRequest(Jn),s.forEach(e=>e?.unwatch())}},t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`txt-right txt-sm m-b-10`},t.button({type:`button`,className:`txt-bold link-hint`,"html-popovertarget":n+`caveats_dropdown`},()=>`Query caveats`)),t.div({id:n+`caveats_dropdown`,className:`dropdown sm query-caveats-dropdown`,popover:`auto`},t.ul(null,t.li(null,`Wildcard columns (*) are not supported.`),t.li(null,`The query must have a unique `,t.code(null,`id`),` column.`,t.br(),`If your query doesn't have a suitable one, you can use the universal `,t.code(null,`(ROW_NUMBER() OVER()) as id`),`.`),t.li(null,`Expressions must be aliased with a valid formatted field name, e.g. `,t.code(null,`MAX(balance) as maxBalance`),`.`),t.li(null,`Combined/multi-spaced expressions must be wrapped in parenthesis, e.g. `,t.code(null,`(MAX(balance) + 1) as maxBalance`),`.`),t.li(null,`UNION expressions are supported but the entire query must be wrapped in parenthesis.`))),t.div({className:`field`},t.label({htmlFor:n+`.viewQuery`},t.span({className:`txt`},`Select query`),t.span({hidden:()=>!i.testError,className:`query-state`,ariaDescription:app.attrs.tooltip(`Invalid query`,`left`)},t.i({className:`ri-error-warning-fill txt-danger`,ariaHidden:!0})),t.span({hidden:()=>!!i.testError,className:`query-state`,ariaDescription:app.attrs.tooltip(`Valid query`,`left`)},t.i({className:`ri-checkbox-circle-fill txt-success`,ariaHidden:!0}))),app.components.codeEditor({id:n+`.viewQuery`,name:`viewQuery`,language:`sql`,required:!0,autocomplete:r,className:`inline-error`,value:()=>e.collection.viewQuery||``,oninput:n=>{e.collection.viewQuery=n}}))),t.div({className:`col-12`},t.p({className:`txt-sm txt-bold`},`Sample output:`),t.div({className:`view-query-sample-wrapper`},app.components.codeBlock({language:()=>i.testError?`plain`:`js`,className:()=>`view-query-sample ${i.testError?`txt-danger`:``}`,value:()=>i.testRecords?.length?JSON.stringify(i.testRecords,null,2):i.testError||`N/A`})))))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openCollectionUpsert=function(e={},n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,onsave:null,ondelete:null,onduplicate:null,ontruncate:null}){app.store.errors=null;let r=Xn(e||{},n||{});document.body.appendChild(r),app.modals.open(r)},window.app.collectionTypes={base:{icon:`ri-folder-2-line`,tabs:{Fields:Q,"API rules":qn}},view:{icon:`ri-table-line`,tabs:{Query:Yn,"API rules":qn}},auth:{icon:`ri-group-line`,tabs:{Fields:Q,"API rules":qn,Options:Kn}}};function Xn(e,n){let r,i=`collection_upsert_`+app.utils.randomString(),a=store({isSaving:!1,originalCollection:{},collection:{},selectedTab:``,get activeTab(){return app.collectionTypes[a.collection.type]?.tabs&&(!a.selectedTab||!app.collectionTypes[a.collection.type].tabs?.[a.selectedTab])?Object.keys(app.collectionTypes[a.collection.type].tabs)?.[0]||``:a.selectedTab},get isNew(){return app.utils.isEmpty(a.originalCollection?.id)},get collectionTypeOptions(){return Object.keys(app.collectionTypes).map(e=>({value:e,label:app.utils.sentenize(e,!1)+` collection`}))},get collectionHash(){return Object.keys(a.collection).length,JSON.stringify(a.collection)},get originalCollectionHash(){return JSON.stringify(a.originalCollection)},get hasChanges(){return a.originalCollectionHash!=a.collectionHash},get canSave(){return!a.isSaving&&(a.isNew||a.hasChanges)}});async function o(e){app.utils.isEmpty(e)&&(e=JSON.parse(JSON.stringify(app.store.collectionScaffolds.base))||{type:`base`,fields:[]},e.fields.push({type:`autodate`,name:`created`,onCreate:!0}),e.fields.push({type:`autodate`,name:`updated`,onCreate:!0,onUpdate:!0})),a.originalCollection=JSON.parse(JSON.stringify(e)),a.collection=JSON.parse(JSON.stringify(e))}async function s(e=!0){a.canSave&&(a.isSaving=!0,app.modals.openCollectionChangesConfirmation(a.originalCollection,a.collection,()=>l(e),()=>{a.isSaving=!1}))}function c(){let e=JSON.parse(JSON.stringify(a.collection));e.fields=e.fields||[];for(let n=e.fields.length-1;n>=0;n--)if(e.fields[n][`@toDelete`]){e.fields.splice(n,1);continue}return e}async function l(e=!0){a.isSaving=!0;try{let i=c(),o=app.utils.isEmpty(a.originalCollection?.id),s;s=o?app.pb.collections.create(i):app.pb.collections.update(a.originalCollection.id,i);let l=JSON.stringify(await s);a.originalCollection=JSON.parse(l),a.collection=JSON.parse(l),app.store.addOrUpdateCollection(JSON.parse(l)),n?.onsave?.(JSON.parse(l),o),a.isSaving=!1,app.toasts.success(o?`Successfully created collection "${a.collection.name}".`:`Successfully updated collection "${a.collection.name}".`,{key:`collectionSave`}),app.store.errors=null,e&&app.modals.close(r,!0)}catch(e){e?.isAbort||(a.isSaving=!1,app.checkApiError(e,!1),app.toasts.error(e.message||`Failed to save collection.`,{key:`collectionSave`}))}}function u(){a.collection=JSON.parse(JSON.stringify(a.originalCollection))}async function d(){let e=a.originalCollection?JSON.parse(JSON.stringify(a.originalCollection)):{};return e.id=``,e.system=!1,e.name+=`_duplicate`,e.created=``,e.updated=``,e.indexes=e.indexes?.map(n=>app.utils.replaceIndexFields(n,n=>({indexName:n.indexName+app.utils.randomString(3),tableName:e.name})))||[],await n.onduplicate?.(e),o(e)}async function f(e){a.selectedTab=e,await new Promise(e=>setTimeout(e,0)),app.store.errors&&(app.store.errors=JSON.parse(JSON.stringify(app.store.errors)))}return r=t.div({pbEvent:`collectionUpsertModal`,"html-data-collectionId":()=>a.originalCollection?.id,"html-data-collectionName":()=>a.originalCollection?.name,className:`modal collection-upsert-modal`,inert:()=>a.isSaving,onkeydown:e=>{if((e.ctrlKey||e.metaKey)&&e.code==`KeyS`){e.preventDefault();let n=document.activeElement;n?.blur(),s(!1),n?.focus()}},onbeforeopen:()=>(o(e),n.onbeforeopen?.(el)),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:(e,r)=>r?n.onbeforeclose?.(e):a.isSaving?!1:a.hasChanges?new Promise(r=>{app.modals.confirm(`You have unsaved changes. Do you really want to discard them?`,()=>r(n.onbeforeclose?.(e)),()=>r(!1))}):n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()},onmount:e=>{e._watchers?.forEach(e=>e?.unwatch()),e._watchers=[watch(()=>a.collection.type,(e,n)=>{if(!n||e==n||!app.store.collectionScaffolds[e])return;app.utils.deleteByPath(app.store.errors,`fields`);let r=JSON.parse(JSON.stringify(app.store.collectionScaffolds[e]));a.collection=Object.assign(structuredClone(r),JSON.parse(JSON.stringify(a.collection))),a.originalCollection=r,Zn(a.collection)}),watch(()=>a.collection.name,(n,r)=>{n=app.utils.slugify(n),a.collection.name=n,!(r===void 0||!n||n==r)&&(clearTimeout(e.__collectionRenameTimeoutId),e.__collectionRenameTimeoutId=setTimeout(()=>{a.collection.indexes=a.collection.indexes?.map(e=>app.utils.replaceIndexFields(e,{tableName:a.collection.name}))},150))})]},onunmount:e=>{clearTimeout(e?.__collectionRenameTimeoutId),e?._watchers?.forEach(e=>e?.unwatch())}},t.header({className:`modal-header isolated`},t.div({className:`grid sm`},t.div({className:`col-12 flex`},t.h6({className:`modal-title`},t.span(null,()=>a.isNew?`Create `:`Edit `),t.strong({hidden:()=>a.isNew,className:`txt-ellipsis collection-name`},()=>a.originalCollection?.name),t.span(null,` collection`)),t.div({className:`flex-fill`}),()=>{if(!app.utils.isEmpty(a.originalCollection?.id))return[t.button({type:`button`,className:`btn sm circle transparent`,title:`More options`,"html-popovertarget":i+`modal-header-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:i+`modal-header-dropdown`,className:`dropdown nowrap modal-header-dropdown`,popover:`auto`},t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),app.utils.copyToClipboard(JSON.stringify(a.originalCollection,null,2)),app.toasts.success(`Collection copied to clipboard!`)}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)),t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),a.hasChanges?app.modals.confirm(`You have unsaved changes. Do you really want to discard them?`,d,null,{yesButton:`Yes, discard`}):d()}},t.i({className:`ri-file-copy-line`,ariaHidden:!0}),t.span({className:`txt`},`Duplicate`)),t.hr(),()=>{if(a.collection.type!=`view`)return Qn(a,n)},()=>{if(!a.collection.system)return $n(a,n)})]}),t.div({className:`col-12`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:i+`col_name`,textContent:()=>`Name${a.collection?.system?` (system)`:``}`}),t.input({id:i+`col_name`,type:`text`,name:`name`,required:!0,spellcheck:!1,placeholder:`e.g. posts`,autofocus:()=>a.isNew,disabled:()=>!a.isNew&&a.collection?.system,value:()=>a.collection.name||``,onmount:e=>{e.addEventListener(`compositionend`,e=>{a.collection.name=e.target.value})},oninput:e=>{e.isComposing||(a.collection.name=e.target.value)}})),t.div({className:`field addon`},t.button({type:`button`,disabled:()=>!a.isNew,className:()=>`btn sm collection-type-select ${a.isNew?`outline`:`transparent`}`,"html-popovertarget":i+`col_type_dropdown`},t.span({className:`txt`},`Type: `,()=>app.utils.sentenize(a.collection.type,!1)||`N/A`),t.i({hidden:()=>!a.isNew,ariaHidden:!0,className:`ri-arrow-drop-down-line m-l-auto`})),t.div({id:i+`col_type_dropdown`,className:`dropdown nowrap collection-type-dropdown`,popover:`auto`},()=>{let e=[];for(let n of a.collectionTypeOptions)e.push(t.button({type:`button`,className:()=>`dropdown-item ${n.value==a.collection.type?`active`:``}`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),a.collection.type=n.value}},t.i({ariaHidden:!0,className:app.collectionTypes[n.value]?.icon||app.utils.fallbackCollectionIcon}),t.span({className:`txt`},n.label||n.value)));return e})))),t.div({className:`col-12`},t.nav({className:`tabs-header equal-width`},()=>{let e=[],n=app.collectionTypes[a.collection.type]?.tabs||{};for(let r in n)e.push(t.button({type:`button`,disabled:()=>a.isSaving,className:()=>`tab-item ${a.activeTab==r?`active`:``}`,onclick:()=>f(r)},t.span({className:`txt`},r)));return e})))),t.div({className:`modal-content`},()=>app.collectionTypes[a.collection.type]?.tabs?.[a.activeTab]?.(a)),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,disabled:()=>a.isSaving,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),()=>{let e=JSON.stringify(app.store.errors);if(!(e==``||e==`null`||e==`{}`||e==`[]`))return t.i({className:`ri-alert-line txt-danger`,ariaDescription:app.attrs.tooltip(()=>`Raw error: `+e)})},t.div({className:`btns`},t.button({type:`button`,className:()=>`btn expanded-lg ${a.isSaving?`loading`:``}`,disabled:()=>!a.canSave,onclick:()=>s(!0)},t.span({className:`txt`},()=>a.isNew?`Create`:`Save changes`)),t.button({type:`button`,title:`Save options`,className:()=>`btn p-5`,disabled:()=>!a.canSave,"html-popovertarget":i+`save_options`},t.i({className:`ri-arrow-up-s-line`,ariaHidden:!0})),t.div({id:i+`save_options`,className:`dropdown nowrap`,popover:`auto`},t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),s(!1)}},t.span({className:`txt`},`Save and continue`),t.small({className:`txt-hint`},`(Ctrl+S)`)),t.hr(),t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`).hidePopover(),u()}},t.span({className:`txt`},`Reset form`)))))),r}function Zn(e){let n=JSON.parse(JSON.stringify(app.store.collectionScaffolds[e.type])),r=JSON.parse(JSON.stringify(e.fields))||[],i=r.filter(e=>!e.system);e.fields=n.fields||[];for(let n of r){if(!n.system)continue;let r=e.fields.find(e=>e.name==n.name);r&&Object.assign(r,n)}for(let n of i)e.fields.push(n);if(e.indexes=e.indexes||[],e.indexes.length){let r=n?.indexes||[];indexesLoop:for(let n=e.indexes.length-1;n>=0;n--){let i=app.utils.parseIndex(e.indexes[n]),a=i.indexName.toLowerCase();for(let i of r)if(a==app.utils.parseIndex(i).indexName.toLowerCase()){e.indexes.splice(n,1);continue indexesLoop}for(let r of i.columns)if(!e.fields.find(e=>e.name.toLowerCase()==r.name.toLowerCase())){e.indexes.splice(n,1);continue indexesLoop}}}app.utils.mergeUnique(e.indexes,n.indexes)}function Qn(e,n){let r=`truncate_`+app.utils.randomString(),i=store({isSubmitting:!1,nameConfirm:``});async function a(){if(i.isSubmitting||!e.originalCollection?.name||e.originalCollection.name!=i.nameConfirm)return!1;i.isSubmitting=!0;try{return await app.pb.collections.truncate(e.originalCollection.name),n.ontruncate?.(JSON.parse(JSON.stringify(e.originalCollection))),app.toasts.success(`Successfully truncated collection "${e.originalCollection.name}".`),i.isSubmitting=!1,!0}catch(e){i.isSubmitting=!1,app.checkApiError(e)}return!1}return t.button({type:`button`,className:`dropdown-item txt-danger`,disabled:()=>i.isSubmitting,onclick:n=>{n.target.closest(`.dropdown`).hidePopover(),app.modals.confirm(t.div(null,t.h6({className:`block txt-center`},`Do you really want to delete all records of the collection?`),t.div({className:`confirm-collection-label txt-bold m-t-sm m-b-sm`},`Type the collection name `,t.div({className:`label`},()=>e.originalCollection.name,app.components.copyButton(()=>e.originalCollection?.name)),` to confirm:`),t.div({className:`field`},t.label({htmlFor:r+`.confirm_name`},`Collection name`),t.input({id:r+`.confirm_name`,type:`text`,required:!0,pattern:()=>RegExp.escape(e.originalCollection.name),value:()=>i.nameConfirm,oninput:e=>i.nameConfirm=e.target.value}))),async()=>{if(document.getElementById(r+`.confirm_name`)?.reportValidity(),!await a())return!1;app.modals.close(n.target.closest(`.modal`))},()=>{i.nameConfirm=``})}},t.i({className:`ri-eraser-line`,ariaHidden:!0}),t.span({className:`txt`},`Truncate`))}function $n(e,n){let r=`delete_`+app.utils.randomString(),i=store({isSubmitting:!1,nameConfirm:``});async function a(){if(i.isSubmitting||!e.originalCollection?.name||e.originalCollection.name!=i.nameConfirm)return!1;i.isSubmitting=!0;try{return await app.pb.collections.delete(e.originalCollection.name),n.ondelete?.(JSON.parse(JSON.stringify(e.originalCollection))),app.utils.removeByKey(app.store.collections,`id`,e.originalCollection.id),app.toasts.success(`Successfully deleted collection "${e.originalCollection.name}".`),i.isSubmitting=!1,!0}catch(e){i.isSubmitting=!1,app.checkApiError(e)}return!1}return t.button({type:`button`,className:`dropdown-item txt-danger`,disabled:()=>i.isSubmitting,onclick:n=>{n.target.closest(`.dropdown`).hidePopover();let o=n.target.closest(`.modal`);app.modals.confirm(t.div({className:`block`},t.h6({className:`block txt-center`},()=>e.originalCollection.type==`view`?`Do you really want to delete the selected collection?`:`Do you really want to delete the selected collection and all its records`),t.div({className:`confirm-collection-label txt-bold m-t-sm m-b-sm`},`Type the collection name `,t.div({className:`label`},()=>e.originalCollection.name,app.components.copyButton(()=>e.originalCollection?.name)),` to confirm:`),t.div({className:`field`},t.label({htmlFor:r+`.confirm_name`},`Collection name`),t.input({id:r+`.confirm_name`,type:`text`,required:!0,pattern:()=>RegExp.escape(e.originalCollection.name),value:()=>i.nameConfirm,oninput:e=>i.nameConfirm=e.target.value}))),async()=>{if(document.getElementById(r+`.confirm_name`)?.reportValidity(),!await a())return!1;app.modals.close(o)},()=>{i.nameConfirm=``})}},t.i({className:`ri-delete-bin-7-line`,ariaHidden:!0}),t.span({className:`txt`},`Delete`))}window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.addCollectionFieldButton=function(e){let n=`new_field_`+app.utils.randomString();function r(n){let r={id:``,name:i(n),type:n,system:!1,hidden:!1,presentable:!1,required:!1,__focus:!0};e.fields=e.fields||[];let a=e.fields.findLastIndex(e=>e.type!=`autodate`);r.type!=`autodate`&&a>=0?e.fields.splice(a+1,0,r):e.fields.push(r)}function i(e=``){let n=e,r=2,i=e.match(/\d+$/)?.[0]||``,o=i?e.substring(0,e.length-i.length):e;for(;a(n);)n=o+((i<<0)+r),r++;return n}function a(n){return!!e.fields?.find(e=>e.name.toLowerCase()===n.toLowerCase())}return t.div({className:`new-collection-field-btn-wrapper`},t.button({type:`button`,className:`btn block outline`,"html-popovertarget":n+`_dropdown`},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({className:`txt`},`New field`)),t.div({id:n+`_dropdown`,className:`dropdown field-types-dropdown`,popover:`auto`},()=>{let e=[];for(let n in app.fieldTypes){if(n==`password`)continue;let i=app.fieldTypes[n];i.settings&&e.push(t.button({type:`button`,className:`dropdown-item`,onclick:e=>{e.target.closest(`.dropdown`)?.hidePopover(),r(n)}},t.i({className:i.icon||app.utils.fallbackFieldIcon,ariaHidden:!0}),t.span({className:`txt`},i.label||n)))}return e}))},window.app=window.app||{},window.app.utils=window.app.utils||{};var er={maxKeys:30,requestKeys:!0,collectionJoinKeys:!0};window.app.utils.collectionAutocompleteKeys=function(e,n,r={}){if(!e||!n||!app.store.collections?.length)return[];r=Object.assign({},er,r);let i=nr(n,app.store.collections,e).sort(tr);if(r.requestKeys){let r=rr(n,app.store.collections,e).sort(tr);for(let e of r)i.push(e)}if(r.collectionJoinKeys){let e=ir(n,app.store.collections).sort(tr);for(let n of e)i.push(n)}return i.length>r.maxKeys?i.slice(0,r.maxKeys):i};function tr(e,n){return e.length-n.length}function nr(e,n,r,i=``,a=0){if(!e||a>=4||(typeof r==`string`&&(r=n.find(e=>e.name==r||e.id==r)),!r))return[];e=e.toLowerCase();let o=r.type==`auth`,s=app.utils.getAllCollectionIdentifiers(r,i).filter(n=>n.toLowerCase().includes(e)),c=r.fields||[];for(let r of c){if(r.type==`password`||o&&r.name==`tokenKey`)continue;let c=[];if(i==`@request.body.`&&(c.push(i+r.name+`:changed`),c.push(i+r.name+`:isset`)),typeof app.fieldTypes[r.type]?.filterModifiers==`function`){let e=app.fieldTypes[r.type]?.filterModifiers(r)||[];for(let n of e)c.push(i+r.name+`:`+n)}for(let n of c)n.toLowerCase().includes(e)&&s.push(n);if(r.type==`relation`&&r.collectionId){let o=nr(e,n,r.collectionId,i+r.name+`.`,a+1);for(let e of o)s.push(e)}}for(let o of n){let c=o.fields||[];for(let l of c){if(l.type!=`relation`||l.collectionId!=r.id)continue;let c=i+o.name+`_via_`+l.name,u=nr(e,n,o,c+`.`,a+2);for(let e of u)s.push(e)}}return s}function rr(e,n,r){if(!e)return[];e=e.toLowerCase();let i=[];for(let n of[`@request.context`,`@request.method`,`@request.query.`,`@request.body.`,`@request.headers.`,`@request.auth.collectionId`,`@request.auth.collectionName`])n.toLowerCase().includes(e)&&i.push(n);let a=n.filter(e=>e.type===`auth`);for(let r of a){if(r.system)continue;let a=nr(e,n,r,`@request.auth.`);for(let e of a)app.utils.pushUnique(i,e)}if(typeof r==`string`&&(r=n.find(e=>e.name==r||e.id==r)),!r)return i;let o=nr(e,n,r,`@request.body.`);for(let e of o)i.push(e);return i}function ir(e,n){let r=[],i=`@collection.`,a,o;if(12!e.exclude?.includes(r.name)&&(r.name+r.displayName).toLowerCase().replaceAll(` `,``).includes(n))}});function i(){r.searchTerm=``}return n=t.div({pbEvent:`providerPickerModal`,className:`modal provider-picker-modal`,onbeforeopen:n=>e.onbeforeopen?.(n),onafteropen:n=>{e.onafteropen?.(n)},onbeforeclose:n=>e.onbeforeclose?.(n),onafterclose:n=>{e.onafterclose?.(n),n?.remove()}},t.header({className:`modal-header`},t.h6({className:`modal-title`},t.span({className:`txt`},`Select OAuth2 provider`))),t.div({className:`modal-content`},t.div({className:`grid sm`},t.div({className:`col-12`},t.div({className:`fields searchbar`},t.div({className:`field`},t.input({placeholder:`Search...`,className:`p-l-20`,value:()=>r.searchTerm,oninput:e=>r.searchTerm=e.target.value})),()=>{if(r.searchTerm)return t.div({rid:`search-ctrls`,className:`field addon p-r-5`},t.button({type:`button`,className:`btn sm pill secondary transparent`,onclick:()=>i()},`Clear`))})),()=>{if(!(app.store.isLoadingOAuth2Providers||r.filteredProviders.length))return t.div({rid:`notfound`,className:`block txt-center txt-hint`},t.p(null,`No providers found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,onclick:()=>i()}))},()=>app.store.isLoadingOAuth2Providers?t.div({className:`col-12 txt-center`},t.span({className:`loader active`})):r.filteredProviders.map(r=>t.div({className:`col-sm-6`},t.button({type:`button`,className:`provider-card handle`,onclick:()=>{app.modals.close(n),e.onselect?.(r)}},t.figure({className:`provider-logo`},()=>r.logo?t.img({src:`data:image/svg+xml;base64,`+btoa(r.logo),alt:r.name+` logo`}):t.i({className:app.utils.fallbackProviderIcon,ariaHidden:!0})),t.div({className:`content`},t.span({className:`primadry-txt`},r.displayName||r.name),t.span({className:`secondary-txt`},r.name))))))),t.footer({className:`modal-footer gap-base`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n)},t.span({className:`txt`},`Close`)))),n}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openProviderSettings=function(e={},n={namePrefix:``,onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,onsubmit:null}){let r=or(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};function or(e,n){let r,i=`provider_`+app.utils.randomString();e||={};let a=!e.clientId,o=JSON.stringify(e),s=app.store.oauth2Providers?.find(n=>n.name==e.name);if(!s){console.warn(`missing provider for config`,e);return}let c=store({config:JSON.parse(o),get hasChanges(){return o!=JSON.stringify(c.config)},onsubmit:(e,n)=>{}});function l(){c.hasChanges&&(n.onsubmit?.(s,JSON.parse(JSON.stringify(c.config))),app.modals.close(r))}return r=t.div({pbEvent:`providerSettingsModal`,className:`modal provider-settings-modal`,onbeforeopen:e=>n.onbeforeopen?.(e),onafteropen:e=>{n.onafteropen?.(e),setTimeout(()=>{app.store.errors?.oauth2&&(app.store.errors.oauth2=JSON.parse(JSON.stringify(app.store.errors.oauth2)))},0)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()}},t.header({className:`modal-header`},t.figure({className:`provider-logo`},()=>s.logo?t.img({src:`data:image/svg+xml;base64,`+btoa(s.logo),alt:s.name+` logo`}):t.i({className:app.utils.fallbackProviderIcon,ariaHidden:!0})),t.h6({className:`modal-title`},e.displayName||s.displayName||s.name,t.small({className:`txt-hint`},` (`,e.name,`)`))),t.form({pbEvent:`providerSettingsForm`,id:i+`form`,className:`modal-content`,onsubmit:e=>{e.preventDefault(),l()}},t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.clientId`,textContent:`Client ID`}),t.input({type:`text`,required:!0,id:i+`.clientId`,autocomplete:`off`,name:()=>n.namePrefix+`.clientId`,value:()=>c.config.clientId||``,oninput:e=>c.config.clientId=e.target.value.trim()}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.clientSecret`,textContent:`Client secret`}),t.input({type:`password`,id:i+`.clientSecret`,autocomplete:`new-password`,required:()=>a||c.config.clientSecret!==void 0,name:()=>n.namePrefix+`.clientSecret`,value:()=>c.config.clientSecret||``,oninput:e=>c.config.clientSecret=e.target.value.trim(),onkeyup:e=>{e.key==`Backspace`&&c.config.clientSecret===void 0&&(c.config.clientSecret=``)},placeholder:()=>a||c.config.clientSecret!==void 0?``:`* * * * * *`}))),()=>{if(typeof app.oauth2?.[s.name]==`function`)return t.div({className:`col-12`},app.oauth2[s.name](s,n.namePrefix,c))})),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),t.button({"html-form":i+`form`,type:`submit`,className:`btn`,disabled:()=>!c.hasChanges},t.span({className:`txt`},`Set provider config`)))),r}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openCollectionChangesConfirmation=async function(e,n,r,i){let a=store({isLoadingConflictingOIDCProviders:!1,conflictingOIDCProviders:[],get isCollectionRenamed(){return e?.name!=n?.name},get isNewCollectionAuth(){return n?.type===`auth`},get isNewCollectionView(){return n?.type===`view`},get renamedFields(){return a.isNewCollectionView?[]:n?.fields?.filter?.(n=>{let r;return n.id&&!n[`@toDelete`]&&(r=e.fields?.find?.(e=>e.id==n.id)),r&&r.name!=n.name})||[]},get deletedFields(){return a.isNewCollectionView?[]:n?.fields?.filter?.(e=>e.id&&e[`@toDelete`])||[]},get multipleToSingleFields(){return a.isNewCollectionView?[]:n?.fields?.filter?.(n=>{let r=e?.fields?.find?.(e=>e.id==n.id);if(!r||r.maxSelect===void 0)return!1;let i=r.maxSelect||1,a=n.maxSelect||1;return i>1&&a==1})||[]},get changedRules(){if(window.location.protocol!=`https:`)return[];let r=[],i=[`listRule`,`viewRule`];a.isNewCollectionView||i.push(`createRule`,`updateRule`,`deleteRule`),a.isNewCollectionAuth&&i.push(`manageRule`,`authRule`);let o,s;for(let a of i)o=e?.[a],s=n?.[a],o!==s&&r.push({prop:a,oldRule:o,newRule:s});return r},get needConfirmation(){return!app.utils.isEmpty(e?.id)&&(a.isCollectionRenamed||a.renamedFields.length||a.deletedFields.length||a.multipleToSingleFields.length||a.changedRules.length||a.conflictingOIDCProviders.length)}}),o=[`oidc`,`oidc2`,`oidc3`];async function s(){if(!(app.utils.isEmpty(e?.id)||!a.isNewCollectionAuth)){a.isLoadingConflictingOIDCProviders=!0;try{a.conflictingOIDCProviders=[];for(let r of o){let i=e?.oauth2?.providers?.find?.(e=>e.name==r),o=n?.oauth2?.providers?.find?.(e=>e.name==r);if(!i||!o)continue;let s=new URL(i.authURL).host,c=new URL(o.authURL).host;s!=c&&await app.pb.collection(`_externalAuths`).getFirstListItem(app.pb.filter(`collectionRef={:collectionId} && provider={:provider}`,{collectionId:n?.id,provider:r}),{requestKey:null})&&a.conflictingOIDCProviders.push({name:r,oldHost:s,newHost:c})}a.isLoadingConflictingOIDCProviders=!1}catch(e){e.isAbort&&(a.isLoadingConflictingOIDCProviders=!1,app.checkApiError(e))}}}if(await s(),!a.needConfirmation)return r();app.modals.confirm(t.div({className:`dangerous-collection-changes-list`},t.h5({className:`block txt-center m-b-base`},`Do you really want to save the collection changes?`),()=>{if(!(!a.isCollectionRenamed&&!a.deletedFields.length&&!a.renamedFields.length))return t.div({className:`alert warning m-b-base`},t.p(null,`If the collection participate in another collection rule, filter or view query, you'll have to update it manually!`),()=>{if(a.deletedFields.length)return t.p(null,`All data associated with the removed fields will be permanently deleted!`)})},()=>{if(a.isCollectionRenamed)return t.ul({className:`collection-changes-list changes-renamed-collection`},t.li({className:`list-item`},`Renamed collection `,t.strong({className:`label warning`},e?.name),t.i({className:`ri-arrow-right-line txt-sm`,ariaHidden:!0}),t.strong({className:`label success`},n?.name||`N/A`)))},()=>{if(a.renamedFields.length)return t.ul({className:`collection-changes-list changes-renamed-fields`},()=>a.renamedFields.map(n=>{let r=e?.fields?.find?.(e=>e.id==n.id);return t.li({className:`list-item`},`Renamed field `,t.strong({className:`label warning`},r?.name),t.i({className:`ri-arrow-right-line txt-sm`,ariaHidden:!0}),t.strong({className:`label success`},n.name||`N/A`))}))},()=>{if(a.deletedFields.length)return t.ul({className:`collection-changes-list changes-deleted-fields`},()=>a.deletedFields.map(e=>t.li({className:`list-item`},`Deleted field `,t.strong({className:`label danger`},e.name||`N/A`))))},()=>{if(a.multipleToSingleFields.length)return t.ul({className:`collection-changes-list changes-multiple-to-single-fields`},()=>a.multipleToSingleFields.map(e=>t.li({className:`list-item`},`Multiple to single value conversion of field `,t.strong({className:`label warning`},e.name||e.id),t.em({className:`txt-sm`},` (will keep only the last array item)`))))},()=>{if(a.changedRules.length)return t.ul({className:`collection-changes-list changes-api-rules`},()=>a.changedRules.map(e=>t.li({className:`list-item`},t.div({className:`content`},t.span({className:`txt`},`Changed API rule for `),t.code(null,e.prop)),t.small({className:`txt-bold`},`Old:`),t.div({className:`rule-content old-rule`},e.oldRule===null?`null (superusers only)`:e.oldRule||`""`),t.small({className:`txt-bold`},`New:`),t.div({className:`rule-content new-rule`},e.newRule===null?`null (superusers only)`:e.newRule||`""`))))},()=>{if(a.conflictingOIDCProviders.length)return t.ul({className:`collection-changes-list changes-api-rules`},()=>a.conflictingOIDCProviders.map(e=>t.li({className:`list-item`},`Changed OIDC `,e.name,` host `,t.strong({className:`label warning`},e.oldHost),t.i({className:`ri-arrow-right-line txt-sm`,ariaHidden:!0}),t.strong({className:`label success`},e.newHost),t.br(),t.span({className:`txt-hint`},`If the old and new OIDC configuration is not for the same provider consider deleting`,` all old _externalAuths records associated to the current collection and provider,`,` otherwise it may result in account linking errors.`),` `,t.a({rel:`noopenener noreferrer`,target:`_blank`,href:()=>`#/collections?collection=_externalAuths&filter=collectionRef%3D%22${n?.id}%22+%26%26+provider%3D%22${e.name}%22`,textContent:`Review existing _externalAuths records`}))))}),r,i,{className:`collection-changes-confirm-modal`})},window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openCollectionsOverview=function(e={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let n=sr(e);n&&(document.body.appendChild(n),app.modals.open(n))};function sr(e={}){let n=`overview_modal_`+app.utils.randomString(),r={"Fields and relations":cr,Rules:lr},i=store({showSystemCollections:!1,activeTab:Object.keys(r)[0],get collections(){return i.showSystemCollections?app.store.collections:app.store.collections.filter(e=>!e.system)}}),a=t.div({pbEvent:`collectionsOverviewModal`,className:`modal popup collections-overview-modal`,onbeforeopen:n=>e.onbeforeopen?.(n),onafteropen:n=>{e.onafteropen?.(n)},onbeforeclose:n=>e.onbeforeclose?.(n),onafterclose:n=>{e.onafterclose?.(n),n?.remove()}},t.header({className:`modal-header isolated`},t.div({className:`grid sm`},t.div({className:`col-12`},t.div({className:`flex`},t.h6({className:`modal-title`},`Collections overview`),t.div({className:`flex-fill`}),t.div({className:`field`},t.input({id:n+`.showSystemCollections`,type:`checkbox`,className:`sm switch`,checked:()=>i.showSystemCollections,onchange:e=>i.showSystemCollections=e.target.checked}),t.label({htmlFor:n+`.showSystemCollections`},`System collections`)),t.button({type:`button`,className:`btn sm secondary transparent circle modal-close-btn`,title:`Close`,onclick:()=>app.modals.close(a)},t.i({className:`ri-close-line`,ariaHidden:!0})))),t.div({className:`col-12`},t.div({className:`tabs-header equal-width`},()=>{let e=[];for(let n in r)e.push(t.button({type:`button`,className:()=>`tab-item ${i.activeTab==n?`active`:``}`,onclick:()=>i.activeTab=n,textContent:n}));return e})))),()=>r[i.activeTab]?.(i));return a}function cr(e){return t.div({className:`modal-content erd-tab`},app.components.erd({collections:()=>{let n,r;function i(e,i){return n=e.name.startsWith(`_`),r=i.name.startsWith(`_`),e.system&&!i.system||n&&!r?1:!e.system&&i.system||!n&&r?-1:0}return e.collections.slice().sort(i)}}))}function lr(e){let n=[{value:`listRule`,label:`List/Search rule`},{value:`viewRule`,label:`View rule`},{value:`createRule`,label:`Create rule`,filter:e=>e.type!=`view`},{value:`updateRule`,label:`Update rule`,filter:e=>e.type!=`view`},{value:`deleteRule`,label:`Delete rule`,filter:e=>e.type!=`view`},{value:`authRule`,label:`Auth rule`,filter:e=>e.type==`auth`},{value:`manageRule`,label:`Manage rule`,filter:e=>e.type==`auth`},{value:`mfaRule`,label:`MFA rule`,emptyLabel:t.span({className:`label info`},`Enabled for everyone`),rule:e=>e.mfa?.rule,filter:e=>e.mfa?.enabled&&e.type==`auth`}],r=store({activeRuleOption:n[0],get activeCollections(){return r.activeRuleOption.filter?e.collections.filter(e=>r.activeRuleOption.filter(e)):e.collections}});return t.div({className:`modal-content rules-tab`},t.table({className:`rules-table`},t.thead({className:`sticky`},t.tr(null,t.td({colSpan:99,className:`col-rule-btns`},t.div({className:`rule-btns`},()=>n.map(e=>t.button({type:`button`,className:()=>`btn sm ${r.activeRuleOption?.value==e.value?`outline`:`transparent secondary`}`,textContent:()=>e.label,onclick:()=>r.activeRuleOption=e})))))),t.tbody(null,()=>r.activeCollections.length?r.activeCollections.map(e=>t.tr(null,t.th({className:`min-width`},t.div({className:`inline-flex gap-10`},t.i({ariaHidden:!0,className:()=>app.collectionTypes[e.type]?.icon||app.utils.fallbackCollectionIcon}),t.span({className:`txt collection-name`,title:()=>e.name,textContent:()=>e.name}))),()=>{let n;return n=r.activeRuleOption.rule?r.activeRuleOption.rule(e):e[r.activeRuleOption.value],t.td({style:`vertical-align: top`},()=>n===null?r.activeRuleOption.nullLabel?r.activeRuleOption.nullLabel:t.span({className:`label success`},`Superusers only`):n===``?r.activeRuleOption.emptyLabel?r.activeRuleOption.emptyLabel:t.span({className:`label info`},`Public`):app.components.codeBlock({language:`pbrule`,value:n}))})):t.tr(null,t.td({colSpan:99,className:`txt-hint`},t.p(null,`No collections with the selected rule.`))))))}window.app=window.app||{},window.app.oauth2=window.app.oauth2||{},window.app.oauth2.microsoft=function(e,n,r){let i=`microsoft_`+app.utils.randomString();return t.div({pbEvent:`oauth2MicrosoftOptions`,className:`oauth2-microsoft-options`},t.p({className:`txt-bold`},`Azure AD endpoints`),t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.authURL`},`Auth URL`),t.input({id:i+`.authURL`,name:n+`.authURL`,type:`url`,required:!0,value:()=>r.config.authURL||``,oninput:e=>r.config.authURL=e.target.value})),t.div({className:`field-help`},`Ex. https://login.microsoftonline.com/YOUR_DIRECTORY_TENANT_ID/oauth2/v2.0/authorize`)),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.tokenURL`},`Token URL`),t.input({id:i+`.tokenURL`,name:n+`.tokenURL`,type:`url`,required:!0,value:()=>r.config.tokenURL||``,oninput:e=>r.config.tokenURL=e.target.value})),t.div({className:`field-help`},`Ex. https://login.microsoftonline.com/YOUR_DIRECTORY_TENANT_ID/oauth2/v2.0/token`))))},window.app=window.app||{},window.app.oauth2=window.app.oauth2||{},window.app.oauth2.lark=function(e,n,r){let i=`lark_`+app.utils.randomString(),a=[{label:`Feishu (China)`,value:`feishu.cn`},{label:`Lark (International)`,value:`larksuite.com`}],o=store({domain:r.config.authURL?.includes(a[1].value)?a[1].value:a[0].value}),s=[watch(()=>o.domain,e=>{e&&(r.config.authURL=`https://accounts.${e}/open-apis/authen/v1/authorize`,r.config.tokenURL=`https://open.${e}/open-apis/authen/v2/oauth/token`,r.config.userInfoURL=`https://open.${e}/open-apis/authen/v1/user_info`)})];return t.div({pbEvent:`oauth2LarkOptions`,className:`oauth2-lark-options`,onunmount:()=>{s.forEach(e=>e?.unwatch())}},t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.site`},`Site`),app.components.select({options:a,required:!0,value:()=>o.domain||``,onchange:e=>{o.domain=e?.[0]?.value}}))),t.div({className:`col-12`},t.div({className:`alert info`},`Note that the Lark user's `,t.strong(null,`Union ID`),` will be used for the association with the PocketBase user (see `,t.a({href:`https://open.feishu.cn/document/platform-overveiw/basic-concepts/user-identity-introduction/introduction#3f2d4b63`,target:`_blank`,rel:`noopener noreferrer`,textContent:`Different Types of Lark User IDs`}),`).`))))},window.app=window.app||{},window.app.components=window.app.components||{},window.app.components.oauth2EndpointFields=function(e,n,r,i={}){let a=`endpoints_`+app.utils.randomString(),o=store({required:!0,title:`Provider endpoints`}),s=app.utils.extendStore(o,i);return t.div({pbEvent:`oauth2Endpoints`,className:`oauth2-endpoints`,onunmount:()=>{s.forEach(e=>e?.unwatch())}},t.p({className:`txt-bold`},e=>(typeof o.title==`function`&&o.title(e),o.title)),t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:a+`.authURL`},`Auth URL`),t.input({id:a+`.authURL`,name:n+`.authURL`,type:`url`,required:()=>!!o.required,value:()=>r.config.authURL||``,oninput:e=>r.config.authURL=e.target.value}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:a+`.tokenURL`},`Token URL`),t.input({id:a+`.tokenURL`,name:n+`.tokenURL`,type:`url`,required:()=>!!o.required,value:()=>r.config.tokenURL||``,oninput:e=>r.config.tokenURL=e.target.value}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:a+`.userInfoURL`},`User info URL`),t.input({id:a+`.userInfoURL`,name:n+`.userInfoURL`,type:`url`,required:()=>!!o.required,value:()=>r.config.userInfoURL||``,oninput:e=>r.config.userInfoURL=e.target.value})))))},window.app.oauth2=window.app.oauth2||{},window.app.oauth2.gitlab=function(e,n,r){return app.components.oauth2EndpointFields(e,n,r,{required:!1,title:`Self-hosted endpoints (optional)`})},window.app.oauth2.gitea=function(e,n,r){return app.components.oauth2EndpointFields(e,n,r,{required:!1,title:`Self-hosted endpoints (optional)`})},window.app.oauth2.mailcow=function(e,n,r){return app.components.oauth2EndpointFields(e,n,r)},window.app=window.app||{},window.app.oauth2=window.app.oauth2||{},window.app.oauth2.oidc=function(e,n,r){let i=`oidc_`+app.utils.randomString(),a=[{label:`User info URL`,value:!0},{label:`ID Token`,value:!1}],o=store({useUserInfoUrl:!1}),s=[];return t.div({pbEvent:`oauth2OIDCOptions`,className:`oauth2-oidc-options`,onmount:e=>{r.config.displayName===void 0&&(r.config.displayName=`OIDC`),r.config.pkce===void 0&&(r.config.pkce=!0),(r.config.userInfoURL||!r.config.extra)&&(o.useUserInfoUrl=!0),s.push(watch(()=>o.useUserInfoUrl,(e,n)=>{e?r.config.extra=null:(r.config.userInfoURL=``,r.config.extra=r.config.extra||{})}))},onunmount:()=>{s.forEach(e=>e?.unwatch())}},t.div({className:`grid`},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.displayName`},`Display name`),t.input({id:i+`.displayName`,name:n+`.displayName`,type:`text`,required:!0,value:()=>r.config.displayName||``,oninput:e=>r.config.displayName=e.target.value}))),t.div({className:`col-12`},t.p({className:`txt-bold`},`Endpoints`),t.div({className:`field`},t.label({htmlFor:i+`.authURL`},`Auth URL`),t.input({id:i+`.authURL`,name:n+`.authURL`,type:`url`,required:!0,value:()=>r.config.authURL||``,oninput:e=>r.config.authURL=e.target.value}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.tokenURL`},`Token URL`),t.input({id:i+`.tokenURL`,name:n+`.tokenURL`,type:`url`,required:!0,value:()=>r.config.tokenURL||``,oninput:e=>r.config.tokenURL=e.target.value}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.userInfoSelect`},`Fetch user info from`),app.components.select({id:i+`.userInfoSelect`,required:!0,options:a,value:()=>o.useUserInfoUrl,onchange:e=>o.useUserInfoUrl=e?.[0]?.value})),t.div({className:`oidc-userinfo-options m-t-10`},()=>o.useUserInfoUrl?t.div({className:`field`},t.label({htmlFor:i+`.userInfoURL`},`User info URL`),t.input({id:i+`.userInfoURL`,name:n+`.userInfoURL`,type:`url`,required:!0,value:()=>r.config.userInfoURL||``,oninput:e=>r.config.userInfoURL=e.target.value})):t.div({className:`grid sm`},t.div({className:`col-12 txt-hint txt-sm`},t.em(null,`Both fields are considered optional because the parsed `,t.code(null,`id_token`),` is a direct result of the TLS code->token exchange server response.`)),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.extra.jwksURL`},t.span({className:`txt`},`JWKS verification URL`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`URL to the public token verification keys.`)})),t.input({id:i+`.extra.jwksURL`,name:n+`.extra.jwksURL`,type:`url`,value:()=>r.config.extra?.jwksURL||``,oninput:e=>{r.config.extra=r.config.extra||{},r.config.extra.jwksURL=e.target.value}}))),t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:i+`.extra.issuers`},t.span({className:`txt`},`Issuers`),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Comma separated list of accepted values for the iss token claim validation.`)})),t.input({id:i+`.extra.issuers`,name:n+`.extra.issuers`,type:`text`,value:()=>app.utils.joinNonEmpty(r.config.extra?.issuers),oninput:e=>{let n=app.utils.splitNonEmpty(e.target.value,`,`),i=app.utils.joinNonEmpty(n);app.utils.joinNonEmpty(r.config.extra?.issuers)!=i&&(r.config.extra=r.config.extra||{},r.config.extra.issuers=n)}})))))),t.div({className:`col-12`},t.div({className:`field`},t.input({id:i+`.pkce`,name:n+`.pkce`,type:`checkbox`,checked:()=>r.config.pkce||!1,onchange:e=>r.config.pkce=e.target.checked}),t.label({htmlFor:i+`.pkce`},t.span({className:`txt`,textContent:`Support PKCE`}),t.i({className:`ri-information-line link-hint`,ariaDescription:app.attrs.tooltip(`Usually it should be safe to be always enabled as most providers will just ignore the extra query parameters if they don't support PKCE.`)}))))))},window.app=window.app||{},window.app.oauth2=window.app.oauth2||{},window.app.oauth2.apple=function(e,n,r){return``+app.utils.randomString(),t.div({pbEvent:`oauth2AppleOptions`,className:`oauth2-apple-options`},t.button({type:`button`,className:`btn sm secondary`,onclick:()=>{app.modals.openAppleSecretGenerator({ongenerate:e=>{r.config.clientSecret=e}})}},t.i({className:`ri-key-line`,ariaHidden:!0}),t.span({className:`txt`},`Generate secret`)))},window.app.modals=window.app.modals||{},window.app.modals.openAppleSecretGenerator=function(e={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,ongenerate:null}){let n=ur(e);n&&(document.body.appendChild(n),app.modals.open(n))};function ur(e={}){let n,r=`secret_generator_`+app.utils.randomString(),i=15777e3,a=store({clientId:``,teamId:``,keyId:``,privateKey:``,duration:i,isSubmitting:!1});async function o(){a.isSubmitting=!0;try{let r=await app.pb.settings.generateAppleClientSecret(a.clientId,a.teamId,a.keyId,a.privateKey.trim(),a.duration);a.isSubmitting=!1,app.toasts.success(`Successfully generated client secret.`),e.ongenerate?.(r.secret),app.modals.close(n)}catch(e){e.isAbort||(app.checkApiError(e),a.isSubmitting=!1)}}return n=t.div({pbEvent:`appleSecretGeneratorModal`,className:`modal popup apple-secret-generator-modal`,onbeforeopen:n=>e.onbeforeopen?.(n),onafteropen:n=>{e.onafteropen?.(n)},onbeforeclose:n=>e.onbeforeclose?.(n),onafterclose:n=>{e.onafterclose?.(n),n?.remove()}},t.header({className:`modal-header`},t.h5({className:`m-auto`},`Generate Apple client secret`)),t.form({id:r+`_form`,className:`modal-content`,onsubmit:e=>{e.preventDefault(),o()}},t.div({className:`grid`},t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:r+`.clientId`},`Client ID`),t.input({id:r+`.clientId`,name:`clientId`,type:`text`,required:!0,value:()=>a.clientId||``,oninput:e=>a.clientId=e.target.value}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:r+`.teamId`},`Team ID`),t.input({id:r+`.teamId`,name:`teamId`,type:`text`,required:!0,value:()=>a.teamId||``,oninput:e=>a.teamId=e.target.value}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:r+`.keyId`},`Key ID`),t.input({id:r+`.keyId`,name:`keyId`,type:`text`,required:!0,value:()=>a.keyId||``,oninput:e=>a.keyId=e.target.value}))),t.div({className:`col-sm-6`},t.div({className:`field`},t.label({htmlFor:r+`.duration`},`Duration (in seconds)`),t.input({id:r+`.duration`,name:`duration`,type:`number`,min:0,step:1,max:i,required:!0,value:()=>a.duration||0,oninput:e=>a.duration=parseInt(e.target.value,10)})),t.div({className:`field-help`},`Max ${i} seconds (~${i/(3600*24*30)<<0} months).`)),t.div({className:`col-sm-12`},t.div({className:`field`},t.label({htmlFor:r+`.privateKey`},`Private key`),t.textarea({id:r+`.privateKey`,name:`privateKey`,type:`text`,required:!0,rows:8,placeholder:`-----BEGIN PRIVATE KEY----- ... ------END PRIVATE KEY-----`,value:()=>a.privateKey||``,oninput:e=>a.privateKey=e.target.value})),t.div({className:`field-help`},`The key is not stored on the server and it is used only for generating the signed JWT.`)))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n)},t.span({className:`txt`},`Close`)),t.button({"html-form":r+`_form`,type:`submit`,className:`btn expanded`},t.i({className:`ri-key-line`,ariaHidden:!0}),t.span({className:`txt`},`Generate secret`)))),n}function dr(){return t.div({className:`inline-flex gap-5`},t.span(null,`Default log levels:`),()=>{let e=[];for(let n in app.utils.logLevels)e.push(t.code(null,`${n}:${app.utils.logLevels[n].label}`));return e})}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openLogsSettings=function(e={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,onsave:null}){let n=fr(e);n&&(document.body.appendChild(n),app.modals.open(n))};function fr(e){let n,r=store({isLoading:!1,isSaving:!1,formSettings:{},initFormSettingsHash:``,get hasChanges(){return r.initFormSettingsHash!=JSON.stringify(r.formSettings)}});function i(e={}){r.formSettings={logs:e?.logs||{}},r.initFormSettingsHash=JSON.stringify(r.formSettings)}async function a(){r.isLoading=!0;try{i(await app.pb.settings.getAll({requestKey:`logsSettings`})),r.isLoading=!1}catch(e){e.isAbort||(r.isLoading=!1,app.checkApiError(e))}}async function o(){if(r.hasChanges){r.isSaving=!0;try{let a=await app.pb.settings.update(app.utils.filterRedactedProps(r.formSettings));e.onsave?.(a),i(a),app.toasts.success(`Successfully saved logs settings.`),r.isSaving=!1,app.modals.close(n)}catch(e){e.isAbort||(r.isSaving=!1,app.checkApiError(e))}}}return n=t.div({pbEvent:`logsSettingsModal`,className:`modal popup sm logs-settings-modal`,onbeforeopen:n=>(a(),e.onbeforeopen?.(n)),onafteropen:n=>{e.onafteropen?.(n)},onbeforeclose:n=>e.onbeforeclose?.(n),onafterclose:n=>{e.onafterclose?.(n),n?.remove()}},t.header({className:`modal-header`},t.h5({className:`m-auto`},`Logs settings`)),()=>r.isLoading?t.div({className:`modal-content flex`,style:`min-height: 200px`},t.span({className:`loader m-auto`})):[t.form({pbEvent:`logsSettingsForm`,id:`logsSettingsForm`,className:`modal-content logs-settings-form`,onsubmit:e=>{e.preventDefault(),o()}},t.div({className:`grid`},t.div({className:`col-lg-12`},t.field({className:`field`},t.label({htmlFor:`logs.maxDays`},`Max days retention`),t.input({type:`number`,id:`logs.maxDays`,name:`logs.maxDays`,min:0,required:!0,value:()=>r.formSettings.logs.maxDays,oninput:e=>r.formSettings.logs.maxDays=e.target.value<<0})),t.div({className:`field-help`},`Set to `,t.code(null,0),` to disable logs persistence.`)),t.div({className:`col-lg-12`},t.field({className:`field`},t.label({htmlFor:`logs.minLevel`},`Min log level`),t.input({type:`number`,id:`logs.minLevel`,name:`logs.minLevel`,min:-100,max:100,required:!0,value:()=>r.formSettings.logs.minLevel,oninput:e=>r.formSettings.logs.minLevel=e.target.value<<0})),t.div({className:`field-help`},t.div(null,`Logs with level below the minimum will be ignored.`),dr())),t.div({className:`col-lg-12`},t.field({className:`field`},t.input({type:`checkbox`,id:`logs.logIP`,name:`logs.logIP`,className:`switch`,checked:()=>r.formSettings.logs.logIP,onchange:e=>r.formSettings.logs.logIP=e.target.checked}),t.label({htmlFor:`logs.logIP`},`Enable IP logging`))),t.div({className:`col-lg-12`},t.field({className:`field`},t.input({type:`checkbox`,id:`logs.logAuthId`,name:`logs.logAuthId`,className:`switch`,checked:()=>r.formSettings.logs.logAuthId,onchange:e=>r.formSettings.logs.logAuthId=e.target.checked}),t.label({htmlFor:`logs.logAuthId`},`Enable Auth Id logging`))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n),disabled:()=>r.isSaving},t.span({className:`txt`},`Close`)),t.button({type:`submit`,"html-form":`logsSettingsForm`,className:()=>`btn ${r.isSaving?`loading`:``}`,disabled:()=>!r.hasChanges||r.isSaving},t.span({className:`txt`},`Save changes`)))]),n}function pr(e){return t.div({className:()=>`label log-level-label level-${e.level}`},t.span({className:`txt`},()=>`${app.utils.logLevels[e.level]?.label||`UNKN`} (${e.level})`))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openLogPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=_r(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};var mr=[`execTime`,`type`,`auth`,`authId`,`status`,`method`,`url`,`referer`,`remoteIP`,`userIP`,`userAgent`,`error`,`details`];function hr(e){app.utils.downloadJSON(e,`log_`+e.created.replaceAll(/[-:\. ]/gi,``)+`.json`)}function gr(e){app.utils.copyToClipboard(JSON.stringify(e,null,2)),app.toasts.success(`Log copied to clipboard!`)}function _r(e,n){let r,i=store({isLoading:!1,log:null,get isRequest(){return i.log?.data?.type==`request`},get orderedDataKeys(){let e=new Set;if(!i.log?.data)return e;for(let n of mr)i.log.data[n]!==void 0&&e.add(n);for(let n in i.log.data)e.add(n);return e}});async function a(){i.isLoading=!0;try{app.utils.isObject(e)?i.log=JSON.parse(JSON.stringify(e)):i.log=await app.pb.logs.getOne(e,{requestKey:`log_preview`}),i.isLoading=!1}catch(e){e.isAbort||(i.isLoading=!1,app.checkApiError(e))}}return r=t.div({pbEvent:`logPreviewModal`,className:`modal log-preview-modal`,onbeforeopen:e=>(a(),n.onbeforeopen?.(e)),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()}},t.header({className:`modal-header`},t.h5(null,`Log details`),t.button({className:`btn sm circle transparent m-l-auto`,title:`More options`,"html-popovertarget":`log-meta-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:`log-meta-dropdown`,className:`dropdown`,popover:`auto`},e=>t.button({className:`dropdown-item`,onclick:()=>{gr(i.log),e.hidePopover()}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)))),t.div({className:`modal-content`},()=>!i.log||i.isLoading?t.div({className:`block txt-center`},t.span({className:`loader`})):t.table({pbEvent:`logPreviewTable`,className:`log-view-table responsive-table`},t.tbody(null,t.tr(null,t.th({className:`col-field-name-id p-r-0`},`id`),t.td(null,()=>i.log.id),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.id))),t.tr(null,t.th({className:`col-field-name-level p-r-0`},`level`),t.td(null,()=>pr(i.log)),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.level))),t.tr(null,t.th({className:`col-field-name-created p-r-0`},`created`),t.td(null,app.components.formattedDate({value:()=>i.log.created,short:!1})),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.created))),()=>{if(!i.isRequest)return t.tr(null,t.th({className:`col-field-name-message p-r-0`},`message`),t.td(null,()=>app.utils.truncate(i.log.message,1e3)),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.message)))},()=>{let e=[];for(let n of i.orderedDataKeys){let r=i.log.data?.[n];app.utils.logDataFormatters[n]&&(r=app.utils.logDataFormatters[n](i.log));let a=app.utils.isEmpty(r),o=!a&&app.utils.isObject(r);o&&(r=JSON.stringify(r,null,2)),e.push(t.tr({rid:`log_data_`+i.log.id+`_`+n},t.th({className:`min-width p-r-0`},`data.`+n),t.td(null,()=>a?t.span({className:`txt txt-hint`,textContent:`N/A`}):n===`error`?t.span({className:`label danger log-error-label ${o?`txt-code`:``}`,textContent:r}):n==`details`?t.span({className:`label warning log-details-label ${o?`txt-code`:``}`,textContent:r}):o?app.components.codeBlock({value:r}):t.span({className:`txt`,textContent:app.utils.stringifyValue(r,`N/A`,1e3)})),t.td({className:`col-copy min-width`},app.components.copyButton(r))))}return e}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:`btn`,onclick:()=>hr(i.log)},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`Download JSON`)))),r}function vr(e){app.store.title=`Superuser login`;let n=store({authMethods:{},identity:e.query.demoEmail?.[0]||``,password:e.query.demoPassword?.[0]||``,showPassword:!1,otpId:``,lastOTPId:``,otpEmail:``,otpPassword:``,mfaId:``,totalSteps:1,get currentStep(){return 1+!!n.mfaId+!!n.otpId},isAuthMethodsLoading:!0,isPasswordAuthSubmitting:!1,isOTPRequestSubmitting:!1,isOTPAuthSubmitting:!1});async function r(){n.isAuthMethodsLoading=!0;try{n.authMethods=await app.pb.collection(`_superusers`).listAuthMethods(),n.totalSteps=1,n.mfaId=``,n.otpId=``,n.authMethods.mfa?.enabled&&n.authMethods.otp?.enabled&&(n.totalSteps+=2)}catch(e){app.checkApiError(e)}n.isAuthMethodsLoading=!1}return r(),t.div({pbEvent:`pageSuperuserLogin`,className:`wrapper sm m-auto p-b-base`},t.header({className:`txt-center m-b-base`},t.img({className:`main-logo`,src:()=>app.store.mainLogo,ariaHidden:!0,alt:`App logo`}),t.h5({className:`m-t-10`},t.span(null,()=>app.store.title),()=>{if(n.totalSteps>1)return t.span(null,()=>` (${n.currentStep}/${n.totalSteps})`)})),()=>{if(n.isAuthMethodsLoading)return t.div({className:`block txt-center`},t.span({className:`loader lg`}));if(n.authMethods.password?.enabled&&!n.mfaId)return br(n);if(n.authMethods.otp?.enabled)return n.otpId?wr(n):Sr(n)})}async function yr(e){if(!e.isPasswordAuthSubmitting){e.isPasswordAuthSubmitting=!0;try{await app.pb.collection(`_superusers`).authWithPassword(e.identity,e.password),app.toasts.removeAll(),app.store.errors=null,app.utils.toRememberedPath()}catch(n){n.status==401?(e.mfaId=n.response.mfaId,e.authMethods?.password?.identityFields?.length==1&&e.authMethods.password.identityFields[0]==`email`?(e.otpEmail=e.identity,await xr(e)):/^[^@\s]+@[^@\s]+$/.test(e.identity)&&(e.otpEmail=e.identity)):n.status==400?app.toasts.error(`Invalid login credentials.`):app.checkApiError(n)}e.isPasswordAuthSubmitting=!1}}function br(e){return t.form({pbEvent:`authWithPasswordForm`,className:`grid auth-with-password-form`,onsubmit:n=>{n.preventDefault(),yr(e)}},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`login_identity`},()=>app.utils.sentenize(e.authMethods.password.identityFields.join(` or `),!1)),t.input({id:`login_identity`,name:`identity`,type:()=>e.authMethods.password.identityFields.length==1&&e.authMethods.password.identityFields[0]==`email`?`email`:`text`,required:!0,autofocus:!0,value:()=>e.identity,oninput:n=>e.identity=n.target.value}))),t.div({className:`col-12`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:`login_pass`},`Password`),t.input({id:`login_pass`,name:`password`,required:!0,type:()=>e.showPassword?`text`:`password`,value:()=>e.password,oninput:n=>e.password=n.target.value})),t.div({className:`field addon`},t.button({type:`button`,tabIndex:-1,className:`btn sm transparent secondary circle tooltip-right`,ariaLabel:app.attrs.tooltip(()=>e.showPassword?`Hide password`:`Show password`),onclick:()=>e.showPassword=!e.showPassword},t.i({className:()=>e.showPassword?`ri-eye-off-line`:`ri-eye-line`,ariaHidden:!0})))),t.a({href:`#/request-password-reset`,className:`link-hint m-t-5`,onclick:e=>e.stopPropagation()},t.small(null,`Forgotten password`))),t.div({className:`col-12`},t.button({className:()=>`btn lg block next ${e.isPasswordAuthSubmitting?`loading`:``}`,disabled:()=>e.isPasswordAuthSubmitting},t.span({className:`txt`},()=>e.totalSteps>1?`Next`:`Login`),t.i({className:`ri-arrow-right-line`,ariaHidden:!0}))))}async function xr(e){if(!e.isOTPRequestSubmitting){e.isOTPRequestSubmitting=!0;try{e.otpId=(await app.pb.collection(`_superusers`).requestOTP(e.otpEmail)).otpId,e.lastOTPId=e.otpId,app.toasts.removeAll(),app.store.errors=null}catch(n){n.status==429&&(e.otpId=e.lastOTPId),app.checkApiError(n)}e.isOTPRequestSubmitting=!1}}function Sr(e){return t.form({pbEvent:`requestOTPForm`,className:`grid request-otp-form`,onsubmit:n=>{n.preventDefault(),xr(e)}},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`otp_email`},`Email`),t.input({id:`otp_email`,name:`email`,type:`email`,required:!0,autofocus:!0,value:()=>e.otpEmail,oninput:n=>e.otpEmail=n.target.value}))),t.div({className:`col-12`},t.button({className:()=>`btn lg block ${e.isOTPRequestSubmitting?`loading`:``}`,disabled:()=>e.isOTPRequestSubmitting},t.i({className:`ri-mail-send-line`,ariaHidden:!0}),t.span({className:`txt`},`Send OTP`))))}async function Cr(e){if(!e.isOTPAuthSubmitting){e.isOTPAuthSubmitting=!0;try{await app.pb.collection(`_superusers`).authWithOTP(e.otpId||e.lastOTPId,e.otpPassword,{mfaId:e.mfaId}),app.toasts.removeAll(),app.store.errors=null,app.utils.toRememberedPath()}catch(e){app.checkApiError(e)}e.isOTPAuthSubmitting=!1}}function wr(e){return t.form({pbEvent:`authWithOTPForm`,className:`grid auht-with-otp-form`,onsubmit:n=>{n.preventDefault(),Cr(e)}},()=>{if(e.otpEmail)return t.div({className:`col-12`},t.div({className:`content txt-center`},`Check your `,t.strong(null,e.otpEmail),` inbox and enter below the received One-time password (OTP).`))},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`otp_id`},`Id`),t.input({id:`otp_id`,name:`otpId`,type:`text`,required:!0,placeholder:()=>e.lastOTPId,value:()=>e.otpId,onchange:n=>{e.otpId=n.target.value||e.lastOTPId,n.target.value=e.otpId}}))),t.div({className:`col-12`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:`otp_password`},`One-time password`),t.input({id:`otp_password`,name:`password`,required:!0,type:()=>e.showPassword?`text`:`password`,value:()=>e.otpPassword,oninput:n=>e.otpPassword=n.target.value})),t.div({className:`field addon`},t.button({type:`button`,tabIndex:-1,className:`btn sm transparent secondary circle tooltip-right`,ariaLabel:app.attrs.tooltip(()=>e.showPassword?`Hide password`:`Show password`),onclick:()=>e.showPassword=!e.showPassword},t.i({className:()=>e.showPassword?`ri-eye-off-line`:`ri-eye-line`}))))),t.div({className:`col-12`},t.button({className:()=>`btn lg block next ${e.isOTPAuthSubmitting?`loading`:``}`,disabled:()=>e.isOTPAuthSubmitting},t.span({className:`txt`},`Login`),t.i({className:`ri-arrow-right-line`,ariaHidden:!0})),t.div({className:`block m-t-sm txt-center`},t.button({type:`button`,className:`link-hint txt-sm`,disabled:()=>e.isOTPAuthSubmitting,onclick:()=>{e.otpId=``,e.otpPassword=``}},`Request another OTP`))))}var Tr=`pbPinnedCollections`,Er=12;function Dr(){let e=store({search:``,pinned:app.utils.getLocalHistory(Tr,[]),get filteredCollections(){if(!e.search.length)return app.store.collections;let n=e.search.replaceAll(` `,``).toLowerCase();return app.store.collections.filter(e=>(e.name+e.id+e.type).toLowerCase().includes(n))},get systemCollections(){return e.filteredCollections.filter(n=>n.system&&!e.pinned.includes(n.id))},get regularCollections(){return e.filteredCollections.filter(n=>!n.system&&!e.pinned.includes(n.id))},get pinnedCollections(){return e.pinned.length?e.filteredCollections.filter(n=>e.pinned.includes(n.id)):[]}});function n(){e.search=``}let r=[];return app.components.pageSidebar({className:()=>`collections-sidebar ${e.responsiveShow?`active`:``}`,onmount:n=>{r.push(watch(()=>{app.utils.saveLocalHistory(Tr,JSON.stringify(e.pinned))})),r.push(watch(()=>app.store.activeCollection?.id,async()=>{await new Promise(e=>setTimeout(e,0));let e=n?.querySelector(`.nav-item.active`),r=e?.closest(`details`);r&&(r.open=!0,e?.scrollIntoView({block:`nearest`}))}))},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.div({className:`sidebar-search`},t.div({className:`fields`},t.div({className:`field`},t.input({className:`p-r-5`,type:`text`,placeholder:`Search collections...`,value:()=>e.search,oninput:n=>e.search=n.target.value})),t.div({className:`field addon p-l-0 p-r-5 gap-0`},t.button({hidden:()=>!e.search.length,type:`button`,className:`btn sm circle transparent secondary`,ariaDescription:app.attrs.tooltip(`Clear`,`left`),onclick:n},t.i({className:`ri-close-line`,ariaHidden:!0})),t.button({type:`button`,disabled:()=>app.store.isLoadingCollections,className:()=>`btn sm circle transparent secondary link-faded ${app.store.isLoadingCollections?`loading`:``}`,ariaDescription:app.attrs.tooltip(`Collections overview`,`left`),onclick:()=>app.modals.openCollectionsOverview()},t.i({className:`ri-organization-chart`,ariaHidden:!0}))))),()=>{if(!(!e.search.length||e.filteredCollections.length||app.store.isLoadingCollections))return t.div({className:`block p-t-base txt-center txt-hint`},t.p(null,`No collections found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,onclick:()=>n()}))},()=>{if(app.store.isLoadingCollections&&!e.filteredCollections.length)return t.div({className:`sidebar-content txt-center`},t.span({className:`loader sm`}))},()=>[t.nav({className:()=>`sidebar-content collections-list scrollable ${e.regularCollections.length+e.pinnedCollections>=Er?`compact`:``}`},t.details({hidden:()=>!e.pinnedCollections.length,className:()=>`nav-group nav-group-pinned-collections`,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},`Pinned`),()=>e.pinnedCollections.map(n=>Or(n,e))),t.details({hidden:()=>!e.regularCollections.length,className:`nav-group nav-group-regular-collections`,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},()=>e.pinnedCollections.length?`Others`:`Collections`),()=>e.regularCollections.map(n=>Or(n,e))),t.details({hidden:()=>!e.systemCollections.length,className:`nav-group nav-group-system-collections`,open:()=>e.search.length},t.summary(null,`System`),()=>e.systemCollections.map(n=>Or(n,e)))),t.div({hidden:()=>e.search.length&&!e.filteredCollections.length,className:`sidebar-content new-collection`},t.button({type:`button`,className:`btn outline block`,onclick:()=>{app.modals.openCollectionUpsert({},{onsave:e=>{app.store.activeCollection=e.id}})}},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({textContent:`New collection`})))])}function Or(e,n){return t.button({"html-data-collection-id":()=>e.id,type:`button`,className:()=>`nav-item responsive-close ${e.id==app.store.activeCollection?.id?`active`:``}`,title:()=>e.name,onauxclick:n=>{n.preventDefault(),window.open(`#/collections?collection=${e.name}`,`_blank`,`noreferrer,noopener`)},onclick:n=>{n.preventDefault(),app.store.activeCollection=e.name}},t.i({className:()=>app.collectionTypes[e.type]?.icon||app.utils.fallbackCollectionIcon,ariaHidden:!0}),t.span({className:`txt`},()=>e.name),()=>{if(!(e.type!=`auth`||!e.oauth2?.enabled||e.oauth2?.providers?.length>0))return t.i({ariaHidden:!0,className:`ri-alert-line txt-hint txt-sm`,ariaDescription:app.attrs.tooltip(`OAuth2 auth is enabled but the collection doesn't have any registered providers`)})},()=>{let r=n.pinned.indexOf(e.id);return t.span({tabIndex:-1,role:`button`,className:`pin`,title:()=>r>=0?`Unpin`:`Pin`,onclick:i=>{i.preventDefault(),i.stopPropagation(),r>=0?n.pinned.splice(r,1):n.pinned.push(e.id)}},t.i({ariaHidden:!1,className:()=>r>=0?`ri-unpin-line`:`ri-pushpin-line`}))})}var kr=`sort`,$=`filter`,Ar=`collection`,jr=`record`,Mr=`pbLastActiveCollection`,Nr=`recordsTotalCountRequest`;function Pr(e){app.store.activeCollection=e.query[Ar]?.[0]||window.localStorage.getItem(Mr);let n=store({reset:null,activeRecordIdOrModel:e.query[jr]?.[0]||``,sort:e.query[kr]?.[0]||``,filter:e.query[$]?.[0]||``,totalCount:0,isTotalCountLoading:!1});async function r(){if(app.store.activeCollection?.id){n.isTotalCountLoading=!0;try{let e=app.utils.normalizeSearchFilter(n.filter,app.store.activeCollection.fields.filter(e=>!e.hidden).map(e=>e.name));n.totalCount=(await app.pb.collection(app.store.activeCollection.name).getList(1,1,{requestKey:Nr,filter:e,fields:`id`})).totalItems}catch(e){e.isAbort||(n.totalCount=0,console.warn(`failed to load total count:`,e))}n.isTotalCountLoading=!1}}function i(){n.reset=Date.now()}let a=[watch(()=>(app.store.activeCollection?.name||``)+(app.store.activeCollection?.updated||``),(e,r)=>{app.store.title=app.store.activeCollection?.name||`Collections`,r&&(r!=e&&(n.filter=``,n.sort=``),app.utils.replaceHashQueryParams({[Ar]:app.store.activeCollection?.name,[$]:n.filter||null,[kr]:n.sort||null},e==r?null:!0),app.store.activeCollection?.id?window.localStorage.setItem(Mr,app.store.activeCollection.id):window.localStorage.removeItem(Mr))}),watch(()=>[n.filter,n.sort],(e,r)=>{r&&app.utils.replaceHashQueryParams({[$]:n.filter||null,[kr]:n.sort||null})}),watch(()=>(n.activeRecordIdOrModel||``)+(app.store.activeCollection?.id||``),(e,r)=>{if(!n.activeRecordIdOrModel){app.utils.replaceHashQueryParams({[jr]:null});return}if(e==r||!app.store.activeCollection?.id)return;let i=typeof n.activeRecordIdOrModel==`string`?{id:n.activeRecordIdOrModel,collectionId:app.store.activeCollection?.id,collectionName:app.store.activeCollection?.name}:n.activeRecordIdOrModel;app.utils.replaceHashQueryParams({[jr]:i.id||null}),app.modals.close(null,!0),app.store.activeCollection?.type==`view`?app.modals.openRecordPreview(i,{onafterclose:()=>{n.activeRecordIdOrModel=``}}):app.modals.openRecordUpsert(app.store.activeCollection,i,{onafterclose:()=>{n.activeRecordIdOrModel=``}})}),watch(()=>[app.store.activeCollection?.id,n.filter,n.reset],()=>r())],o={"record:save":e=>{e.detail.collectionId==app.store.activeCollection?.id&&n.totalCount++},"record:delete":e=>{e.detail.collectionId!=app.store.activeCollection?.id&&e.detail.collectionName!=app.store.activeCollection?.name||n.totalCount--}};return t.div({pbEvent:`pageCollections`,className:`page`,onmount:()=>{app.store.isLoadingCollections||app.store.silentlyReloadCollections();for(let e in o)document.addEventListener(e,o[e])},onunmount:()=>{app.pb.cancelRequest(Nr),a.forEach(e=>e?.unwatch());for(let e in o)document.removeEventListener(e,o[e])}},()=>Dr(),t.div({className:`page-content full-height`},t.header({className:`page-header compact flex-nowrap`},t.nav({className:`breadcrumbs`},t.div(null,`Collections`),()=>{if(app.store.activeCollection?.name)return t.div({title:app.store.activeCollection.name,textContent:app.store.activeCollection.name})}),t.div({hidden:()=>!app.store.activeCollection?.id,pbEvent:`pageHeaderSecondaryBtns`,className:`page-header-secondary-btns`},t.button({type:`button`,className:`btn circle transparent secondary tooltip-bottom btn-collection-settings`,ariaLabel:app.attrs.tooltip(`Collection settings`),onclick:()=>{app.modals.openCollectionUpsert(app.store.activeCollection,{ontruncate:()=>i(),onsave:(e,n)=>{n?app.store.activeCollection=e.id:i()}})}},t.i({className:`ri-settings-3-line`,ariaHidden:!0})),app.components.refreshButton({onclick:()=>i()})),t.div({hidden:()=>!app.store.activeCollection?.id,pbEvent:`pageHeaderPrimaryBtns`,className:`page-header-primary-btns`},t.button({type:`button`,className:`btn outline api-preview-btn`,onclick:()=>app.modals.openApiPreview(app.store.activeCollection)},t.i({className:`ri-code-s-slash-line`,ariaHidden:!0}),t.span({className:`txt`,textContent:`API preview`})),()=>{if(app.store.activeCollection?.type!=`view`)return t.button({type:`button`,className:`btn new-record-btn`,onclick:()=>app.modals.openRecordUpsert(app.store.activeCollection)},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({className:`txt`,textContent:`New Record`}))})),t.div({hidden:()=>!app.store.isLoadingCollections||app.store.activeCollection?.id,className:`block txt-center p-base`},t.span({className:`loader lg`})),t.div({hidden:()=>app.store.isLoadingCollections||app.store.activeCollection?.id,className:`block txt-center p-base`},t.h6({className:`txt`},()=>app.store.collections?.length?`Select collection from the sidebar.`:`No collections found.`)),app.components.recordsSearchbar({hidden:()=>!app.store.activeCollection?.id,collection:()=>app.store.activeCollection,value:()=>n.filter,onsubmit:e=>n.filter=e}),app.components.recordsList({className:`m-t-sm`,reset:()=>n.reset,hidden:()=>!app.store.activeCollection?.id,collection:()=>app.store.activeCollection,filter:()=>n.filter,sort:()=>n.sort,onselect:e=>{n.activeRecordIdOrModel=e},onchange:(e,r)=>{n.filter=e,n.sort=r}}),t.footer({className:`page-footer`},t.span({className:()=>`total-count ${n.isTotalCountLoading?`faded`:``}`},`Total: `,()=>n.totalCount),app.components.credits())))}function Fr(){return document.body.clientWidth>600&&document.body.clientHeight>=720?150:100}function Ir(e){let n=store({stats:[]});async function r(r){if(r){e.isChartLoading=!0;try{let i=(e.presets||[]).concat(app.utils.normalizeSearchFilter(e.filter,[`level`,`message`,`data`])),a=await app.pb.logs.getStats({filter:i.filter(Boolean).map(e=>`(`+e+`)`).join(`&&`)}),o=a.length,s=[],c=[];e.totalFound=0;for(let n=0;n3600&&(s.push(r+3600),c.push(0)):n+1==o&&(s.push(r+3600),c.push(0))}n.stats=a,e.isChartLoading=!1,Rr(r,[s,c],e)}catch(n){n?.isAbort||(e.isChartLoading=!1,console.warn(`failed to load logs chart:`,n))}}}let i=[];return t.div({pbEvent:`logsChart`,className:()=>[`logs-chart`,e.isChartLoading?`loading`:null,e.zoom?.min&&e.zoom?.max?`zoomed`:``,!n.stats.length||!e.isFirstLoadReady?`nodata`:null].filter(Boolean).join(` `),onmount:n=>{i.push(watch(()=>[e.reset,e.filter,e.presets?.length],()=>r(n))),n._resizeChartFunc=()=>{clearTimeout(n._resizeTimeoutId),n._resizeTimeoutId=setTimeout(()=>{n?._uplot&&n._uplot.setSize({width:n.clientWidth,height:Fr()})},100)},window.addEventListener(`resize`,n._resizeChartFunc)},onunmount:e=>{i.forEach(e=>e?.unwatch()),e._uplot?.destroy(),e._resizeChartFunc&&(clearTimeout(e._resizeTimeoutId),window.removeEventListener(`resize`,e._resizeChartFunc),e._resizeChartFunc=null,e._resizeTimeoutId=null)}},t.button({type:`button`,className:()=>`logs-reset-zoom-ctrl ${e.zoom?.min&&e.zoom?.max?``:`hidden`}`,onclick(){e.zoom={}}},t.div({className:`content-primary`},`Reset zoom`),t.div({className:`content-secondary`},`(drag the timeline to pan)`)),t.span({hidden:()=>!e.isChartLoading,className:()=>`loader logs-chart-loader`}))}function Lr(e){let n=e?.data?.[0];n&&e.setScale(`x`,{min:n[0],max:n[n.length-1]})}function Rr(e,n,r){let i=window.getComputedStyle(e),a=i.getPropertyValue(`--surfaceTxtHintColor`),o=i.getPropertyValue(`--surfaceAlt1Color`),s=i.getPropertyValue(`--surfaceAlt4Color`),c=i.getPropertyValue(`--surfaceAlt2Color`),l={width:e.clientWidth,height:Fr(),legend:{show:!1},cursor:{x:!1,y:!1},scales:{x:{range:(e,r,i)=>rn[0][n[0].length-1]?[e.scales.x.min,e.scales.x.max]:[r,i]},y:{range:{min:{pad:.2,soft:0,mode:1},max:{pad:.2,soft:0,mode:2}}}},series:[{},{paths:uPlot.paths.stepped({align:1}),points:{show:!1,size:1},width:2,fill:c,stroke:s}],axes:[{show:!0,size:35,lineGap:1,space:60,stroke:a,incrs:[300,600,900,1800,3600,3600*2,3600*3,3600*4,3600*6,3600*12,86400,86400*2],values:[[3600,`{h}{aa}`,` +-----END PRIVATE KEY-----`,value:()=>a.privateKey||``,oninput:e=>a.privateKey=e.target.value})),t.div({className:`field-help`},`The key is not stored on the server and it is used only for generating the signed JWT.`)))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n)},t.span({className:`txt`},`Close`)),t.button({"html-form":r+`_form`,type:`submit`,className:`btn expanded`},t.i({className:`ri-key-line`,ariaHidden:!0}),t.span({className:`txt`},`Generate secret`)))),n}function dr(){return t.div({className:`inline-flex gap-5`},t.span(null,`Default log levels:`),()=>{let e=[];for(let n in app.utils.logLevels)e.push(t.code(null,`${n}:${app.utils.logLevels[n].label}`));return e})}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openLogsSettings=function(e={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null,onsave:null}){let n=fr(e);n&&(document.body.appendChild(n),app.modals.open(n))};function fr(e){let n,r=store({isLoading:!1,isSaving:!1,formSettings:{},initFormSettingsHash:``,get hasChanges(){return r.initFormSettingsHash!=JSON.stringify(r.formSettings)}});function i(e={}){r.formSettings={logs:e?.logs||{}},r.initFormSettingsHash=JSON.stringify(r.formSettings)}async function a(){r.isLoading=!0;try{i(await app.pb.settings.getAll({requestKey:`logsSettings`})),r.isLoading=!1}catch(e){e.isAbort||(r.isLoading=!1,app.checkApiError(e))}}async function o(){if(r.hasChanges){r.isSaving=!0;try{let a=await app.pb.settings.update(app.utils.filterRedactedProps(r.formSettings));e.onsave?.(a),i(a),app.toasts.success(`Successfully saved logs settings.`),r.isSaving=!1,app.modals.close(n)}catch(e){e.isAbort||(r.isSaving=!1,app.checkApiError(e))}}}return n=t.div({pbEvent:`logsSettingsModal`,className:`modal popup sm logs-settings-modal`,onbeforeopen:n=>(a(),e.onbeforeopen?.(n)),onafteropen:n=>{e.onafteropen?.(n)},onbeforeclose:n=>e.onbeforeclose?.(n),onafterclose:n=>{e.onafterclose?.(n),n?.remove()}},t.header({className:`modal-header`},t.h5({className:`m-auto`},`Logs settings`)),()=>r.isLoading?t.div({className:`modal-content flex`,style:`min-height: 200px`},t.span({className:`loader m-auto`})):[t.form({pbEvent:`logsSettingsForm`,id:`logsSettingsForm`,className:`modal-content logs-settings-form`,onsubmit:e=>{e.preventDefault(),o()}},t.div({className:`grid`},t.div({className:`col-lg-12`},t.field({className:`field`},t.label({htmlFor:`logs.maxDays`},`Max days retention`),t.input({type:`number`,id:`logs.maxDays`,name:`logs.maxDays`,min:0,required:!0,value:()=>r.formSettings.logs.maxDays,oninput:e=>r.formSettings.logs.maxDays=e.target.value<<0})),t.div({className:`field-help`},`Set to `,t.code(null,0),` to disable logs persistence.`)),t.div({className:`col-lg-12`},t.field({className:`field`},t.label({htmlFor:`logs.minLevel`},`Min log level`),t.input({type:`number`,id:`logs.minLevel`,name:`logs.minLevel`,min:-100,max:100,required:!0,value:()=>r.formSettings.logs.minLevel,oninput:e=>r.formSettings.logs.minLevel=e.target.value<<0})),t.div({className:`field-help`},t.div(null,`Logs with level below the minimum will be ignored.`),dr())),t.div({className:`col-lg-12`},t.field({className:`field`},t.input({type:`checkbox`,id:`logs.logIP`,name:`logs.logIP`,className:`switch`,checked:()=>r.formSettings.logs.logIP,onchange:e=>r.formSettings.logs.logIP=e.target.checked}),t.label({htmlFor:`logs.logIP`},`Enable IP logging`))),t.div({className:`col-lg-12`},t.field({className:`field`},t.input({type:`checkbox`,id:`logs.logAuthId`,name:`logs.logAuthId`,className:`switch`,checked:()=>r.formSettings.logs.logAuthId,onchange:e=>r.formSettings.logs.logAuthId=e.target.checked}),t.label({htmlFor:`logs.logAuthId`},`Enable Auth Id logging`))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(n),disabled:()=>r.isSaving},t.span({className:`txt`},`Close`)),t.button({type:`submit`,"html-form":`logsSettingsForm`,className:()=>`btn ${r.isSaving?`loading`:``}`,disabled:()=>!r.hasChanges||r.isSaving},t.span({className:`txt`},`Save changes`)))]),n}function pr(e){return t.div({className:()=>`label log-level-label level-${e.level}`},t.span({className:`txt`},()=>`${app.utils.logLevels[e.level]?.label||`UNKN`} (${e.level})`))}window.app=window.app||{},window.app.modals=window.app.modals||{},window.app.modals.openLogPreview=function(e,n={onbeforeopen:null,onafteropen:null,onbeforeclose:null,onafterclose:null}){let r=_r(e,n);r&&(document.body.appendChild(r),app.modals.open(r))};var mr=[`execTime`,`type`,`auth`,`authId`,`status`,`method`,`url`,`referer`,`remoteIP`,`userIP`,`userAgent`,`error`,`details`];function hr(e){app.utils.downloadJSON(e,`log_`+e.created.replaceAll(/[-:\. ]/gi,``)+`.json`)}function gr(e){app.utils.copyToClipboard(JSON.stringify(e,null,2)),app.toasts.success(`Log copied to clipboard!`)}function _r(e,n){let r,i=store({isLoading:!1,log:null,get isRequest(){return i.log?.data?.type==`request`},get orderedDataKeys(){let e=new Set;if(!i.log?.data)return e;for(let n of mr)i.log.data[n]!==void 0&&e.add(n);for(let n in i.log.data)e.add(n);return e}});async function a(){i.isLoading=!0;try{app.utils.isObject(e)?i.log=JSON.parse(JSON.stringify(e)):i.log=await app.pb.logs.getOne(e,{requestKey:`log_preview`}),i.isLoading=!1}catch(e){e.isAbort||(i.isLoading=!1,app.checkApiError(e))}}return r=t.div({pbEvent:`logPreviewModal`,className:`modal log-preview-modal`,onbeforeopen:e=>(a(),n.onbeforeopen?.(e)),onafteropen:e=>{n.onafteropen?.(e)},onbeforeclose:e=>n.onbeforeclose?.(e),onafterclose:e=>{n.onafterclose?.(e),e?.remove()}},t.header({className:`modal-header`},t.h5(null,`Log details`),t.button({className:`btn sm circle transparent m-l-auto`,title:`More options`,"html-popovertarget":`log-meta-dropdown`},t.i({className:`ri-more-line`,ariaHidden:!0})),t.div({id:`log-meta-dropdown`,className:`dropdown`,popover:`auto`},e=>t.button({className:`dropdown-item`,onclick:()=>{gr(i.log),e.hidePopover()}},t.i({className:`ri-braces-line`,ariaHidden:!0}),t.span({className:`txt`},`Copy JSON`)))),t.div({className:`modal-content`},()=>!i.log||i.isLoading?t.div({className:`block txt-center`},t.span({className:`loader`})):t.table({pbEvent:`logPreviewTable`,className:`log-view-table responsive-table`},t.tbody(null,t.tr(null,t.th({className:`col-field-name-id p-r-0`},`id`),t.td(null,()=>i.log.id),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.id))),t.tr(null,t.th({className:`col-field-name-level p-r-0`},`level`),t.td(null,()=>pr(i.log)),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.level))),t.tr(null,t.th({className:`col-field-name-created p-r-0`},`created`),t.td(null,app.components.formattedDate({value:()=>i.log.created,short:!1})),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.created))),()=>{if(!i.isRequest)return t.tr(null,t.th({className:`col-field-name-message p-r-0`},`message`),t.td(null,()=>app.utils.truncate(i.log.message,1e3)),t.td({className:`col-copy min-width`},app.components.copyButton(i.log.message)))},()=>{let e=[];for(let n of i.orderedDataKeys){let r=i.log.data?.[n];app.utils.logDataFormatters[n]&&(r=app.utils.logDataFormatters[n](i.log));let a=app.utils.isEmpty(r),o=!a&&app.utils.isObject(r);o&&(r=JSON.stringify(r,null,2)),e.push(t.tr({rid:`log_data_`+i.log.id+`_`+n},t.th({className:`min-width p-r-0`},`data.`+n),t.td(null,()=>a?t.span({className:`txt txt-hint`,textContent:`N/A`}):n===`error`?t.span({className:`label danger log-error-label ${o?`txt-code`:``}`,textContent:r}):n==`details`?t.span({className:`label warning log-details-label ${o?`txt-code`:``}`,textContent:r}):o?app.components.codeBlock({value:r}):t.span({className:`txt`,textContent:app.utils.displayValue(r,1e3)})),t.td({className:`col-copy min-width`},app.components.copyButton(r))))}return e}))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close(r)},t.span({className:`txt`},`Close`)),t.button({type:`button`,className:`btn`,onclick:()=>hr(i.log)},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`Download JSON`)))),r}function vr(e){app.store.title=`Superuser login`;let n=store({authMethods:{},identity:e.query.demoEmail?.[0]||``,password:e.query.demoPassword?.[0]||``,showPassword:!1,otpId:``,lastOTPId:``,otpEmail:``,otpPassword:``,mfaId:``,totalSteps:1,get currentStep(){return 1+!!n.mfaId+!!n.otpId},isAuthMethodsLoading:!0,isPasswordAuthSubmitting:!1,isOTPRequestSubmitting:!1,isOTPAuthSubmitting:!1});async function r(){n.isAuthMethodsLoading=!0;try{n.authMethods=await app.pb.collection(`_superusers`).listAuthMethods(),n.totalSteps=1,n.mfaId=``,n.otpId=``,n.authMethods.mfa?.enabled&&n.authMethods.otp?.enabled&&(n.totalSteps+=2)}catch(e){app.checkApiError(e)}n.isAuthMethodsLoading=!1}return r(),t.div({pbEvent:`pageSuperuserLogin`,className:`wrapper sm m-auto p-b-base`},t.header({className:`txt-center m-b-base`},t.img({className:`main-logo`,src:()=>app.store.mainLogo,ariaHidden:!0,alt:`App logo`}),t.h5({className:`m-t-10`},t.span(null,()=>app.store.title),()=>{if(n.totalSteps>1)return t.span(null,()=>` (${n.currentStep}/${n.totalSteps})`)})),()=>{if(n.isAuthMethodsLoading)return t.div({className:`block txt-center`},t.span({className:`loader lg`}));if(n.authMethods.password?.enabled&&!n.mfaId)return br(n);if(n.authMethods.otp?.enabled)return n.otpId?wr(n):Sr(n)})}async function yr(e){if(!e.isPasswordAuthSubmitting){e.isPasswordAuthSubmitting=!0;try{await app.pb.collection(`_superusers`).authWithPassword(e.identity,e.password),app.toasts.removeAll(),app.store.errors=null,app.utils.toRememberedPath()}catch(n){n.status==401?(e.mfaId=n.response.mfaId,e.authMethods?.password?.identityFields?.length==1&&e.authMethods.password.identityFields[0]==`email`?(e.otpEmail=e.identity,await xr(e)):/^[^@\s]+@[^@\s]+$/.test(e.identity)&&(e.otpEmail=e.identity)):n.status==400?app.toasts.error(`Invalid login credentials.`):app.checkApiError(n)}e.isPasswordAuthSubmitting=!1}}function br(e){return t.form({pbEvent:`authWithPasswordForm`,className:`grid auth-with-password-form`,onsubmit:n=>{n.preventDefault(),yr(e)}},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`login_identity`},()=>app.utils.sentenize(e.authMethods.password.identityFields.join(` or `),!1)),t.input({id:`login_identity`,name:`identity`,type:()=>e.authMethods.password.identityFields.length==1&&e.authMethods.password.identityFields[0]==`email`?`email`:`text`,required:!0,autofocus:!0,value:()=>e.identity,oninput:n=>e.identity=n.target.value}))),t.div({className:`col-12`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:`login_pass`},`Password`),t.input({id:`login_pass`,name:`password`,required:!0,type:()=>e.showPassword?`text`:`password`,value:()=>e.password,oninput:n=>e.password=n.target.value})),t.div({className:`field addon`},t.button({type:`button`,tabIndex:-1,className:`btn sm transparent secondary circle tooltip-right`,ariaLabel:app.attrs.tooltip(()=>e.showPassword?`Hide password`:`Show password`),onclick:()=>e.showPassword=!e.showPassword},t.i({className:()=>e.showPassword?`ri-eye-off-line`:`ri-eye-line`,ariaHidden:!0})))),t.a({href:`#/request-password-reset`,className:`link-hint m-t-5`,onclick:e=>e.stopPropagation()},t.small(null,`Forgotten password`))),t.div({className:`col-12`},t.button({className:()=>`btn lg block next ${e.isPasswordAuthSubmitting?`loading`:``}`,disabled:()=>e.isPasswordAuthSubmitting},t.span({className:`txt`},()=>e.totalSteps>1?`Next`:`Login`),t.i({className:`ri-arrow-right-line`,ariaHidden:!0}))))}async function xr(e){if(!e.isOTPRequestSubmitting){e.isOTPRequestSubmitting=!0;try{e.otpId=(await app.pb.collection(`_superusers`).requestOTP(e.otpEmail)).otpId,e.lastOTPId=e.otpId,app.toasts.removeAll(),app.store.errors=null}catch(n){n.status==429&&(e.otpId=e.lastOTPId),app.checkApiError(n)}e.isOTPRequestSubmitting=!1}}function Sr(e){return t.form({pbEvent:`requestOTPForm`,className:`grid request-otp-form`,onsubmit:n=>{n.preventDefault(),xr(e)}},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`otp_email`},`Email`),t.input({id:`otp_email`,name:`email`,type:`email`,required:!0,autofocus:!0,value:()=>e.otpEmail,oninput:n=>e.otpEmail=n.target.value}))),t.div({className:`col-12`},t.button({className:()=>`btn lg block ${e.isOTPRequestSubmitting?`loading`:``}`,disabled:()=>e.isOTPRequestSubmitting},t.i({className:`ri-mail-send-line`,ariaHidden:!0}),t.span({className:`txt`},`Send OTP`))))}async function Cr(e){if(!e.isOTPAuthSubmitting){e.isOTPAuthSubmitting=!0;try{await app.pb.collection(`_superusers`).authWithOTP(e.otpId||e.lastOTPId,e.otpPassword,{mfaId:e.mfaId}),app.toasts.removeAll(),app.store.errors=null,app.utils.toRememberedPath()}catch(e){app.checkApiError(e)}e.isOTPAuthSubmitting=!1}}function wr(e){return t.form({pbEvent:`authWithOTPForm`,className:`grid auht-with-otp-form`,onsubmit:n=>{n.preventDefault(),Cr(e)}},()=>{if(e.otpEmail)return t.div({className:`col-12`},t.div({className:`content txt-center`},`Check your `,t.strong(null,e.otpEmail),` inbox and enter below the received One-time password (OTP).`))},t.div({className:`col-12`},t.div({className:`field`},t.label({htmlFor:`otp_id`},`Id`),t.input({id:`otp_id`,name:`otpId`,type:`text`,required:!0,placeholder:()=>e.lastOTPId,value:()=>e.otpId,onchange:n=>{e.otpId=n.target.value||e.lastOTPId,n.target.value=e.otpId}}))),t.div({className:`col-12`},t.div({className:`fields`},t.div({className:`field`},t.label({htmlFor:`otp_password`},`One-time password`),t.input({id:`otp_password`,name:`password`,required:!0,type:()=>e.showPassword?`text`:`password`,value:()=>e.otpPassword,oninput:n=>e.otpPassword=n.target.value})),t.div({className:`field addon`},t.button({type:`button`,tabIndex:-1,className:`btn sm transparent secondary circle tooltip-right`,ariaLabel:app.attrs.tooltip(()=>e.showPassword?`Hide password`:`Show password`),onclick:()=>e.showPassword=!e.showPassword},t.i({className:()=>e.showPassword?`ri-eye-off-line`:`ri-eye-line`}))))),t.div({className:`col-12`},t.button({className:()=>`btn lg block next ${e.isOTPAuthSubmitting?`loading`:``}`,disabled:()=>e.isOTPAuthSubmitting},t.span({className:`txt`},`Login`),t.i({className:`ri-arrow-right-line`,ariaHidden:!0})),t.div({className:`block m-t-sm txt-center`},t.button({type:`button`,className:`link-hint txt-sm`,disabled:()=>e.isOTPAuthSubmitting,onclick:()=>{e.otpId=``,e.otpPassword=``}},`Request another OTP`))))}var Tr=`pbPinnedCollections`,Er=12;function Dr(){let e=store({search:``,pinned:app.utils.getLocalHistory(Tr,[]),get filteredCollections(){if(!e.search.length)return app.store.collections;let n=e.search.replaceAll(` `,``).toLowerCase();return app.store.collections.filter(e=>(e.name+e.id+e.type).toLowerCase().includes(n))},get systemCollections(){return e.filteredCollections.filter(n=>n.system&&!e.pinned.includes(n.id))},get regularCollections(){return e.filteredCollections.filter(n=>!n.system&&!e.pinned.includes(n.id))},get pinnedCollections(){return e.pinned.length?e.filteredCollections.filter(n=>e.pinned.includes(n.id)):[]}});function n(){e.search=``}let r=[];return app.components.pageSidebar({className:()=>`collections-sidebar ${e.responsiveShow?`active`:``}`,onmount:n=>{r.push(watch(()=>{app.utils.saveLocalHistory(Tr,JSON.stringify(e.pinned))})),r.push(watch(()=>app.store.activeCollection?.id,async()=>{await new Promise(e=>setTimeout(e,0));let e=n?.querySelector(`.nav-item.active`),r=e?.closest(`details`);r&&(r.open=!0,e?.scrollIntoView({block:`nearest`}))}))},onunmount:()=>{r.forEach(e=>e?.unwatch())}},t.div({className:`sidebar-search`},t.div({className:`fields`},t.div({className:`field`},t.input({className:`p-r-5`,type:`text`,placeholder:`Search collections...`,value:()=>e.search,oninput:n=>e.search=n.target.value})),t.div({className:`field addon p-l-0 p-r-5 gap-0`},t.button({hidden:()=>!e.search.length,type:`button`,className:`btn sm circle transparent secondary`,ariaDescription:app.attrs.tooltip(`Clear`,`left`),onclick:n},t.i({className:`ri-close-line`,ariaHidden:!0})),t.button({type:`button`,disabled:()=>app.store.isLoadingCollections,className:()=>`btn sm circle transparent secondary link-faded ${app.store.isLoadingCollections?`loading`:``}`,ariaDescription:app.attrs.tooltip(`Collections overview`,`left`),onclick:()=>app.modals.openCollectionsOverview()},t.i({className:`ri-organization-chart`,ariaHidden:!0}))))),()=>{if(!(!e.search.length||e.filteredCollections.length||app.store.isLoadingCollections))return t.div({className:`block p-t-base txt-center txt-hint`},t.p(null,`No collections found.`),t.button({type:`button`,className:`btn sm secondary`,textContent:`Clear search`,onclick:()=>n()}))},()=>{if(app.store.isLoadingCollections&&!e.filteredCollections.length)return t.div({className:`sidebar-content txt-center`},t.span({className:`loader sm`}))},()=>[t.nav({className:()=>`sidebar-content collections-list scrollable ${e.regularCollections.length+e.pinnedCollections>=Er?`compact`:``}`},t.details({hidden:()=>!e.pinnedCollections.length,className:()=>`nav-group nav-group-pinned-collections`,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},`Pinned`),()=>e.pinnedCollections.map(n=>Or(n,e))),t.details({hidden:()=>!e.regularCollections.length,className:`nav-group nav-group-regular-collections`,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},()=>e.pinnedCollections.length?`Others`:`Collections`),()=>e.regularCollections.map(n=>Or(n,e))),t.details({hidden:()=>!e.systemCollections.length,className:`nav-group nav-group-system-collections`,open:()=>e.search.length},t.summary(null,`System`),()=>e.systemCollections.map(n=>Or(n,e)))),t.div({hidden:()=>e.search.length&&!e.filteredCollections.length,className:`sidebar-content new-collection`},t.button({type:`button`,className:`btn outline block`,onclick:()=>{app.modals.openCollectionUpsert({},{onsave:e=>{app.store.activeCollection=e.id}})}},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({textContent:`New collection`})))])}function Or(e,n){return t.button({"html-data-collection-id":()=>e.id,type:`button`,className:()=>`nav-item responsive-close ${e.id==app.store.activeCollection?.id?`active`:``}`,title:()=>e.name,onauxclick:n=>{n.preventDefault(),window.open(`#/collections?collection=${e.name}`,`_blank`,`noreferrer,noopener`)},onclick:n=>{n.preventDefault(),app.store.activeCollection=e.name}},t.i({className:()=>app.collectionTypes[e.type]?.icon||app.utils.fallbackCollectionIcon,ariaHidden:!0}),t.span({className:`txt`},()=>e.name),()=>{if(!(e.type!=`auth`||!e.oauth2?.enabled||e.oauth2?.providers?.length>0))return t.i({ariaHidden:!0,className:`ri-alert-line txt-hint txt-sm`,ariaDescription:app.attrs.tooltip(`OAuth2 auth is enabled but the collection doesn't have any registered providers`)})},()=>{let r=n.pinned.indexOf(e.id);return t.span({tabIndex:-1,role:`button`,className:`pin`,title:()=>r>=0?`Unpin`:`Pin`,onclick:i=>{i.preventDefault(),i.stopPropagation(),r>=0?n.pinned.splice(r,1):n.pinned.push(e.id)}},t.i({ariaHidden:!1,className:()=>r>=0?`ri-unpin-line`:`ri-pushpin-line`}))})}var kr=`sort`,$=`filter`,Ar=`collection`,jr=`record`,Mr=`pbLastActiveCollection`,Nr=`recordsTotalCountRequest`;function Pr(e){app.store.activeCollection=e.query[Ar]?.[0]||window.localStorage.getItem(Mr);let n=store({reset:null,activeRecordIdOrModel:e.query[jr]?.[0]||``,sort:e.query[kr]?.[0]||``,filter:e.query[$]?.[0]||``,totalCount:0,isTotalCountLoading:!1});async function r(){if(app.store.activeCollection?.id){n.isTotalCountLoading=!0;try{let e=app.utils.normalizeSearchFilter(n.filter,app.store.activeCollection.fields.filter(e=>!e.hidden).map(e=>e.name));n.totalCount=(await app.pb.collection(app.store.activeCollection.name).getList(1,1,{requestKey:Nr,filter:e,fields:`id`})).totalItems}catch(e){e.isAbort||(n.totalCount=0,console.warn(`failed to load total count:`,e))}n.isTotalCountLoading=!1}}function i(){n.reset=Date.now()}let a=[watch(()=>(app.store.activeCollection?.name||``)+(app.store.activeCollection?.updated||``),(e,r)=>{app.store.title=app.store.activeCollection?.name||`Collections`,r&&(r!=e&&(n.filter=``,n.sort=``),app.utils.replaceHashQueryParams({[Ar]:app.store.activeCollection?.name,[$]:n.filter||null,[kr]:n.sort||null},e==r?null:!0),app.store.activeCollection?.id?window.localStorage.setItem(Mr,app.store.activeCollection.id):window.localStorage.removeItem(Mr))}),watch(()=>[n.filter,n.sort],(e,r)=>{r&&app.utils.replaceHashQueryParams({[$]:n.filter||null,[kr]:n.sort||null})}),watch(()=>(n.activeRecordIdOrModel||``)+(app.store.activeCollection?.id||``),(e,r)=>{if(!n.activeRecordIdOrModel){app.utils.replaceHashQueryParams({[jr]:null});return}if(e==r||!app.store.activeCollection?.id)return;let i=typeof n.activeRecordIdOrModel==`string`?{id:n.activeRecordIdOrModel,collectionId:app.store.activeCollection?.id,collectionName:app.store.activeCollection?.name}:n.activeRecordIdOrModel;app.utils.replaceHashQueryParams({[jr]:i.id||null}),app.modals.close(null,!0),app.store.activeCollection?.type==`view`?app.modals.openRecordPreview(i,{onafterclose:()=>{n.activeRecordIdOrModel=``}}):app.modals.openRecordUpsert(app.store.activeCollection,i,{onafterclose:()=>{n.activeRecordIdOrModel=``}})}),watch(()=>[app.store.activeCollection?.id,n.filter,n.reset],()=>r())],o={"record:save":e=>{e.detail.collectionId==app.store.activeCollection?.id&&n.totalCount++},"record:delete":e=>{e.detail.collectionId!=app.store.activeCollection?.id&&e.detail.collectionName!=app.store.activeCollection?.name||n.totalCount--}};return t.div({pbEvent:`pageCollections`,className:`page`,onmount:()=>{app.store.isLoadingCollections||app.store.silentlyReloadCollections();for(let e in o)document.addEventListener(e,o[e])},onunmount:()=>{app.pb.cancelRequest(Nr),a.forEach(e=>e?.unwatch());for(let e in o)document.removeEventListener(e,o[e])}},()=>Dr(),t.div({className:`page-content full-height`},t.header({className:`page-header compact flex-nowrap`},t.nav({className:`breadcrumbs`},t.div(null,`Collections`),()=>{if(app.store.activeCollection?.name)return t.div({title:app.store.activeCollection.name,textContent:app.store.activeCollection.name})}),t.div({hidden:()=>!app.store.activeCollection?.id,pbEvent:`pageHeaderSecondaryBtns`,className:`page-header-secondary-btns`},t.button({type:`button`,className:`btn circle transparent secondary tooltip-bottom btn-collection-settings`,ariaLabel:app.attrs.tooltip(`Collection settings`),onclick:()=>{app.modals.openCollectionUpsert(app.store.activeCollection,{ontruncate:()=>i(),onsave:(e,n)=>{n?app.store.activeCollection=e.id:i()}})}},t.i({className:`ri-settings-3-line`,ariaHidden:!0})),app.components.refreshButton({onclick:()=>i()})),t.div({hidden:()=>!app.store.activeCollection?.id,pbEvent:`pageHeaderPrimaryBtns`,className:`page-header-primary-btns`},t.button({type:`button`,className:`btn outline api-preview-btn`,onclick:()=>app.modals.openApiPreview(app.store.activeCollection)},t.i({className:`ri-code-s-slash-line`,ariaHidden:!0}),t.span({className:`txt`,textContent:`API preview`})),()=>{if(app.store.activeCollection?.type!=`view`)return t.button({type:`button`,className:`btn new-record-btn`,onclick:()=>app.modals.openRecordUpsert(app.store.activeCollection)},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({className:`txt`,textContent:`New Record`}))})),t.div({hidden:()=>!app.store.isLoadingCollections||app.store.activeCollection?.id,className:`block txt-center p-base`},t.span({className:`loader lg`})),t.div({hidden:()=>app.store.isLoadingCollections||app.store.activeCollection?.id,className:`block txt-center p-base`},t.h6({className:`txt`},()=>app.store.collections?.length?`Select collection from the sidebar.`:`No collections found.`)),app.components.recordsSearchbar({hidden:()=>!app.store.activeCollection?.id,collection:()=>app.store.activeCollection,value:()=>n.filter,onsubmit:e=>n.filter=e}),app.components.recordsList({className:`m-t-sm`,reset:()=>n.reset,hidden:()=>!app.store.activeCollection?.id,collection:()=>app.store.activeCollection,filter:()=>n.filter,sort:()=>n.sort,onselect:e=>{n.activeRecordIdOrModel=e},onchange:(e,r)=>{n.filter=e,n.sort=r}}),t.footer({className:`page-footer`},t.span({className:()=>`total-count ${n.isTotalCountLoading?`faded`:``}`},`Total: `,()=>n.totalCount),app.components.credits())))}function Fr(){return document.body.clientWidth>600&&document.body.clientHeight>=720?150:100}function Ir(e){let n=store({stats:[]});async function r(r){if(r){e.isChartLoading=!0;try{let i=(e.presets||[]).concat(app.utils.normalizeSearchFilter(e.filter,[`level`,`message`,`data`])),a=await app.pb.logs.getStats({filter:i.filter(Boolean).map(e=>`(`+e+`)`).join(`&&`)}),o=a.length,s=[],c=[];e.totalFound=0;for(let n=0;n3600&&(s.push(r+3600),c.push(0)):n+1==o&&(s.push(r+3600),c.push(0))}n.stats=a,e.isChartLoading=!1,Rr(r,[s,c],e)}catch(n){n?.isAbort||(e.isChartLoading=!1,console.warn(`failed to load logs chart:`,n))}}}let i=[];return t.div({pbEvent:`logsChart`,className:()=>[`logs-chart`,e.isChartLoading?`loading`:null,e.zoom?.min&&e.zoom?.max?`zoomed`:``,!n.stats.length||!e.isFirstLoadReady?`nodata`:null].filter(Boolean).join(` `),onmount:n=>{i.push(watch(()=>[e.reset,e.filter,e.presets?.length],()=>r(n))),n._resizeChartFunc=()=>{clearTimeout(n._resizeTimeoutId),n._resizeTimeoutId=setTimeout(()=>{n?._uplot&&n._uplot.setSize({width:n.clientWidth,height:Fr()})},100)},window.addEventListener(`resize`,n._resizeChartFunc)},onunmount:e=>{i.forEach(e=>e?.unwatch()),e._uplot?.destroy(),e._resizeChartFunc&&(clearTimeout(e._resizeTimeoutId),window.removeEventListener(`resize`,e._resizeChartFunc),e._resizeChartFunc=null,e._resizeTimeoutId=null)}},t.button({type:`button`,className:()=>`logs-reset-zoom-ctrl ${e.zoom?.min&&e.zoom?.max?``:`hidden`}`,onclick(){e.zoom={}}},t.div({className:`content-primary`},`Reset zoom`),t.div({className:`content-secondary`},`(drag the timeline to pan)`)),t.span({hidden:()=>!e.isChartLoading,className:()=>`loader logs-chart-loader`}))}function Lr(e){let n=e?.data?.[0];n&&e.setScale(`x`,{min:n[0],max:n[n.length-1]})}function Rr(e,n,r){let i=window.getComputedStyle(e),a=i.getPropertyValue(`--surfaceTxtHintColor`),o=i.getPropertyValue(`--surfaceAlt1Color`),s=i.getPropertyValue(`--surfaceAlt4Color`),c=i.getPropertyValue(`--surfaceAlt2Color`),l={width:e.clientWidth,height:Fr(),legend:{show:!1},cursor:{x:!1,y:!1},scales:{x:{range:(e,r,i)=>rn[0][n[0].length-1]?[e.scales.x.min,e.scales.x.max]:[r,i]},y:{range:{min:{pad:.2,soft:0,mode:1},max:{pad:.2,soft:0,mode:2}}}},series:[{},{paths:uPlot.paths.stepped({align:1}),points:{show:!1,size:1},width:2,fill:c,stroke:s}],axes:[{show:!0,size:35,lineGap:1,space:60,stroke:a,incrs:[300,600,900,1800,3600,3600*2,3600*3,3600*4,3600*6,3600*12,86400,86400*2],values:[[3600,`{h}{aa}`,` {MMM} {DD}`,null,` {MMM} {DD}`,null,null,null,1],[60,`{h}:{mm}{aa}`,` {MMM} {DD}`,null,` -{MMM} {DD}`,null,null,null,1]],grid:{show:!0,stroke:o,width:1},ticks:{show:!0,stroke:o,width:1,size:5}},{show:!0,stroke:a,grid:{show:!0,stroke:o,width:1},ticks:{show:!0,stroke:o,width:1,size:5}}],plugins:[Vr(),zr(r),Br(r)]};e._uplot?.destroy(),e._uplot=new uPlot(l,n,e)}function zr(e){let n;return{hooks:{init:r=>{r.over.ondblclick=n=>{e.zoom={}},n=watch(()=>{!e.zoom?.min||!e.zoom?.max?Lr(r):r.setScale(`x`,{min:e.zoom.min,max:e.zoom.max})})},destroy:e=>{n?.unwatch()},setSelect:n=>{n.select.width>0&&(e.zoom={min:n.posToVal(n.select.left,`x`),max:n.posToVal(n.select.left+n.select.width,`x`)})}}}}function Br(e){let n;return{hooks:{init:r=>{let i=r.root.querySelectorAll(`.u-axis`);if(!i.length){console.warn(`xPanPlugin requires x axis to be defined`);return}i[0].addEventListener(`mousedown`,i=>{if(!e.zoom?.min)return;let a=i.clientX,{min:o,max:s}=r.scales.x,c=r.bbox.width,l=(s-o)/(c/uPlot.pxRatio),u=i=>{let c=(a-i.clientX)*l;r.setScale(`x`,{min:o+c,max:s+c}),clearTimeout(n),n=setTimeout(()=>{r?.scales?.x&&(e.zoom={min:r.scales.x.min,max:r.scales.x.max})},100)},d=e=>{document.removeEventListener(`mousemove`,u),document.removeEventListener(`mouseup`,d)};document.addEventListener(`mousemove`,u),document.addEventListener(`mouseup`,d)})},destroy:e=>{n&&clearTimeout(n)}}}}function Vr(e){let n;return{hooks:{init:e=>{let r=e.over;n=store({date:``,total:0,left:0,top:0,show:!1});let i=t.div({className:()=>`chart-tooltip ${n.show?``:`hidden`}`,onmount(e){e._positionWatcher?.unwatch(),e._positionWatcher=watch(()=>[n.left,n.top],()=>{if(!e)return;let i=e.getBoundingClientRect(),a=n.left;a<0?a=0:a+i.width>r.clientWidth&&(a=r.clientWidth-i.width),e.style.left=a+`px`;let o=n.top-i.height-5;o<0&&(o=n.top+5,o+i.high>r.clientHeight&&(o=r.clientHeight-i.height)),e.style.top=o+`px`})},onunmount(e){e._positionWatcher?.unwatch()}},t.div({className:`content-primary`},()=>`${n.total} ${n.total==1?`request`:`requests`}`),t.div({className:`content-secondary`},()=>n.date));r.appendChild(i),r.addEventListener(`mouseleave`,()=>{n&&(n.show=!1)})},destroy:()=>{n.show=!1},setCursor:e=>{if(!n)return;let r=e.data[0][e.cursor.idx]||0,i=e.data[1][e.cursor.idx]||0;if(r==0||i==0){n.show=!1;return}n.show=!0,n.total=i;let a=new Date(r*1e3),o=new Date(r*1e3+36e5),s=a.toLocaleString(`default`,{month:`short`}),c=a.getDate().toString().padStart(2,`0`);n.date=`${s} ${c} ${Hr(a)}-${Hr(o)}`,n.left=Math.round(e.valToPos(r,`x`)),n.top=Math.round(e.valToPos(i,`y`))}}}}function Hr(e){let n=e.getHours(),r=n>=12?`pm`:`am`;return n=n%12||12,n+r}var Ur=50;function Wr(e){let n=store({logs:[],lastLoadCount:0,lastPage:1,bulkSelected:{},get canLoadMore(){return n.lastLoadCount>=Ur},get totalSelected(){return Object.keys(n.bulkSelected).length},get areAllSelected(){return n.logs.length&&n.logs.length==n.totalSelected}});async function r(r=!1){e.isListLoading=!0;try{let i=r?1:n.lastPage+1,a=(e.presets||[]).concat(app.utils.normalizeSearchFilter(e.filter,[`level`,`message`,`data`]));if(e.zoom?.min&&e.zoom?.max){let n=new Date(e.zoom.min*1e3);n.setSeconds(0),n.setMilliseconds(0);let r=app.utils.toRFC3339Datetime(n),i=new Date(e.zoom.max*1e3);i.setSeconds(59),i.setMilliseconds(999);let o=app.utils.toRFC3339Datetime(i);a.push(`created >= "${r}" && created <= "${o}"`)}else i>1&&a.push(`created <= "${n.logs[n.logs.length-1].created}"`);let o=await app.pb.logs.getList(i,Ur,{skipTotal:1,sort:`-@rowid`,requestKey:`logs_list`,filter:a.filter(Boolean).map(e=>`(`+e+`)`).join(`&&`)});o.page==1&&(n.logs=[],n.bulkSelected={}),n.lastPage=o.page,n.lastLoadCount=o.items.length;for(let e=0;e1&&e%20==0&&await new Promise(e=>setTimeout(e,20));e.isListLoading=!1,e.isFirstLoadReady||=!0}catch(n){n.isAbort||(e.isListLoading=!1,app.checkApiError(n))}}function i(e=!0){let r={};if(e)for(let e of n.logs)r[e.id]=e;n.bulkSelected=r}function a(e){let n=[];if(!e.data)return n;if(e.data.type==`request`){for(let r of[`status`,`execTime`,`auth`,`authId`,`userIP`])e.data[r]!==void 0&&n.push({key:r});e.data.referer&&!e.data.referer.includes(window.location.host)&&n.push({key:`referer`})}else{let r=Object.keys(e.data);for(let e of r)e!=`error`&&e!=`details`&&n.length<6&&n.push({key:e})}return e.data.error&&n.push({key:`error`,label:`danger`}),e.data.details&&n.push({key:`details`,label:`warning`}),n}let o=/[-:\. ]/gi;function s(){let e=Object.values(n.bulkSelected).sort((e,n)=>e.createdn.created?-1:0);if(!e.length)return;if(e.length==1)return app.utils.downloadJSON(e[0],`log_`+e[0].created.replaceAll(o,``)+`.json`);let r=e[0].created.replaceAll(o,``),i=e[e.length-1].created.replaceAll(o,``);return app.utils.downloadJSON(e,`${e.length}_logs_${i}_to_${r}.json`)}let c=[];return t.div({pbEvent:`logsList`,className:`page-table-wrapper`,onmount(n){c.push(watch(()=>[e.filter,e.presets?.length],()=>{e.zoom={}}),watch(()=>[e.reset,e.filter,e.presets?.length,e.zoom?.min,e.zoom?.max],()=>{r(!0),n&&(n.scrollTop=0)}))},onunmount(){c.forEach(e=>e?.unwatch())}},t.table({className:()=>`logs-table ${n.logs?.length>Ur?`optimize`:``}`},t.thead(null,t.tr(null,t.th({className:`col-bulk-select`},t.div({className:`field`,hidden:()=>e.isLoading},t.input({id:`logs_select_all`,type:`checkbox`,checked:()=>n.areAllSelected,onchange:e=>i(e.target.checked)}),t.label({htmlFor:`logs_select_all`})),t.span({className:`loader`,hidden:()=>!e.isLoading})),t.th({className:`col-field-name-level`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-bookmark-line`,ariaHidden:!0}),t.span({textContent:`Level`}))),t.th({className:`col-field-name-message`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-file-list-2-line`,ariaHidden:!0}),t.span({textContent:`Message`}))),t.th({className:`col-field-type-date col-field-name-created`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-calendar-line`,ariaHidden:!0}),t.span({textContent:`Created`}))),t.th({className:`col-meta`}))),t.tbody(null,()=>n.logs?.length?n.logs.map(r=>t.tr({rid:r.id,tabIndex:0,role:`button`,className:()=>`handle ${r.data.type==`request`?`log-request`:``}`,onclick:()=>{e.activeLogIdOrModel=r},onkeypress:n=>{(n.key==`Enter`||n.key==` `)&&(n.preventDefault(),e.activeLogIdOrModel=r)}},()=>[t.td({className:`col-bulk-select`,onclick:e=>e.stopPropagation(),onkeypress:e=>e.stopPropagation()},t.div({className:`field`},t.input({id:`cb_`+r.id,type:`checkbox`,checked:()=>!!n.bulkSelected[r.id],onchange:e=>{let i=JSON.parse(JSON.stringify(n.bulkSelected));e.target.checked?i[r.id]=!0:delete i[r.id],n.bulkSelected=i}}),t.label({htmlFor:`cb_`+r.id}))),t.td({className:`col-field-name-level`},pr(r)),t.td({className:`col-field-name-message`},t.div({className:`content-primary`},()=>app.utils.truncate(r.message,1e3)),t.div({className:`content-secondary`},()=>{let e=[],n=a(r);for(let i of n){let n;n=app.utils.logDataFormatters[i.key]?app.utils.logDataFormatters[i.key](r):app.utils.stringifyValue(r.data[i.key],`N/A`,80),e.push(t.span({className:`label sm ${i.label||``}`},`${i.key}: ${n}`))}return e})),t.td({className:`col-field-type-date col-field-name-created`},app.components.formattedDate({value:()=>r.created,short:!1})),t.td({className:`col-meta`},t.i({className:`ri-arrow-right-line`,ariaHidden:!0}))])):t.tr(null,t.td({colSpan:99},()=>e.isListLoading?t.span({className:`skeleton-loader`}):t.div({className:`sticky-content txt-center txt-hint`},t.p({className:`txt-bold`},`No logs found.`),t.button({hidden:()=>e.filter?.length||app.utils.isEmpty(e.zoom),type:`button`,className:`btn secondary expanded-lg`,onclick(){e.zoom={}}},t.span({className:`txt`},`Reset zoom`)),t.button({hidden:()=>!e.filter?.length,type:`button`,className:`btn secondary expanded-lg`,onclick(){e.filter=``}},t.span({className:`txt`},`Clear search`))))),t.tr({hidden:()=>!n.canLoadMore},t.td({colSpan:99},t.button({className:()=>`btn lg secondary load-more-btn ${e.isListLoading?`transparent loading`:``}`,disabled:()=>e.isListLoading,onclick:()=>r()},t.span({className:`txt`},`Load older`)))))),t.div({className:`bulkbar-wrapper`},t.div({hidden:()=>n.totalSelected==0,className:`bulkbar logs-bulkbar`},t.span({className:`txt`},`Selected `,t.strong(null,()=>n.totalSelected),()=>` ${n.totalSelected==1?`log`:`logs`}`),t.button({type:`button`,className:`btn sm secondary pill m-r-auto`,onclick:()=>i(!1)},t.span({className:`txt`},`Reset`)),t.button({type:`button`,className:`btn sm pill`,onclick:()=>s()},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`JSON`)))))}function Gr(e){app.store.title=`Logs`;let n=`logId`,r=`filter`,i=`superuserRequests`,a=`pbLogSuperuserRequests`,o=`data.auth!='_superusers'`,s=e.query[n]?.[0]||``,c=e.query[r]?.[0]||``,l=!!(e.query[i]?.[0]<<0)||!!(window.localStorage.getItem(a)<<0),u=store({reset:null,isChartLoading:!1,isListLoading:!1,isFirstLoadReady:!1,zoom:{},presets:l?[]:[o],filter:c,totalFound:null,activeLogIdOrModel:s,get hasIncludeRequestsBySuperusers(){return!u.presets.includes(o)},get isLoading(){return u.isListLoading||u.isChartLoading}});function d(e){return e?typeof e==`string`?e:e?.id:null}function f(){u.reset=Date.now()}let p=[];return[t.div({pbEvent:`logsChartContainer`,className:`logs-chart-container accent-surface`},Ir(u)),t.div({pbEvent:`pageLogs`,className:`page page-logs`,onmount(e){p.push(watch(()=>{app.utils.replaceHashQueryParams({[r]:u.filter})}),watch(()=>{let e=+!!u.hasIncludeRequestsBySuperusers;app.utils.replaceHashQueryParams({[i]:e}),window.localStorage.setItem(a,e)}),watch(()=>u.activeLogIdOrModel,()=>{app.utils.replaceHashQueryParams({[n]:d(u.activeLogIdOrModel)}),u.activeLogIdOrModel&&(app.modals.close(null,!0),app.modals.openLogPreview(u.activeLogIdOrModel,{onafterclose:()=>{u.activeLogIdOrModel=null}}))}))},onunmount(e){clearTimeout(e._chartTiemoutId),p.forEach(e=>e?.unwatch())}},t.div({className:`page-content full-height`},t.header({className:`page-header`},t.nav({className:`breadcrumbs`},t.div(null,`Logs`)),t.div({className:`inline-flex gap-sm`},t.button({className:`btn circle transparent secondary tooltip-right`,ariaLabel:app.attrs.tooltip(`Logs settings`),onclick:()=>app.modals.openLogsSettings({onsave:()=>f()})},t.i({className:`ri-settings-3-line`,ariaHidden:!0})),app.components.refreshButton({onclick:f})),app.components.searchbar({className:`logs-searchbar`,historyKey:`pbLogsSearchHistory`,placeholder:"Search term or filter like `level > 0`",value:()=>u.filter||``,onsubmit:e=>u.filter=e,autocomplete:[`id`,`level`,`message`,`created`,{value:`data.`,label:`data.*`}]}),t.div({className:`meta m-l-auto`},t.div({className:`field logs-include-superuser-requests`},t.input({type:`checkbox`,id:`logs_checkbox`,className:`switch sm`,checked:()=>u.hasIncludeRequestsBySuperusers,onchange:e=>{e.target.checked?app.utils.removeByValue(u.presets,o):app.utils.pushUnique(u.presets,o)}}),t.label({htmlFor:`logs_checkbox`},t.small({className:`txt`},`Include requests by superusers`))))),Wr(u),t.footer({className:`page-footer`},t.span({className:`txt total-logs`},`Total: `,()=>u.totalFound==null?`...`:u.totalFound),app.components.credits())))]}function Kr(){return app.components.pageSidebar({pbEvent:`settingsSidebar`,className:`settings-sidebar`},t.nav({className:`sidebar-content scrollable`},()=>{let e=[];for(let n in app.store.settingsNavGroups){let r=app.store.settingsNavGroups[n],i=t.details({className:`nav-group`,"html-data-group":n,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},n),()=>r.map(e=>{let n=e.href.startsWith(`#/`);return t.a({href:()=>e.href,target:()=>n?void 0:`_blank`,rel:()=>n?void 0:`noopener noreferrer`,className:n=>`nav-item ${e.isActive?.(n)||app.utils.isActivePath(e.href,!1)?`active`:``}`},()=>{if(e.icon)return t.i({className:e.icon,ariaHidden:!0})},t.span({className:`txt`},()=>e.label))}));e.push(i)}return e}))}function qr(e){return t.details({pbEvent:`batchApiAccordion`,className:`accordion batch-api-accordion`,name:`settingsAccordion`},t.summary(null,t.i({className:`ri-archive-stack-line`,ariaHidden:!0}),t.span({className:`txt`},`Batch API`),t.div({className:`flex-fill`}),()=>e.formSettings.batch.enabled?t.span({className:`label success`},`Enabled`):t.span({className:`label`},`Disabled`),()=>{if(!app.utils.isEmpty(app.store.errors?.batch))return t.i({className:`ri-error-warning-fill txt-danger`,ariaDescription:app.attrs.tooltip(`Has errors`,`left`)})}),t.div({className:`grid sm`},t.div({className:`col-lg-12`},t.div({className:`field`},t.input({id:`batch.enabled`,name:`batch.enabled`,type:`checkbox`,className:`switch`,checked:()=>e.formSettings.batch.enabled||!1,onchange:n=>e.formSettings.batch.enabled=n.target.checked}),t.label({htmlFor:`batch.enabled`},t.span({className:`txt`},`Enable`),t.small({className:`txt-hint`},` (experimental)`)))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.maxRequests`},t.span({className:`txt`},`Max requests in a batch`),t.i({className:`ri-information-line link-faded`,ariaDescription:app.attrs.tooltip(`Rate limiting (if enabled) also applies for the batch create/update/upsert/delete requests.`,`right`)})),t.input({id:`batch.maxRequests`,name:`batch.maxRequests`,type:`number`,min:1,step:1,required:()=>e.formSettings.batch.enabled,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.maxRequests,oninput:n=>e.formSettings.batch.maxRequests=n.target.value<<0}))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.timeout`},t.span({className:`txt`},`Max processing time (in seconds)`)),t.input({id:`batch.timeout`,name:`batch.timeout`,type:`number`,min:1,step:1,required:()=>e.formSettings.batch.enabled,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.timeout,oninput:n=>e.formSettings.batch.timeout=parseInt(n.target.value,10)}))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.maxBodySize`},t.span({className:`txt`},`Max body size (in bytes)`)),t.input({id:`batch.maxBodySize`,name:`batch.maxBodySize`,type:`number`,min:0,step:1,placeholder:`Default to 128MB`,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.maxBodySize||``,oninput:n=>e.formSettings.batch.maxBodySize=parseInt(n.target.value,10)})))))}var Jr=[{value:`*:list`},{value:`*:view`},{value:`*:create`},{value:`*:update`},{value:`*:delete`},{value:`*:file`,description:`targets the files download endpoint`},{value:`*:listAuthMethods`},{value:`*:authRefresh`},{value:`*:auth`,description:`targets all auth methods`},{value:`*:authWithPassword`},{value:`*:authWithOAuth2`},{value:`*:authWithOTP`},{value:`*:requestOTP`},{value:`*:requestPasswordReset`},{value:`*:confirmPasswordReset`},{value:`*:requestVerification`},{value:`*:confirmVerification`},{value:`*:requestEmailChange`},{value:`*:confirmEmailChange`}];function Yr(){let e=Xr();document.body.appendChild(e),app.modals.open(e)}function Xr(){return t.div({pbEvent:`rateLimitInfoModal`,className:`modal rate-limit-info-modal`,onafterclose:e=>{e?.remove()}},t.header({className:`modal-header`},t.h5(null,`Rate limit label format`)),t.div({className:`modal-content`},t.p(null,`The rate limit rules are resolved in the following order (stops on the first match):`),t.ol(null,t.li(null,`exact tag (e.g. `,t.code(null,`users:create`)),t.li(null,`wildcard tag (e.g. `,t.code(null,`*:create`)),t.li(null,`METHOD + exact path (e.g. `,t.code(null,`POST /a/b`)),t.li(null,`METHOD + prefix path (e.g. `,t.code(null,`POST /a/b`,t.strong(null,`/`))),t.li(null,`exact path (e.g. `,t.code(null,`/a/b`)),t.li(null,`prefix path (e.g. `,t.code(null,`/a/b`,t.strong(null,`/`)))),t.p(null,`In case of multiple rules with the same label but different target user audience (e.g. "guest" vs "auth"), only the matching audience rule is taken in consideration.`),t.hr(),t.p(null,`The rate limit label could be in one of the following formats:`),t.ul(null,t.li({className:`m-b-sm`},t.code(null,`[METHOD ]/my/path`),` - full exact route match (`,t.strong(null,`must be without trailing slash`),`; "METHOD" is optional).`,t.br(),`For example:`,t.ul({className:`m-0`},t.li(null,t.code(null,`/hello`),` - matches `,t.code(null,`GET /hello`),`, `,t.code(null,`POST /hello`),`, etc.`),t.li(null,t.code(null,`POST /hello`),` - matches only `,t.code(null,`POST /hello`)))),t.li({className:`m-b-sm`},t.code(null,`[METHOD ]/my/prefix`,t.strong(null,`/`)),` - path prefix (`,t.strong(null,`must end with trailing slash;`),`"METHOD" is optional). For example:`,t.ul({className:`m-0`},t.li(null,t.code(null,`/hello/`),` - matches `,t.code(null,`GET /hello`),`, `,t.code(null,`POST /hello/a/b/c`),`, etc.`),t.li(null,t.code(null,`POST /hello/`),` - matches `,t.code(null,`POST /hello`),`, `,t.code(null,`POST /hello/a/b/c`),`, etc.`))),t.li({className:`m-b-0`},t.code(null,`collectionName:predefinedTag`),` - targets a specific action of a single collection.`,` To apply the rule for all collections you can use the `,t.code(null,`*`),` wildcard. For example:`,t.code(null,`posts:create`),`, `,t.code(null,`users:listAuthMethods`),`, `,t.code(null,`*:auth`),`.`,t.br(),`The predifined collection tags are (`,t.em(null,`there should be autocomplete once you start typing`),`):`,t.ul({className:`m-0`},()=>Jr.map(e=>t.li(null,e.value.replace(`*:`,`:`),()=>{if(e.description)return t.em({className:`txt-hint`},` (`,e.description,`)`)})))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close()},t.span({className:`txt`},`Close`))))}function Zr(e){if(!e)return;let n=[{},{}];return e.sort((e,r)=>{n[0].length=e.label.length,n[0].isTag=e.label.includes(`:`)||!e.label.includes(`/`),n[0].isWildcardTag=n[0].isTag&&e.label.startsWith(`*`),n[0].isExactTag=n[0].isTag&&!n[0].isWildcardTag,n[0].isPrefix=!n[0].isTag&&e.label.endsWith(`/`),n[0].hasMethod=!n[0].isTag&&e.label.includes(` /`),n[1].length=r.label.length,n[1].isTag=r.label.includes(`:`)||!r.label.includes(`/`),n[1].isWildcardTag=n[1].isTag&&r.label.startsWith(`*`),n[1].isExactTag=n[1].isTag&&!n[1].isWildcardTag,n[1].isPrefix=!n[1].isTag&&r.label.endsWith(`/`),n[1].hasMethod=!n[1].isTag&&r.label.includes(` /`);for(let e of n)e.priority=0,e.isTag?(e.priority+=1e3,e.isExactTag?e.priority+=10:e.priority+=5):(e.hasMethod&&(e.priority+=10),e.isPrefix||(e.priority+=5));return n[0].isPrefix&&n[1].isPrefix&&(n[0].hasMethod&&n[1].hasMethod||!n[0].hasMethod&&!n[1].hasMethod)&&(n[0].length>n[1].length?n[0].priority+=1:n[0].lengthn[1].priority?-1:+(n[0].prioritye.type==`file`)&&r.predefinedTags.push({value:n.name+`:file`}));r.predefinedTags=r.predefinedTags.concat(Jr)}function a(){Array.isArray(e.formSettings.rateLimits.rules)||(e.formSettings.rateLimits.rules=[]),e.formSettings.rateLimits.rules.push({label:``,maxRequests:200,duration:3,audience:``}),e.formSettings.rateLimits.rules.length==1&&(e.formSettings.rateLimits.enabled=!0)}function o(n){e.formSettings.rateLimits.rules.splice(n,1),e.formSettings.rateLimits.rules.length||(e.formSettings.rateLimits.enabled=!1)}let s=[];return t.details({pbEvent:`rateLimitAccordion`,className:`accordion rate-limit-accordion`,name:`settingsAccordion`,onmount:()=>{s.push(watch(()=>JSON.stringify(e.formSettings.rateLimits.rules),()=>{app.store.errors?.rateLimits?.rules&&delete app.store.errors.rateLimits}))},onunmount:()=>{s.forEach(e=>e?.unwatch())}},t.summary(null,t.i({className:`ri-pulse-fill`,ariaHidden:!0}),t.span({className:`txt`},`Rate limiting`),t.div({className:`flex-fill`}),()=>e.formSettings.rateLimits.enabled?t.span({className:`label success`},`Enabled`):t.span({className:`label`},`Disabled`),()=>{if(!app.utils.isEmpty(app.store.errors?.rateLimits))return t.i({className:`ri-error-warning-fill txt-danger`,ariaDescription:app.attrs.tooltip(`Has errors`,`left`)})}),t.div({className:`grid sm`},t.div({className:`col-lg-12`},t.div({className:`field`},t.input({id:`rateLimits.enabled`,name:`rateLimits.enabled`,type:`checkbox`,className:`switch`,checked:()=>e.formSettings.rateLimits.enabled||!1,onchange:n=>e.formSettings.rateLimits.enabled=n.target.checked}),t.label({htmlFor:`rateLimits.enabled`},t.span({className:`txt`},`Enable`),t.small({className:`txt-hint`},` (experimental)`)))),t.div({className:`col-lg-12`},t.div({className:`rate-limit-table-wrapper`},t.table({className:`rate-limit-table`},t.thead({hidden:()=>!e.formSettings.rateLimits.rules?.length},t.tr(null,t.th({className:`col-label`},`Rate limit label`),t.th({className:`col-requests`},`Max requests`,t.br(),t.small(null,`(per IP)`)),t.th({className:`col-duration`},`Interval`,t.br(),t.small(null,`(in seconds)`)),t.th({className:`col-audience`},`Targeted users`),t.th({className:`col-action`}))),t.tbody(null,()=>{let i=[],a=e.formSettings.rateLimits.rules||[];for(let e=0;es.label,oninput:e=>s.label=e.target.value}),t.datalist({id:`rateLimits.rules.`+e+`.label_list`},()=>r.predefinedTags.map(e=>t.option({value:e.value},e.label||``))))),t.td({className:`col-requests`},t.div({className:`field`},t.input({type:`number`,required:!0,placeholder:`Max requests*`,className:`inline-error`,min:1,step:1,name:`rateLimits.rules.`+e+`.maxRequests`,value:()=>s.maxRequests||0,oninput:e=>s.maxRequests=parseInt(e.target.value,10)}))),t.td({className:`col-duration`},t.div({className:`field`},t.input({type:`number`,required:!0,placeholder:`Interval*`,className:`inline-error`,min:1,step:1,name:`rateLimits.rules.`+e+`.duration`,value:()=>s.duration,oninput:e=>s.duration=parseInt(e.target.value,10)}))),t.td({className:`col-audience`},t.div({className:`field`},app.components.select({name:`rateLimits.rules.`+e+`.audience`,className:`inline-error`,options:n,required:!0,value:()=>s.audience||``,onchange:e=>{s.audience=e?.[0]?.value}}))),t.td({className:`col-action`},t.button({type:`button`,araiaDescription:app.attrs.tooltip(`Remove rule`),className:`btn sm secondary transparent circle`,onclick:()=>o(e)},t.i({className:`ri-close-line`})))))}return i}))),t.div({className:`flex m-t-sm`},t.button({type:`button`,className:`btn secondary sm`,onclick:()=>a()},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({className:`txt`},`Add rate limit rule`)),t.button({type:`button`,className:`link-hint txt-sm m-l-auto`,onclick:()=>Yr()},t.em(null,`Learn more about the rate limit rules`))))))}function $r(e){let n=[`X-Forwarded-For`,`Fly-Client-IP`,`CF-Connecting-IP`],r=[{label:`Use leftmost IP`,value:!0},{label:`Use rightmost IP`,value:!1}],i=store({isLoading:!1,realIP:``,possibleProxyHeader:``,get suggestedProxyHeaders(){return i.possibleProxyHeader?[i.possibleProxyHeader].concat(n.filter(e=>e!=i.possibleProxyHeader)):n},get isEnabled(){return!app.utils.isEmpty(e.formSettings.trustedProxy?.headers)}});a();async function a(){i.isLoading=!0;try{let e=await app.pb.health.check({requestKey:`loadProxyInfo`});i.realIP=e.data?.realIP||``,i.possibleProxyHeader=e.data?.possibleProxyHeader||``,i.isLoading=!1}catch(e){e.isAbort||(app.checkApiError(e),i.isLoading=!1)}}return t.details({pbEvent:`trustedProxyAccordion`,className:`accordion trusted-proxy-accordion`,name:`settingsAccordion`,open:()=>i.isLoading?!1:null},t.summary(null,t.i({className:`ri-route-line`,ariaHidden:!0}),t.span({className:`txt`},`User IP proxy headers`),()=>{if(i.isLoading)return t.span({className:`loader sm`});if(!i.isEnabled&&i.possibleProxyHeader)return t.i({className:`ri-alert-line txt-warning`,ariaDescription:app.attrs.tooltip(`Detected proxy header. +{MMM} {DD}`,null,null,null,1]],grid:{show:!0,stroke:o,width:1},ticks:{show:!0,stroke:o,width:1,size:5}},{show:!0,stroke:a,grid:{show:!0,stroke:o,width:1},ticks:{show:!0,stroke:o,width:1,size:5}}],plugins:[Vr(),zr(r),Br(r)]};e._uplot?.destroy(),e._uplot=new uPlot(l,n,e)}function zr(e){let n;return{hooks:{init:r=>{r.over.ondblclick=n=>{e.zoom={}},n=watch(()=>{!e.zoom?.min||!e.zoom?.max?Lr(r):r.setScale(`x`,{min:e.zoom.min,max:e.zoom.max})})},destroy:e=>{n?.unwatch()},setSelect:n=>{n.select.width>0&&(e.zoom={min:n.posToVal(n.select.left,`x`),max:n.posToVal(n.select.left+n.select.width,`x`)})}}}}function Br(e){let n;return{hooks:{init:r=>{let i=r.root.querySelectorAll(`.u-axis`);if(!i.length){console.warn(`xPanPlugin requires x axis to be defined`);return}i[0].addEventListener(`mousedown`,i=>{if(!e.zoom?.min)return;let a=i.clientX,{min:o,max:s}=r.scales.x,c=r.bbox.width,l=(s-o)/(c/uPlot.pxRatio),u=i=>{let c=(a-i.clientX)*l;r.setScale(`x`,{min:o+c,max:s+c}),clearTimeout(n),n=setTimeout(()=>{r?.scales?.x&&(e.zoom={min:r.scales.x.min,max:r.scales.x.max})},100)},d=e=>{document.removeEventListener(`mousemove`,u),document.removeEventListener(`mouseup`,d)};document.addEventListener(`mousemove`,u),document.addEventListener(`mouseup`,d)})},destroy:e=>{n&&clearTimeout(n)}}}}function Vr(e){let n;return{hooks:{init:e=>{let r=e.over;n=store({date:``,total:0,left:0,top:0,show:!1});let i=t.div({className:()=>`chart-tooltip ${n.show?``:`hidden`}`,onmount(e){e._positionWatcher?.unwatch(),e._positionWatcher=watch(()=>[n.left,n.top],()=>{if(!e)return;let i=e.getBoundingClientRect(),a=n.left;a<0?a=0:a+i.width>r.clientWidth&&(a=r.clientWidth-i.width),e.style.left=a+`px`;let o=n.top-i.height-5;o<0&&(o=n.top+5,o+i.high>r.clientHeight&&(o=r.clientHeight-i.height)),e.style.top=o+`px`})},onunmount(e){e._positionWatcher?.unwatch()}},t.div({className:`content-primary`},()=>`${n.total} ${n.total==1?`request`:`requests`}`),t.div({className:`content-secondary`},()=>n.date));r.appendChild(i),r.addEventListener(`mouseleave`,()=>{n&&(n.show=!1)})},destroy:()=>{n.show=!1},setCursor:e=>{if(!n)return;let r=e.data[0][e.cursor.idx]||0,i=e.data[1][e.cursor.idx]||0;if(r==0||i==0){n.show=!1;return}n.show=!0,n.total=i;let a=new Date(r*1e3),o=new Date(r*1e3+36e5),s=a.toLocaleString(`default`,{month:`short`}),c=a.getDate().toString().padStart(2,`0`);n.date=`${s} ${c} ${Hr(a)}-${Hr(o)}`,n.left=Math.round(e.valToPos(r,`x`)),n.top=Math.round(e.valToPos(i,`y`))}}}}function Hr(e){let n=e.getHours(),r=n>=12?`pm`:`am`;return n=n%12||12,n+r}var Ur=50;function Wr(e){let n=store({logs:[],lastLoadCount:0,lastPage:1,bulkSelected:{},get canLoadMore(){return n.lastLoadCount>=Ur},get totalSelected(){return Object.keys(n.bulkSelected).length},get areAllSelected(){return n.logs.length&&n.logs.length==n.totalSelected}});async function r(r=!1){e.isListLoading=!0;try{let i=r?1:n.lastPage+1,a=(e.presets||[]).concat(app.utils.normalizeSearchFilter(e.filter,[`level`,`message`,`data`]));if(e.zoom?.min&&e.zoom?.max){let n=new Date(e.zoom.min*1e3);n.setSeconds(0),n.setMilliseconds(0);let r=app.utils.toRFC3339Datetime(n),i=new Date(e.zoom.max*1e3);i.setSeconds(59),i.setMilliseconds(999);let o=app.utils.toRFC3339Datetime(i);a.push(`created >= "${r}" && created <= "${o}"`)}else i>1&&a.push(`created <= "${n.logs[n.logs.length-1].created}"`);let o=await app.pb.logs.getList(i,Ur,{skipTotal:1,sort:`-@rowid`,requestKey:`logs_list`,filter:a.filter(Boolean).map(e=>`(`+e+`)`).join(`&&`)});o.page==1&&(n.logs=[],n.bulkSelected={}),n.lastPage=o.page,n.lastLoadCount=o.items.length;for(let e=0;e1&&e%20==0&&await new Promise(e=>setTimeout(e,20));e.isListLoading=!1,e.isFirstLoadReady||=!0}catch(n){n.isAbort||(e.isListLoading=!1,app.checkApiError(n))}}function i(e=!0){let r={};if(e)for(let e of n.logs)r[e.id]=e;n.bulkSelected=r}function a(e){let n=[];if(!e.data)return n;if(e.data.type==`request`){for(let r of[`status`,`execTime`,`auth`,`authId`,`userIP`])e.data[r]!==void 0&&n.push({key:r});e.data.referer&&!e.data.referer.includes(window.location.host)&&n.push({key:`referer`})}else{let r=Object.keys(e.data);for(let e of r)e!=`error`&&e!=`details`&&n.length<6&&n.push({key:e})}return e.data.error&&n.push({key:`error`,label:`danger`}),e.data.details&&n.push({key:`details`,label:`warning`}),n}let o=/[-:\. ]/gi;function s(){let e=Object.values(n.bulkSelected).sort((e,n)=>e.createdn.created?-1:0);if(!e.length)return;if(e.length==1)return app.utils.downloadJSON(e[0],`log_`+e[0].created.replaceAll(o,``)+`.json`);let r=e[0].created.replaceAll(o,``),i=e[e.length-1].created.replaceAll(o,``);return app.utils.downloadJSON(e,`${e.length}_logs_${i}_to_${r}.json`)}let c=[];return t.div({pbEvent:`logsList`,className:`page-table-wrapper`,onmount(n){c.push(watch(()=>[e.filter,e.presets?.length],()=>{e.zoom={}}),watch(()=>[e.reset,e.filter,e.presets?.length,e.zoom?.min,e.zoom?.max],()=>{r(!0),n&&(n.scrollTop=0)}))},onunmount(){c.forEach(e=>e?.unwatch())}},t.table({className:()=>`logs-table ${n.logs?.length>Ur?`optimize`:``}`},t.thead(null,t.tr(null,t.th({className:`col-bulk-select`},t.div({className:`field`,hidden:()=>e.isLoading},t.input({id:`logs_select_all`,type:`checkbox`,checked:()=>n.areAllSelected,onchange:e=>i(e.target.checked)}),t.label({htmlFor:`logs_select_all`})),t.span({className:`loader`,hidden:()=>!e.isLoading})),t.th({className:`col-field-name-level`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-bookmark-line`,ariaHidden:!0}),t.span({textContent:`Level`}))),t.th({className:`col-field-name-message`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-file-list-2-line`,ariaHidden:!0}),t.span({textContent:`Message`}))),t.th({className:`col-field-type-date col-field-name-created`},t.div({className:`inline-flex gap-5`},t.i({className:`ri-calendar-line`,ariaHidden:!0}),t.span({textContent:`Created`}))),t.th({className:`col-meta`}))),t.tbody(null,()=>n.logs?.length?n.logs.map(r=>t.tr({rid:r.id,tabIndex:0,role:`button`,className:()=>`handle ${r.data.type==`request`?`log-request`:``}`,onclick:()=>{e.activeLogIdOrModel=r},onkeypress:n=>{(n.key==`Enter`||n.key==` `)&&(n.preventDefault(),e.activeLogIdOrModel=r)}},()=>[t.td({className:`col-bulk-select`,onclick:e=>e.stopPropagation(),onkeypress:e=>e.stopPropagation()},t.div({className:`field`},t.input({id:`cb_`+r.id,type:`checkbox`,checked:()=>!!n.bulkSelected[r.id],onchange:e=>{let i=JSON.parse(JSON.stringify(n.bulkSelected));e.target.checked?i[r.id]=!0:delete i[r.id],n.bulkSelected=i}}),t.label({htmlFor:`cb_`+r.id}))),t.td({className:`col-field-name-level`},pr(r)),t.td({className:`col-field-name-message`},t.div({className:`content-primary`},()=>app.utils.truncate(r.message,1e3)),t.div({className:`content-secondary`},()=>{let e=[],n=a(r);for(let i of n){let n;n=app.utils.logDataFormatters[i.key]?app.utils.logDataFormatters[i.key](r):app.utils.displayValue(r.data[i.key],80),e.push(t.span({className:`label sm ${i.label||``}`},`${i.key}: ${n}`))}return e})),t.td({className:`col-field-type-date col-field-name-created`},app.components.formattedDate({value:()=>r.created,short:!1})),t.td({className:`col-meta`},t.i({className:`ri-arrow-right-line`,ariaHidden:!0}))])):t.tr(null,t.td({colSpan:99},()=>e.isListLoading?t.span({className:`skeleton-loader`}):t.div({className:`sticky-content txt-center txt-hint`},t.p({className:`txt-bold`},`No logs found.`),t.button({hidden:()=>e.filter?.length||app.utils.isEmpty(e.zoom),type:`button`,className:`btn secondary expanded-lg`,onclick(){e.zoom={}}},t.span({className:`txt`},`Reset zoom`)),t.button({hidden:()=>!e.filter?.length,type:`button`,className:`btn secondary expanded-lg`,onclick(){e.filter=``}},t.span({className:`txt`},`Clear search`))))),t.tr({hidden:()=>!n.canLoadMore},t.td({colSpan:99},t.button({className:()=>`btn lg secondary load-more-btn ${e.isListLoading?`transparent loading`:``}`,disabled:()=>e.isListLoading,onclick:()=>r()},t.span({className:`txt`},`Load older`)))))),t.div({className:`bulkbar-wrapper`},t.div({hidden:()=>n.totalSelected==0,className:`bulkbar logs-bulkbar`},t.span({className:`txt`},`Selected `,t.strong(null,()=>n.totalSelected),()=>` ${n.totalSelected==1?`log`:`logs`}`),t.button({type:`button`,className:`btn sm secondary pill m-r-auto`,onclick:()=>i(!1)},t.span({className:`txt`},`Reset`)),t.button({type:`button`,className:`btn sm pill`,onclick:()=>s()},t.i({className:`ri-download-line`,ariaHidden:!0}),t.span({className:`txt`},`JSON`)))))}function Gr(e){app.store.title=`Logs`;let n=`logId`,r=`filter`,i=`superuserRequests`,a=`pbLogSuperuserRequests`,o=`data.auth!='_superusers'`,s=e.query[n]?.[0]||``,c=e.query[r]?.[0]||``,l=!!(e.query[i]?.[0]<<0)||!!(window.localStorage.getItem(a)<<0),u=store({reset:null,isChartLoading:!1,isListLoading:!1,isFirstLoadReady:!1,zoom:{},presets:l?[]:[o],filter:c,totalFound:null,activeLogIdOrModel:s,get hasIncludeRequestsBySuperusers(){return!u.presets.includes(o)},get isLoading(){return u.isListLoading||u.isChartLoading}});function d(e){return e?typeof e==`string`?e:e?.id:null}function f(){u.reset=Date.now()}let p=[];return[t.div({pbEvent:`logsChartContainer`,className:`logs-chart-container accent-surface`},Ir(u)),t.div({pbEvent:`pageLogs`,className:`page page-logs`,onmount(e){p.push(watch(()=>{app.utils.replaceHashQueryParams({[r]:u.filter})}),watch(()=>{let e=+!!u.hasIncludeRequestsBySuperusers;app.utils.replaceHashQueryParams({[i]:e}),window.localStorage.setItem(a,e)}),watch(()=>u.activeLogIdOrModel,()=>{app.utils.replaceHashQueryParams({[n]:d(u.activeLogIdOrModel)}),u.activeLogIdOrModel&&(app.modals.close(null,!0),app.modals.openLogPreview(u.activeLogIdOrModel,{onafterclose:()=>{u.activeLogIdOrModel=null}}))}))},onunmount(e){clearTimeout(e._chartTiemoutId),p.forEach(e=>e?.unwatch())}},t.div({className:`page-content full-height`},t.header({className:`page-header`},t.nav({className:`breadcrumbs`},t.div(null,`Logs`)),t.div({className:`inline-flex gap-sm`},t.button({className:`btn circle transparent secondary tooltip-right`,ariaLabel:app.attrs.tooltip(`Logs settings`),onclick:()=>app.modals.openLogsSettings({onsave:()=>f()})},t.i({className:`ri-settings-3-line`,ariaHidden:!0})),app.components.refreshButton({onclick:f})),app.components.searchbar({className:`logs-searchbar`,historyKey:`pbLogsSearchHistory`,placeholder:"Search term or filter like `level > 0`",value:()=>u.filter||``,onsubmit:e=>u.filter=e,autocomplete:[`id`,`level`,`message`,`created`,{value:`data.`,label:`data.*`}]}),t.div({className:`meta m-l-auto`},t.div({className:`field logs-include-superuser-requests`},t.input({type:`checkbox`,id:`logs_checkbox`,className:`switch sm`,checked:()=>u.hasIncludeRequestsBySuperusers,onchange:e=>{e.target.checked?app.utils.removeByValue(u.presets,o):app.utils.pushUnique(u.presets,o)}}),t.label({htmlFor:`logs_checkbox`},t.small({className:`txt`},`Include requests by superusers`))))),Wr(u),t.footer({className:`page-footer`},t.span({className:`txt total-logs`},`Total: `,()=>u.totalFound==null?`...`:u.totalFound),app.components.credits())))]}function Kr(){return app.components.pageSidebar({pbEvent:`settingsSidebar`,className:`settings-sidebar`},t.nav({className:`sidebar-content scrollable`},()=>{let e=[];for(let n in app.store.settingsNavGroups){let r=app.store.settingsNavGroups[n],i=t.details({className:`nav-group`,"html-data-group":n,open:!0},t.summary({tabIndex:-1,onfocusout:()=>!1,onclick:()=>!1,onkeyup:()=>!1},n),()=>r.map(e=>{let n=e.href.startsWith(`#/`);return t.a({href:()=>e.href,target:()=>n?void 0:`_blank`,rel:()=>n?void 0:`noopener noreferrer`,className:n=>`nav-item ${e.isActive?.(n)||app.utils.isActivePath(e.href,!1)?`active`:``}`},()=>{if(e.icon)return t.i({className:e.icon,ariaHidden:!0})},t.span({className:`txt`},()=>e.label))}));e.push(i)}return e}))}function qr(e){return t.details({pbEvent:`batchApiAccordion`,className:`accordion batch-api-accordion`,name:`settingsAccordion`},t.summary(null,t.i({className:`ri-archive-stack-line`,ariaHidden:!0}),t.span({className:`txt`},`Batch API`),t.div({className:`flex-fill`}),()=>e.formSettings.batch.enabled?t.span({className:`label success`},`Enabled`):t.span({className:`label`},`Disabled`),()=>{if(!app.utils.isEmpty(app.store.errors?.batch))return t.i({className:`ri-error-warning-fill txt-danger`,ariaDescription:app.attrs.tooltip(`Has errors`,`left`)})}),t.div({className:`grid sm`},t.div({className:`col-lg-12`},t.div({className:`field`},t.input({id:`batch.enabled`,name:`batch.enabled`,type:`checkbox`,className:`switch`,checked:()=>e.formSettings.batch.enabled||!1,onchange:n=>e.formSettings.batch.enabled=n.target.checked}),t.label({htmlFor:`batch.enabled`},t.span({className:`txt`},`Enable`),t.small({className:`txt-hint`},` (experimental)`)))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.maxRequests`},t.span({className:`txt`},`Max requests in a batch`),t.i({className:`ri-information-line link-faded`,ariaDescription:app.attrs.tooltip(`Rate limiting (if enabled) also applies for the batch create/update/upsert/delete requests.`,`right`)})),t.input({id:`batch.maxRequests`,name:`batch.maxRequests`,type:`number`,min:1,step:1,required:()=>e.formSettings.batch.enabled,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.maxRequests,oninput:n=>e.formSettings.batch.maxRequests=n.target.value<<0}))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.timeout`},t.span({className:`txt`},`Max processing time (in seconds)`)),t.input({id:`batch.timeout`,name:`batch.timeout`,type:`number`,min:1,step:1,required:()=>e.formSettings.batch.enabled,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.timeout,oninput:n=>e.formSettings.batch.timeout=parseInt(n.target.value,10)}))),t.div({className:`col-lg-4`},t.div({className:`field`},t.label({htmlFor:`batch.maxBodySize`},t.span({className:`txt`},`Max body size (in bytes)`)),t.input({id:`batch.maxBodySize`,name:`batch.maxBodySize`,type:`number`,min:0,step:1,placeholder:`Default to 128MB`,disabled:()=>!e.formSettings.batch.enabled,value:()=>e.formSettings.batch.maxBodySize||``,oninput:n=>e.formSettings.batch.maxBodySize=parseInt(n.target.value,10)})))))}var Jr=[{value:`*:list`},{value:`*:view`},{value:`*:create`},{value:`*:update`},{value:`*:delete`},{value:`*:file`,description:`targets the files download endpoint`},{value:`*:listAuthMethods`},{value:`*:authRefresh`},{value:`*:auth`,description:`targets all auth methods`},{value:`*:authWithPassword`},{value:`*:authWithOAuth2`},{value:`*:authWithOTP`},{value:`*:requestOTP`},{value:`*:requestPasswordReset`},{value:`*:confirmPasswordReset`},{value:`*:requestVerification`},{value:`*:confirmVerification`},{value:`*:requestEmailChange`},{value:`*:confirmEmailChange`}];function Yr(){let e=Xr();document.body.appendChild(e),app.modals.open(e)}function Xr(){return t.div({pbEvent:`rateLimitInfoModal`,className:`modal rate-limit-info-modal`,onafterclose:e=>{e?.remove()}},t.header({className:`modal-header`},t.h5(null,`Rate limit label format`)),t.div({className:`modal-content`},t.p(null,`The rate limit rules are resolved in the following order (stops on the first match):`),t.ol(null,t.li(null,`exact tag (e.g. `,t.code(null,`users:create`)),t.li(null,`wildcard tag (e.g. `,t.code(null,`*:create`)),t.li(null,`METHOD + exact path (e.g. `,t.code(null,`POST /a/b`)),t.li(null,`METHOD + prefix path (e.g. `,t.code(null,`POST /a/b`,t.strong(null,`/`))),t.li(null,`exact path (e.g. `,t.code(null,`/a/b`)),t.li(null,`prefix path (e.g. `,t.code(null,`/a/b`,t.strong(null,`/`)))),t.p(null,`In case of multiple rules with the same label but different target user audience (e.g. "guest" vs "auth"), only the matching audience rule is taken in consideration.`),t.hr(),t.p(null,`The rate limit label could be in one of the following formats:`),t.ul(null,t.li({className:`m-b-sm`},t.code(null,`[METHOD ]/my/path`),` - full exact route match (`,t.strong(null,`must be without trailing slash`),`; "METHOD" is optional).`,t.br(),`For example:`,t.ul({className:`m-0`},t.li(null,t.code(null,`/hello`),` - matches `,t.code(null,`GET /hello`),`, `,t.code(null,`POST /hello`),`, etc.`),t.li(null,t.code(null,`POST /hello`),` - matches only `,t.code(null,`POST /hello`)))),t.li({className:`m-b-sm`},t.code(null,`[METHOD ]/my/prefix`,t.strong(null,`/`)),` - path prefix (`,t.strong(null,`must end with trailing slash;`),`"METHOD" is optional). For example:`,t.ul({className:`m-0`},t.li(null,t.code(null,`/hello/`),` - matches `,t.code(null,`GET /hello`),`, `,t.code(null,`POST /hello/a/b/c`),`, etc.`),t.li(null,t.code(null,`POST /hello/`),` - matches `,t.code(null,`POST /hello`),`, `,t.code(null,`POST /hello/a/b/c`),`, etc.`))),t.li({className:`m-b-0`},t.code(null,`collectionName:predefinedTag`),` - targets a specific action of a single collection.`,` To apply the rule for all collections you can use the `,t.code(null,`*`),` wildcard. For example:`,t.code(null,`posts:create`),`, `,t.code(null,`users:listAuthMethods`),`, `,t.code(null,`*:auth`),`.`,t.br(),`The predifined collection tags are (`,t.em(null,`there should be autocomplete once you start typing`),`):`,t.ul({className:`m-0`},()=>Jr.map(e=>t.li(null,e.value.replace(`*:`,`:`),()=>{if(e.description)return t.em({className:`txt-hint`},` (`,e.description,`)`)})))))),t.footer({className:`modal-footer`},t.button({type:`button`,className:`btn transparent m-r-auto`,onclick:()=>app.modals.close()},t.span({className:`txt`},`Close`))))}function Zr(e){if(!e)return;let n=[{},{}];return e.sort((e,r)=>{n[0].length=e.label.length,n[0].isTag=e.label.includes(`:`)||!e.label.includes(`/`),n[0].isWildcardTag=n[0].isTag&&e.label.startsWith(`*`),n[0].isExactTag=n[0].isTag&&!n[0].isWildcardTag,n[0].isPrefix=!n[0].isTag&&e.label.endsWith(`/`),n[0].hasMethod=!n[0].isTag&&e.label.includes(` /`),n[1].length=r.label.length,n[1].isTag=r.label.includes(`:`)||!r.label.includes(`/`),n[1].isWildcardTag=n[1].isTag&&r.label.startsWith(`*`),n[1].isExactTag=n[1].isTag&&!n[1].isWildcardTag,n[1].isPrefix=!n[1].isTag&&r.label.endsWith(`/`),n[1].hasMethod=!n[1].isTag&&r.label.includes(` /`);for(let e of n)e.priority=0,e.isTag?(e.priority+=1e3,e.isExactTag?e.priority+=10:e.priority+=5):(e.hasMethod&&(e.priority+=10),e.isPrefix||(e.priority+=5));return n[0].isPrefix&&n[1].isPrefix&&(n[0].hasMethod&&n[1].hasMethod||!n[0].hasMethod&&!n[1].hasMethod)&&(n[0].length>n[1].length?n[0].priority+=1:n[0].lengthn[1].priority?-1:+(n[0].prioritye.type==`file`)&&r.predefinedTags.push({value:n.name+`:file`}));r.predefinedTags=r.predefinedTags.concat(Jr)}function a(){Array.isArray(e.formSettings.rateLimits.rules)||(e.formSettings.rateLimits.rules=[]),e.formSettings.rateLimits.rules.push({label:``,maxRequests:200,duration:3,audience:``}),e.formSettings.rateLimits.rules.length==1&&(e.formSettings.rateLimits.enabled=!0)}function o(n){e.formSettings.rateLimits.rules.splice(n,1),e.formSettings.rateLimits.rules.length||(e.formSettings.rateLimits.enabled=!1)}let s=[];return t.details({pbEvent:`rateLimitAccordion`,className:`accordion rate-limit-accordion`,name:`settingsAccordion`,onmount:()=>{s.push(watch(()=>JSON.stringify(e.formSettings.rateLimits.rules),()=>{app.store.errors?.rateLimits?.rules&&delete app.store.errors.rateLimits}))},onunmount:()=>{s.forEach(e=>e?.unwatch())}},t.summary(null,t.i({className:`ri-pulse-fill`,ariaHidden:!0}),t.span({className:`txt`},`Rate limiting`),t.div({className:`flex-fill`}),()=>e.formSettings.rateLimits.enabled?t.span({className:`label success`},`Enabled`):t.span({className:`label`},`Disabled`),()=>{if(!app.utils.isEmpty(app.store.errors?.rateLimits))return t.i({className:`ri-error-warning-fill txt-danger`,ariaDescription:app.attrs.tooltip(`Has errors`,`left`)})}),t.div({className:`grid sm`},t.div({className:`col-lg-12`},t.div({className:`field`},t.input({id:`rateLimits.enabled`,name:`rateLimits.enabled`,type:`checkbox`,className:`switch`,checked:()=>e.formSettings.rateLimits.enabled||!1,onchange:n=>e.formSettings.rateLimits.enabled=n.target.checked}),t.label({htmlFor:`rateLimits.enabled`},t.span({className:`txt`},`Enable`),t.small({className:`txt-hint`},` (experimental)`)))),t.div({className:`col-lg-12`},t.div({className:`rate-limit-table-wrapper`},t.table({className:`rate-limit-table`},t.thead({hidden:()=>!e.formSettings.rateLimits.rules?.length},t.tr(null,t.th({className:`col-label`},`Rate limit label`),t.th({className:`col-requests`},`Max requests`,t.br(),t.small(null,`(per IP)`)),t.th({className:`col-duration`},`Interval`,t.br(),t.small(null,`(in seconds)`)),t.th({className:`col-audience`},`Targeted users`),t.th({className:`col-action`}))),t.tbody(null,()=>{let i=[],a=e.formSettings.rateLimits.rules||[];for(let e=0;es.label,oninput:e=>s.label=e.target.value}),t.datalist({id:`rateLimits.rules.`+e+`.label_list`},()=>r.predefinedTags.map(e=>t.option({value:e.value},e.label||``))))),t.td({className:`col-requests`},t.div({className:`field`},t.input({type:`number`,required:!0,placeholder:`Max requests*`,className:`inline-error`,min:1,step:1,name:`rateLimits.rules.`+e+`.maxRequests`,value:()=>s.maxRequests||0,oninput:e=>s.maxRequests=parseInt(e.target.value,10)}))),t.td({className:`col-duration`},t.div({className:`field`},t.input({type:`number`,required:!0,placeholder:`Interval*`,className:`inline-error`,min:1,step:1,name:`rateLimits.rules.`+e+`.duration`,value:()=>s.duration,oninput:e=>s.duration=parseInt(e.target.value,10)}))),t.td({className:`col-audience`},t.div({className:`field`},app.components.select({name:`rateLimits.rules.`+e+`.audience`,className:`inline-error`,options:n,required:!0,value:()=>s.audience||``,onchange:e=>{s.audience=e?.[0]?.value}}))),t.td({className:`col-action`},t.button({type:`button`,araiaDescription:app.attrs.tooltip(`Remove rule`),className:`btn sm secondary transparent circle`,onclick:()=>o(e)},t.i({className:`ri-close-line`})))))}return i}))),t.div({className:`flex m-t-sm`},t.button({type:`button`,className:`btn secondary sm`,onclick:()=>a()},t.i({className:`ri-add-line`,ariaHidden:!0}),t.span({className:`txt`},`Add rate limit rule`)),t.button({type:`button`,className:`link-hint txt-sm m-l-auto`,onclick:()=>Yr()},t.em(null,`Learn more about the rate limit rules`))))))}function $r(e){let n=[`X-Forwarded-For`,`Fly-Client-IP`,`CF-Connecting-IP`],r=[{label:`Use leftmost IP`,value:!0},{label:`Use rightmost IP`,value:!1}],i=store({isLoading:!1,realIP:``,possibleProxyHeader:``,get suggestedProxyHeaders(){return i.possibleProxyHeader?[i.possibleProxyHeader].concat(n.filter(e=>e!=i.possibleProxyHeader)):n},get isEnabled(){return!app.utils.isEmpty(e.formSettings.trustedProxy?.headers)}});a();async function a(){i.isLoading=!0;try{let e=await app.pb.health.check({requestKey:`loadProxyInfo`});i.realIP=e.data?.realIP||``,i.possibleProxyHeader=e.data?.possibleProxyHeader||``,i.isLoading=!1}catch(e){e.isAbort||(app.checkApiError(e),i.isLoading=!1)}}return t.details({pbEvent:`trustedProxyAccordion`,className:`accordion trusted-proxy-accordion`,name:`settingsAccordion`,open:()=>i.isLoading?!1:null},t.summary(null,t.i({className:`ri-route-line`,ariaHidden:!0}),t.span({className:`txt`},`User IP proxy headers`),()=>{if(i.isLoading)return t.span({className:`loader sm`});if(!i.isEnabled&&i.possibleProxyHeader)return t.i({className:`ri-alert-line txt-warning`,ariaDescription:app.attrs.tooltip(`Detected proxy header. It is recommend to list it as trusted.`,`right`)});if(i.isEnabled&&i.possibleProxyHeader&&!e.formSettings.trustedProxy.headers.includes(i.possibleProxyHeader))return t.i({className:`ri-alert-line txt-hint`,ariaDescription:app.attrs.tooltip(`The configured proxy header doesn't match with the detected one.`,`right`)})},t.div({className:`flex-fill`}),()=>i.isEnabled?t.span({className:`label success`},`Enabled`):t.span({className:`label`},`Disabled`),()=>{if(!app.utils.isEmpty(app.store.errors?.trustedProxy))return t.i({className:`ri-error-warning-fill txt-danger`,ariaDescription:app.attrs.tooltip(`Has errors`,`left`)})}),t.p({className:`m-t-0`},`Below you should see your real IP. If not - configure the correct proxy header for your environment.`),t.div({hidden:()=>i.isLoading,className:`alert info m-b-sm`},t.div({className:`flex gap-5`},t.span(null,`Resolved user IP:`),t.strong(null,()=>i.realIP||`N/A`)),t.div({className:`flex gap-5`},t.span(null,`Detected proxy header:`),t.strong(null,()=>i.possibleProxyHeader||`N/A`))),t.div({className:`content m-b-sm`},t.p(null,` When PocketBase is deployed on platforms like Fly or it is accessible through proxies such as NGINX, requests from different users will originate from the same IP address (the IP of the proxy diff --git a/ui/dist/index.html b/ui/dist/index.html index 533d25b8..19ab1233 100644 --- a/ui/dist/index.html +++ b/ui/dist/index.html @@ -13,7 +13,7 @@ - + diff --git a/ui/src/fields/text/input.js b/ui/src/fields/text/input.js index d2082a23..361d16e4 100644 --- a/ui/src/fields/text/input.js +++ b/ui/src/fields/text/input.js @@ -73,7 +73,7 @@ export function input(props) { const autodateValues = []; for (let f of autodateFields) { - autodateValues.push(`${f.name}: ${app.utils.stringifyValue(props.record[f.name])}`); + autodateValues.push(`${f.name}: ${app.utils.displayValue(props.record[f.name])}`); } return t.div( diff --git a/ui/src/logs/logPreviewModal.js b/ui/src/logs/logPreviewModal.js index ad104875..cba543f8 100644 --- a/ui/src/logs/logPreviewModal.js +++ b/ui/src/logs/logPreviewModal.js @@ -239,7 +239,7 @@ function logPreviewModal(logIdOrModel, settings) { return t.span({ className: "txt", - textContent: app.utils.stringifyValue(value, "N/A", 1000), + textContent: app.utils.displayValue(value, 1000), }); }), t.td({ className: "col-copy min-width" }, app.components.copyButton(value)), diff --git a/ui/src/logs/logsList.js b/ui/src/logs/logsList.js index 8e18f3d3..89e12c32 100644 --- a/ui/src/logs/logsList.js +++ b/ui/src/logs/logsList.js @@ -374,18 +374,12 @@ export function logsList(logsSettings) { if (app.utils.logDataFormatters[keyItem.key]) { value = app.utils.logDataFormatters[keyItem.key](log); } else { - value = app.utils.stringifyValue( - log.data[keyItem.key], - "N/A", - 80, - ); + value = app.utils.displayValue(log.data[keyItem.key], 80); } labels.push( t.span( - { - className: `label sm ${keyItem.label || ""}`, - }, + { className: `label sm ${keyItem.label || ""}` }, `${keyItem.key}: ${value}`, ), ); diff --git a/ui/src/records/recordPreviewModal.js b/ui/src/records/recordPreviewModal.js index 3c166b1b..2e4c7909 100644 --- a/ui/src/records/recordPreviewModal.js +++ b/ui/src/records/recordPreviewModal.js @@ -213,7 +213,7 @@ function recordPreviewModal(rawRecord, modalSettings) { }); } - return app.utils.stringifyValue(data.record[f.name]); + return app.utils.displayValue(data.record[f.name], 1000); }, ), ); diff --git a/ui/src/utils.js b/ui/src/utils.js index 3257cc2b..e32f356c 100644 --- a/ui/src/utils.js +++ b/ui/src/utils.js @@ -606,47 +606,36 @@ const utils = { }, /** - * Stringifies the provided value or fallback to missingValue in case it is empty. + * Returns a stringified truncated version of the provided value + * or fallback to `missingValue` in case it is empty. * * @param {Mixed} val + * @param {number} [truncateLength] * @param {string} [missingValue] - * @param {string} [truncateLength] * @return {string} */ - stringifyValue(val, missingValue = "N/A", truncateLength = 150) { + displayValue(val, truncateLength = 150, missingValue = "N/A") { + // check the raw value for "emptiness" if (utils.isEmpty(val)) { return missingValue; } - if (typeof val == "number") { - return "" + val; - } - - if (typeof val == "boolean") { - return val ? "True" : "False"; - } - if (typeof val == "string") { - val = val.indexOf("<") >= 0 ? utils.plainText(val) : val; - return utils.truncate(val, truncateLength) || missingValue; - } - - // plain array - if (Array.isArray(val) && typeof val[0] != "object") { - return utils.truncate(val.join(","), truncateLength); - } - - // json - if (typeof val == "object") { + // already a string + } else if (typeof val == "boolean") { + val = val ? "True" : "False"; + } else if (Array.isArray(val) && typeof val[0] != "object") { + // assuming primitive array values + val = val.map((child) => utils.displayValue(child, truncateLength, missingValue)).join(", "); + } else { try { - return utils.truncate(JSON.stringify(val), truncateLength) || missingValue; + val = JSON.stringify(val) || ""; } catch (_) { - return missingValue; + val = "" + val; } } - // return as it is - return val; + return val ? utils.truncate(val, truncateLength) : missingValue; }, /**