@lmjs/cli 1.0.51 → 2.0.1
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/LICENSE +0 -0
- package/README.md +5 -16
- package/dist/bin/commands.js +2 -0
- package/dist/lib/app.js +3 -0
- package/dist/lib/check-version.js +2 -0
- package/dist/lib/fcs.js +11 -0
- package/{lib → dist/lib}/files/build_serverless/.htaccess +0 -0
- package/{lib/files/build/src → dist/lib/files/build_serverless}/favicon.ico +0 -0
- package/{lib/files/build/src → dist/lib/files/build_serverless}/robots.txt +0 -0
- package/{lib/files/build/src → dist/lib/files/build_serverless}/sitemap.xml +0 -0
- package/dist/lib/files/layout.layout +4 -0
- package/dist/lib/files/libs/bea.css +1 -0
- package/dist/lib/files/libs/lm-with-plugins.js +539 -0
- package/dist/lib/files/libs/lm.js +30 -0
- package/dist/lib/files/libs/lumenjs-plugins.css +2822 -0
- package/{lib → dist/lib}/files/project/config.json +1 -1
- package/dist/lib/files/project/package.json +6 -0
- package/{lib → dist/lib}/files/project/src/404.html +1 -1
- package/{lib → dist/lib}/files/project/src/index.html +3 -3
- package/dist/lib/files/project/src/index.js +1 -0
- package/dist/lib/files/project/src/layouts/default.layout +4 -0
- package/{lib → dist/lib}/files/project/src/views/home.view +2 -3
- package/{lib → dist/lib}/files/sub_view.view +0 -0
- package/dist/lib/files/view.view +13 -0
- package/dist/lib/npm-bundle.js +1 -0
- package/dist/lib/plugins-esbuild-plugin.js +3 -0
- package/package.json +37 -19
- package/bin/commands.js +0 -2
- package/lib/app.js +0 -132
- package/lib/check-version.js +0 -28
- package/lib/fcs.js +0 -804
- package/lib/files/build/func.js +0 -102
- package/lib/files/build/package.json +0 -31
- package/lib/files/build/server.js +0 -58
- package/lib/files/build_serverless/favicon.ico +0 -0
- package/lib/files/build_serverless/robots.txt +0 -4
- package/lib/files/build_serverless/sitemap.xml +0 -9
- package/lib/files/project/src/index.js +0 -15
- package/lib/files/project/src/tpls/tpl1.tpl +0 -1
- package/lib/files/project/src/views/widgets/footer.view +0 -0
- package/lib/files/project/src/views/widgets/header.view +0 -0
- package/lib/files/project/src/views/widgets/nav.view +0 -0
- package/lib/files/tpl.tpl +0 -1
- package/lib/files/view.view +0 -14
- /package/{lib → dist/lib}/files/project/src/images/lumenjs.svg +0 -0
package/LICENSE
CHANGED
|
File without changes
|
package/README.md
CHANGED
|
@@ -64,28 +64,17 @@ lm purge
|
|
|
64
64
|
|
|
65
65
|
|
|
66
66
|
|
|
67
|
-
Build A
|
|
68
|
-
```
|
|
69
|
-
lm build --serverless
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
Build A Serverless Dist For Production Version & Deploy It Directly
|
|
75
|
-
```
|
|
76
|
-
lm build --serverless --deploy
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
Build A Dist For Production Version + NodeJs Server
|
|
67
|
+
Build A Dist For Production Version
|
|
82
68
|
```
|
|
83
69
|
lm build
|
|
84
70
|
```
|
|
71
|
+
(`--serverless` is accepted but no longer changes anything — this is the only
|
|
72
|
+
build output now. The old Node-server build mode was removed: nobody's own
|
|
73
|
+
projects actually shipped it, and it's not maintained going forward.)
|
|
85
74
|
|
|
86
75
|
|
|
87
76
|
|
|
88
|
-
Build A Dist For Production Version
|
|
77
|
+
Build A Dist For Production Version & Deploy It Directly
|
|
89
78
|
```
|
|
90
79
|
lm build --deploy
|
|
91
80
|
```
|
package/dist/lib/app.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var fs=require("fs");const path=require("path");const chokidar=require("chokidar");const express=require("express");var compression=require("compression");const app=express();const server=require("http").createServer(app);var WebSocketServer=require("ws").Server;var wss=new WebSocketServer({server,path:"/"});const fcs=require("./fcs.js");var cl=console.log;var cookieParser=require("cookie-parser");var expressSession=require("express-session");const bodyParser=require("body-parser");var multer=require("multer");var upload=multer();let session=expressSession({secret:"keyboardcat",resave:true,saveUninitialized:true,cookie:{maxAge:9999e3}});var config=fcs.getConfig();var _views={};var _layouts={};var _compiledScripts={};(function buildCompiledScriptsMap(){try{var projectRoot=`${process.cwd()}`;var srcRoot=projectRoot+path.sep+`src`;var hasOwnDeps=fcs.hasOwnDependencies(projectRoot);var indexJsPath=srcRoot+path.sep+"index.js";if(fs.existsSync(indexJsPath)){var indexJsSrc=hasOwnDeps?fcs.buildEntryWithImports(indexJsPath,projectRoot):fs.readFileSync(indexJsPath,"utf8");_compiledScripts["/index.js"]=fcs.compileProjectScript(indexJsSrc,"index")}var indexHtmlPath=srcRoot+path.sep+"index.html";if(fs.existsSync(indexHtmlPath)){var localSrcs=fcs.detectLocalProjectScripts(fs.readFileSync(indexHtmlPath,"utf8"));for(const src of localSrcs){var scriptPath=srcRoot+src.split("/").join(path.sep);if(fs.existsSync(scriptPath)){var scriptSrc=hasOwnDeps?fcs.buildEntryWithImports(scriptPath,projectRoot):fs.readFileSync(scriptPath,"utf8");_compiledScripts[src]=fcs.compileProjectScript(scriptSrc,src)}}}}catch(e){cl("Failed to compile index.js / project scripts for reactivity \u2014 serving them raw. "+e.message)}})();var _pluginsJs=null;var _pluginsCss=null;(async function buildSelectedPluginsBundle(){try{var projectRoot=`${process.cwd()}`;var selected=fcs.selectedProjectPlugins(projectRoot);if(!selected.length)return;var pluginsEsbuild=require(path.join(__dirname,"plugins-esbuild-plugin.js"));_pluginsJs=await pluginsEsbuild.buildSelectedPluginsBundle(selected,projectRoot);_pluginsCss=await pluginsEsbuild.buildSelectedCss(selected,projectRoot+path.sep+"node_modules");var indexHtmlPath=projectRoot+path.sep+"src"+path.sep+"index.html";if(fs.existsSync(indexHtmlPath)){var html5=fs.readFileSync(indexHtmlPath,"utf8");var tags="";if(html5.indexOf("/js/lumenjs-plugins.js")==-1){tags+=`
|
|
2
|
+
<script src="/js/lumenjs-plugins.js" type="text/javascript"><\/script>`}if(_pluginsCss&&_pluginsCss.trim()!=""&&html5.indexOf("/css/lumenjs-plugins.css")==-1){tags+=`
|
|
3
|
+
<link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />`}if(tags!=""){fs.writeFileSync(indexHtmlPath,html5.split("</head>").join(tags+"\n</head>"))}}}catch(e){cl("Failed to build the selective plugins bundle \u2014 "+e.message)}})();app.use(compression());app.use(cookieParser());app.use(session);app.use("/",function(req,res,next){if(Object.prototype.hasOwnProperty.call(_compiledScripts,req.path)){res.type("application/javascript").send(_compiledScripts[req.path]);return}if(req.path==="/js/lumenjs-plugins.js"&&_pluginsJs!=null){res.type("application/javascript").send(_pluginsJs);return}if(req.path==="/css/lumenjs-plugins.css"&&_pluginsCss!=null){res.type("text/css").send(_pluginsCss);return}next()});app.use("/",express.static(`${process.cwd()}`+path.sep+`src`));app.set("etag",false);app.use(bodyParser.urlencoded({extended:true}));app.use(bodyParser.json());app.use(bodyParser.raw());app.use(upload.array());wss.on("connection",ws=>{ws.on("message",async message=>{try{const buffer=Buffer.from(message);const data=JSON.parse(buffer.toString());if(data.hasOwnProperty("e")){var _data={"e":data.e,"_iter":data._iter,"payload":{}};if(data.e=="getfiles"){_data["payload"]={"hstFormatVersion":fcs.HST_FORMAT_VERSION,"views":_views,"layouts":_layouts}}else if(data.e=="getlayout"){_data.payload=_layouts[data.payload]}else if(data.e=="getview"){_data.payload=_views[data.payload]}else if(data.e=="request"){try{let pata=data.payload;let __data=pata["data"];let _body=pata["body"];var resa=await API.req(_body["path"],__data,_body["headers"],_body["method"],_body["api"],true);let res=await resa.text();try{res=JSON.parse(res)}catch(e){}_data.payload=_body["full"]?{"headers":resa.headers,"data":res}:res;ws.send(JSON.stringify(_data))}catch(e){_data.payload={"code":108,"error":e.message,"type":"RequestError"};ws.send(JSON.stringify(_data))}return}ws.send(JSON.stringify(_data))}}catch(e){}})}).on("error",e=>{});global.app=app;var fetch=fcs.fetch;global.fetch=fetch;global.wss=wss;global.fs=fs;global.path=path;var API=fcs.API;global.API=API;if(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`app.js`)){require(`${process.cwd()}`+path.sep+`src`+path.sep+`app.js`)}app.get("*",function(req,res){let nodes=req.params[0].split("/");if(nodes.length)nodes.shift();res.sendFile(`${process.cwd()}`+path.sep+`src`+path.sep+(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep+nodes[0]+`.view`)?"index":"404")+`.html`);return});app.post("*",function(req,res){let nodes=req.params[0].split("/");if(nodes.length)nodes.shift();res.sendFile(`${process.cwd()}`+path.sep+`src`+path.sep+(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep+nodes[0]+`.view`)?"index":"404")+`.html`);return});function broadcastFilesChanged(){wss.clients.forEach(function(client){if(client.readyState===1){client.send(JSON.stringify({e:"files-changed"}))}})}chokidar.watch(`${process.cwd()}`+path.sep+`src`+path.sep+`views`,{ignoreInitial:true}).on("all",function(){_views=fcs.getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);broadcastFilesChanged()});chokidar.watch(`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`,{ignoreInitial:true}).on("all",function(){_layouts=fcs.getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep,{},false,true);broadcastFilesChanged()});server.listen(config.server.port>0?config.server.port:0,function(err){cl(`LumenJS server running at http://${config.server.host}:${config.server.port>0&&server.address().port==config.server.port?config.server.port:server.address().port}/`);config.server.port=server.address().port;_views=fcs.getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);_layouts=fcs.getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep,{},false,true)}).on("error",e=>{if(e.code==="EADDRINUSE"){cl("Port "+config.server.port+" is already in use..");server.close();server.listen(0)}});
|
package/dist/lib/fcs.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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");var _min=require("html-minifier").minify;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"));function selectedProjectPlugins(projectRoot){try{const pkgPath=path.join(projectRoot,"package.json");if(!fs.existsSync(pkgPath))return[];const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));if(!pkg.dependencies)return[];return _pluginsBundle.selectedRegistryEntries(pkg.dependencies)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;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 detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")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=1;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;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 applyWithPlugins(filePath,libsPath){let pluginsJsSrc=libsPath+path.sep+"lm-with-plugins.js";let pluginsCssSrc=libsPath+path.sep+"lumenjs-plugins.css";if(!fs.existsSync(pluginsJsSrc)||!fs.existsSync(pluginsCssSrc)){console.log("--with-plugins was requested, but "+pluginsJsSrc+" / "+pluginsCssSrc+" aren't present in this CLI install \u2014 falling back to the default (no-plugins) build. Run the with-plugins build in packages/core first.");return}fs.writeFileSync(filePath+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",fs.readFileSync(pluginsJsSrc));fs.writeFileSync(filePath+path.sep+"src"+path.sep+"css"+path.sep+"lumenjs-plugins.css",fs.readFileSync(pluginsCssSrc));let indexHtmlPath=filePath+path.sep+"src"+path.sep+"index.html";if(fs.existsSync(indexHtmlPath)){let html5=fs.readFileSync(indexHtmlPath,"utf8");if(html5.indexOf("lumenjs-plugins.css")==-1){html5=html5.replace('<link href="/css/styles.css" rel="stylesheet" type="text/css" />','<link href="/css/styles.css" rel="stylesheet" type="text/css" />\n <link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />');fs.writeFileSync(indexHtmlPath,html5)}}}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;require("dns").resolve("www.google.com",function(err){if(!err){if(!fs.existsSync(libsPath+path.sep+"lm.js"))getLibs=true}if(getLibs){API.get(CORE_Libs.COREJS,{}).then(corejs=>{API.get(CORE_Libs.BEACSS,{}).then(beacss=>{var libsPath2=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath2);fs.writeFileSync(libsPath2+path.sep+"lm.js",String(corejs));fs.writeFileSync(libsPath2+path.sep+"bea.css",String(beacss));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+"bea.css",String(beacss));if(conf.withPlugins)applyWithPlugins(filePath3,libsPath2)})}).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 beacss=Buffer.from(fs.readFileSync(libsPath+path.sep+"bea.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+"bea.css",String(beacss));if(conf.withPlugins)applyWithPlugins(filePath2,libsPath)}})}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}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?(".*?"|'.*?')/g;tagRE=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;whitespaceRE=/^\s*$/;empty=Object.create(null);reactiveVariables=[];constructor(html){let hst2=this.parse(html);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);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);this.reactiveVariables.push(res.forX.js)}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);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}}}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]);if(_t.substring(_m.index-1,1)!="`"){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,"jst":JST,"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 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){if(tag!=="</"+current.name+">"){return""}else{inComponent=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"&¤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=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"?{jst:acorn.parse(hl,{ecmaVersion:"latest"})}:{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);if(par.whitespaceRE.test(content)){content=" "}if(_end>-1&&level+parent.length>=0||content!==" "){if(parent&&Array.isArray(parent)){if(content!==" "){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);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;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 withPlugins=process.argv.includes("--with-plugins");let c=process.argv.slice(3,process.argv.length).filter(a=>a!="--with-plugins");let t=lw(c[0]);create({type:t[0]=="-"?t.split("-").join(""):t,name:t[0]=="-"?c.slice(1,c.length):c,withPlugins})}else if(command=="purge"){import("ora").then(async({default:ora,oraPromise})=>{const spinner=ora({color:"green"});spinner.start("Purging..");try{const corejsRes=await API.req(CORE_Libs.COREJS,{},void 0,"GET",void 0,true);if(!corejsRes.ok)throw new Error("fetching core JS failed: HTTP "+corejsRes.status);const corejs=await corejsRes.text();if(!corejs||corejs.length<1e3||/^\s*<(!doctype|html)/i.test(corejs)){throw new Error("fetched core JS doesn't look valid ("+(corejs?corejs.length:0)+" bytes, possibly an error page) \u2014 refusing to overwrite the real bundle")}spinner.start("Gathering Resources..");const beacssRes=await API.req(CORE_Libs.BEACSS,{},void 0,"GET",void 0,true);if(!beacssRes.ok)throw new Error("fetching core CSS failed: HTTP "+beacssRes.status);const beacss=await beacssRes.text();if(beacss==null||/^\s*<(!doctype|html)/i.test(beacss)){throw new Error("fetched core CSS doesn't look valid \u2014 refusing to overwrite")}spinner.start("Writing Files...");var filePath=`${process.cwd()}`;var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath);fs.writeFileSync(libsPath+path.sep+"lm.js",String(corejs));fs.writeFileSync(libsPath+path.sep+"bea.css",String(beacss));fs.writeFileSync(filePath+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath+path.sep+"src"+path.sep+"css"+path.sep+"bea.css",String(beacss));spinner.succeed("Successfully Purged!")}catch(err){spinner.fail("Purge Failed! "+(err&&err.message?err.message:""))}})}else if(command=="build"){let cmds=process.argv;_bp(cmds)}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()}`;var dest=projectPath+path.sep+"dist";let _views=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);let _layouts=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep,{},false,true);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");var beaCSSCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"css"+path.sep+"bea.css","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 vt=`
|
|
2
|
+
var _vcData = {
|
|
3
|
+
"hstFormatVersion": `+HST_FORMAT_VERSION+`,
|
|
4
|
+
"views": `+JSON.stringify(_views)+`,
|
|
5
|
+
"layouts": `+JSON.stringify(_layouts)+`
|
|
6
|
+
};
|
|
7
|
+
`;try{let _indexJsSrc=_hasOwnDeps?_npmBundle.buildEntryWithImports(projectPath+path.sep+"src"+path.sep+"index.js",projectPath):String(indexJs);vt+=_compiledScripts+"\n"+compileProjectScript(_indexJsSrc,"index")}catch(e){spinner.fail("Error compiling index.js: "+(e&&e.message?e.message:e));spinner.fail("Build Failed! Fix index.js and try again.");return}indexCode=indexCode.split('<script src="/index.js" defer type="text/javascript"><\/script>').join("").split('<script src="/index.js" type="text/javascript"><\/script>').join("");spinner.succeed("Gathering Required Resources").start("Signing & Securing App..");let r=await API.post("https://www.beaapis.com/1/beajs",{data:{apis:JSON.stringify(config.apis),js:vt}});let token_=r.token;let js_="";js_+=`
|
|
8
|
+
var _beaTn = "`+token_+`";
|
|
9
|
+
`;let ownRuntime=fs.readFileSync(projectPath+path.sep+"src"+path.sep+"js"+path.sep+"lm.js","utf8");js_+=ownRuntime+"\n"+vt;if(token_==""){spinner.fail("Error getting a unique token for production!");spinner.fail("Build Failed! Try again later.");return}spinner.succeed("Signing & Securing App").start("Packing & Cleaning...");rd(dest);spinner.succeed("Packing & Cleaning").start("Writing Files...");let buildPath=`build_serverless`;copyDir(`${__dirname}`+path.sep+`files`+path.sep+buildPath,dest);copyDir(projectPath+path.sep+"src",dest,"_beajsBuild");cd(dest+path.sep+"js");cd(dest+path.sep+"css");cd(dest+path.sep+"images");copyDir(projectPath+path.sep+"src"+path.sep+"js",dest+path.sep+"js","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"css",dest+path.sep+"css","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"images",dest+path.sep+"images","_beajsBuild");fs.writeFileSync(dest+path.sep+"js"+path.sep+"lm.js",String(js_));fs.writeFileSync(dest+path.sep+"css"+path.sep+"bea.css",String(beaCSSCode));let _dT=new Date().getTime();fs.renameSync(dest+path.sep+"js"+path.sep+"lm.js",dest+path.sep+"js"+path.sep+"app."+_dT+".js");fs.renameSync(dest+path.sep+"css"+path.sep+"bea.css",dest+path.sep+"css"+path.sep+"app."+_dT+".css");fs.renameSync(dest+path.sep+"css"+path.sep+"styles.css",dest+path.sep+"css"+path.sep+"styles."+_dT+".css");let _selectedPlugins=selectedProjectPlugins(projectPath);let _pluginsTags="";if(_selectedPlugins.length){let _pluginsJs=await _pluginsBundle.buildSelectedPluginsBundle(_selectedPlugins,projectPath);let _pluginsCss=await _pluginsBundle.buildSelectedCss(_selectedPlugins,projectPath+path.sep+"node_modules");fs.writeFileSync(dest+path.sep+"js"+path.sep+"plugins."+_dT+".js",String(_pluginsJs));_pluginsTags+=`
|
|
10
|
+
<script src="/js/plugins.`+_dT+`.js" type="text/javascript"><\/script>`;if(_pluginsCss&&_pluginsCss.trim()!=""){fs.writeFileSync(dest+path.sep+"css"+path.sep+"plugins."+_dT+".css",String(_pluginsCss));_pluginsTags+=`
|
|
11
|
+
<link href="/css/plugins.`+_dT+`.css" rel="stylesheet" type="text/css" />`}}fs.writeFileSync(dest+path.sep+"index.html",String(indexCode).split("/js/lm.js").join("/js/app."+_dT+".js").split("/css/styles.css").join("/css/styles."+_dT+".css").split("/css/bea.css").join("/css/app."+_dT+".css").split("</head>").join(_pluginsTags+"\n</head>"));if(cmds.indexOf("--deploy")>=0){spinner.succeed("Writing Files").start("Uploading To Server..");const _config={user:config.ftp.username,password:config.ftp.password,host:config.ftp.host,port:config.ftp.port,localRoot:dest,remoteRoot:config.ftp.remotePath,include:["*","**/*",".*"],exclude:config.ftp.ignore,deleteRemote:false,forcePasv:true,sftp:config.ftp.protocol=="sftp"?true:false};_fD.deploy(_config,function(err,res){if(err){console.log(err)}else{spinner.succeed("Finished Uploading To Server");spinner.succeed("Done")}});_fD.on("uploading",function(data){spinner.start(parseFloat((data.transferredFileCount*100/data.totalFilesCount).toFixed(2))+"% Uploading "+data.filename+" ")})}else spinner.succeed("Writing Files").succeed("Done")})}function clear(isSoft){process.stdout.write(isSoft?"\x1B[H\x1B[2J":"\x1B[2J\x1B[3J\x1B[H\x1Bc")}function startServer(){clear();nodemon({script:path.join(__dirname.toString(),"app.js"),ext:"view,js,css,json,layout,html",watch:["src/","config.json"],ignore:["src/views/**","src/layouts/**"]});nodemon.on("restart",files2=>{console.log(files2)})}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|