
window.ls=window.ls||{};window.ls.container=function(){let stock={};let listeners={};let namespaces={};let set=function(name,object,singleton,watch=true){if(typeof name!=='string'){throw new Error('var name must be of type string');}
if(typeof singleton!=='boolean'){throw new Error('var singleton "'+singleton+'" of service "'+name+'" must be of type boolean');}
stock[name]={name:name,object:object,singleton:singleton,instance:null,watch:watch,};if(!watch){return this;}
let binds=listeners[name]||{};for(let key in binds){if(binds.hasOwnProperty(key)){document.dispatchEvent(new CustomEvent(key));}}
return this;};let get=function(name){let service=(undefined!==stock[name])?stock[name]:null;if(null==service){return null;}
if(service.instance){return service.instance;}
let instance=(typeof service.object==='function')?this.resolve(service.object):service.object;let skip=false;if(service.watch&&name!=='window'&&name!=='document'&&name!=='element'&&typeof instance==='object'&&instance!==null){let handler={name:service.name,watch:function(){},get:function(target,key){if(key==="__name"){return this.name;}
if(key==="__watch"){return this.watch;}
if(key==="__proxy"){return true;}
if(key!=='constructor'&&typeof target[key]==='function'&&([Map,Set,WeakMap,WeakSet].includes(target.constructor))){return target[key].bind(target);}
if(typeof target[key]==='object'&&target[key]!==null&&!target[key].__proxy){let handler=Object.assign({},this);handler.name=handler.name+'.'+key;return new Proxy(target[key],handler)}
else{return target[key];}},set:function(target,key,value,receiver){if(key==="__name"){return this.name=value;}
if(key==="__watch"){return this.watch=value;}
target[key]=value;let path=receiver.__name+'.'+key;document.dispatchEvent(new CustomEvent(path+'.changed'));if(skip){return true;}
skip=true;container.set('$prop',key,true);container.set('$value',value,true);container.resolve(this.watch);container.set('$key',null,true);container.set('$value',null,true);skip=false;return true;},};instance=new Proxy(instance,handler);}
if(service.singleton){service.instance=instance;}
return instance;};let resolve=function(target){if(!target){return()=>{};}
let self=this;const REGEX_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const REGEX_FUNCTION_PARAMS=/(?:\s*(?:function\s*[^(]*)?\s*)((?:[^'"]|(?:(?:(['"])(?:(?:.*?[^\\]\2)|\2))))*?)\s*(?=(?:=>)|{)/m;const REGEX_PARAMETERS_VALUES=/\s*([\w\\$]+)\s*(?:=\s*((?:(?:(['"])(?:\3|(?:.*?[^\\]\3)))((\s*\+\s*)(?:(?:(['"])(?:\6|(?:.*?[^\\]\6)))|(?:[\w$]*)))*)|.*?))?\s*(?:,|$)/gm;function getParams(func){let functionAsString=func.toString();let params=[];let match;functionAsString=functionAsString.replace(REGEX_COMMENTS,'');functionAsString=functionAsString.match(REGEX_FUNCTION_PARAMS)[1];if(functionAsString.charAt(0)==='('){functionAsString=functionAsString.slice(1,-1);}
while(match=REGEX_PARAMETERS_VALUES.exec(functionAsString)){params.push(match[1]);}
return params;}
let args=getParams(target);return target.apply(target,args.map(function(value){return self.get(value.trim());}));};let path=function(path,value,type){type=(type)?type:'assign';path=container.scope(path).split('.');let name=path.shift();let object=container.get(name);let result=null;while(path.length>1){if(!object){return null;}
object=object[path.shift()];}
let shift=path.shift();if(value!==null&&value!==undefined&&object&&shift&&(object[shift]!==undefined||object[shift]!==null)){switch(type){case'append':if(!Array.isArray(object[shift])){object[shift]=[];}
object[shift].push(value);break;case'prepend':if(!Array.isArray(object[shift])){object[shift]=[];}
object[shift].unshift(value);break;case'splice':if(!Array.isArray(object[shift])){object[shift]=[];}
object[shift].splice(value,1);break;default:object[shift]=value;}
return true;}
if(!object){return null;}
if(!shift){result=object;}
else{return object[shift];}
return result;};let bind=function(element,path,callback){let event=container.scope(path)+'.changed';let service=event.split('.').slice(0,1).pop();let debug=element.getAttribute('data-debug')||false;listeners[service]=listeners[service]||{};listeners[service][event]=true;let printer=(function(x){return function(){if(!document.body.contains(element)){element=null;document.removeEventListener(event,printer,false);return false;}
let oldNamespaces=namespaces;namespaces=x;callback();namespaces=oldNamespaces;}}(Object.assign({},namespaces)));document.addEventListener(event,printer);};let addNamespace=function(key,scope){namespaces[key]=scope;return this;}
let removeNamespace=function(key){delete namespaces[key];return this;}
let scope=function(path){for(let[key,value]of Object.entries(namespaces)){path=(path.indexOf('.')>-1)?path.replace(key+'.',value+'.'):path.replace(key,value);}
return path;}
let container={set:set,get:get,resolve:resolve,path:path,bind:bind,scope:scope,addNamespace:addNamespace,removeNamespace:removeNamespace,stock:stock,listeners:listeners,namespaces:namespaces,};set('container',container,true,false);return container;}();window.ls.container.set('http',function(document){let globalParams=[],globalHeaders=[];let addParam=function(url,param,value){param=encodeURIComponent(param);let a=document.createElement('a');param+=(value?"="+encodeURIComponent(value):"");a.href=url;a.search+=(a.search?"&":"")+param;return a.href;};let request=function(method,url,headers,payload,progress){let i;if(-1===['GET','POST','PUT','DELETE','TRACE','HEAD','OPTIONS','CONNECT','PATCH'].indexOf(method)){throw new Error('var method must contain a valid HTTP method name');}
if(typeof url!=='string'){throw new Error('var url must be of type string');}
if(typeof headers!=='object'){throw new Error('var headers must be of type object');}
if(typeof url!=='string'){throw new Error('var url must be of type string');}
for(i=0;i<globalParams.length;i++){url=addParam(url,globalParams[i].key,globalParams[i].value);}
return new Promise(function(resolve,reject){let xmlhttp=new XMLHttpRequest();xmlhttp.open(method,url,true);for(i=0;i<globalHeaders.length;i++){xmlhttp.setRequestHeader(globalHeaders[i].key,globalHeaders[i].value);}
for(let key in headers){if(headers.hasOwnProperty(key)){xmlhttp.setRequestHeader(key,headers[key]);}}
xmlhttp.onload=function(){if(4===xmlhttp.readyState&&200===xmlhttp.status){resolve(xmlhttp.response);}
else{document.dispatchEvent(new CustomEvent('http-'+method.toLowerCase()+'-'+xmlhttp.status));reject(new Error(xmlhttp.statusText));}};if(progress){xmlhttp.addEventListener('progress',progress);xmlhttp.upload.addEventListener('progress',progress,false);}
xmlhttp.onerror=function(){reject(new Error("Network Error"));};xmlhttp.send(payload);})};return{'get':function(url){return request('GET',url,{},'')},'post':function(url,headers,payload){return request('POST',url,headers,payload)},'put':function(url,headers,payload){return request('PUT',url,headers,payload)},'patch':function(url,headers,payload){return request('PATCH',url,headers,payload)},'delete':function(url){return request('DELETE',url,{},'')},'addGlobalParam':function(key,value){globalParams.push({key:key,value:value});},'addGlobalHeader':function(key,value){globalHeaders.push({key:key,value:value});}}},true,false);window.ls.container.set('cookie',function(document){function get(name){let value="; "+document.cookie,parts=value.split("; "+name+"=");if(parts.length===2){return parts.pop().split(";").shift();}
return null;}
function set(name,value,days){let date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));let expires=(0<days)?'expires='+date.toUTCString():'expires=0';document.cookie=name+"="+value+";"+expires+";path=/";return this;}
return{'get':get,'set':set}},true,false);window.ls.container.set('view',function(http,container){let stock={};let execute=function(view,node,container){container.set('element',node,true,false);container.resolve(view.controller);if(true!==view.repeat){node.removeAttribute(view.selector);}};let parse=function(node,skip,callback){if(node.tagName==='SCRIPT'){return;}
if(node.attributes&&skip!==true){let attrs=[];let attrsLen=node.attributes.length;for(let x=0;x<attrsLen;x++){attrs.push(node.attributes[x].nodeName);}
if(1!==node.nodeType){return;}
if(attrs&&attrsLen){for(let x=0;x<attrsLen;x++){if(node.$lsSkip===true){break;}
let pointer=(!/Edge/.test(navigator.userAgent))?x:(attrsLen-1)-x;let length=attrsLen;let attr=attrs[pointer];if(!stock[attr]){continue;}
let comp=stock[attr];if(typeof comp.template==="function"){comp.template=container.resolve(comp.template);}
if(!comp.template){(function(comp,node,container){execute(comp,node,container);})(comp,node,container);if(length!==attrsLen){x--;}
if(callback){callback();}
continue;}
node.classList.remove('load-end');node.classList.add('load-start');node.$lsSkip=true;http.get(comp.template).then(function(node,comp){return function(data){node.$lsSkip=false;node.innerHTML=data;node.classList.remove('load-start');node.classList.add('load-end');(function(comp,node,container){execute(comp,node,container);})(comp,node,container);parse(node,true);if(callback){callback();}}}(node,comp),function(error){throw new Error('Failed to load comp template: '+error.message);});}}}
if(true===node.$lsSkip){return;}
let list=(node)?node.childNodes:[];if(node.$lsSkip===true){list=[];}
for(let i=0;i<list.length;i++){let child=list[i];parse(child);}};return{stock:stock,add:function(object){if(typeof object!=='object'){throw new Error('object must be of type object');}
let defaults={'selector':'','controller':function(){},'template':'','repeat':false,'protected':false};for(let prop in defaults){if(!defaults.hasOwnProperty(prop)){continue;}
if(prop in object){continue;}
object[prop]=defaults[prop];}
if(!object.selector){throw new Error('View component is missing a selector attribute');}
stock[object.selector]=object;return this;},render:function(element,callback){parse(element,false,callback);element.dispatchEvent(new window.Event('rendered',{bubbles:false}));}}},true,false);window.ls.container.set('router',function(window){let getJsonFromUrl=function(URL){let query;if(URL){let pos=location.search.indexOf('?');if(pos===-1)return[];query=location.search.substr(pos+1);}else{query=location.search.substr(1);}
let result={};query.split('&').forEach(function(part){if(!part){return;}
part=part.split('+').join(' ');let eq=part.indexOf('=');let key=eq>-1?part.substr(0,eq):part;let val=eq>-1?decodeURIComponent(part.substr(eq+1)):'';let from=key.indexOf('[');if(from===-1){result[decodeURIComponent(key)]=val;}
else{let to=key.indexOf(']');let index=decodeURIComponent(key.substring(from+1,to));key=decodeURIComponent(key.substring(0,from));if(!result[key]){result[key]=[];}
if(!index){result[key].push(val);}
else{result[key][index]=val;}}});return result;};let states=[];let params=getJsonFromUrl(window.location.search);let hash=window.location.hash;let current=null;let previous=null;let getPrevious=()=>previous;let getCurrent=()=>current;let setPrevious=(value)=>{previous=value;return this;};let setCurrent=(value)=>{current=value;return this;};let setParam=function(key,value){params[key]=value;return this;};let getParam=function(key,def){if(key in params){return params[key];}
return def;};let getParams=function(){return params;};let getURL=function(){return window.location.href;};let add=function(path,view){if(typeof path!=='string'){throw new Error('path must be of type string');}
if(typeof view!=='object'){throw new Error('view must be of type object');}
states[states.length++]={path:path,view:view};return this;};let match=function(location){let url=location.pathname;if(url.endsWith('/')){url=url.slice(0,-1);}
states.sort(function(a,b){return b.path.length-a.path.length;});states.sort(function(a,b){let n=b.path.split('/').length-a.path.split('/').length;if(n!==0){return n;}
return b.path.length-a.path.length;});for(let i=0;i<states.length;i++){let value=states[i];value.path=(value.path.substring(0,1)!=='/')?location.pathname+value.path:value.path;let match=new RegExp("^"+value.path.replace(/:[^\s/]+/g,'([\\w-]+)')+"$");let found=url.match(match);if(found){previous=current;current=value;return value;}}
return null};let change=function(URL,replace){if(!replace){window.history.pushState({},'',URL);}
else{window.history.replaceState({},'',URL);}
window.dispatchEvent(new PopStateEvent('popstate',{}));return this;};let reload=function(){return change(window.location.href);};return{setParam:setParam,getParam:getParam,getParams:getParams,getURL:getURL,add:add,change:change,reload:reload,match:match,getCurrent:getCurrent,setCurrent:setCurrent,getPrevious:getPrevious,setPrevious:setPrevious,params:params,hash:hash,reset:function(){this.params=getJsonFromUrl(window.location.search);this.hash=window.location.hash;}};},true,true);window.ls.container.set('expression',function(container,filter){let paths=[];return{regex:/(\{{.*?\}})/gi,parse:function(string,def,cast=false){def=def||'';paths=[];return string.replace(this.regex,match=>{let reference=match.substring(2,match.length-2).replace('[\'','.').replace('\']','').trim();reference=reference.split('|');let path=container.scope((reference[0]||''));let result=container.path(path);path=container.scope(path);if(!paths.includes(path)){paths.push(path);}
if(reference.length>=2){for(let i=1;i<reference.length;i++){result=filter.apply(reference[i],result);}}
if(null===result||undefined===result){result=def;}
else if(typeof result==='object'){result=JSON.stringify(result,null,4);}
else if(((typeof result==='object')||(typeof result==='string'))&&cast){result='\''+result+'\'';}
return result;}).replace(/\\{/g,"{").replace(/\\}/g,"}");},getPaths:()=>paths,}},true,false);window.ls.container.set('filter',function(container){let filters={};let add=function(name,callback){filters[name]=callback;return this;};let apply=function(name,value){container.set('$value',value,true,false);return container.resolve(filters[name]);};add('uppercase',($value)=>{if(typeof $value!=='string'){return $value;}
return $value.toUpperCase();});add('lowercase',($value)=>{if(typeof $value!=='string'){return $value;}
return $value.toLowerCase();});return{add:add,apply:apply}},true,false);window.ls.container.get('filter').add('escape',$value=>{if(typeof $value!=='string'){return $value;}
return $value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;').replace(/\'/g,'&#39;').replace(/\//g,'&#x2F;');});window.ls=window.ls||{};window.ls.container.set('window',window,true,false).set('document',window.document,true,false).set('element',window.document,true,false);window.ls.run=function(window){try{this.view.render(window.document);}
catch(error){let handler=window.ls.container.resolve(this.error);handler(error);}};window.ls.error=()=>{return error=>{console.error('ls-error',error.message,error.stack,error.toString());}};window.ls.router=window.ls.container.get('router');window.ls.view=window.ls.container.get('view');window.ls.filter=window.ls.container.get('filter');window.ls.container.get('view').add({selector:'data-ls-router',controller:function(element,window,document,view,router){let firstFromServer=(element.getAttribute('data-first-from-server')==='true');let scope={selector:'data-ls-scope',template:false,repeat:true,controller:function(){},};let init=function(route){let count=parseInt(element.getAttribute('data-ls-scope-count')||0);element.setAttribute('data-ls-scope-count',count+1);window.scrollTo(0,0);if(window.document.body.scrollTo){window.document.body.scrollTo(0,0);}
router.reset();if(null===route){return;}
scope.template=(undefined!==route.view.template)?route.view.template:null;scope.controller=(undefined!==route.view.controller)?route.view.controller:function(){};document.dispatchEvent(new CustomEvent('state-change'));if(firstFromServer&&null===router.getPrevious()){scope.template='';document.dispatchEvent(new CustomEvent('state-changed'));}
else if(count===1){view.render(element,function(){document.dispatchEvent(new CustomEvent('state-changed'));});}
else if(null!==router.getPrevious()){view.render(element,function(){document.dispatchEvent(new CustomEvent('state-changed'));});}};let findParent=function(tagName,el){if((el.nodeName||el.tagName).toLowerCase()===tagName.toLowerCase()){return el;}
while(el=el.parentNode){if((el.nodeName||el.tagName).toLowerCase()===tagName.toLowerCase()){return el;}}
return null;};element.removeAttribute('data-ls-router');element.setAttribute('data-ls-scope','');element.setAttribute('data-ls-scope-count',1);view.add(scope);document.addEventListener('click',function(event){let target=findParent('a',event.target);if(!target){return false;}
if(!target.href){return false;}
if((event.metaKey)){return false;}
if((target.hasAttribute('target'))&&('_blank'===target.getAttribute('target'))){return false;}
if(target.hostname!==window.location.hostname){return false;}
let route=router.match(target);if(null===route){return false;}
event.preventDefault();if(window.location===target.href){return false;}
route.view.state=(undefined===route.view.state)?true:route.view.state;if(true===route.view.state){if(router.getPrevious()&&router.getPrevious().view&&(router.getPrevious().view.scope!==route.view.scope)){window.location.href=target.href;return false;}
window.history.pushState({},'Unknown',target.href);}
init(route);return true;});window.addEventListener('popstate',function(){init(router.match(window.location));});window.addEventListener('hashchange',function(){init(router.match(window.location));});init(router.match(window.location));}});window.ls.container.get('view').add({selector:'data-ls-attrs',controller:function(element,expression,container){let attrs=element.getAttribute('data-ls-attrs').trim().split(',');let paths=[];let debug=element.getAttribute('data-debug')||false;let check=()=>{container.set('element',element,true,false);if(debug){console.info('debug-ls-attrs attributes:',attrs);}
for(let i=0;i<attrs.length;i++){let attr=attrs[i];let key=expression.parse((attr.substring(0,attr.indexOf('='))||attr));paths=paths.concat(expression.getPaths());let value='';if(attr.indexOf('=')>-1){value=expression.parse(attr.substring(attr.indexOf('=')+1))||'';paths=paths.concat(expression.getPaths());}
if(!key){return null;}
element.setAttribute(key,value);}};check();for(let i=0;i<paths.length;i++){let path=paths[i].split('.');while(path.length){container.bind(element,path.join('.'),check);path.pop();}}}});window.ls.container.get('view').add({selector:'data-ls-bind',controller:function(element,expression,container){let debug=element.getAttribute('data-debug')||false;let echo=function(value,bind=true){if(element.tagName==='INPUT'||element.tagName==='SELECT'||element.tagName==='BUTTON'||element.tagName==='TEXTAREA'){let type=element.getAttribute('type');if('radio'===type){if(value.toString()===element.value){element.setAttribute('checked','checked');}
else{element.removeAttribute('checked');}
if(bind){element.addEventListener('change',()=>{for(let i=0;i<paths.length;i++){if(element.checked){value=element.value;}
container.path(paths[i],value);}});}
return;}
if('checkbox'===type){if(typeof value==='boolean'||value==='true'||value==='false'){if(value===true||value==='true'){element.setAttribute('checked','checked');element.checked=true;}
else{element.removeAttribute('checked');element.checked=false;}}
else{try{value=JSON.parse(value);element.checked=(Array.isArray(value)&&(value.indexOf(element.value)>-1));value=element.value;}
catch{return null;}}
if(bind){element.addEventListener('change',()=>{for(let i=0;i<paths.length;i++){let value=container.path(paths[i]);let index=value.indexOf(element.value);if(element.checked&&index<0){value.push(element.value);}
if(!element.checked&&index>-1){value.splice(index,1);}
container.path(paths[i],value);}});}
return;}
if(element.value!==value){element.value=value;element.dispatchEvent(new Event('change'));}
if(bind){element.addEventListener('input',sync);element.addEventListener('change',sync);}}
else{if(element.textContent!=value){element.textContent=value;}}};let sync=(()=>{return()=>{if(debug){console.info('debug-ls-bind','sync-path',paths);console.info('debug-ls-bind','sync-syntax',syntax);console.info('debug-ls-bind','sync-syntax-parsed',parsedSyntax);console.info('debug-ls-bind','sync-value',element.value);}
for(let i=0;i<paths.length;i++){if('{{'+paths[i]+'}}'!==parsedSyntax){if(debug){console.info('debug-ls-bind','sync-skipped-path',paths[i]);console.info('debug-ls-bind','sync-skipped-syntax',syntax);console.info('debug-ls-bind','sync-skipped-syntax-parsed',parsedSyntax);}
continue;}
if(debug){console.info('debug-ls-bind','sync-loop-path',paths[i]);console.info('debug-ls-bind','sync-loop-syntax',parsedSyntax);}
container.path(paths[i],element.value);}}})();let syntax=element.getAttribute('data-ls-bind');let parsedSyntax=container.scope(syntax);let unsync=(!!element.getAttribute('data-unsync'))||false;let result=expression.parse(syntax);let paths=expression.getPaths();echo(result,!unsync);element.addEventListener('looped',function(){echo(expression.parse(parsedSyntax),false);});for(let i=0;i<paths.length;i++){let path=paths[i].split('.');if(debug){console.info('debug-ls-bind','bind-path',path);console.info('debug-ls-bind','bind-syntax',syntax);}
while(path.length){container.bind(element,path.join('.'),()=>{echo(expression.parse(parsedSyntax),false);});path.pop();}}}});window.ls.container.get('view').add({selector:'data-ls-if',controller:function(element,expression,container,view){let result='';let syntax=element.getAttribute('data-ls-if')||'';let debug=element.getAttribute('data-debug')||false;let paths=[];let check=()=>{if(debug){console.info('debug-ls-if',expression.parse(syntax.replace(/(\r\n|\n|\r)/gm,' '),'undefined',true));}
try{result=(eval(expression.parse(syntax.replace(/(\r\n|\n|\r)/gm,' '),'undefined',true)));}
catch(error){throw new Error('Failed to evaluate expression "'+syntax+' (resulted with: "'+result+'")": '+error);}
if(debug){console.info('debug-ls-if result:',result);}
paths=expression.getPaths();let prv=element.$lsSkip;element.$lsSkip=!result;if(!result){element.style.visibility='hidden';element.style.display='none';}
else{element.style.removeProperty('display');element.style.removeProperty('visibility');}
if(prv===true&&element.$lsSkip===false){view.render(element)}};check();for(let i=0;i<paths.length;i++){let path=paths[i].split('.');while(path.length){container.bind(element,path.join('.'),check);path.pop();}}}});window.ls.container.get('view').add({selector:'data-ls-loop',template:false,nested:false,controller:function(element,view,container,window,expression){let expr=expression.parse(element.getAttribute('data-ls-loop'));let as=element.getAttribute('data-ls-as');let key=element.getAttribute('data-ls-key')||'$index';let limit=parseInt(expression.parse(element.getAttribute('data-limit')||'')||-1);let debug=element.getAttribute('data-debug')||false;let echo=function(){let array=container.path(expr);let counter=0;array=(!array)?[]:array;let watch=!!(array&&array.__proxy);while(element.hasChildNodes()){element.removeChild(element.lastChild);element.lastChild=null;}
if(array instanceof Array&&typeof array!=='object'){throw new Error('Reference value must be array or object. '+(typeof array)+' given');}
let children=[];element.$lsSkip=true;element.style.visibility=(0===array.length&&element.style.visibility=='')?'hidden':'visible';for(let prop in array){if(counter==limit){break;}
counter++;if(!array.hasOwnProperty(prop)){continue;}
children[prop]=template.cloneNode(true);element.appendChild(children[prop]);(index=>{let context=expr+'.'+index;container.addNamespace(as,context);if(debug){console.info('debug-ls-loop','index',index);console.info('debug-ls-loop','context',context);console.info('debug-ls-loop','context-path',container.path(context).name);console.info('debug-ls-loop','namespaces',container.namespaces);}
container.set(as,container.path(context),true,watch);container.set(key,index,true,false);view.render(children[prop]);container.removeNamespace(as);})(prop);}
element.dispatchEvent(new Event('looped'));};let template=(element.children.length===1)?element.children[0]:window.document.createElement('li');echo();container.bind(element,expr+'.length',echo);let path=(expr+'.length').split('.');while(path.length){container.bind(element,path.join('.'),echo);path.pop();}}});window.ls.container.get('view').add({selector:'data-ls-template',template:false,controller:function(element,view,http,expression,document,container){let template=element.getAttribute('data-ls-template')||'';let type=element.getAttribute('data-type')||'url';let debug=element.getAttribute('data-debug')||false;let paths=[];let check=function(init=false){let source=expression.parse(template);paths=expression.getPaths();element.innerHTML='';if('script'===type){let inlineTemplate=document.getElementById(source);if(inlineTemplate&&inlineTemplate.innerHTML){element.innerHTML=inlineTemplate.innerHTML;element.dispatchEvent(new CustomEvent('template-loaded',{bubbles:true,cancelable:false}));}
else{if(debug){console.error('Missing template "'+source+'"');}}
if(!init){view.render(element);}
return;}
http.get(source).then(function(element){return function(data){element.innerHTML=data;view.render(element);element.dispatchEvent(new CustomEvent('template-loaded',{bubbles:true,cancelable:false}));}}(element),function(){throw new Error('Failed loading template');});};check(true);for(let i=0;i<paths.length;i++){let path=paths[i].split('.');while(path.length){container.bind(element,path.join('.'),check);path.pop();}}}});(()=>{var flushPending=false;var flushing=false;var queue=[];function scheduler(callback){queueJob(callback);}
function queueJob(job){if(!queue.includes(job))
queue.push(job);queueFlush();}
function queueFlush(){if(!flushing&&!flushPending){flushPending=true;queueMicrotask(flushJobs);}}
function flushJobs(){flushPending=false;flushing=true;for(let i=0;i<queue.length;i++){queue[i]();}
queue.length=0;flushing=false;}
var reactive;var effect;var release;var raw;var shouldSchedule=true;function disableEffectScheduling(callback){shouldSchedule=false;callback();shouldSchedule=true;}
function setReactivityEngine(engine){reactive=engine.reactive;release=engine.release;effect=(callback)=>engine.effect(callback,{scheduler:(task)=>{if(shouldSchedule){scheduler(task);}else{task();}}});raw=engine.raw;}
function overrideEffect(override){effect=override;}
function elementBoundEffect(el){let cleanup2=()=>{};let wrappedEffect=(callback)=>{let effectReference=effect(callback);if(!el._x_effects){el._x_effects=new Set();el._x_runEffects=()=>{el._x_effects.forEach((i)=>i());};}
el._x_effects.add(effectReference);cleanup2=()=>{if(effectReference===void 0)
return;el._x_effects.delete(effectReference);release(effectReference);};};return[wrappedEffect,()=>{cleanup2();}];}
var onAttributeAddeds=[];var onElRemoveds=[];var onElAddeds=[];function onElAdded(callback){onElAddeds.push(callback);}
function onElRemoved(callback){onElRemoveds.push(callback);}
function onAttributesAdded(callback){onAttributeAddeds.push(callback);}
function onAttributeRemoved(el,name,callback){if(!el._x_attributeCleanups)
el._x_attributeCleanups={};if(!el._x_attributeCleanups[name])
el._x_attributeCleanups[name]=[];el._x_attributeCleanups[name].push(callback);}
function cleanupAttributes(el,names){if(!el._x_attributeCleanups)
return;Object.entries(el._x_attributeCleanups).forEach(([name,value])=>{if(names===void 0||names.includes(name)){value.forEach((i)=>i());delete el._x_attributeCleanups[name];}});}
var observer=new MutationObserver(onMutate);var currentlyObserving=false;function startObservingMutations(){observer.observe(document,{subtree:true,childList:true,attributes:true,attributeOldValue:true});currentlyObserving=true;}
function stopObservingMutations(){flushObserver();observer.disconnect();currentlyObserving=false;}
var recordQueue=[];var willProcessRecordQueue=false;function flushObserver(){recordQueue=recordQueue.concat(observer.takeRecords());if(recordQueue.length&&!willProcessRecordQueue){willProcessRecordQueue=true;queueMicrotask(()=>{processRecordQueue();willProcessRecordQueue=false;});}}
function processRecordQueue(){onMutate(recordQueue);recordQueue.length=0;}
function mutateDom(callback){if(!currentlyObserving)
return callback();stopObservingMutations();let result=callback();startObservingMutations();return result;}
var isCollecting=false;var deferredMutations=[];function deferMutations(){isCollecting=true;}
function flushAndStopDeferringMutations(){isCollecting=false;onMutate(deferredMutations);deferredMutations=[];}
function onMutate(mutations){if(isCollecting){deferredMutations=deferredMutations.concat(mutations);return;}
let addedNodes=[];let removedNodes=[];let addedAttributes=new Map();let removedAttributes=new Map();for(let i=0;i<mutations.length;i++){if(mutations[i].target._x_ignoreMutationObserver)
continue;if(mutations[i].type==="childList"){mutations[i].addedNodes.forEach((node)=>node.nodeType===1&&addedNodes.push(node));mutations[i].removedNodes.forEach((node)=>node.nodeType===1&&removedNodes.push(node));}
if(mutations[i].type==="attributes"){let el=mutations[i].target;let name=mutations[i].attributeName;let oldValue=mutations[i].oldValue;let add2=()=>{if(!addedAttributes.has(el))
addedAttributes.set(el,[]);addedAttributes.get(el).push({name,value:el.getAttribute(name)});};let remove=()=>{if(!removedAttributes.has(el))
removedAttributes.set(el,[]);removedAttributes.get(el).push(name);};if(el.hasAttribute(name)&&oldValue===null){add2();}else if(el.hasAttribute(name)){remove();add2();}else{remove();}}}
removedAttributes.forEach((attrs,el)=>{cleanupAttributes(el,attrs);});addedAttributes.forEach((attrs,el)=>{onAttributeAddeds.forEach((i)=>i(el,attrs));});for(let node of addedNodes){if(removedNodes.includes(node))
continue;onElAddeds.forEach((i)=>i(node));}
for(let node of removedNodes){if(addedNodes.includes(node))
continue;onElRemoveds.forEach((i)=>i(node));}
addedNodes=null;removedNodes=null;addedAttributes=null;removedAttributes=null;}
function addScopeToNode(node,data2,referenceNode){node._x_dataStack=[data2,...closestDataStack(referenceNode||node)];return()=>{node._x_dataStack=node._x_dataStack.filter((i)=>i!==data2);};}
function refreshScope(element,scope){let existingScope=element._x_dataStack[0];Object.entries(scope).forEach(([key,value])=>{existingScope[key]=value;});}
function closestDataStack(node){if(node._x_dataStack)
return node._x_dataStack;if(typeof ShadowRoot==="function"&&node instanceof ShadowRoot){return closestDataStack(node.host);}
if(!node.parentNode){return[];}
return closestDataStack(node.parentNode);}
function mergeProxies(objects){let thisProxy=new Proxy({},{ownKeys:()=>{return Array.from(new Set(objects.flatMap((i)=>Object.keys(i))));},has:(target,name)=>{return objects.some((obj)=>obj.hasOwnProperty(name));},get:(target,name)=>{return(objects.find((obj)=>{if(obj.hasOwnProperty(name)){let descriptor=Object.getOwnPropertyDescriptor(obj,name);if(descriptor.get&&descriptor.get._x_alreadyBound||descriptor.set&&descriptor.set._x_alreadyBound){return true;}
if((descriptor.get||descriptor.set)&&descriptor.enumerable){let getter=descriptor.get;let setter=descriptor.set;let property=descriptor;getter=getter&&getter.bind(thisProxy);setter=setter&&setter.bind(thisProxy);if(getter)
getter._x_alreadyBound=true;if(setter)
setter._x_alreadyBound=true;Object.defineProperty(obj,name,{...property,get:getter,set:setter});}
return true;}
return false;})||{})[name];},set:(target,name,value)=>{let closestObjectWithKey=objects.find((obj)=>obj.hasOwnProperty(name));if(closestObjectWithKey){closestObjectWithKey[name]=value;}else{objects[objects.length-1][name]=value;}
return true;}});return thisProxy;}
function initInterceptors(data2){let isObject2=(val)=>typeof val==="object"&&!Array.isArray(val)&&val!==null;let recurse=(obj,basePath="")=>{Object.entries(Object.getOwnPropertyDescriptors(obj)).forEach(([key,{value,enumerable}])=>{if(enumerable===false||value===void 0)
return;let path=basePath===""?key:`${basePath}.${key}`;if(typeof value==="object"&&value!==null&&value._x_interceptor){obj[key]=value.initialize(data2,path,key);}else{if(isObject2(value)&&value!==obj&&!(value instanceof Element)){recurse(value,path);}}});};return recurse(data2);}
function interceptor(callback,mutateObj=()=>{}){let obj={initialValue:void 0,_x_interceptor:true,initialize(data2,path,key){return callback(this.initialValue,()=>get(data2,path),(value)=>set(data2,path,value),path,key);}};mutateObj(obj);return(initialValue)=>{if(typeof initialValue==="object"&&initialValue!==null&&initialValue._x_interceptor){let initialize=obj.initialize.bind(obj);obj.initialize=(data2,path,key)=>{let innerValue=initialValue.initialize(data2,path,key);obj.initialValue=innerValue;return initialize(data2,path,key);};}else{obj.initialValue=initialValue;}
return obj;};}
function get(obj,path){return path.split(".").reduce((carry,segment)=>carry[segment],obj);}
function set(obj,path,value){if(typeof path==="string")
path=path.split(".");if(path.length===1)
obj[path[0]]=value;else if(path.length===0)
throw error;else{if(obj[path[0]])
return set(obj[path[0]],path.slice(1),value);else{obj[path[0]]={};return set(obj[path[0]],path.slice(1),value);}}}
var magics={};function magic(name,callback){magics[name]=callback;}
function injectMagics(obj,el){Object.entries(magics).forEach(([name,callback])=>{Object.defineProperty(obj,`$${name}`,{get(){return callback(el,{Alpine:alpine_default,interceptor});},enumerable:false});});return obj;}
function tryCatch(el,expression,callback,...args){try{return callback(...args);}catch(e){handleError(e,el,expression);}}
function handleError(error2,el,expression=void 0){Object.assign(error2,{el,expression});console.warn(`Alpine Expression Error: ${error2.message}
  
  ${expression ? 'Expression: "' + expression + '"\n\n' : ""}`,el);setTimeout(()=>{throw error2;},0);}
function evaluate(el,expression,extras={}){let result;evaluateLater(el,expression)((value)=>result=value,extras);return result;}
function evaluateLater(...args){return theEvaluatorFunction(...args);}
var theEvaluatorFunction=normalEvaluator;function setEvaluator(newEvaluator){theEvaluatorFunction=newEvaluator;}
function normalEvaluator(el,expression){let overriddenMagics={};injectMagics(overriddenMagics,el);let dataStack=[overriddenMagics,...closestDataStack(el)];if(typeof expression==="function"){return generateEvaluatorFromFunction(dataStack,expression);}
let evaluator=generateEvaluatorFromString(dataStack,expression,el);return tryCatch.bind(null,el,expression,evaluator);}
function generateEvaluatorFromFunction(dataStack,func){return(receiver=()=>{},{scope={},params=[]}={})=>{let result=func.apply(mergeProxies([scope,...dataStack]),params);runIfTypeOfFunction(receiver,result);};}
var evaluatorMemo={};function generateFunctionFromString(expression,el){if(evaluatorMemo[expression]){return evaluatorMemo[expression];}
let AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;let rightSideSafeExpression=/^[\n\s]*if.*\(.*\)/.test(expression)||/^(let|const)\s/.test(expression)?`(() => { ${expression} })()`:expression;const safeAsyncFunction=()=>{try{return new AsyncFunction(["__self","scope"],`with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`);}catch(error2){handleError(error2,el,expression);return Promise.resolve();}};let func=safeAsyncFunction();evaluatorMemo[expression]=func;return func;}
function generateEvaluatorFromString(dataStack,expression,el){let func=generateFunctionFromString(expression,el);return(receiver=()=>{},{scope={},params=[]}={})=>{func.result=void 0;func.finished=false;let completeScope=mergeProxies([scope,...dataStack]);if(typeof func==="function"){let promise=func(func,completeScope).catch((error2)=>handleError(error2,el,expression));if(func.finished){runIfTypeOfFunction(receiver,func.result,completeScope,params,el);}else{promise.then((result)=>{runIfTypeOfFunction(receiver,result,completeScope,params,el);}).catch((error2)=>handleError(error2,el,expression));}}};}
function runIfTypeOfFunction(receiver,value,scope,params,el){if(typeof value==="function"){let result=value.apply(scope,params);if(result instanceof Promise){result.then((i)=>runIfTypeOfFunction(receiver,i,scope,params)).catch((error2)=>handleError(error2,el,value));}else{receiver(result);}}else{receiver(value);}}
var prefixAsString="x-";function prefix(subject=""){return prefixAsString+subject;}
function setPrefix(newPrefix){prefixAsString=newPrefix;}
var directiveHandlers={};function directive(name,callback){directiveHandlers[name]=callback;}
function directives(el,attributes,originalAttributeOverride){let transformedAttributeMap={};let directives2=Array.from(attributes).map(toTransformedAttributes((newName,oldName)=>transformedAttributeMap[newName]=oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap,originalAttributeOverride)).sort(byPriority);return directives2.map((directive2)=>{return getDirectiveHandler(el,directive2);});}
function attributesOnly(attributes){return Array.from(attributes).map(toTransformedAttributes()).filter((attr)=>!outNonAlpineAttributes(attr));}
var isDeferringHandlers=false;var directiveHandlerStacks=new Map();var currentHandlerStackKey=Symbol();function deferHandlingDirectives(callback){isDeferringHandlers=true;let key=Symbol();currentHandlerStackKey=key;directiveHandlerStacks.set(key,[]);let flushHandlers=()=>{while(directiveHandlerStacks.get(key).length)
directiveHandlerStacks.get(key).shift()();directiveHandlerStacks.delete(key);};let stopDeferring=()=>{isDeferringHandlers=false;flushHandlers();};callback(flushHandlers);stopDeferring();}
function getDirectiveHandler(el,directive2){let noop=()=>{};let handler3=directiveHandlers[directive2.type]||noop;let cleanups=[];let cleanup2=(callback)=>cleanups.push(callback);let[effect3,cleanupEffect]=elementBoundEffect(el);cleanups.push(cleanupEffect);let utilities={Alpine:alpine_default,effect:effect3,cleanup:cleanup2,evaluateLater:evaluateLater.bind(evaluateLater,el),evaluate:evaluate.bind(evaluate,el)};let doCleanup=()=>cleanups.forEach((i)=>i());onAttributeRemoved(el,directive2.original,doCleanup);let fullHandler=()=>{if(el._x_ignore||el._x_ignoreSelf)
return;handler3.inline&&handler3.inline(el,directive2,utilities);handler3=handler3.bind(handler3,el,directive2,utilities);isDeferringHandlers?directiveHandlerStacks.get(currentHandlerStackKey).push(handler3):handler3();};fullHandler.runCleanups=doCleanup;return fullHandler;}
var startingWith=(subject,replacement)=>({name,value})=>{if(name.startsWith(subject))
name=name.replace(subject,replacement);return{name,value};};var into=(i)=>i;function toTransformedAttributes(callback=()=>{}){return({name,value})=>{let{name:newName,value:newValue}=attributeTransformers.reduce((carry,transform)=>{return transform(carry);},{name,value});if(newName!==name)
callback(newName,name);return{name:newName,value:newValue};};}
var attributeTransformers=[];function mapAttributes(callback){attributeTransformers.push(callback);}
function outNonAlpineAttributes({name}){return alpineAttributeRegex().test(name);}
var alpineAttributeRegex=()=>new RegExp(`^${prefixAsString}([^:^.]+)\\b`);function toParsedDirectives(transformedAttributeMap,originalAttributeOverride){return({name,value})=>{let typeMatch=name.match(alpineAttributeRegex());let valueMatch=name.match(/:([a-zA-Z0-9\-:]+)/);let modifiers=name.match(/\.[^.\]]+(?=[^\]]*$)/g)||[];let original=originalAttributeOverride||transformedAttributeMap[name]||name;return{type:typeMatch?typeMatch[1]:null,value:valueMatch?valueMatch[1]:null,modifiers:modifiers.map((i)=>i.replace(".","")),expression:value,original};};}
var DEFAULT="DEFAULT";var directiveOrder=["ignore","ref","data","bind","init","for","model","transition","show","if",DEFAULT,"element"];function byPriority(a,b){let typeA=directiveOrder.indexOf(a.type)===-1?DEFAULT:a.type;let typeB=directiveOrder.indexOf(b.type)===-1?DEFAULT:b.type;return directiveOrder.indexOf(typeA)-directiveOrder.indexOf(typeB);}
function dispatch(el,name,detail={}){el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,composed:true,cancelable:true}));}
var tickStack=[];var isHolding=false;function nextTick(callback){tickStack.push(callback);queueMicrotask(()=>{isHolding||setTimeout(()=>{releaseNextTicks();});});}
function releaseNextTicks(){isHolding=false;while(tickStack.length)
tickStack.shift()();}
function holdNextTicks(){isHolding=true;}
function walk(el,callback){if(typeof ShadowRoot==="function"&&el instanceof ShadowRoot){Array.from(el.children).forEach((el2)=>walk(el2,callback));return;}
let skip=false;callback(el,()=>skip=true);if(skip)
return;let node=el.firstElementChild;while(node){walk(node,callback,false);node=node.nextElementSibling;}}
function warn(message,...args){console.warn(`Alpine Warning: ${message}`,...args);}
function start(){if(!document.body)
warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?");dispatch(document,"alpine:init");dispatch(document,"alpine:initializing");startObservingMutations();onElAdded((el)=>initTree(el,walk));onElRemoved((el)=>nextTick(()=>destroyTree(el)));onAttributesAdded((el,attrs)=>{directives(el,attrs).forEach((handle)=>handle());});let outNestedComponents=(el)=>!closestRoot(el.parentElement,true);Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el)=>{initTree(el);});dispatch(document,"alpine:initialized");}
var rootSelectorCallbacks=[];var initSelectorCallbacks=[];function rootSelectors(){return rootSelectorCallbacks.map((fn)=>fn());}
function allSelectors(){return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn)=>fn());}
function addRootSelector(selectorCallback){rootSelectorCallbacks.push(selectorCallback);}
function addInitSelector(selectorCallback){initSelectorCallbacks.push(selectorCallback);}
function closestRoot(el,includeInitSelectors=false){if(!el)
return;const selectors=includeInitSelectors?allSelectors():rootSelectors();if(selectors.some((selector)=>el.matches(selector)))
return el;if(!el.parentElement)
return;return closestRoot(el.parentElement,includeInitSelectors);}
function isRoot(el){return rootSelectors().some((selector)=>el.matches(selector));}
function initTree(el,walker=walk){deferHandlingDirectives(()=>{walker(el,(el2,skip)=>{directives(el2,el2.attributes).forEach((handle)=>handle());el2._x_ignore&&skip();});});}
function destroyTree(root){walk(root,(el)=>cleanupAttributes(el));}
function setClasses(el,value){if(Array.isArray(value)){return setClassesFromString(el,value.join(" "));}else if(typeof value==="object"&&value!==null){return setClassesFromObject(el,value);}else if(typeof value==="function"){return setClasses(el,value());}
return setClassesFromString(el,value);}
function setClassesFromString(el,classString){let split=(classString2)=>classString2.split(" ").filter(Boolean);let missingClasses=(classString2)=>classString2.split(" ").filter((i)=>!el.classList.contains(i)).filter(Boolean);let addClassesAndReturnUndo=(classes)=>{el.classList.add(...classes);return()=>{el.classList.remove(...classes);};};classString=classString===true?classString="":classString||"";return addClassesAndReturnUndo(missingClasses(classString));}
function setClassesFromObject(el,classObject){let split=(classString)=>classString.split(" ").filter(Boolean);let forAdd=Object.entries(classObject).flatMap(([classString,bool])=>bool?split(classString):false).filter(Boolean);let forRemove=Object.entries(classObject).flatMap(([classString,bool])=>!bool?split(classString):false).filter(Boolean);let added=[];let removed=[];forRemove.forEach((i)=>{if(el.classList.contains(i)){el.classList.remove(i);removed.push(i);}});forAdd.forEach((i)=>{if(!el.classList.contains(i)){el.classList.add(i);added.push(i);}});return()=>{removed.forEach((i)=>el.classList.add(i));added.forEach((i)=>el.classList.remove(i));};}
function setStyles(el,value){if(typeof value==="object"&&value!==null){return setStylesFromObject(el,value);}
return setStylesFromString(el,value);}
function setStylesFromObject(el,value){let previousStyles={};Object.entries(value).forEach(([key,value2])=>{previousStyles[key]=el.style[key];el.style.setProperty(kebabCase(key),value2);});setTimeout(()=>{if(el.style.length===0){el.removeAttribute("style");}});return()=>{setStyles(el,previousStyles);};}
function setStylesFromString(el,value){let cache=el.getAttribute("style",value);el.setAttribute("style",value);return()=>{el.setAttribute("style",cache);};}
function kebabCase(subject){return subject.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();}
function once(callback,fallback=()=>{}){let called=false;return function(){if(!called){called=true;callback.apply(this,arguments);}else{fallback.apply(this,arguments);}};}
directive("transition",(el,{value,modifiers,expression},{evaluate:evaluate2})=>{if(typeof expression==="function")
expression=evaluate2(expression);if(!expression){registerTransitionsFromHelper(el,modifiers,value);}else{registerTransitionsFromClassString(el,expression,value);}});function registerTransitionsFromClassString(el,classString,stage){registerTransitionObject(el,setClasses,"");let directiveStorageMap={enter:(classes)=>{el._x_transition.enter.during=classes;},"enter-start":(classes)=>{el._x_transition.enter.start=classes;},"enter-end":(classes)=>{el._x_transition.enter.end=classes;},leave:(classes)=>{el._x_transition.leave.during=classes;},"leave-start":(classes)=>{el._x_transition.leave.start=classes;},"leave-end":(classes)=>{el._x_transition.leave.end=classes;}};directiveStorageMap[stage](classString);}
function registerTransitionsFromHelper(el,modifiers,stage){registerTransitionObject(el,setStyles);let doesntSpecify=!modifiers.includes("in")&&!modifiers.includes("out")&&!stage;let transitioningIn=doesntSpecify||modifiers.includes("in")||["enter"].includes(stage);let transitioningOut=doesntSpecify||modifiers.includes("out")||["leave"].includes(stage);if(modifiers.includes("in")&&!doesntSpecify){modifiers=modifiers.filter((i,index)=>index<modifiers.indexOf("out"));}
if(modifiers.includes("out")&&!doesntSpecify){modifiers=modifiers.filter((i,index)=>index>modifiers.indexOf("out"));}
let wantsAll=!modifiers.includes("opacity")&&!modifiers.includes("scale");let wantsOpacity=wantsAll||modifiers.includes("opacity");let wantsScale=wantsAll||modifiers.includes("scale");let opacityValue=wantsOpacity?0:1;let scaleValue=wantsScale?modifierValue(modifiers,"scale",95)/100:1;let delay=modifierValue(modifiers,"delay",0);let origin=modifierValue(modifiers,"origin","center");let property="opacity, transform";let durationIn=modifierValue(modifiers,"duration",150)/1e3;let durationOut=modifierValue(modifiers,"duration",75)/1e3;let easing=`cubic-bezier(0.4, 0.0, 0.2, 1)`;if(transitioningIn){el._x_transition.enter.during={transformOrigin:origin,transitionDelay:delay,transitionProperty:property,transitionDuration:`${durationIn}s`,transitionTimingFunction:easing};el._x_transition.enter.start={opacity:opacityValue,transform:`scale(${scaleValue})`};el._x_transition.enter.end={opacity:1,transform:`scale(1)`};}
if(transitioningOut){el._x_transition.leave.during={transformOrigin:origin,transitionDelay:delay,transitionProperty:property,transitionDuration:`${durationOut}s`,transitionTimingFunction:easing};el._x_transition.leave.start={opacity:1,transform:`scale(1)`};el._x_transition.leave.end={opacity:opacityValue,transform:`scale(${scaleValue})`};}}
function registerTransitionObject(el,setFunction,defaultValue={}){if(!el._x_transition)
el._x_transition={enter:{during:defaultValue,start:defaultValue,end:defaultValue},leave:{during:defaultValue,start:defaultValue,end:defaultValue},in(before=()=>{},after=()=>{}){transition(el,setFunction,{during:this.enter.during,start:this.enter.start,end:this.enter.end},before,after);},out(before=()=>{},after=()=>{}){transition(el,setFunction,{during:this.leave.during,start:this.leave.start,end:this.leave.end},before,after);}};}
window.Element.prototype._x_toggleAndCascadeWithTransitions=function(el,value,show,hide){let clickAwayCompatibleShow=()=>{document.visibilityState==="visible"?requestAnimationFrame(show):setTimeout(show);};if(value){if(el._x_transition&&(el._x_transition.enter||el._x_transition.leave)){el._x_transition.enter&&(Object.entries(el._x_transition.enter.during).length||Object.entries(el._x_transition.enter.start).length||Object.entries(el._x_transition.enter.end).length)?el._x_transition.in(show):clickAwayCompatibleShow();}else{el._x_transition?el._x_transition.in(show):clickAwayCompatibleShow();}
return;}
el._x_hidePromise=el._x_transition?new Promise((resolve,reject)=>{el._x_transition.out(()=>{},()=>resolve(hide));el._x_transitioning.beforeCancel(()=>reject({isFromCancelledTransition:true}));}):Promise.resolve(hide);queueMicrotask(()=>{let closest=closestHide(el);if(closest){if(!closest._x_hideChildren)
closest._x_hideChildren=[];closest._x_hideChildren.push(el);}else{queueMicrotask(()=>{let hideAfterChildren=(el2)=>{let carry=Promise.all([el2._x_hidePromise,...(el2._x_hideChildren||[]).map(hideAfterChildren)]).then(([i])=>i());delete el2._x_hidePromise;delete el2._x_hideChildren;return carry;};hideAfterChildren(el).catch((e)=>{if(!e.isFromCancelledTransition)
throw e;});});}});};function closestHide(el){let parent=el.parentNode;if(!parent)
return;return parent._x_hidePromise?parent:closestHide(parent);}
function transition(el,setFunction,{during,start:start2,end}={},before=()=>{},after=()=>{}){if(el._x_transitioning)
el._x_transitioning.cancel();if(Object.keys(during).length===0&&Object.keys(start2).length===0&&Object.keys(end).length===0){before();after();return;}
let undoStart,undoDuring,undoEnd;performTransition(el,{start(){undoStart=setFunction(el,start2);},during(){undoDuring=setFunction(el,during);},before,end(){undoStart();undoEnd=setFunction(el,end);},after,cleanup(){undoDuring();undoEnd();}});}
function performTransition(el,stages){let interrupted,reachedBefore,reachedEnd;let finish=once(()=>{mutateDom(()=>{interrupted=true;if(!reachedBefore)
stages.before();if(!reachedEnd){stages.end();releaseNextTicks();}
stages.after();if(el.isConnected)
stages.cleanup();delete el._x_transitioning;});});el._x_transitioning={beforeCancels:[],beforeCancel(callback){this.beforeCancels.push(callback);},cancel:once(function(){while(this.beforeCancels.length){this.beforeCancels.shift()();};finish();}),finish};mutateDom(()=>{stages.start();stages.during();});holdNextTicks();requestAnimationFrame(()=>{if(interrupted)
return;let duration=Number(getComputedStyle(el).transitionDuration.replace(/,.*/,"").replace("s",""))*1e3;let delay=Number(getComputedStyle(el).transitionDelay.replace(/,.*/,"").replace("s",""))*1e3;if(duration===0)
duration=Number(getComputedStyle(el).animationDuration.replace("s",""))*1e3;mutateDom(()=>{stages.before();});reachedBefore=true;requestAnimationFrame(()=>{if(interrupted)
return;mutateDom(()=>{stages.end();});releaseNextTicks();setTimeout(el._x_transitioning.finish,duration+delay);reachedEnd=true;});});}
function modifierValue(modifiers,key,fallback){if(modifiers.indexOf(key)===-1)
return fallback;const rawValue=modifiers[modifiers.indexOf(key)+1];if(!rawValue)
return fallback;if(key==="scale"){if(isNaN(rawValue))
return fallback;}
if(key==="duration"){let match=rawValue.match(/([0-9]+)ms/);if(match)
return match[1];}
if(key==="origin"){if(["top","right","left","center","bottom"].includes(modifiers[modifiers.indexOf(key)+2])){return[rawValue,modifiers[modifiers.indexOf(key)+2]].join(" ");}}
return rawValue;}
function debounce(func,wait){var timeout;return function(){var context=this,args=arguments;var later=function(){timeout=null;func.apply(context,args);};clearTimeout(timeout);timeout=setTimeout(later,wait);};}
function throttle(func,limit){let inThrottle;return function(){let context=this,args=arguments;if(!inThrottle){func.apply(context,args);inThrottle=true;setTimeout(()=>inThrottle=false,limit);}};}
function plugin(callback){callback(alpine_default);}
var stores={};var isReactive=false;function store(name,value){if(!isReactive){stores=reactive(stores);isReactive=true;}
if(value===void 0){return stores[name];}
stores[name]=value;if(typeof value==="object"&&value!==null&&value.hasOwnProperty("init")&&typeof value.init==="function"){stores[name].init();}
initInterceptors(stores[name]);}
function getStores(){return stores;}
var isCloning=false;function skipDuringClone(callback,fallback=()=>{}){return(...args)=>isCloning?fallback(...args):callback(...args);}
function clone(oldEl,newEl){newEl._x_dataStack=oldEl._x_dataStack;isCloning=true;dontRegisterReactiveSideEffects(()=>{cloneTree(newEl);});isCloning=false;}
function cloneTree(el){let hasRunThroughFirstEl=false;let shallowWalker=(el2,callback)=>{walk(el2,(el3,skip)=>{if(hasRunThroughFirstEl&&isRoot(el3))
return skip();hasRunThroughFirstEl=true;callback(el3,skip);});};initTree(el,shallowWalker);}
function dontRegisterReactiveSideEffects(callback){let cache=effect;overrideEffect((callback2,el)=>{let storedEffect=cache(callback2);release(storedEffect);return()=>{};});callback();overrideEffect(cache);}
var datas={};function data(name,callback){datas[name]=callback;}
function injectDataProviders(obj,context){Object.entries(datas).forEach(([name,callback])=>{Object.defineProperty(obj,name,{get(){return(...args)=>{return callback.bind(context)(...args);};},enumerable:false});});return obj;}
var Alpine={get reactive(){return reactive;},get release(){return release;},get effect(){return effect;},get raw(){return raw;},version:"3.5.1",flushAndStopDeferringMutations,disableEffectScheduling,setReactivityEngine,skipDuringClone,addRootSelector,deferMutations,mapAttributes,evaluateLater,setEvaluator,mergeProxies,closestRoot,interceptor,transition,setStyles,mutateDom,directive,throttle,debounce,evaluate,initTree,nextTick,prefix:setPrefix,plugin,magic,store,start,clone,data};var alpine_default=Alpine;function makeMap(str,expectsLowerCase){const map=Object.create(null);const list=str.split(",");for(let i=0;i<list.length;i++){map[list[i]]=true;}
return expectsLowerCase?(val)=>!!map[val.toLowerCase()]:(val)=>!!map[val];}
var PatchFlagNames={[1]:`TEXT`,[2]:`CLASS`,[4]:`STYLE`,[8]:`PROPS`,[16]:`FULL_PROPS`,[32]:`HYDRATE_EVENTS`,[64]:`STABLE_FRAGMENT`,[128]:`KEYED_FRAGMENT`,[256]:`UNKEYED_FRAGMENT`,[512]:`NEED_PATCH`,[1024]:`DYNAMIC_SLOTS`,[2048]:`DEV_ROOT_FRAGMENT`,[-1]:`HOISTED`,[-2]:`BAIL`};var slotFlagsText={[1]:"STABLE",[2]:"DYNAMIC",[3]:"FORWARDED"};var specialBooleanAttrs=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;var isBooleanAttr=makeMap(specialBooleanAttrs+`,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`);var EMPTY_OBJ=true?Object.freeze({}):{};var EMPTY_ARR=true?Object.freeze([]):[];var extend=Object.assign;var hasOwnProperty=Object.prototype.hasOwnProperty;var hasOwn=(val,key)=>hasOwnProperty.call(val,key);var isArray=Array.isArray;var isMap=(val)=>toTypeString(val)==="[object Map]";var isString=(val)=>typeof val==="string";var isSymbol=(val)=>typeof val==="symbol";var isObject=(val)=>val!==null&&typeof val==="object";var objectToString=Object.prototype.toString;var toTypeString=(value)=>objectToString.call(value);var toRawType=(value)=>{return toTypeString(value).slice(8,-1);};var isIntegerKey=(key)=>isString(key)&&key!=="NaN"&&key[0]!=="-"&&""+parseInt(key,10)===key;var cacheStringFunction=(fn)=>{const cache=Object.create(null);return(str)=>{const hit=cache[str];return hit||(cache[str]=fn(str));};};var camelizeRE=/-(\w)/g;var camelize=cacheStringFunction((str)=>{return str.replace(camelizeRE,(_,c)=>c?c.toUpperCase():"");});var hyphenateRE=/\B([A-Z])/g;var hyphenate=cacheStringFunction((str)=>str.replace(hyphenateRE,"-$1").toLowerCase());var capitalize=cacheStringFunction((str)=>str.charAt(0).toUpperCase()+str.slice(1));var toHandlerKey=cacheStringFunction((str)=>str?`on${capitalize(str)}`:``);var hasChanged=(value,oldValue)=>value!==oldValue&&(value===value||oldValue===oldValue);var targetMap=new WeakMap();var effectStack=[];var activeEffect;var ITERATE_KEY=Symbol(true?"iterate":"");var MAP_KEY_ITERATE_KEY=Symbol(true?"Map key iterate":"");function isEffect(fn){return fn&&fn._isEffect===true;}
function effect2(fn,options=EMPTY_OBJ){if(isEffect(fn)){fn=fn.raw;}
const effect3=createReactiveEffect(fn,options);if(!options.lazy){effect3();}
return effect3;}
function stop(effect3){if(effect3.active){cleanup(effect3);if(effect3.options.onStop){effect3.options.onStop();}
effect3.active=false;}}
var uid=0;function createReactiveEffect(fn,options){const effect3=function reactiveEffect(){if(!effect3.active){return fn();}
if(!effectStack.includes(effect3)){cleanup(effect3);try{enableTracking();effectStack.push(effect3);activeEffect=effect3;return fn();}finally{effectStack.pop();resetTracking();activeEffect=effectStack[effectStack.length-1];}}};effect3.id=uid++;effect3.allowRecurse=!!options.allowRecurse;effect3._isEffect=true;effect3.active=true;effect3.raw=fn;effect3.deps=[];effect3.options=options;return effect3;}
function cleanup(effect3){const{deps}=effect3;if(deps.length){for(let i=0;i<deps.length;i++){deps[i].delete(effect3);}
deps.length=0;}}
var shouldTrack=true;var trackStack=[];function pauseTracking(){trackStack.push(shouldTrack);shouldTrack=false;}
function enableTracking(){trackStack.push(shouldTrack);shouldTrack=true;}
function resetTracking(){const last=trackStack.pop();shouldTrack=last===void 0?true:last;}
function track(target,type,key){if(!shouldTrack||activeEffect===void 0){return;}
let depsMap=targetMap.get(target);if(!depsMap){targetMap.set(target,depsMap=new Map());}
let dep=depsMap.get(key);if(!dep){depsMap.set(key,dep=new Set());}
if(!dep.has(activeEffect)){dep.add(activeEffect);activeEffect.deps.push(dep);if(activeEffect.options.onTrack){activeEffect.options.onTrack({effect:activeEffect,target,type,key});}}}
function trigger(target,type,key,newValue,oldValue,oldTarget){const depsMap=targetMap.get(target);if(!depsMap){return;}
const effects=new Set();const add2=(effectsToAdd)=>{if(effectsToAdd){effectsToAdd.forEach((effect3)=>{if(effect3!==activeEffect||effect3.allowRecurse){effects.add(effect3);}});}};if(type==="clear"){depsMap.forEach(add2);}else if(key==="length"&&isArray(target)){depsMap.forEach((dep,key2)=>{if(key2==="length"||key2>=newValue){add2(dep);}});}else{if(key!==void 0){add2(depsMap.get(key));}
switch(type){case"add":if(!isArray(target)){add2(depsMap.get(ITERATE_KEY));if(isMap(target)){add2(depsMap.get(MAP_KEY_ITERATE_KEY));}}else if(isIntegerKey(key)){add2(depsMap.get("length"));}
break;case"delete":if(!isArray(target)){add2(depsMap.get(ITERATE_KEY));if(isMap(target)){add2(depsMap.get(MAP_KEY_ITERATE_KEY));}}
break;case"set":if(isMap(target)){add2(depsMap.get(ITERATE_KEY));}
break;}}
const run=(effect3)=>{if(effect3.options.onTrigger){effect3.options.onTrigger({effect:effect3,target,key,type,newValue,oldValue,oldTarget});}
if(effect3.options.scheduler){effect3.options.scheduler(effect3);}else{effect3();}};effects.forEach(run);}
var isNonTrackableKeys=makeMap(`__proto__,__v_isRef,__isVue`);var builtInSymbols=new Set(Object.getOwnPropertyNames(Symbol).map((key)=>Symbol[key]).filter(isSymbol));var get2=createGetter();var shallowGet=createGetter(false,true);var readonlyGet=createGetter(true);var shallowReadonlyGet=createGetter(true,true);var arrayInstrumentations={};["includes","indexOf","lastIndexOf"].forEach((key)=>{const method=Array.prototype[key];arrayInstrumentations[key]=function(...args){const arr=toRaw(this);for(let i=0,l=this.length;i<l;i++){track(arr,"get",i+"");}
const res=method.apply(arr,args);if(res===-1||res===false){return method.apply(arr,args.map(toRaw));}else{return res;}};});["push","pop","shift","unshift","splice"].forEach((key)=>{const method=Array.prototype[key];arrayInstrumentations[key]=function(...args){pauseTracking();const res=method.apply(this,args);resetTracking();return res;};});function createGetter(isReadonly=false,shallow=false){return function get3(target,key,receiver){if(key==="__v_isReactive"){return!isReadonly;}else if(key==="__v_isReadonly"){return isReadonly;}else if(key==="__v_raw"&&receiver===(isReadonly?shallow?shallowReadonlyMap:readonlyMap:shallow?shallowReactiveMap:reactiveMap).get(target)){return target;}
const targetIsArray=isArray(target);if(!isReadonly&&targetIsArray&&hasOwn(arrayInstrumentations,key)){return Reflect.get(arrayInstrumentations,key,receiver);}
const res=Reflect.get(target,key,receiver);if(isSymbol(key)?builtInSymbols.has(key):isNonTrackableKeys(key)){return res;}
if(!isReadonly){track(target,"get",key);}
if(shallow){return res;}
if(isRef(res)){const shouldUnwrap=!targetIsArray||!isIntegerKey(key);return shouldUnwrap?res.value:res;}
if(isObject(res)){return isReadonly?readonly(res):reactive2(res);}
return res;};}
var set2=createSetter();var shallowSet=createSetter(true);function createSetter(shallow=false){return function set3(target,key,value,receiver){let oldValue=target[key];if(!shallow){value=toRaw(value);oldValue=toRaw(oldValue);if(!isArray(target)&&isRef(oldValue)&&!isRef(value)){oldValue.value=value;return true;}}
const hadKey=isArray(target)&&isIntegerKey(key)?Number(key)<target.length:hasOwn(target,key);const result=Reflect.set(target,key,value,receiver);if(target===toRaw(receiver)){if(!hadKey){trigger(target,"add",key,value);}else if(hasChanged(value,oldValue)){trigger(target,"set",key,value,oldValue);}}
return result;};}
function deleteProperty(target,key){const hadKey=hasOwn(target,key);const oldValue=target[key];const result=Reflect.deleteProperty(target,key);if(result&&hadKey){trigger(target,"delete",key,void 0,oldValue);}
return result;}
function has(target,key){const result=Reflect.has(target,key);if(!isSymbol(key)||!builtInSymbols.has(key)){track(target,"has",key);}
return result;}
function ownKeys(target){track(target,"iterate",isArray(target)?"length":ITERATE_KEY);return Reflect.ownKeys(target);}
var mutableHandlers={get:get2,set:set2,deleteProperty,has,ownKeys};var readonlyHandlers={get:readonlyGet,set(target,key){if(true){console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`,target);}
return true;},deleteProperty(target,key){if(true){console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`,target);}
return true;}};var shallowReactiveHandlers=extend({},mutableHandlers,{get:shallowGet,set:shallowSet});var shallowReadonlyHandlers=extend({},readonlyHandlers,{get:shallowReadonlyGet});var toReactive=(value)=>isObject(value)?reactive2(value):value;var toReadonly=(value)=>isObject(value)?readonly(value):value;var toShallow=(value)=>value;var getProto=(v)=>Reflect.getPrototypeOf(v);function get$1(target,key,isReadonly=false,isShallow=false){target=target["__v_raw"];const rawTarget=toRaw(target);const rawKey=toRaw(key);if(key!==rawKey){!isReadonly&&track(rawTarget,"get",key);}
!isReadonly&&track(rawTarget,"get",rawKey);const{has:has2}=getProto(rawTarget);const wrap=isShallow?toShallow:isReadonly?toReadonly:toReactive;if(has2.call(rawTarget,key)){return wrap(target.get(key));}else if(has2.call(rawTarget,rawKey)){return wrap(target.get(rawKey));}else if(target!==rawTarget){target.get(key);}}
function has$1(key,isReadonly=false){const target=this["__v_raw"];const rawTarget=toRaw(target);const rawKey=toRaw(key);if(key!==rawKey){!isReadonly&&track(rawTarget,"has",key);}
!isReadonly&&track(rawTarget,"has",rawKey);return key===rawKey?target.has(key):target.has(key)||target.has(rawKey);}
function size(target,isReadonly=false){target=target["__v_raw"];!isReadonly&&track(toRaw(target),"iterate",ITERATE_KEY);return Reflect.get(target,"size",target);}
function add(value){value=toRaw(value);const target=toRaw(this);const proto=getProto(target);const hadKey=proto.has.call(target,value);if(!hadKey){target.add(value);trigger(target,"add",value,value);}
return this;}
function set$1(key,value){value=toRaw(value);const target=toRaw(this);const{has:has2,get:get3}=getProto(target);let hadKey=has2.call(target,key);if(!hadKey){key=toRaw(key);hadKey=has2.call(target,key);}else if(true){checkIdentityKeys(target,has2,key);}
const oldValue=get3.call(target,key);target.set(key,value);if(!hadKey){trigger(target,"add",key,value);}else if(hasChanged(value,oldValue)){trigger(target,"set",key,value,oldValue);}
return this;}
function deleteEntry(key){const target=toRaw(this);const{has:has2,get:get3}=getProto(target);let hadKey=has2.call(target,key);if(!hadKey){key=toRaw(key);hadKey=has2.call(target,key);}else if(true){checkIdentityKeys(target,has2,key);}
const oldValue=get3?get3.call(target,key):void 0;const result=target.delete(key);if(hadKey){trigger(target,"delete",key,void 0,oldValue);}
return result;}
function clear(){const target=toRaw(this);const hadItems=target.size!==0;const oldTarget=true?isMap(target)?new Map(target):new Set(target):void 0;const result=target.clear();if(hadItems){trigger(target,"clear",void 0,void 0,oldTarget);}
return result;}
function createForEach(isReadonly,isShallow){return function forEach(callback,thisArg){const observed=this;const target=observed["__v_raw"];const rawTarget=toRaw(target);const wrap=isShallow?toShallow:isReadonly?toReadonly:toReactive;!isReadonly&&track(rawTarget,"iterate",ITERATE_KEY);return target.forEach((value,key)=>{return callback.call(thisArg,wrap(value),wrap(key),observed);});};}
function createIterableMethod(method,isReadonly,isShallow){return function(...args){const target=this["__v_raw"];const rawTarget=toRaw(target);const targetIsMap=isMap(rawTarget);const isPair=method==="entries"||method===Symbol.iterator&&targetIsMap;const isKeyOnly=method==="keys"&&targetIsMap;const innerIterator=target[method](...args);const wrap=isShallow?toShallow:isReadonly?toReadonly:toReactive;!isReadonly&&track(rawTarget,"iterate",isKeyOnly?MAP_KEY_ITERATE_KEY:ITERATE_KEY);return{next(){const{value,done}=innerIterator.next();return done?{value,done}:{value:isPair?[wrap(value[0]),wrap(value[1])]:wrap(value),done};},[Symbol.iterator](){return this;}};};}
function createReadonlyMethod(type){return function(...args){if(true){const key=args[0]?`on key "${args[0]}" `:``;console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`,toRaw(this));}
return type==="delete"?false:this;};}
var mutableInstrumentations={get(key){return get$1(this,key);},get size(){return size(this);},has:has$1,add,set:set$1,delete:deleteEntry,clear,forEach:createForEach(false,false)};var shallowInstrumentations={get(key){return get$1(this,key,false,true);},get size(){return size(this);},has:has$1,add,set:set$1,delete:deleteEntry,clear,forEach:createForEach(false,true)};var readonlyInstrumentations={get(key){return get$1(this,key,true);},get size(){return size(this,true);},has(key){return has$1.call(this,key,true);},add:createReadonlyMethod("add"),set:createReadonlyMethod("set"),delete:createReadonlyMethod("delete"),clear:createReadonlyMethod("clear"),forEach:createForEach(true,false)};var shallowReadonlyInstrumentations={get(key){return get$1(this,key,true,true);},get size(){return size(this,true);},has(key){return has$1.call(this,key,true);},add:createReadonlyMethod("add"),set:createReadonlyMethod("set"),delete:createReadonlyMethod("delete"),clear:createReadonlyMethod("clear"),forEach:createForEach(true,true)};var iteratorMethods=["keys","values","entries",Symbol.iterator];iteratorMethods.forEach((method)=>{mutableInstrumentations[method]=createIterableMethod(method,false,false);readonlyInstrumentations[method]=createIterableMethod(method,true,false);shallowInstrumentations[method]=createIterableMethod(method,false,true);shallowReadonlyInstrumentations[method]=createIterableMethod(method,true,true);});function createInstrumentationGetter(isReadonly,shallow){const instrumentations=shallow?isReadonly?shallowReadonlyInstrumentations:shallowInstrumentations:isReadonly?readonlyInstrumentations:mutableInstrumentations;return(target,key,receiver)=>{if(key==="__v_isReactive"){return!isReadonly;}else if(key==="__v_isReadonly"){return isReadonly;}else if(key==="__v_raw"){return target;}
return Reflect.get(hasOwn(instrumentations,key)&&key in target?instrumentations:target,key,receiver);};}
var mutableCollectionHandlers={get:createInstrumentationGetter(false,false)};var shallowCollectionHandlers={get:createInstrumentationGetter(false,true)};var readonlyCollectionHandlers={get:createInstrumentationGetter(true,false)};var shallowReadonlyCollectionHandlers={get:createInstrumentationGetter(true,true)};function checkIdentityKeys(target,has2,key){const rawKey=toRaw(key);if(rawKey!==key&&has2.call(target,rawKey)){const type=toRawType(target);console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? `as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`);}}
var reactiveMap=new WeakMap();var shallowReactiveMap=new WeakMap();var readonlyMap=new WeakMap();var shallowReadonlyMap=new WeakMap();function targetTypeMap(rawType){switch(rawType){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0;}}
function getTargetType(value){return value["__v_skip"]||!Object.isExtensible(value)?0:targetTypeMap(toRawType(value));}
function reactive2(target){if(target&&target["__v_isReadonly"]){return target;}
return createReactiveObject(target,false,mutableHandlers,mutableCollectionHandlers,reactiveMap);}
function readonly(target){return createReactiveObject(target,true,readonlyHandlers,readonlyCollectionHandlers,readonlyMap);}
function createReactiveObject(target,isReadonly,baseHandlers,collectionHandlers,proxyMap){if(!isObject(target)){if(true){console.warn(`value cannot be made reactive: ${String(target)}`);}
return target;}
if(target["__v_raw"]&&!(isReadonly&&target["__v_isReactive"])){return target;}
const existingProxy=proxyMap.get(target);if(existingProxy){return existingProxy;}
const targetType=getTargetType(target);if(targetType===0){return target;}
const proxy=new Proxy(target,targetType===2?collectionHandlers:baseHandlers);proxyMap.set(target,proxy);return proxy;}
function toRaw(observed){return observed&&toRaw(observed["__v_raw"])||observed;}
function isRef(r){return Boolean(r&&r.__v_isRef===true);}
magic("nextTick",()=>nextTick);magic("dispatch",(el)=>dispatch.bind(dispatch,el));magic("watch",(el)=>(key,callback)=>{let evaluate2=evaluateLater(el,key);let firstTime=true;let oldValue;effect(()=>evaluate2((value)=>{let div=document.createElement("div");div.dataset.throwAway=value;if(!firstTime){queueMicrotask(()=>{callback(value,oldValue);oldValue=value;});}else{oldValue=value;}
firstTime=false;}));});magic("store",getStores);magic("data",(el)=>{return mergeProxies(closestDataStack(el));});magic("root",(el)=>closestRoot(el));magic("refs",(el)=>{if(el._x_refs_proxy)
return el._x_refs_proxy;el._x_refs_proxy=mergeProxies(getArrayOfRefObject(el));return el._x_refs_proxy;});function getArrayOfRefObject(el){let refObjects=[];let currentEl=el;while(currentEl){if(currentEl._x_refs)
refObjects.push(currentEl._x_refs);currentEl=currentEl.parentNode;}
return refObjects;}
magic("el",(el)=>el);var handler=()=>{};handler.inline=(el,{modifiers},{cleanup:cleanup2})=>{modifiers.includes("self")?el._x_ignoreSelf=true:el._x_ignore=true;cleanup2(()=>{modifiers.includes("self")?delete el._x_ignoreSelf:delete el._x_ignore;});};directive("ignore",handler);directive("effect",(el,{expression},{effect:effect3})=>effect3(evaluateLater(el,expression)));function bind(el,name,value,modifiers=[]){if(!el._x_bindings)
el._x_bindings=reactive({});el._x_bindings[name]=value;name=modifiers.includes("camel")?camelCase(name):name;switch(name){case"value":bindInputValue(el,value);break;case"style":bindStyles(el,value);break;case"class":bindClasses(el,value);break;default:bindAttribute(el,name,value);break;}}
function bindInputValue(el,value){if(el.type==="radio"){if(el.attributes.value===void 0){el.value=value;}
if(window.fromModel){el.checked=checkedAttrLooseCompare(el.value,value);}}else if(el.type==="checkbox"){if(Number.isInteger(value)){el.value=value;}else if(!Number.isInteger(value)&&!Array.isArray(value)&&typeof value!=="boolean"&&![null,void 0].includes(value)){el.value=String(value);}else{if(Array.isArray(value)){el.checked=value.some((val)=>checkedAttrLooseCompare(val,el.value));}else{el.checked=!!value;}}}else if(el.tagName==="SELECT"){updateSelect(el,value);}else{if(el.value===value)
return;el.value=value;}}
function bindClasses(el,value){if(el._x_undoAddedClasses)
el._x_undoAddedClasses();el._x_undoAddedClasses=setClasses(el,value);}
function bindStyles(el,value){if(el._x_undoAddedStyles)
el._x_undoAddedStyles();el._x_undoAddedStyles=setStyles(el,value);}
function bindAttribute(el,name,value){if([null,void 0,false].includes(value)&&attributeShouldntBePreservedIfFalsy(name)){el.removeAttribute(name);}else{if(isBooleanAttr2(name))
value=name;setIfChanged(el,name,value);}}
function setIfChanged(el,attrName,value){if(el.getAttribute(attrName)!=value){el.setAttribute(attrName,value);}}
function updateSelect(el,value){const arrayWrappedValue=[].concat(value).map((value2)=>{return value2+"";});Array.from(el.options).forEach((option)=>{option.selected=arrayWrappedValue.includes(option.value);});}
function camelCase(subject){return subject.toLowerCase().replace(/-(\w)/g,(match,char)=>char.toUpperCase());}
function checkedAttrLooseCompare(valueA,valueB){return valueA==valueB;}
function isBooleanAttr2(attrName){const booleanAttributes=["disabled","checked","required","readonly","hidden","open","selected","autofocus","itemscope","multiple","novalidate","allowfullscreen","allowpaymentrequest","formnovalidate","autoplay","controls","loop","muted","playsinline","default","ismap","reversed","async","defer","nomodule"];return booleanAttributes.includes(attrName);}
function attributeShouldntBePreservedIfFalsy(name){return!["aria-pressed","aria-checked","aria-expanded"].includes(name);}
function on(el,event,modifiers,callback){let listenerTarget=el;let handler3=(e)=>callback(e);let options={};let wrapHandler=(callback2,wrapper)=>(e)=>wrapper(callback2,e);if(modifiers.includes("dot"))
event=dotSyntax(event);if(modifiers.includes("camel"))
event=camelCase2(event);if(modifiers.includes("passive"))
options.passive=true;if(modifiers.includes("capture"))
options.capture=true;if(modifiers.includes("window"))
listenerTarget=window;if(modifiers.includes("document"))
listenerTarget=document;if(modifiers.includes("prevent"))
handler3=wrapHandler(handler3,(next,e)=>{e.preventDefault();next(e);});if(modifiers.includes("stop"))
handler3=wrapHandler(handler3,(next,e)=>{e.stopPropagation();next(e);});if(modifiers.includes("self"))
handler3=wrapHandler(handler3,(next,e)=>{e.target===el&&next(e);});if(modifiers.includes("away")||modifiers.includes("outside")){listenerTarget=document;handler3=wrapHandler(handler3,(next,e)=>{if(el.contains(e.target))
return;if(el.offsetWidth<1&&el.offsetHeight<1)
return;if(el._x_isShown===false)
return;next(e);});}
handler3=wrapHandler(handler3,(next,e)=>{if(isKeyEvent(event)){if(isListeningForASpecificKeyThatHasntBeenPressed(e,modifiers)){return;}}
next(e);});if(modifiers.includes("debounce")){let nextModifier=modifiers[modifiers.indexOf("debounce")+1]||"invalid-wait";let wait=isNumeric(nextModifier.split("ms")[0])?Number(nextModifier.split("ms")[0]):250;handler3=debounce(handler3,wait);}
if(modifiers.includes("throttle")){let nextModifier=modifiers[modifiers.indexOf("throttle")+1]||"invalid-wait";let wait=isNumeric(nextModifier.split("ms")[0])?Number(nextModifier.split("ms")[0]):250;handler3=throttle(handler3,wait);}
if(modifiers.includes("once")){handler3=wrapHandler(handler3,(next,e)=>{next(e);listenerTarget.removeEventListener(event,handler3,options);});}
listenerTarget.addEventListener(event,handler3,options);return()=>{listenerTarget.removeEventListener(event,handler3,options);};}
function dotSyntax(subject){return subject.replace(/-/g,".");}
function camelCase2(subject){return subject.toLowerCase().replace(/-(\w)/g,(match,char)=>char.toUpperCase());}
function isNumeric(subject){return!Array.isArray(subject)&&!isNaN(subject);}
function kebabCase2(subject){return subject.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]/,"-").toLowerCase();}
function isKeyEvent(event){return["keydown","keyup"].includes(event);}
function isListeningForASpecificKeyThatHasntBeenPressed(e,modifiers){let keyModifiers=modifiers.filter((i)=>{return!["window","document","prevent","stop","once"].includes(i);});if(keyModifiers.includes("debounce")){let debounceIndex=keyModifiers.indexOf("debounce");keyModifiers.splice(debounceIndex,isNumeric((keyModifiers[debounceIndex+1]||"invalid-wait").split("ms")[0])?2:1);}
if(keyModifiers.length===0)
return false;if(keyModifiers.length===1&&keyToModifiers(e.key).includes(keyModifiers[0]))
return false;const systemKeyModifiers=["ctrl","shift","alt","meta","cmd","super"];const selectedSystemKeyModifiers=systemKeyModifiers.filter((modifier)=>keyModifiers.includes(modifier));keyModifiers=keyModifiers.filter((i)=>!selectedSystemKeyModifiers.includes(i));if(selectedSystemKeyModifiers.length>0){const activelyPressedKeyModifiers=selectedSystemKeyModifiers.filter((modifier)=>{if(modifier==="cmd"||modifier==="super")
modifier="meta";return e[`${modifier}Key`];});if(activelyPressedKeyModifiers.length===selectedSystemKeyModifiers.length){if(keyToModifiers(e.key).includes(keyModifiers[0]))
return false;}}
return true;}
function keyToModifiers(key){if(!key)
return[];key=kebabCase2(key);let modifierToKeyMap={ctrl:"control",slash:"/",space:"-",spacebar:"-",cmd:"meta",esc:"escape",up:"arrow-up",down:"arrow-down",left:"arrow-left",right:"arrow-right",period:".",equal:"="};modifierToKeyMap[key]=key;return Object.keys(modifierToKeyMap).map((modifier)=>{if(modifierToKeyMap[modifier]===key)
return modifier;}).filter((modifier)=>modifier);}
directive("model",(el,{modifiers,expression},{effect:effect3,cleanup:cleanup2})=>{let evaluate2=evaluateLater(el,expression);let assignmentExpression=`${expression} = rightSideOfExpression($event, ${expression})`;let evaluateAssignment=evaluateLater(el,assignmentExpression);var event=el.tagName.toLowerCase()==="select"||["checkbox","radio"].includes(el.type)||modifiers.includes("lazy")?"change":"input";let assigmentFunction=generateAssignmentFunction(el,modifiers,expression);let removeListener=on(el,event,modifiers,(e)=>{evaluateAssignment(()=>{},{scope:{$event:e,rightSideOfExpression:assigmentFunction}});});cleanup2(()=>removeListener());let evaluateSetModel=evaluateLater(el,`${expression} = __placeholder`);el._x_model={get(){let result;evaluate2((value)=>result=value);return result;},set(value){evaluateSetModel(()=>{},{scope:{__placeholder:value}});}};el._x_forceModelUpdate=()=>{evaluate2((value)=>{if(value===void 0&&expression.match(/\./))
value="";window.fromModel=true;mutateDom(()=>bind(el,"value",value));delete window.fromModel;});};effect3(()=>{if(modifiers.includes("unintrusive")&&document.activeElement.isSameNode(el))
return;el._x_forceModelUpdate();});});function generateAssignmentFunction(el,modifiers,expression){if(el.type==="radio"){mutateDom(()=>{if(!el.hasAttribute("name"))
el.setAttribute("name",expression);});}
return(event,currentValue)=>{return mutateDom(()=>{if(event instanceof CustomEvent&&event.detail!==void 0){return event.detail||event.target.value;}else if(el.type==="checkbox"){if(Array.isArray(currentValue)){let newValue=modifiers.includes("number")?safeParseNumber(event.target.value):event.target.value;return event.target.checked?currentValue.concat([newValue]):currentValue.filter((el2)=>!checkedAttrLooseCompare2(el2,newValue));}else{return event.target.checked;}}else if(el.tagName.toLowerCase()==="select"&&el.multiple){return modifiers.includes("number")?Array.from(event.target.selectedOptions).map((option)=>{let rawValue=option.value||option.text;return safeParseNumber(rawValue);}):Array.from(event.target.selectedOptions).map((option)=>{return option.value||option.text;});}else{let rawValue=event.target.value;return modifiers.includes("number")?safeParseNumber(rawValue):modifiers.includes("trim")?rawValue.trim():rawValue;}});};}
function safeParseNumber(rawValue){let number=rawValue?parseFloat(rawValue):null;return isNumeric2(number)?number:rawValue;}
function checkedAttrLooseCompare2(valueA,valueB){return valueA==valueB;}
function isNumeric2(subject){return!Array.isArray(subject)&&!isNaN(subject);}
directive("cloak",(el)=>queueMicrotask(()=>mutateDom(()=>el.removeAttribute(prefix("cloak")))));addInitSelector(()=>`[${prefix("init")}]`);directive("init",skipDuringClone((el,{expression})=>{if(typeof expression==="string"){return!!expression.trim()&&evaluate(el,expression,{},false);}
return evaluate(el,expression,{},false);}));directive("text",(el,{expression},{effect:effect3,evaluateLater:evaluateLater2})=>{let evaluate2=evaluateLater2(expression);effect3(()=>{evaluate2((value)=>{mutateDom(()=>{el.textContent=value;});});});});directive("html",(el,{expression},{effect:effect3,evaluateLater:evaluateLater2})=>{let evaluate2=evaluateLater2(expression);effect3(()=>{evaluate2((value)=>{el.innerHTML=value;});});});mapAttributes(startingWith(":",into(prefix("bind:"))));directive("bind",(el,{value,modifiers,expression,original},{effect:effect3})=>{if(!value)
return applyBindingsObject(el,expression,original,effect3);if(value==="key")
return storeKeyForXFor(el,expression);let evaluate2=evaluateLater(el,expression);effect3(()=>evaluate2((result)=>{if(result===void 0&&expression.match(/\./))
result="";mutateDom(()=>bind(el,value,result,modifiers));}));});function applyBindingsObject(el,expression,original,effect3){let getBindings=evaluateLater(el,expression);let cleanupRunners=[];effect3(()=>{while(cleanupRunners.length)
cleanupRunners.pop()();getBindings((bindings)=>{let attributes=Object.entries(bindings).map(([name,value])=>({name,value}));attributes=attributes.filter((attr)=>{return!(typeof attr.value==="object"&&!Array.isArray(attr.value)&&attr.value!==null);});let staticAttributes=attributesOnly(attributes);attributes=attributes.map((attribute)=>{if(staticAttributes.find((attr)=>attr.name===attribute.name)){return{name:`x-bind:${attribute.name}`,value:`"${attribute.value}"`};}
return attribute;});directives(el,attributes,original).map((handle)=>{cleanupRunners.push(handle.runCleanups);handle();});});});}
function storeKeyForXFor(el,expression){el._x_keyExpression=expression;}
addRootSelector(()=>`[${prefix("data")}]`);directive("data",skipDuringClone((el,{expression},{cleanup:cleanup2})=>{expression=expression===""?"{}":expression;let magicContext={};injectMagics(magicContext,el);let dataProviderContext={};injectDataProviders(dataProviderContext,magicContext);let data2=evaluate(el,expression,{scope:dataProviderContext});if(data2===void 0)
data2={};injectMagics(data2,el);let reactiveData=reactive(data2);initInterceptors(reactiveData);let undo=addScopeToNode(el,reactiveData);reactiveData["init"]&&evaluate(el,reactiveData["init"]);cleanup2(()=>{undo();reactiveData["destroy"]&&evaluate(el,reactiveData["destroy"]);});}));directive("show",(el,{modifiers,expression},{effect:effect3})=>{let evaluate2=evaluateLater(el,expression);let hide=()=>mutateDom(()=>{el.style.display="none";el._x_isShown=false;});let show=()=>mutateDom(()=>{if(el.style.length===1&&el.style.display==="none"){el.removeAttribute("style");}else{el.style.removeProperty("display");}
el._x_isShown=true;});let clickAwayCompatibleShow=()=>setTimeout(show);let toggle=once((value)=>value?show():hide(),(value)=>{if(typeof el._x_toggleAndCascadeWithTransitions==="function"){el._x_toggleAndCascadeWithTransitions(el,value,show,hide);}else{value?clickAwayCompatibleShow():hide();}});let oldValue;let firstTime=true;effect3(()=>evaluate2((value)=>{if(!firstTime&&value===oldValue)
return;if(modifiers.includes("immediate"))
value?clickAwayCompatibleShow():hide();toggle(value);oldValue=value;firstTime=false;}));});directive("for",(el,{expression},{effect:effect3,cleanup:cleanup2})=>{let iteratorNames=parseForExpression(expression);let evaluateItems=evaluateLater(el,iteratorNames.items);let evaluateKey=evaluateLater(el,el._x_keyExpression||"index");el._x_prevKeys=[];el._x_lookup={};effect3(()=>loop(el,iteratorNames,evaluateItems,evaluateKey));cleanup2(()=>{Object.values(el._x_lookup).forEach((el2)=>el2.remove());delete el._x_prevKeys;delete el._x_lookup;});});function loop(el,iteratorNames,evaluateItems,evaluateKey){let isObject2=(i)=>typeof i==="object"&&!Array.isArray(i);let templateEl=el;evaluateItems((items)=>{if(isNumeric3(items)&&items>=0){items=Array.from(Array(items).keys(),(i)=>i+1);}
if(items===void 0)
items=[];let lookup=el._x_lookup;let prevKeys=el._x_prevKeys;let scopes=[];let keys=[];if(isObject2(items)){items=Object.entries(items).map(([key,value])=>{let scope=getIterationScopeVariables(iteratorNames,value,key,items);evaluateKey((value2)=>keys.push(value2),{scope:{index:key,...scope}});scopes.push(scope);});}else{for(let i=0;i<items.length;i++){let scope=getIterationScopeVariables(iteratorNames,items[i],i,items);evaluateKey((value)=>keys.push(value),{scope:{index:i,...scope}});scopes.push(scope);}}
let adds=[];let moves=[];let removes=[];let sames=[];for(let i=0;i<prevKeys.length;i++){let key=prevKeys[i];if(keys.indexOf(key)===-1)
removes.push(key);}
prevKeys=prevKeys.filter((key)=>!removes.includes(key));let lastKey="template";for(let i=0;i<keys.length;i++){let key=keys[i];let prevIndex=prevKeys.indexOf(key);if(prevIndex===-1){prevKeys.splice(i,0,key);adds.push([lastKey,i]);}else if(prevIndex!==i){let keyInSpot=prevKeys.splice(i,1)[0];let keyForSpot=prevKeys.splice(prevIndex-1,1)[0];prevKeys.splice(i,0,keyForSpot);prevKeys.splice(prevIndex,0,keyInSpot);moves.push([keyInSpot,keyForSpot]);}else{sames.push(key);}
lastKey=key;}
for(let i=0;i<removes.length;i++){let key=removes[i];lookup[key].remove();lookup[key]=null;delete lookup[key];}
for(let i=0;i<moves.length;i++){let[keyInSpot,keyForSpot]=moves[i];let elInSpot=lookup[keyInSpot];let elForSpot=lookup[keyForSpot];let marker=document.createElement("div");mutateDom(()=>{elForSpot.after(marker);elInSpot.after(elForSpot);marker.before(elInSpot);marker.remove();});refreshScope(elForSpot,scopes[keys.indexOf(keyForSpot)]);}
for(let i=0;i<adds.length;i++){let[lastKey2,index]=adds[i];let lastEl=lastKey2==="template"?templateEl:lookup[lastKey2];let scope=scopes[index];let key=keys[index];let clone2=document.importNode(templateEl.content,true).firstElementChild;addScopeToNode(clone2,reactive(scope),templateEl);mutateDom(()=>{lastEl.after(clone2);initTree(clone2);});if(typeof key==="object"){warn("x-for key cannot be an object, it must be a string or an integer",templateEl);}
lookup[key]=clone2;}
for(let i=0;i<sames.length;i++){refreshScope(lookup[sames[i]],scopes[keys.indexOf(sames[i])]);}
templateEl._x_prevKeys=keys;});}
function parseForExpression(expression){let forIteratorRE=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/;let stripParensRE=/^\s*\(|\)\s*$/g;let forAliasRE=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;let inMatch=expression.match(forAliasRE);if(!inMatch)
return;let res={};res.items=inMatch[2].trim();let item=inMatch[1].replace(stripParensRE,"").trim();let iteratorMatch=item.match(forIteratorRE);if(iteratorMatch){res.item=item.replace(forIteratorRE,"").trim();res.index=iteratorMatch[1].trim();if(iteratorMatch[2]){res.collection=iteratorMatch[2].trim();}}else{res.item=item;}
return res;}
function getIterationScopeVariables(iteratorNames,item,index,items){let scopeVariables={};if(/^\[.*\]$/.test(iteratorNames.item)&&Array.isArray(item)){let names=iteratorNames.item.replace("[","").replace("]","").split(",").map((i)=>i.trim());names.forEach((name,i)=>{scopeVariables[name]=item[i];});}else if(/^\{.*\}$/.test(iteratorNames.item)&&!Array.isArray(item)&&typeof item==="object"){let names=iteratorNames.item.replace("{","").replace("}","").split(",").map((i)=>i.trim());names.forEach((name)=>{scopeVariables[name]=item[name];});}else{scopeVariables[iteratorNames.item]=item;}
if(iteratorNames.index)
scopeVariables[iteratorNames.index]=index;if(iteratorNames.collection)
scopeVariables[iteratorNames.collection]=items;return scopeVariables;}
function isNumeric3(subject){return!Array.isArray(subject)&&!isNaN(subject);}
function handler2(){}
handler2.inline=(el,{expression},{cleanup:cleanup2})=>{let root=closestRoot(el);if(!root._x_refs)
root._x_refs={};root._x_refs[expression]=el;cleanup2(()=>delete root._x_refs[expression]);};directive("ref",handler2);directive("if",(el,{expression},{effect:effect3,cleanup:cleanup2})=>{let evaluate2=evaluateLater(el,expression);let show=()=>{if(el._x_currentIfEl)
return el._x_currentIfEl;let clone2=el.content.cloneNode(true).firstElementChild;addScopeToNode(clone2,{},el);mutateDom(()=>{el.after(clone2);initTree(clone2);});el._x_currentIfEl=clone2;el._x_undoIf=()=>{clone2.remove();delete el._x_currentIfEl;};return clone2;};let hide=()=>{if(!el._x_undoIf)
return;el._x_undoIf();delete el._x_undoIf;};effect3(()=>evaluate2((value)=>{value?show():hide();}));cleanup2(()=>el._x_undoIf&&el._x_undoIf());});mapAttributes(startingWith("@",into(prefix("on:"))));directive("on",skipDuringClone((el,{value,modifiers,expression},{cleanup:cleanup2})=>{let evaluate2=expression?evaluateLater(el,expression):()=>{};let removeListener=on(el,value,modifiers,(e)=>{evaluate2(()=>{},{scope:{$event:e},params:[e]});});cleanup2(()=>removeListener());}));alpine_default.setEvaluator(normalEvaluator);alpine_default.setReactivityEngine({reactive:reactive2,effect:effect2,release:stop,raw:toRaw});var src_default=alpine_default;window.Alpine=src_default;queueMicrotask(()=>{src_default.start();});})();window.ls.error=function(){return function(error){window.console.error(error);if(window.location.pathname!=='/console'){window.location='/console';}};};window.addEventListener("error",function(event){console.error("ERROR-EVENT:",event.error.message,event.error.stack);});document.addEventListener("account.deleteSession",function(){window.location="/auth/signin";});document.addEventListener("account.create",function(){let container=window.ls.container;let form=container.get('serviceForm');let sdk=container.get('console');let promise=sdk.account.createEmailSession(form.email,form.password);container.set("serviceForm",{},true,true);promise.then(function(){var subscribe=document.getElementById('newsletter').checked;if(subscribe){let alerts=container.get('alerts');let loaderId=alerts.add({text:'Loading...',class:""},0);fetch('https://appwrite.io/v1/newsletter/subscribe',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:form.name,email:form.email,}),}).finally(function(){alerts.remove(loaderId);window.location='/console';});}else{window.location='/console';}},function(error){window.location='/auth/signup?failure=1';});});window.addEventListener("load",async()=>{const bars=12;const realtime=window.ls.container.get('realtime');const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));let current={};window.ls.container.get('console').subscribe(['project','console'],response=>{if(response.events.includes('stats.connections')){for(let project in response.payload){current[project]=response.payload[project]??0;}
return;}
if(response.events.includes('databases.*.collections.*.attributes.*')){document.dispatchEvent(new CustomEvent('databases.createAttribute'));return;}
if(response.events.includes('databases.*.collections.*.indexes.*')){document.dispatchEvent(new CustomEvent('databases.createIndex'));return;}
if(response.events.includes('functions.*.deployments.*')){document.dispatchEvent(new CustomEvent('functions.createDeployment'));return;}
if(response.events.includes('functions.*.executions.*')){document.dispatchEvent(new CustomEvent('functions.createExecution'));return;}});while(true){let newHistory={};for(const project in current){let history=realtime?.history??{};if(!(project in history)){history[project]=new Array(bars).fill({percentage:0,value:0});}
history=history[project];history.push({percentage:0,value:current[project]});if(history.length>=bars){history.shift();}
const highest=history.reduce((prev,curr)=>{return(curr.value>prev)?curr.value:prev;},0);history=history.map(({percentage,value})=>{createdHistory=true;percentage=value===0?0:((Math.round((value/highest)*10)/10)*100);if(percentage>100)percentage=100;else if(percentage==0&&value!=0)percentage=5;return{percentage:percentage,value:value};})
newHistory[project]=history;}
let currentSnapshot={...current};for(let index=.1;index<=1;index+=.05){let currentTransition={...currentSnapshot};for(const project in current){if(project in newHistory){let base=newHistory[project][bars-2].value;let cur=currentSnapshot[project];let offset=(cur-base)*index;currentTransition[project]=base+Math.floor(offset);}}
realtime.setCurrent(currentTransition);await sleep(250);}
realtime.setHistory(newHistory);}});function addAttribute(doc,key){if(!Array.isArray(doc[key])){doc[key]=[];}
doc[key].push(null);return doc;}
(function(window){"use strict";window.ls.container.set('alerts',function(window){return{list:[],ids:0,counter:0,max:5,add:function(message,time){var scope=this;message.id=scope.ids++;message.remove=function(){scope.remove(message.id);};scope.counter++;scope.list.unshift(message);if(scope.counter>scope.max){scope.list.pop();scope.counter--;}
if(time>0){window.setTimeout(function(message){return function(){scope.remove(message.id)}}(message),time);}
return message.id;},remove:function(id){let scope=this;for(let index=0;index<scope.list.length;index++){let obj=scope.list[index];if(obj.id===parseInt(id)){scope.counter--;if(typeof obj.callback==="function"){obj.callback();}
scope.list.splice(index,1);};}}};},true,true);})(window);(function(window){"use strict";window.ls.container.set('appwrite',function(window,env){let config={endpoint:'https://appwrite.io/v1',};let http=function(document,env){let globalParams=[],globalHeaders=[];let addParam=function(url,param,value){let a=document.createElement('a'),regex=/(?:\?|&amp;|&)+([^=]+)(?:=([^&]*))*/g;let match,str=[];a.href=url;param=encodeURIComponent(param);while(match=regex.exec(a.search))if(param!==match[1])str.push(match[1]+(match[2]?"="+match[2]:""));str.push(param+(value?"="+encodeURIComponent(value):""));a.search=str.join("&");return a.href;};let buildQuery=function(params){let str=[];for(let p in params){if(params.hasOwnProperty(p)){str.push(encodeURIComponent(p)+"="+encodeURIComponent(params[p]));}}
return str.join("&");};let addGlobalHeader=function(key,value){globalHeaders[key]={key:key.toLowerCase(),value:value.toLowerCase()};};let addGlobalParam=function(key,value){globalParams.push({key:key,value:value});};addGlobalHeader('content-type','');let call=function(method,path,headers={},params={},progress=null){let i;path=config.endpoint+path;if(-1===['GET','POST','PUT','DELETE','TRACE','HEAD','OPTIONS','CONNECT','PATCH'].indexOf(method)){throw new Error('var method must contain a valid HTTP method name');}
if(typeof path!=='string'){throw new Error('var path must be of type string');}
if(typeof headers!=='object'){throw new Error('var headers must be of type object');}
for(i=0;i<globalParams.length;i++){path=addParam(path,globalParams[i].key,globalParams[i].value);}
for(let key in globalHeaders){if(globalHeaders.hasOwnProperty(key)){if(!headers[globalHeaders[key].key]){headers[globalHeaders[key].key]=globalHeaders[key].value;}}}
if(method==='GET'){for(let param in params){if(param.hasOwnProperty(key)){path=addParam(path,key,params[key]);}}}
switch(headers['content-type']){case'application/json':params=JSON.stringify(params);break;case'multipart/form-data':let formData=new FormData();for(let param in params){if(param.hasOwnProperty(key)){formData.append(key,param[key]);}}
params=formData;break;}
return new Promise(function(resolve,reject){let request=new XMLHttpRequest(),key;request.withCredentials=true;request.open(method,path,true);for(key in headers){if(headers.hasOwnProperty(key)){request.setRequestHeader(key,headers[key]);}}
request.onload=function(){if(4===request.readyState&&399>=request.status){let data=request.response;let contentType=this.getResponseHeader('content-type');contentType=contentType.substring(0,contentType.indexOf(';'));switch(contentType){case'application/json':data=JSON.parse(data);break;}
resolve(data);}else{reject(new Error(request.statusText));}};if(progress){request.addEventListener('progress',progress);request.upload.addEventListener('progress',progress,false);}
request.onerror=function(){reject(new Error("Network Error"));};request.send(params);})};return{'get':function(path,headers={},params={}){return call('GET',path+((params.length>0)?'?'+buildQuery(params):''),headers,{});},'post':function(path,headers={},params={},progress=null){return call('POST',path,headers,params,progress);},'put':function(path,headers={},params={},progress=null){return call('PUT',headers,params,progress);},'patch':function(path,headers={},params={},progress=null){return call('PATCH',path,headers,params,progress);},'delete':function(path,headers={},params={},progress=null){return call('DELETE',path,headers,params,progress);},'addGlobalParam':addGlobalParam,'addGlobalHeader':addGlobalHeader}}(window.document);let analytics={create:function(id,source,activity,url){return http.post('/analytics',{'content-type':'application/json'},{id:id,source:source,activity:activity,url:url,version:env.VERSION,setup:env.SETUP});},};return{analytics:analytics,};},true);})(window);(function(window){"use strict";window.ls.container.set('console',function(window){var sdk=new window.Appwrite();var endpoint=window.location.origin+'/v1';sdk.setEndpoint(endpoint).setProject('console').setLocale(APP_ENV.LOCALE);return sdk;},true);})(window);(function(window){"use strict";window.ls.container.set('date',function(){function format(format,timestamp){var jsdate,f
var txtWords=['Sun','Mon','Tues','Wednes','Thurs','Fri','Satur','January','February','March','April','May','June','July','August','September','October','November','December']
var formatChr=/\\?(.?)/gi
var formatChrCb=function(t,s){return f[t]?f[t]():s}
var _pad=function(n,c){n=String(n)
while(n.length<c){n='0'+n}
return n}
f={d:function(){return _pad(f.j(),2)},D:function(){return f.l().slice(0,3)},j:function(){return jsdate.getDate()},l:function(){return txtWords[f.w()]+'day'},N:function(){return f.w()||7},S:function(){var j=f.j()
var i=j%10
if(i<=3&&parseInt((j%100)/10,10)===1){i=0}
return['st','nd','rd'][i-1]||'th'},w:function(){return jsdate.getDay()},z:function(){var a=new Date(f.Y(),f.n()-1,f.j())
var b=new Date(f.Y(),0,1)
return Math.round((a-b)/864e5)},W:function(){var a=new Date(f.Y(),f.n()-1,f.j()-f.N()+3)
var b=new Date(a.getFullYear(),0,4)
return _pad(1+Math.round((a-b)/864e5/7),2)},F:function(){return txtWords[6+f.n()]},m:function(){return _pad(f.n(),2)},M:function(){return f.F().slice(0,3)},n:function(){return jsdate.getMonth()+1},t:function(){return(new Date(f.Y(),f.n(),0)).getDate()},L:function(){var j=f.Y()
return j%4===0&j%100!==0|j%400===0},o:function(){var n=f.n()
var W=f.W()
var Y=f.Y()
return Y+(n===12&&W<9?1:n===1&&W>9?-1:0)},Y:function(){return jsdate.getFullYear()},y:function(){return f.Y().toString().slice(-2)},a:function(){return jsdate.getHours()>11?'pm':'am'},A:function(){return f.a().toUpperCase()},B:function(){var H=jsdate.getUTCHours()*36e2
var i=jsdate.getUTCMinutes()*60
var s=jsdate.getUTCSeconds()
return _pad(Math.floor((H+i+s+36e2)/86.4)%1e3,3)},g:function(){return f.G()%12||12},G:function(){return jsdate.getHours()},h:function(){return _pad(f.g(),2)},H:function(){return _pad(f.G(),2)},i:function(){return _pad(jsdate.getMinutes(),2)},s:function(){return _pad(jsdate.getSeconds(),2)},u:function(){return _pad(jsdate.getMilliseconds()*1000,6)},e:function(){var msg='Not supported (see source code of date() for timezone on how to add support)'
throw new Error(msg)},I:function(){var a=new Date(f.Y(),0)
var c=Date.UTC(f.Y(),0)
var b=new Date(f.Y(),6)
var d=Date.UTC(f.Y(),6)
return((a-c)!==(b-d))?1:0},O:function(){var tzo=jsdate.getTimezoneOffset()
var a=Math.abs(tzo)
return(tzo>0?'-':'+')+_pad(Math.floor(a/60)*100+a%60,4)},P:function(){var O=f.O()
return(O.substr(0,3)+':'+O.substr(3,2))},T:function(){return'UTC'},Z:function(){return-jsdate.getTimezoneOffset()*60},c:function(){return'Y-m-d\\TH:i:sP'.replace(formatChr,formatChrCb)},r:function(){return'D, d M Y H:i:s O'.replace(formatChr,formatChrCb)},U:function(){return jsdate/1000|0}}
var _date=function(format,timestamp){jsdate=(timestamp===undefined?new Date():(timestamp instanceof Date)?new Date(timestamp):new Date(timestamp*1000))
return format.replace(formatChr,formatChrCb)}
return _date(format,timestamp)}
function strtotime(text,now){var parsed
var match
var today
var year
var date
var days
var ranges
var len
var times
var regex
var i
var fail=false
if(!text){return fail}
text=text.replace(/^\s+|\s+$/g,'').replace(/\s{2,}/g,' ').replace(/[\t\r\n]/g,'').toLowerCase()
var pattern=new RegExp(['^(\\d{1,4})','([\\-\\.\\/:])','(\\d{1,2})','([\\-\\.\\/:])','(\\d{1,4})','(?:\\s(\\d{1,2}):(\\d{2})?:?(\\d{2})?)?','(?:\\s([A-Z]+)?)?$'].join(''))
match=text.match(pattern)
if(match&&match[2]===match[4]){if(match[1]>1901){switch(match[2]){case'-':if(match[3]>12||match[5]>31){return fail}
return new Date(match[1],parseInt(match[3],10)-1,match[5],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000
case'.':return fail
case'/':if(match[3]>12||match[5]>31){return fail}
return new Date(match[1],parseInt(match[3],10)-1,match[5],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000}}else if(match[5]>1901){switch(match[2]){case'-':if(match[3]>12||match[1]>31){return fail}
return new Date(match[5],parseInt(match[3],10)-1,match[1],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000
case'.':if(match[3]>12||match[1]>31){return fail}
return new Date(match[5],parseInt(match[3],10)-1,match[1],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000
case'/':if(match[1]>12||match[3]>31){return fail}
return new Date(match[5],parseInt(match[1],10)-1,match[3],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000}}else{switch(match[2]){case'-':if(match[3]>12||match[5]>31||(match[1]<70&&match[1]>38)){return fail}
year=match[1]>=0&&match[1]<=38?+match[1]+2000:match[1]
return new Date(year,parseInt(match[3],10)-1,match[5],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000
case'.':if(match[5]>=70){if(match[3]>12||match[1]>31){return fail}
return new Date(match[5],parseInt(match[3],10)-1,match[1],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000}
if(match[5]<60&&!match[6]){if(match[1]>23||match[3]>59){return fail}
today=new Date()
return new Date(today.getFullYear(),today.getMonth(),today.getDate(),match[1]||0,match[3]||0,match[5]||0,match[9]||0)/1000}
return fail
case'/':if(match[1]>12||match[3]>31||(match[5]<70&&match[5]>38)){return fail}
year=match[5]>=0&&match[5]<=38?+match[5]+2000:match[5]
return new Date(year,parseInt(match[1],10)-1,match[3],match[6]||0,match[7]||0,match[8]||0,match[9]||0)/1000
case':':if(match[1]>23||match[3]>59||match[5]>59){return fail}
today=new Date()
return new Date(today.getFullYear(),today.getMonth(),today.getDate(),match[1]||0,match[3]||0,match[5]||0)/1000}}}
if(text==='now'){return now===null||isNaN(now)?new Date().getTime()/1000|0:now|0}
if(!isNaN(parsed=Date.parse(text))){return parsed/1000|0}
pattern=new RegExp(['^([0-9]{4}-[0-9]{2}-[0-9]{2})','[ t]','([0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?)','([\\+-][0-9]{2}(:[0-9]{2})?|z)'].join(''))
match=text.match(pattern)
if(match){if(match[4]==='z'){match[4]='Z'}else if(match[4].match(/^([+-][0-9]{2})$/)){match[4]=match[4]+':00'}
if(!isNaN(parsed=Date.parse(match[1]+'T'+match[2]+match[4]))){return parsed/1000|0}}
date=now?new Date(now*1000):new Date()
days={'sun':0,'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6}
ranges={'yea':'FullYear','mon':'Month','day':'Date','hou':'Hours','min':'Minutes','sec':'Seconds'}
function lastNext(type,range,modifier){var diff
var day=days[range]
if(typeof day!=='undefined'){diff=day-date.getDay()
if(diff===0){diff=7*modifier}else if(diff>0&&type==='last'){diff-=7}else if(diff<0&&type==='next'){diff+=7}
date.setDate(date.getDate()+diff)}}
function process(val){var splt=val.split(' ')
var type=splt[0]
var range=splt[1].substring(0,3)
var typeIsNumber=/\d+/.test(type)
var ago=splt[2]==='ago'
var num=(type==='last'?-1:1)*(ago?-1:1)
if(typeIsNumber){num*=parseInt(type,10)}
if(ranges.hasOwnProperty(range)&&!splt[1].match(/^mon(day|\.)?$/i)){return date['set'+ranges[range]](date['get'+ranges[range]]()+num)}
if(range==='wee'){return date.setDate(date.getDate()+(num*7))}
if(type==='next'||type==='last'){lastNext(type,range,num)}else if(!typeIsNumber){return false}
return true}
times='(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec'+'|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?'+'|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)'
regex='([+-]?\\d+\\s'+times+'|'+'(last|next)\\s'+times+')(\\sago)?'
match=text.match(new RegExp(regex,'gi'))
if(!match){return fail}
for(i=0,len=match.length;i<len;i++){if(!process(match[i])){return fail}}
return(date.getTime()/1000)}
return{format:format,strtotime:strtotime}}(),true);})(window);(function(window){"use strict";window.ls.container.set('env',function(){return APP_ENV;},true);})(window);(function(window){"use strict";window.ls.container.set('form',function(){function cast(value,to){if(value&&Array.isArray(value)&&to!=='array'){value=value.map(element=>cast(element,to));return value;}
switch(to){case'int':case'integer':value=parseInt(value);break;case'numeric':value=Number(value);break;case'float':value=parseFloat(value);break;case'string':value=value.toString();if(value.length===0){value=null;}
break;case'json':value=(value)?JSON.parse(value):[];break;case'array':value=(value&&value.constructor&&value.constructor===Array)?value:[value];break;case'array-empty':value=[];break;case'bool':case'boolean':value=(value==='false')?false:value;value=!!value;break;}
return value;}
function toJson(element,json){json=json||{};let name=element.getAttribute('name');let type=element.getAttribute('type');let castTo=element.getAttribute('data-cast-to');let ref=json;if(name&&'FORM'!==element.tagName){if(name.startsWith('[')){let splitName=name.split('.');if(splitName.length>1&&splitName[0].endsWith(']')){name=splitName[splitName.length-1];}}
if('FIELDSET'===element.tagName){if(castTo==='object'){if(json[name]===undefined){json[name]={};}
ref=json[name];}
else{if(!Array.isArray(json[name])){json[name]=[];}
json[name].push({});ref=json[name][json[name].length-1];}}
else if(undefined!==element.value){if('SELECT'===element.tagName&&element.children>0){json[name]=element.children[element.selectedIndex].value;}
else if('radio'===type){if(element.checked){json[name]=element.value;}}
else if('checkbox'===type){const byKey=!!element.getAttribute('data-by-key');if(byKey){if(!Array.isArray(json[name])){json[name]=[];}
if(element.checked){json[name].push(element.value);}}else{if(Array.isArray(json[name])){json[name].push(element.checked);}else{json[name]=element.checked;}}}
else if('file'===type){json[name]=element.files[0];}
else if(undefined!==element.value){if((json[name]!==undefined)&&(!Array.isArray(json[name]))){json[name]=[json[name]];}
if(Array.isArray(json[name])){json[name].push(element.value);}
else{json[name]=element.value;}}
json[name]=cast(json[name],castTo);}}
for(let i=0;i<element.children.length;i++){if(Array.isArray(ref)){ref.push({});toJson(element.children[i],ref[ref.length]);}
else{toJson(element.children[i],ref);}}
return json;}
return{'toJson':toJson}},true,false);})(window);(function(window){"use strict";window.ls.container.set('markdown',function(window){var md=window.markdownit();function renderEm(tokens,idx,opts,_,slf){var token=tokens[idx];if(token.markup==='__'){token.tag='u';}
return slf.renderToken(tokens,idx,opts);}
md.renderer.rules.strong_open=renderEm;md.renderer.rules.strong_close=renderEm;return md;},true);})(window);(function(window){"use strict";window.ls.container.set('rtl',function(){var rtlStock="^ا^ب^ت^ث^ج^ح^خ^د^ذ^ر^ز^س^ش^ص^ض^ط^ظ^ع^غ^ف^ق^ك^ل^م^ن^ه^و^ي^א^ב^ג^ד^ה^ו^ז^ח^ט^י^כ^ך^ל^מ^ם^נ^ן^ס^ע^פ^ף^צ^ץ^ק^ר^ש^ת^";var special=["\n"," "," ","״",'"',"_","'","!","@","#","$","^","&","%","*","(",")","+","=","-","[","]","\\","/","{","}","|",":","<",">","?",",",".","0","1","2","3","4","5","6","7","8","9"];var isRTL=function(value){for(var i=0;i<value.length;i++){if(/\s/g.test(value[i])){continue;}
if(-1===special.indexOf(value[i])){var firstChar=value[i];break;}}
if(-1<rtlStock.indexOf("^"+firstChar+"^")){return true;}
return false;};return{isRTL:isRTL,};},true);})(window);(function(window){"use strict";window.ls.container.set('sdk',function(window,router){var sdk=new window.Appwrite();var endpoint=window.location.origin+'/v1';sdk.setEndpoint(endpoint).setProject(router.params.project||'').setLocale(APP_ENV.LOCALE).setMode('admin');return sdk;},false);})(window);(function(window){"use strict";window.ls.container.set('search',function(window){return{params:{},path:'',pointer:'',selected:'',};},true,true);})(window);(function(window){"use strict";window.ls.container.set('timezone',function(){return{convert:function(unixTime){var timezoneMinutes=new Date().getTimezoneOffset();timezoneMinutes=(timezoneMinutes===0)?0:-timezoneMinutes;return parseInt(unixTime)+(timezoneMinutes*60);}};},true);})(window);(function(window){"use strict";window.ls.container.set('realtime',()=>{return{current:null,history:null,setCurrent:function(currentConnections){var scope=this;scope.current=currentConnections;return scope.current;},setHistory:function(history){var scope=this;scope.history=history;return scope.history;}};},true,true);})(window);window.ls.router.add("/auth/signin",{template:"/auth/signin?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/signup",{template:"/auth/signup?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/recovery",{template:"/auth/recovery?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/recovery/reset",{template:"/auth/recovery/reset?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/confirm",{template:"/auth/confirm?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/join",{template:"/auth/join?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/magic-url",{template:"/auth/magic-url?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/oauth2/success",{template:"/auth/oauth2/success?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/auth/oauth2/failure",{template:"/auth/oauth2/failure?version="+APP_ENV.CACHEBUSTER,scope:"home"}).add("/console",{template:"/console?version="+APP_ENV.CACHEBUSTER,scope:"console"}).add("/console/account",{template:"/console/account?version="+APP_ENV.CACHEBUSTER,scope:"console"}).add("/console/account/:tab",{template:"/console/account?version="+APP_ENV.CACHEBUSTER,scope:"console"}).add("/console/home",{template:"/console/home?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/home/:tab",{template:"/console/home?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/platforms/:platform",{template:function(window){return window.location.pathname+"?version="+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/notifications",{template:"/console/notifications?version="+APP_ENV.CACHEBUSTER,scope:"console"}).add("/console/settings",{template:"/console/settings?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/settings/:tab",{template:"/console/settings?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/webhooks",{template:"/console/webhooks?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/webhooks/webhook",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/webhooks/webhook/new",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/keys",{template:"/console/keys?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/keys/:tab",{template:"/console/keys?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/tasks",{template:"/console/tasks?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/tasks/:tab",{template:"/console/tasks?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/databases",{template:"/console/databases?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/databases/database",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/database/:tab",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/usage",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/collection",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/collection/:tab",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/document",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/databases/document/:tab",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/storage",{template:"/console/storage?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/storage/usage",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/storage/bucket",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/storage/bucket/:tab",{template:function(window){return window.location.pathname+window.location.search+'&version='+APP_ENV.CACHEBUSTER;},scope:"console",project:true}).add("/console/users",{template:"/console/users?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/users/user",{template:"/console/users/user?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/users/user/:tab",{template:"/console/users/user?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/users/teams/team",{template:"/console/users/teams/team?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/users/teams/team/:tab",{template:"/console/users/teams/team?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/users/:tab",{template:"/console/users?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/functions",{template:"/console/functions?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/functions/function",{template:"/console/functions/function?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/functions/function/:tab",{template:"/console/functions/function?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true}).add("/console/functions/:tab",{template:"/console/functions?version="+APP_ENV.CACHEBUSTER,scope:"console",project:true});window.ls.filter.add("avatar",function($value,element){if(!$value){return"";}
let size=element.dataset["size"]||80;let name=$value.name||$value||"";name=(typeof name!=='string')?'--':name;return def="/v1/avatars/initials?project=console"+"&name="+
encodeURIComponent(name)+"&width="+
size+"&height="+
size;}).add("selectedCollection",function($value,router){return $value===router.params.collectionId?"selected":"";}).add("selectedDocument",function($value,router){return $value===router.params.documentId?"selected":"";}).add("localeString",function($value){$value=parseInt($value);return!Number.isNaN($value)?$value.toLocaleString():"";}).add("date",function($value,date){return $value?date.format("Y-m-d",$value):"";}).add("dateTime",function($value,date){return $value?date.format("Y-m-d H:i",$value):"";}).add("dateText",function($value,date){return $value?date.format("d M Y",$value):"";}).add("timeSince",function($value){$value=$value*1000;let seconds=Math.floor((Date.now()-$value)/1000);let unit="second";let direction="ago";if(seconds<0){seconds=-seconds;direction="from now";}
let value=seconds;if(seconds>=31536000){value=Math.floor(seconds/31536000);unit="year";}
else if(seconds>=86400){value=Math.floor(seconds/86400);unit="day";}
else if(seconds>=3600){value=Math.floor(seconds/3600);unit="hour";}
else if(seconds>=60){value=Math.floor(seconds/60);unit="minute";}
if(value!=1){unit=unit+"s";}
return value+" "+unit+" "+direction;}).add("ms2hum",function($value){let temp=$value;const years=Math.floor(temp/31536000),days=Math.floor((temp%=31536000)/86400),hours=Math.floor((temp%=86400)/3600),minutes=Math.floor((temp%=3600)/60),seconds=temp%60;if(days||hours||seconds||minutes){return((years?years+"y ":"")+
(days?days+"d ":"")+
(hours?hours+"h ":"")+
(minutes?minutes+"m ":"")+
Number.parseFloat(seconds).toFixed(0)+"s");}
return"< 1s";}).add("seconds2hum",function($value){var seconds=($value).toFixed(3);var minutes=($value/(60)).toFixed(1);var hours=($value/(60*60)).toFixed(1);var days=($value/(60*60*24)).toFixed(1);if(seconds<60){return seconds+"s";}else if(minutes<60){return minutes+"m";}else if(hours<24){return hours+"h";}else{return days+"d"}}).add("markdown",function($value,markdown){return markdown.render($value);}).add("pageCurrent",function($value,env){return Math.ceil(parseInt($value||0)/env.PAGING_LIMIT)+1;}).add("pageTotal",function($value,env){let total=Math.ceil(parseInt($value||0)/env.PAGING_LIMIT);return total?total:1;}).add("humanFileSize",function($value){if(!$value){return 0;}
let thresh=1000;if(Math.abs($value)<thresh){return $value;}
let units=["kB","MB","GB","TB","PB","EB","ZB","YB"];let u=-1;do{$value/=thresh;++u;}while(Math.abs($value)>=thresh&&u<units.length-1);return $value.toFixed(1);}).add("humanFileUnit",function($value){if(!$value){return'';}
let thresh=1000;if(Math.abs($value)<thresh){return'B';}
let units=["kB","MB","GB","TB","PB","EB","ZB","YB"];let u=-1;do{$value/=thresh;++u;}while(Math.abs($value)>=thresh&&u<units.length-1);return units[u];}).add("statsTotal",function($value){if(!$value){return 0;}
$value=abbreviate($value,0,false,false);return $value??"N/A";}).add("statsGetLast",function($value){if(!$value||$value.length<1){return 0;}
return $value[$value.length-1].value;}).add("statsGetTotal",function($value){if(!$value||$value.length<1){return 0;}
return $value.reduce(function(value,object){return value+object.value},0);}).add("isEmpty",function($value){return(!!$value);}).add("isEmptyObject",function($value){return((Object.keys($value).length===0&&$value.constructor===Object)||$value.length===0)}).add("activeDomainsCount",function($value){let result=[];if(Array.isArray($value)){result=$value.filter(function(node){return(node.verification&&node.certificateId);});}
return result.length;}).add("documentAction",function(container){let collection=container.get('project-collection');let document=container.get('project-document');if(collection&&document&&!document.$id){return'databases.createDocument';}
return'databases.updateDocument';}).add("documentSuccess",function(container){let document=container.get('project-document');if(document&&!document.$id){return',redirect';}
return'';}).add("firstElement",function($value){if($value&&$value[0]){return $value[0];}
return $value;}).add("platformsLimit",function($value){return $value;}).add("limit",function($value){let postfix=($value.length>=50)?'...':'';return $value.substring(0,50)+postfix;;}).add("arraySentence",function($value){if(!Array.isArray($value)){return'';}
return $value.join(", ").replace(/,\s([^,]+)$/,' and $1');}).add("runtimeName",function($value,env){if(env&&env.RUNTIMES&&env.RUNTIMES[$value]){return env.RUNTIMES[$value].name;}
return'';}).add("runtimeLogo",function($value,env){if(env&&env.RUNTIMES&&env.RUNTIMES[$value]){return env.RUNTIMES[$value].logo;}
return'';}).add("runtimeVersion",function($value,env){if(env&&env.RUNTIMES&&env.RUNTIMES[$value]){return env.RUNTIMES[$value].version;}
return'';}).add("indexAttributes",function($value){let output='';for(let i=0;i<$value.attributes.length;i++){output+=$value.attributes[i]+' ('+$value.orders[i]+'), '}
return output.slice(0,-2);}).add("collectionAttributes",function($value){if(!Array.isArray($value)){return[];}
$value.unshift({$id:'$id'});return $value;}).add("documentAttribute",function($value,attribute){if(attribute.key in $value){return $value[attribute.key];}
return null;}).add("accessProject",function($value,router){return($value&&$value.hasOwnProperty(router.params.project))?$value[router.params.project]:0;}).add("first",function($value){return $value[0].$id;}).add("last",function($value){return $value[$value.length-1].$id;});function abbreviate(number,maxPlaces,forcePlaces,forceLetter){number=Number(number);forceLetter=forceLetter||false;if(forceLetter!==false){return annotate(number,maxPlaces,forcePlaces,forceLetter);}
let abbr;if(number>=1e12){abbr="T";}else if(number>=1e9){abbr="B";}else if(number>=1e6){abbr="M";}else if(number>=1e3){abbr="K";}else{abbr="";}
return annotate(number,maxPlaces,forcePlaces,abbr);}
function annotate(number,maxPlaces,forcePlaces,abbr){let rounded=0;switch(abbr){case"T":rounded=number/1e12;break;case"B":rounded=number/1e9;break;case"M":rounded=number/1e6;break;case"K":rounded=number/1e3;break;case"":rounded=number;break;}
if(maxPlaces!==false){let test=new RegExp("\\.\\d{"+(maxPlaces+1)+",}$");if(test.test(""+rounded)){rounded=rounded.toFixed(maxPlaces);}}
if(forcePlaces!==false){rounded=Number(rounded).toFixed(forcePlaces);}
return rounded+abbr;}
window.ls.container.get("view").add({selector:"data-acl",controller:function(element,document,router,alerts){document.body.classList.remove("console");document.body.classList.remove("home");document.body.classList.add(router.getCurrent().view.scope);if(!router.getCurrent().view.project){document.body.classList.add("hide-nav");document.body.classList.remove("show-nav");}else{document.body.classList.add("show-nav");document.body.classList.remove("hide-nav");}
if("/console"===router.getCurrent().path){document.body.classList.add("index");}else{document.body.classList.remove("index");}}}).add({selector:"data-prism",controller:function(window,document,element,alerts){Prism.highlightElement(element);let copy=document.createElement("i");copy.className="icon-docs copy";copy.title="Copy to Clipboard";copy.textContent="Click Here to Copy";copy.addEventListener("click",function(){window.getSelection().removeAllRanges();let range=document.createRange();range.selectNode(element);window.getSelection().addRange(range);try{document.execCommand("copy");alerts.add({text:"Copied to clipboard",class:""},3000);}catch(err){alerts.add({text:"Failed to copy text ",class:"error"},3000);}
window.getSelection().removeAllRanges();});element.parentNode.parentNode.appendChild(copy);}});(function(window){document.addEventListener('alpine:init',()=>{Alpine.store('uploader',{_files:[],files(){return(this._files??[]).filter((file)=>!file.cancelled);},isOpen:true,init(){window.addEventListener('beforeunload',(event)=>{if(this.hasOngoingUploads()){let confirmationMessage="There are incomplete uploads, are you sure you want to leave?";event.returnValue=confirmationMessage;return confirmationMessage;}});},cancelAll(){if(this.hasOngoingUploads()?confirm("Are you sure? This will cancel and remove any ongoing uploads?"):true){this._files.forEach(file=>{if(file.completed||file.failed){this.removeFile(file.id);}else{this.updateFile(file.id,{cancelled:true});}});}},hasOngoingUploads(){let ongoing=false;this._files.some((file)=>{if(!file.completed&&!file.failed){ongoing=true;return;}});return ongoing;},toggle(){this.isOpen=!this.isOpen;},addFile(file){this._files.push(file);},updateFile(id,file){this._files=this._files.map((oldFile)=>id==oldFile.id?{...oldFile,...file}:oldFile);},removeFile(id){const file=this.getFile(id)??{};if(file.completed||file.failed){this._files=this._files.filter((file)=>file.id!==id);}else{if(confirm("Are you sure you want to cancel the upload?")){this.updateFile(id,{cancelled:true});}}},getFile(id){return this._files.find((file)=>file.id===id);},async uploadFile(target){const formData=new FormData(target);const sdk=window.ls.container.get('sdk');const bucketId=formData.get('bucketId');const file=formData.get('file');const fileId=formData.get('fileId');let id=fileId==='unique()'?performance.now():fileId;let read=formData.get('read');if(!file||!fileId){return;}
if(read){read=JSON.parse(read);}
let write=formData.get('write');if(write){write=JSON.parse(write);}
if(this.getFile(id)){this.updateFile(id,{name:file.name,completed:false,failed:false,cancelled:false,error:"",});}else{this.addFile({id:id,name:file.name,progress:0,completed:false,failed:false,cancelled:false,error:"",});}
target.reset();try{const response=await sdk.storage.createFile(bucketId,fileId,file,read,write,(progress)=>{this.updateFile(id,{id:progress.$id,progress:Math.round(progress.progress),error:"",});id=progress.$id;const file=this.getFile(id)??{};if(file.cancelled===true){throw'USER_CANCELLED';}});const existingFile=this.getFile(id)??{};if(existingFile.cancelled){this.updateFile(id,{id:response.$id,name:response.name,failed:false,});id=response.$id;throw'USER_CANCELLED'}else{this.updateFile(id,{id:response.$id,name:response.name,progress:100,completed:true,failed:false,});id=response.$id;}
document.dispatchEvent(new CustomEvent('storage.createFile'));}catch(error){if(error==='USER_CANCELLED'){await sdk.storage.deleteFile(bucketId,id);this.updateFile(id,{cancelled:false,failed:true,});this.removeFile(id);}else{this.updateFile(id,{id:id,failed:true,error:error.message??error});}
document.dispatchEvent(new CustomEvent('storage.createFile'));}}});});})(window);(function(window){document.addEventListener('alpine:init',()=>{Alpine.data('events',()=>({events:new Set(),selected:null,action:null,type:null,subType:null,subSubType:null,resource:null,resourceName:'',subResource:null,subResourceName:'',subSubResource:null,subSubResourceName:'',hasResource:false,hasSubResource:false,hasSubSubResource:false,attribute:null,hasAttribute:false,attributes:[],load(events){this.events=new Set(events);},reset(){this.hasResource=this.hasSubResource=this.hasSubSubResource=this.hasAttribute=false;this.type=this.subType=this.subResource=this.resource=this.attribute=this.selected=this.action=null;},setEvent(){this.hasResource=this.hasSubResource=this.hasSubSubResource=this.hasAttribute=this.action=false;if(!this.selected){this.reset();return;}
let[type,action]=this.selected.split('.');switch(type){case'users':if(action==='update'){this.hasAttribute=true;this.attributes=['email','name','password','status','prefs']}
this.hasResource=true;this.type=type;this.resourceName='User ID';break;case'collections':this.hasResource=this.hasSubResource=true;this.type='databases';this.subType=type;this.resourceName='Database ID';this.subResourceName='Collection ID';break;case'databases':this.hasResource=true;this.type=type;this.resourceName='Database ID';break;case'teams':this.hasResource=true;this.type=type;this.resourceName='Team ID';break;case'buckets':this.hasResource=true;this.type=type;this.resourceName='Bucket ID';break;case'functions':this.hasResource=true;this.type=type;this.resourceName='Function ID';break;case'sessions':this.hasResource=this.hasSubResource=true;this.type='users';this.subType=type;this.resourceName='User ID';this.subResourceName='Session ID';break;case'verification':this.hasResource=this.hasSubResource=true;this.type='users';this.subType=type;this.resourceName='User ID';this.subResourceName='Verification ID';break;case'recovery':this.hasResource=this.hasSubResource=true;this.type='users';this.subType=type;this.resourceName='User ID';this.subResourceName='Recovery ID';break;case'documents':this.hasResource=this.hasSubResource=this.hasSubSubResource=true;this.type='databases';this.subType='collections';this.subSubType=type;this.resourceName='Database ID';this.subResourceName='Collection ID';this.subSubResourceName='Document ID';break;case'attributes':this.hasResource=this.hasSubResource=true;this.type='collections';this.subType=type;this.resourceName='Collection ID';this.subResourceName='Attribute ID';break;case'indexes':this.hasResource=this.hasSubResource=true;this.type='collections';this.subType=type;this.resourceName='Collection ID';this.subResourceName='Index ID';break;case'files':this.hasResource=this.hasSubResource=true;this.type='buckets';this.subType=type;this.resourceName='Bucket ID';this.subResourceName='File ID';break;case'memberships':if(action==='update'){this.hasAttribute=true;this.attributes=['status']}
this.hasResource=this.hasSubResource=true;this.type='teams';this.subType=type;this.resourceName='Team ID';this.subResourceName='Membership ID';break;case'executions':this.hasResource=this.hasSubResource=true;this.type='functions';this.subType=type;this.resourceName='Function ID';this.subResourceName='Execution ID';break;case'deployments':this.hasResource=this.hasSubResource=true;this.type='functions';this.subType=type;this.resourceName='Function ID';this.subResourceName='Deployment ID';break;default:this.hasResource=true;this.hasSubResource=true;this.hasSubSubResource=true;break;}
this.action=action;},showModal(modal){document.documentElement.classList.add("modal-open");modal.classList.remove("close");modal.classList.add("open");},closeModal(modal){document.documentElement.classList.remove("modal-open");modal.classList.add("close");modal.classList.remove("open");},addEvent(modal){this.closeModal(modal);let event=`${this.type}.${this.resource ? this.resource : '*'}`;if(this.hasSubResource){event+=`.${this.subType}.${this.subResource ? this.subResource : '*'}`;}
if(this.hasSubSubResource){event+=`.${this.subSubType}.${this.subSubResource ? this.subSubResource : '*'}`;}
if(this.action){event+=`.${this.action}`;}
if(this.attribute){event+=`.${this.attribute}`;}
this.events.add(event);this.reset();},removeEvent(value){this.events.delete(value);}}));});})(window);(function(window){"use strict";window.ls.view.add({selector:"data-service",controller:function(element,view,container,form,alerts,expression,window){let action=element.dataset["service"];let service=element.dataset["name"]||null;let event=expression.parse(element.dataset["event"]);let confirm=element.dataset["confirm"]||"";let loading=element.dataset["loading"]||"";let loaderId=null;let scope=element.dataset["scope"]||"sdk";let success=element.dataset["success"]||"";let failure=element.dataset["failure"]||"";let running=false;let callbacks={hide:function(){return function(){return element.style.opacity='0';};},reset:function(){return function(){if("FORM"===element.tagName){return element.reset();}
throw new Error("This callback is only valid for forms");};},alert:function(text,classname){return function(alerts){alerts.add({text:text,class:classname||"success"},6000);};},redirect:function(url){return function(router){if(url==="/console"){window.location=url;return;}
router.change(url||"/");};},reload:function(){return function(router){router.reload();};},state:function(keys){let updateQueryString=function(key,value,url){var re=new RegExp("([?&])"+key+"=.*?(&|#|$)(.*)","gi"),hash;if(re.test(url)){if(typeof value!=="undefined"&&value!==null){return url.replace(re,"$1"+key+"="+value+"$2$3");}else{hash=url.split("#");url=hash[0].replace(re,"$1$3").replace(/(&|\?)$/,"");if(typeof hash[1]!=="undefined"&&hash[1]!==null){url+="#"+hash[1];}
return url;}}else{if(typeof value!=="undefined"&&value!==null){var separator=url.indexOf("?")!==-1?"&":"?";hash=url.split("#");url=hash[0]+separator+key+"="+value;if(typeof hash[1]!=="undefined"&&hash[1]!==null){url+="#"+hash[1];}
return url;}else{return url;}}};keys=keys.split(",").map(element=>element.trim());return function(serviceForm,router,window){let url=window.location.href;keys.map(node=>{node=node.split("=");let key=node[0]||"";let name=node[1]||key;let value=getValue(key,"param",serviceForm);url=updateQueryString(name,value?value:null,url);});if(url!==window.location.href){window.history.pushState({},"",url);router.reset();}};},trigger:function(events){return function(document){events=events.trim().split(",");for(let i=0;i<events.length;i++){if(""===events[i]){continue;}
document.dispatchEvent(new CustomEvent(events[i]));}};},setId:function name(params){},default:function(){let collection=container.get('project-collection');let document=container.get('project-document');if(collection&&document&&collection.$id===document.$id){for(const[key,value]of Object.entries(document)){delete document[key];}
if(collection.rules){for(let index=0;index<collection.rules.length;index++){const element=collection.rules[index];switch(element.type){case'text':case'email':case'url':case'ip':document[element.key]=element.default||'';break;case'numeric':document[element.key]=element.default||'0';break;case'boolean':document[element.key]=element.default||false;break;case'document':document[element.key]=element.default||{'$id':'','$collection':'','$permissions':{}};break;default:document[element.key]=null;break;}
if(element.array){document[element.key]=[];}}}}}};let getParams=function getParams(func){const REGEX_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;const REGEX_FUNCTION_PARAMS=/(?:\s*(?:function\s*[^(]*)?\s*)((?:[^'"]|(?:(?:(['"])(?:(?:.*?[^\\]\2)|\2))))*?)\s*(?=(?:=>)|{)/m;const REGEX_PARAMETERS_VALUES=/\s*([\w\\$]+)\s*(?:=\s*((?:(?:(['"])(?:\3|(?:.*?[^\\]\3)))((\s*\+\s*)(?:(?:(['"])(?:\6|(?:.*?[^\\]\6)))|(?:[\w$]*)))*)|.*?))?\s*(?:,|$)/gm;let functionAsString=func.toString();let params=[];let match;functionAsString=functionAsString.replaceAll('={}',"");functionAsString=functionAsString.replaceAll('=[]',"");functionAsString=functionAsString.replace(REGEX_COMMENTS,"");functionAsString=functionAsString.match(REGEX_FUNCTION_PARAMS)[1];if(functionAsString.charAt(0)==="("){functionAsString=functionAsString.slice(1,-1);}
while((match=REGEX_PARAMETERS_VALUES.exec(functionAsString))){params.push(match[1]);}
return params;};let getValue=function(key,prefix,data){let result=null;if(!key){return null;}
let attrKey=prefix+key.charAt(0).toUpperCase()+key.slice(1);if(element.dataset[attrKey]){result=expression.parse(element.dataset[attrKey]);if(element.dataset[attrKey+"CastTo"]==="array"){result=result.split(",");}}
if(typeof data[key]!=='undefined'){result=data[key];}
if(typeof result==='undefined'){result="";}
return result;};let resolve=function(target,prefix="param",data={}){if(!target){return function(){};}
let args=getParams(target);return target.apply(target,args.map(function(value){let result=getValue(value,prefix,data);return result??undefined;}));};let exec=function(event){let parsedSuccess=expression.parse(success);let parsedFailure=expression.parse(failure);let parsedAction=expression.parse(action);parsedSuccess=parsedSuccess&&parsedSuccess!=""?parsedSuccess.split(",").map(element=>element.trim()):[];parsedFailure=parsedFailure&&parsedFailure!=""?parsedFailure.split(",").map(element=>element.trim()):[];element.$lsSkip=true;element.classList.add("load-service-start");if(!document.body.contains(element)){element=undefined;return false;}
if(event){event.preventDefault();}
if(running){return false;}
running=true;element.style.backgroud='red';if(confirm){if(window.confirm(confirm)!==true){element.classList.add("load-service-end");element.$lsSkip=false;running=false;return false;}}
if(loading){loaderId=alerts.add({text:loading,class:""},0);}
let method=container.path(scope+"."+parsedAction);if(!method){throw new Error('Method "'+scope+"."+parsedAction+'" not found');}
let formData="FORM"===element.tagName?form.toJson(element):{};let result=resolve(method,"param",formData);if(!result){return;}
if(Promise.resolve(result)!=result){result=new Promise((resolve,reject)=>{resolve(result);});}
result.then(function(data){if(loaderId!==null){alerts.remove(loaderId);}
if(!element){return;}
running=false;element.style.backgroud='transparent';element.classList.add("load-service-end");if(service){container.set(service.replace(".","-"),data,true,true);}
container.set("serviceData",data,true,true);container.set("serviceForm",formData,true,true);for(let i=0;i<parsedSuccess.length;i++){container.resolve(resolve(callbacks[parsedSuccess[i]],"successParam"+
parsedSuccess[i].charAt(0).toUpperCase()+
parsedSuccess[i].slice(1),{}));}
container.set("serviceData",null,true,true);container.set("serviceForm",null,true,true);element.$lsSkip=false;view.render(element);},function(exception){console.error(exception);if(loaderId!==null){alerts.remove(loaderId);}
if(!element){return;}
running=false;element.style.backgroud='transparent';element.classList.add("load-service-end");for(let i=0;i<parsedFailure.length;i++){container.resolve(resolve(callbacks[parsedFailure[i]],"failureParam"+
parsedFailure[i].charAt(0).toUpperCase()+
parsedFailure[i].slice(1),{text:exception.message??undefined}));}
element.$lsSkip=false;view.render(element);});};let events=event.trim().split(",");for(let y=0;y<events.length;y++){if(""===events[y]){continue;}
switch(events[y].trim()){case"load":exec();break;case"none":break;case"click":case"change":case"keypress":case"keydown":case"keyup":case"input":case"submit":element.addEventListener(events[y],exec);break;default:document.addEventListener(events[y],exec);}}}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-analytics",controller:function(element){let action=element.getAttribute("data-analytics-event")||"click";let doNotTrack=window.navigator.doNotTrack;if(doNotTrack=='1'){return;}
element.addEventListener(action,function(){let category=element.getAttribute("data-analytics-category")||"undefined";let label=element.getAttribute("data-analytics-label")||"undefined";if(!ga){console.error("Google Analytics ga object is not available");}
ga("send",{hitType:"event",eventCategory:category,eventAction:action,eventLabel:label});});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-analytics-activity",controller:function(window,element,appwrite,container){let action=element.getAttribute("data-analytics-event")||"click";let activity=element.getAttribute("data-analytics-label")||"None";let doNotTrack=window.navigator.doNotTrack;if(doNotTrack=='1'){return;}
element.addEventListener(action,function(){let account=container.get('account');let email=account?.email||element?.elements['email']?.value||'';appwrite.analytics.create(email,'console',activity,window.location.href)});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-analytics-pageview",controller:function(window,router,env){if(!ga){console.error("Google Analytics ga object is not available");}
let doNotTrack=window.navigator.doNotTrack;if(doNotTrack=='1'){return;}
let project=router.params["project"]||'None';ga("set","page",window.location.pathname);ga("set","dimension1",project);ga('set','dimension2',env.VERSION);ga('set','dimension3',env.SETUP);ga("send","pageview");}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-clone",controller:function(element,document,view,expression){element.removeAttribute('data-forms-clone');view.render(element);var template=element.innerHTML.toString();var label=element.dataset["label"]||"Add";var icon=element.dataset["icon"]||null;var target=expression.parse(element.dataset["target"]||null);var first=parseInt(element.dataset["first"]||1);var button=document.createElement("button");var debug=element.dataset["debug"]||false;button.type="button";button.innerText=" "+label+" ";button.classList.add("margin-end");button.classList.add("margin-bottom-small");button.classList.add("reverse");if(icon){var iconElement=document.createElement("i");iconElement.className=icon;button.insertBefore(iconElement,button.firstChild);}
if(target){target=document.getElementById(target);}
button.addEventListener("click",function(){var clone=document.createElement(element.tagName);if(element.name){clone.name=element.name;}
clone.innerHTML=template;clone.className=element.className;var input=clone.querySelector("input, select, textarea");view.render(clone);if(debug){console.log('Debug: clone: ',clone);console.log('Debug: target: ',target);}
if(target){target.appendChild(clone);}else{button.parentNode.insertBefore(clone,button);}
if(input){input.focus();}
Array.prototype.slice.call(clone.querySelectorAll("[data-remove]")).map(function(obj){obj.addEventListener("click",function(){clone.parentNode.removeChild(clone);obj.scrollIntoView({behavior:"smooth"});});});Array.prototype.slice.call(clone.querySelectorAll("[data-up]")).map(function(obj){obj.addEventListener("click",function(){if(clone.previousElementSibling){clone.parentNode.insertBefore(clone,clone.previousElementSibling);obj.scrollIntoView({behavior:"smooth"});}});});Array.prototype.slice.call(clone.querySelectorAll("[data-down]")).map(function(obj){obj.addEventListener("click",function(){if(clone.nextElementSibling){clone.parentNode.insertBefore(clone.nextElementSibling,clone);obj.scrollIntoView({behavior:"smooth"});}});});});element.parentNode.insertBefore(button,element.nextSibling);element.parentNode.removeChild(element);button.form.addEventListener('reset',function(event){target.innerHTML='';if(first){button.click();}});if(first){button.click();}}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-add",repeat:false,controller:function(element,view,container,document){for(var i=0;i<element.children.length;i++){let button=document.createElement("button");let template=element.children[i].cloneNode(true);let as=element.getAttribute('data-ls-as');let counter=0;button.type="button";button.innerText="Add";button.classList.add("reverse");button.classList.add("margin-end-small");button.addEventListener('click',function(){container.addNamespace(as,'new-'+counter++);console.log(container.namespaces,container.get(as),as);container.set(as,null,true,true);let child=template.cloneNode(true);view.render(child);element.appendChild(child);element.style.visibility='visible';let inputs=child.querySelectorAll('input,textarea');for(let index=0;index<inputs.length;++index){if(inputs[index].type!=='hidden'){inputs[index].focus();break;}}});element.after(button);}}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-chart",controller:function(element,container,date,document){let wrapper=document.createElement("div");let child=document.createElement("canvas");let sources=element.getAttribute('data-forms-chart');let width=element.getAttribute('data-width')||500;let height=element.getAttribute('data-height')||175;let showXAxis=element.getAttribute('data-show-x-axis')||false;let showYAxis=element.getAttribute('data-show-y-axis')||false;let colors=(element.getAttribute('data-colors')||'blue,green,orange,red').split(',');let themes={'blue':'#29b5d9','green':'#4eb55b','orange':'#fba233','red':'#dc3232','create':'#00b680','read':'#009cde','update':'#696fd7','delete':'#da5d95',};let range={'24h':'H:i','7d':'d F Y','30d':'d F Y','90d':'d F Y'}
let ticksCount=5;element.parentNode.insertBefore(wrapper,element.nextSibling);wrapper.classList.add('content');child.width=width;child.height=height;sources=sources.split(',');wrapper.appendChild(child);let chart=null;let check=function(){let config={type:"line",data:{labels:[],datasets:[]},options:{animation:{duration:0},responsive:true,hover:{mode:"nearest",intersect:false},scales:{x:{display:showXAxis},y:{display:showYAxis,min:0,ticks:{count:ticksCount,fontColor:"#8f8f8f"},}},plugins:{title:{display:false,text:"Stats"},legend:{display:false},tooltip:{mode:"index",intersect:false,caretPadding:0},}}};let highest=0;for(let i=0;i<sources.length;i++){let label=sources[i].substring(0,sources[i].indexOf('='));let path=sources[i].substring(sources[i].indexOf('=')+1);let usage=container.get('usage');let data=usage[path];let value=JSON.parse(element.value);config.data.labels[i]=label;config.data.datasets[i]={};config.data.datasets[i].label=label;config.data.datasets[i].borderColor=themes[colors[i]];config.data.datasets[i].backgroundColor=themes[colors[i]]+'36';config.data.datasets[i].borderWidth=2;config.data.datasets[i].data=[0,0,0,0,0,0,0];config.data.datasets[i].fill=true;if(!data){return;}
let dateFormat=(value.range&&range[value.range])?range[value.range]:'d F Y';for(let x=0;x<data.length;x++){if(data[x].value>highest){highest=data[x].value;}
config.data.datasets[i].data[x]=data[x].value;config.data.labels[x]=date.format(dateFormat,data[x].date);}}
if(highest==0){config.options.scales.y.ticks.stepSize=1;config.options.scales.y.max=ticksCount;}else{highest=Math.ceil(highest/ticksCount)*ticksCount;config.options.scales.y.ticks.stepSize=highest/ticksCount;config.options.scales.y.max=highest;}
if(chart){chart.destroy();}
else{}
chart=new Chart(child.getContext("2d"),config);wrapper.dataset["canvas"]=true;}
check();element.addEventListener('change',check);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-chart-bars",controller:(element)=>{let observer=null;let populateChart=()=>{let history=element.dataset?.history;if(history==0){history=new Array(12).fill({percentage:0,value:0});}else{history=JSON.parse(history);}
element.innerHTML='';history.forEach(({percentage,value},index)=>{const seconds=60-(index*5);const bar=document.createElement('span');bar.classList.add('bar');bar.classList.add(`bar-${percentage}`);bar.classList.add('tooltip');bar.classList.add('down');bar.setAttribute('data-tooltip',`${value} (${seconds} seconds ago)`);element.appendChild(bar);})}
if(observer){observer.disconnect();}else{observer=new MutationObserver(populateChart);observer.observe(element,{attributes:true,attributeFilter:['data-history']});}
populateChart();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-code",controller:function(element,alerts){let lang=element.dataset["formsCode"]||"json";let div=document.createElement("div");let pre=document.createElement("pre");let code=document.createElement("code");let copy=document.createElement("i");div.appendChild(pre);div.appendChild(copy);pre.appendChild(code);element.parentNode.appendChild(div);element.style.display='none';div.className="ide";div.dataset['langLabel']=element.dataset["langLabel"]||'JSON';div.dataset['lang']=element.dataset["lang"]||'json';pre.className="line-numbers";code.className="prism language-"+lang;copy.className="icon-docs copy";copy.textContent="Click Here to Copy";copy.title="Copy to Clipboard";copy.addEventListener("click",function(){window.getSelection().removeAllRanges();let range=document.createRange();range.selectNode(code);window.getSelection().addRange(range);try{document.execCommand("copy");alerts.add({text:"Copied to clipboard",class:""},3000);}catch(err){alerts.add({text:"Failed to copy text ",class:"error"},3000);}
window.getSelection().removeAllRanges();});let check=function(){if(!element.value){return;}
let value=null;try{value=JSON.stringify(JSON.parse(element.value),null,4);}catch(error){value=element.value;}
code.innerHTML=value;Prism.highlightElement(code);div.scrollTop=0;};element.addEventListener("change",check);check();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-color",controller:function(element){var preview=document.createElement("div");var picker=document.createElement("input");picker.type="color";preview.className="color-preview";preview.appendChild(picker);picker.addEventListener("change",syncA);picker.addEventListener("input",syncA);element.addEventListener("input",update);element.addEventListener("change",update);function update(){if(element.validity.valid){preview.style.background=element.value;syncB();}}
function syncA(){element.value=picker.value;update();}
function syncB(){picker.value=element.value;}
element.parentNode.insertBefore(preview,element);update();syncB();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-copy",controller:function(element,alerts,document,window){var button=window.document.createElement("i");button.type="button";button.className="icon-docs note copy";button.style.cursor="pointer";element.parentNode.insertBefore(button,element.nextSibling);var copy=function(event){let disabled=element.disabled;element.disabled=false;element.focus();element.select();document.execCommand("Copy");if(document.selection){document.selection.empty();}else if(window.getSelection){window.getSelection().removeAllRanges();}
element.disabled=disabled;element.blur();alerts.add({text:"Copied to clipboard",class:""},3000);};button.addEventListener("click",copy);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-custom-id",controller:function(element,sdk,console,window){let prevData="";let idType=element.getAttribute('data-id-type');let disableSwitch=element.getAttribute('data-disable-switch');const div=window.document.createElement("div");if(disableSwitch!=="true"){div.className="input-copy";}
const button=window.document.createElement("i");button.type="button";button.style.cursor="pointer";const writer=window.document.createElement("input");writer.type="text";writer.setAttribute("maxlength",element.getAttribute("maxlength"));const placeholder=element.getAttribute("placeholder");if(placeholder){writer.setAttribute("placeholder",placeholder);}
const info=window.document.createElement("div");info.className="text-fade text-size-xs margin-top-negative-small margin-bottom";div.appendChild(writer);if(disableSwitch!=="true"){div.appendChild(button);}
element.parentNode.insertBefore(div,element);element.parentNode.insertBefore(info,div.nextSibling);const switchType=function(event){if(idType=="custom"){idType="auto";setIdType(idType);}else{idType="custom";setIdType(idType);}}
const validate=function(event){const[service,method]=element.dataset["validator"].split('.');const value=event.target.value;if(value.length<1){event.target.setCustomValidity("ID is required");}else{switch(service){case'projects':setValidity(console[service][method](value),event.target);break;default:setValidity(sdk[service][method](value),event.target);}}}
const setValidity=async function(promise,target){try{await promise;target.setCustomValidity("ID already exists");}catch(e){target.setCustomValidity("");}}
const setIdType=function(idType){if(idType=="custom"){element.setAttribute("data-id-type",idType);info.innerHTML="Allowed Characters A-Z, a-z, 0-9, and non-leading underscore, hyphen and dot";if(prevData==='auto-generated'){prevData=""}
writer.setAttribute("value",prevData);writer.value=prevData;element.value=prevData;writer.removeAttribute("disabled");writer.focus();writer.addEventListener('blur',validate);}else{idType='auto'
element.setAttribute("data-id-type",idType);info.innerHTML="Appwrite will generate a unique ID";prevData=writer.value;writer.setAttribute("disabled",true);writer.setAttribute("value","auto-generated");writer.value="auto-generated";element.value='unique()';}
button.className=idType=="custom"?"icon-shuffle copy":"icon-edit copy";}
const syncEditorWithID=function(event){if(element.value!=='unique()'||idType!='auto'){writer.value=element.value;}
if(idType=='auto'){element.value='unique()';}}
const keypress=function(e){const key=e.which||e.keyCode;const ZERO=48;const NINE=57;const SMALL_A=97;const SMALL_Z=122;const CAPITAL_A=65;const CAPITAL_Z=90;const UNDERSCORE=95;const HYPHEN=45;const PERIOD=46;const isNotValidDigit=key<ZERO||key>NINE;const isNotValidSmallAlphabet=key<SMALL_A||key>SMALL_Z;const isNotValidCapitalAlphabet=key<CAPITAL_A||key>CAPITAL_Z;const isNotValidFirstChar=(key===UNDERSCORE||key===HYPHEN||key===PERIOD);if(isNotValidFirstChar&&e.target.value.length==0){e.preventDefault();}
if(key!=UNDERSCORE&&key!=HYPHEN&&key!=PERIOD&&isNotValidDigit&&isNotValidSmallAlphabet&&isNotValidCapitalAlphabet){e.preventDefault();}}
syncEditorWithID();setIdType(idType);writer.addEventListener("change",function(event){element.value=writer.value;});writer.form.addEventListener('reset',function(event){const resetEvent=new Event('reset');element.dispatchEvent(resetEvent);});element.addEventListener('reset',function(event){idType=element.getAttribute('data-id-type');setIdType(idType);});writer.addEventListener('keypress',keypress);button.addEventListener("click",switchType);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-document",controller:function(element,container,search){var formsDocument=(element.dataset["formsDocument"]||'');var searchButton=(element.dataset["search"]||0);let path=container.scope(searchButton);element.addEventListener('click',function(){search.selected=element.value;search.path=path;document.dispatchEvent(new CustomEvent(formsDocument,{bubbles:false,cancelable:true}));});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-duplications",controller:function(element){let validate=function(element){let duplication=0;let form=element.form;for(let i=0;i<form.elements.length;i++){let field=form.elements[i];if(field.name===element.name&&field.value===element.value){duplication++;}}
if(duplication>1){element.setCustomValidity("Duplicated value");}
else{element.setCustomValidity("");}};element.addEventListener('change',function(event){validate(event.target)});element.addEventListener('focus',function(event){validate(event.target)});element.addEventListener('blur',function(event){validate(event.target)});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-document-preview",controller:function(element,container,search){element.addEventListener('change',function(){console.log(element.value);});}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-forms-filter",controller:function(document,container,expression,element,form,di){let name=element.dataset["formsFilter"]||"";let events=element.dataset["event"]||"";let serialize=function(obj,prefix){let str=[],p;for(p in obj){if(obj.hasOwnProperty(p)){let k=prefix?prefix+"["+p+"]":p,v=obj[p];if(v===""){continue;}
str.push(v!==null&&typeof v==="object"?serialize(v,k):encodeURIComponent(k)+"="+encodeURIComponent(v));}}
return str.join("&");};let parse=function(filter){if(filter===""){return null;}
let operatorsMap=["!=",">=","<=","=",">","<"];let operator=null;for(let key=0;key<operatorsMap.length;key++){if(filter.indexOf(operatorsMap[key])>-1){operator=operatorsMap[key];}}
if(operator===null){throw new Error("Invalid operator");}
filter=filter.split(operator);if(filter.length!==2){throw new Error("Invalid filter expression");}
return{key:filter[0],value:filter[1],operator:operator};};let flatten=function(params){let list={};for(let key in params){if(params.hasOwnProperty(key)){if(key!=="filters"){list[key]=params[key];}else{for(let i=0;i<params[key].length;i++){let filter=parse(params[key][i]);if(null===filter){continue;}
list["filters-"+filter.key]=params[key][i];}}}}
return list;};let apply=function(params){let cached=container.get(name);cached=cached?cached.params:[];params=Object.assign(cached,params);container.set(name,{name:name,params:params,query:serialize(params),forward:parseInt(params.offset)+parseInt(params.limit),backward:parseInt(params.offset)-parseInt(params.limit),keys:flatten(params)},true,name);document.dispatchEvent(new CustomEvent(name+"-changed",{bubbles:false,cancelable:true}));};switch(element.tagName){case"INPUT":break;case"TEXTAREA":break;case"BUTTON":element.addEventListener("click",function(){apply(JSON.parse(expression.parse(element.dataset["params"]||"{}")));});break;case"FORM":element.addEventListener("input",function(){apply(form.toJson(element));});element.addEventListener("change",function(){apply(form.toJson(element));});element.addEventListener("reset",function(){setTimeout(function(){apply(form.toJson(element));},0);});events=events.trim().split(",");for(let y=0;y<events.length;y++){if(events[y]==="init"){element.addEventListener("rendered",function(){apply(form.toJson(element));},{once:true});}else{}
element.setAttribute("data-event","none");}
break;default:break;}}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-forms-headers",controller:function(element){let key=document.createElement("input");let value=document.createElement("input");let wrap=document.createElement("div");let cell1=document.createElement("div");let cell2=document.createElement("div");key.type="text";key.className="margin-bottom-no";key.placeholder="Key";value.type="text";value.className="margin-bottom-no";value.placeholder="Value";wrap.className="row thin margin-bottom-small";cell1.className="col span-6";cell2.className="col span-6";element.parentNode.insertBefore(wrap,element);cell1.appendChild(key);cell2.appendChild(value);wrap.appendChild(cell1);wrap.appendChild(cell2);key.addEventListener("input",function(){syncA();});value.addEventListener("input",function(){syncA();});element.addEventListener("change",function(){syncB();});let syncA=function(){element.value=key.value.toLowerCase()+":"+value.value.toLowerCase();};let syncB=function(){let split=element.value.toLowerCase().split(":");key.value=split[0]||"";value.value=split[1]||"";key.value=key.value.trim();value.value=value.value.trim();};syncB();}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-forms-key-value",controller:function(element){let key=document.createElement("input");let value=document.createElement("input");let wrap=document.createElement("div");let cell1=document.createElement("div");let cell2=document.createElement("div");key.type="text";key.className="margin-bottom-no";key.placeholder="Key";key.required=true;value.type="text";value.className="margin-bottom-no";value.placeholder="Value";value.required=true;wrap.className="row thin margin-bottom-small";cell1.className="col span-6";cell2.className="col span-6";element.parentNode.insertBefore(wrap,element);cell1.appendChild(key);cell2.appendChild(value);wrap.appendChild(cell1);wrap.appendChild(cell2);key.addEventListener("input",function(){syncA();});value.addEventListener("input",function(){syncA();});element.addEventListener("change",function(){syncB();});let syncA=function(){element.name=key.value;element.value=value.value;};let syncB=function(){key.value=element.name||"";value.value=element.value||"";};syncB();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-move-down",controller:function(element){Array.prototype.slice.call(element.querySelectorAll("[data-move-down]")).map(function(obj){obj.addEventListener("click",function(){if(element.nextElementSibling){console.log('down',element.offsetHeight);element.parentNode.insertBefore(element.nextElementSibling,element);element.scrollIntoView({block:'center'});}});});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-move-up",controller:function(element){Array.prototype.slice.call(element.querySelectorAll("[data-move-up]")).map(function(obj){obj.addEventListener("click",function(){if(element.previousElementSibling){console.log('up',element);element.parentNode.insertBefore(element,element.previousElementSibling);element.scrollIntoView({block:'center'});}});});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-nav",repeat:false,controller:function(element,view,container,document){let titles=document.querySelectorAll('[data-forms-nav-anchor]');let links=element.querySelectorAll('[data-forms-nav-link]');let minLink=null;let check=function(){let minDistance=null;let minElement=null;for(let i=0;i<titles.length;++i){let title=titles[i];let distance=title.getBoundingClientRect().top;console.log(i);if((minDistance===null||minDistance>=distance)&&(distance>=0)){if(minLink){minLink.classList.remove('selected');}
console.log('old',minLink);minDistance=distance;minElement=title;minLink=links[i];minLink.classList.add('selected');console.log('new',minLink);}}};window.addEventListener('scroll',check);check();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-oauth-custom",controller:function(element){let providers={"Microsoft":{"clientSecret":"oauth2MicrosoftClientSecret","tenantID":"oauth2MicrosoftTenantId"},"Apple":{"keyID":"oauth2AppleKeyId","teamID":"oauth2AppleTeamId","p8":"oauth2AppleP8"},"Okta":{"clientSecret":"oauth2OktaClientSecret","oktaDomain":"oauth2OktaDomain","authorizationServerId":"oauth2OktaAuthorizationServerId"},"Auth0":{"clientSecret":"oauth2Auth0ClientSecret","auth0Domain":"oauth2Auth0Domain"},"Gitlab":{"endpoint":"oauth2GitlabEndpoint","clientSecret":"oauth2GitlabClientSecret",},}
let provider=element.getAttribute("data-forms-oauth-custom");if(!provider||!providers.hasOwnProperty(provider)){console.error("Provider for custom form not set or unknown")}
let config=providers[provider];element.addEventListener('change',sync);let elements={};for(const key in config){if(Object.hasOwnProperty.call(config,key)){elements[key]=document.getElementById(config[key]);elements[key].addEventListener('change',update);}}
function update(){let json={};for(const key in elements){if(Object.hasOwnProperty.call(elements,key)){json[key]=elements[key].value}}
element.value=JSON.stringify(json);}
function sync(){if(!element.value){return;}
let json={};try{json=JSON.parse(element.value);}catch(error){console.error('Failed to parse secret key');}
for(const key in elements){if(Object.hasOwnProperty.call(elements,key)){elements[key].value=json[key]||'';}}}
sync();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-password-meter",controller:function(element,window){var calc=function(password){var score=0;if(!password)return score;var letters=new window.Object();for(var i=0;i<password.length;i++){letters[password[i]]=(letters[password[i]]||0)+1;score+=5.0/letters[password[i]];}
var variations={digits:/\d/.test(password),lower:/[a-z]/.test(password),upper:/[A-Z]/.test(password),nonWords:/\W/.test(password)};var variationCount=0;for(var check in variations){if(variations.hasOwnProperty(check)){variationCount+=variations[check]===true?1:0;}}
score+=(variationCount-1)*10;return parseInt(score);};var callback=function(){var score=calc(this.value);if(""===this.value)return(meter.className="password-meter");if(score>60)return(meter.className="password-meter strong");if(score>30)return(meter.className="password-meter medium");if(score>=0)return(meter.className="password-meter weak");};var meter=window.document.createElement("div");meter.className="password-meter";element.parentNode.insertBefore(meter,element.nextSibling);element.addEventListener("change",callback);element.addEventListener("keypress",callback);element.addEventListener("keyup",callback);element.addEventListener("keydown",callback);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-pell",controller:function(element,window,document,markdown,rtl){var div=document.createElement("div");element.className="pell hide";div.className="input pell";element.parentNode.insertBefore(div,element);element.tabIndex=-1;var turndownService=new TurndownService();turndownService.addRule("underline",{filter:["u"],replacement:function(content){return"__"+content+"__";}});var editor=window.pell.init({element:div,onChange:function onChange(html){alignText();element.value=turndownService.turndown(html);},defaultParagraphSeparator:"p",actions:[{name:"bold",icon:'<i class="icon-bold"></i>'},{name:"underline",icon:'<i class="icon-underline"></i>'},{name:"italic",icon:'<i class="icon-italic"></i>'},{name:"olist",icon:'<i class="icon-list-numbered"></i>'},{name:"ulist",icon:'<i class="icon-list-bullet"></i>'},{name:"link",icon:'<i class="icon-link"></i>'}]});var clean=function(e){e.stopPropagation();e.preventDefault();var clipboardData=e.clipboardData||window.clipboardData;console.log(clipboardData.getData("Text"));window.pell.exec("insertText",clipboardData.getData("Text"));return true;};var alignText=function(){let paragraphs=editor.content.querySelectorAll('p,li');let last='';for(let paragraph of paragraphs){var content=paragraph.textContent;if(content.trim()===''){content=last.textContent;}
if(rtl.isRTL(content)){paragraph.style.direction='rtl';paragraph.style.textAlign='right';}
else{paragraph.style.direction='ltr';paragraph.style.textAlign='left';}
last=paragraph;}};var santize=function(e){clean(e);alignText(e);};element.addEventListener("change",function(){editor.content.innerHTML=markdown.render(element.value);alignText();});editor.content.setAttribute("placeholder",element.placeholder);editor.content.innerHTML=markdown.render(element.value);editor.content.tabIndex=0;alignText();editor.content.onkeydown=function preventTab(event){if(event.which===9){event.preventDefault();if(document.activeElement){var focussable=Array.prototype.filter.call(document.querySelectorAll('a:not([disabled]), button:not([disabled]), select:not([disabled]), input[type=text]:not([disabled]), input[type=checkbox]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])'),function(element){return(element.offsetWidth>0||element.offsetHeight>0||element===document.activeElement);});var index=focussable.indexOf(document.activeElement);if(index>-1){if(event.shiftKey){var prevElement=focussable[index-1]||focussable[focussable.length-1];prevElement.focus();}else{var nextElement=focussable[index+1]||focussable[0];nextElement.focus();}}}}};div.addEventListener("paste",santize);div.addEventListener("drop",santize);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-required",controller:function(element,expression){const isRequired=expression.parse(element.getAttribute('data-forms-required'))==="true";if(isRequired){element.setAttribute("required",true);}else{element.removeAttribute("disabled");}}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-remove",controller:function(element){Array.prototype.slice.call(element.querySelectorAll("[data-remove]")).map(function(obj){obj.addEventListener("click",function(){element.parentNode.removeChild(element);});});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-run",repeat:false,controller:function(element,expression,container){let action=expression.parse(element.dataset["formsRun"]||'');element.addEventListener('click',function(){return container.path(action)();});}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-select-all",controller:function(element){let select=document.createElement("button");let unselect=document.createElement("button");select.textContent='Select All';unselect.textContent='Unselect All';select.classList.add('link');select.classList.add('margin-top-tiny');select.classList.add('margin-start-small');select.classList.add('text-size-small');select.classList.add('pull-end');unselect.classList.add('link');unselect.classList.add('margin-top-tiny');unselect.classList.add('margin-start-small');unselect.classList.add('text-size-small');unselect.classList.add('pull-end');select.type='button';unselect.type='button';element.parentNode.insertBefore(select,element);element.parentNode.insertBefore(unselect,element);select.addEventListener('click',function(){let checkboxes=element.querySelectorAll("input[type='checkbox']");for(var i=0;i<checkboxes.length;i++){checkboxes[i].checked=true;checkboxes[i].dispatchEvent(new Event('change'));}})
unselect.addEventListener('click',function(){let checkboxes=element.querySelectorAll("input[type='checkbox']");for(var i=0;i<checkboxes.length;i++){checkboxes[i].checked=false;checkboxes[i].dispatchEvent(new Event('change'));}})}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-selected",controller:function(element,expression){const isSelected=expression.parse(element.getAttribute('data-forms-selected'))===element.getAttribute('value');if(isSelected){element.setAttribute("selected",true);}else{element.removeAttribute("selected");}}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-show-secret",controller:function(element,document){let button=document.createElement('span');button.className="link pull-end text-size-small margin-top-negative icon-eye";button.innerHTML=(element.type=='password')?'Show Secret':'Hide Secret';button.style.visibility=(element.value=='')?'hidden':'visible';element.insertAdjacentElement("beforebegin",button);button.addEventListener("click",function(event){switch(element.type){case"password":element.type="text";button.innerHTML='Hide Secret';break;case"text":element.type="password";button.innerHTML='Show Secret';break;default:console.warn("data-forms-show-secret: element.type NOT text NOR password");}});let sync=function(event){button.style.visibility=(element.value=='')?'hidden':'visible';};element.addEventListener("keyup",sync);element.addEventListener("change",sync);},});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-switch",controller:function(element){let input=window.document.createElement("input");input.type="checkbox";input.className="button switch "+element.className;let syncA=function(){let value=input.checked?"true":"false"
let old=element.value;element.value=value;if(value!==old){element.dispatchEvent(new Event('change'));}};let syncB=function(){input.checked=(element.value==="true");if(element.disabled){input.setAttribute("disabled",true);}else{input.removeAttribute("disabled");}};input.addEventListener("input",syncA);input.addEventListener("change",syncA);element.addEventListener("input",syncB);element.addEventListener("change",syncB);syncA();element.parentNode.insertBefore(input,element);}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-tags",controller:function(element){let array=[];let tags=window.document.createElement("div");let preview=window.document.createElement("ul");let add=window.document.createElement("input");let listen=function(event){if((event.key==="Enter"||event.key===" "||event.key==="Tab")&&add.value.length>0){array.push(add.value);add.value="";element.value=JSON.stringify(array);check();if(event.key!=="Tab"){event.preventDefault();}}
if((event.key==="Backspace"||event.key==="Delete")&&add.value===""){array.splice(-1,1);element.value=JSON.stringify(array);check();}
return false;};let check=function(){try{array=JSON.parse(element.value)||[];}catch(error){array=[];}
if(!Array.isArray(array)){array=[];}
preview.innerHTML="";for(let index=0;index<array.length;index++){let value=array[index];let tag=window.document.createElement("li");if(!value||value===' '){continue;}
tag.className="tag";tag.textContent=value;tag.addEventListener("click",function(){array.splice(index,1);element.value=JSON.stringify(array);check();});preview.appendChild(tag);}
if(element.required&&array.length===0){add.setCustomValidity("Please add permissions");}else{add.setCustomValidity("");}};tags.className="tags";preview.className="tags-list";add.type="text";add.className="add";add.placeholder=element.placeholder;tags.addEventListener("click",function(){add.focus();});add.addEventListener("keydown",listen);add.addEventListener("blur",function(event){if(add.value!==''){array.push(add.value);add.value="";element.value=JSON.stringify(array);check();}});tags.appendChild(preview);tags.appendChild(add);element.parentNode.insertBefore(tags,element);element.addEventListener("change",check);check();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-text-count",controller:function(element){var counter=document.createElement("div");counter.className="counter";element.parentNode.insertBefore(counter,element.nextSibling);var count=function(){if(0<=element.maxLength){counter.innerText=(element.maxLength-element.value.length).toString()+" / "+
element.maxLength;}else{var words=element.value!==""?element.value.trim().split(" ").length:0;counter.innerText=words+" words and "+element.value.length.toString()+" chars";}};element.addEventListener("keyup",count);element.addEventListener("change",count);element.addEventListener("cut",count);element.addEventListener("paste",count);element.addEventListener("drop",count);count();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-text-direction",controller:function(element,rtl){var setDirection=function(){var value=element.value[0]?element.value:"";var direction="ltr";var align="left";if(rtl.isRTL(value)){direction="rtl";align="right";}
element.style.direction=direction;element.style.textAlign=align;};element.addEventListener("keyup",setDirection);element.addEventListener("change",setDirection);element.addEventListener("cut",setDirection);element.addEventListener("paste",setDirection);element.addEventListener("drop",setDirection);setDirection();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-text-resize",controller:function(element,window){function resize(){var scrollLeft=window.pageXOffset||(window.document.documentElement||window.document.body.parentNode||window.document.body).scrollLeft;var scrollTop=window.pageYOffset||(window.document.documentElement||window.document.body.parentNode||window.document.body).scrollTop;var offset=element.offsetHeight-element.clientHeight;element.style.height="auto";element.style.height=element.scrollHeight+offset+"px";window.scrollTo(scrollLeft,scrollTop);}
element.addEventListener("keyup",resize);element.addEventListener("change",resize);element.addEventListener("cut",resize);element.addEventListener("paste",resize);element.addEventListener("drop",resize);window.addEventListener("resize",resize);resize();}});})(window);(function(window){"use strict";window.ls.container.get("view").add({selector:"data-forms-upload",controller:function(element,container,alerts,expression,env,search){var scope=element.dataset["scope"];var project=expression.parse(element.dataset["project"]||"console");var labelButton=element.dataset["labelButton"]||"Upload";var labelLoading=element.dataset["labelLoading"]||"Uploading...";var previewWidth=element.dataset["previewWidth"]||200;var previewHeight=element.dataset["previewHeight"]||200;var previewAlt=element.dataset["previewAlt"]||200;var accept=element.dataset["accept"]||"";var searchButton=(element.dataset["search"]||0);var required=element.dataset["required"]||false;var className=element.dataset["class"]||"upload";var max=parseInt(element.dataset["max"]||4);var sdk=scope==="sdk"?container.get("sdk"):container.get("console");var output=element.value||null;var wrapper=document.createElement("div");var input=document.createElement("input");var upload=document.createElement("div");var preview=document.createElement("ul");var progress=document.createElement("div");var count=document.createElement("div");wrapper.className=className;input.type="file";input.accept=accept;input.required=required;input.tabIndex=-1;count.className="count";upload.className="button reverse margin-bottom-small";upload.innerHTML='<i class="icon icon-upload"></i> '+labelButton;upload.tabIndex=0;preview.className="preview";progress.className="progress";progress.style.width="0%";progress.style.display="none";var onComplete=function(message){alerts.remove(message);input.disabled=false;upload.classList.remove("disabled");progress.style.width="0%";progress.style.display="none";};var render=function(result){try{result=JSON.parse(result);}catch(err){}
preview.innerHTML="";count.innerHTML="0 / "+max;if(!result){return;}
var file=document.createElement("li");var image=document.createElement("img");image.src=image.src=env.API+"/storage/buckets/"+
result.bucketId+"/files/"+
result.fileId+"/preview?width="+
previewWidth+"&height="+
previewHeight+"&project="+project+"&mode=admin";image.alt=previewAlt;file.className="file avatar";file.tabIndex=0;file.appendChild(image);preview.appendChild(file);var remove=(function(result){return function(event){render(result.$id);element.value='';};})(result);file.addEventListener("click",remove);file.addEventListener("keypress",remove);element.value=JSON.stringify(result);};input.addEventListener("change",function(){var message=alerts.add({text:labelLoading,class:""},0);var files=input.files;var read=JSON.parse(expression.parse(element.dataset["read"]||"[]"));var write=JSON.parse(expression.parse(element.dataset["write"]||"[]"));sdk.storage.createFile('default','unique()',files[0],read,write).then(function(response){onComplete(message);render({bucketId:response.bucketId,fileId:response.$id});},function(error){alerts.add({text:"An error occurred!",class:""},3000);onComplete(message);});input.disabled=true;});element.addEventListener("change",function(){if(!element.value){return;}
render(element.value);wrapper.scrollIntoView();});upload.addEventListener("keypress",function(){input.click();});element.parentNode.insertBefore(wrapper,element);wrapper.appendChild(preview);wrapper.appendChild(progress);wrapper.appendChild(upload);upload.appendChild(input);render(output);if(searchButton){let searchOpen=document.createElement("button");searchOpen.type='button';searchOpen.innerHTML='<i class="icon icon-search"></i> Search';searchOpen.classList.add('reverse');let path=container.scope(searchButton);searchOpen.addEventListener('click',function(){search.selected=element.value;search.path=path;document.dispatchEvent(new CustomEvent("open-file-search",{bubbles:false,cancelable:true}));});wrapper.appendChild(searchOpen);}}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-cookies",controller:function(element,alerts,cookie,env){if(!cookie.get("cookie-alert")){let text=element.dataset["cookies"]||"";alerts.add({text:text,class:"cookie-alert",link:env.HOME+"/policy/cookies",label:'Learn More',callback:function(){cookie.set("cookie-alert","true",365*10);}},0);}}});})(window);(function(window){"use strict";window.ls.view.add({selector:'data-general-copy',repeat:false,controller:function(document,element,alerts){let button=document.createElement("i");button.type="button";button.title="Copy to Clipboard";button.className=element.getAttribute("data-class")||"icon-docs note copy";button.style.cursor="pointer";element.parentNode.insertBefore(button,element.nextSibling);let copy=function(event){window.getSelection().removeAllRanges();let range=document.createRange();range.selectNode(element);window.getSelection().addRange(range);try{document.execCommand("copy");alerts.add({text:"Copied to clipboard",class:""},3000);}catch(err){alerts.add({text:"Failed to copy text ",class:"error"},3000);}
window.getSelection().removeAllRanges();};button.addEventListener("click",copy);}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-page-title",repeat:true,controller:function(element,document,expression){document.title=expression.parse(element.getAttribute("data-page-title"))||document.title;}});})(window);(function(window){"use strict";window.ls.view.add({selector:'data-general-scroll-to',repeat:false,controller:function(element,window){let button=window.document.createElement('button');button.className='scroll-to icon-up-dir';button.alt='Back To Top';button.title='Back To Top';button.addEventListener('click',function(){element.scrollIntoView(true,{behavior:'smooth'});button.blur();},false);element.appendChild(button);}});})(window);(function(window){"use strict";window.ls.view.add({selector:'data-general-scroll-direction',repeat:false,controller:function(element,window){let position=0;let check=function(){let direction=window.document.documentElement.scrollTop;if(direction>position){element.classList.remove('scroll-to-top')
element.classList.add('scroll-to-bottom')}
else{element.classList.remove('scroll-to-bottom')
element.classList.add('scroll-to-top')}
position=direction;let current=Math.ceil(direction/window.innerHeight);element.setAttribute('data-views-total',Math.ceil(element.scrollHeight/window.innerHeight));element.setAttribute('data-views-current',current);if(element.scrollHeight<=(direction+element.offsetHeight+300)&&direction>0){element.classList.add('scroll-end')}
else{element.classList.remove('scroll-end')}};window.addEventListener('scroll',check,false);window.addEventListener('resize',check,false);check();}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-setup",controller:function(element,console,form,alerts,router){element.addEventListener("submit",function(event){event.preventDefault();let loaderId=alerts.add({text:'Creating new project...',class:""},0);let formData=form.toJson(element);formData["name"]=formData["name"]||(element.dataset["defaultName"]||"");console.teams.create('unique()',formData["name"]||"").then(function(data){let team=data["$id"];formData=JSON.parse(JSON.stringify(formData).replace(new RegExp("{{teamId}}","g"),team));console.projects.create(formData["projectId"],formData["name"],team).then(function(project){alerts.remove(loaderId);window.location.href="/console/home?project="+project["$id"];},function(){throw new Error("Failed to setup project");});},function(){throw new Error("Setup failed creating project team");});});}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-switch",controller:function(element,router,document){let check=function(c){if(!element.value){return;}
if(element.value===router.params.project){return;}
return router.change("/console/home?project="+element.value);};element.addEventListener("change",function(){check();});}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-general-theme",controller:function(element,router,document){let toggle=function(c){if(document.body.classList.contains('theme-light')){document.body.classList.remove('theme-light');document.body.classList.add('theme-dark');window.localStorage.setItem('user-theme','theme-dark')}
else{document.body.classList.remove('theme-dark');document.body.classList.add('theme-light');window.localStorage.setItem('user-theme','theme-light')}};element.addEventListener("click",function(){toggle();});}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-version",controller:function(alerts,env,cookie){let cookieName="version-update-"+env.VERSION.replace(/\./g,"_");if(!cookie.get(cookieName)){var xhr=new XMLHttpRequest();xhr.open('GET','https://appwrite.io/version',true);xhr.onload=function(){if(this.readyState==4&&this.status==200){let data=JSON.parse(this.responseText);let text='Appwrite version '+data.version+' is available, check the';if(isNewerVersion(env.VERSION,data.version)){alerts.add({text:text,class:"success",link:"https://github.com/appwrite/appwrite/releases",label:'release notes',callback:function(){cookie.set(cookieName,"true",365*10);}},0);}}};xhr.send(null);function isNewerVersion(oldVer,newVer){const oldParts=oldVer.split('.')
const newParts=newVer.split('.')
for(var i=0;i<newParts.length;i++){const a=parseInt(newParts[i])||0
const b=parseInt(oldParts[i])||0
if(a>b)return true
if(a<b)return false}
return false}}}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-paging-back",controller:function(element,container,expression,env){let paths=[];let limit=env.PAGING_LIMIT;let check=function(){let offset=parseInt(expression.parse(element.dataset["offset"])||"0");paths=paths.concat(expression.getPaths());if(offset-limit<0){element.disabled=true;}else{element.disabled=false;element.value=offset-limit;}};check();for(let i=0;i<paths.length;i++){let path=paths[i].split(".");while(path.length){container.bind(element,path.join("."),check);path.pop();}}}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-paging-next",controller:function(element,container,expression,env){let paths=[];let limit=env.PAGING_LIMIT;let check=function(){let offset=parseInt(expression.parse(element.dataset["offset"])||"0");paths=paths.concat(expression.getPaths());let total=parseInt(expression.parse(element.dataset["total"])||"0");paths=paths.concat(expression.getPaths());if(offset+limit>=total){element.disabled=true;}else{element.disabled=false;element.value=offset+limit;}};check();for(let i=0;i<paths.length;i++){let path=paths[i].split(".");while(path.length){container.bind(element,path.join("."),check);path.pop();}}}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ui-highlight",controller:function(element,expression,document){let check=function(){let links=element.getElementsByTagName("a");let selected=null;let list=[];for(let i=0;i<links.length;i++){list.push(links[i]);}
list.sort(function(a,b){return a.pathname.length-b.pathname.length;});if(selected&&list[selected].dataset["selected"]){let parent=element.querySelector("a[href='"+list[selected].dataset["selected"]+"']");if(parent){parent.classList.remove("selected");}}
for(let i=0;i<list.length;i++){let path=list[i].pathname;if(path===window.location.pathname.substring(0,path.length)){list[i].classList.add("selected");if(selected!==null){list[selected].classList.remove("selected");}
selected=i;}else{list[i].classList.remove("selected");}}
if(selected&&list[selected].dataset["selected"]){let parent=element.querySelector("a[href='"+list[selected].dataset["selected"]+"']");if(parent){parent.classList.add("selected");}}};document.addEventListener("state-changed",check);check();},});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ls-ui-loader",controller:function(element,document){document.addEventListener('account.get',function(){element.classList.add('loaded');});}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ui-modal",controller:function(document,element,expression){let name=expression.parse(element.dataset["name"]||'');let buttonText=expression.parse(element.dataset["buttonText"]||"");let buttonElement=expression.parse(element.dataset["buttonElement"]||"button");let buttonClass=expression.parse(element.dataset["buttonClass"]||"button-class");let buttonIcon=expression.parse(element.dataset["buttonIcon"]||'');let buttonEvent=expression.parse(element.dataset["buttonEvent"]||"");let buttonHide=expression.parse(element.dataset["buttonHide"]||"");let buttonAlias=expression.parse(element.dataset["buttonAlias"]||"");let buttonElements=!buttonAlias?[document.createElement(buttonElement)]:document.querySelectorAll(buttonAlias);let openEvent=expression.parse(element.dataset["openEvent"]||'');let closeEvent=expression.parse(element.dataset["closeEvent"]||'submit');let background=document.getElementById("modal-bg");if(!background){background=document.createElement("div");background.id="modal-bg";background.className="modal-bg";document.body.appendChild(background);background.addEventListener("click",function(){document.dispatchEvent(new CustomEvent("modal-close",{bubbles:false,cancelable:true}));});}
if(!buttonAlias){buttonElements.forEach(button=>{button.innerText=buttonText;button.className=buttonClass;button.type=buttonElement;if(buttonIcon){let iconElement=document.createElement("i");iconElement.className=buttonIcon;button.insertBefore(iconElement,button.firstChild);}});}
if(buttonEvent){buttonElements.forEach(button=>{button.addEventListener("click",function(){document.dispatchEvent(new CustomEvent(buttonEvent,{bubbles:false,cancelable:true}));});});}
element.classList.add("modal");if(!buttonAlias&&!buttonHide){buttonElements.forEach(button=>{element.parentNode.insertBefore(button,element);});}
let open=function(){document.documentElement.classList.add("modal-open");document.dispatchEvent(new CustomEvent("modal-open",{bubbles:false,cancelable:true}));element.classList.add("open");element.classList.remove("close");let form=element.querySelector('form');let elements=form?form.querySelectorAll('[name]'):[];for(const element of elements){if(element.type!=='hidden'&&element.type!=='button'&&element.type!=='submit'&&!element.disabled){element.focus();break;}}};let close=function(event){document.documentElement.classList.remove("modal-open");element.classList.add("close");element.classList.remove("open");};if(name){document.querySelectorAll("[data-ui-modal-ref='"+name+"']").forEach(function(elem){elem.addEventListener("click",open);});}
if(openEvent){document.addEventListener(openEvent,open);}
buttonElements.forEach(button=>{button.addEventListener("click",open);});document.addEventListener("keydown",function(event){if(event.which===27){close();}});element.addEventListener("blur",close);let closeButtons=element.querySelectorAll("[data-ui-modal-close]");for(let i=0;i<closeButtons.length;i++){closeButtons[i].addEventListener("click",close);}
document.addEventListener("modal-close",close);element.addEventListener(closeEvent,close);}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ls-ui-open",controller:function(element,window){let def=element.classList.contains("open")?"open":"close";let buttonClass=element.dataset["buttonClass"]||"ls-ui-open";let buttonText=element.dataset["buttonText"]||"";let buttonIcon=element.dataset["buttonIcon"]||"";let buttonAria=element.dataset["buttonAria"]||"Open";let buttonSelector=element.dataset["buttonSelector"]||"";let hover=element.hasAttribute("data-hover");let blur=element.hasAttribute("data-blur");let button=window.document.createElement("button");let isTouch=function(){return("ontouchstart"in window||navigator.maxTouchPoints);};button.innerText=buttonText;button.className=buttonClass;button.type="button";if(buttonIcon){let icon=window.document.createElement("i");icon.className=buttonIcon;button.insertBefore(icon,button.firstChild);}
if(buttonAria){button.setAttribute('aria-label',buttonAria);}
if(def==="close"){element.classList.add("close");element.classList.remove("open");}else{element.classList.add("open");element.classList.remove("close");}
button.addEventListener("click",function(){element.classList.toggle("open");element.classList.toggle("close");});if(hover&&!isTouch()){element.addEventListener("mouseover",function(){element.classList.add("open");element.classList.remove("close");});element.addEventListener("mouseout",function(){element.classList.add("close");element.classList.remove("open");});}
let close=function(){element.classList.add("close");element.classList.remove("open");};let closeDelay=function(){window.setTimeout(function(){close();},400);};let findParent=function(tagName,el){if((el.nodeName||el.tagName).toLowerCase()===tagName.toLowerCase()){return el;}
while((el=el.parentNode)){if((el.nodeName||el.tagName).toLowerCase()===tagName.toLowerCase()){return el;}}
return null;};if(blur){button.addEventListener("blur",closeDelay);}
if(buttonSelector){let buttonElements=element.querySelectorAll(buttonSelector);buttonElements.forEach(node=>{node.addEventListener("click",function(){element.classList.toggle("open");element.classList.toggle("close");});if(blur){node.addEventListener("blur",closeDelay);}});}
element.addEventListener('click',function(event){let targetA=findParent('a',event.target);let targetB=findParent('button',event.target);if(!targetA&&!targetB){return false;}
if(targetA&&!targetA.href){return false;}
if(targetB&&!targetB.classList.contains('link')){return false;}
closeDelay();});element.insertBefore(button,element.firstChild);}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ui-phases",controller:function(element,window,document,expression,router,view){var tabs=document.createElement("ul");var container=document.createElement("div");var titles=Array.prototype.slice.call(element.querySelectorAll("li > h1"));var next=Array.prototype.slice.call(element.querySelectorAll("[data-next]"));var previous=Array.prototype.slice.call(element.querySelectorAll("[data-previous]"));var position=0;var init=false;if(titles.length===0){titles=Array.prototype.slice.call(element.querySelectorAll("li > h2"));}
if(titles.length===0){titles=Array.prototype.slice.call(element.querySelectorAll("li > h3"));}
if(titles.length===0){titles=Array.prototype.slice.call(element.querySelectorAll("li > h4"));}
if(titles.length===0){titles=Array.prototype.slice.call(element.querySelectorAll("li > h5"));}
if(titles.length===0){titles=Array.prototype.slice.call(element.querySelectorAll("li > h6"));}
for(var i=0;i<element.children.length;i++){var tabState=expression.parse(element.children[i].dataset["state"]||"");if(tabState&&tabState===(window.location.pathname+window.location.search).substring(0,tabState.length)){position=i;}}
var setTab=function(index){var tabState=expression.parse(element.children[index].dataset["state"]||"");var url="";if(tabState!==""&&tabState!==window.location.pathname+window.location.search){var parser=document.createElement("a");parser.href=tabState;url=!init?parser.pathname+window.location.search:tabState;if(position!=index){window.history.pushState({},"",url);router.reset();}}
element.children[position].classList.remove("selected");element.children[index].classList.add("selected");tabs.children[position].classList.remove("selected");tabs.children[index].classList.add("selected");position=index;document.dispatchEvent(new CustomEvent("tab-changed"));init=true;};tabs.classList.add("tabs");container.classList.add("container");container.classList.add("close");container.dataset["lsUiOpen"]="";container.dataset["buttonClass"]="icon icon-down-dir";titles.map(function(obj,i){var title=document.createElement("li");title.innerHTML=obj.innerHTML;title.className=obj.className;title.tabIndex=0;tabs.appendChild(title);title.addEventListener("click",function(){setTab(i);});title.addEventListener("keyup",function(){if(event.which===13){setTab(i);}});view.render(title);});next.map(function(obj){obj.addEventListener("click",function(){setTab(position+1);});});previous.map(function(obj){obj.addEventListener("click",function(){setTab(position-1);});});setTab(position);container.appendChild(tabs);element.parentNode.insertBefore(container,element);}});})(window);(function(window){window.ls.container.get("view").add({selector:"data-ls-ui-trigger",controller:function(element,document,expression){let trigger=expression.parse(element.dataset["lsUiTrigger"]||'').trim().split(',');let event=expression.parse(element.dataset["event"]||'click');let debug=element.getAttribute('data-debug')||false;for(let index=0;index<trigger.length;index++){let name=trigger[index];element.addEventListener(event,function(){if(debug){console.log('Debug: event triggered: '+name);}
document.dispatchEvent(new CustomEvent(name));});}}});})(window);