@lmjs/cli 2.5.1 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -12,6 +12,15 @@ LumenJS comes along with MobiusCSS which is a utility-first CSS framework packed
|
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
|
|
15
|
+
## For AI coding agents
|
|
16
|
+
LumenJS is not Vue or React. Read the plain-text reference before writing `.view` files:
|
|
17
|
+
[lumenjs.com/llms.txt](https://lumenjs.com/llms.txt) (short guide) and
|
|
18
|
+
[lumenjs.com/llms/lumenjs.txt](https://lumenjs.com/llms/lumenjs.txt) (full reference).
|
|
19
|
+
`lm create` adds an `AGENTS.md` + `CLAUDE.md` with the same pointer to every new project, and
|
|
20
|
+
`lm update-core` adds them to existing projects.
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
15
24
|
## Installation
|
|
16
25
|
Using npm:
|
|
17
26
|
```
|
|
@@ -62,7 +71,8 @@ Update This Project's Runtime (src/js/lm.js, src/css/mobius.css) To Match The In
|
|
|
62
71
|
lm update-core
|
|
63
72
|
```
|
|
64
73
|
Run this after updating `@lmjs/cli` globally — an existing project's runtime is copied once, at
|
|
65
|
-
`lm create` time, and isn't kept in sync automatically. `lm
|
|
74
|
+
`lm create` time, and isn't kept in sync automatically. `lm build` stops with an error if the
|
|
75
|
+
project's runtime is too old for the installed CLI. `lm purge` still works as an alias.
|
|
66
76
|
|
|
67
77
|
|
|
68
78
|
|
package/dist/lib/fcs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const fetch=require("node-fetch");const path=require("path");const fs=require("fs");const nodemon=require("nodemon");var _acorn=require("acorn");var acorn=require("acorn-loose");function parseScriptJs(source){let ast;try{ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"})}catch(e){ast=acorn.parse(source,{ecmaVersion:"latest"})}return stripAstPositions(ast)}function precompileViewScripts(groups){let failed=0;function visit(nodes,vars,inSection,file){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;const sectioned=inSection||n.type==="section"||n.type==="sections";const nm=String(n.name||"").toLowerCase();if((nm==="script"||nm==="js")&&Array.isArray(n.children)&&n.children[0]&&n.children[0].type==="text"){const t=n.children[0];if(t.content||t.jst){try{const ast=t.jst||_acorn.parse(t.content,{ecmaVersion:"latest",sourceType:"script"});const code=_walk.getWatcher(ast,{name:file},sectioned?void 0:(vars||[]).slice(),["__LMROOT__"]).code;new Function(code);t.pre=code;delete t.content;delete t.jst}catch(e){failed++;console.warn("\x1B[33mLumenJS: could not precompile a <script> in "+file+": "+(e&&e.message)+" (it will be compiled in the browser)\x1B[0m")}}}visit(n.children,vars,sectioned,file)}}for(const group of groups){const isTpl=group.kind==="tpls";for(const key in group.files){const entry=group.files[key];if(!entry||!Array.isArray(entry.hst))continue;const file=Buffer.from(key,"base64").toString().split(/[\\/]/).slice(-2).join("/");visit(entry.hst,entry.reactiveVars,isTpl,file)}}return failed}exports.precompileViewScripts=precompileViewScripts;function stripDevOnlyRuntime(src){const a=src.indexOf("var __lmDevOnlyStart__ = 1;");const b=src.indexOf("var __lmDevOnlyEnd__ = 1;");if(a<0||b<a)return src;return src.slice(0,a)+src.slice(b+"var __lmDevOnlyEnd__ = 1;".length)}exports.stripDevOnlyRuntime=stripDevOnlyRuntime;const _HST_EMPTY_OBJ={attrs:1,ax:1,evs:1,ex:1};function compactHstReplacer(key,value){if(_HST_EMPTY_OBJ[key]===1&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return void 0;if(key==="isV"&&value===false)return void 0;if((key==="mss"||key==="children")&&Array.isArray(value)&&value.length===0)return void 0;return value}exports.compactHstReplacer=compactHstReplacer;function scriptPayload(source){try{_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});return{content:source}}catch(e){return{jst:parseScriptJs(source)}}}exports.scriptPayload=scriptPayload;function stripAstPositions(node){if(Array.isArray(node)){for(let i=0;i<node.length;i++)stripAstPositions(node[i]);return node}if(!node||typeof node!=="object")return node;delete node.start;delete node.end;delete node.loc;delete node.range;for(const k in node){const v=node[k];if(v&&typeof v==="object")stripAstPositions(v)}return node}exports.stripAstPositions=stripAstPositions;var _min=require("html-minifier").minify;var he=require("he");const _FD=require("ftp-deploy");const _fD=new _FD;global.astring=global.astring||require("astring");const _corePackageDir=path.dirname(require.resolve("@lmjs/core/package.json"));const _walk=require(path.join(_corePackageDir,"src","walk.js"));const _npmBundle=require(path.join(__dirname,"npm-bundle.js"));exports.hasOwnDependencies=_npmBundle.hasOwnDependencies;exports.buildEntryWithImports=_npmBundle.buildEntryWithImports;const _pluginsBundle=require(path.join(__dirname,"plugins-esbuild-plugin.js"));const _vault=require(path.join(__dirname,"vault.js"));exports.login=_vault.login;exports.apiSet=_vault.apiSet;exports.apiUpdate=_vault.apiUpdate;exports.apiGet=_vault.apiGet;exports.apiList=_vault.apiList;exports.apiRemove=_vault.apiRemove;function selectedProjectPlugins(projectRoot){try{let deps={};const pkgPath=path.join(projectRoot,"package.json");if(fs.existsSync(pkgPath)){const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));Object.assign(deps,pkg.dependencies||{})}for(const key of detectUsedPlugins(projectRoot))if(!deps.hasOwnProperty(key))deps[key]="*";if(!Object.keys(deps).length)return[];return _pluginsBundle.selectedRegistryEntries(deps)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;const PLUGIN_SIGNATURES={"select2":[/\.select2\s*\(/,/<[a-z][^>]*\s(?:sl|slct)(?=[\s>=\/])/i],"flickity":[/\.flickity\s*\(/,/\bFlickity\b/,/<[a-z][^>]*\scrslf(?=[\s>=\/])/i],"bootstrap-colorpicker":[/\.colorpicker\s*\(/,/<input[^>]*\scolor(?=[\s>=\/])/i],"bootstrap-datetimepicker":[/\.datetimepicker\s*\(/,/<input[^>]*\s(?:date|time|datetime)(?=[\s>=\/])/i],"jquery-ui-dist":[/\.(?:sortable|draggable|droppable|resizable|datepicker|autocomplete|slider|accordion)\s*\(/,/<[a-z][^>]*\s(?:sort|drag|drop)(?=[\s>=\/])/i],"jquery.easing":[/\beas(?:e|ing)(?:In|Out)[A-Z]\w*/],"nestedSortable":[/\.nestedSortable\s*\(/],"jquery.numeric":[/\.numeric\s*\(/,/<input[^>]*\s(?:numeric|integer|decimal)(?=[\s>=\/])/i],"timeago":[/\.timeago\s*\(/,/\$\.timeago\b/],"slick-carousel":[/\.(?:crsl|slick)\s*\(/,/<[a-z][^>]*\scrsl(?=[\s>=\/])/i],"@iconify/iconify":[/class=["'][^"']*\biconify\b/,/\bIconify\./],"rellax":[/\bRellax\b/],"headroom.js":[/\bHeadroom\b/,/<[a-z][^>]*\spinnable(?=[\s>=\/])/i],"in-view":[/\binView\b/],"gsap":[/\bgsap\b/,/\bTween(?:Max|Lite)\b/,/\bTimeline(?:Max|Lite)\b/],"jquery.caret":[/\.caret\s*\(/],"jquery-tageditor":[/\.tagEditor\s*\(/,/<[a-z][^>]*\stags(?=[\s>=\/])/i],"jquery-lazy":[/\.lazy\s*\(/,/<img[^>]*\slazy(?=[\s>=\/])/i]};function detectUsedPlugins(projectRoot){const src=path.join(projectRoot,"src");if(!fs.existsSync(src))return[];let indexHtml="";try{indexHtml=fs.readFileSync(path.join(src,"index.html"),"utf8")}catch(e){}const texts=[];(function walk(dir){let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){return}for(const e of entries){const p=path.join(dir,e.name);if(e.isDirectory()){if(e.name==="node_modules"||e.name==="js"||e.name==="css"||e.name==="images")continue;walk(p)}else if(/\.(view|tpl|layout)$/.test(e.name)){try{texts.push(fs.readFileSync(p,"utf8"))}catch(x){}}}})(src);try{texts.push(fs.readFileSync(path.join(src,"index.js"),"utf8"))}catch(e){}for(const s of detectLocalProjectScripts(indexHtml)){try{texts.push(fs.readFileSync(path.join(src,s.replace(/^\//,"")),"utf8"))}catch(e){}}const all=texts.join("\n");const loadedByPage=key=>new RegExp(`<script[^>]+src=["'][^"']*`+key.replace(/^@[^/]+\//,"").replace(/\.js$/,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i").test(indexHtml);const found=[];for(const key in PLUGIN_SIGNATURES){if(loadedByPage(key))continue;if(PLUGIN_SIGNATURES[key].some(re=>re.test(all)))found.push(key)}return found}exports.detectUsedPlugins=detectUsedPlugins;function compileProjectScript(source,name){let ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});let topLevelNames=[];for(const stmt of ast.body){if(stmt.type==="VariableDeclaration"){for(const d of stmt.declarations){if(d.id&&d.id.type==="Identifier")topLevelNames.push(d.id.name)}}}return _walk.getWatcher(ast,{name:name||"script"},topLevelNames,"Global").code}exports.compileProjectScript=compileProjectScript;function placePluginsCss(html,cssTag){html=String(html);let at=html.search(/<link\b[^>]*href=["']\/css\//i);return at>=0?html.slice(0,at)+cssTag+"\n "+html.slice(at):html.split("</head>").join(" "+cssTag+"\n</head>")}exports.placePluginsCss=placePluginsCss;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;indexHtmlSource=String(indexHtmlSource).replace(/<!--[\s\S]*?-->/g,"");while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;if(/^\/js\/bea\.js(\?|$)/.test(src))continue;found.push(src)}return found}exports.detectLocalProjectScripts=detectLocalProjectScripts;const CORE_Libs={BEACSS:"https://s.beacdn.com/beacss/latest",COREJS:"https://lmjs.beacdn.com/latest"};const HST_FORMAT_VERSION=3;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;function checkProjectRuntime(projectPath){try{let lm=fs.readFileSync(path.join(projectPath,"src","js","lm.js"),"utf8");let m=/EXPECTED_HST_FORMAT_VERSION\s*=\s*(\d+)/.exec(lm);let accepts=/_HST_FORMATS_ACCEPTED\s*=\s*\[([\d,\s]+)\]/.exec(lm);let ok=accepts?accepts[1].split(",").map(Number).indexOf(HST_FORMAT_VERSION)>-1:m&&Number(m[1])===HST_FORMAT_VERSION;if(m&&!ok){console.warn("\n\x1B[33mLumenJS: src/js/lm.js is older than this CLI (it expects HST v"+m[1]+", this CLI emits v"+HST_FORMAT_VERSION+"). Run `lm update-core` to update the project's runtime.\x1B[0m\n");return false}}catch(e){}return true}exports.checkProjectRuntime=checkProjectRuntime;exports.getAllFiles=getAllFiles;exports.ucwords=ucwords;exports.fetch=fetch;exports.getConfig=getConfig;function getConfig(){config={version:"1.0.0.1",server:{host:"127.0.0.1",port:"3000",ssl:{enabled:false,key:"/key.pem",cert:"/certificate.cer"}},apis:[{baseURL:"https://www.beaapis.com/1",headers:{"X-BEA-Application-ID":"YOUR_APPLICATION_ID","X-BEA-Authorization":"YOUR_REST_API_KEY"}}],ftp:{host:"ftp_host",username:"ftp_username",password:"ftp_password",remotePath:"/",concurrency:4,protocol:"ftp",port:21,ignore:[],syncOption:{delete:false,ignoreExisting:false,skipCreate:false,update:true},connectTimeout:3e4}};let configPath=process.cwd()+path.sep+`config.json`;if(fs.existsSync(configPath)){config=JSON.parse(fs.readFileSync(configPath,{encoding:"utf8"}))}return config}var config=getConfig();function ucwords(str){return(str+"").replace(/^([a-z])|\s+([a-z])/g,function($1){return $1.toUpperCase()})}function lw(s){return s.toString().toLowerCase()}exports.lw=lw;function cd(d){if(!fs.existsSync(d))fs.mkdirSync(d)}exports.cd=cd;function rd(d){if(fs.existsSync(d))fs.rmSync(d,{recursive:true,force:true})}exports.rd=rd;function create(conf){let t=conf.type=="v"||conf.type=="s"||conf.type=="t"?conf.type:"p";let n=conf.type=="v"||conf.type=="s"||conf.type=="t"?lw(conf.name[0]):conf.name.join(" ");if(t=="p"){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var getLibs=false;var _beacssMissing=false;var _lmMissing=false;require("dns").resolve("www.google.com",function(err){if(!err){var _mobiuscssPath=libsPath+path.sep+"mobius.css";_beacssMissing=!fs.existsSync(_mobiuscssPath)||fs.statSync(_mobiuscssPath).size===0;_lmMissing=!fs.existsSync(libsPath+path.sep+"lm.js");if(_lmMissing||_beacssMissing)getLibs=true}if(getLibs){API.get(CORE_Libs.COREJS,{}).then(corejs=>{API.get(CORE_Libs.BEACSS,{}).then(mobiuscss=>{var libsPath2=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath2);if(_lmMissing){fs.writeFileSync(libsPath2+path.sep+"lm.js",String(corejs))}if(_beacssMissing){fs.writeFileSync(libsPath2+path.sep+"mobius.css",String(mobiuscss))}var filePath3=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath3,n);cd(filePath3+path.sep+"src");cd(filePath3+path.sep+"src"+path.sep+"css");cd(filePath3+path.sep+"src"+path.sep+"images");cd(filePath3+path.sep+"src"+path.sep+"js");let stylesFile=filePath3+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath3+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))})}).catch(err2=>{})}else{var filePath2=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath2,n);cd(filePath2+path.sep+"src");cd(filePath2+path.sep+"src"+path.sep+"css");cd(filePath2+path.sep+"src"+path.sep+"images");cd(filePath2+path.sep+"src"+path.sep+"js");let stylesFile=filePath2+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath2+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));let corejs=Buffer.from(fs.readFileSync(libsPath+path.sep+"lm.js").toString());let mobiuscss=Buffer.from(fs.readFileSync(libsPath+path.sep+"mobius.css").toString());fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))}})}else{let file=t=="s"?"sub_view.view":t=="t"?"layout.layout":"view.view";let ident=t=="s"?"SubView":t=="t"?"Template":"View";let dir=t=="t"?"layouts":"views";let ext=t=="t"?"layout":"view";let html5=Buffer.from(fs.readFileSync(`${__dirname}`+path.sep+`files`+path.sep+file).toString().split("["+ident+"Name]").join(ucwords(n)));var filePath=`${process.cwd()}`+path.sep+`src`+path.sep+dir+path.sep+`${n}.${ext}`;if(fs.existsSync(filePath)){console.log(ident+" already exists:",filePath)}else{fs.writeFileSync(filePath,html5)}}}function getAllFiles(dirPath,arrayOfFiles={},mini=false,hst2=true){files=fs.readdirSync(dirPath);files.forEach(function(file){if(fs.statSync(dirPath+path.sep+file).isDirectory()){arrayOfFiles=getAllFiles(dirPath+path.sep+file,arrayOfFiles,mini,hst2)}else{let filePath=path.join(dirPath,path.sep,file);let fileKey=Buffer.from(filePath.split(`${process.cwd()}`+path.sep).join("").split("\\").join("/")).toString("base64");if(mini){var result=_min(fs.readFileSync(filePath,{encoding:"utf8"}),{removeAttributeQuotes:false,caseSensitive:true,collapseWhitespace:true,collapseInlineTagWhitespace:true,conservativeCollapse:true,removeComments:true,minifyJS:false,minifyCSS:false,processConditionalComments:true,collapseBooleanAttributes:false,decodeEntities:false,html5:true,includeAutoGeneratedTags:true,keepClosingSlash:true,maxLineLength:null,minifyURLs:false,preserveLineBreaks:false,preventAttributesEscaping:false,processScripts:["text/html"],quoteCharacter:"",removeEmptyAttributes:true,removeEmptyElements:false,removeOptionalTags:true,removeRedundantAttributes:true,removeScriptTypeAttributes:false,removeStyleLinkTypeAttributes:true,removeTagWhitespace:false,sortAttributes:false,sortClassName:false,trimCustomFragments:true,useShortDoctype:true,continueOnParseError:true})}else if(hst2){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}const RESERVED_BARE_ATTRS=new Set(["body","view","scoped","tpl","sl","color","time","date","datetime","up","stop","confirm","econfirm","acl","rcl","hidden","disabled","readonly","required","checked","selected","autofocus","multiple","async","defer"]);function _collectWidgetRegions(nodes,found){if(!Array.isArray(nodes))return;for(const node of nodes){if(node&&node.type==="tag"&&node.attrs){for(const attrName in node.attrs){if(Object.prototype.hasOwnProperty.call(node.attrs,attrName)&&node.attrs[attrName]===""&&!RESERVED_BARE_ATTRS.has(attrName)&&!found.includes(attrName)){found.push(attrName)}}}if(node&&Array.isArray(node.children)){_collectWidgetRegions(node.children,found)}}}function annotateLayoutRegions(layoutsObj){for(const key in layoutsObj){if(!Object.prototype.hasOwnProperty.call(layoutsObj,key))continue;let entry=layoutsObj[key];if(!entry||!entry.hst)continue;let found=[];_collectWidgetRegions(entry.hst,found);entry.regions=found}return layoutsObj}exports.annotateLayoutRegions=annotateLayoutRegions;function v1CompatIndexHtml(html){return String(html).replace(/(<script\b[^>]*\bsrc=["'])\/?js\/bea\.js(?:\?[^"']*)?(["'])/gi,"$1/js/lm.js$2").replace(/<script\b[^>]*\bsrc=["']\/?index\.js(?:\?[^"']*)?["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/(?:s\.|www\.)?beacdn\.com\/beajs\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/lmjs\.beacdn\.com\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"")}exports.v1CompatIndexHtml=v1CompatIndexHtml;function readTemplates(root){let out={};for(const folder of["tpls","comps"]){let dir=root+path.sep+"src"+path.sep+folder+path.sep;if(fs.existsSync(dir))Object.assign(out,getAllFiles(dir,{},false,true))}return out}exports.readTemplates=readTemplates;function linkTemplateReactiveVars(files2,templates){function templateFor(attrs){let name=String(attrs.tpl).replace(/^\/+/,"");for(const f of["tpls","comps"]){let key=Buffer.from("src/"+f+"/"+name+".tpl").toString("base64");if(templates[key])return templates[key]}return null}function scan(nodes,add){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;let a=node.attrs;if(a&&node.type==="sections"&&a.hasOwnProperty("tpl")){let t=templateFor(a);if(t)(t.reactiveVars||[]).forEach(add)}if(a&&a.hasOwnProperty("view")){let sv=viewFor(a.view);if(sv)(sv.reactiveVars||[]).forEach(add)}if(node.children)scan(node.children,add);if(Array.isArray(node.content))scan(node.content,add)}}let viewByPath={};for(const key in files2){let p=Buffer.from(key,"base64").toString().replace(/\\/g,"/");let m=p.match(/(?:^|\/)views\/(.+)\.view$/);if(m)viewByPath[m[1]]=files2[key]}function viewFor(v){let p=String(v).trim().replace(/^\/+/,"").replace(/\.view$/,"");if(!p||/\{\{/.test(p))return null;return viewByPath[p]||null}for(let pass=0;pass<10;pass++){let grew=false;for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1){entry.reactiveVars.push(n);grew=true}})}if(!grew)break}for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1)entry.reactiveVars.push(n)})}return files2}exports.linkTemplateReactiveVars=linkTemplateReactiveVars;function hst_markSvg(nodes,inSvg){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;let name=String(n.name||"").toLowerCase();let here=inSvg||name==="svg";if(here)n.svg=true;let kidsInSvg=here&&name!=="foreignobject";hst_markSvg(n.children,kidsInSvg);if(Array.isArray(n.content))hst_markSvg(n.content,kidsInSvg)}}function hst_orderIfFor(res){if(!res||!res.attrs||!res.forX||!Object.prototype.hasOwnProperty.call(res.attrs,":if"))return;let keys=Object.keys(res.attrs);let cond=String(res.attrs[":if"]);if(keys.indexOf(":if")<keys.indexOf(":for")){res.forX.js="("+cond+") ? ("+res.forX.js+") : []"}else{let prev=res.attrs[":for-if"];res.attrs[":for-if"]=prev?"("+prev+") && ("+cond+")":cond}res.type="sections";delete res.cond;delete res.attrs[":if"];if(res.ax)delete res.ax[":if"]}exports.hst_orderIfFor=hst_orderIfFor;class hst{htmlVoidElements=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","isindex","keygen","link","menuitem","meta","nextid","param","source","track","wbr"];moustachePattern=/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g;attrRE=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?("[\s\S]*?"|'[\s\S]*?')/g;tagRE=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;whitespaceRE=/^\s*$/;empty=Object.create(null);reactiveVariables=[];constructor(html){let hst2=this.parse(html);hst_markSvg(hst2,false);this.reactiveVariables=this.reactiveVariables.filter((value,index,self)=>{return self.indexOf(value)===index});return{hst:hst2,"reactiveVars":this.reactiveVariables}}keepOneSpace(_t){_t=_t.replace(/\s\s/gm," ");if(/\s\s/gm.test(_t))return this.keepOneSpace(_t);return _t}_clean(_t){_t=_t.replace(/(\r?\n|\r)/gm,"");_t=_t.replace(/(\t)/gm,"");_t=this.keepOneSpace(_t);return _t.replace(/^(?:\s*\t*\r*\n*\{*)+|(?:\s*\t*\r*\n*\})+$/g,"").trim()}processAttr(n,v,res){}processForXAttr(val){let forX={"js":"","as":{"k":"","v":""},"dx":""};var val=val.trim();if(val.indexOf(";")>-1){let zxx=val.split(";");forX["dx"]=zxx[1].trim();val=zxx[0].trim()}if(val.indexOf(" as ")>-1){let arr2=val.split(" as ");let kv=[];let arr3=arr2[1].split(" ").join("").split(",");if(arr3.length>1){kv=[arr3[0],arr3[1]]}else{kv=[arr3[0]]}if(kv.length){forX["as"]["k"]=kv[0].trim();if(kv.length>1){forX["as"]["v"]=kv[1].trim()}}val=arr2[0].trim()}forX["js"]=val.trim();return forX}parseTag(tag){var res={type:"tag",name:"",isV:false,attrs:{},ax:{},evs:{},ex:{},children:[]};var tagMatch=tag.match(/<\/?([^\s]+?)[/\s>]/);if(tagMatch){res.name=tagMatch[1];res.isV=this.htmlVoidElements.includes(tagMatch[1])||tag.charAt(tag.length-2)==="/"}var reg=new RegExp(this.attrRE);var result=null;for(;;){result=reg.exec(tag);if(result===null){break}if(!result[0].trim()){continue}if(result[1]){var attr=result[1].trim();var arr=[attr,""];if(arr[0]==":else"){res.type="section";res.cond=""}if(attr.indexOf("=")>-1){arr=attr.split("=")}if(arr[0].substring(0,1)=="@"){}else{if(res.name.toLowerCase()=="icon"&&arr[0].indexOf(":")>-1&&arr[0].substr(0,1)!=":"){res.icon=arr[0]}else res.attrs[arr[0]]=arr[1]}reg.lastIndex--}else if(result[2]){let sl=result[3].trim().substring(1,result[3].length-1);sl=he.decode(sl);if(result[2]==":if"||result[2]==":else-if"||result[2]==":else"){res.type="section";res.cond=sl;if(sl){try{let condAST=acorn.parse(sl,{ecmaVersion:"latest"});let condVars=this.collectVariableUsageFromAST(condAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<condVars.length;X++){this.reactiveVariables.push(condVars[X])}}catch(e){}}}else if(result[2]==":for"){res.type="sections";res.content=sl;res.forX=this.processForXAttr(sl);if(res.forX.js){try{let forAST=acorn.parse(res.forX.js,{ecmaVersion:"latest"});let forVars=this.collectVariableUsageFromAST(forAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<forVars.length;X++){this.reactiveVariables.push(forVars[X])}}catch(e){}}}if(result[2].substring(0,1)=="@"){let max=this._getMs2(sl);res.evs[result[2]]=max[1];max[0].length?res.ex[result[2]]=max[0]:null}else{let max=this._getMs2(sl.replace(/`(\{\s*\{[\s\S]*?\}\s*\})`/g,"$1"));if(res.name.toLowerCase()=="icon"&&result[2].indexOf(":")>-1&&result[2].substr(0,1)!=":"){res.icon=result[2]}else res.attrs[result[2]]=max[1];max[0].length?res.ax[result[2]]=max[0]:null}}}hst_orderIfFor(res);return res}removeComments(str){str=str.replace(/<!--[\s\S]*?(?:-->)/g,"");return str}cleanExpression(expression){let cleaned="";let inSingle=false,inDouble=false,inTemplate=false;let inRegex=false,escapeNext=false;let inBlockComment=false,inLineComment=false;for(let i=0;i<expression.length;i++){let char=expression[i];let next=expression[i+1];if(escapeNext){cleaned+=char;escapeNext=false;continue}if(inBlockComment){if(char==="*"&&next==="/"){inBlockComment=false;i++}continue}if(inLineComment){if(char==="\n"){inLineComment=false}continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(char==="/"&&next==="*"){inBlockComment=true;i++;continue}if(char==="/"&&next==="/"){inLineComment=true;i++;continue}}if(!inDouble&&!inTemplate&&!inRegex&&char==="'"&&!inSingle){inSingle=true;cleaned+=char;continue}else if(inSingle&&char==="'"){inSingle=false;cleaned+=char;continue}if(!inSingle&&!inTemplate&&!inRegex&&char==='"'&&!inDouble){inDouble=true;cleaned+=char;continue}else if(inDouble&&char==='"'){inDouble=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inRegex&&char==="`"&&!inTemplate){inTemplate=true;cleaned+=char;continue}else if(inTemplate&&char==="`"){inTemplate=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&char==="/"&&!inRegex){let prevNonSpace=cleaned.match(/\S$/);if(!prevNonSpace||/[=({[,;:?!+\-*/%&|^~<>]/.test(prevNonSpace[0])){inRegex=true}cleaned+=char;continue}else if(inRegex&&char==="/"&&expression[i-1]!=="\\"){inRegex=false;cleaned+=char;continue}if(char==="\\"&&(inSingle||inDouble||inTemplate||inRegex)){escapeNext=true;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(/\s/.test(char)){if(cleaned[cleaned.length-1]!==" "){cleaned+=" "}continue}}cleaned+=char}return cleaned.trim()}_getMs(_t,wbt){let result="";let lastIndex=0;let _m;var _ms=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{let AST=acorn.parse(_m[0],{ecmaVersion:"latest"});hasError=false;let mux=this._clean(_m[0]);if(wbt){if(_t.substring(_m.index-1,1)=="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}else{if(_t.substring(_m.index-1,1)!="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}}catch(e){hasError=true;result+=_t.substring(lastIndex,_m.index);result+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)result+=_t.substring(lastIndex);return[_ms,result]}_getMs2(_t,wbt){let content="";let lastIndex=0;let _m;var _muxes=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{hasError=false;let mux=this._clean(_m[0]);let JST=acorn.parse(mux,{ecmaVersion:"latest"});let rvs=[];let vss=this.collectVariableUsageFromAST(JST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<vss.length;X++){rvs.push(vss[X]);this.reactiveVariables.push(vss[X])}rvs=rvs.filter((value,index,self)=>{return self.indexOf(value)===index});_muxes.push({"mus":mux,"rvs":rvs});content+=_t.substring(lastIndex,_m.index);content+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}catch(e){hasError=true;content+=_t.substring(lastIndex,_m.index);content+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)content+=_t.substring(lastIndex);_muxes=this.setMuxesIndexes(content,_muxes);return[_muxes,content]}setMuxesIndexes(content,_muxes){let muxes=[];let lastIndex=0;let i=0;let _m;while((_m=this.moustachePattern.exec(content))!=null){muxes.push({..._muxes[i],"start":_m.index,"end":_m.index+_m[0].length});lastIndex=_m.index+_m[0].length;i++}return muxes}parse(html,options){if(options===void 0){options={}}options||(options={});options.components||(options.components=this.empty);html=this.removeComments(html);var result=[];var arr=[];var current;var level=-1;var inComponent=false;var inRawText=false;var par=this;if(html.indexOf("<")!==0){var end=html.indexOf("<");let zl=end===-1?html:html.substring(0,end);let mssx=this._getMs2(zl);let textObj={type:"text",content:mssx[1],mss:mssx[0]};result.push(textObj)}html.replace(this.tagRE,async function(tag,index){if(inComponent||inRawText){if(tag!=="</"+current.name+">"){return""}else{inComponent=false;inRawText=false}}var isOpen=tag.charAt(1)!=="/";var start=index+tag.length;var nextChar=html.charAt(start);var parent;if(isOpen){level++;current=par.parseTag(tag);if(current.type==="tag"&&(current.name==="script"||current.name==="style")){inRawText=true}if(current.type==="tag"&¤t.name&&options.components&&options.components[current.name]){current.type="component";inComponent=true}if(!current.isV&&!inComponent&&nextChar&&nextChar!=="<"&&Array.isArray(current.children)){let end2;if(current.name==="script"||current.name==="style"){let closeRe=new RegExp("</\\s*"+current.name+"\\s*>","i");let m=closeRe.exec(html.slice(start));end2=m?start+m.index:html.length}else{end2=html.indexOf("<",start);while(html.charAt(end2+1)==" "){end2=html.indexOf("<",start+(end2+1-start))}}let hl=html.slice(start,end2);let mssx=null;if(current.name!="script")mssx=par._getMs2(hl);let textObj={type:"text",content:current.name=="script"?"":mssx[1],...current.name=="script"?scriptPayload(hl):{mss:mssx[0]},tag:current.name};current.children.push(textObj)}if(level===0){result.push(current)}parent=arr[level-1];if(parent&&parent.children){parent.children.push(current)}arr[level]=current}if(!isOpen||current.isV){if(level>-1&&(current.isV||current.name===tag.slice(2,-1))){level--;current=level===-1?result:arr[level]}if(!inComponent&&nextChar!=="<"&&nextChar){parent=level===-1?result:arr[level].children;var _end=html.indexOf("<",start);var content=html.slice(start,_end===-1?void 0:_end);let wsOnly=par.whitespaceRE.test(content);if(wsOnly?_end>-1&&parent&&Array.isArray(parent):true){if(parent&&Array.isArray(parent)){if(wsOnly){parent.push({type:"text",content,mss:[]})}else{let mssx=par._getMs2(content);let textObj={type:"text",content:mssx[1],mss:mssx[0]};parent.push(textObj)}}}}}});return result}collectVariableUsageFromAST(ast,options={}){const{excludeBuiltins=true,extraBuiltins=[]}=options;const DEFAULT_BUILTINS=new Set(["undefined","NaN","Infinity","null","true","false","Object","Function","Boolean","Symbol","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","Number","BigInt","Math","Date","String","RegExp","Array","Map","Set","WeakMap","WeakSet","Promise","Reflect","Proxy","Intl","JSON","Atomics","SharedArrayBuffer","ArrayBuffer","DataView","WeakRef","FinalizationRegistry","console","window","document","navigator","location","localStorage","sessionStorage","fetch","XMLHttpRequest","setTimeout","clearTimeout","setInterval","clearInterval","requestAnimationFrame","cancelAnimationFrame","process","global","globalThis","require","module","exports","Buffer","parseInt","parseFloat","isFinite","isNaN","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","escape","unescape"]);const builtinSet=new Set([...DEFAULT_BUILTINS,...extraBuiltins]);function createScope(parent=null,isFunction=false){return{parent,isFunction:!!isFunction,names:new Set}}const scopeForNode=new WeakMap;const bindingIdNodes=new WeakSet;const allDeclaredNames=new Set;function markPatternBindings(pattern,scope,kind="var"){if(!pattern)return;switch(pattern.type){case"Identifier":bindingIdNodes.add(pattern);declareInScope(pattern.name,kind,scope);allDeclaredNames.add(pattern.name);break;case"ArrayPattern":for(const el of pattern.elements)if(el)markPatternBindings(el,scope,kind);break;case"ObjectPattern":for(const p of pattern.properties){if(p.type==="Property")markPatternBindings(p.value,scope,kind);else if(p.type==="RestElement")markPatternBindings(p.argument,scope,kind)}break;case"RestElement":markPatternBindings(pattern.argument,scope,kind);break;case"AssignmentPattern":markPatternBindings(pattern.left,scope,kind);break;default:break}}function declareInScope(name,kind,currentScope){if(!name||!currentScope)return;if(kind==="var"||kind==="function"){let s=currentScope;while(s&&!s.isFunction&&s.parent)s=s.parent;s.names.add(name)}else{currentScope.names.add(name)}}function buildScopes(node,currentScope){if(!node||typeof node!=="object")return;switch(node.type){case"Program":{scopeForNode.set(node,currentScope);for(const stmt of node.body)buildScopes(stmt,currentScope);return}case"FunctionDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"function",currentScope);allDeclaredNames.add(node.id.name)}const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"FunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",fnScope);allDeclaredNames.add(node.id.name)}for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"ArrowFunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"BlockStatement":case"StaticBlock":case"SwitchStatement":{const blockScope=createScope(currentScope,false);scopeForNode.set(node,blockScope);if(node.type==="SwitchStatement"){for(const c of node.cases)buildScopes(c,blockScope)}else{for(const s of node.body)buildScopes(s,blockScope)}return}case"CatchClause":{const catchScope=createScope(currentScope,false);scopeForNode.set(node,catchScope);if(node.param)markPatternBindings(node.param,catchScope,"let");buildScopes(node.body,catchScope);return}case"ForStatement":case"ForInStatement":case"ForOfStatement":{const forScope=createScope(currentScope,false);scopeForNode.set(node,forScope);if(node.init)buildScopes(node.init,forScope);if(node.left)buildScopes(node.left,forScope);if(node.test)buildScopes(node.test,forScope);if(node.update)buildScopes(node.update,forScope);buildScopes(node.body,forScope);return}case"VariableDeclaration":{for(const decl of node.declarations||[]){markPatternBindings(decl.id,currentScope,node.kind||"var");if(decl.init)buildScopes(decl.init,currentScope)}return}case"ClassDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",currentScope);allDeclaredNames.add(node.id.name)}if(node.body)buildScopes(node.body,currentScope);return}case"ImportDeclaration":{for(const spec of node.specifiers||[]){if(spec.local){bindingIdNodes.add(spec.local);declareInScope(spec.local.name,"const",currentScope);allDeclaredNames.add(spec.local.name)}}return}case"ExportNamedDeclaration":case"ExportDefaultDeclaration":case"ExportAllDeclaration":{if(node.declaration)buildScopes(node.declaration,currentScope);return}default:break}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(const c of child)if(c&&typeof c==="object")buildScopes(c,currentScope)}else if(child&&typeof child==="object"){buildScopes(child,currentScope)}}}const rootScope=createScope(null,true);scopeForNode.set(ast,rootScope);buildScopes(ast,rootScope);const usageSet=new Set;function isVariableUsageIdentifier(node,parent,propName){if(!parent)return true;if(bindingIdNodes.has(node))return false;if(parent.type==="LabeledStatement"&&propName==="label"||(parent.type==="BreakStatement"||parent.type==="ContinueStatement")&&propName==="label"){return false}if(parent.type==="MemberExpression"&&propName==="property"&&parent.computed===false){return false}if(parent.type==="Property"&&propName==="key"&&parent.computed===false&&!parent.shorthand){return false}if((parent.type==="MethodDefinition"||parent.type==="PropertyDefinition")&&propName==="key"&&parent.computed===false){return false}if(parent.type&&(parent.type.startsWith("Import")||parent.type.startsWith("Export")||parent.type==="MetaProperty")){return false}if((parent.type==="FunctionDeclaration"||parent.type==="FunctionExpression"||parent.type==="ClassDeclaration")&&propName==="id"){return false}if(parent.type==="VariableDeclarator"&&propName==="id"||parent.type==="CatchClause"&&propName==="param"){return false}if((parent.type==="CallExpression"||parent.type==="OptionalCallExpression")&&propName==="callee"){return false}if(parent.type==="NewExpression"&&propName==="callee"){return false}return true}const scopeStack=[rootScope];function collect(node,parent,propName,index){if(!node||typeof node!=="object")return;const nodeScope=scopeForNode.get(node);if(nodeScope)scopeStack.push(nodeScope);if(node.type==="Identifier"){if(isVariableUsageIdentifier(node,parent,propName)){const name=node.name;if(!(excludeBuiltins&&builtinSet.has(name))){usageSet.add(name)}}}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(let i=0;i<child.length;i++){const c=child[i];if(c&&typeof c==="object")collect(c,node,key,i)}}else if(child&&typeof child==="object"){collect(child,node,key,null)}}if(nodeScope)scopeStack.pop()}collect(ast,null,null,null);const self=this;(function findTpl(node){if(!node||typeof node!=="object")return;if(node.type==="TemplateLiteral"&&node.expressions.length===0&&node.quasis.length===1){const inner=node.quasis[0].value.cooked;if(inner&&inner.trim()){try{const innerAst=_acorn.parse(inner,{ecmaVersion:"latest",sourceType:"script"});for(const n of self.collectVariableUsageFromAST(innerAst,options))usageSet.add(n)}catch(e){}}return}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child))child.forEach(findTpl);else if(child&&typeof child==="object")findTpl(child)}})(ast);return Array.from(usageSet).sort()}}function _hst(html){return new hst(html)}function copyDir(src,dest,projectName){try{const entries=fs.readdirSync(src,{encoding:"utf8",withFileTypes:true});cd(dest);for(let entry of entries){const srcPath=path.join(src.toString(),entry.name.toString());const destPath=path.join(dest.toString(),entry.name.toString());if(entry.isDirectory()){if(projectName=="_beajsBuild"){if(entry.name!="layouts"&&entry.name!="views"&&entry.name!="css"&&entry.name!="js")copyDir(srcPath,destPath,projectName)}else copyDir(srcPath,destPath,projectName)}else{if(projectName=="_beajsBuild"){if(projectName=="_beajsBuild"&&entry.name!="index.js"&&entry.name!="index.html")fs.copyFileSync(srcPath,destPath)}else{if(!fs.existsSync(destPath)){if(projectName){if(entry.name=="index.html"){let html5=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(ucwords(projectName)));fs.writeFileSync(destPath,html5)}else if(entry.name=="package.json"){let slug=lw(projectName).replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"lumenjs-project";let pkgJson=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(slug));fs.writeFileSync(destPath,pkgJson)}else fs.copyFileSync(srcPath,destPath)}else fs.copyFileSync(srcPath,destPath)}else{console.log("File already exists:",destPath)}}}}}catch(e){console.log(e)}}exports.copyDir=copyDir;function validURL(string){let url;try{url=new URL(string)}catch(_){return false}return url.protocol==="http:"||url.protocol==="https:"}exports.validURL=validURL;let getPairs=(obj,keys=[])=>Object.entries(obj).reduce((pairs,[key,value])=>{if(typeof value==="object")pairs.push(...getPairs(value,[...keys,key]));else pairs.push([[...keys,key],value]);return pairs},[]);function pairIt(obj){return getPairs(obj).map(([[key0,...keysRest],value])=>`${key0}${keysRest.map(a=>`[${a}]`).join("")}=${value}`).join("&")}var API={get:async function(u,d,h,a){return await this.req(u,d,h,"GET",a)},put:async function(u,d,h,a){return await this.req(u,d,h,"PUT",a)},post:async function(u,d,h,a){return await this.req(u,d,h,"POST",a)},delete:async function(u,d,h,a){return await this.req(u,d,h,"DELETE",a)},patch:async function(u,d,h,a){return await this.req(u,d,h,"PATCH",a)},req:async function(u,d,h,m,a,f){var urled=validURL(u)?u:config.apis[a??0].baseURL+u;if(m.toString().toLowerCase()=="get"){if(urled.indexOf("?")>-1)urled=urled+"&"+pairIt(d??{});else urled=urled+"?"+pairIt(d??{})}let resa=await fetch(urled,{method:m.toString().toLowerCase(),body:m.toString().toLowerCase()=="get"?null:JSON.stringify(d??{}),headers:h??config.apis[a??0].headers});if(f)return resa;let res=await resa.text();try{return JSON.parse(res)}catch(e){return res}}};exports.API=API;function updateCore(){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var projectJsPath=process.cwd()+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";var projectCssPath=process.cwd()+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css";if(!fs.existsSync(process.cwd()+path.sep+"config.json")||!fs.existsSync(process.cwd()+path.sep+"src")){console.log("This doesn't look like a LumenJS project (no config.json/src here) \u2014 run this from your project's root.");return}if(!fs.existsSync(libsPath+path.sep+"lm.js")){console.log("This CLI install has no bundled runtime to copy from \u2014 reinstall @lmjs/cli.");return}var oldSize=fs.existsSync(projectJsPath)?fs.statSync(projectJsPath).size:null;var newJs=fs.readFileSync(libsPath+path.sep+"lm.js");var newSize=newJs.length;if(oldSize===newSize){console.log("Already up to date \u2014 this project's src/js/lm.js already matches the installed @lmjs/cli's runtime ("+newSize+" bytes). Nothing to do.");return}fs.writeFileSync(projectJsPath,newJs);if(fs.existsSync(libsPath+path.sep+"mobius.css")){fs.writeFileSync(projectCssPath,fs.readFileSync(libsPath+path.sep+"mobius.css"))}console.log("Updated src/js/lm.js"+(oldSize!==null?" (was "+oldSize+" bytes, now "+newSize+" bytes)":" (was missing, now "+newSize+" bytes)")+" \u2014 matches the currently installed @lmjs/cli.")}exports.updateCore=updateCore;exports.processCommand=processCommands;exports.startServer=startServer;exports.create=create;function processCommands(cmd){var command=cmd?cmd:process.argv[2];if(command=="run"||command=="serve"){startServer()}else if(command=="create"||command=="update"){let c=process.argv.slice(3,process.argv.length);let t=lw(c[0]);create({type:t[0]=="-"?t.split("-").join(""):t,name:t[0]=="-"?c.slice(1,c.length):c})}else if(command=="update-core"){updateCore()}else if(command=="purge"){console.log("(lm purge now does the same thing as `lm update-core` \u2014 prefer that name going forward.)");updateCore()}else if(command=="build"){let cmds=process.argv;_bp(cmds)}else if(command=="login"){_vault.login()}else if(command=="api"){let sub=process.argv[3];let name=process.argv[4];if(sub=="set")_vault.apiSet(name);else if(sub=="update")_vault.apiUpdate(name);else if(sub=="get")_vault.apiGet(name);else if(sub=="list")_vault.apiList();else if(sub=="remove")_vault.apiRemove(name);else console.log("Usage: lm api <set|get|update|list|remove> [name]")}else if(command=="-v"||command=="-version"){let _pkgJsonPath=fs.existsSync(path.join(__dirname,"..","..","package.json"))?path.join(__dirname,"..","..","package.json"):path.join(__dirname,"..","package.json");console.log("LumenJS version "+require(_pkgJsonPath).version)}else{console.log("LumenJS CLI's command not found!")}}async function _bp(cmds){import("ora").then(async({default:ora,oraPromise})=>{const spinner=ora({color:"green"});spinner.succeed("Started Building Project For Production").start("Gathering Required Resources..");var projectPath=`${process.cwd()}`;checkProjectRuntime(projectPath);var dest=projectPath+path.sep+"dist";let _views=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);let _layoutsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep;let _layouts=fs.existsSync(_layoutsDir)?annotateLayoutRegions(getAllFiles(_layoutsDir,{},false,true)):{};let _tpls=readTemplates(`${process.cwd()}`);linkTemplateReactiveVars(_views,_tpls);linkTemplateReactiveVars(_layouts,_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");let _cssDir=projectPath+path.sep+`src`+path.sep+"css"+path.sep;let _mainCssName=["mobius.css","bea.css"].find(f=>fs.existsSync(_cssDir+f))||null;var beaCSSCode=_mainCssName?fs.readFileSync(_cssDir+_mainCssName,"utf8"):"";var indexJs=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.js","utf8");let _hasOwnDeps=_npmBundle.hasOwnDependencies(projectPath);let _localScriptSrcs=detectLocalProjectScripts(String(indexCode));let _compiledScripts="";for(const src of _localScriptSrcs){let scriptPath=projectPath+path.sep+"src"+path.sep+src.split("/").join(path.sep).replace(/^\\|^\//,"");try{let raw=_hasOwnDeps?_npmBundle.buildEntryWithImports(scriptPath,projectPath):fs.readFileSync(scriptPath,"utf8");_compiledScripts+="\n"+compileProjectScript(raw,src);indexCode=indexCode.split(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']`+src.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+`["'][^>]*>\\s*<\\/script>`,"i")).join("")}catch(e){}}let _uncompiledScripts=precompileViewScripts([{kind:"views",files:_views},{kind:"layouts",files:_layouts},{kind:"tpls",files:_tpls}]);let vt=`
|
|
1
|
+
const fetch=require("node-fetch");const path=require("path");const fs=require("fs");const nodemon=require("nodemon");var _acorn=require("acorn");var acorn=require("acorn-loose");function parseScriptJs(source){let ast;try{ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"})}catch(e){ast=acorn.parse(source,{ecmaVersion:"latest"})}return stripAstPositions(ast)}function precompileViewScripts(groups){let failed=0;function visit(nodes,vars,inSection,file){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;const sectioned=inSection||n.type==="section"||n.type==="sections";const nm=String(n.name||"").toLowerCase();if((nm==="script"||nm==="js")&&Array.isArray(n.children)&&n.children[0]&&n.children[0].type==="text"){const t=n.children[0];if(t.content||t.jst){try{const ast=t.jst||_acorn.parse(t.content,{ecmaVersion:"latest",sourceType:"script"});const code=_walk.getWatcher(ast,{name:file},sectioned?void 0:(vars||[]).slice(),["__LMROOT__"]).code;new Function(code);t.pre=code;delete t.content;delete t.jst}catch(e){failed++;console.warn("\x1B[33mLumenJS: could not precompile a <script> in "+file+": "+(e&&e.message)+" (it will be compiled in the browser)\x1B[0m")}}}visit(n.children,vars,sectioned,file)}}for(const group of groups){const isTpl=group.kind==="tpls";for(const key in group.files){const entry=group.files[key];if(!entry||!Array.isArray(entry.hst))continue;const file=Buffer.from(key,"base64").toString().split(/[\\/]/).slice(-2).join("/");visit(entry.hst,entry.reactiveVars,isTpl,file)}}return failed}exports.precompileViewScripts=precompileViewScripts;function stripDevOnlyRuntime(src){const a=src.indexOf("var __lmDevOnlyStart__ = 1;");const b=src.indexOf("var __lmDevOnlyEnd__ = 1;");if(a<0||b<a)return src;return src.slice(0,a)+src.slice(b+"var __lmDevOnlyEnd__ = 1;".length)}exports.stripDevOnlyRuntime=stripDevOnlyRuntime;const _HST_EMPTY_OBJ={attrs:1,ax:1,evs:1,ex:1};function compactHstReplacer(key,value){if(_HST_EMPTY_OBJ[key]===1&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return void 0;if(key==="isV"&&value===false)return void 0;if((key==="mss"||key==="children")&&Array.isArray(value)&&value.length===0)return void 0;return value}exports.compactHstReplacer=compactHstReplacer;function scriptPayload(source){try{_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});return{content:source}}catch(e){return{jst:parseScriptJs(source)}}}exports.scriptPayload=scriptPayload;function stripAstPositions(node){if(Array.isArray(node)){for(let i=0;i<node.length;i++)stripAstPositions(node[i]);return node}if(!node||typeof node!=="object")return node;delete node.start;delete node.end;delete node.loc;delete node.range;for(const k in node){const v=node[k];if(v&&typeof v==="object")stripAstPositions(v)}return node}exports.stripAstPositions=stripAstPositions;var _min=require("html-minifier").minify;var he=require("he");const _FD=require("ftp-deploy");const _fD=new _FD;global.astring=global.astring||require("astring");const _corePackageDir=path.dirname(require.resolve("@lmjs/core/package.json"));const _walk=require(path.join(_corePackageDir,"src","walk.js"));const _npmBundle=require(path.join(__dirname,"npm-bundle.js"));exports.hasOwnDependencies=_npmBundle.hasOwnDependencies;exports.buildEntryWithImports=_npmBundle.buildEntryWithImports;const _pluginsBundle=require(path.join(__dirname,"plugins-esbuild-plugin.js"));const _vault=require(path.join(__dirname,"vault.js"));exports.login=_vault.login;exports.apiSet=_vault.apiSet;exports.apiUpdate=_vault.apiUpdate;exports.apiGet=_vault.apiGet;exports.apiList=_vault.apiList;exports.apiRemove=_vault.apiRemove;function selectedProjectPlugins(projectRoot){try{let deps={};const pkgPath=path.join(projectRoot,"package.json");if(fs.existsSync(pkgPath)){const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));Object.assign(deps,pkg.dependencies||{})}for(const key of detectUsedPlugins(projectRoot))if(!deps.hasOwnProperty(key))deps[key]="*";if(!Object.keys(deps).length)return[];return _pluginsBundle.selectedRegistryEntries(deps)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;const PLUGIN_SIGNATURES={"select2":[/\.select2\s*\(/,/<[a-z][^>]*\s(?:sl|slct)(?=[\s>=\/])/i],"flickity":[/\.flickity\s*\(/,/\bFlickity\b/,/<[a-z][^>]*\scrslf(?=[\s>=\/])/i],"bootstrap-colorpicker":[/\.colorpicker\s*\(/,/<input[^>]*\scolor(?=[\s>=\/])/i],"bootstrap-datetimepicker":[/\.datetimepicker\s*\(/,/<input[^>]*\s(?:date|time|datetime)(?=[\s>=\/])/i],"jquery-ui-dist":[/\.(?:sortable|draggable|droppable|resizable|datepicker|autocomplete|slider|accordion)\s*\(/,/<[a-z][^>]*\s(?:sort|drag|drop)(?=[\s>=\/])/i],"jquery.easing":[/\beas(?:e|ing)(?:In|Out)[A-Z]\w*/],"nestedSortable":[/\.nestedSortable\s*\(/],"jquery.numeric":[/\.numeric\s*\(/,/<input[^>]*\s(?:numeric|integer|decimal)(?=[\s>=\/])/i],"timeago":[/\.timeago\s*\(/,/\$\.timeago\b/],"slick-carousel":[/\.(?:crsl|slick)\s*\(/,/<[a-z][^>]*\scrsl(?=[\s>=\/])/i],"@iconify/iconify":[/class=["'][^"']*\biconify\b/,/\bIconify\./],"rellax":[/\bRellax\b/],"headroom.js":[/\bHeadroom\b/,/<[a-z][^>]*\spinnable(?=[\s>=\/])/i],"in-view":[/\binView\b/],"gsap":[/\bgsap\b/,/\bTween(?:Max|Lite)\b/,/\bTimeline(?:Max|Lite)\b/],"jquery.caret":[/\.caret\s*\(/],"jquery-tageditor":[/\.tagEditor\s*\(/,/<[a-z][^>]*\stags(?=[\s>=\/])/i],"jquery-lazy":[/\.lazy\s*\(/,/<img[^>]*\slazy(?=[\s>=\/])/i]};function detectUsedPlugins(projectRoot){const src=path.join(projectRoot,"src");if(!fs.existsSync(src))return[];let indexHtml="";try{indexHtml=fs.readFileSync(path.join(src,"index.html"),"utf8")}catch(e){}const texts=[];(function walk(dir){let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){return}for(const e of entries){const p=path.join(dir,e.name);if(e.isDirectory()){if(e.name==="node_modules"||e.name==="js"||e.name==="css"||e.name==="images")continue;walk(p)}else if(/\.(view|tpl|layout)$/.test(e.name)){try{texts.push(fs.readFileSync(p,"utf8"))}catch(x){}}}})(src);try{texts.push(fs.readFileSync(path.join(src,"index.js"),"utf8"))}catch(e){}for(const s of detectLocalProjectScripts(indexHtml)){try{texts.push(fs.readFileSync(path.join(src,s.replace(/^\//,"")),"utf8"))}catch(e){}}const all=texts.join("\n");const loadedByPage=key=>new RegExp(`<script[^>]+src=["'][^"']*`+key.replace(/^@[^/]+\//,"").replace(/\.js$/,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i").test(indexHtml);const found=[];for(const key in PLUGIN_SIGNATURES){if(loadedByPage(key))continue;if(PLUGIN_SIGNATURES[key].some(re=>re.test(all)))found.push(key)}return found}exports.detectUsedPlugins=detectUsedPlugins;function compileProjectScript(source,name){let ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});let topLevelNames=[];for(const stmt of ast.body){if(stmt.type==="VariableDeclaration"){for(const d of stmt.declarations){if(d.id&&d.id.type==="Identifier")topLevelNames.push(d.id.name)}}}return _walk.getWatcher(ast,{name:name||"script"},topLevelNames,"Global").code}exports.compileProjectScript=compileProjectScript;function placePluginsCss(html,cssTag){html=String(html);let at=html.search(/<link\b[^>]*href=["']\/css\//i);return at>=0?html.slice(0,at)+cssTag+"\n "+html.slice(at):html.split("</head>").join(" "+cssTag+"\n</head>")}exports.placePluginsCss=placePluginsCss;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;indexHtmlSource=String(indexHtmlSource).replace(/<!--[\s\S]*?-->/g,"");while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;if(/^\/js\/bea\.js(\?|$)/.test(src))continue;found.push(src)}return found}exports.detectLocalProjectScripts=detectLocalProjectScripts;const CORE_Libs={BEACSS:"https://s.beacdn.com/beacss/latest",COREJS:"https://lmjs.beacdn.com/latest"};const HST_FORMAT_VERSION=3;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;function checkProjectRuntime(projectPath){try{let lm=fs.readFileSync(path.join(projectPath,"src","js","lm.js"),"utf8");let m=/EXPECTED_HST_FORMAT_VERSION\s*=\s*(\d+)/.exec(lm);let accepts=/_HST_FORMATS_ACCEPTED\s*=\s*\[([\d,\s]+)\]/.exec(lm);let ok=accepts?accepts[1].split(",").map(Number).indexOf(HST_FORMAT_VERSION)>-1:m&&Number(m[1])===HST_FORMAT_VERSION;if(m&&!ok){console.warn("\n\x1B[33mLumenJS: src/js/lm.js is older than this CLI (it expects HST v"+m[1]+", this CLI emits v"+HST_FORMAT_VERSION+"). Run `lm update-core` to update the project's runtime.\x1B[0m\n");return false}}catch(e){}return true}exports.checkProjectRuntime=checkProjectRuntime;exports.getAllFiles=getAllFiles;exports.ucwords=ucwords;exports.fetch=fetch;exports.getConfig=getConfig;function getConfig(){config={version:"1.0.0.1",server:{host:"127.0.0.1",port:"3000",ssl:{enabled:false,key:"/key.pem",cert:"/certificate.cer"}},apis:[{baseURL:"https://www.beaapis.com/1",headers:{"X-BEA-Application-ID":"YOUR_APPLICATION_ID","X-BEA-Authorization":"YOUR_REST_API_KEY"}}],ftp:{host:"ftp_host",username:"ftp_username",password:"ftp_password",remotePath:"/",concurrency:4,protocol:"ftp",port:21,ignore:[],syncOption:{delete:false,ignoreExisting:false,skipCreate:false,update:true},connectTimeout:3e4}};let configPath=process.cwd()+path.sep+`config.json`;if(fs.existsSync(configPath)){config=JSON.parse(fs.readFileSync(configPath,{encoding:"utf8"}))}return config}var config=getConfig();function ucwords(str){return(str+"").replace(/^([a-z])|\s+([a-z])/g,function($1){return $1.toUpperCase()})}function lw(s){return s.toString().toLowerCase()}exports.lw=lw;function cd(d){if(!fs.existsSync(d))fs.mkdirSync(d)}exports.cd=cd;function rd(d){if(fs.existsSync(d))fs.rmSync(d,{recursive:true,force:true})}exports.rd=rd;function create(conf){let t=conf.type=="v"||conf.type=="s"||conf.type=="t"?conf.type:"p";let n=conf.type=="v"||conf.type=="s"||conf.type=="t"?lw(conf.name[0]):conf.name.join(" ");if(t=="p"){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var getLibs=false;var _beacssMissing=false;var _lmMissing=false;require("dns").resolve("www.google.com",function(err){if(!err){var _mobiuscssPath=libsPath+path.sep+"mobius.css";_beacssMissing=!fs.existsSync(_mobiuscssPath)||fs.statSync(_mobiuscssPath).size===0;_lmMissing=!fs.existsSync(libsPath+path.sep+"lm.js");if(_lmMissing||_beacssMissing)getLibs=true}if(getLibs){API.get(CORE_Libs.COREJS,{}).then(corejs=>{API.get(CORE_Libs.BEACSS,{}).then(mobiuscss=>{var libsPath2=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath2);if(_lmMissing){fs.writeFileSync(libsPath2+path.sep+"lm.js",String(corejs))}if(_beacssMissing){fs.writeFileSync(libsPath2+path.sep+"mobius.css",String(mobiuscss))}var filePath3=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath3,n);cd(filePath3+path.sep+"src");cd(filePath3+path.sep+"src"+path.sep+"css");cd(filePath3+path.sep+"src"+path.sep+"images");cd(filePath3+path.sep+"src"+path.sep+"js");let stylesFile=filePath3+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath3+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))})}).catch(err2=>{})}else{var filePath2=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath2,n);cd(filePath2+path.sep+"src");cd(filePath2+path.sep+"src"+path.sep+"css");cd(filePath2+path.sep+"src"+path.sep+"images");cd(filePath2+path.sep+"src"+path.sep+"js");let stylesFile=filePath2+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath2+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));let corejs=Buffer.from(fs.readFileSync(libsPath+path.sep+"lm.js").toString());let mobiuscss=Buffer.from(fs.readFileSync(libsPath+path.sep+"mobius.css").toString());fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))}})}else{let file=t=="s"?"sub_view.view":t=="t"?"layout.layout":"view.view";let ident=t=="s"?"SubView":t=="t"?"Template":"View";let dir=t=="t"?"layouts":"views";let ext=t=="t"?"layout":"view";let html5=Buffer.from(fs.readFileSync(`${__dirname}`+path.sep+`files`+path.sep+file).toString().split("["+ident+"Name]").join(ucwords(n)));var filePath=`${process.cwd()}`+path.sep+`src`+path.sep+dir+path.sep+`${n}.${ext}`;if(fs.existsSync(filePath)){console.log(ident+" already exists:",filePath)}else{fs.writeFileSync(filePath,html5)}}}function getAllFiles(dirPath,arrayOfFiles={},mini=false,hst2=true){files=fs.readdirSync(dirPath);files.forEach(function(file){if(fs.statSync(dirPath+path.sep+file).isDirectory()){arrayOfFiles=getAllFiles(dirPath+path.sep+file,arrayOfFiles,mini,hst2)}else{let filePath=path.join(dirPath,path.sep,file);let fileKey=Buffer.from(filePath.split(`${process.cwd()}`+path.sep).join("").split("\\").join("/")).toString("base64");if(mini){var result=_min(fs.readFileSync(filePath,{encoding:"utf8"}),{removeAttributeQuotes:false,caseSensitive:true,collapseWhitespace:true,collapseInlineTagWhitespace:true,conservativeCollapse:true,removeComments:true,minifyJS:false,minifyCSS:false,processConditionalComments:true,collapseBooleanAttributes:false,decodeEntities:false,html5:true,includeAutoGeneratedTags:true,keepClosingSlash:true,maxLineLength:null,minifyURLs:false,preserveLineBreaks:false,preventAttributesEscaping:false,processScripts:["text/html"],quoteCharacter:"",removeEmptyAttributes:true,removeEmptyElements:false,removeOptionalTags:true,removeRedundantAttributes:true,removeScriptTypeAttributes:false,removeStyleLinkTypeAttributes:true,removeTagWhitespace:false,sortAttributes:false,sortClassName:false,trimCustomFragments:true,useShortDoctype:true,continueOnParseError:true})}else if(hst2){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}const RESERVED_BARE_ATTRS=new Set(["body","view","scoped","tpl","sl","color","time","date","datetime","up","stop","confirm","econfirm","acl","rcl","hidden","disabled","readonly","required","checked","selected","autofocus","multiple","async","defer"]);function _collectWidgetRegions(nodes,found){if(!Array.isArray(nodes))return;for(const node of nodes){if(node&&node.type==="tag"&&node.attrs){for(const attrName in node.attrs){if(Object.prototype.hasOwnProperty.call(node.attrs,attrName)&&node.attrs[attrName]===""&&!RESERVED_BARE_ATTRS.has(attrName)&&!found.includes(attrName)){found.push(attrName)}}}if(node&&Array.isArray(node.children)){_collectWidgetRegions(node.children,found)}}}function annotateLayoutRegions(layoutsObj){for(const key in layoutsObj){if(!Object.prototype.hasOwnProperty.call(layoutsObj,key))continue;let entry=layoutsObj[key];if(!entry||!entry.hst)continue;let found=[];_collectWidgetRegions(entry.hst,found);entry.regions=found}return layoutsObj}exports.annotateLayoutRegions=annotateLayoutRegions;function v1CompatIndexHtml(html){return String(html).replace(/(<script\b[^>]*\bsrc=["'])\/?js\/bea\.js(?:\?[^"']*)?(["'])/gi,"$1/js/lm.js$2").replace(/<script\b[^>]*\bsrc=["']\/?index\.js(?:\?[^"']*)?["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/(?:s\.|www\.)?beacdn\.com\/beajs\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/lmjs\.beacdn\.com\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"")}exports.v1CompatIndexHtml=v1CompatIndexHtml;function readTemplates(root){let out={};for(const folder of["tpls","comps"]){let dir=root+path.sep+"src"+path.sep+folder+path.sep;if(fs.existsSync(dir))Object.assign(out,getAllFiles(dir,{},false,true))}return out}exports.readTemplates=readTemplates;function linkTemplateReactiveVars(files2,templates){function templateFor(attrs){let name=String(attrs.tpl).replace(/^\/+/,"");for(const f of["tpls","comps"]){let key=Buffer.from("src/"+f+"/"+name+".tpl").toString("base64");if(templates[key])return templates[key]}return null}function scan(nodes,add){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;let a=node.attrs;if(a&&node.type==="sections"&&a.hasOwnProperty("tpl")){let t=templateFor(a);if(t)(t.reactiveVars||[]).forEach(add)}if(a&&a.hasOwnProperty("view")){let sv=viewFor(a.view);if(sv)(sv.reactiveVars||[]).forEach(add)}if(node.children)scan(node.children,add);if(Array.isArray(node.content))scan(node.content,add)}}let viewByPath={};for(const key in files2){let p=Buffer.from(key,"base64").toString().replace(/\\/g,"/");let m=p.match(/(?:^|\/)views\/(.+)\.view$/);if(m)viewByPath[m[1]]=files2[key]}function viewFor(v){let p=String(v).trim().replace(/^\/+/,"").replace(/\.view$/,"");if(!p||/\{\{/.test(p))return null;return viewByPath[p]||null}for(let pass=0;pass<10;pass++){let grew=false;for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1){entry.reactiveVars.push(n);grew=true}})}if(!grew)break}for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1)entry.reactiveVars.push(n)})}return files2}exports.linkTemplateReactiveVars=linkTemplateReactiveVars;function hst_markSvg(nodes,inSvg){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;let name=String(n.name||"").toLowerCase();let here=inSvg||name==="svg";if(here)n.svg=true;let kidsInSvg=here&&name!=="foreignobject";hst_markSvg(n.children,kidsInSvg);if(Array.isArray(n.content))hst_markSvg(n.content,kidsInSvg)}}function hst_orderIfFor(res){if(!res||!res.attrs||!res.forX||!Object.prototype.hasOwnProperty.call(res.attrs,":if"))return;let keys=Object.keys(res.attrs);let cond=String(res.attrs[":if"]);if(keys.indexOf(":if")<keys.indexOf(":for")){res.forX.js="("+cond+") ? ("+res.forX.js+") : []"}else{let prev=res.attrs[":for-if"];res.attrs[":for-if"]=prev?"("+prev+") && ("+cond+")":cond}res.type="sections";delete res.cond;delete res.attrs[":if"];if(res.ax)delete res.ax[":if"]}exports.hst_orderIfFor=hst_orderIfFor;class hst{htmlVoidElements=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","isindex","keygen","link","menuitem","meta","nextid","param","source","track","wbr"];moustachePattern=/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g;attrRE=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?("[\s\S]*?"|'[\s\S]*?')/g;tagRE=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;whitespaceRE=/^\s*$/;empty=Object.create(null);reactiveVariables=[];constructor(html){let hst2=this.parse(html);hst_markSvg(hst2,false);this.reactiveVariables=this.reactiveVariables.filter((value,index,self)=>{return self.indexOf(value)===index});return{hst:hst2,"reactiveVars":this.reactiveVariables}}keepOneSpace(_t){_t=_t.replace(/\s\s/gm," ");if(/\s\s/gm.test(_t))return this.keepOneSpace(_t);return _t}_clean(_t){_t=_t.replace(/(\r?\n|\r)/gm,"");_t=_t.replace(/(\t)/gm,"");_t=this.keepOneSpace(_t);return _t.replace(/^(?:\s*\t*\r*\n*\{*)+|(?:\s*\t*\r*\n*\})+$/g,"").trim()}processAttr(n,v,res){}processForXAttr(val){let forX={"js":"","as":{"k":"","v":""},"dx":""};var val=val.trim();if(val.indexOf(";")>-1){let zxx=val.split(";");forX["dx"]=zxx[1].trim();val=zxx[0].trim()}if(val.indexOf(" as ")>-1){let arr2=val.split(" as ");let kv=[];let arr3=arr2[1].split(" ").join("").split(",");if(arr3.length>1){kv=[arr3[0],arr3[1]]}else{kv=[arr3[0]]}if(kv.length){forX["as"]["k"]=kv[0].trim();if(kv.length>1){forX["as"]["v"]=kv[1].trim()}}val=arr2[0].trim()}forX["js"]=val.trim();return forX}parseTag(tag){var res={type:"tag",name:"",isV:false,attrs:{},ax:{},evs:{},ex:{},children:[]};var tagMatch=tag.match(/<\/?([^\s]+?)[/\s>]/);if(tagMatch){res.name=tagMatch[1];res.isV=this.htmlVoidElements.includes(tagMatch[1])||tag.charAt(tag.length-2)==="/"}var reg=new RegExp(this.attrRE);var result=null;for(;;){result=reg.exec(tag);if(result===null){break}if(!result[0].trim()){continue}if(result[1]){var attr=result[1].trim();var arr=[attr,""];if(arr[0]==":else"){res.type="section";res.cond=""}if(attr.indexOf("=")>-1){arr=attr.split("=")}if(arr[0].substring(0,1)=="@"){}else{if(res.name.toLowerCase()=="icon"&&arr[0].indexOf(":")>-1&&arr[0].substr(0,1)!=":"){res.icon=arr[0]}else res.attrs[arr[0]]=arr[1]}reg.lastIndex--}else if(result[2]){let sl=result[3].trim().substring(1,result[3].length-1);sl=he.decode(sl);if(result[2]==":if"||result[2]==":else-if"||result[2]==":else"){res.type="section";res.cond=sl;if(sl){try{let condAST=acorn.parse(sl,{ecmaVersion:"latest"});let condVars=this.collectVariableUsageFromAST(condAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<condVars.length;X++){this.reactiveVariables.push(condVars[X])}}catch(e){}}}else if(result[2]==":for"){res.type="sections";res.content=sl;res.forX=this.processForXAttr(sl);if(res.forX.js){try{let forAST=acorn.parse(res.forX.js,{ecmaVersion:"latest"});let forVars=this.collectVariableUsageFromAST(forAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<forVars.length;X++){this.reactiveVariables.push(forVars[X])}}catch(e){}}}if(result[2].substring(0,1)=="@"){let max=this._getMs2(sl);res.evs[result[2]]=max[1];max[0].length?res.ex[result[2]]=max[0]:null}else{let max=this._getMs2(sl.replace(/`(\{\s*\{[\s\S]*?\}\s*\})`/g,"$1"));if(res.name.toLowerCase()=="icon"&&result[2].indexOf(":")>-1&&result[2].substr(0,1)!=":"){res.icon=result[2]}else res.attrs[result[2]]=max[1];max[0].length?res.ax[result[2]]=max[0]:null}}}hst_orderIfFor(res);return res}removeComments(str){str=str.replace(/<!--[\s\S]*?(?:-->)/g,"");return str}cleanExpression(expression){let cleaned="";let inSingle=false,inDouble=false,inTemplate=false;let inRegex=false,escapeNext=false;let inBlockComment=false,inLineComment=false;for(let i=0;i<expression.length;i++){let char=expression[i];let next=expression[i+1];if(escapeNext){cleaned+=char;escapeNext=false;continue}if(inBlockComment){if(char==="*"&&next==="/"){inBlockComment=false;i++}continue}if(inLineComment){if(char==="\n"){inLineComment=false}continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(char==="/"&&next==="*"){inBlockComment=true;i++;continue}if(char==="/"&&next==="/"){inLineComment=true;i++;continue}}if(!inDouble&&!inTemplate&&!inRegex&&char==="'"&&!inSingle){inSingle=true;cleaned+=char;continue}else if(inSingle&&char==="'"){inSingle=false;cleaned+=char;continue}if(!inSingle&&!inTemplate&&!inRegex&&char==='"'&&!inDouble){inDouble=true;cleaned+=char;continue}else if(inDouble&&char==='"'){inDouble=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inRegex&&char==="`"&&!inTemplate){inTemplate=true;cleaned+=char;continue}else if(inTemplate&&char==="`"){inTemplate=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&char==="/"&&!inRegex){let prevNonSpace=cleaned.match(/\S$/);if(!prevNonSpace||/[=({[,;:?!+\-*/%&|^~<>]/.test(prevNonSpace[0])){inRegex=true}cleaned+=char;continue}else if(inRegex&&char==="/"&&expression[i-1]!=="\\"){inRegex=false;cleaned+=char;continue}if(char==="\\"&&(inSingle||inDouble||inTemplate||inRegex)){escapeNext=true;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(/\s/.test(char)){if(cleaned[cleaned.length-1]!==" "){cleaned+=" "}continue}}cleaned+=char}return cleaned.trim()}_getMs(_t,wbt){let result="";let lastIndex=0;let _m;var _ms=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{let AST=acorn.parse(_m[0],{ecmaVersion:"latest"});hasError=false;let mux=this._clean(_m[0]);if(wbt){if(_t.substring(_m.index-1,1)=="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}else{if(_t.substring(_m.index-1,1)!="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}}catch(e){hasError=true;result+=_t.substring(lastIndex,_m.index);result+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)result+=_t.substring(lastIndex);return[_ms,result]}_getMs2(_t,wbt){let content="";let lastIndex=0;let _m;var _muxes=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{hasError=false;let mux=this._clean(_m[0]);let JST=acorn.parse(mux,{ecmaVersion:"latest"});let rvs=[];let vss=this.collectVariableUsageFromAST(JST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<vss.length;X++){rvs.push(vss[X]);this.reactiveVariables.push(vss[X])}rvs=rvs.filter((value,index,self)=>{return self.indexOf(value)===index});_muxes.push({"mus":mux,"rvs":rvs});content+=_t.substring(lastIndex,_m.index);content+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}catch(e){hasError=true;content+=_t.substring(lastIndex,_m.index);content+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)content+=_t.substring(lastIndex);_muxes=this.setMuxesIndexes(content,_muxes);return[_muxes,content]}setMuxesIndexes(content,_muxes){let muxes=[];let lastIndex=0;let i=0;let _m;while((_m=this.moustachePattern.exec(content))!=null){muxes.push({..._muxes[i],"start":_m.index,"end":_m.index+_m[0].length});lastIndex=_m.index+_m[0].length;i++}return muxes}parse(html,options){if(options===void 0){options={}}options||(options={});options.components||(options.components=this.empty);html=this.removeComments(html);var result=[];var arr=[];var current;var level=-1;var inComponent=false;var inRawText=false;var par=this;if(html.indexOf("<")!==0){var end=html.indexOf("<");let zl=end===-1?html:html.substring(0,end);let mssx=this._getMs2(zl);let textObj={type:"text",content:mssx[1],mss:mssx[0]};result.push(textObj)}html.replace(this.tagRE,async function(tag,index){if(inComponent||inRawText){if(tag!=="</"+current.name+">"){return""}else{inComponent=false;inRawText=false}}var isOpen=tag.charAt(1)!=="/";var start=index+tag.length;var nextChar=html.charAt(start);var parent;if(isOpen){level++;current=par.parseTag(tag);if(current.type==="tag"&&(current.name==="script"||current.name==="style")){inRawText=true}if(current.type==="tag"&¤t.name&&options.components&&options.components[current.name]){current.type="component";inComponent=true}if(!current.isV&&!inComponent&&nextChar&&nextChar!=="<"&&Array.isArray(current.children)){let end2;if(current.name==="script"||current.name==="style"){let closeRe=new RegExp("</\\s*"+current.name+"\\s*>","i");let m=closeRe.exec(html.slice(start));end2=m?start+m.index:html.length}else{end2=html.indexOf("<",start);while(html.charAt(end2+1)==" "){end2=html.indexOf("<",start+(end2+1-start))}}let hl=html.slice(start,end2);let mssx=null;if(current.name!="script")mssx=par._getMs2(hl);let textObj={type:"text",content:current.name=="script"?"":mssx[1],...current.name=="script"?scriptPayload(hl):{mss:mssx[0]},tag:current.name};current.children.push(textObj)}if(level===0){result.push(current)}parent=arr[level-1];if(parent&&parent.children){parent.children.push(current)}arr[level]=current}if(!isOpen||current.isV){if(level>-1&&(current.isV||current.name===tag.slice(2,-1))){level--;current=level===-1?result:arr[level]}if(!inComponent&&nextChar!=="<"&&nextChar){parent=level===-1?result:arr[level].children;var _end=html.indexOf("<",start);var content=html.slice(start,_end===-1?void 0:_end);let wsOnly=par.whitespaceRE.test(content);if(wsOnly?_end>-1&&parent&&Array.isArray(parent):true){if(parent&&Array.isArray(parent)){if(wsOnly){parent.push({type:"text",content,mss:[]})}else{let mssx=par._getMs2(content);let textObj={type:"text",content:mssx[1],mss:mssx[0]};parent.push(textObj)}}}}}});return result}collectVariableUsageFromAST(ast,options={}){const{excludeBuiltins=true,extraBuiltins=[]}=options;const DEFAULT_BUILTINS=new Set(["undefined","NaN","Infinity","null","true","false","Object","Function","Boolean","Symbol","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","Number","BigInt","Math","Date","String","RegExp","Array","Map","Set","WeakMap","WeakSet","Promise","Reflect","Proxy","Intl","JSON","Atomics","SharedArrayBuffer","ArrayBuffer","DataView","WeakRef","FinalizationRegistry","console","window","document","navigator","location","localStorage","sessionStorage","fetch","XMLHttpRequest","setTimeout","clearTimeout","setInterval","clearInterval","requestAnimationFrame","cancelAnimationFrame","process","global","globalThis","require","module","exports","Buffer","parseInt","parseFloat","isFinite","isNaN","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","escape","unescape"]);const builtinSet=new Set([...DEFAULT_BUILTINS,...extraBuiltins]);function createScope(parent=null,isFunction=false){return{parent,isFunction:!!isFunction,names:new Set}}const scopeForNode=new WeakMap;const bindingIdNodes=new WeakSet;const allDeclaredNames=new Set;function markPatternBindings(pattern,scope,kind="var"){if(!pattern)return;switch(pattern.type){case"Identifier":bindingIdNodes.add(pattern);declareInScope(pattern.name,kind,scope);allDeclaredNames.add(pattern.name);break;case"ArrayPattern":for(const el of pattern.elements)if(el)markPatternBindings(el,scope,kind);break;case"ObjectPattern":for(const p of pattern.properties){if(p.type==="Property")markPatternBindings(p.value,scope,kind);else if(p.type==="RestElement")markPatternBindings(p.argument,scope,kind)}break;case"RestElement":markPatternBindings(pattern.argument,scope,kind);break;case"AssignmentPattern":markPatternBindings(pattern.left,scope,kind);break;default:break}}function declareInScope(name,kind,currentScope){if(!name||!currentScope)return;if(kind==="var"||kind==="function"){let s=currentScope;while(s&&!s.isFunction&&s.parent)s=s.parent;s.names.add(name)}else{currentScope.names.add(name)}}function buildScopes(node,currentScope){if(!node||typeof node!=="object")return;switch(node.type){case"Program":{scopeForNode.set(node,currentScope);for(const stmt of node.body)buildScopes(stmt,currentScope);return}case"FunctionDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"function",currentScope);allDeclaredNames.add(node.id.name)}const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"FunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",fnScope);allDeclaredNames.add(node.id.name)}for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"ArrowFunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"BlockStatement":case"StaticBlock":case"SwitchStatement":{const blockScope=createScope(currentScope,false);scopeForNode.set(node,blockScope);if(node.type==="SwitchStatement"){for(const c of node.cases)buildScopes(c,blockScope)}else{for(const s of node.body)buildScopes(s,blockScope)}return}case"CatchClause":{const catchScope=createScope(currentScope,false);scopeForNode.set(node,catchScope);if(node.param)markPatternBindings(node.param,catchScope,"let");buildScopes(node.body,catchScope);return}case"ForStatement":case"ForInStatement":case"ForOfStatement":{const forScope=createScope(currentScope,false);scopeForNode.set(node,forScope);if(node.init)buildScopes(node.init,forScope);if(node.left)buildScopes(node.left,forScope);if(node.test)buildScopes(node.test,forScope);if(node.update)buildScopes(node.update,forScope);buildScopes(node.body,forScope);return}case"VariableDeclaration":{for(const decl of node.declarations||[]){markPatternBindings(decl.id,currentScope,node.kind||"var");if(decl.init)buildScopes(decl.init,currentScope)}return}case"ClassDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",currentScope);allDeclaredNames.add(node.id.name)}if(node.body)buildScopes(node.body,currentScope);return}case"ImportDeclaration":{for(const spec of node.specifiers||[]){if(spec.local){bindingIdNodes.add(spec.local);declareInScope(spec.local.name,"const",currentScope);allDeclaredNames.add(spec.local.name)}}return}case"ExportNamedDeclaration":case"ExportDefaultDeclaration":case"ExportAllDeclaration":{if(node.declaration)buildScopes(node.declaration,currentScope);return}default:break}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(const c of child)if(c&&typeof c==="object")buildScopes(c,currentScope)}else if(child&&typeof child==="object"){buildScopes(child,currentScope)}}}const rootScope=createScope(null,true);scopeForNode.set(ast,rootScope);buildScopes(ast,rootScope);const usageSet=new Set;function isVariableUsageIdentifier(node,parent,propName){if(!parent)return true;if(bindingIdNodes.has(node))return false;if(parent.type==="LabeledStatement"&&propName==="label"||(parent.type==="BreakStatement"||parent.type==="ContinueStatement")&&propName==="label"){return false}if(parent.type==="MemberExpression"&&propName==="property"&&parent.computed===false){return false}if(parent.type==="Property"&&propName==="key"&&parent.computed===false&&!parent.shorthand){return false}if((parent.type==="MethodDefinition"||parent.type==="PropertyDefinition")&&propName==="key"&&parent.computed===false){return false}if(parent.type&&(parent.type.startsWith("Import")||parent.type.startsWith("Export")||parent.type==="MetaProperty")){return false}if((parent.type==="FunctionDeclaration"||parent.type==="FunctionExpression"||parent.type==="ClassDeclaration")&&propName==="id"){return false}if(parent.type==="VariableDeclarator"&&propName==="id"||parent.type==="CatchClause"&&propName==="param"){return false}if((parent.type==="CallExpression"||parent.type==="OptionalCallExpression")&&propName==="callee"){return false}if(parent.type==="NewExpression"&&propName==="callee"){return false}return true}const scopeStack=[rootScope];function collect(node,parent,propName,index){if(!node||typeof node!=="object")return;const nodeScope=scopeForNode.get(node);if(nodeScope)scopeStack.push(nodeScope);if(node.type==="Identifier"){if(isVariableUsageIdentifier(node,parent,propName)){const name=node.name;if(!(excludeBuiltins&&builtinSet.has(name))){usageSet.add(name)}}}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(let i=0;i<child.length;i++){const c=child[i];if(c&&typeof c==="object")collect(c,node,key,i)}}else if(child&&typeof child==="object"){collect(child,node,key,null)}}if(nodeScope)scopeStack.pop()}collect(ast,null,null,null);const self=this;(function findTpl(node){if(!node||typeof node!=="object")return;if(node.type==="TemplateLiteral"&&node.expressions.length===0&&node.quasis.length===1){const inner=node.quasis[0].value.cooked;if(inner&&inner.trim()){try{const innerAst=_acorn.parse(inner,{ecmaVersion:"latest",sourceType:"script"});for(const n of self.collectVariableUsageFromAST(innerAst,options))usageSet.add(n)}catch(e){}}return}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child))child.forEach(findTpl);else if(child&&typeof child==="object")findTpl(child)}})(ast);return Array.from(usageSet).sort()}}function _hst(html){return new hst(html)}function copyDir(src,dest,projectName){try{const entries=fs.readdirSync(src,{encoding:"utf8",withFileTypes:true});cd(dest);for(let entry of entries){const srcPath=path.join(src.toString(),entry.name.toString());const destPath=path.join(dest.toString(),entry.name.toString());if(entry.isDirectory()){if(projectName=="_beajsBuild"){if(entry.name!="layouts"&&entry.name!="views"&&entry.name!="css"&&entry.name!="js")copyDir(srcPath,destPath,projectName)}else copyDir(srcPath,destPath,projectName)}else{if(projectName=="_beajsBuild"){if(projectName=="_beajsBuild"&&entry.name!="index.js"&&entry.name!="index.html")fs.copyFileSync(srcPath,destPath)}else{if(!fs.existsSync(destPath)){if(projectName){if(entry.name=="index.html"){let html5=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(ucwords(projectName)));fs.writeFileSync(destPath,html5)}else if(entry.name=="package.json"){let slug=lw(projectName).replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"lumenjs-project";let pkgJson=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(slug));fs.writeFileSync(destPath,pkgJson)}else fs.copyFileSync(srcPath,destPath)}else fs.copyFileSync(srcPath,destPath)}else{console.log("File already exists:",destPath)}}}}}catch(e){console.log(e)}}exports.copyDir=copyDir;function validURL(string){let url;try{url=new URL(string)}catch(_){return false}return url.protocol==="http:"||url.protocol==="https:"}exports.validURL=validURL;let getPairs=(obj,keys=[])=>Object.entries(obj).reduce((pairs,[key,value])=>{if(typeof value==="object")pairs.push(...getPairs(value,[...keys,key]));else pairs.push([[...keys,key],value]);return pairs},[]);function pairIt(obj){return getPairs(obj).map(([[key0,...keysRest],value])=>`${key0}${keysRest.map(a=>`[${a}]`).join("")}=${value}`).join("&")}var API={get:async function(u,d,h,a){return await this.req(u,d,h,"GET",a)},put:async function(u,d,h,a){return await this.req(u,d,h,"PUT",a)},post:async function(u,d,h,a){return await this.req(u,d,h,"POST",a)},delete:async function(u,d,h,a){return await this.req(u,d,h,"DELETE",a)},patch:async function(u,d,h,a){return await this.req(u,d,h,"PATCH",a)},req:async function(u,d,h,m,a,f){var urled=validURL(u)?u:config.apis[a??0].baseURL+u;if(m.toString().toLowerCase()=="get"){if(urled.indexOf("?")>-1)urled=urled+"&"+pairIt(d??{});else urled=urled+"?"+pairIt(d??{})}let resa=await fetch(urled,{method:m.toString().toLowerCase(),body:m.toString().toLowerCase()=="get"?null:JSON.stringify(d??{}),headers:h??config.apis[a??0].headers});if(f)return resa;let res=await resa.text();try{return JSON.parse(res)}catch(e){return res}}};exports.API=API;function updateCore(){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var projectJsPath=process.cwd()+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";var projectCssPath=process.cwd()+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css";if(!fs.existsSync(process.cwd()+path.sep+"config.json")||!fs.existsSync(process.cwd()+path.sep+"src")){console.log("This doesn't look like a LumenJS project (no config.json/src here) \u2014 run this from your project's root.");return}if(!fs.existsSync(libsPath+path.sep+"lm.js")){console.log("This CLI install has no bundled runtime to copy from \u2014 reinstall @lmjs/cli.");return}addAgentFiles(process.cwd());var oldSize=fs.existsSync(projectJsPath)?fs.statSync(projectJsPath).size:null;var newJs=fs.readFileSync(libsPath+path.sep+"lm.js");var newSize=newJs.length;if(oldSize===newSize){console.log("Already up to date \u2014 this project's src/js/lm.js already matches the installed @lmjs/cli's runtime ("+newSize+" bytes). Nothing to do.");return}fs.writeFileSync(projectJsPath,newJs);if(fs.existsSync(libsPath+path.sep+"mobius.css")){fs.writeFileSync(projectCssPath,fs.readFileSync(libsPath+path.sep+"mobius.css"))}console.log("Updated src/js/lm.js"+(oldSize!==null?" (was "+oldSize+" bytes, now "+newSize+" bytes)":" (was missing, now "+newSize+" bytes)")+" \u2014 matches the currently installed @lmjs/cli.")}exports.updateCore=updateCore;function addAgentFiles(projectPath){var tplDir=path.join(__dirname,"files","project");var added=[];["AGENTS.md","CLAUDE.md"].forEach(function(f){var dest=path.join(projectPath,f);if(!fs.existsSync(dest)&&fs.existsSync(path.join(tplDir,f))){fs.copyFileSync(path.join(tplDir,f),dest);added.push(f)}});if(added.length)console.log("Added "+added.join(" + ")+" (points AI coding agents at the LumenJS reference).");return added}exports.addAgentFiles=addAgentFiles;exports.processCommand=processCommands;exports.startServer=startServer;exports.create=create;function processCommands(cmd){var command=cmd?cmd:process.argv[2];if(command=="run"||command=="serve"){startServer()}else if(command=="create"||command=="update"){let c=process.argv.slice(3,process.argv.length);let t=lw(c[0]);create({type:t[0]=="-"?t.split("-").join(""):t,name:t[0]=="-"?c.slice(1,c.length):c})}else if(command=="update-core"){updateCore()}else if(command=="purge"){console.log("(lm purge now does the same thing as `lm update-core` \u2014 prefer that name going forward.)");updateCore()}else if(command=="build"){let cmds=process.argv;_bp(cmds)}else if(command=="login"){_vault.login()}else if(command=="api"){let sub=process.argv[3];let name=process.argv[4];if(sub=="set")_vault.apiSet(name);else if(sub=="update")_vault.apiUpdate(name);else if(sub=="get")_vault.apiGet(name);else if(sub=="list")_vault.apiList();else if(sub=="remove")_vault.apiRemove(name);else console.log("Usage: lm api <set|get|update|list|remove> [name]")}else if(command=="-v"||command=="-version"){let _pkgJsonPath=fs.existsSync(path.join(__dirname,"..","..","package.json"))?path.join(__dirname,"..","..","package.json"):path.join(__dirname,"..","package.json");console.log("LumenJS version "+require(_pkgJsonPath).version)}else{console.log("LumenJS CLI's command not found!")}}async function _bp(cmds){import("ora").then(async({default:ora,oraPromise})=>{const spinner=ora({color:"green"});spinner.succeed("Started Building Project For Production").start("Gathering Required Resources..");var projectPath=`${process.cwd()}`;if(!checkProjectRuntime(projectPath)){spinner.fail("Build stopped: run `lm update-core` first, then build again.");process.exit(1)}var dest=projectPath+path.sep+"dist";let _views=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);let _layoutsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep;let _layouts=fs.existsSync(_layoutsDir)?annotateLayoutRegions(getAllFiles(_layoutsDir,{},false,true)):{};let _tpls=readTemplates(`${process.cwd()}`);linkTemplateReactiveVars(_views,_tpls);linkTemplateReactiveVars(_layouts,_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");let _cssDir=projectPath+path.sep+`src`+path.sep+"css"+path.sep;let _mainCssName=["mobius.css","bea.css"].find(f=>fs.existsSync(_cssDir+f))||null;var beaCSSCode=_mainCssName?fs.readFileSync(_cssDir+_mainCssName,"utf8"):"";var indexJs=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.js","utf8");let _hasOwnDeps=_npmBundle.hasOwnDependencies(projectPath);let _localScriptSrcs=detectLocalProjectScripts(String(indexCode));let _compiledScripts="";for(const src of _localScriptSrcs){let scriptPath=projectPath+path.sep+"src"+path.sep+src.split("/").join(path.sep).replace(/^\\|^\//,"");try{let raw=_hasOwnDeps?_npmBundle.buildEntryWithImports(scriptPath,projectPath):fs.readFileSync(scriptPath,"utf8");_compiledScripts+="\n"+compileProjectScript(raw,src);indexCode=indexCode.split(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']`+src.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+`["'][^>]*>\\s*<\\/script>`,"i")).join("")}catch(e){}}let _uncompiledScripts=precompileViewScripts([{kind:"views",files:_views},{kind:"layouts",files:_layouts},{kind:"tpls",files:_tpls}]);let vt=`
|
|
2
2
|
var _vcData = {
|
|
3
3
|
"hstFormatVersion": `+HST_FORMAT_VERSION+`,
|
|
4
4
|
"views": `+JSON.stringify(_views,compactHstReplacer)+`,
|
|
@@ -33,7 +33,7 @@ var LM_BUILD=(function(){try{var m=/\/js\/app\.(\d+)\.js/.exec(document.currentS
|
|
|
33
33
|
!(function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.ReconnectingWebSocket=b()})(this,function(){function a(b,c,d){function l(a2,b2){var c2=document.createEvent("CustomEvent");return c2.initCustomEvent(a2,false,false,b2),c2}var e={debug:false,automaticOpen:true,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1,timeoutInterval:3e3};d||(d={});for(var f in e)this[f]="undefined"!=typeof d[f]?d[f]:e[f];this.url=b,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var h,g=this,i2=false,j=false,k=document.createElement("div");k.addEventListener("open",function(a2){g.onopen(a2)}),k.addEventListener("close",function(a2){g.onclose(a2)}),k.addEventListener("connecting",function(a2){g.onconnecting(a2)}),k.addEventListener("message",function(a2){g.onmessage(a2)}),k.addEventListener("error",function(a2){g.onerror(a2)}),this.addEventListener=k.addEventListener.bind(k),this.removeEventListener=k.removeEventListener.bind(k),this.dispatchEvent=k.dispatchEvent.bind(k),this.open=function(b2){try{h=new WebSocket(g.url,c||[]),b2||k.dispatchEvent(l("connecting")),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",g.url);var d2=h,e2=setTimeout(function(){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",g.url),j=true,j=false;if(d2.readyState==1)d2.close()},g.timeoutInterval);h.onopen=function(){clearTimeout(e2),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onopen",g.url),g.protocol=h.protocol,g.readyState=WebSocket.OPEN,g.reconnectAttempts=0;var d3=l("open");d3.isReconnect=b2,b2=false,k.dispatchEvent(d3)},h.onclose=function(c2){if(clearTimeout(e3),h=null,i2)g.readyState=WebSocket.CLOSED,k.dispatchEvent(l("close"));else{g.readyState=WebSocket.CONNECTING;var d3=l("connecting");d3.code=c2.code,d3.reason=c2.reason,d3.wasClean=c2.wasClean,k.dispatchEvent(d3),b2||j||((g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onclose",g.url),k.dispatchEvent(l("close")));var e3=g.reconnectInterval*Math.pow(g.reconnectDecay,g.reconnectAttempts);setTimeout(function(){g.reconnectAttempts++,g.open(true)},e3>g.maxReconnectInterval?g.maxReconnectInterval:e3)}},h.onmessage=function(b3){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",g.url,b3.data);var c2=l("message");c2.data=b3.data,k.dispatchEvent(c2)},h.onerror=function(b3){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onerror",g.url,b3),k.dispatchEvent(l("error"))}}catch(error){console.error("WebSocket connection error:",error)}},1==this.automaticOpen&&this.open(false),this.send=function(b2){if(h)return(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","send",g.url,b2),h.send(b2);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(a2,b2){"undefined"==typeof a2&&(a2=1e3),i2=true,h&&h.close(a2,b2)},this.refresh=function(){h&&h.readyState==1&&h.close()}}return a.prototype.onopen=function(){},a.prototype.onclose=function(){},a.prototype.onconnecting=function(){},a.prototype.onmessage=function(){},a.prototype.onerror=function(){},a.debugAll=false,a.CONNECTING=WebSocket.CONNECTING,a.OPEN=WebSocket.OPEN,a.CLOSING=WebSocket.CLOSING,a.CLOSED=WebSocket.CLOSED,a});let _isTipped=false;var _debugMode=false;var _initialized=null;var _dbcrs={};var _dbcrsTime=200;var _tickTime=20;var _scW=0;var cl=console.log;if(!_vcData)var _vcData=void 0;if(!_beaTn)var _beaTn=void 0;var beas;var appSettings;var execEl="";var currentlyValidTags=new Array;var _upwrk=new WebWorker("_upw");var _csswrk=new WebWorker("_cssw");_csswrk.start();var _ups=[];(function(e,t2){typeof module!="undefined"&&module.exports?module.exports=t2():typeof define=="function"&&define.amd?define(t2):this[e]=t2()})("bea",function(){function p(e2,t3){for(var n3=0,i3=e2.length;n3<i3;++n3)if(!t3(e2[n3]))return r2;return 1}function d(e2,t3){p(e2,function(e3){return t3(e3),1})}function v(e2,t3,n3){function g(e3){return e3.call?e3():u[e3]}function y(){if(!--h2){u[o2]=1,s2&&s2();for(var e3 in f)p(e3.split("|"),g)&&!d(f[e3],g)&&(f[e3]=[])}}e2=e2[i2]?e2:[e2];var r3=t3&&t3.call,s2=r3?t3:n3,o2=r3?e2.join(""):t3,h2=e2.length;return setTimeout(function(){d(e2,function t4(e3,n4){if(e3===null)return y();/*!n &&
|
|
34
34
|
!/^https?:\/\//.test(e) &&
|
|
35
35
|
c &&
|
|
36
|
-
(e = e.indexOf(".js") === -1 ? c + e + ".js" : c + e);*/if(l[e3])return o2&&(a[o2]=1),l[e3]==2?y():setTimeout(function(){t4(e3,true)},0);l[e3]=1,o2&&(a[o2]=1),m(e3,y)})},0),v}function m(n3,r3){var i3=e.createElement("script"),u2;i3.onload=i3.onerror=i3[o]=function(){if(i3[s]&&!/^c|loade/.test(i3[s])||u2)return;i3.onload=i3[o]=null,u2=1,l[n3]=2,r3()},i3.async=1,i3.setAttribute("crossorigin","anonymous"),i3.setAttribute("data-permanent",1),i3.src=h?n3+(n3.indexOf("?")===-1?"?":"&")+h:n3,t2.insertBefore(i3,t2.lastChild)}var e=document,t2=e.getElementsByTagName("head")[0],n2="string",r2=false,i2="push",s="readyState",o="onreadystatechange",u={},a={},f={},l={},c,h;return v.get=m,v.order=function(e2,t3,n3){(function r3(i3){i3=e2.shift(),e2.length?v(i3,r3):v(i3,t3,n3)})()},v.path=function(e2){c=e2},v.urlArgs=function(e2){h=e2},v.ready=function(e2,t3,n3){e2=e2[i2]?e2:[e2];var r3=[];return!d(e2,function(e3){u[e3]||r3[i2](e3)})&&p(e2,function(e3){return u[e3]})?t3():!(function(e3){f[e3]=f[e3]||[],f[e3][i2](t3),n3&&n3(r3)})(e2.join("|")),v},v.done=function(e2){v([null],e2)},v});(function(n2,t2){this[n2]=t2()})("sbea",function(){return function(x2){beas=x2}});(function(n2,t2){this[n2]=t2()})("Reactor",function(){return function(o){appSettings=o;if(o.Base)beas=o.Base;else{var getUrl=window.location;var baseUrl=getUrl.protocol+"//"+getUrl.host+"/";if(o.subDirectory)baseUrl=baseUrl+o.subDirectory+"/";appSettings.Base=baseUrl}if(o.App)execEl=o.App;if(o.Additional){bea([o.Additional],"ready",function(){})}if(o.init&&typeof o.init==="function")o.init()}});var fullTB=[{items:["Source","-","searchCode","autoFormat","CommentSelectedRange","UncommentSelectedRange","AutoComplete","-","Save","NewPage","Preview","Print","-","Templates","-","Cut","Copy","Paste","PasteText","PasteFromWord","PasteCode","-","Undo","Redo","-","SelectAll","-","Find","-","Image","CodeSnippet","Flash","Table","HorizontalRule","Smiley","SpecialChar","PageBreak","Iframe","VideoDetector","-","Blockquote","CreateDiv","simplebutton","-","Link","Unlink","Anchor","-","TextColor","BGColor","-","Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","-","NumberedList","BulletedList","-","Outdent","Indent","-","CopyFormatting","RemoveFormat","-","lineheight","letterspacing","Styles","Format","Font","FontSize","-","ShowBlocks"]}];var normalTB=[{name:"basicstyles",groups:["basicstyles","cleanup"],items:["Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","Language","-","Undo","Redo","-","SelectAll","-","CopyFormatting","RemoveFormat"]},"/",{items:["Find","-","Image","Table","HorizontalRule","Smiley","SpecialChar","Iframe","VideoDetector","-","Link","Unlink","Anchor"]},{name:"paragraph",groups:["list","indent","blocks","align","bidi"],items:["TextColor","BGColor","-","NumberedList","BulletedList","-","Outdent","Indent"]},"/",{name:"styles",items:["lineheight","letterspacing","Styles","Format","Font","FontSize"]}];var miniTB=[{name:"basicstyles",groups:["basicstyles","cleanup"],items:["Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","Language","-","Link","Unlink","Anchor","-","CopyFormatting","RemoveFormat"]},"/",{name:"paragraph",groups:["list","indent","blocks","align","bidi"],items:["TextColor","BGColor","-","NumberedList","BulletedList","-","Outdent","Indent"]},{name:"styles",items:["Styles","Format","Font","FontSize"]}];(function(submit){HTMLFormElement.prototype.submit=function(data2){$(this).submit();return false}})(HTMLFormElement.prototype.submit);[HTMLElement,typeof SVGElement!=="undefined"?SVGElement:null].forEach(function(Ctor){if(!Ctor)return;var P=Ctor.prototype;P.setAttributeNative=P.setAttribute;P.removeAttributeNative=P.removeAttribute;P.getAttributeNative=P.getAttribute;P.setAttribute=function(prop,val2){if(prop.substr(0,1)=="@"){try{this.events[prop]=val2}catch(e){}}else{this.setAttributeNative(prop,val2)}};P.removeAttribute=function(prop,val2){if(prop.substr(0,1)=="@"){try{delete this.events[prop]}catch(e){}}else{this.removeAttributeNative(prop,val2)}};P.getAttribute=function(prop,val2){if(prop.substr(0,1)=="@"){try{return this.events[prop]}catch(e){return this.getAttributeNative(prop,val2)}}else{return this.getAttributeNative(prop,val2)}}});var XHRs=new Array;if(localStorage.getItem("globals")===null)localStorage.setItem("globals",JSON.stringify({}));if(localStorage.getItem("_rx")===null)localStorage.setItem("_rx",JSON.stringify({}));var _globalsBackingValue;Object.defineProperty(window,"globals",{configurable:true,enumerable:true,get:function(){return _globalsBackingValue},set:function(v){if(v===_globalsBackingValue)return;_globalsBackingValue=_deepReactive(v,_onGlobalsDeepChange);_onGlobalsDeepChange()}});function _onGlobalsDeepChange(){if(typeof _vt!=="undefined"&&_vt.Global&&_vt.Global.vars){_vt.Global.vars.globals=globals}_scheduleGlobalsSave()}var _globalsSaveQueued=false;function _scheduleGlobalsSave(){if(_globalsSaveQueued)return;_globalsSaveQueued=true;setTimeout(function(){_globalsSaveQueued=false;try{var json=JSON.stringify(_globalsBackingValue===void 0?{}:_globalsBackingValue);if(localStorage.getItem("globals")!==json)localStorage.setItem("globals",json)}catch(e){}},0)}globals=clone(JSON.parse(localStorage.getItem("globals")));let _rx=clone(JSON.parse(localStorage.getItem("_rx")));var watch={};var popups={"modals":[],"react-modals":[]};var cntrlon=0;var _gn=0,_worker;var nodes=[];var historyStack=[];var _jsuid={};function clone(item){if(!item){return item}var types2=[Number,String,Boolean],result;types2.forEach(function(type2){if(item instanceof type2){result=type2(item)}});if(typeof result=="undefined"){if(Object.prototype.toString.call(item)==="[object Array]"){result=[];item.forEach(function(child,index,array){result[index]=clone(child)})}else if(typeof item=="object"){if(item.nodeType&&typeof item.cloneNode=="function"){result=item.cloneNode(true)}else if(!item.prototype){if(item instanceof Date){result=new Date(item)}else{result={};for(var i2 in item){result[i2]=clone(item[i2])}}}else{if(false){result=new item.constructor}else{result=item}}}else{result=item}}return result}function isInput(o){if(o.is(":checkbox")||o.is("input")||o.is("textarea")||o.is(":radio")||o.is("select"))return true;return false}function getVal(o){if(isInput(o)){return $.trim(o.val())}return o.html()}function setVal(o,v){if(isInput(o)){o.val(v)}else o.html(v)}function iterateConditions(text){var results=[];var opts=text.split("##");var iff=opts.shift();opts=opts.join("##");if(opts.indexOf("#else#")>-1)var hasElse=true;if(opts.indexOf("#elseif#")>-1)var hasElseIfs=true;if(hasElse){opts=opts.split("#else#");var elsee=opts.pop();opts=opts.join("")}if(hasElseIfs){results["elseif"]=[];var elseifs=opts.split("#elseif#");var ifOpts=elseifs.shift();results["if"]={cond:iff,val:ifOpts};for(var index=0;index<elseifs.length;index++){var elf=elseifs[index].split("##");results["elseif"].push({cond:elf[0],val:elf[1]})}if(hasElse)results["else"]=elsee}else if(hasElse){results["if"]={cond:iff,val:opts};if(hasElse)results["else"]=elsee}else{results["if"]={cond:iff,val:opts}}return results}function wait(){_initialized=false}function resume(){_initialized=true}const pause=msec=>new Promise((resolve,_)=>{setTimeout(resolve,msec)});function _lumenReadyHandler(){if(typeof appSettings==="undefined"||!appSettings){setTimeout(_lumenReadyHandler,10);return}nodes=getURLNodes();if(_initialized==null)_initialized=true;$("html").removeClass("no_js");if(!$("[exec]").length)$("body").append({beajs:true,body:"<div exec class=h></div>"});$(document).keyup(function(e){cntrlon=0});$(document).keydown(function(e){if(e.ctrlKey||e.metaKey){cntrlon=1}});goToNode()}$(document).ready(_lumenReadyHandler);function updateLocalVariable(k){if(k=="_rx")_rx=clone(JSON.parse(localStorage.getItem("_rx")));else globals=clone(JSON.parse(localStorage.getItem("globals")))}function setGlobals(x2){localStorage.setItem("globals",JSON.stringify(x2));globals=clone(JSON.parse(localStorage.getItem("globals")))}function setRX(x2){localStorage.setItem("_rx",JSON.stringify(x2));_rx=clone(JSON.parse(localStorage.getItem("_rx")))}$(window).on("storage",function(e){if(e.originalEvent.key=="globals"){if(localStorage.getItem("globals")!=null)updateLocalVariable();else setGlobals(globals)}else if(e.originalEvent.key=="_rx"){if(localStorage.getItem("_rx")!=null)updateLocalVariable("_rx");else setRX(_rx)}});var _work=function(){if(!$(".prog").length)$("body").append('<div class="prog"><div class=bar role=bar></div><div class=spinner role=spinner><div class="spinner-icon"></div></div></div>');_worker=setTimeout(function(){_gn=incri(_gn);barSet(_gn,200);_work()},200)};$(document).ajaxStart(function(){_gn=0;_work();if(typeof heartbeat==="function")heartbeat()}).ajaxStop(function(){_gn=0;barSet(1,200);if(typeof heartbeat==="function")heartbeat();globalWatch()}).ajaxError(function(e,xhr,opt){if(xhr.statusText=="error"){if(xhr.status=="422")$("[exec]").html(xhr.responseText);else if(xhr.status=="0"){$("[dropzone].pending").removeClass("pending").addClass("error");$("body").addClass("no-internet-connection")}}if(typeof heartbeat==="function")heartbeat();globalWatch();_gn=0;barSet(1,200)});(function($2){$2.extend({inArrayIn:function(elem,arr,i2){if(typeof elem!=="string"){return $2.inArray.apply(this,arguments)}if(arr){var len=arr.length;i2=i2?i2<0?Math.max(0,len+i2):i2:0;elem=elem.toLowerCase();for(;i2<len;i2++){if(i2 in arr&&arr[i2].toLowerCase()==elem){return i2}}}return-1}})})(jQuery);$.fn.priorityOn=function(type2,selector2,data2,fn2){this.each(function(){var $this=$(this);var types2=type2.split(" ");for(var t2 in types2){$this.on(types2[t2],selector2,data2,fn2);if(typeof $._data!=="function")continue;var currentBindings=($._data(this,"events")||{})[types2[t2]];if($.isArray(currentBindings)){currentBindings.unshift(currentBindings.pop())}}});return this};$.fn.lock=function(){if($(this).is("form")){$(this).find('[type="submit"]').attr("disabled","disabled");$(this).find("button:not([type])").attr("disabled","disabled")}return this};$.fn.unlock=function(){if($(this).is("form")){$(this).find('[type="submit"]').removeAttr("disabled");$(this).find("button:not([type])").removeAttr("disabled")}return this};$.fn.onClose=function(selector2,data2,fn2){this.each(function(){var el2=$(this);var types2=["close"];for(var t2 in types2){el2.on(types2[t2],selector2,data2,fn2)}});return this};$.fn.attach=function(type,selector,data,fn){var el=$(this);var types=type.split(" ");for(var t in types){var lu="$.fn.on"+types[t]+' = function (selector, data, fn) { var el = $(this); var types = ["'+types[t]+'"]; for (var t in types) { el.live(types[t], selector, data, fn); } return this;};';try{eval(lu)}catch(e){}}return this};$.fn.hasAttr=function(k){return!!(this[0]&&this[0].getAttribute(k)!=null)};$.fn.hasKey=function(k){return typeof this.data(k)!=="undefined"};function dotsIntoObjs(keys,value){var tempObject={};var container=tempObject;keys.split(".").map((k,i2,values)=>{container=container[k]=i2==values.length-1?value:{}});return tempObject}$.fn.set=function(name,value){var splitter=name.split(".");if(splitter.length>1){var key=splitter.shift();return this.data(key,dotsIntoObjs(splitter.join("."),value))}return this.data(name,value)};$.fn.props=function(){return this.data("props")};$.fn.scope=function(_sview){var _scopedVariables=_sview(this,this.data("props")??{})??{};for(var x2=0;x2<Object.keys(_scopedVariables).length;x2++){var _key=Object.keys(_scopedVariables)[x2];var val2=_scopedVariables[_key];this.set(_key,val2)}};$.fn.isOverflown=function(){return $(this)[0].scrollHeight>$(this)[0].clientHeight||$(this)[0].scrollWidth>$(this)[0].clientWidth};function removeEmptyElement(arr){var filtered=arr.filter(function(el2){return el2});return filtered}function findInObject(object,property,value){for(var i2=0;i2<object.length;i2+=1){if(object[i2][property]===value){return i2}}}function compareUs(object1,object2){var areObjects=isObject(object1)&&isObject(object2);if(!areObjects){if(typeof object1=="number"&&typeof object2=="number"){if(isNaN(object1)&&isNaN(object2))return true}return object1==object2}const keys1=Object.keys(object1);const keys2=Object.keys(object2);if(keys1.length!==keys2.length){return false}for(const key of keys1){const val1=object1[key];const val2=object2[key];const areObjects2=isObject(val1)&&isObject(val2);if(areObjects2&&!compareUs(val1,val2)||!areObjects2&&val1!==val2){return false}}return true}function deepCompare(object1,object2,path=""){const areObjects=isObject(object1)&&isObject(object2);if(!areObjects){if(typeof object1==="number"&&typeof object2==="number"){if(isNaN(object1)&&isNaN(object2)){return true}}if(object1!==object2){return false}return true}const keys1=Object.keys(object1);const keys2=Object.keys(object2);if(keys1.length!==keys2.length){return false}for(const key of keys1){const newPath=path?`${path}.${key}`:key;const val1=object1[key];const val2=object2[key];const areNestedObjects=isObject(val1)&&isObject(val2);if(!deepCompare(val1,val2,newPath)){return false}}return true}function isObject(object){return object!=null&&typeof object==="object"}(function(old){$.fn.attr=function(){if(arguments.length===0){if(this.length===0){return null}var obj={};$.each(this[0].attributes,function(){if(this.specified){obj[this.name]=this.value}});return obj}return old.apply(this,arguments)}})($.fn.attr);function st(b){if(!isNaN(b))$("html,body").stop().animate({scrollTop:b+"px"},{duration:400});else $("html,body").stop().animate({scrollTop:$(b).offset().top+"px"},{duration:400})}function pushURL(url,d){if(url||url==""){if(history&&history.pushState){history.pushState({},"",appSettings.Base+"/"+url.replace(new RegExp("^[/]+"),""));goToNode(d)}else{parent.location.href=url}}else{alert(url)}}function formatBytes(bytes,decimals){if(bytes==0)return"0 Bytes";var k=1024,dm=decimals<=0?0:decimals||2,sizes=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i2=Math.floor(Math.log(bytes)/Math.log(k));return parseFloat((bytes/Math.pow(k,i2)).toFixed(dm))+" "+sizes[i2]}function passwordContainsSymbol(value){var containsSymbol=false,symbols=`-!\xA7$%&/()=?.:,~;'#+*-/\\|{}[]_<>"`.split("");$.each(symbols,function(index,symbol){if(value.indexOf(symbol)>-1){containsSymbol=true;return false}});return containsSymbol}function passwordStrength(pass){var s=0,n2;if(pass.length>5)s+=10;if(/[a-z]/.test(pass))s+=1;if(/[A-Z]/.test(pass))s+=1;if(/[0-9]/.test(pass))s+=1;if(passwordContainsSymbol(pass))s+=1;if(s==14)n2="very-strong";else if(s==13)n2="strong";else if(s==12)n2="medium";else if(s==11)n2="weak";else n2="";if(/\s/g.test(pass))n2="has-spaces";return n2}function passwordValid(pass){var n2=passwordStrength(pass);if(n2=="strong"||n2=="very-strong")return true;return false}function incri(n2){var amount;if(n2>1){return .994}else{if(n2>=0&&n2<.2){amount=.1}else if(n2>=.2&&n2<.5){amount=.04}else if(n2>=.5&&n2<.8){amount=.02}else if(n2>=.8&&n2<.99){amount=.005}else{amount=5e-4}n2=n2+amount;if(n2<.08)n2=.08;else if(n2>.994)n2=.994;return n2}}function barSet(n2,speed){clearTimeout(_worker);if(n2<.08)n2=.08;else if(n2>1)n2=1;var bar=$('.bar[role="bar"]');bar.css({transition:"all "+speed+"ms linear","-webkit-transition":"all "+speed+"ms linear","-moz-transition":"all "+speed+"ms linear","-o-transition":"all "+speed+"ms linear"});if($("body").hasClass("rtl"))bar.css({"margin-right":-100+n2*100+"%"});else bar.css({"margin-left":-100+n2*100+"%"});if(n2==1){_worker=setTimeout(function(){$(".prog").animate({opacity:0},{duration:speed,complete:function(){$(".prog").remove()}})},speed)}}function getFormData(form){var unindexed_array=form.serializeArray();var indexed_array={};$.map(unindexed_array,function(n2,i2){if(n2["name"].includes("[]")){var key=n2["name"].split("[]")[0];if(!indexed_array.hasOwnProperty(key))indexed_array[key]=[];indexed_array[key].push(n2["value"])}else{indexed_array[n2["name"]]=n2["value"]}});return indexed_array}$(window).on("popstate",function(){if(history&&history.pushState)goToNode()});var getLocation=function(href){var l=document.createElement("a");l.href=href;return l};function getURLNodes(){appSettings.Base=appSettings.Base.replace(new RegExp("[/]+$"),"");var base=getLocation(appSettings.Base);if(base.origin!=window.location.origin){appSettings.Base=window.location.origin+base.pathname;var base=getLocation(appSettings.Base)}var _nodes=base.pathname!="/"?window.location.pathname.split(base.pathname).join("").replace(new RegExp("^[/]+"),"").split("/"):location.href.split(appSettings.Base).join("").replace(new RegExp("^[/]+"),"").split("?")[0].split("/");if(!_nodes[0])_nodes[0]=appSettings.defaultView??"home";if(historyStack[historyStack.length-1]?.url!=window.location.href)historyStack.push({"nodes":_nodes,"params":paramsToObj(window.location.href),"url":window.location.href});return _nodes}var prevNodes=[];function goToNode(d){if(_initialized){prevNodes=clone(nodes);nodes=getURLNodes();renderView(nodes[0],null,d)}else{setTimeout(function(){goToNode(d)},100)}}var View={};function setError(e,t2){if(!e){console.warn(t2);return}console.warn(t2,e.message)}function renderTpl(el2,n2,vars2){if(!el2.length)return;if(el2.data("_status")=="error")return;if(!el2.hasKey("_re")){if(el2.data("_status")=="pending"){getTpl(n2,el2,vars2)}setTimeout(function(){renderTpl(el2,n2,vars2)},_tickTime)}}function prepareNode(n2,rep){var _arr2=n2.split("/");if(_arr2.length>1){for(var i2=_arr2.length-1;i2>=_arr2.length-1;i2--)_arr2[i2]=_arr2[i2];n2=_arr2.join("/")}else n2=n2;return rep?n2.replace(new RegExp("^[/]+"),""):n2}var _esps={};var _Views={};function setAppFuncs(){let initFunc=appSettings.init&&typeof appSettings.init==="function"?appSettings.init:typeof init==="function"?init:null;if(typeof initFunc==="function")initFunc()}function getView(n2,el2,d){let filePath="src/views/"+n2+".view";let fileKey=btoa(filePath);if($("body").hasKey("view_"+fileKey)){renderView(n2,el2,d,true)}else{if(_vcData&&_vcData["views"].hasOwnProperty(fileKey)){$("body").data("view_"+fileKey,_vcData["views"][fileKey]);renderView(n2,el2,d,true);return}if(Nuke&&Nuke._ws&&Nuke._ws.readyState){Nuke.emit("getview",fileKey,function(e){var r2=e.data;$("body").data("view_"+fileKey,r2);renderView(n2,el2,d,true)})}else{setTimeout(()=>{getView(n2,el2,d)},_tickTime)}}}function fileToDataURL(file){var reader=new FileReader;return new Promise(function(resolve,reject){reader.onload=function(event){resolve(event.target.result)};reader.readAsDataURL(file)})}function readFilesAsDataURL(files){return Promise.all(files.map(fileToDataURL))}function defer(){var res,rej;var promise=new Promise((resolve,reject)=>{res=resolve;rej=reject});promise.resolve=res;promise.reject=rej;promise.success=res;promise.failed=rej;return promise}function getTpl(n2,el2,vaz2){let filePath="src/tpls/"+n2+".tpl";let fileKey=btoa(filePath);if(el2.data("_status")!="pending")return;el2.data("_status","getting");if($("body").hasKey("tpl_"+fileKey)){let r2=$("body").data("tpl_"+fileKey);el2.html(r2);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2)}else{if(_vcData&&_vcData["tpls"].hasOwnProperty(fileKey)){$("body").data("tpl_"+fileKey,_vcData["tpls"][fileKey]);el2.html(_vcData["tpls"][fileKey]);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2);return}if(Nuke&&Nuke._ws&&Nuke._ws.readyState){Nuke.emit("gettpl",fileKey,function(e){var r2=e.data;$("body").data("tpl_"+fileKey,r2);el2.html(r2);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2)})}else{setTimeout(()=>{getTpl(n2,el2,vaz2)},_tickTime)}}}function setRe(_el,vaz){try{if(!_el.hasKey("_vars")){if(_debugMode)cl("The Data Arrived",vaz);let data={};let vars=vaz.split(",");vars=vars.map(s=>s.trim());let binds=[];let dataNamesValues=[];var _subView=_el.closest("[view]");for(let x=0;x<vars.length;x++){if(vars[x]!=""){try{let varName=vars[x];let varValue=vars[x];let NameAs=null;if(varName.indexOf(" as ")!==-1){varName=varName.split(" as ");varValue=varName[0];varName=varName[1];NameAs=vars[x]}let val="";if(_subView.length){val=_subView.hasKey(varValue)?_subView.data(varValue):eval(varValue)}else val=eval(varValue);dataNamesValues.push({Name:varName,NameAs,Value:val})}catch(e){let varName2=vars[x];let varValue2=vars[x];let NameAs2=null;if(varName2.indexOf(" as ")!==-1){varName2=varName2.split(" as ");varValue2=varName2[0];varName2=varName2[1];NameAs2=vars[x]}dataNamesValues.push({Name:varName2,NameAs:NameAs2,Value:void 0});setError(e,"Error in bind variables for "+vars[x])}}}for(let x2=0;x2<dataNamesValues.length;x2++){let dn=dataNamesValues[x2];binds.push({dataName:dn["Name"],dataNameAs:dn["NameAs"],dataValue:clone(dn["Value"])});data[dn["Name"]]=dn["Value"]}if(_debugMode)cl(["The Data Set",data,binds]);if(appSettings.beforetick&&typeof appSettings.beforetick==="function")appSettings.beforetick();_el.data("_vars",binds).data("_re",new RenderEngine(_el,data));globalWatch()}_el.data("_status","complete");return true}catch(e){_el.data("_status","error");return false}return false}function parseFromString(html){return doc=new DOMParser().parseFromString(html,"text/html")}var _binds={};let _oldGlobals=clone(globals);let _oldRX=clone(_rx);let _watch=clone($("body").data("_watch"));$("body").data("_watch",{old:{},list:[]});function reloads(){$("[crslf].flickity-enabled.reload-on-bind").each(function(){var el2=$(this);el2.flickity("destroy");var opts=el2.attr("crslf-opts");if(!opts)opts={};else opts=JSON.parse(opts);el2.flickity(opts);var flkty=el2.data("flickity");flkty.on("dragStart",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="none"));flkty.on("dragEnd",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="all"))});$("[crsl].crsl-initialized").each(function(){$(this).crsl("refresh")});let tickFunc=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc==="function")tickFunc();if(typeof scsc!=="undefined")scsc.reset();if(typeof dgsc!=="undefined")dgsc.reset();applyTriggers();setTimeout(()=>{if(typeof scsc!=="undefined")scsc.reset();if(typeof dgsc!=="undefined")dgsc.reset();applyTriggers()},_tickTime*2)}function renderViewsTpls(){$("[view]").each(function(i){var el=$(this);if(el.data("_status")!="pending"&&el.data("_status")!="error"&&el.data("_status")!="getting"&&el.data("_status")!="complete"){var modal=el.closest("popup");var n=el.attr("view");var _props=el.attr(":props")??null;var _binds=el.attr(":props-bind")??null;el.data("_status","pending");let nn=n;var _arr=nn.split("/");if(_arr.length>1){for(var i=_arr.length-1;i>=_arr.length-1;i--){_arr[i]=_arr[i].toLowerCase()}nn=_arr.join("/")}else{nn=nn.toLowerCase()}var _queryParams=nn.split("?");nn=_queryParams.shift();if(el.attr(":data")){let vaz=el.attr(":data");let data={};let vars=vaz.split(",");let dataNamesValues=[];let binds=[];vars=vars.map(s=>s.trim());for(let x=0;x<vars.length;x++){if(vars[x]!=""){try{let varName=vars[x];let varValue=vars[x];let NameAs=null;if(varName.indexOf(" as ")!==-1){varName=varName.split(" as ");varValue=varName[0];varName=varName[1];NameAs=vars[x]}let val="";val=eval(varValue);dataNamesValues.push({Name:varName,NameAs,Value:val})}catch(e){cl(e);let varName2=vars[x];let varValue2=vars[x];let NameAs2=null;if(varName2.indexOf(" as ")!==-1){varName2=varName2.split(" as ");varValue2=varName2[0];varName2=varName2[1];NameAs2=vars[x]}dataNamesValues.push({Name:varName2,NameAs:NameAs2,Value:void 0});setError(e,"Error in bind variables for "+vars[x])}}}for(let x2=0;x2<dataNamesValues.length;x2++){let dn=dataNamesValues[x2];binds.push({dataName:dn["Name"],dataNameAs:dn["NameAs"],dataValue:clone(dn["Value"])});data[dn["Name"]]=dn["Value"]}el.data("props",data)}else{var _d=paraToObj(getBind(_binds,_props));el.data("params",paraToObj(_queryParams));if(modal.length)_d["modal"]=modal.data("props");el.data("props",_d)}if(n==""||!n||n.split("/").slice(-1)==""){el.data("_status","error")}else{renderView(n,el,_d)}}})}function renderPlugins(){$("[crslf]:not(.flickity-enabled,[comp],[tpl],[view]),[crslf][comp]:not(.flickity-enabled),[crslf][tpl]:not(.flickity-enabled),[crslf][view]:not(.flickity-enabled)").each(function(){if(typeof $.fn.flickity!=="function")return;var el2=$(this);if(el2.hasAttr("[tpl]")||el2.hasAttr("[comp]")||el2.hasAttr("[view]")){if(el2.data("_status")!="complete")return}var opts=el2.attr("crslf-opts");if(!opts)opts={};else opts=JSON.parse(opts);el2.flickity(opts);var flkty=el2.data("flickity");flkty.on("dragStart",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="none"));flkty.on("dragEnd",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="all"));setTimeout(function(){globalWatch()},600)});$("[crsl]:not(.crsl-initialized,[comp],[tpl],[view]),[crsl][comp]:not(.crsl-initialized),[crsl][tpl]:not(.crsl-initialized),[crsl][view]:not(.crsl-initialized)").each(function(){if(typeof $.fn.crsl!=="function")return;var el2=$(this);if(el2.hasAttr("[tpl]")||el2.hasAttr("[comp]")||el2.hasAttr("[view]")){if(el2.data("_status")!="complete")return}el2.crsl();el2.on("setPosition beforeChange",function(event,slick,currentSlide,nextSlide){$(window).trigger("scroll.scsc");$(window).trigger("resize")})});$("[up]:not([upid])").each(function(){var u=_ups.length;var t2=$(this);var mxf=t2.attr("data-mxf")?t2.attr("data-mxf"):10;if(!t2.hasAttr("upid")){var sl="up_"+u;t2.attr("upid",sl);t2.prepend(`<input `+(mxf>1?"multiple":"")+` type="file" files style="display:none;" />`);_ups.push(t2);if(typeof _upwrkStarted==="function")_upwrkStarted()}});$("form:not(.binded,[norm])").each(function(){var el2=$(this);var reset=false;if(el2.hasAttr("reset"))reset=true;var actn=el2.attr("action")??"";var local=false;el2.addClass("binded");if(actn==""){actn=getURLNodes().join("/");local=true}else local=isPathLocal(actn);if(el2.hasAttr("o-sub")){el2.ajaxForm({beforeSubmit:function(formData,f,options){let formDataMapped={};let formDataMappedAdditionals={};formDataMapped=Object.assign({},...formData.map(x2=>{if(x2.type=="file"){if(!formDataMappedAdditionals.hasOwnProperty(x2.name))formDataMappedAdditionals[x2.name]=[];formDataMappedAdditionals[x2.name].push(x2["value"]);return void 0}if(x2["name"].includes("[]")){var key=x2["name"].split("[]").join("");if(!formDataMappedAdditionals.hasOwnProperty(key))formDataMappedAdditionals[key]=[];formDataMappedAdditionals[key].push(x2["value"]);return void 0}return{[x2.name]:x2.value}}));formDataMapped={...formDataMapped,...formDataMappedAdditionals};if(f.hasAttr("b-sub")){var bfs=f.attr("b-sub");if(typeof window[bfs]==="function"){checkFormInputs(f);if(window[bfs](f,formDataMapped)===false)return false}}if(!checkFormInputs(f))return false;if(f.hasAttr("o-sub")){var ofs=f.attr("o-sub");if(typeof window[ofs]==="function"){window[ofs](f,formDataMapped)}}return false},clearForm:reset,resetForm:reset,success:function(responseText,statusText,xhr,f){},timeout:3e5,error:function(xhr,textStatus,errorThrown){}})}else{if(local){el2.ajaxForm({beforeSubmit:function(formData,f,options){if(!checkFormInputs(f))return false;let formDataMapped={};let formDataMappedAdditionals={};formDataMapped=Object.assign({},...formData.map(x2=>{if(x2.type=="file"){if(!formDataMappedAdditionals.hasOwnProperty(x2.name))formDataMappedAdditionals[x2.name]=[];formDataMappedAdditionals[x2.name].push(x2["value"]);return void 0}if(x2["name"].includes("[]")){var key=x2["name"].split("[]").join("");if(!formDataMappedAdditionals.hasOwnProperty(key))formDataMappedAdditionals[key]=[];formDataMappedAdditionals[key].push(x2["value"]);return void 0}return{[x2.name]:x2.value}}));formDataMapped={...formDataMapped,...formDataMappedAdditionals};try{if(f.hasAttr("b-sub")){var bfs=f.attr("b-sub");if(typeof window[bfs]==="function"){if(window[bfs](f,formDataMapped)===false)return false}}var actn2=f.attr("action")??"";if(actn2==""){actn2=getURLNodes().join("/")}if(validateInputs(f)){var d=getFormData(f);if(f.attr("method")?.toLowerCase()=="get"){actn2=addOrChangeParameters(actn2,d)}pushURL(actn2,d)}}catch(e){cl(e)}return false},clearForm:reset,resetForm:reset,success:function(responseText,statusText,xhr,f){},timeout:3e5,error:function(xhr,textStatus,errorThrown){}})}}});$("[editor]").each(function(i2){var editor=$(this);editor.removeAttr("editor");var TB=normalTB;if(editor.is("[mini]"))TB=miniTB;else if(editor.is("[full]"))TB=fullTB;if(typeof CKEDITOR!=="undefined"){CKEDITOR.replace(this,{uiColor:"#ffffff",language:$("html").attr("lang"),allowedContent:true,enterMode:CKEDITOR.ENTER_BR,toolbar:TB,on:{instanceReady:function(evt){var itemTemplate='<li class="l" data-id="{id}"><div><strong class="item-title">{name}</strong></div><div><i>{description}</i></div></li>',outputTemplate="<span class=hash>{linked}</span> ";var autocomplete=new CKEDITOR.plugins.autocomplete(evt.editor,{textTestCallback:function(range){if(!range.collapsed){return null}return CKEDITOR.plugins.textMatch.match(range,function(text,offset){var left=text.slice(0,offset);var matchHash=left.match(/#\d*$/);var matchAt=left.match(/(@)[A-Za-z]+(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9.]+[A-Za-z0-9]{6,30}$/);if((!matchHash||matchHash=="#")&&(!matchAt||matchAt=="@")){return null}var match=matchHash;if(!match)match=matchAt;return{start:match.index,end:offset}})},dataCallback:function(matchInfo,callback){var query=matchInfo.query;if(myR["[ck]"])myR["[ck]"].abort();clearTimeout(debounceTimeout["[ck]"]);debounceTimeout["[ck]"]=setTimeout(function(){myR["[ck]"]=$.post(beas+"a/hashes/get",{id:query},function(result){if(result){result=$.parseJSON(result);var suggestions=result.filter(function(item){return String(item.name).indexOf(query.substring(1))==0});callback(suggestions)}})},500)},itemTemplate,outputTemplate,throttle:100});autocomplete.getHtmlToInsert=function(item){return this.outputTemplate.output(item)}},change:function(ev){if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty");editor.val(ev.editor.getData()).trigger("change")},focus:function(ev){editor.closest(".fields").addClass("focused");if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty")},blur:function(ev){editor.closest(".fields").removeClass("focused");if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty")}}})}});$(".cke_autocomplete_panel").each(function(){if($(this).html()=="")$(this).remove()});$("[tags]:not(.tag-editor-hidden-src)").each(function(){if(typeof $.fn.tagEditor!=="function")return;var t2=$(this);var u=currentlyValidTags.length;t2.attr("data-u",u);var del=t2.attr("dl")?t2.attr("dl"):", ";var maxTags=t2.attr("mt")?t2.attr("mt"):50;var maxLength=t2.attr("ml")?t2.attr("ml"):100;var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var tagslower=t2.attr("tags-lower")?true:false;var autocomplete=t2.attr("acs")?{delay:250,autoFocus:true,position:{collision:"flip"},source:function(request,response){$.post(beas+"a"+t2.attr("acs"),request,response)},minLength:1,select:function(event,ui){if(ui.item==null){t2.val("")}},change:function(event,ui){if(ui.item==null){t2.val("")}}}:null;t2.tagEditor({autocomplete,delimiter:del,removeDuplicates:true,forceLowercase:tagslower,placeholder:plchldr,animateDelete:50,maxLength,maxTags,onChange:function(field,editor,tags){field.trigger("change")},beforeTagSave:function(field,editor,tags,tag,val2){if(!t2.attr("sts")){if($.inArrayIn(val2,tags)!==-1){return false}}else{if($.inArray(tag,currentlyValidTags[u][tags])==-1){return false}}if(t2.attr("tags-before")){var bfs=t2.attr("tags-before");if(typeof window[bfs]==="function"){if(window[bfs](t2,field,editor,tags,tag,val2)===false)return false}}}});currentlyValidTags.push(t2)});$("[slct]:not(.select2-hidden-accessible)").each(function(){if(typeof $.fn.select2!=="function")return;var t2=$(this);var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var dropdownParent=t2.attr("prnt")?t2.attr("prnt"):"body";var tpl=t2.attr("slct-tpl")?t2.attr("slct-tpl"):null;var dir=t2.attr("slct-dir")?t2.attr("slct-dir"):"ltr";var minResultsForSearch=t2.attr("mins")?t2.attr("mins"):"";if(dropdownParent=="self")dropdownParent=t2.parent();else dropdownParent=$(dropdownParent);var allowNewTags=t2.attr("ntgs")?true:false;var ax=t2.attr("axs")?{url:t2.attr("axs"),dataType:"json",delay:250}:null;t2.select2({dropdownParent,placeholder:plchldr,dir,allowClear:false,tags:allowNewTags,ajax:ax,minimumResultsForSearch:minResultsForSearch,templateSelection:function(data2,container){if(data2.newTag){if(allowNewTags&&t2.attr("ntgs")!="true"){var tag=data2.text;var id=data2.id;$.post(beas+"a"+t2.attr("ntgs"),{tag},function(r2){if(r2=="true"){var newOption=new Option(tag,id,true,true);t2.append(newOption).trigger("change")}else{alert("Error adding tag! Please Try again.");t2.val(null).trigger("change")}});return data2.text}else{return data2.text}}else{return data2.text}},templateResult:function(state){if(tpl){if(typeof window[tpl]==="function")return window[tpl](state)}if(state.newTag){if(allowNewTags&&t2.attr("ntgs")!="true"){var new_state=$("<span>+ Add <b>"+state.text+"</b></span>");return new_state}return state.text}else return state.text},tokenSeparators:[","],createTag:function(params){var term=$.trim(params.term);if(term===""){return null}return{id:term,text:term,newTag:true}},insertTag:function(data2,tag){data2.push(tag)}});if(t2.attr("nosearch"))t2.on("select2:opening select2:closing",function(event){var searchfield=$(this).parent().find(".select2-search__field");searchfield.prop("disabled",true)})});$("[sl]:not(.select2-hidden-accessible)").each(function(){if(typeof $.fn.select2!=="function")return;var t2=$(this);try{var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var dir=$("body").hasClass("rtl")?"rtl":"ltr";var nr=t2.attr("sl-nrmsg")?t2.attr("sl-nrmsg"):"No results found";var minResultsForSearch=t2.attr("sl-mins")?t2.attr("sl-mins"):10;var allowNewTags=t2.attr("sl-ntgs")?true:false;var dropdownParent=t2.attr("sl-prt")?t2.attr("sl-prt"):"body";if(dropdownParent=="self")dropdownParent=t2.parent();else dropdownParent=$(dropdownParent);var query=t2.attr("sl-query")?t2.attr("sl-query"):null;var uniquer=Date.now();if(typeof window[query]==="function"){let dbcrID="dbcr_"+(Object.keys(_dbcrs).length+1);t2.select2.amd.define("adapt_"+uniquer,["select2/data/array","select2/utils"],function(ArrayAdapter,Utils){function CustomDataAdapter($element,options){CustomDataAdapter.__super__.constructor.call(this,$element,options)}Utils.Extend(CustomDataAdapter,ArrayAdapter);CustomDataAdapter.prototype.query=function(params,callback){clearTimeout(_dbcrs[dbcrID]);let _t=t2;_dbcrs[dbcrID]=setTimeout(function(){window[query](params,callback,_t)},!_dbcrs.hasOwnProperty(dbcrID)?0:_dbcrsTime)};return CustomDataAdapter});t2.select2({dropdownParent,minimumResultsForSearch:minResultsForSearch,placeholder:plchldr,dir,tags:allowNewTags,allowClear:false,language:{noResults:function(){return nr}},...t2.select2.amd.require("adapt_"+uniquer)?{ajax:{},dataAdapter:t2.select2.amd.require("adapt_"+uniquer)}:{}})}else{t2.select2({dropdownParent,minimumResultsForSearch:minResultsForSearch,placeholder:plchldr,dir,tags:allowNewTags,allowClear:false,language:{noResults:function(){return nr}}})}if(t2.attr("sl-nosrch"))t2.on("select2:opening select2:closing",function(event){var searchfield=$(this).parent().find(".select2-search__field");searchfield.prop("disabled",true)});if(t2.attr("sl-class")){t2.on("select2:opening",function(event){dropdownParent.addClass(t2.attr("sl-class"))});t2.on("select2:closing",function(event){dropdownParent.removeClass(t2.attr("sl-class"))})}}catch(e){cl(e)}});$("[pinnable]:not(.pinnable)").each(function(){if(typeof Headroom==="undefined")return;var t2=$(this);var offsetU=t2.attr("pinnable-offset-up")??100;var offsetD=t2.attr("pinnable-offset-down")??50;var options={offset:0,offset:{up:offsetU,down:offsetD},tolerance:0,tolerance:{up:5,down:0},classes:{initial:"pinnable",pinned:"pinnable--pinned",unpinned:"pinnable--unpinned",top:"pinnable--top",notTop:"pinnable--not-top",bottom:"pinnable--bottom",notBottom:"pinnable--not-bottom",frozen:"pinnable--frozen",pinned:"pinnable--pinned"},onPin:function(){},onUnpin:function(){},onTop:function(){},onNotTop:function(){},onBottom:function(){},onNotBottom:function(){}};var pinnable=new Headroom(t2[0],options);pinnable.init()});$("[sort]").each(function(e){if(typeof $.fn.sortable!=="function")return;let t2=$(this);if(t2.hasClass("ui-sortable"))return;let opts={delay:50,placeholder:"g_rows_helper",scrollSpeed:40,opacity:1};opts=avc(t2,"sort-axis",opts);opts=avc(t2,"sort-handle",opts);opts=avc(t2,"sort-cancel",opts);opts=avc(t2,"sort-cursor",opts,"grabbing");opts=avc(t2,"sort-helper",opts,"clone");if(opts.hasOwnProperty("helper")&&opts["helper"]!="clone"){if(typeof window[opts["helper"]]==="function")opts["helper"]=window[opts["helper"]]}opts=avc(t2,"sort-placeholder",opts);opts=avc(t2,"sort-opacity",opts);opts=avc(t2,"sort-items",opts);opts=avc(t2,"sort-tolerance",opts,"pointer");opts=avc(t2,"sort-revert",opts,false);opts=avc(t2,"sort-forcePlaceholderSize",opts);opts=avc(t2,"sort-containment",opts,"parent");opts=avc(t2,"sort-connectWith",opts);if(opts.hasOwnProperty("forceplaceholdersize")){opts["forcePlaceholderSize"]=opts["forceplaceholdersize"];delete opts["forceplaceholdersize"]}t2.sortable(opts)});$("[drag]").each(function(e){if(typeof $.fn.draggable!=="function")return;let t2=$(this);let opts={};opts=avc(t2,"drag-connectToSortable",opts);opts=avc(t2,"drag-scroll",opts,true);opts=avc(t2,"drag-revert",opts,true);opts=avc(t2,"drag-helper",opts,"clone");opts=avc(t2,"drag-containment",opts,false);opts=avc(t2,"drag-cursor",opts,"auto");opts=avc(t2,"drag-appendTo",opts,"parent");opts=avc(t2,"drag-disabled",opts,false);if(opts.disabled=="false")delete opts.disabled;if(opts.hasOwnProperty("appendto")){opts.appendTo=opts["appendto"];delete opts["appendto"]}if(opts.hasOwnProperty("helper")&&opts["helper"]!="clone"){if(typeof window[opts["helper"]]==="function")opts["helper"]=window[opts["helper"]]}if(opts.hasOwnProperty("connecttosortable")){opts["connectToSortable"]=opts["connecttosortable"];delete opts["connecttosortable"]}t2.draggable(opts)});$("[drop]").each(function(e){if(typeof $.fn.droppable!=="function")return;let t2=$(this);let opts={};opts=avc(t2,"drop-accept",opts);opts=avc(t2,"drop-greedy",opts);opts=avc(t2,"drop-hoverClass",opts);opts=avc(t2,"drop-disabled",opts,false);if(opts.disabled=="false")delete opts.disabled;if(opts.hasOwnProperty("hoverclass")){opts.hoverClass=opts["hoverclass"];delete opts["hoverclass"]}t2.droppable(opts)});$("body").on("touchstart mouseover",function(e){let isTippedOe=true;if($(e.target).closest(".oe").length){let oe=$(e.target).closest(".oe");if((oe.find("[tip]").length||oe.hasAttr("tip"))&&oe.isOverflown()&&$(window).width()>480){isTippedOe=true}else isTippedOe=false}if($(e.target).closest("[tip]").length&&isTippedOe){var target=$(e.target).closest("[tip]");var tip=`<tip class="pa ${target.attr("tip-class")}"><div class="pa [[P]]"><span>[[T]]</span></div></tip>`;if(target.find("droplet").length==0){var t2=target.attr("tip");var p=target.attr("tip-pos");if(!p)p="";$("tip").remove();$("body").append(tip.replace("[[T]]",t2).replace("[[P]]",p));_isTipped=true;let _tipSc=target;while(true){if(_isScrollable(_tipSc)||_tipSc[0]==$("body")[0])break;_tipSc=_tipSc.parent()}var self=target;_setPos(self,p,_tipSc);_setPos(self,p,_tipSc);target.data("_tipSc",_tipSc);_tipSc.unbind("scroll.kuku").bind("scroll.kuku",function(){_setPos(self,p,_tipSc)})}else{$("tip").remove();_isTipped=false}}else{$("body").unbind("scroll.kuku");$("tip").remove();_isTipped=false}});$("[numeric]").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("numeric").numeric()});$("[pattern]").each(function(){$(this).data("pattern",$(this).attr("pattern")).removeAttr("pattern")});$("[integer]:not([pve])").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("integer").numeric({decimal:false})});$("[integer][pve]").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("integer").numeric({decimal:false,negative:false})});$("[decimal]:not([pve])").each(function(){if(typeof $.fn.numeric!=="function")return;var places=-1;if($(this).is("[dp0]"))places=0;else if($(this).is("[dp1]"))places=1;else if($(this).is("[dp2]"))places=2;else if($(this).is("[dp3]"))places=3;else if($(this).is("[dp4]"))places=4;if(places>=0)$(this).removeAttr("decimal").numeric({decimalPlaces:places,decimal:places==0?false:"."});else $(this).removeAttr("decimal").numeric({})});$("[decimal][pve]").each(function(){if(typeof $.fn.numeric!=="function")return;var places=-1;if($(this).is("[dp0]"))places=0;else if($(this).is("[dp1]"))places=1;else if($(this).is("[dp2]"))places=2;else if($(this).is("[dp3]"))places=3;else if($(this).is("[dp4]"))places=4;if(places>=0)$(this).removeAttr("decimal").numeric({negative:false,decimalPlaces:places,decimal:places==0?false:"."});else $(this).removeAttr("decimal").numeric({negative:false})});$("[time]").each(function(){dtp($(this),"time")});$("[date]").each(function(){dtp($(this),"date")});$("[datetime]").each(function(){dtp($(this),"datetime")});$("[color]").each(function(){if(typeof $.fn.colorpicker!=="function")return;$(this).removeAttr("color").colorpicker({format:"rgba"})});$("lmlst:not(.binded)").each(function(){var el=$(this);el.addClass("binded");let _conf=el.attr(":config");let conf=null;if(_conf){try{conf=typeof _evalEventScopedExpr==="function"?_evalEventScopedExpr(el[0]._ownerRe,_conf):eval(_conf)}catch(x2){conf=null}}el[0].list=new __myList(el,conf||{})})}function dtp(el2,t2){el2.removeAttr(t2);let opts={format:t2=="date"?"yyyy-mm-dd":t2=="time"?"hh:ii":"yyyy-mm-dd hh:ii",weekStart:el2.attr("date-week-start")??1,startView:t2=="time"?1:2,minView:el2.attr("minview")?el2.attr("minview"):t2=="time"?0:t2=="datetime"?0:2,maxView:el2.attr("maxview")?el2.attr("maxview"):t2=="time"?1:4,todayBtn:t2=="time"?0:el2.attr("date-today")=="false"?0:1,todayHighlight:t2=="time"?0:el2.attr("date-today")=="false"?0:1,language:el2.attr("date-lang")??"en",minuteStep:el2.attr("date-minute-step")??5,pickerPosition:"top-right",autoclose:1,showMeridian:false};if(el2.attr("date-start"))opts["startDate"]=el2.attr("date-start");if(el2.attr("date-end"))opts["endDate"]=el2.attr("date-end");if(el2.attr("date-value"))opts["date"]=el2.attr("date-value");el2.datetimepicker(opts);if(t2=="time"){el2.on("show",function(ev){$(".table-condensed > thead, .table-condensed > thead > tr > th, .table-condensed > thead > tr > th > i").attr("style","visibility: hidden; font-size:0px !Important; overflow: hidden; height: 0px;")}).on("hide",function(ev){$(".table-condensed > thead, .table-condensed > thead > tr > th, .table-condensed > thead > tr > th > i").attr("style","visibility: visible;")})}if(el2.attr("date-link-start")){el2.on("change",function(e){let dp1=el2.data("datetimepicker");let dp2=$(el2.attr("date-link-start")).data("datetimepicker");dp2.setStartDate(dp1.getFormattedDate());if(dp2.getFormattedDate()<dp1.getFormattedDate()||dp2.getFormattedDate()=="")$(el2.attr("date-link-start")).val(dp1.getFormattedDate())})}else if(el2.attr("date-link-end")){el2.on("change",function(e){let dp1=$(el2.attr("date-link-end")).data("datetimepicker");let dp2=el2.data("datetimepicker");dp1.setEndDate(dp2.getFormattedDate())});opts["useCurrent"]=false}}function avc(t2,n2,o,d=null){if(t2.attr(n2.toLowerCase()))o[n2.toLowerCase().split("sort-").join("").split("drop-").join("").split("drag-").join("")]=t2.attr(n2.toLowerCase());else if(d!=null)o[n2.toLowerCase().split("sort-").join("").split("drop-").join("").split("drag-").join("")]=d;return o}var _lmAtIndex=new Map;function _lmIndexAtEl(el2,name){var set=_lmAtIndex.get(name);if(!set){set=new Set;_lmAtIndex.set(name,set)}set.add(el2);if(set.size>5e3)set.forEach(function(e){if(!e.isConnected)set.delete(e)})}function _findByAtAttrNames(names){var out=[];var seen=new Set;for(var j=0;j<names.length;j++){var set=_lmAtIndex.get(names[j]);if(!set)continue;set.forEach(function(el2){if(seen.has(el2)||!el2.isConnected)return;if(el2.events&&el2.events[names[j]]!=null){seen.add(el2);out.push(el2)}})}try{var sel=names.map(function(n2){return"[\\"+n2+"]"}).join(",");var raw=document.querySelectorAll(sel);for(var i2=0;i2<raw.length;i2++)if(!seen.has(raw[i2])){seen.add(raw[i2]);out.push(raw[i2])}}catch(e){}return out}function _installScrollStartEndSynthesis(el2){if(el2._lumenScrollSynthInstalled)return;el2._lumenScrollSynthInstalled=true;var scrolling=false;var settleTimer=null;el2.addEventListener("scroll",function(){if(!scrolling){scrolling=true;el2.dispatchEvent(new Event("scrollstart"))}clearTimeout(settleTimer);settleTimer=setTimeout(function(){scrolling=false;el2.dispatchEvent(new Event("scrollend"))},150)},{passive:true})}function applyTriggers(){$("[click]").each(function(){$(this).trigger("click").removeAttr("click")});$("[focus]").each(function(){$(this).trigger("focus").removeAttr("focus")});let _Ns=[];for(let x2=9;x2>=0;x2--){let _els=$("[n"+x2+"]");_els.each(function(){let _el2=$(this);let _d2={};for(let y=9;y>=0;y--){if(_el2.hasAttr("n"+y)){_d2["n"+y]=_el2.attr("n"+y).split(",")}}_el2.data("_Ns",_d2);_Ns.push(_el2)})}for(let i2=0;i2<_Ns.length;i2++){const _n=_Ns[i2];let _act=[];let attrs=_n.data("_Ns");for(const nK in attrs){if(Object.hasOwnProperty.call(attrs,nK)){const nV=attrs[nK];let index=nK.slice(1);if(nV.indexOf(nodes[index])!=-1){_act.push(true)}else{_act.push(false);break}}}setTimeout(()=>{if(_act.indexOf(false)!=-1)_n.removeClass("active");else _n.addClass("active")})}if(typeof viewLoaded==="function"&&!_viewLoaded){_viewLoaded=true;viewLoaded()}var _scrollAttrEls=_findByAtAttrNames(["@scroll","@scroll-start","@scroll-end","@scroll-left","@scroll-right","@scroll-top","@scroll-bottom"]);for(var _sei=0;_sei<_scrollAttrEls.length;_sei++){_installScrollStartEndSynthesis(_scrollAttrEls[_sei])}$(_scrollAttrEls).unbind("scroll touchmove scrollstart scrollend").on("scroll touchmove scrollstart scrollend",function(ev){let el2=$(this);if(ev.type=="scrollend"){var newScrollLeft=el2.scrollLeft(),newScrollTop=el2.scrollTop(),width=el2.width(),scrollWidth=el2.get(0).scrollWidth,scrollHeight=el2.get(0).scrollHeight;var hasScX=el2.prop("scrollWidth")>el2.width();var hasScY=el2.prop("scrollHeight")>el2.height();if(newScrollLeft==0){processEv(ev,el2,"scroll-left")}else if(Math.round(scrollWidth-newScrollLeft-width-(hasScY?-_scW:0))==0){processEv(ev,el2,"scroll-right")}if(newScrollTop==0){processEv(ev,el2,"scroll-top")}else if(newScrollTop+el2.innerHeight()>=scrollHeight-(hasScX?-_scW:0)){processEv(ev,el2,"scroll-bottom")}}processEv(ev,el2,ev.type.length==6?"scroll":ev.type.split("scroll").join("scroll-"))})}_viewLoaded=false;function globalWatch(){if(!_initialized)return;$('[beajs="1"]').remove();$('script[type="beajs"]').each(function(){var html=$(this).html();$(this).remove();var myScript=document.createElement("script");myScript.setAttribute("beajs","1");myScript.textContent=html;document.body.appendChild(myScript)});let bindsCount=0;let prom=defer();prom.then(function(val2){renderPlugins();loadPics();reloads();let tickFunc2=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc2==="function")tickFunc2()}).catch(reason=>{renderPlugins();loadPics();reloads();let tickFunc2=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc2==="function")tickFunc2()});if(bindsCount==0){prom.resolve()}reloads();let tickFunc=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc==="function")tickFunc()}function loadPics(){$("[lazy]").each(function(){if(typeof $.fn.lazy!=="function")return;let _el2=$(this);_el2.lazy({effect:"show",bind:"event",threshold:200,visibleOnly:false,beforeLoad:function(element){_el2.removeAttr("lazy")},afterLoad:function(element){},onError:function(element){cl("error loading "+_el2.attr("data-src"))},onFinishedAll:function(){}})})}function paraToObj(para){if(para=="")return JSON.parse("{}");return JSON.parse('{"'+decodeURI(para).replace(/"/g,'\\"').replace(/&/g,'","').replace(/=/g,'":"')+'"}')}function getBind(b,d){d=d?d.split("&"):new Array;if(b){var binder=b.split(",");for(var x2=0;x2<binder.length;x2++){var finder=binder[x2].split(" as ");if(finder[0].indexOf(" attr ")!==-1){var findz=finder[0].split(" attr ");d.push(finder[1]+"="+$.trim($(findz[0]).attr(findz[1])))}else if(finder[0].indexOf(" find ")!==-1){var findz=finder[0].split(" find ");var val2=getVal($(findz[0]).find(findz[1]));d.push(finder[1]+"="+$.trim(val2))}else if(finder[0].indexOf(" from ")!==-1){var findz=finder[0].split(" from ");if(findz[1].toLowerCase()=="ls"){d.push(finder[1]+"="+localStorage.getItem(findz[0]))}else{d.push(finder[1]+"="+findz[0])}}else d.push(finder[1]+"="+getVal($(finder[0])))}}d=d.join("&");return d}function isPathLocal(path){var local=false;var l=getLocation(path);var l2=getLocation(appSettings.Base);var url="home";local=l.hostname==l2.hostname;return local}function checkFormInputs(f,inp,classesOnly){var inputs=inp?[inp]:f.find("[\\:required]:not([disabled])");for(var i2=0;i2<inputs.length;i2++){let el2=$(inputs[i2]);let pat=el2.data("pattern");let req=el2.hasAttr(":required");let lbl=el2.closest("label");let fs=el2.closest("fieldset");let max=el2.attr("max");let max_num=el2.attr("max-num");let min_num=el2.attr("min-num");let v=el2.val();var or=el2.attr("or");if(or!=""){var or=f.find("[name='"+or+"']")}var into;let allCls="is-not-checked is-checked is-valid is-not-empty is-empty is-invalid error success not-4-chars not-on-pattern";el2.removeClass(allCls);el2.parent().removeClass(allCls);if(lbl.length)lbl.removeClass(allCls);if(fs.length)fs.removeClass(allCls);if(el2.is(":checkbox")||el2.is(":radio")){var isCheck="is-not-checked"+(req?" is-invalid":"");if(el2.is(":checked")){isCheck="is-checked"+(req?" is-valid":"")}else{if(or.length){if(or.is(":checked")){isCheck="is-checked"+(req?" is-valid":"")}}}if(el2.is(":radio")){f.find("[name='"+el2.attr("Name")+"']:radio").not(el2[0]).each(function(){let _el2=$(this);let _req=_el2.hasAttr(":required");var _isCheck="is-not-checked"+(_req?" is-invalid":"");var _or=_el2.attr("or");let _lbl=_el2.closest("label");_el2.removeClass(allCls);_el2.parent().removeClass(allCls);if(_lbl.length)_lbl.removeClass(allCls);if(_or!=""){var _or=f.find("[name='"+_or+"']")}if(_el2.is(":checked")){_isCheck="is-checked"+(_req?" is-valid":"")}else{if(_or.length){if(_or.is(":checked")){_isCheck="is-checked"+(_req?" is-valid":"")}}}if(_el2.parent().prop("nodeName")!="FORM")_el2.parent().addClass(_isCheck);if(_lbl.length)_lbl.addClass(_isCheck);_el2.addClass(_isCheck)})}if(el2.parent().prop("nodeName")!="FORM")el2.parent().addClass(isCheck);if(lbl.length)lbl.addClass(isCheck);el2.addClass(isCheck)}else{var isV="is-empty"+(req?" is-invalid":"");if(el2.is("[username]")){if(v.length&&v.length<4){isV="not-4-chars is-not-empty"+(req?" is-invalid":"")}else{let vld=true;var k=v.match(/[a-z]+(?!\.)(?!.*\.$)(?!.*?\_\_)[a-z0-9_]+[a-z0-9]/);if(!k){vld=false}else{if(k.input!=k[0]){vld=false}}if(vld)isV="is-not-empty"+(req?" is-valid":"");else isV="not-on-pattern is-not-empty"+(req?" is-invalid":"")}}else if(el2.is("[password]")){if(!passwordValid(v)){isV="is-not-empty"+(req?" is-invalid":"")}else{isV="is-not-empty"+(req?" is-valid":"")}}else if(el2.is("[rpassword]")){if($.trim(v)!=$.trim(f.find("[password]").val())){isV="is-not-empty"+(req?" is-invalid":"")}else{isV="is-not-empty"+(req?" is-valid":"")}}else{if($.trim(v).length!=0){if(max&&!isNaN(max)){if($.trim(v).length>max){el2.val($.trim($.trim(v).substr(0,max)))}}if(min_num&&!isNaN(min_num)){if(!isNaN($.trim(v))){if(parseFloat($.trim(v))<parseFloat(min_num))el2.val($.trim(min_num))}else{el2.val(min_num)}}if(max_num&&!isNaN(max_num)){if(!isNaN($.trim(v))){if(parseFloat($.trim(v))>parseFloat(max_num))el2.val($.trim(max_num))}else{if(min_num&&!isNaN(min_num))el2.val($.trim(min_num));else el2.val("0")}}isV="is-not-empty";if(pat){pat=new RegExp(pat);if(pat.test($.trim(v))){isV+=req?" is-valid":""}else{isV+=req?" is-invalid":"";el2.val("")}}else isV+=req?" is-valid":""}else{if(or.length){if($.trim(or.val()).length!=0){isV="is-not-empty"+(req?" is-valid":"")}}}}if(el2.parent().prop("nodeName")!="FORM")el2.parent().addClass(isV);if(lbl.length)lbl.addClass(isV);el2.addClass(isV)}var isRadioChecked=false;if(el2.is(":radio")){if(el2.hasClass("is-invalid")){f.find("[name='"+el2.attr("Name")+"']:radio").not(el2[0]).each(function(){if($(this).hasClass("is-valid")){isRadioChecked=true}})}else{isRadioChecked=true}}if(el2.hasClass("is-invalid")||el2.is(":radio")&&!isRadioChecked){if(el2.hasAttr("data-into")){let intoTxt=el2.data("into");if(lbl.length)into=lbl.find(intoTxt);if(!into){if(fs.length)into=fs.find(intoTxt)}if(!into)into=$(intoTxt);if(into.length){if(el2.is("[password]")){if($.trim(v).length==0)into.text(el2.attr("data-empty"));else if(el2.hasAttr("data-wpm"))into.text(el2.attr("data-wpm"));let rpass=f.find("[rpassword]");if(rpass.length){if($.trim(rpass.val()).length!=0)checkFormInputs(f,rpass,true)}}else if(el2.is("[rpassword]")){if($.trim(v).length==0)into.text(el2.attr("data-empty"));else if(el2.hasAttr("data-pnm"))into.text(el2.attr("data-pnm"))}else if(el2.is("[username]")){let txt=el2.hasAttr("data-empty")?el2.attr("data-empty"):el2.attr("placeholder");if($.trim(v).length==0)into.text(txt);else{if(el2.hasClass("not-4-chars")){if(el2.hasAttr("data-4-chars"))txt=el2.attr("data-4-chars")}else if(el2.hasClass("not-on-pattern")){if(el2.hasAttr("data-chars-not-allowed"))txt=el2.attr("data-chars-not-allowed")}into.text(txt)}}else if(el2.hasAttr("data-empty")){into.text(el2.attr("data-empty"))}else{if(el2.is(":checkbox")||el2.is(":radio")){into.text(el2.attr("placeholder"))}else{into.text(el2.attr("placeholder"))}}}}if(!classesOnly){if(el2.is(":radio")){if(!isRadioChecked){if(fs.length)fs.addClass(isCheck);el2.focus();return false}}else{if(fs.length)fs.addClass(isV);el2.focus();return false}}else{if(el2.is(":radio")){if(!isRadioChecked){if(fs.length)fs.addClass(isCheck)}}else{if(fs.length)fs.addClass(isV)}}}else if(el2.hasClass("is-valid")){if(el2.hasAttr("data-into")){let intoTxt=el2.data("into");if(lbl.length)into=lbl.find(intoTxt);if(fs.length)into=fs.find(intoTxt);if(!into)into=$(intoTxt);if(into.length){into.text("")}}}}return true}function validateInputs(f){if(f.hasAttr("ax-before")){var bfs=f.attr("ax-before");if(typeof window[bfs]==="function"){if(window[bfs](f)===false)return false}}var inps=[];f.find("input.required,select.required,textarea.required").each(function(){inps.push($(this).attr("name"))});for(var i2=0;i2<inps.length;i2++){var inp=f.find("input[name='"+inps[i2]+"']");var sel=f.find('select[name="'+inps[i2]+'"]');var txt=f.find('textarea[name="'+inps[i2]+'"]');var e=inp;if(!e.length)e=sel;if(!e.length)e=txt;var or=e.attr("or");if(or!=""){var inp2=f.find("input[name='"+or+"']");var sel2=f.find('select[name="'+or+'"]');var txt2=f.find('textarea[name="'+or+'"]');var or=inp2;if(!or.length)or=sel2;if(!or.length)or=txt2}if(e.is(":checkbox")||e.is(":radio")){if(!e.is(":checked")){if(or.length){if(!or.is(":checked")){alert(e.attr("placeholder")+" or "+or.attr("placeholder"));e.addClass("error");e.focus();return false}}else{alert(e.attr("placeholder"));e.addClass("error");e.focus();return false}}}else{if($.trim(e.val()).length==0){if(or.length){if($.trim(or.val()).length==0){alert(e.attr("placeholder")+" or "+or.attr("placeholder"));e.addClass("error");e.focus();return false}}else{alert(e.attr("placeholder"));e.addClass("error");e.focus();return false}}if(e.is("[password]")){if(!passwordValid(e.val())){alert(e.attr("data-wpm"));e.addClass("error");e.focus();return false}}if(e.is("[rpassword]")){if($.trim(e.val())!=$.trim(e.closest("form").find("[password]").val())){e.addClass("error");alert(e.attr("data-pnm"));e.focus();return false}e.removeClass("error");$(".passStrength").remove()}}}return true}let _cookies={getItem:function(sKey){if(!sKey){return null}return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(sKey,sValue,vEnd,sPath,sDomain,bSecure){if(!sKey||/^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)){return false}var sExpires="";if(vEnd){switch(vEnd.constructor){case Number:sExpires=vEnd===Infinity?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+vEnd;break;case String:sExpires="; expires="+vEnd;break;case Date:sExpires="; expires="+vEnd.toUTCString();break}}if(!sPath)sPath="/";document.cookie=encodeURIComponent(sKey)+"="+encodeURIComponent(sValue)+sExpires+(sDomain?"; domain="+sDomain:"")+(sPath?"; path="+sPath:"")+(bSecure?"; secure":"");return true},removeItem:function(sKey,sPath,sDomain){if(!this.hasItem(sKey)){return false}if(!sPath)sPath="/";document.cookie=encodeURIComponent(sKey)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(sDomain?"; domain="+sDomain:"")+"; path="+sPath;return true},hasItem:function(sKey){if(!sKey){return false}return new RegExp("(?:^|;\\s*)"+encodeURIComponent(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){var aKeys=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/);for(var nLen=aKeys.length,nIdx=0;nIdx<nLen;nIdx++){aKeys[nIdx]=decodeURIComponent(aKeys[nIdx])}return aKeys}};var cookies=new Proxy(_cookies,{get(target,key){return target[key]??target.getItem(key)??void 0},set(target,key,value){if(key in target){return false}return target.setItem(key,value)},deleteProperty(target,key){if(!(key in target)){return false}return target.removeItem(key)},ownKeys(target){return target.keys()},has(target,key){return key in target||target.hasItem(key)},defineProperty(target,key,descriptor){if(descriptor&&"value"in descriptor){target.setItem(key,descriptor.value)}return target},getOwnPropertyDescriptor(target,key){const value=target.getItem(key);return value?{value,enumerable:true,configurable:true}:void 0}});function getCookie(n2){return cookies[n2]}function setCookie(n2,v,d,p,e){var now=new Date;var time=now.getTime();if(!e)e=time+24*60*60*1e3*365;else e=time+e;if(!d)d=window.location.hostname;if(!p)p="/";now.setTime(e);return cookies.setItem(n2,v,now.toGMTString(),p,d,true)}function getComData(c,fromHTML){if(fromHTML){try{var el2=$("<div></div>");el2.html(c.html());var k={};var mtitle=$("modal-title",el2).html();if(!mtitle)mtitle="";var mbody=$("modal-body",el2).html();if(!mbody)mbody="";var mdesc=$("modal-description",el2).html();if(!mdesc)mdesc="";var mfoot=$("modal-footer",el2).html();if(!mfoot)mfoot="";k.Title=mtitle;k.Body=mbody;k.Description=mdesc;k.Footer=mfoot;c=k;return c}catch(e){return false}return false}try{c=c.contents().filter(function(){return this.nodeType===8}).get(0);if(c.nodeValue=="")return false;try{c=JSON.parse(c.nodeValue)}catch(e){try{c=JSON.parse(atob(c.nodeValue))}catch(e2){try{var el2=$("<div></div>");el2.html(c.nodeValue);var k={};var mtitle=$("modal-title",el2).html();if(!mtitle)mtitle="";var mbody=$("modal-body",el2).html();if(!mbody)mbody="";var mdesc=$("modal-description",el2).html();if(!mdesc)mdesc="";var mfoot=$("modal-footer",el2).html();if(!mfoot)mfoot="";k.Title=mtitle;k.Body=mbody;k.Description=mdesc;k.Footer=mfoot;c=k}catch(e3){return false}}}return c}catch(e){return false}}function addOrChangeParameters(url,params){let splitParams={};let splitPath=/(.*)[?](.*)/.exec(url);if(splitPath&&splitPath[2])splitPath[2].split("&").forEach(k=>{let d=k.split("=");splitParams[d[0]]=d[1]});let newParams=Object.assign(splitParams,params);let finalParams=Object.keys(newParams).map(a=>a+"="+newParams[a]).join("&");return splitPath?splitPath[1]+"?"+finalParams:url+"?"+finalParams}class BEA{Cart=null;Products=null;Authorize=null;Pay=null;localCache=true;_prom=null;proms=[];l="En";fields={Section:"Section,Title,Text",Product:"Name,Price,Quantity"};constructor(options){if(options===void 0)options={};if(!Object.keys(options).length==0){if(options.hasOwnProperty("fields")){for(var i2 in options["fields"]){this.fields[i2]=options["fields"][i2]}}if(options.hasOwnProperty("localisation"))this.l=options.localisation;if(options.hasOwnProperty("locale")&&options.locale===true){this.getLocale()}if(options.hasOwnProperty("sections")&&options.sections===true){this.getSections()}if(options.hasOwnProperty("localCache")&&options.localCache===false){this.localCache=false}}this.Cart=new Cart(this);this.Products=new Products(this);this.Authorize=new Authorize(this);this.Pay=new Pay(this);this._prom=Promise.all(this.proms)}request(className,data2,async,type2,a){var prom=defer();var x2;API.req(className,data2,null,type2,a??0).then(r2=>{if(async){prom.resolve(r2)}else{x2=r2.results}});if(async)return prom;return x2}getSections(){var sec=new Section(this);this.proms.push(sec._prom);return sec.get()}getLocale(){var loc=new Locale(this);this.proms.push(loc._prom);return loc.get()}order(){let prom=defer();var ids="";var productsInfo;var user;var orderData={User:"",productItems:[],Amount:0};user=this.Authorize.me();orderData.User=user.objectId;$.each(this.Cart.cartData,function(key,value){ids=ids+value.P+","});this.Products.get({fields:"Name,Price,Quantity",media:"images",crops:"ax200,ax600,ax700,200x200,ax300"},{ids},true).then(res=>{let productsInfo2=res.results;var productsDB=Object.assign({},...productsInfo2.map(x2=>({[x2.objectId]:x2})));$.each(this.Cart.cartData,function(key,value){orderData.productItems.push({Qty:value.Q,Product:value.P,productData:JSON.stringify(productsDB[value.P]),Price:productsDB[value.P].Price});orderData.Amount+=value.Q*productsDB[value.P].Price});this.request("/Order",{User:orderData.User,Amount:orderData.Amount},true,"POST").then(res2=>{let orderId=res2.results;for(var i2=0;i2<orderData.productItems.length;i2++){orderData.productItems[i2]["Order"]=orderId[0].objectId;this.request("/orderItems ",orderData.productItems[i2],true,"POST")}prom.resolve(orderId)})});return prom}sendEmail(data2){let prom=defer();this.request("/_Emails/send",data2,true,"POST").then(res=>{prom.resolve(r)})}batch(data2){return this.request("/batch",data2,true,"POST")}query(className,data2){return this.request(className,data2,true,"GET")}get(className,data2,options=true){return this.request(className,data2,options,"GET")}post(className,data2,options=true){return this.request(className,data2,options,"POST")}put(className,data2,options=true){return this.request(className,data2,options,"PUT")}delete(className,options=true){return this.request(className,"",options,"DELETE")}}class Pay{tsdk=null;object={};constructor(tsdk){this.tsdk=tsdk;let self=this;$(window).unbind("message").on("message",function(e){let dd=$("#gosell-gateway")[0].contentWindow;if(e.originalEvent.source===dd&&e.originalEvent.data=="close"){$(".gosell-gateway").remove();self.onClose()}})}create(data2){let prom=defer();API.post("https://pay.bea.com.lb/create",data2,{},666).then(d=>{this.object=d;cl(d);this.process(this.object.transaction.url.replace("mode=page","mode=popup"));prom.resolve(this.object.id)}).catch(err=>{cl(err)});return prom}process(link){var d=`
|
|
36
|
+
(e = e.indexOf(".js") === -1 ? c + e + ".js" : c + e);*/if(l[e3])return o2&&(a[o2]=1),l[e3]==2?y():setTimeout(function(){t4(e3,true)},0);l[e3]=1,o2&&(a[o2]=1),m(e3,y)})},0),v}function m(n3,r3){var i3=e.createElement("script"),u2;i3.onload=i3.onerror=i3[o]=function(){if(i3[s]&&!/^c|loade/.test(i3[s])||u2)return;i3.onload=i3[o]=null,u2=1,l[n3]=2,r3()},i3.async=1,i3.setAttribute("crossorigin","anonymous"),i3.setAttribute("data-permanent",1),i3.src=h?n3+(n3.indexOf("?")===-1?"?":"&")+h:n3,t2.insertBefore(i3,t2.lastChild)}var e=document,t2=e.getElementsByTagName("head")[0],n2="string",r2=false,i2="push",s="readyState",o="onreadystatechange",u={},a={},f={},l={},c,h;return v.get=m,v.order=function(e2,t3,n3){(function r3(i3){i3=e2.shift(),e2.length?v(i3,r3):v(i3,t3,n3)})()},v.path=function(e2){c=e2},v.urlArgs=function(e2){h=e2},v.ready=function(e2,t3,n3){e2=e2[i2]?e2:[e2];var r3=[];return!d(e2,function(e3){u[e3]||r3[i2](e3)})&&p(e2,function(e3){return u[e3]})?t3():!(function(e3){f[e3]=f[e3]||[],f[e3][i2](t3),n3&&n3(r3)})(e2.join("|")),v},v.done=function(e2){v([null],e2)},v});(function(n2,t2){this[n2]=t2()})("sbea",function(){return function(x2){beas=x2}});(function(n2,t2){this[n2]=t2()})("Reactor",function(){return function(o){appSettings=o;if(o.Base)beas=o.Base;else{var getUrl=window.location;var baseUrl=getUrl.protocol+"//"+getUrl.host+"/";if(o.subDirectory)baseUrl=baseUrl+o.subDirectory+"/";appSettings.Base=baseUrl}if(o.App)execEl=o.App;if(o.Additional){bea([o.Additional],"ready",function(){})}if(o.init&&typeof o.init==="function")o.init()}});var fullTB=[{items:["Source","-","searchCode","autoFormat","CommentSelectedRange","UncommentSelectedRange","AutoComplete","-","Save","NewPage","Preview","Print","-","Templates","-","Cut","Copy","Paste","PasteText","PasteFromWord","PasteCode","-","Undo","Redo","-","SelectAll","-","Find","-","Image","CodeSnippet","Flash","Table","HorizontalRule","Smiley","SpecialChar","PageBreak","Iframe","VideoDetector","-","Blockquote","CreateDiv","simplebutton","-","Link","Unlink","Anchor","-","TextColor","BGColor","-","Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","-","NumberedList","BulletedList","-","Outdent","Indent","-","CopyFormatting","RemoveFormat","-","lineheight","letterspacing","Styles","Format","Font","FontSize","-","ShowBlocks"]}];var normalTB=[{name:"basicstyles",groups:["basicstyles","cleanup"],items:["Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","Language","-","Undo","Redo","-","SelectAll","-","CopyFormatting","RemoveFormat"]},"/",{items:["Find","-","Image","Table","HorizontalRule","Smiley","SpecialChar","Iframe","VideoDetector","-","Link","Unlink","Anchor"]},{name:"paragraph",groups:["list","indent","blocks","align","bidi"],items:["TextColor","BGColor","-","NumberedList","BulletedList","-","Outdent","Indent"]},"/",{name:"styles",items:["lineheight","letterspacing","Styles","Format","Font","FontSize"]}];var miniTB=[{name:"basicstyles",groups:["basicstyles","cleanup"],items:["Bold","Italic","Underline","Strike","Subscript","Superscript","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl","Language","-","Link","Unlink","Anchor","-","CopyFormatting","RemoveFormat"]},"/",{name:"paragraph",groups:["list","indent","blocks","align","bidi"],items:["TextColor","BGColor","-","NumberedList","BulletedList","-","Outdent","Indent"]},{name:"styles",items:["Styles","Format","Font","FontSize"]}];(function(submit){HTMLFormElement.prototype.submit=function(data2){$(this).submit();return false}})(HTMLFormElement.prototype.submit);[HTMLElement,typeof SVGElement!=="undefined"?SVGElement:null].forEach(function(Ctor){if(!Ctor)return;var P=Ctor.prototype;P.setAttributeNative=P.setAttribute;P.removeAttributeNative=P.removeAttribute;P.getAttributeNative=P.getAttribute;P.setAttribute=function(prop,val2){if(prop.substr(0,1)=="@"){(this.events||(this.events={}))[prop]=val2}else{this.setAttributeNative(prop,val2)}};P.removeAttribute=function(prop,val2){if(prop.substr(0,1)=="@"&&this.events)delete this.events[prop];this.removeAttributeNative(prop,val2)};P.getAttribute=function(prop,val2){if(prop.substr(0,1)=="@"&&this.events&&Object.prototype.hasOwnProperty.call(this.events,prop)){return this.events[prop]}return this.getAttributeNative(prop,val2)}});(function(replaceChild){Node.prototype.replaceChild=function(newChild,oldChild){if(oldChild&&oldChild.events&&typeof SVGElement!=="undefined"&&newChild instanceof SVGElement&&newChild.classList.contains("iconify")){newChild.events=Object.assign({},oldChild.events,newChild.events)}return replaceChild.call(this,newChild,oldChild)}})(Node.prototype.replaceChild);var XHRs=new Array;if(localStorage.getItem("globals")===null)localStorage.setItem("globals",JSON.stringify({}));if(localStorage.getItem("_rx")===null)localStorage.setItem("_rx",JSON.stringify({}));var _globalsBackingValue;Object.defineProperty(window,"globals",{configurable:true,enumerable:true,get:function(){return _globalsBackingValue},set:function(v){if(v===_globalsBackingValue)return;_globalsBackingValue=_deepReactive(v,_onGlobalsDeepChange);_onGlobalsDeepChange()}});function _onGlobalsDeepChange(){if(typeof _vt!=="undefined"&&_vt.Global&&_vt.Global.vars){_vt.Global.vars.globals=globals}_scheduleGlobalsSave()}var _globalsSaveQueued=false;function _scheduleGlobalsSave(){if(_globalsSaveQueued)return;_globalsSaveQueued=true;setTimeout(function(){_globalsSaveQueued=false;try{var json=JSON.stringify(_globalsBackingValue===void 0?{}:_globalsBackingValue);if(localStorage.getItem("globals")!==json)localStorage.setItem("globals",json)}catch(e){}},0)}globals=clone(JSON.parse(localStorage.getItem("globals")));let _rx=clone(JSON.parse(localStorage.getItem("_rx")));var watch={};var popups={"modals":[],"react-modals":[]};var cntrlon=0;var _gn=0,_worker;var nodes=[];var historyStack=[];var _jsuid={};function clone(item){if(!item){return item}var types2=[Number,String,Boolean],result;types2.forEach(function(type2){if(item instanceof type2){result=type2(item)}});if(typeof result=="undefined"){if(Object.prototype.toString.call(item)==="[object Array]"){result=[];item.forEach(function(child,index,array){result[index]=clone(child)})}else if(typeof item=="object"){if(item.nodeType&&typeof item.cloneNode=="function"){result=item.cloneNode(true)}else if(!item.prototype){if(item instanceof Date){result=new Date(item)}else{result={};for(var i2 in item){result[i2]=clone(item[i2])}}}else{if(false){result=new item.constructor}else{result=item}}}else{result=item}}return result}function isInput(o){if(o.is(":checkbox")||o.is("input")||o.is("textarea")||o.is(":radio")||o.is("select"))return true;return false}function getVal(o){if(isInput(o)){return $.trim(o.val())}return o.html()}function setVal(o,v){if(isInput(o)){o.val(v)}else o.html(v)}function iterateConditions(text){var results=[];var opts=text.split("##");var iff=opts.shift();opts=opts.join("##");if(opts.indexOf("#else#")>-1)var hasElse=true;if(opts.indexOf("#elseif#")>-1)var hasElseIfs=true;if(hasElse){opts=opts.split("#else#");var elsee=opts.pop();opts=opts.join("")}if(hasElseIfs){results["elseif"]=[];var elseifs=opts.split("#elseif#");var ifOpts=elseifs.shift();results["if"]={cond:iff,val:ifOpts};for(var index=0;index<elseifs.length;index++){var elf=elseifs[index].split("##");results["elseif"].push({cond:elf[0],val:elf[1]})}if(hasElse)results["else"]=elsee}else if(hasElse){results["if"]={cond:iff,val:opts};if(hasElse)results["else"]=elsee}else{results["if"]={cond:iff,val:opts}}return results}function wait(){_initialized=false}function resume(){_initialized=true}const pause=msec=>new Promise((resolve,_)=>{setTimeout(resolve,msec)});function _lumenReadyHandler(){if(typeof appSettings==="undefined"||!appSettings){setTimeout(_lumenReadyHandler,10);return}nodes=getURLNodes();if(_initialized==null)_initialized=true;$("html").removeClass("no_js");if(!$("[exec]").length)$("body").append({beajs:true,body:"<div exec class=h></div>"});$(document).keyup(function(e){cntrlon=0});$(document).keydown(function(e){if(e.ctrlKey||e.metaKey){cntrlon=1}});goToNode()}$(document).ready(_lumenReadyHandler);function updateLocalVariable(k){if(k=="_rx")_rx=clone(JSON.parse(localStorage.getItem("_rx")));else globals=clone(JSON.parse(localStorage.getItem("globals")))}function setGlobals(x2){localStorage.setItem("globals",JSON.stringify(x2));globals=clone(JSON.parse(localStorage.getItem("globals")))}function setRX(x2){localStorage.setItem("_rx",JSON.stringify(x2));_rx=clone(JSON.parse(localStorage.getItem("_rx")))}$(window).on("storage",function(e){if(e.originalEvent.key=="globals"){if(localStorage.getItem("globals")!=null)updateLocalVariable();else setGlobals(globals)}else if(e.originalEvent.key=="_rx"){if(localStorage.getItem("_rx")!=null)updateLocalVariable("_rx");else setRX(_rx)}});var _work=function(){if(!$(".prog").length)$("body").append('<div class="prog"><div class=bar role=bar></div><div class=spinner role=spinner><div class="spinner-icon"></div></div></div>');_worker=setTimeout(function(){_gn=incri(_gn);barSet(_gn,200);_work()},200)};$(document).ajaxStart(function(){_gn=0;_work();if(typeof heartbeat==="function")heartbeat()}).ajaxStop(function(){_gn=0;barSet(1,200);if(typeof heartbeat==="function")heartbeat();globalWatch()}).ajaxError(function(e,xhr,opt){if(xhr.statusText=="error"){if(xhr.status=="422")$("[exec]").html(xhr.responseText);else if(xhr.status=="0"){$("[dropzone].pending").removeClass("pending").addClass("error");$("body").addClass("no-internet-connection")}}if(typeof heartbeat==="function")heartbeat();globalWatch();_gn=0;barSet(1,200)});(function($2){$2.extend({inArrayIn:function(elem,arr,i2){if(typeof elem!=="string"){return $2.inArray.apply(this,arguments)}if(arr){var len=arr.length;i2=i2?i2<0?Math.max(0,len+i2):i2:0;elem=elem.toLowerCase();for(;i2<len;i2++){if(i2 in arr&&arr[i2].toLowerCase()==elem){return i2}}}return-1}})})(jQuery);$.fn.priorityOn=function(type2,selector2,data2,fn2){this.each(function(){var $this=$(this);var types2=type2.split(" ");for(var t2 in types2){$this.on(types2[t2],selector2,data2,fn2);if(typeof $._data!=="function")continue;var currentBindings=($._data(this,"events")||{})[types2[t2]];if($.isArray(currentBindings)){currentBindings.unshift(currentBindings.pop())}}});return this};$.fn.lock=function(){if($(this).is("form")){$(this).find('[type="submit"]').attr("disabled","disabled");$(this).find("button:not([type])").attr("disabled","disabled")}return this};$.fn.unlock=function(){if($(this).is("form")){$(this).find('[type="submit"]').removeAttr("disabled");$(this).find("button:not([type])").removeAttr("disabled")}return this};$.fn.onClose=function(selector2,data2,fn2){this.each(function(){var el2=$(this);var types2=["close"];for(var t2 in types2){el2.on(types2[t2],selector2,data2,fn2)}});return this};$.fn.attach=function(type,selector,data,fn){var el=$(this);var types=type.split(" ");for(var t in types){var lu="$.fn.on"+types[t]+' = function (selector, data, fn) { var el = $(this); var types = ["'+types[t]+'"]; for (var t in types) { el.live(types[t], selector, data, fn); } return this;};';try{eval(lu)}catch(e){}}return this};$.fn.hasAttr=function(k){return!!(this[0]&&this[0].getAttribute(k)!=null)};$.fn.hasKey=function(k){return typeof this.data(k)!=="undefined"};function dotsIntoObjs(keys,value){var tempObject={};var container=tempObject;keys.split(".").map((k,i2,values)=>{container=container[k]=i2==values.length-1?value:{}});return tempObject}$.fn.set=function(name,value){var splitter=name.split(".");if(splitter.length>1){var key=splitter.shift();return this.data(key,dotsIntoObjs(splitter.join("."),value))}return this.data(name,value)};$.fn.props=function(){return this.data("props")};$.fn.scope=function(_sview){var _scopedVariables=_sview(this,this.data("props")??{})??{};for(var x2=0;x2<Object.keys(_scopedVariables).length;x2++){var _key=Object.keys(_scopedVariables)[x2];var val2=_scopedVariables[_key];this.set(_key,val2)}};$.fn.isOverflown=function(){return $(this)[0].scrollHeight>$(this)[0].clientHeight||$(this)[0].scrollWidth>$(this)[0].clientWidth};function removeEmptyElement(arr){var filtered=arr.filter(function(el2){return el2});return filtered}function findInObject(object,property,value){for(var i2=0;i2<object.length;i2+=1){if(object[i2][property]===value){return i2}}}function compareUs(object1,object2){var areObjects=isObject(object1)&&isObject(object2);if(!areObjects){if(typeof object1=="number"&&typeof object2=="number"){if(isNaN(object1)&&isNaN(object2))return true}return object1==object2}const keys1=Object.keys(object1);const keys2=Object.keys(object2);if(keys1.length!==keys2.length){return false}for(const key of keys1){const val1=object1[key];const val2=object2[key];const areObjects2=isObject(val1)&&isObject(val2);if(areObjects2&&!compareUs(val1,val2)||!areObjects2&&val1!==val2){return false}}return true}function deepCompare(object1,object2,path=""){const areObjects=isObject(object1)&&isObject(object2);if(!areObjects){if(typeof object1==="number"&&typeof object2==="number"){if(isNaN(object1)&&isNaN(object2)){return true}}if(object1!==object2){return false}return true}const keys1=Object.keys(object1);const keys2=Object.keys(object2);if(keys1.length!==keys2.length){return false}for(const key of keys1){const newPath=path?`${path}.${key}`:key;const val1=object1[key];const val2=object2[key];const areNestedObjects=isObject(val1)&&isObject(val2);if(!deepCompare(val1,val2,newPath)){return false}}return true}function isObject(object){return object!=null&&typeof object==="object"}(function(old){$.fn.attr=function(){if(arguments.length===0){if(this.length===0){return null}var obj={};$.each(this[0].attributes,function(){if(this.specified){obj[this.name]=this.value}});return obj}return old.apply(this,arguments)}})($.fn.attr);function st(b){if(!isNaN(b))$("html,body").stop().animate({scrollTop:b+"px"},{duration:400});else $("html,body").stop().animate({scrollTop:$(b).offset().top+"px"},{duration:400})}function pushURL(url,d){if(url||url==""){if(history&&history.pushState){history.pushState({},"",appSettings.Base+"/"+url.replace(new RegExp("^[/]+"),""));goToNode(d)}else{parent.location.href=url}}else{alert(url)}}function formatBytes(bytes,decimals){if(bytes==0)return"0 Bytes";var k=1024,dm=decimals<=0?0:decimals||2,sizes=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i2=Math.floor(Math.log(bytes)/Math.log(k));return parseFloat((bytes/Math.pow(k,i2)).toFixed(dm))+" "+sizes[i2]}function passwordContainsSymbol(value){var containsSymbol=false,symbols=`-!\xA7$%&/()=?.:,~;'#+*-/\\|{}[]_<>"`.split("");$.each(symbols,function(index,symbol){if(value.indexOf(symbol)>-1){containsSymbol=true;return false}});return containsSymbol}function passwordStrength(pass){var s=0,n2;if(pass.length>5)s+=10;if(/[a-z]/.test(pass))s+=1;if(/[A-Z]/.test(pass))s+=1;if(/[0-9]/.test(pass))s+=1;if(passwordContainsSymbol(pass))s+=1;if(s==14)n2="very-strong";else if(s==13)n2="strong";else if(s==12)n2="medium";else if(s==11)n2="weak";else n2="";if(/\s/g.test(pass))n2="has-spaces";return n2}function passwordValid(pass){var n2=passwordStrength(pass);if(n2=="strong"||n2=="very-strong")return true;return false}function incri(n2){var amount;if(n2>1){return .994}else{if(n2>=0&&n2<.2){amount=.1}else if(n2>=.2&&n2<.5){amount=.04}else if(n2>=.5&&n2<.8){amount=.02}else if(n2>=.8&&n2<.99){amount=.005}else{amount=5e-4}n2=n2+amount;if(n2<.08)n2=.08;else if(n2>.994)n2=.994;return n2}}function barSet(n2,speed){clearTimeout(_worker);if(n2<.08)n2=.08;else if(n2>1)n2=1;var bar=$('.bar[role="bar"]');bar.css({transition:"all "+speed+"ms linear","-webkit-transition":"all "+speed+"ms linear","-moz-transition":"all "+speed+"ms linear","-o-transition":"all "+speed+"ms linear"});if($("body").hasClass("rtl"))bar.css({"margin-right":-100+n2*100+"%"});else bar.css({"margin-left":-100+n2*100+"%"});if(n2==1){_worker=setTimeout(function(){$(".prog").animate({opacity:0},{duration:speed,complete:function(){$(".prog").remove()}})},speed)}}function getFormData(form){var unindexed_array=form.serializeArray();var indexed_array={};$.map(unindexed_array,function(n2,i2){if(n2["name"].includes("[]")){var key=n2["name"].split("[]")[0];if(!indexed_array.hasOwnProperty(key))indexed_array[key]=[];indexed_array[key].push(n2["value"])}else{indexed_array[n2["name"]]=n2["value"]}});return indexed_array}$(window).on("popstate",function(){if(history&&history.pushState)goToNode()});var getLocation=function(href){var l=document.createElement("a");l.href=href;return l};function getURLNodes(){appSettings.Base=appSettings.Base.replace(new RegExp("[/]+$"),"");var base=getLocation(appSettings.Base);if(base.origin!=window.location.origin){appSettings.Base=window.location.origin+base.pathname;var base=getLocation(appSettings.Base)}var _nodes=base.pathname!="/"?window.location.pathname.split(base.pathname).join("").replace(new RegExp("^[/]+"),"").split("/"):location.href.split(appSettings.Base).join("").replace(new RegExp("^[/]+"),"").split("?")[0].split("/");if(!_nodes[0])_nodes[0]=appSettings.defaultView??"home";if(historyStack[historyStack.length-1]?.url!=window.location.href)historyStack.push({"nodes":_nodes,"params":paramsToObj(window.location.href),"url":window.location.href});return _nodes}var prevNodes=[];function goToNode(d){if(_initialized){prevNodes=clone(nodes);nodes=getURLNodes();renderView(nodes[0],null,d)}else{setTimeout(function(){goToNode(d)},100)}}var View={};function setError(e,t2){if(!e){console.warn(t2);return}console.warn(t2,e.message)}function renderTpl(el2,n2,vars2){if(!el2.length)return;if(el2.data("_status")=="error")return;if(!el2.hasKey("_re")){if(el2.data("_status")=="pending"){getTpl(n2,el2,vars2)}setTimeout(function(){renderTpl(el2,n2,vars2)},_tickTime)}}function prepareNode(n2,rep){var _arr2=n2.split("/");if(_arr2.length>1){for(var i2=_arr2.length-1;i2>=_arr2.length-1;i2--)_arr2[i2]=_arr2[i2];n2=_arr2.join("/")}else n2=n2;return rep?n2.replace(new RegExp("^[/]+"),""):n2}var _esps={};var _Views={};function setAppFuncs(){let initFunc=appSettings.init&&typeof appSettings.init==="function"?appSettings.init:typeof init==="function"?init:null;if(typeof initFunc==="function")initFunc()}function getView(n2,el2,d){let filePath="src/views/"+n2+".view";let fileKey=btoa(filePath);if($("body").hasKey("view_"+fileKey)){renderView(n2,el2,d,true)}else{if(_vcData&&_vcData["views"].hasOwnProperty(fileKey)){$("body").data("view_"+fileKey,_vcData["views"][fileKey]);renderView(n2,el2,d,true);return}if(Nuke&&Nuke._ws&&Nuke._ws.readyState){Nuke.emit("getview",fileKey,function(e){var r2=e.data;$("body").data("view_"+fileKey,r2);renderView(n2,el2,d,true)})}else{setTimeout(()=>{getView(n2,el2,d)},_tickTime)}}}function fileToDataURL(file){var reader=new FileReader;return new Promise(function(resolve,reject){reader.onload=function(event){resolve(event.target.result)};reader.readAsDataURL(file)})}function readFilesAsDataURL(files){return Promise.all(files.map(fileToDataURL))}function defer(){var res,rej;var promise=new Promise((resolve,reject)=>{res=resolve;rej=reject});promise.resolve=res;promise.reject=rej;promise.success=res;promise.failed=rej;return promise}function getTpl(n2,el2,vaz2){let filePath="src/tpls/"+n2+".tpl";let fileKey=btoa(filePath);if(el2.data("_status")!="pending")return;el2.data("_status","getting");if($("body").hasKey("tpl_"+fileKey)){let r2=$("body").data("tpl_"+fileKey);el2.html(r2);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2)}else{if(_vcData&&_vcData["tpls"].hasOwnProperty(fileKey)){$("body").data("tpl_"+fileKey,_vcData["tpls"][fileKey]);el2.html(_vcData["tpls"][fileKey]);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2);return}if(Nuke&&Nuke._ws&&Nuke._ws.readyState){Nuke.emit("gettpl",fileKey,function(e){var r2=e.data;$("body").data("tpl_"+fileKey,r2);el2.html(r2);if(!setRe(el2,vaz2))setError(null,"Error in rendering template "+n2)})}else{setTimeout(()=>{getTpl(n2,el2,vaz2)},_tickTime)}}}function setRe(_el,vaz){try{if(!_el.hasKey("_vars")){if(_debugMode)cl("The Data Arrived",vaz);let data={};let vars=vaz.split(",");vars=vars.map(s=>s.trim());let binds=[];let dataNamesValues=[];var _subView=_el.closest("[view]");for(let x=0;x<vars.length;x++){if(vars[x]!=""){try{let varName=vars[x];let varValue=vars[x];let NameAs=null;if(varName.indexOf(" as ")!==-1){varName=varName.split(" as ");varValue=varName[0];varName=varName[1];NameAs=vars[x]}let val="";if(_subView.length){val=_subView.hasKey(varValue)?_subView.data(varValue):eval(varValue)}else val=eval(varValue);dataNamesValues.push({Name:varName,NameAs,Value:val})}catch(e){let varName2=vars[x];let varValue2=vars[x];let NameAs2=null;if(varName2.indexOf(" as ")!==-1){varName2=varName2.split(" as ");varValue2=varName2[0];varName2=varName2[1];NameAs2=vars[x]}dataNamesValues.push({Name:varName2,NameAs:NameAs2,Value:void 0});setError(e,"Error in bind variables for "+vars[x])}}}for(let x2=0;x2<dataNamesValues.length;x2++){let dn=dataNamesValues[x2];binds.push({dataName:dn["Name"],dataNameAs:dn["NameAs"],dataValue:clone(dn["Value"])});data[dn["Name"]]=dn["Value"]}if(_debugMode)cl(["The Data Set",data,binds]);if(appSettings.beforetick&&typeof appSettings.beforetick==="function")appSettings.beforetick();_el.data("_vars",binds).data("_re",new RenderEngine(_el,data));globalWatch()}_el.data("_status","complete");return true}catch(e){_el.data("_status","error");return false}return false}function parseFromString(html){return doc=new DOMParser().parseFromString(html,"text/html")}var _binds={};let _oldGlobals=clone(globals);let _oldRX=clone(_rx);let _watch=clone($("body").data("_watch"));$("body").data("_watch",{old:{},list:[]});function reloads(){$("[crslf].flickity-enabled.reload-on-bind").each(function(){var el2=$(this);el2.flickity("destroy");var opts=el2.attr("crslf-opts");if(!opts)opts={};else opts=JSON.parse(opts);el2.flickity(opts);var flkty=el2.data("flickity");flkty.on("dragStart",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="none"));flkty.on("dragEnd",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="all"))});$("[crsl].crsl-initialized").each(function(){$(this).crsl("refresh")});let tickFunc=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc==="function")tickFunc();if(typeof scsc!=="undefined")scsc.reset();if(typeof dgsc!=="undefined")dgsc.reset();applyTriggers();setTimeout(()=>{if(typeof scsc!=="undefined")scsc.reset();if(typeof dgsc!=="undefined")dgsc.reset();applyTriggers()},_tickTime*2)}function renderViewsTpls(){$("[view]").each(function(i){var el=$(this);if(el.data("_status")!="pending"&&el.data("_status")!="error"&&el.data("_status")!="getting"&&el.data("_status")!="complete"){var modal=el.closest("popup");var n=el.attr("view");var _props=el.attr(":props")??null;var _binds=el.attr(":props-bind")??null;el.data("_status","pending");let nn=n;var _arr=nn.split("/");if(_arr.length>1){for(var i=_arr.length-1;i>=_arr.length-1;i--){_arr[i]=_arr[i].toLowerCase()}nn=_arr.join("/")}else{nn=nn.toLowerCase()}var _queryParams=nn.split("?");nn=_queryParams.shift();if(el.attr(":data")){let vaz=el.attr(":data");let data={};let vars=vaz.split(",");let dataNamesValues=[];let binds=[];vars=vars.map(s=>s.trim());for(let x=0;x<vars.length;x++){if(vars[x]!=""){try{let varName=vars[x];let varValue=vars[x];let NameAs=null;if(varName.indexOf(" as ")!==-1){varName=varName.split(" as ");varValue=varName[0];varName=varName[1];NameAs=vars[x]}let val="";val=eval(varValue);dataNamesValues.push({Name:varName,NameAs,Value:val})}catch(e){cl(e);let varName2=vars[x];let varValue2=vars[x];let NameAs2=null;if(varName2.indexOf(" as ")!==-1){varName2=varName2.split(" as ");varValue2=varName2[0];varName2=varName2[1];NameAs2=vars[x]}dataNamesValues.push({Name:varName2,NameAs:NameAs2,Value:void 0});setError(e,"Error in bind variables for "+vars[x])}}}for(let x2=0;x2<dataNamesValues.length;x2++){let dn=dataNamesValues[x2];binds.push({dataName:dn["Name"],dataNameAs:dn["NameAs"],dataValue:clone(dn["Value"])});data[dn["Name"]]=dn["Value"]}el.data("props",data)}else{var _d=paraToObj(getBind(_binds,_props));el.data("params",paraToObj(_queryParams));if(modal.length)_d["modal"]=modal.data("props");el.data("props",_d)}if(n==""||!n||n.split("/").slice(-1)==""){el.data("_status","error")}else{renderView(n,el,_d)}}})}function renderPlugins(){$("[crslf]:not(.flickity-enabled,[comp],[tpl],[view]),[crslf][comp]:not(.flickity-enabled),[crslf][tpl]:not(.flickity-enabled),[crslf][view]:not(.flickity-enabled)").each(function(){if(typeof $.fn.flickity!=="function")return;var el2=$(this);if(el2.hasAttr("[tpl]")||el2.hasAttr("[comp]")||el2.hasAttr("[view]")){if(el2.data("_status")!="complete")return}var opts=el2.attr("crslf-opts");if(!opts)opts={};else opts=JSON.parse(opts);el2.flickity(opts);var flkty=el2.data("flickity");flkty.on("dragStart",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="none"));flkty.on("dragEnd",()=>flkty.slider.childNodes.forEach(slide=>slide.style.pointerEvents="all"));setTimeout(function(){globalWatch()},600)});$("[crsl]:not(.crsl-initialized,[comp],[tpl],[view]),[crsl][comp]:not(.crsl-initialized),[crsl][tpl]:not(.crsl-initialized),[crsl][view]:not(.crsl-initialized)").each(function(){if(typeof $.fn.crsl!=="function")return;var el2=$(this);if(el2.hasAttr("[tpl]")||el2.hasAttr("[comp]")||el2.hasAttr("[view]")){if(el2.data("_status")!="complete")return}el2.crsl();el2.on("setPosition beforeChange",function(event,slick,currentSlide,nextSlide){$(window).trigger("scroll.scsc");$(window).trigger("resize")})});$("[up]:not([upid])").each(function(){var u=_ups.length;var t2=$(this);var mxf=t2.attr("data-mxf")?t2.attr("data-mxf"):10;if(!t2.hasAttr("upid")){var sl="up_"+u;t2.attr("upid",sl);t2.prepend(`<input `+(mxf>1?"multiple":"")+` type="file" files style="display:none;" />`);_ups.push(t2);if(typeof _upwrkStarted==="function")_upwrkStarted()}});$("form:not(.binded,[norm])").each(function(){var el2=$(this);var reset=false;if(el2.hasAttr("reset"))reset=true;var actn=el2.attr("action")??"";var local=false;el2.addClass("binded");if(actn==""){actn=getURLNodes().join("/");local=true}else local=isPathLocal(actn);if(el2.hasAttr("o-sub")){el2.ajaxForm({beforeSubmit:function(formData,f,options){let formDataMapped={};let formDataMappedAdditionals={};formDataMapped=Object.assign({},...formData.map(x2=>{if(x2.type=="file"){if(!formDataMappedAdditionals.hasOwnProperty(x2.name))formDataMappedAdditionals[x2.name]=[];formDataMappedAdditionals[x2.name].push(x2["value"]);return void 0}if(x2["name"].includes("[]")){var key=x2["name"].split("[]").join("");if(!formDataMappedAdditionals.hasOwnProperty(key))formDataMappedAdditionals[key]=[];formDataMappedAdditionals[key].push(x2["value"]);return void 0}return{[x2.name]:x2.value}}));formDataMapped={...formDataMapped,...formDataMappedAdditionals};if(f.hasAttr("b-sub")){var bfs=f.attr("b-sub");if(typeof window[bfs]==="function"){checkFormInputs(f);if(window[bfs](f,formDataMapped)===false)return false}}if(!checkFormInputs(f))return false;if(f.hasAttr("o-sub")){var ofs=f.attr("o-sub");if(typeof window[ofs]==="function"){window[ofs](f,formDataMapped)}}return false},clearForm:reset,resetForm:reset,success:function(responseText,statusText,xhr,f){},timeout:3e5,error:function(xhr,textStatus,errorThrown){}})}else{if(local){el2.ajaxForm({beforeSubmit:function(formData,f,options){if(!checkFormInputs(f))return false;let formDataMapped={};let formDataMappedAdditionals={};formDataMapped=Object.assign({},...formData.map(x2=>{if(x2.type=="file"){if(!formDataMappedAdditionals.hasOwnProperty(x2.name))formDataMappedAdditionals[x2.name]=[];formDataMappedAdditionals[x2.name].push(x2["value"]);return void 0}if(x2["name"].includes("[]")){var key=x2["name"].split("[]").join("");if(!formDataMappedAdditionals.hasOwnProperty(key))formDataMappedAdditionals[key]=[];formDataMappedAdditionals[key].push(x2["value"]);return void 0}return{[x2.name]:x2.value}}));formDataMapped={...formDataMapped,...formDataMappedAdditionals};try{if(f.hasAttr("b-sub")){var bfs=f.attr("b-sub");if(typeof window[bfs]==="function"){if(window[bfs](f,formDataMapped)===false)return false}}var actn2=f.attr("action")??"";if(actn2==""){actn2=getURLNodes().join("/")}if(validateInputs(f)){var d=getFormData(f);if(f.attr("method")?.toLowerCase()=="get"){actn2=addOrChangeParameters(actn2,d)}pushURL(actn2,d)}}catch(e){cl(e)}return false},clearForm:reset,resetForm:reset,success:function(responseText,statusText,xhr,f){},timeout:3e5,error:function(xhr,textStatus,errorThrown){}})}}});$("[editor]").each(function(i2){var editor=$(this);editor.removeAttr("editor");var TB=normalTB;if(editor.is("[mini]"))TB=miniTB;else if(editor.is("[full]"))TB=fullTB;if(typeof CKEDITOR!=="undefined"){CKEDITOR.replace(this,{uiColor:"#ffffff",language:$("html").attr("lang"),allowedContent:true,enterMode:CKEDITOR.ENTER_BR,toolbar:TB,on:{instanceReady:function(evt){var itemTemplate='<li class="l" data-id="{id}"><div><strong class="item-title">{name}</strong></div><div><i>{description}</i></div></li>',outputTemplate="<span class=hash>{linked}</span> ";var autocomplete=new CKEDITOR.plugins.autocomplete(evt.editor,{textTestCallback:function(range){if(!range.collapsed){return null}return CKEDITOR.plugins.textMatch.match(range,function(text,offset){var left=text.slice(0,offset);var matchHash=left.match(/#\d*$/);var matchAt=left.match(/(@)[A-Za-z]+(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9.]+[A-Za-z0-9]{6,30}$/);if((!matchHash||matchHash=="#")&&(!matchAt||matchAt=="@")){return null}var match=matchHash;if(!match)match=matchAt;return{start:match.index,end:offset}})},dataCallback:function(matchInfo,callback){var query=matchInfo.query;if(myR["[ck]"])myR["[ck]"].abort();clearTimeout(debounceTimeout["[ck]"]);debounceTimeout["[ck]"]=setTimeout(function(){myR["[ck]"]=$.post(beas+"a/hashes/get",{id:query},function(result){if(result){result=$.parseJSON(result);var suggestions=result.filter(function(item){return String(item.name).indexOf(query.substring(1))==0});callback(suggestions)}})},500)},itemTemplate,outputTemplate,throttle:100});autocomplete.getHtmlToInsert=function(item){return this.outputTemplate.output(item)}},change:function(ev){if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty");editor.val(ev.editor.getData()).trigger("change")},focus:function(ev){editor.closest(".fields").addClass("focused");if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty")},blur:function(ev){editor.closest(".fields").removeClass("focused");if($.trim(ev.editor.getData()).length==0)editor.closest(".fields").addClass("is-empty").removeClass("is-not-empty");else editor.closest(".fields").removeClass("is-empty error").addClass("is-not-empty")}}})}});$(".cke_autocomplete_panel").each(function(){if($(this).html()=="")$(this).remove()});$("[tags]:not(.tag-editor-hidden-src)").each(function(){if(typeof $.fn.tagEditor!=="function")return;var t2=$(this);var u=currentlyValidTags.length;t2.attr("data-u",u);var del=t2.attr("dl")?t2.attr("dl"):", ";var maxTags=t2.attr("mt")?t2.attr("mt"):50;var maxLength=t2.attr("ml")?t2.attr("ml"):100;var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var tagslower=t2.attr("tags-lower")?true:false;var autocomplete=t2.attr("acs")?{delay:250,autoFocus:true,position:{collision:"flip"},source:function(request,response){$.post(beas+"a"+t2.attr("acs"),request,response)},minLength:1,select:function(event,ui){if(ui.item==null){t2.val("")}},change:function(event,ui){if(ui.item==null){t2.val("")}}}:null;t2.tagEditor({autocomplete,delimiter:del,removeDuplicates:true,forceLowercase:tagslower,placeholder:plchldr,animateDelete:50,maxLength,maxTags,onChange:function(field,editor,tags){field.trigger("change")},beforeTagSave:function(field,editor,tags,tag,val2){if(!t2.attr("sts")){if($.inArrayIn(val2,tags)!==-1){return false}}else{if($.inArray(tag,currentlyValidTags[u][tags])==-1){return false}}if(t2.attr("tags-before")){var bfs=t2.attr("tags-before");if(typeof window[bfs]==="function"){if(window[bfs](t2,field,editor,tags,tag,val2)===false)return false}}}});currentlyValidTags.push(t2)});$("[slct]:not(.select2-hidden-accessible)").each(function(){if(typeof $.fn.select2!=="function")return;var t2=$(this);var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var dropdownParent=t2.attr("prnt")?t2.attr("prnt"):"body";var tpl=t2.attr("slct-tpl")?t2.attr("slct-tpl"):null;var dir=t2.attr("slct-dir")?t2.attr("slct-dir"):"ltr";var minResultsForSearch=t2.attr("mins")?t2.attr("mins"):"";if(dropdownParent=="self")dropdownParent=t2.parent();else dropdownParent=$(dropdownParent);var allowNewTags=t2.attr("ntgs")?true:false;var ax=t2.attr("axs")?{url:t2.attr("axs"),dataType:"json",delay:250}:null;t2.select2({dropdownParent,placeholder:plchldr,dir,allowClear:false,tags:allowNewTags,ajax:ax,minimumResultsForSearch:minResultsForSearch,templateSelection:function(data2,container){if(data2.newTag){if(allowNewTags&&t2.attr("ntgs")!="true"){var tag=data2.text;var id=data2.id;$.post(beas+"a"+t2.attr("ntgs"),{tag},function(r2){if(r2=="true"){var newOption=new Option(tag,id,true,true);t2.append(newOption).trigger("change")}else{alert("Error adding tag! Please Try again.");t2.val(null).trigger("change")}});return data2.text}else{return data2.text}}else{return data2.text}},templateResult:function(state){if(tpl){if(typeof window[tpl]==="function")return window[tpl](state)}if(state.newTag){if(allowNewTags&&t2.attr("ntgs")!="true"){var new_state=$("<span>+ Add <b>"+state.text+"</b></span>");return new_state}return state.text}else return state.text},tokenSeparators:[","],createTag:function(params){var term=$.trim(params.term);if(term===""){return null}return{id:term,text:term,newTag:true}},insertTag:function(data2,tag){data2.push(tag)}});if(t2.attr("nosearch"))t2.on("select2:opening select2:closing",function(event){var searchfield=$(this).parent().find(".select2-search__field");searchfield.prop("disabled",true)})});$("[sl]:not(.select2-hidden-accessible)").each(function(){if(typeof $.fn.select2!=="function")return;var t2=$(this);try{var plchldr=t2.attr("placeholder")?t2.attr("placeholder"):"";var dir=$("body").hasClass("rtl")?"rtl":"ltr";var nr=t2.attr("sl-nrmsg")?t2.attr("sl-nrmsg"):"No results found";var minResultsForSearch=t2.attr("sl-mins")?t2.attr("sl-mins"):10;var allowNewTags=t2.attr("sl-ntgs")?true:false;var dropdownParent=t2.attr("sl-prt")?t2.attr("sl-prt"):"body";if(dropdownParent=="self")dropdownParent=t2.parent();else dropdownParent=$(dropdownParent);var query=t2.attr("sl-query")?t2.attr("sl-query"):null;var uniquer=Date.now();if(typeof window[query]==="function"){let dbcrID="dbcr_"+(Object.keys(_dbcrs).length+1);t2.select2.amd.define("adapt_"+uniquer,["select2/data/array","select2/utils"],function(ArrayAdapter,Utils){function CustomDataAdapter($element,options){CustomDataAdapter.__super__.constructor.call(this,$element,options)}Utils.Extend(CustomDataAdapter,ArrayAdapter);CustomDataAdapter.prototype.query=function(params,callback){clearTimeout(_dbcrs[dbcrID]);let _t=t2;_dbcrs[dbcrID]=setTimeout(function(){window[query](params,callback,_t)},!_dbcrs.hasOwnProperty(dbcrID)?0:_dbcrsTime)};return CustomDataAdapter});t2.select2({dropdownParent,minimumResultsForSearch:minResultsForSearch,placeholder:plchldr,dir,tags:allowNewTags,allowClear:false,language:{noResults:function(){return nr}},...t2.select2.amd.require("adapt_"+uniquer)?{ajax:{},dataAdapter:t2.select2.amd.require("adapt_"+uniquer)}:{}})}else{t2.select2({dropdownParent,minimumResultsForSearch:minResultsForSearch,placeholder:plchldr,dir,tags:allowNewTags,allowClear:false,language:{noResults:function(){return nr}}})}if(t2.attr("sl-nosrch"))t2.on("select2:opening select2:closing",function(event){var searchfield=$(this).parent().find(".select2-search__field");searchfield.prop("disabled",true)});if(t2.attr("sl-class")){t2.on("select2:opening",function(event){dropdownParent.addClass(t2.attr("sl-class"))});t2.on("select2:closing",function(event){dropdownParent.removeClass(t2.attr("sl-class"))})}}catch(e){cl(e)}});$("[pinnable]:not(.pinnable)").each(function(){if(typeof Headroom==="undefined")return;var t2=$(this);var offsetU=t2.attr("pinnable-offset-up")??100;var offsetD=t2.attr("pinnable-offset-down")??50;var options={offset:0,offset:{up:offsetU,down:offsetD},tolerance:0,tolerance:{up:5,down:0},classes:{initial:"pinnable",pinned:"pinnable--pinned",unpinned:"pinnable--unpinned",top:"pinnable--top",notTop:"pinnable--not-top",bottom:"pinnable--bottom",notBottom:"pinnable--not-bottom",frozen:"pinnable--frozen",pinned:"pinnable--pinned"},onPin:function(){},onUnpin:function(){},onTop:function(){},onNotTop:function(){},onBottom:function(){},onNotBottom:function(){}};var pinnable=new Headroom(t2[0],options);pinnable.init()});$("[sort]").each(function(e){if(typeof $.fn.sortable!=="function")return;let t2=$(this);if(t2.hasClass("ui-sortable"))return;let opts={delay:50,placeholder:"g_rows_helper",scrollSpeed:40,opacity:1};opts=avc(t2,"sort-axis",opts);opts=avc(t2,"sort-handle",opts);opts=avc(t2,"sort-cancel",opts);opts=avc(t2,"sort-cursor",opts,"grabbing");opts=avc(t2,"sort-helper",opts,"clone");if(opts.hasOwnProperty("helper")&&opts["helper"]!="clone"){if(typeof window[opts["helper"]]==="function")opts["helper"]=window[opts["helper"]]}opts=avc(t2,"sort-placeholder",opts);opts=avc(t2,"sort-opacity",opts);opts=avc(t2,"sort-items",opts);opts=avc(t2,"sort-tolerance",opts,"pointer");opts=avc(t2,"sort-revert",opts,false);opts=avc(t2,"sort-forcePlaceholderSize",opts);opts=avc(t2,"sort-containment",opts,"parent");opts=avc(t2,"sort-connectWith",opts);if(opts.hasOwnProperty("forceplaceholdersize")){opts["forcePlaceholderSize"]=opts["forceplaceholdersize"];delete opts["forceplaceholdersize"]}t2.sortable(opts)});$("[drag]").each(function(e){if(typeof $.fn.draggable!=="function")return;let t2=$(this);let opts={};opts=avc(t2,"drag-connectToSortable",opts);opts=avc(t2,"drag-scroll",opts,true);opts=avc(t2,"drag-revert",opts,true);opts=avc(t2,"drag-helper",opts,"clone");opts=avc(t2,"drag-containment",opts,false);opts=avc(t2,"drag-cursor",opts,"auto");opts=avc(t2,"drag-appendTo",opts,"parent");opts=avc(t2,"drag-disabled",opts,false);if(opts.disabled=="false")delete opts.disabled;if(opts.hasOwnProperty("appendto")){opts.appendTo=opts["appendto"];delete opts["appendto"]}if(opts.hasOwnProperty("helper")&&opts["helper"]!="clone"){if(typeof window[opts["helper"]]==="function")opts["helper"]=window[opts["helper"]]}if(opts.hasOwnProperty("connecttosortable")){opts["connectToSortable"]=opts["connecttosortable"];delete opts["connecttosortable"]}t2.draggable(opts)});$("[drop]").each(function(e){if(typeof $.fn.droppable!=="function")return;let t2=$(this);let opts={};opts=avc(t2,"drop-accept",opts);opts=avc(t2,"drop-greedy",opts);opts=avc(t2,"drop-hoverClass",opts);opts=avc(t2,"drop-disabled",opts,false);if(opts.disabled=="false")delete opts.disabled;if(opts.hasOwnProperty("hoverclass")){opts.hoverClass=opts["hoverclass"];delete opts["hoverclass"]}t2.droppable(opts)});$("body").on("touchstart mouseover",function(e){let isTippedOe=true;if($(e.target).closest(".oe").length){let oe=$(e.target).closest(".oe");if((oe.find("[tip]").length||oe.hasAttr("tip"))&&oe.isOverflown()&&$(window).width()>480){isTippedOe=true}else isTippedOe=false}if($(e.target).closest("[tip]").length&&isTippedOe){var target=$(e.target).closest("[tip]");var tip=`<tip class="pa ${target.attr("tip-class")}"><div class="pa [[P]]"><span>[[T]]</span></div></tip>`;if(target.find("droplet").length==0){var t2=target.attr("tip");var p=target.attr("tip-pos");if(!p)p="";$("tip").remove();$("body").append(tip.replace("[[T]]",t2).replace("[[P]]",p));_isTipped=true;let _tipSc=target;while(true){if(_isScrollable(_tipSc)||_tipSc[0]==$("body")[0])break;_tipSc=_tipSc.parent()}var self=target;_setPos(self,p,_tipSc);_setPos(self,p,_tipSc);target.data("_tipSc",_tipSc);_tipSc.unbind("scroll.kuku").bind("scroll.kuku",function(){_setPos(self,p,_tipSc)})}else{$("tip").remove();_isTipped=false}}else{$("body").unbind("scroll.kuku");$("tip").remove();_isTipped=false}});$("[numeric]").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("numeric").numeric()});$("[pattern]").each(function(){$(this).data("pattern",$(this).attr("pattern")).removeAttr("pattern")});$("[integer]:not([pve])").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("integer").numeric({decimal:false})});$("[integer][pve]").each(function(){if(typeof $.fn.numeric!=="function")return;$(this).removeAttr("integer").numeric({decimal:false,negative:false})});$("[decimal]:not([pve])").each(function(){if(typeof $.fn.numeric!=="function")return;var places=-1;if($(this).is("[dp0]"))places=0;else if($(this).is("[dp1]"))places=1;else if($(this).is("[dp2]"))places=2;else if($(this).is("[dp3]"))places=3;else if($(this).is("[dp4]"))places=4;if(places>=0)$(this).removeAttr("decimal").numeric({decimalPlaces:places,decimal:places==0?false:"."});else $(this).removeAttr("decimal").numeric({})});$("[decimal][pve]").each(function(){if(typeof $.fn.numeric!=="function")return;var places=-1;if($(this).is("[dp0]"))places=0;else if($(this).is("[dp1]"))places=1;else if($(this).is("[dp2]"))places=2;else if($(this).is("[dp3]"))places=3;else if($(this).is("[dp4]"))places=4;if(places>=0)$(this).removeAttr("decimal").numeric({negative:false,decimalPlaces:places,decimal:places==0?false:"."});else $(this).removeAttr("decimal").numeric({negative:false})});$("[time]").each(function(){dtp($(this),"time")});$("[date]").each(function(){dtp($(this),"date")});$("[datetime]").each(function(){dtp($(this),"datetime")});$("[color]").each(function(){if(typeof $.fn.colorpicker!=="function")return;$(this).removeAttr("color").colorpicker({format:"rgba"})});$("lmlst:not(.binded)").each(function(){var el=$(this);el.addClass("binded");let _conf=el.attr(":config");let conf=null;if(_conf){try{conf=typeof _evalEventScopedExpr==="function"?_evalEventScopedExpr(el[0]._ownerRe,_conf):eval(_conf)}catch(x2){conf=null}}el[0].list=new __myList(el,conf||{})})}function dtp(el2,t2){el2.removeAttr(t2);let opts={format:t2=="date"?"yyyy-mm-dd":t2=="time"?"hh:ii":"yyyy-mm-dd hh:ii",weekStart:el2.attr("date-week-start")??1,startView:t2=="time"?1:2,minView:el2.attr("minview")?el2.attr("minview"):t2=="time"?0:t2=="datetime"?0:2,maxView:el2.attr("maxview")?el2.attr("maxview"):t2=="time"?1:4,todayBtn:t2=="time"?0:el2.attr("date-today")=="false"?0:1,todayHighlight:t2=="time"?0:el2.attr("date-today")=="false"?0:1,language:el2.attr("date-lang")??"en",minuteStep:el2.attr("date-minute-step")??5,pickerPosition:"top-right",autoclose:1,showMeridian:false};if(el2.attr("date-start"))opts["startDate"]=el2.attr("date-start");if(el2.attr("date-end"))opts["endDate"]=el2.attr("date-end");if(el2.attr("date-value"))opts["date"]=el2.attr("date-value");el2.datetimepicker(opts);if(t2=="time"){el2.on("show",function(ev){$(".table-condensed > thead, .table-condensed > thead > tr > th, .table-condensed > thead > tr > th > i").attr("style","visibility: hidden; font-size:0px !Important; overflow: hidden; height: 0px;")}).on("hide",function(ev){$(".table-condensed > thead, .table-condensed > thead > tr > th, .table-condensed > thead > tr > th > i").attr("style","visibility: visible;")})}if(el2.attr("date-link-start")){el2.on("change",function(e){let dp1=el2.data("datetimepicker");let dp2=$(el2.attr("date-link-start")).data("datetimepicker");dp2.setStartDate(dp1.getFormattedDate());if(dp2.getFormattedDate()<dp1.getFormattedDate()||dp2.getFormattedDate()=="")$(el2.attr("date-link-start")).val(dp1.getFormattedDate())})}else if(el2.attr("date-link-end")){el2.on("change",function(e){let dp1=$(el2.attr("date-link-end")).data("datetimepicker");let dp2=el2.data("datetimepicker");dp1.setEndDate(dp2.getFormattedDate())});opts["useCurrent"]=false}}function avc(t2,n2,o,d=null){if(t2.attr(n2.toLowerCase()))o[n2.toLowerCase().split("sort-").join("").split("drop-").join("").split("drag-").join("")]=t2.attr(n2.toLowerCase());else if(d!=null)o[n2.toLowerCase().split("sort-").join("").split("drop-").join("").split("drag-").join("")]=d;return o}var _lmAtIndex=new Map;function _lmIndexAtEl(el2,name){var set=_lmAtIndex.get(name);if(!set){set=new Set;_lmAtIndex.set(name,set)}set.add(el2);if(set.size>5e3)set.forEach(function(e){if(!e.isConnected)set.delete(e)})}function _findByAtAttrNames(names){var out=[];var seen=new Set;for(var j=0;j<names.length;j++){var set=_lmAtIndex.get(names[j]);if(!set)continue;set.forEach(function(el2){if(seen.has(el2)||!el2.isConnected)return;if(el2.events&&el2.events[names[j]]!=null){seen.add(el2);out.push(el2)}})}try{var sel=names.map(function(n2){return"[\\"+n2+"]"}).join(",");var raw=document.querySelectorAll(sel);for(var i2=0;i2<raw.length;i2++)if(!seen.has(raw[i2])){seen.add(raw[i2]);out.push(raw[i2])}}catch(e){}return out}function _installScrollStartEndSynthesis(el2){if(el2._lumenScrollSynthInstalled)return;el2._lumenScrollSynthInstalled=true;var scrolling=false;var settleTimer=null;el2.addEventListener("scroll",function(){if(!scrolling){scrolling=true;el2.dispatchEvent(new Event("scrollstart"))}clearTimeout(settleTimer);settleTimer=setTimeout(function(){scrolling=false;el2.dispatchEvent(new Event("scrollend"))},150)},{passive:true})}function applyTriggers(){$("[click]").each(function(){$(this).trigger("click").removeAttr("click")});$("[focus]").each(function(){$(this).trigger("focus").removeAttr("focus")});let _Ns=[];for(let x2=9;x2>=0;x2--){let _els=$("[n"+x2+"]");_els.each(function(){let _el2=$(this);let _d2={};for(let y=9;y>=0;y--){if(_el2.hasAttr("n"+y)){_d2["n"+y]=_el2.attr("n"+y).split(",")}}_el2.data("_Ns",_d2);_Ns.push(_el2)})}for(let i2=0;i2<_Ns.length;i2++){const _n=_Ns[i2];let _act=[];let attrs=_n.data("_Ns");for(const nK in attrs){if(Object.hasOwnProperty.call(attrs,nK)){const nV=attrs[nK];let index=nK.slice(1);if(nV.indexOf(nodes[index])!=-1){_act.push(true)}else{_act.push(false);break}}}setTimeout(()=>{if(_act.indexOf(false)!=-1)_n.removeClass("active");else _n.addClass("active")})}if(typeof viewLoaded==="function"&&!_viewLoaded){_viewLoaded=true;viewLoaded()}var _scrollAttrEls=_findByAtAttrNames(["@scroll","@scroll-start","@scroll-end","@scroll-left","@scroll-right","@scroll-top","@scroll-bottom"]);for(var _sei=0;_sei<_scrollAttrEls.length;_sei++){_installScrollStartEndSynthesis(_scrollAttrEls[_sei])}$(_scrollAttrEls).unbind("scroll touchmove scrollstart scrollend").on("scroll touchmove scrollstart scrollend",function(ev){let el2=$(this);if(ev.type=="scrollend"){var newScrollLeft=el2.scrollLeft(),newScrollTop=el2.scrollTop(),width=el2.width(),scrollWidth=el2.get(0).scrollWidth,scrollHeight=el2.get(0).scrollHeight;var hasScX=el2.prop("scrollWidth")>el2.width();var hasScY=el2.prop("scrollHeight")>el2.height();if(newScrollLeft==0){processEv(ev,el2,"scroll-left")}else if(Math.round(scrollWidth-newScrollLeft-width-(hasScY?-_scW:0))==0){processEv(ev,el2,"scroll-right")}if(newScrollTop==0){processEv(ev,el2,"scroll-top")}else if(newScrollTop+el2.innerHeight()>=scrollHeight-(hasScX?-_scW:0)){processEv(ev,el2,"scroll-bottom")}}processEv(ev,el2,ev.type.length==6?"scroll":ev.type.split("scroll").join("scroll-"))})}_viewLoaded=false;function globalWatch(){if(!_initialized)return;$('[beajs="1"]').remove();$('script[type="beajs"]').each(function(){var html=$(this).html();$(this).remove();var myScript=document.createElement("script");myScript.setAttribute("beajs","1");myScript.textContent=html;document.body.appendChild(myScript)});let bindsCount=0;let prom=defer();prom.then(function(val2){renderPlugins();loadPics();reloads();let tickFunc2=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc2==="function")tickFunc2()}).catch(reason=>{renderPlugins();loadPics();reloads();let tickFunc2=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc2==="function")tickFunc2()});if(bindsCount==0){prom.resolve()}reloads();let tickFunc=appSettings.tick&&typeof appSettings.tick==="function"?appSettings.tick:typeof tick==="function"?tick:null;if(typeof tickFunc==="function")tickFunc()}function loadPics(){$("[lazy]").each(function(){if(typeof $.fn.lazy!=="function")return;let _el2=$(this);_el2.lazy({effect:"show",bind:"event",threshold:200,visibleOnly:false,beforeLoad:function(element){_el2.removeAttr("lazy")},afterLoad:function(element){},onError:function(element){cl("error loading "+_el2.attr("data-src"))},onFinishedAll:function(){}})})}function paraToObj(para){if(para=="")return JSON.parse("{}");return JSON.parse('{"'+decodeURI(para).replace(/"/g,'\\"').replace(/&/g,'","').replace(/=/g,'":"')+'"}')}function getBind(b,d){d=d?d.split("&"):new Array;if(b){var binder=b.split(",");for(var x2=0;x2<binder.length;x2++){var finder=binder[x2].split(" as ");if(finder[0].indexOf(" attr ")!==-1){var findz=finder[0].split(" attr ");d.push(finder[1]+"="+$.trim($(findz[0]).attr(findz[1])))}else if(finder[0].indexOf(" find ")!==-1){var findz=finder[0].split(" find ");var val2=getVal($(findz[0]).find(findz[1]));d.push(finder[1]+"="+$.trim(val2))}else if(finder[0].indexOf(" from ")!==-1){var findz=finder[0].split(" from ");if(findz[1].toLowerCase()=="ls"){d.push(finder[1]+"="+localStorage.getItem(findz[0]))}else{d.push(finder[1]+"="+findz[0])}}else d.push(finder[1]+"="+getVal($(finder[0])))}}d=d.join("&");return d}function isPathLocal(path){var local=false;var l=getLocation(path);var l2=getLocation(appSettings.Base);var url="home";local=l.hostname==l2.hostname;return local}function checkFormInputs(f,inp,classesOnly){var inputs=inp?[inp]:f.find("[\\:required]:not([disabled])");for(var i2=0;i2<inputs.length;i2++){let el2=$(inputs[i2]);let pat=el2.data("pattern");let req=el2.hasAttr(":required");let lbl=el2.closest("label");let fs=el2.closest("fieldset");let max=el2.attr("max");let max_num=el2.attr("max-num");let min_num=el2.attr("min-num");let v=el2.val();var or=el2.attr("or");if(or!=""){var or=f.find("[name='"+or+"']")}var into;let allCls="is-not-checked is-checked is-valid is-not-empty is-empty is-invalid error success not-4-chars not-on-pattern";el2.removeClass(allCls);el2.parent().removeClass(allCls);if(lbl.length)lbl.removeClass(allCls);if(fs.length)fs.removeClass(allCls);if(el2.is(":checkbox")||el2.is(":radio")){var isCheck="is-not-checked"+(req?" is-invalid":"");if(el2.is(":checked")){isCheck="is-checked"+(req?" is-valid":"")}else{if(or.length){if(or.is(":checked")){isCheck="is-checked"+(req?" is-valid":"")}}}if(el2.is(":radio")){f.find("[name='"+el2.attr("Name")+"']:radio").not(el2[0]).each(function(){let _el2=$(this);let _req=_el2.hasAttr(":required");var _isCheck="is-not-checked"+(_req?" is-invalid":"");var _or=_el2.attr("or");let _lbl=_el2.closest("label");_el2.removeClass(allCls);_el2.parent().removeClass(allCls);if(_lbl.length)_lbl.removeClass(allCls);if(_or!=""){var _or=f.find("[name='"+_or+"']")}if(_el2.is(":checked")){_isCheck="is-checked"+(_req?" is-valid":"")}else{if(_or.length){if(_or.is(":checked")){_isCheck="is-checked"+(_req?" is-valid":"")}}}if(_el2.parent().prop("nodeName")!="FORM")_el2.parent().addClass(_isCheck);if(_lbl.length)_lbl.addClass(_isCheck);_el2.addClass(_isCheck)})}if(el2.parent().prop("nodeName")!="FORM")el2.parent().addClass(isCheck);if(lbl.length)lbl.addClass(isCheck);el2.addClass(isCheck)}else{var isV="is-empty"+(req?" is-invalid":"");if(el2.is("[username]")){if(v.length&&v.length<4){isV="not-4-chars is-not-empty"+(req?" is-invalid":"")}else{let vld=true;var k=v.match(/[a-z]+(?!\.)(?!.*\.$)(?!.*?\_\_)[a-z0-9_]+[a-z0-9]/);if(!k){vld=false}else{if(k.input!=k[0]){vld=false}}if(vld)isV="is-not-empty"+(req?" is-valid":"");else isV="not-on-pattern is-not-empty"+(req?" is-invalid":"")}}else if(el2.is("[password]")){if(!passwordValid(v)){isV="is-not-empty"+(req?" is-invalid":"")}else{isV="is-not-empty"+(req?" is-valid":"")}}else if(el2.is("[rpassword]")){if($.trim(v)!=$.trim(f.find("[password]").val())){isV="is-not-empty"+(req?" is-invalid":"")}else{isV="is-not-empty"+(req?" is-valid":"")}}else{if($.trim(v).length!=0){if(max&&!isNaN(max)){if($.trim(v).length>max){el2.val($.trim($.trim(v).substr(0,max)))}}if(min_num&&!isNaN(min_num)){if(!isNaN($.trim(v))){if(parseFloat($.trim(v))<parseFloat(min_num))el2.val($.trim(min_num))}else{el2.val(min_num)}}if(max_num&&!isNaN(max_num)){if(!isNaN($.trim(v))){if(parseFloat($.trim(v))>parseFloat(max_num))el2.val($.trim(max_num))}else{if(min_num&&!isNaN(min_num))el2.val($.trim(min_num));else el2.val("0")}}isV="is-not-empty";if(pat){pat=new RegExp(pat);if(pat.test($.trim(v))){isV+=req?" is-valid":""}else{isV+=req?" is-invalid":"";el2.val("")}}else isV+=req?" is-valid":""}else{if(or.length){if($.trim(or.val()).length!=0){isV="is-not-empty"+(req?" is-valid":"")}}}}if(el2.parent().prop("nodeName")!="FORM")el2.parent().addClass(isV);if(lbl.length)lbl.addClass(isV);el2.addClass(isV)}var isRadioChecked=false;if(el2.is(":radio")){if(el2.hasClass("is-invalid")){f.find("[name='"+el2.attr("Name")+"']:radio").not(el2[0]).each(function(){if($(this).hasClass("is-valid")){isRadioChecked=true}})}else{isRadioChecked=true}}if(el2.hasClass("is-invalid")||el2.is(":radio")&&!isRadioChecked){if(el2.hasAttr("data-into")){let intoTxt=el2.data("into");if(lbl.length)into=lbl.find(intoTxt);if(!into){if(fs.length)into=fs.find(intoTxt)}if(!into)into=$(intoTxt);if(into.length){if(el2.is("[password]")){if($.trim(v).length==0)into.text(el2.attr("data-empty"));else if(el2.hasAttr("data-wpm"))into.text(el2.attr("data-wpm"));let rpass=f.find("[rpassword]");if(rpass.length){if($.trim(rpass.val()).length!=0)checkFormInputs(f,rpass,true)}}else if(el2.is("[rpassword]")){if($.trim(v).length==0)into.text(el2.attr("data-empty"));else if(el2.hasAttr("data-pnm"))into.text(el2.attr("data-pnm"))}else if(el2.is("[username]")){let txt=el2.hasAttr("data-empty")?el2.attr("data-empty"):el2.attr("placeholder");if($.trim(v).length==0)into.text(txt);else{if(el2.hasClass("not-4-chars")){if(el2.hasAttr("data-4-chars"))txt=el2.attr("data-4-chars")}else if(el2.hasClass("not-on-pattern")){if(el2.hasAttr("data-chars-not-allowed"))txt=el2.attr("data-chars-not-allowed")}into.text(txt)}}else if(el2.hasAttr("data-empty")){into.text(el2.attr("data-empty"))}else{if(el2.is(":checkbox")||el2.is(":radio")){into.text(el2.attr("placeholder"))}else{into.text(el2.attr("placeholder"))}}}}if(!classesOnly){if(el2.is(":radio")){if(!isRadioChecked){if(fs.length)fs.addClass(isCheck);el2.focus();return false}}else{if(fs.length)fs.addClass(isV);el2.focus();return false}}else{if(el2.is(":radio")){if(!isRadioChecked){if(fs.length)fs.addClass(isCheck)}}else{if(fs.length)fs.addClass(isV)}}}else if(el2.hasClass("is-valid")){if(el2.hasAttr("data-into")){let intoTxt=el2.data("into");if(lbl.length)into=lbl.find(intoTxt);if(fs.length)into=fs.find(intoTxt);if(!into)into=$(intoTxt);if(into.length){into.text("")}}}}return true}function validateInputs(f){if(f.hasAttr("ax-before")){var bfs=f.attr("ax-before");if(typeof window[bfs]==="function"){if(window[bfs](f)===false)return false}}var inps=[];f.find("input.required,select.required,textarea.required").each(function(){inps.push($(this).attr("name"))});for(var i2=0;i2<inps.length;i2++){var inp=f.find("input[name='"+inps[i2]+"']");var sel=f.find('select[name="'+inps[i2]+'"]');var txt=f.find('textarea[name="'+inps[i2]+'"]');var e=inp;if(!e.length)e=sel;if(!e.length)e=txt;var or=e.attr("or");if(or!=""){var inp2=f.find("input[name='"+or+"']");var sel2=f.find('select[name="'+or+'"]');var txt2=f.find('textarea[name="'+or+'"]');var or=inp2;if(!or.length)or=sel2;if(!or.length)or=txt2}if(e.is(":checkbox")||e.is(":radio")){if(!e.is(":checked")){if(or.length){if(!or.is(":checked")){alert(e.attr("placeholder")+" or "+or.attr("placeholder"));e.addClass("error");e.focus();return false}}else{alert(e.attr("placeholder"));e.addClass("error");e.focus();return false}}}else{if($.trim(e.val()).length==0){if(or.length){if($.trim(or.val()).length==0){alert(e.attr("placeholder")+" or "+or.attr("placeholder"));e.addClass("error");e.focus();return false}}else{alert(e.attr("placeholder"));e.addClass("error");e.focus();return false}}if(e.is("[password]")){if(!passwordValid(e.val())){alert(e.attr("data-wpm"));e.addClass("error");e.focus();return false}}if(e.is("[rpassword]")){if($.trim(e.val())!=$.trim(e.closest("form").find("[password]").val())){e.addClass("error");alert(e.attr("data-pnm"));e.focus();return false}e.removeClass("error");$(".passStrength").remove()}}}return true}let _cookies={getItem:function(sKey){if(!sKey){return null}return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(sKey,sValue,vEnd,sPath,sDomain,bSecure){if(!sKey||/^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)){return false}var sExpires="";if(vEnd){switch(vEnd.constructor){case Number:sExpires=vEnd===Infinity?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+vEnd;break;case String:sExpires="; expires="+vEnd;break;case Date:sExpires="; expires="+vEnd.toUTCString();break}}if(!sPath)sPath="/";document.cookie=encodeURIComponent(sKey)+"="+encodeURIComponent(sValue)+sExpires+(sDomain?"; domain="+sDomain:"")+(sPath?"; path="+sPath:"")+(bSecure?"; secure":"");return true},removeItem:function(sKey,sPath,sDomain){if(!this.hasItem(sKey)){return false}if(!sPath)sPath="/";document.cookie=encodeURIComponent(sKey)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(sDomain?"; domain="+sDomain:"")+"; path="+sPath;return true},hasItem:function(sKey){if(!sKey){return false}return new RegExp("(?:^|;\\s*)"+encodeURIComponent(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){var aKeys=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/);for(var nLen=aKeys.length,nIdx=0;nIdx<nLen;nIdx++){aKeys[nIdx]=decodeURIComponent(aKeys[nIdx])}return aKeys}};var cookies=new Proxy(_cookies,{get(target,key){return target[key]??target.getItem(key)??void 0},set(target,key,value){if(key in target){return false}return target.setItem(key,value)},deleteProperty(target,key){if(!(key in target)){return false}return target.removeItem(key)},ownKeys(target){return target.keys()},has(target,key){return key in target||target.hasItem(key)},defineProperty(target,key,descriptor){if(descriptor&&"value"in descriptor){target.setItem(key,descriptor.value)}return target},getOwnPropertyDescriptor(target,key){const value=target.getItem(key);return value?{value,enumerable:true,configurable:true}:void 0}});function getCookie(n2){return cookies[n2]}function setCookie(n2,v,d,p,e){var now=new Date;var time=now.getTime();if(!e)e=time+24*60*60*1e3*365;else e=time+e;if(!d)d=window.location.hostname;if(!p)p="/";now.setTime(e);return cookies.setItem(n2,v,now.toGMTString(),p,d,true)}function getComData(c,fromHTML){if(fromHTML){try{var el2=$("<div></div>");el2.html(c.html());var k={};var mtitle=$("modal-title",el2).html();if(!mtitle)mtitle="";var mbody=$("modal-body",el2).html();if(!mbody)mbody="";var mdesc=$("modal-description",el2).html();if(!mdesc)mdesc="";var mfoot=$("modal-footer",el2).html();if(!mfoot)mfoot="";k.Title=mtitle;k.Body=mbody;k.Description=mdesc;k.Footer=mfoot;c=k;return c}catch(e){return false}return false}try{c=c.contents().filter(function(){return this.nodeType===8}).get(0);if(c.nodeValue=="")return false;try{c=JSON.parse(c.nodeValue)}catch(e){try{c=JSON.parse(atob(c.nodeValue))}catch(e2){try{var el2=$("<div></div>");el2.html(c.nodeValue);var k={};var mtitle=$("modal-title",el2).html();if(!mtitle)mtitle="";var mbody=$("modal-body",el2).html();if(!mbody)mbody="";var mdesc=$("modal-description",el2).html();if(!mdesc)mdesc="";var mfoot=$("modal-footer",el2).html();if(!mfoot)mfoot="";k.Title=mtitle;k.Body=mbody;k.Description=mdesc;k.Footer=mfoot;c=k}catch(e3){return false}}}return c}catch(e){return false}}function addOrChangeParameters(url,params){let splitParams={};let splitPath=/(.*)[?](.*)/.exec(url);if(splitPath&&splitPath[2])splitPath[2].split("&").forEach(k=>{let d=k.split("=");splitParams[d[0]]=d[1]});let newParams=Object.assign(splitParams,params);let finalParams=Object.keys(newParams).map(a=>a+"="+newParams[a]).join("&");return splitPath?splitPath[1]+"?"+finalParams:url+"?"+finalParams}class BEA{Cart=null;Products=null;Authorize=null;Pay=null;localCache=true;_prom=null;proms=[];l="En";fields={Section:"Section,Title,Text",Product:"Name,Price,Quantity"};constructor(options){if(options===void 0)options={};if(!Object.keys(options).length==0){if(options.hasOwnProperty("fields")){for(var i2 in options["fields"]){this.fields[i2]=options["fields"][i2]}}if(options.hasOwnProperty("localisation"))this.l=options.localisation;if(options.hasOwnProperty("locale")&&options.locale===true){this.getLocale()}if(options.hasOwnProperty("sections")&&options.sections===true){this.getSections()}if(options.hasOwnProperty("localCache")&&options.localCache===false){this.localCache=false}}this.Cart=new Cart(this);this.Products=new Products(this);this.Authorize=new Authorize(this);this.Pay=new Pay(this);this._prom=Promise.all(this.proms)}request(className,data2,async,type2,a){var prom=defer();var x2;API.req(className,data2,null,type2,a??0).then(r2=>{if(async){prom.resolve(r2)}else{x2=r2.results}});if(async)return prom;return x2}getSections(){var sec=new Section(this);this.proms.push(sec._prom);return sec.get()}getLocale(){var loc=new Locale(this);this.proms.push(loc._prom);return loc.get()}order(){let prom=defer();var ids="";var productsInfo;var user;var orderData={User:"",productItems:[],Amount:0};user=this.Authorize.me();orderData.User=user.objectId;$.each(this.Cart.cartData,function(key,value){ids=ids+value.P+","});this.Products.get({fields:"Name,Price,Quantity",media:"images",crops:"ax200,ax600,ax700,200x200,ax300"},{ids},true).then(res=>{let productsInfo2=res.results;var productsDB=Object.assign({},...productsInfo2.map(x2=>({[x2.objectId]:x2})));$.each(this.Cart.cartData,function(key,value){orderData.productItems.push({Qty:value.Q,Product:value.P,productData:JSON.stringify(productsDB[value.P]),Price:productsDB[value.P].Price});orderData.Amount+=value.Q*productsDB[value.P].Price});this.request("/Order",{User:orderData.User,Amount:orderData.Amount},true,"POST").then(res2=>{let orderId=res2.results;for(var i2=0;i2<orderData.productItems.length;i2++){orderData.productItems[i2]["Order"]=orderId[0].objectId;this.request("/orderItems ",orderData.productItems[i2],true,"POST")}prom.resolve(orderId)})});return prom}sendEmail(data2){let prom=defer();this.request("/_Emails/send",data2,true,"POST").then(res=>{prom.resolve(r)})}batch(data2){return this.request("/batch",data2,true,"POST")}query(className,data2){return this.request(className,data2,true,"GET")}get(className,data2,options=true){return this.request(className,data2,options,"GET")}post(className,data2,options=true){return this.request(className,data2,options,"POST")}put(className,data2,options=true){return this.request(className,data2,options,"PUT")}delete(className,options=true){return this.request(className,"",options,"DELETE")}}class Pay{tsdk=null;object={};constructor(tsdk){this.tsdk=tsdk;let self=this;$(window).unbind("message").on("message",function(e){let dd=$("#gosell-gateway")[0].contentWindow;if(e.originalEvent.source===dd&&e.originalEvent.data=="close"){$(".gosell-gateway").remove();self.onClose()}})}create(data2){let prom=defer();API.post("https://pay.bea.com.lb/create",data2,{},666).then(d=>{this.object=d;cl(d);this.process(this.object.transaction.url.replace("mode=page","mode=popup"));prom.resolve(this.object.id)}).catch(err=>{cl(err)});return prom}process(link){var d=`
|
|
37
37
|
<div class="gosell-gateway" reactive>
|
|
38
38
|
<div style="position: fixed;left: 0;right: 0;top: 0;bottom: 0;z-index: 9999;background-color: rgb(0,0,0,0.2);">
|
|
39
39
|
<iframe id="gosell-gateway"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# AGENTS.md — LumenJS project
|
|
2
|
+
|
|
3
|
+
This is a **LumenJS V2** project (`@lmjs/cli` + `@lmjs/core`). LumenJS is not Vue or React. Before writing or
|
|
4
|
+
changing any `.view` file, read the framework reference:
|
|
5
|
+
|
|
6
|
+
- Short guide: https://lumenjs.com/llms.txt
|
|
7
|
+
- Full reference: https://lumenjs.com/llms/lumenjs.txt
|
|
8
|
+
|
|
9
|
+
## Layout
|
|
10
|
+
|
|
11
|
+
- `src/views/*.view` (pages and sub-views), `src/layouts/*.layout`, `src/tpls/` (row templates), `src/index.js`
|
|
12
|
+
(app start-up), `src/index.html`.
|
|
13
|
+
- `src/js/lm.js` is the framework runtime copied into this project. Don't edit it. After upgrading
|
|
14
|
+
`@lmjs/cli`, run `lm update-core` before building.
|
|
15
|
+
|
|
16
|
+
## Commands
|
|
17
|
+
|
|
18
|
+
- `lm serve`: dev server. `lm build`: production build into `dist/`. `lm build --deploy`: build, then upload
|
|
19
|
+
`dist/` using `config.json`'s `ftp` block.
|
|
20
|
+
- `lm create -v name` / `-s name` / `-t name`: new view / sub-view / layout.
|
|
21
|
+
- Pin a version without a global install: `npx -y -p @lmjs/cli@<version> lm <command>`.
|
|
22
|
+
|
|
23
|
+
## Rules that are easy to get wrong
|
|
24
|
+
|
|
25
|
+
- Top-level `var`/`let`/`const` in a view's `<script>` is reactive. There is no `bind=`.
|
|
26
|
+
- A function call inside `{{ }}` is not re-run when its data changes. Keep the value in a variable.
|
|
27
|
+
- A `{{ }}` value that looks like HTML is rendered as HTML. Escape untrusted text yourself.
|
|
28
|
+
- Attribute order is priority: `<i :if="a" :for="xs as x">` gates the loop; `<i :for="xs as x" :if="x.on">`
|
|
29
|
+
filters rows.
|
|
30
|
+
- `tpl="name"` works only on a `:for` element. `comp=` no longer exists.
|
|
31
|
+
- Each mounted sub-view (`view="..."`) has its own variables. Pass data in with `@init`, not `:data`.
|
|
32
|
+
- There is no `session` global: use `sessionStorage`.
|
|
33
|
+
- Never put API secrets in `config.json`. Use `lm login` + `lm api set <name>`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@AGENTS.md
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmjs/cli",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.3",
|
|
4
4
|
"description": "Command line interface for LumenJS — scaffold, develop, and build LumenJS applications. LumenJS is a tiny, fast reactive JavaScript framework for building web applications and interfaces with standard HTML, CSS, and JavaScript.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"lm": "./dist/bin/commands.js",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"ora": "^6.1.2",
|
|
53
53
|
"semver": "^7.3.7",
|
|
54
54
|
"ws": "^8.8.1",
|
|
55
|
-
"@lmjs/core": "2.5.
|
|
55
|
+
"@lmjs/core": "2.5.3"
|
|
56
56
|
},
|
|
57
57
|
"engines": {
|
|
58
58
|
"node": ">=18.0.0"
|