qcobjects-cli
Advanced tools
Comparing version 2.3.50 to 2.4.21
@@ -39,5 +39,9 @@ /** | ||
Package("com.qcobjects.backend.microservice.static", [ | ||
Class("Microservice", BackendMicroservice, { | ||
finishWithBody: function(stream) {}, | ||
done: function() { | ||
class Microservice extends BackendMicroservice { | ||
constructor (){ | ||
super(...arguments); | ||
} | ||
finishWithBody (){} | ||
done() { | ||
// read and send file content in the stream | ||
@@ -144,4 +148,5 @@ | ||
}, | ||
static: function(method, data) { | ||
} | ||
static(method, data) { | ||
var microservice = this; | ||
@@ -183,4 +188,5 @@ var redirect_to = microservice.route.redirect_to; | ||
}); | ||
}, | ||
head: function(formData) { | ||
} | ||
head(formData) { | ||
var microservice = this; | ||
@@ -191,4 +197,5 @@ microservice.static("head", formData).then(response => { | ||
}); | ||
}, | ||
get: function(formData) { | ||
} | ||
get(formData) { | ||
var microservice = this; | ||
@@ -199,4 +206,5 @@ microservice.static("get", formData).then(response => { | ||
}); | ||
}, | ||
post: function(formData) { | ||
} | ||
post(formData) { | ||
var microservice = this; | ||
@@ -207,4 +215,5 @@ microservice.static("post", formData).then(response => { | ||
}); | ||
}, | ||
put: function(formData) { | ||
} | ||
put(formData) { | ||
var microservice = this; | ||
@@ -215,4 +224,5 @@ microservice.static("put", formData).then(response => { | ||
}); | ||
}, | ||
delete: function(formData) { | ||
} | ||
delete(formData) { | ||
var microservice = this; | ||
@@ -223,4 +233,5 @@ microservice.static("delete", formData).then(response => { | ||
}); | ||
}, | ||
connect: function(formData) { | ||
} | ||
connect(formData) { | ||
var microservice = this; | ||
@@ -231,4 +242,5 @@ microservice.static("connect", formData).then(response => { | ||
}); | ||
}, | ||
options: function(formData) { | ||
} | ||
options(formData) { | ||
var microservice = this; | ||
@@ -239,4 +251,5 @@ microservice.static("options", formData).then(response => { | ||
}); | ||
}, | ||
trace: function(formData) { | ||
} | ||
trace(formData) { | ||
var microservice = this; | ||
@@ -247,4 +260,5 @@ microservice.static("trace", formData).then(response => { | ||
}); | ||
}, | ||
patch: function(formData) { | ||
} | ||
patch(formData) { | ||
var microservice = this; | ||
@@ -256,3 +270,5 @@ microservice.static("patch", formData).then(response => { | ||
} | ||
}) | ||
} | ||
]); |
@@ -24,3 +24,3 @@ /** | ||
* license document, but changing it is not allowed. | ||
*/ | ||
*/ | ||
/*eslint no-unused-vars: "off"*/ | ||
@@ -35,8 +35,11 @@ /*eslint no-redeclare: "off"*/ | ||
const os = require("os"); | ||
const { exec,execSync } = require("child_process"); | ||
const { | ||
exec, | ||
execSync | ||
} = require("child_process"); | ||
// MY_ENV_VAR="HELLO WORLD" php -f index.php | ||
let fixWinCmd = function (commandline){ | ||
if (!process.platform.toLowerCase().startsWith("win")){ | ||
commandline = commandline.replace(/(")/g, String.fromCharCode(92)+"\""); | ||
let fixWinCmd = function (commandline) { | ||
if (!process.platform.toLowerCase().startsWith("win")) { | ||
commandline = commandline.replace(/(")/g, String.fromCharCode(92) + "\""); | ||
} | ||
@@ -46,30 +49,68 @@ return commandline; | ||
Package("org.quickcorp.backend.php",[ | ||
Class("PHPMicroservice",BackendMicroservice,{ | ||
body:null, | ||
tempFileName: "", | ||
get_php_headers_list:function (){ | ||
Package("org.quickcorp.backend.php", [ | ||
class PHPMicroservice extends BackendMicroservice { | ||
constructor() { | ||
super(...arguments); | ||
var o = this; | ||
logger.debug("PHP Microservice executing"); | ||
let microservice = this; | ||
let request = microservice.request; | ||
let stream = o.stream; | ||
microservice.stream = stream; | ||
stream.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = { | ||
"post": microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedmethods, requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice, data); | ||
} | ||
}); | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = { | ||
"get": microservice.get, | ||
"head": microservice.head, | ||
"put": microservice.put, | ||
"delete": microservice.delete, | ||
"connect": microservice.connect, | ||
"options": microservice.options, | ||
"trace": microservice.trace, | ||
"patch": microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods, requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
} | ||
get_php_headers_list() { | ||
var phpheaders = { | ||
"QUERY_STRING":`${this.request.query}`, | ||
"REDIRECT_STATUS":"200", | ||
"REQUEST_METHOD":`${this.request.method}`, | ||
"SCRIPT_FILENAME":`${this.scriptFilePath}`, | ||
"SCRIPT_NAME":`${this.scriptFilePath.toString()}`, | ||
"PATH_INFO":`${this.request.path}`, | ||
"SERVER_NAME":`${this.domain}`, | ||
"SERVER_PROTOCOL":"HTTP/2", | ||
"REQUEST_URI":`${this.request.href}`, | ||
"HTTP_HOST":`${this.domain}` | ||
"QUERY_STRING": `${this.request.query}`, | ||
"REDIRECT_STATUS": "200", | ||
"REQUEST_METHOD": `${this.request.method}`, | ||
"SCRIPT_FILENAME": `${this.scriptFilePath}`, | ||
"SCRIPT_NAME": `${this.scriptFilePath.toString()}`, | ||
"PATH_INFO": `${this.request.path}`, | ||
"SERVER_NAME": `${this.domain}`, | ||
"SERVER_PROTOCOL": "HTTP/2", | ||
"REQUEST_URI": `${this.request.href}`, | ||
"HTTP_HOST": `${this.domain}` | ||
}; | ||
function fixedEncodeURIComponent (str) { | ||
function fixedEncodeURIComponent(str) { | ||
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A"); | ||
} | ||
for (var headername in this.request.headers){ | ||
if (!headername.startsWith(":")){ | ||
var phpheadername = headername.toUpperCase().replace(new RegExp("-","g"),"_"); | ||
for (var headername in this.request.headers) { | ||
if (!headername.startsWith(":")) { | ||
var phpheadername = headername.toUpperCase().replace(new RegExp("-", "g"), "_"); | ||
var headervalue = this.request.headers[headername]; | ||
if (typeof headervalue != "string"){ | ||
if (typeof headervalue != "string") { | ||
headervalue = JSON.stringify(headervalue); | ||
} | ||
phpheaders["HTTP_"+phpheadername] = fixedEncodeURIComponent(headervalue); | ||
phpheaders["HTTP_" + phpheadername] = fixedEncodeURIComponent(headervalue); | ||
} | ||
@@ -79,4 +120,5 @@ } | ||
return PipeLog.pipe(phpheaders); | ||
}, | ||
saveTempData: function (data,done){ | ||
} | ||
saveTempData(data, done) { | ||
var filename = os.tmpdir() + this.tempFileName; | ||
@@ -88,30 +130,33 @@ fs.writeFile(filename, data, (err) => { | ||
}); | ||
}, | ||
generateTempFileName: function (){ | ||
} | ||
generateTempFileName() { | ||
this.tempFileName = "temp" + Date.now().toString(); | ||
return this.tempFileName; | ||
}, | ||
trimSlash:function (pathname){ | ||
if (pathname.startsWith("/")){ | ||
} | ||
trimSlash(pathname) { | ||
if (pathname.startsWith("/")) { | ||
pathname = pathname.slice(1); | ||
} | ||
if (pathname.endsWith("/")){ | ||
pathname = pathname.slice(0,-1); | ||
if (pathname.endsWith("/")) { | ||
pathname = pathname.slice(0, -1); | ||
} | ||
return pathname.replace("//","/"); | ||
}, | ||
get:function (){ | ||
return pathname.replace("//", "/"); | ||
} | ||
get() { | ||
var microservice = this; | ||
microservice.generateTempFileName(); | ||
microservice.saveTempData(this.request.query,function (){ | ||
microservice.saveTempData(this.request.query, function () { | ||
try { | ||
process.chdir(CONFIG.get("documentRoot")+microservice.request.pathname.slice(1)); | ||
} catch (e){} | ||
process.chdir(CONFIG.get("documentRoot") + microservice.request.pathname.slice(1)); | ||
} catch (e) {} | ||
var scriptFileName = (microservice.route.hasOwnProperty.call(microservice.route,"redirect_to") | ||
&& microservice.route.redirect_to !== "")?(microservice.route.redirect_to):(microservice.request.scriptname); | ||
var scriptFileName = (microservice.route.hasOwnProperty.call(microservice.route, "redirect_to") && | ||
microservice.route.redirect_to !== "") ? (microservice.route.redirect_to) : (microservice.request.scriptname); | ||
var pathname = this.trimSlash(microservice.request.pathname); | ||
var documentRoot = CONFIG.get("documentRoot",""); | ||
if (documentRoot == "./"){ | ||
var documentRoot = CONFIG.get("documentRoot", ""); | ||
if (documentRoot == "./") { | ||
documentRoot = ""; | ||
@@ -121,3 +166,3 @@ } | ||
var scriptFilePath; | ||
if (documentRoot !== ""){ | ||
if (documentRoot !== "") { | ||
scriptFilePath = `${documentRoot}/${pathname}/${scriptFileName}`; | ||
@@ -128,4 +173,4 @@ } else { | ||
scriptFilePath = scriptFilePath.replace("//","/"); | ||
if (scriptFilePath.startsWith("/") && !documentRoot.startsWith("/")){ | ||
scriptFilePath = scriptFilePath.replace("//", "/"); | ||
if (scriptFilePath.startsWith("/") && !documentRoot.startsWith("/")) { | ||
scriptFilePath = scriptFilePath.slice(1); | ||
@@ -139,3 +184,3 @@ } | ||
var commandline = `echo $(cat ${os.tmpdir()}${microservice.tempFileName}) |` + microservice.get_php_headers_list()+` php -d include_path="${PHPIncludePath}" -q <<- 'EOF' | ||
var commandline = `echo $(cat ${os.tmpdir()}${microservice.tempFileName}) |` + microservice.get_php_headers_list() + ` php -d include_path="${PHPIncludePath}" -q <<- 'EOF' | ||
<?php | ||
@@ -160,3 +205,3 @@ $_payload = file_get_contents(sys_get_temp_dir().'${microservice.tempFileName}'); | ||
try { | ||
let php = exec(commandline,(err,stdout,stderr)=>{ | ||
let php = exec(commandline, (err, stdout, stderr) => { | ||
microservice.body = stdout; | ||
@@ -166,3 +211,3 @@ console.log(stderr); | ||
}); | ||
} catch (ex){ | ||
} catch (ex) { | ||
microservice.body = "500 - INTERNAL ERROR"; | ||
@@ -176,5 +221,8 @@ logger.debug(ex.toString()); | ||
}, | ||
head:function (formData){this.done();}, | ||
post:function (formData){ | ||
} | ||
head(formData) { | ||
this.done(); | ||
} | ||
post(formData) { | ||
logger.debug("POST DATA"); | ||
@@ -184,12 +232,12 @@ var microservice = this; | ||
microservice.saveTempData(formData,function (){ | ||
microservice.saveTempData(formData, function () { | ||
try { | ||
process.chdir(CONFIG.get("documentRoot")+microservice.request.pathname.slice(1)); | ||
} catch (e){} | ||
process.chdir(CONFIG.get("documentRoot") + microservice.request.pathname.slice(1)); | ||
} catch (e) {} | ||
var scriptFileName = (microservice.route.hasOwnProperty.call(microservice.route,"redirect_to") | ||
&& microservice.route.redirect_to !== "")?(microservice.route.redirect_to):(microservice.request.scriptname); | ||
var scriptFileName = (microservice.route.hasOwnProperty.call(microservice.route, "redirect_to") && | ||
microservice.route.redirect_to !== "") ? (microservice.route.redirect_to) : (microservice.request.scriptname); | ||
var pathname = this.trimSlash(microservice.request.pathname); | ||
var documentRoot = CONFIG.get("documentRoot",""); | ||
if (documentRoot == "./"){ | ||
var documentRoot = CONFIG.get("documentRoot", ""); | ||
if (documentRoot == "./") { | ||
documentRoot = ""; | ||
@@ -199,3 +247,3 @@ } | ||
var scriptFilePath; | ||
if (documentRoot !== ""){ | ||
if (documentRoot !== "") { | ||
scriptFilePath = `${documentRoot}/${pathname}/${scriptFileName}`; | ||
@@ -206,4 +254,4 @@ } else { | ||
scriptFilePath = scriptFilePath.replace("//","/"); | ||
if (scriptFilePath.startsWith("/") && !documentRoot.startsWith("/")){ | ||
scriptFilePath = scriptFilePath.replace("//", "/"); | ||
if (scriptFilePath.startsWith("/") && !documentRoot.startsWith("/")) { | ||
scriptFilePath = scriptFilePath.slice(1); | ||
@@ -217,3 +265,3 @@ } | ||
var commandline = `echo $(cat ${os.tmpdir()}${microservice.tempFileName}) |` + microservice.get_php_headers_list()+` php -d include_path="${PHPIncludePath}" -q <<- 'EOF' | ||
var commandline = `echo $(cat ${os.tmpdir()}${microservice.tempFileName}) |` + microservice.get_php_headers_list() + ` php -d include_path="${PHPIncludePath}" -q <<- 'EOF' | ||
<?php | ||
@@ -236,7 +284,7 @@ $_payload = file_get_contents(sys_get_temp_dir().'${microservice.tempFileName}'); | ||
commandline = fixWinCmd(commandline); | ||
// logger.debug(commandline); | ||
// logger.debug(commandline); | ||
try { | ||
microservice.body = execSync(commandline).toString(); | ||
} catch (ex){ | ||
} catch (ex) { | ||
microservice.body = "500 - INTERNAL ERROR"; | ||
@@ -249,10 +297,23 @@ logger.debug(ex.toString()); | ||
}, | ||
put:function (formData){this.done();}, | ||
delete:function (formData){this.done();}, | ||
connect:function (formData){this.done();}, | ||
options:function (formData){this.done();}, | ||
trace:function (formData){this.done();}, | ||
patch:function (formData){this.done();}, | ||
done: function(){ | ||
} | ||
put(formData) { | ||
this.done(); | ||
} | ||
delete(formData) { | ||
this.done(); | ||
} | ||
connect(formData) { | ||
this.done(); | ||
} | ||
options(formData) { | ||
this.done(); | ||
} | ||
trace(formData) { | ||
this.done(); | ||
} | ||
patch(formData) { | ||
this.done(); | ||
} | ||
done() { | ||
var microservice = this; | ||
@@ -262,51 +323,23 @@ var stream = microservice.stream; | ||
stream.respond(microservice.headers); | ||
} catch (e){ | ||
} catch (e) { | ||
// | ||
} | ||
if (microservice.body != null){ | ||
microservice.finishWithBody.call(microservice,stream); | ||
if (microservice.body != null) { | ||
microservice.finishWithBody.call(microservice, stream); | ||
} | ||
}, | ||
finishWithBody:function (stream){ | ||
} | ||
finishWithBody(stream) { | ||
try { | ||
stream.write(this.body); | ||
stream.end(); | ||
} catch (e){ | ||
logger.debug("Something wrong writing the response for microservice"+e.toString()); | ||
} catch (e) { | ||
logger.debug("Something wrong writing the response for microservice" + e.toString()); | ||
} | ||
}, | ||
_new_:function (o){ | ||
logger.debug("PHP Microservice executing"); | ||
let microservice = this; | ||
let request = microservice.request; | ||
let stream = o.stream; | ||
microservice.stream = stream; | ||
stream.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"post":microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedmethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice,data); | ||
} | ||
}); | ||
} | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"get":microservice.get, | ||
"head":microservice.head, | ||
"put":microservice.put, | ||
"delete":microservice.delete, | ||
"connect":microservice.connect, | ||
"options":microservice.options, | ||
"trace":microservice.trace, | ||
"patch":microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
} | ||
}), | ||
Class("Microservice",PHPMicroservice) | ||
]); | ||
}, | ||
Class("Microservice", PHPMicroservice) | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -40,146 +40,156 @@ * | ||
Class ("QCObjectsEnterprise", { | ||
install (switchCommander) { | ||
let instance = this; | ||
return instance.installEnterprise(license, email); | ||
}, | ||
upgrade (switchCommander){ | ||
let instance = this; | ||
const readline = require("readline"); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout | ||
}); | ||
var emailQuestion = function (){ | ||
rl.question(` | ||
[NOTE: No information will be sent to a server until I got your consent] | ||
Please tell me your e-Mail (\u{1F48C}): | ||
`, (email) => { | ||
const asterisk = "*"; | ||
if (email !== ""){ | ||
var phoneNumberQuestion = function (){ | ||
rl.question ("Please tell me your phone number (\u{1F919}): \n", (phonenumber) => { | ||
if (phonenumber !== ""){ | ||
rl.question (` | ||
Please select one of the following options (type a number): | ||
1.- \u{1F640} This is your first interaction \u{1F60D} with QCObjects Enterprise Edition \u{1F3E2}, | ||
you want to send your email and phone number to one of our executives to process your | ||
inquiry, pay the license (when aplies) and receive a new fresh license number | ||
that will free up to you the most advanced features for large companies | ||
2.- \u{2714} Your assigned executive \u{1F9D1} has given to you a new fresh QCObjects Enterprise Edition License Number | ||
and you want to enter it to follow up with the next steps. | ||
3.- \u{1F3C3} You want to quit this form, as you got here accidentally | ||
(You should think about it. It's not a coincidence, It's destiny \u{1F600}). | ||
Please enter the number of the option and press [enter]: `, (interaction_option)=> { | ||
logger.infoEnabled=true; | ||
switch (interaction_option) { | ||
case "1": | ||
switchCommander.register(email,phonenumber).then(function (response){ | ||
logger.info(`\u{1F44F} Congrats! You have been successfully registered to the cloud! \u{1F44F} | ||
One of our executives will be in touch with you as soon as possible to give you the next steps | ||
to get a new License Number and start using QCObjects Entrprise Edition! | ||
(In the meantime, you can continue using all the features of the QCObjects Community Edition) | ||
`); | ||
Package ("org.qcobjects.enterprise.commands", [ | ||
class QCObjectsEnterprise extends InheritClass { | ||
constructor(){ | ||
super(...arguments); | ||
} | ||
install (switchCommander) { | ||
let instance = this; | ||
return instance.installEnterprise(license, email); | ||
} | ||
upgrade (switchCommander){ | ||
let instance = this; | ||
const readline = require("readline"); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout | ||
}); | ||
var emailQuestion = function (){ | ||
rl.question(` | ||
[NOTE: No information will be sent to a server until I got your consent] | ||
Please tell me your e-Mail (\u{1F48C}): | ||
`, (email) => { | ||
const asterisk = "*"; | ||
if (email !== ""){ | ||
var phoneNumberQuestion = function (){ | ||
rl.question ("Please tell me your phone number (\u{1F919}): \n", (phonenumber) => { | ||
if (phonenumber !== ""){ | ||
rl.question (` | ||
Please select one of the following options (type a number): | ||
1.- \u{1F640} This is your first interaction \u{1F60D} with QCObjects Enterprise Edition \u{1F3E2}, | ||
you want to send your email and phone number to one of our executives to process your | ||
inquiry, pay the license (when aplies) and receive a new fresh license number | ||
that will free up to you the most advanced features for large companies | ||
2.- \u{2714} Your assigned executive \u{1F9D1} has given to you a new fresh QCObjects Enterprise Edition License Number | ||
and you want to enter it to follow up with the next steps. | ||
3.- \u{1F3C3} You want to quit this form, as you got here accidentally | ||
(You should think about it. It's not a coincidence, It's destiny \u{1F600}). | ||
Please enter the number of the option and press [enter]: `, (interaction_option)=> { | ||
logger.infoEnabled=true; | ||
switch (interaction_option) { | ||
case "1": | ||
switchCommander.register(email,phonenumber).then(function (response){ | ||
logger.info(`\u{1F44F} Congrats! You have been successfully registered to the cloud! \u{1F44F} | ||
One of our executives will be in touch with you as soon as possible to give you the next steps | ||
to get a new License Number and start using QCObjects Entrprise Edition! | ||
(In the meantime, you can continue using all the features of the QCObjects Community Edition) | ||
`); | ||
rl.close(); | ||
}).catch ((e)=>{ | ||
rl.close(); | ||
}); | ||
break; | ||
case "2": | ||
rl.stdoutMuted = true; | ||
rl._writeToOutput = function _writeToOutput(stringToWrite) { | ||
if (rl.stdoutMuted) | ||
rl.output.write("*"); | ||
else | ||
rl.output.write(stringToWrite); | ||
}; | ||
rl.question("Please tell me the number of license that your executive has given to you: \n", (license) => { | ||
rl.stdoutMuted = false; | ||
instance.installEnterprise(license, email); | ||
rl.close(); | ||
}); | ||
break; | ||
default: | ||
logger.info("\u{1F937} You can continue to use QCObjects Community Edition, see you! \u{1F64B} "); | ||
rl.close(); | ||
}).catch ((e)=>{ | ||
rl.close(); | ||
}); | ||
break; | ||
case "2": | ||
rl.stdoutMuted = true; | ||
rl._writeToOutput = function _writeToOutput(stringToWrite) { | ||
if (rl.stdoutMuted) | ||
rl.output.write("*"); | ||
else | ||
rl.output.write(stringToWrite); | ||
}; | ||
rl.question("Please tell me the number of license that your executive has given to you: \n", (license) => { | ||
rl.stdoutMuted = false; | ||
instance.installEnterprise(license, email); | ||
rl.close(); | ||
}); | ||
break; | ||
default: | ||
logger.info("\u{1F937} You can continue to use QCObjects Community Edition, see you! \u{1F64B} "); | ||
rl.close(); | ||
break; | ||
} | ||
}); | ||
} else { | ||
console.log(`You need to enter a Phone Number if you want to be contacted. | ||
If you want to quit, press Ctrl-C. | ||
break; | ||
} | ||
}); | ||
} else { | ||
console.log(`You need to enter a Phone Number if you want to be contacted. | ||
If you want to quit, press Ctrl-C. | ||
`); | ||
phoneNumberQuestion(); | ||
} | ||
}); | ||
}; | ||
phoneNumberQuestion(); | ||
} else { | ||
console.log(`You need to enter a real e-Mail adress if you want to be contacted. | ||
If you want to quit, press Ctrl-C. | ||
`); | ||
emailQuestion(); | ||
} | ||
}); | ||
}; | ||
emailQuestion(); | ||
} | ||
installEnterprise (license, email) { | ||
const asterisk = "*"; | ||
var license = CONFIG.get("enterprise-license", license); | ||
var email = CONFIG.get("enterprise-email", email); | ||
logger.info(`Your entered license number is ${asterisk.repeat(license.length)} and the email that you have entered is ${email}`); | ||
logger.info("Now, I'm installing QCObjects Enterprise Edition in your computer..."); | ||
let cmdDownloadGit = `npm i --force -g git+https://license:${license}@software.qcobjects.io/qcobjects-enterprise/qcobjects-enterprise.git`; | ||
exec(cmdDownloadGit,(err,stdout,stderr)=>{ | ||
if(!err){ | ||
exec("qcobjects --version",(err,stdout,stderr)=>{ | ||
if (stdout.lastIndexOf("Enterprise Edition")!==-1){ | ||
logger.info("\u{1F44F} Congrats! Now you have installed QCObjects Entrprise Edition! \u{1F44F}"); | ||
logger.info(`You can test it using: | ||
> qcobjects --version | ||
To find more help, type the command: | ||
> qcobjects --help | ||
Enjoy! | ||
`); | ||
phoneNumberQuestion(); | ||
} | ||
}); | ||
}; | ||
phoneNumberQuestion(); | ||
} else { | ||
console.log("\u{1F926} Something went wrong \u{1F926} when trying to update your license to QCObjects Enterprise Edition"); | ||
console.log("Ask your executive to help"); | ||
} | ||
}); | ||
} else { | ||
console.log(`You need to enter a real e-Mail adress if you want to be contacted. | ||
If you want to quit, press Ctrl-C. | ||
`); | ||
emailQuestion(); | ||
} | ||
}); | ||
}; | ||
emailQuestion(); | ||
}, | ||
installEnterprise (license, email) { | ||
const asterisk = "*"; | ||
var license = CONFIG.get("enterprise-license", license); | ||
var email = CONFIG.get("enterprise-email", email); | ||
logger.info(`Your entered license number is ${asterisk.repeat(license.length)} and the email that you have entered is ${email}`); | ||
logger.info("Now, I'm installing QCObjects Enterprise Edition in your computer..."); | ||
let cmdDownloadGit = `npm i --force -g git+https://license:${license}@software.qcobjects.io/qcobjects-enterprise/qcobjects-enterprise.git`; | ||
exec(cmdDownloadGit,(err,stdout,stderr)=>{ | ||
if(!err){ | ||
exec("qcobjects --version",(err,stdout,stderr)=>{ | ||
if (stdout.lastIndexOf("Enterprise Edition")!==-1){ | ||
logger.info("\u{1F44F} Congrats! Now you have installed QCObjects Entrprise Edition! \u{1F44F}"); | ||
logger.info(`You can test it using: | ||
> qcobjects --version | ||
To find more help, type the command: | ||
> qcobjects --help | ||
Enjoy! | ||
`); | ||
console.log("\u{1F926} Something went wrong \u{1F926} when trying to update your license to QCObjects Enterprise Edition"); | ||
if (stderr.lastIndexOf("Authentication failed")!==-1){ | ||
console.log("Please ask to your executive for the right license number"); | ||
} else { | ||
console.log("\u{1F926} Something went wrong \u{1F926} when trying to update your license to QCObjects Enterprise Edition"); | ||
console.log("Ask your executive to help"); | ||
console.log(stderr); | ||
} | ||
}); | ||
} else { | ||
console.log("\u{1F926} Something went wrong \u{1F926} when trying to update your license to QCObjects Enterprise Edition"); | ||
if (stderr.lastIndexOf("Authentication failed")!==-1){ | ||
console.log("Please ask to your executive for the right license number"); | ||
} else { | ||
console.log(stderr); | ||
} | ||
} | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} | ||
} | ||
}) | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -33,16 +33,23 @@ * | ||
Package("org.quickcorp.qcobjects.api.client_services", [ | ||
Class("QuickCorpCloud", Service, { | ||
name: "quickcorp_cloud", | ||
external: true, | ||
useHTTP2:true, | ||
cached: false, | ||
method: "post", | ||
headers: { | ||
"origin": "localhost", | ||
"content-type": "application/json" | ||
}, | ||
basePath: "https://cloud.quickcorp.org/", | ||
url: "", | ||
withCredentials: false, | ||
_new_: function(o) { | ||
class QuickCorpCloud extends Service { | ||
constructor ({ | ||
name= "quickcorp_cloud", | ||
external= true, | ||
useHTTP2=true, | ||
cached= false, | ||
method= "post", | ||
headers= { | ||
"origin": "localhost", | ||
"content-type": "application/json" | ||
}, | ||
basePath= "https://cloud.quickcorp.org/", | ||
url= "", | ||
withCredentials= false | ||
}) { | ||
super(...arguments); | ||
} | ||
_new_(o) { | ||
// service instantiated | ||
@@ -52,11 +59,15 @@ this.headers["authorization"] = "Basic token"; | ||
this.data = o.data; | ||
}, | ||
done: function(service,standardResponse) { | ||
} | ||
done(service,standardResponse) { | ||
// service loaded | ||
logger.debug(standardResponse); | ||
}, | ||
fail: function (e){ | ||
} | ||
fail(e){ | ||
logger.debug(e); | ||
} | ||
}) | ||
} | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -46,3 +46,3 @@ * | ||
require(absolutePath+"/org.quickcorp.qcobjects.api.client_services"); | ||
require(absolutePath+"/org.quickcorp.qcobjects.cli.commands"); | ||
require(absolutePath+"/com.qcobjects.cli.commands"); | ||
@@ -63,5 +63,268 @@ let ImportCustomCommand = function (commandName, commandPackage){ | ||
Package("org.quickcorp.qcobjects.cli",[ | ||
Class("SwitchCommander",{ | ||
program:require("commander"), | ||
shellCommands: function (_shell_commands){ | ||
class SwitchCommander extends InheritClass { | ||
constructor (){ | ||
super(...arguments); | ||
this.program = require("commander"); | ||
this.choiceOption={ | ||
generateSw(_appName){ | ||
let switchCommander = this; | ||
let appName = (typeof _appName ==="undefined" || _appName === true)?("MyAppName"):(_appName); | ||
switchCommander.generateServiceWorker(appName); | ||
}, | ||
create(_appName, options){ | ||
const version = global.__get_version__(); | ||
let switchCommander = this; | ||
let appName = (typeof _appName ==="undefined" || _appName === true)?("MyAppName"):(_appName); | ||
const readline = require("readline"); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout | ||
}); | ||
rl.question(`Please tell me your git repository url | ||
[press ENTER \u{21b5} to leave it blank or Ctrl+C to cancel]: | ||
`, (answer) => { | ||
logger.info(`your git repository url is ${answer}`); | ||
rl.close(); | ||
let giturl = answer; | ||
let createAppCommandCustom = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "This is a custom NPM template app from ${options.createCustom} generated with QCObjects.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"${options.createCustom}": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandPWA = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome PWA application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjectsnewapp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandAMP = `echo | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome AMP application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjects-ecommerce-amp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandPHP = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome PHP application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjectsnewphp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommand; | ||
let appTemplateName; | ||
let _package_json_content; | ||
if (options.createAmp){ | ||
appTemplateName = "qcobjects-ecommerce-amp"; | ||
_package_json_content = createAppCommandAMP; | ||
} else if (options.createPwa){ | ||
appTemplateName = "qcobjectsnewapp"; | ||
_package_json_content = createAppCommandPWA; | ||
} else if (options.createPhp){ | ||
appTemplateName = "qcobjectsnewphp"; | ||
_package_json_content = createAppCommandPHP; | ||
} else if (options.createCustom){ | ||
appTemplateName = options.createCustom; | ||
_package_json_content = createAppCommandCustom; | ||
} else { | ||
appTemplateName = "qcobjectsnewapp"; | ||
_package_json_content = createAppCommandPWA; | ||
} | ||
CONFIG.set("qcobjectsnewapp_path",CONFIG.get("node_modules_path")+"/"+appTemplateName); | ||
/* if (!process.platform.toLowerCase().startsWith("win")){ | ||
_package_json_content = _package_json_content.replace(/(")/g, String.fromCharCode(92)+"\""); | ||
}*/ | ||
createAppCommand = "npm init -y"; | ||
let _package_json_file = path.resolve(CONFIG.get("projectPath"),"./package.json"); | ||
logger.debug("_package_json_file: "+_package_json_file); | ||
logger.debug(createAppCommand); | ||
exec(createAppCommand, (err, stdout, stderr) => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
fs.writeFile(_package_json_file, _package_json_content, err => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
exec("npm cache verify && npm i --save-dev --legacy-peer-deps", (err, stdout, stderr) => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
Promise.resolve(switchCommander.copyTemplate()) | ||
.then(()=>{ | ||
logger.info("Good! Your application is getting done. You can play with QCObjects now!"); | ||
logger.info("In about five seconds your server will start..."); | ||
exec("qcobjects-createcert",(err,stdout,stderr)=>{ | ||
logger.info("Test certificates generated"); | ||
exec("npm uninstall "+appTemplateName+" --save && npm cache verify",(err,stdout,stderr)=>{ | ||
switchCommander.generateServiceWorker(appName); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log("App generation started..."); | ||
}); | ||
}); | ||
}, | ||
publish(_appName){ | ||
logger.debug("publish is not yet implemented"); | ||
}, | ||
upgradeToEnterprise (){ | ||
let switchCommander = this; | ||
QCObjectsEnterprise.upgrade(switchCommander); | ||
} | ||
}; | ||
} | ||
shellCommands(_shell_commands){ | ||
return new Promise(function (resolve_all,reject_all){ | ||
@@ -93,4 +356,5 @@ var _promises_set = _shell_commands.map( | ||
}).catch(e=>console.log(e)); | ||
}, | ||
fileListRecursive : function (dir) { | ||
} | ||
fileListRecursive (dir) { | ||
var instance = this; | ||
@@ -104,4 +368,5 @@ return (fs.statSync(dir).isDirectory()) | ||
: (dir); | ||
}, | ||
register: function (email,phonenumber){ | ||
} | ||
register(email,phonenumber){ | ||
return new Promise (function (resolve,reject){ | ||
@@ -129,4 +394,5 @@ logger.info("I'm going to register your profile on the cloud..."); | ||
}); | ||
}, | ||
generateServiceWorker: function (appName){ | ||
} | ||
generateServiceWorker(appName){ | ||
var filelist = ["/"].concat(this.fileListRecursive("./")); | ||
@@ -168,4 +434,5 @@ filelist = filelist.filter(function (fl){return fl !== "sw.js" && (!fl.startsWith("node_modules/")); }); | ||
return component; | ||
}, | ||
copyTemplate: function (){ | ||
} | ||
copyTemplate(){ | ||
var map_files = function (pathname,callback){ | ||
@@ -229,259 +496,5 @@ var _filenames = function (pathname){ | ||
}, | ||
choiceOption:{ | ||
generateSw: function (_appName){ | ||
let switchCommander = this; | ||
let appName = (typeof _appName ==="undefined" || _appName === true)?("MyAppName"):(_appName); | ||
switchCommander.generateServiceWorker(appName); | ||
} | ||
}, | ||
create:function (_appName, options){ | ||
const version = global.__get_version__(); | ||
let switchCommander = this; | ||
let appName = (typeof _appName ==="undefined" || _appName === true)?("MyAppName"):(_appName); | ||
const readline = require("readline"); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout | ||
}); | ||
rl.question(`Please tell me your git repository url | ||
[press ENTER \u{21b5} to leave it blank or Ctrl+C to cancel]: | ||
`, (answer) => { | ||
logger.info(`your git repository url is ${answer}`); | ||
rl.close(); | ||
let giturl = answer; | ||
let createAppCommandCustom = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "This is a custom NPM template app from ${options.createCustom} generated with QCObjects.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"${options.createCustom}": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandPWA = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome PWA application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjectsnewapp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandAMP = `echo | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome AMP application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjects-ecommerce-amp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommandPHP = ` | ||
{ | ||
"name": "${appName.toLowerCase()}", | ||
"version": "0.0.1", | ||
"repository": { | ||
"type": "git", | ||
"url": "${giturl}" | ||
}, | ||
"description": "Awesome PHP application that will help you achieve your dreams.", | ||
"main": "js/init.js", | ||
"license": "LGPL-3.0-or-later", | ||
"scripts": { | ||
"test": "(npx eslint *.js js/*.js js/packages/*.js --fix) && (npx jasmine)", | ||
"sync": "git add . && git commit -am ", | ||
"preversion": "npm i --upgrade && npm test", | ||
"postversion": "git push && git push --tags", | ||
"coverage": "nyc --reporter=lcov --reporter=text-summary npm run test", | ||
"start": "node app.js", | ||
"build": "exit 0" | ||
}, | ||
"dependencies": { | ||
"qcobjectsnewphp": "latest", | ||
"qcobjects": "^${version.qcobjects}", | ||
"qcobjects-sdk": "^${version.sdk}" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "latest", | ||
"jasmine": "latest", | ||
"qcobjects-cli": "^${version.cli}", | ||
"grunt": "^1.4.1", | ||
"grunt-contrib-jasmine": "^2.0.2", | ||
"nyc": "^15.1.0" | ||
} | ||
}`; | ||
let createAppCommand; | ||
let appTemplateName; | ||
let _package_json_content; | ||
if (options.createAmp){ | ||
appTemplateName = "qcobjects-ecommerce-amp"; | ||
_package_json_content = createAppCommandAMP; | ||
} else if (options.createPwa){ | ||
appTemplateName = "qcobjectsnewapp"; | ||
_package_json_content = createAppCommandPWA; | ||
} else if (options.createPhp){ | ||
appTemplateName = "qcobjectsnewphp"; | ||
_package_json_content = createAppCommandPHP; | ||
} else if (options.createCustom){ | ||
appTemplateName = options.createCustom; | ||
_package_json_content = createAppCommandCustom; | ||
} else { | ||
appTemplateName = "qcobjectsnewapp"; | ||
_package_json_content = createAppCommandPWA; | ||
} | ||
CONFIG.set("qcobjectsnewapp_path",CONFIG.get("node_modules_path")+"/"+appTemplateName); | ||
/* if (!process.platform.toLowerCase().startsWith("win")){ | ||
_package_json_content = _package_json_content.replace(/(")/g, String.fromCharCode(92)+"\""); | ||
}*/ | ||
createAppCommand = "npm init -y"; | ||
let _package_json_file = path.resolve(CONFIG.get("projectPath"),"./package.json"); | ||
logger.debug("_package_json_file: "+_package_json_file); | ||
logger.debug(createAppCommand); | ||
exec(createAppCommand, (err, stdout, stderr) => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
fs.writeFile(_package_json_file, _package_json_content, err => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
exec("npm cache verify && npm i --save-dev --legacy-peer-deps", (err, stdout, stderr) => { | ||
if (err) { | ||
logger.warn(err); | ||
process.exit(1); | ||
return; | ||
} | ||
Promise.resolve(switchCommander.copyTemplate()) | ||
.then(()=>{ | ||
logger.info("Good! Your application is getting done. You can play with QCObjects now!"); | ||
logger.info("In about five seconds your server will start..."); | ||
exec("qcobjects-createcert",(err,stdout,stderr)=>{ | ||
logger.info("Test certificates generated"); | ||
exec("npm uninstall "+appTemplateName+" --save && npm cache verify",(err,stdout,stderr)=>{ | ||
switchCommander.generateServiceWorker(appName); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
}); | ||
}).stdout.on("data", function(data) { | ||
console.log("App generation started..."); | ||
}); | ||
}); | ||
}, | ||
publish: function (_appName){ | ||
logger.debug("publish is not yet implemented"); | ||
}, | ||
upgradeToEnterprise (){ | ||
let switchCommander = this; | ||
QCObjectsEnterprise.upgrade(switchCommander); | ||
} | ||
}, | ||
initCommand: function (){ | ||
initCommand(){ | ||
let switchCommander = this; | ||
@@ -517,7 +530,5 @@ if (process.argv.length>1){ | ||
this.pluginCommandsList = []; | ||
let _pluginCommandsList = global.ClassesList.filter(c=>c.packageName.startsWith("org.quickcorp.qcobjects.cli.commands.")); | ||
_pluginCommandsList.filter(pluginCommand=>pluginCommand.className.endsWith(".CommandHandler")).map(pluginCommand => { | ||
this.pluginCommandsList.push(New(pluginCommand.classFactory,{ | ||
switchCommander:this | ||
})); | ||
let _pluginCommandsList = global.ClassesList.filter(c=>c.packageName.startsWith("com.qcobjects.cli.commands.")); | ||
_pluginCommandsList.filter(p=>p.classFactory.name.endsWith("CommandHandler")).map(pluginCommand => { | ||
this.pluginCommandsList.push(new pluginCommand.classFactory({switchCommander:switchCommander})); | ||
}); | ||
@@ -580,3 +591,5 @@ }; | ||
} | ||
}) | ||
} | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -31,3 +31,2 @@ * | ||
/*eslint no-undef: "off"*/ | ||
/*eslint no-global-assign: "off"*/ | ||
"use strict"; | ||
@@ -80,333 +79,343 @@ const os = require("os"); | ||
Class("CollabServer",{ | ||
runScript: function (context){ | ||
const runScript = (code,logOutput=false)=>{ | ||
const options = {filename:sandbox.__filename}; | ||
const backgroundRunScript = (code)=>{ | ||
var output = vm.runInContext(code,context,options); | ||
return output; | ||
}; | ||
var output = backgroundRunScript(code); | ||
if (logOutput && typeof output !== "undefined"){ | ||
console.log(output); | ||
} | ||
}; | ||
}, | ||
protected_symbols: [ "clearInterval", | ||
"clearTimeout", | ||
"setInterval", | ||
"setTimeout", "queueMicrotask", | ||
"clearImmediate", "setImmediate", "_asyncLoad", | ||
"_fireAsyncLoad", "asyncLoad", "logger", | ||
"_Crypt", "CONFIG", "waitUntil", | ||
"_super_", "ComplexStorageCache", "TagElements", | ||
"onload", "InheritClass", "Component", | ||
"Controller", "View", "Service", | ||
"JSONService", "ConfigService", "VO", | ||
"serviceLoader", "componentLoader", "ComponentURI", | ||
"SourceJS", "SourceCSS", "ArrayList", | ||
"ArrayCollection", "Effect", "Timer", | ||
"Export", "Import", "Package", | ||
"Class", "New", "Tag", | ||
"Ready", "Contact", "FormField", | ||
"ButtonField", "InputField", "TextField", | ||
"EmailField", "GridComponent", "GridController", | ||
"GridView", "Move", "RotateX", | ||
"RotateY", "RotateZ", "Rotate", | ||
"Fade", "Radius", "CanvasTool", | ||
"BasicLayout" | ||
], | ||
commands: { | ||
loadcmd_json:{ | ||
help: ` | ||
Executes a CMD Shell Command | ||
and loads the stdout to a variable after trying to convert the result | ||
to JSON format | ||
The first argument is the variable name followed by an equal sign "=". | ||
Example: | ||
> .loadcmd_json result = cat somefile.json | ||
The above command will save the content of somefile.json using cat into the variable global.result | ||
as JSON format | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var cmdArguments = commandArgs.slice(2).join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
try { | ||
_rplServer.context[_variableName] = JSON.parse(stdout); | ||
} catch (e){ | ||
logger.debug("It was not possible to parse the data."); | ||
} | ||
Package("org.quickcorp.qcobjects.collab.server",[ | ||
class CollabServer extends InheritClass { | ||
constructor(){ | ||
super(...arguments); | ||
this.protected_symbols= [ "clearInterval", | ||
"clearTimeout", | ||
"setInterval", | ||
"setTimeout", "queueMicrotask", | ||
"clearImmediate", "setImmediate", "_asyncLoad", | ||
"_fireAsyncLoad", "asyncLoad", "logger", | ||
"_Crypt", "CONFIG", "waitUntil", | ||
"_super_", "ComplexStorageCache", "TagElements", | ||
"onload", "InheritClass", "Component", | ||
"Controller", "View", "Service", | ||
"JSONService", "ConfigService", "VO", | ||
"serviceLoader", "componentLoader", "ComponentURI", | ||
"SourceJS", "SourceCSS", "ArrayList", | ||
"ArrayCollection", "Effect", "Timer", | ||
"Export", "Import", "Package", | ||
"Class", "New", "Tag", | ||
"Ready", "Contact", "FormField", | ||
"ButtonField", "InputField", "TextField", | ||
"EmailField", "GridComponent", "GridController", | ||
"GridView", "Move", "RotateX", | ||
"RotateY", "RotateZ", "Rotate", | ||
"Fade", "Radius", "CanvasTool", | ||
"BasicLayout" | ||
]; | ||
this.commands= { | ||
loadcmd_json:{ | ||
help: ` | ||
Executes a CMD Shell Command | ||
and loads the stdout to a variable after trying to convert the result | ||
to JSON format | ||
The first argument is the variable name followed by an equal sign "=". | ||
Example: | ||
> .loadcmd_json result = cat somefile.json | ||
The above command will save the content of somefile.json using cat into the variable global.result | ||
as JSON format | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var cmdArguments = commandArgs.slice(2).join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
try { | ||
_rplServer.context[_variableName] = JSON.parse(stdout); | ||
} catch (e){ | ||
logger.debug("It was not possible to parse the data."); | ||
} | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} else { | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} | ||
}, | ||
loadcmd_str:{ | ||
help: ` | ||
Executes a CMD Shell Command | ||
and loads the stdout to a variable. | ||
The first argument is the variable name followed by an equal sign "=". | ||
Example: | ||
> .loadcmd_str foo = ls * | ||
The above command will save the output of "ls *" into the variable global.foo as string | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var cmdArguments = commandArgs.slice(2).join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
_rplServer.context[_variableName] = stdout; | ||
}, | ||
loadcmd_str:{ | ||
help: ` | ||
Executes a CMD Shell Command | ||
and loads the stdout to a variable. | ||
The first argument is the variable name followed by an equal sign "=". | ||
Example: | ||
> .loadcmd_str foo = ls * | ||
The above command will save the output of "ls *" into the variable global.foo as string | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var cmdArguments = commandArgs.slice(2).join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
_rplServer.context[_variableName] = stdout; | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} else { | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} | ||
}, | ||
save_json:{ | ||
help: ` | ||
Serializes a variable using JSON.stringify | ||
and saves it in a file. | ||
The first argument is the variable name and the second argument is the name of the file. | ||
Example: | ||
> .save_json foo ./filename | ||
The above command will save the stringified content of foo into ./filename | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>=2){ | ||
var _variableName = commandArgs[0]; | ||
var _filename = commandArgs[1].toString(); | ||
logger.debug(`Saving variable ${_variableName} in ${_filename}...`); | ||
var data = JSON.stringify(_rplServer.context[_variableName]); | ||
fs.writeFile(_filename, data, (err) => { | ||
if (err) throw err; | ||
logger.debug(`The data of the file ${_filename} has been saved!`); | ||
_rplServer.displayPrompt(); | ||
}); | ||
} else { | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} | ||
}, | ||
load_json:{ | ||
help: ` | ||
Loads a json from a file and saves it into a variable. | ||
The first argument is the variable name and the second argument is the name of the file. | ||
Example: | ||
> .load_json foo = ./filename | ||
The above command will load a json from ./filename and save it in global.foo as an object | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var _filename = commandArgs[2].toString(); | ||
logger.debug(`Trying to read ${_variableName} from ${_filename}...`); | ||
fs.readFile(_filename,(err, data) => { | ||
}, | ||
save_json:{ | ||
help: ` | ||
Serializes a variable using JSON.stringify | ||
and saves it in a file. | ||
The first argument is the variable name and the second argument is the name of the file. | ||
Example: | ||
> .save_json foo ./filename | ||
The above command will save the stringified content of foo into ./filename | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>=2){ | ||
var _variableName = commandArgs[0]; | ||
var _filename = commandArgs[1].toString(); | ||
logger.debug(`Saving variable ${_variableName} in ${_filename}...`); | ||
var data = JSON.stringify(_rplServer.context[_variableName]); | ||
fs.writeFile(_filename, data, (err) => { | ||
if (err) throw err; | ||
try { | ||
_rplServer.context[_variableName] = JSON.parse(data.toString()); | ||
logger.debug(`The data of the file ${_filename} has been loaded!`); | ||
} catch (e){ | ||
logger.debug("It was not possible to parse the data."); | ||
} | ||
logger.debug(`The data of the file ${_filename} has been saved!`); | ||
_rplServer.displayPrompt(); | ||
}); | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} else { | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
}, | ||
load_json:{ | ||
help: ` | ||
Loads a json from a file and saves it into a variable. | ||
The first argument is the variable name and the second argument is the name of the file. | ||
Example: | ||
> .load_json foo = ./filename | ||
The above command will load a json from ./filename and save it in global.foo as an object | ||
`, | ||
action(args) { | ||
let _rplServer = this; | ||
var commandArgs = args.split(" "); | ||
if (commandArgs.length>2){ | ||
var _variableName = commandArgs[0]; | ||
var _equal_sign = commandArgs[1].toString(); | ||
if (_equal_sign === "="){ | ||
var _filename = commandArgs[2].toString(); | ||
logger.debug(`Trying to read ${_variableName} from ${_filename}...`); | ||
fs.readFile(_filename,(err, data) => { | ||
if (err) throw err; | ||
try { | ||
_rplServer.context[_variableName] = JSON.parse(data.toString()); | ||
logger.debug(`The data of the file ${_filename} has been loaded!`); | ||
} catch (e){ | ||
logger.debug("It was not possible to parse the data."); | ||
} | ||
_rplServer.displayPrompt(); | ||
}); | ||
} else { | ||
console.log("That is no good my friend. You need to specify an equal sign."); | ||
_rplServer.displayPrompt(); | ||
} | ||
} else { | ||
console.log("No enough data in the command line. Try .help"); | ||
_rplServer.displayPrompt(); | ||
} | ||
} | ||
}, | ||
cmd:{ | ||
help: "Executes a CMD Shell Command", | ||
action() { | ||
let _rplServer = this; | ||
var cmdArguments = [...arguments].join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} | ||
} | ||
}, | ||
cmd:{ | ||
help: "Executes a CMD Shell Command", | ||
action() { | ||
let _rplServer = this; | ||
var cmdArguments = [...arguments].join(" "); | ||
_rplServer.clearBufferedCommand(); | ||
logger.debug(`Executing... ${cmdArguments}`); | ||
exec(cmdArguments, (err, stdout, stderr) => { | ||
_rplServer.displayPrompt(); | ||
}).stdout.on("data", function(data) { | ||
console.log(data); | ||
}); | ||
} | ||
} | ||
}, | ||
start:function (){ | ||
var collabServer = this; | ||
const vm = require("vm"); | ||
let sandbox = { | ||
require:require, | ||
module:module, | ||
__dirname:"./", | ||
__filename:"qcobjects-collab" | ||
}; | ||
global = require("qcobjects"); | ||
global.require = require.bind(global); | ||
global.module = module; | ||
global.__dirname = "./"; | ||
global.__filename = "qcobjects-collab"; | ||
global = vm.createContext(global); | ||
var net = require("net"), | ||
repl = require("repl"); | ||
global.connections = 0; | ||
function unlink_socket (){ | ||
try { | ||
logger.debug("Trying to delete the socket... "); | ||
fs.unlink(CONFIG.get("collab-unix-socket",unixsocket_default), (err) => { | ||
if (err) { | ||
logger.debug("Unix Socket does not exist"); | ||
} | ||
logger.debug("Unix Socket was deleted before start"); | ||
}); | ||
} catch (e){ | ||
// socket doesnt exists | ||
logger.debug("Unix Socket was not deleted"); | ||
} | ||
} | ||
unlink_socket(); | ||
var _defineReplCommands = function (_cmdReplServer,commands){ | ||
for (var _command in commands){ | ||
_cmdReplServer.defineCommand(_command, commands[_command]); | ||
runScript(context){ | ||
const runScript = (code,logOutput=false)=>{ | ||
const options = {filename:sandbox.__filename}; | ||
const backgroundRunScript = (code)=>{ | ||
var output = vm.runInContext(code,context,options); | ||
return output; | ||
}; | ||
var output = backgroundRunScript(code); | ||
if (logOutput && typeof output !== "undefined"){ | ||
console.log(output); | ||
} | ||
}; | ||
} | ||
start (){ | ||
var collabServer = this; | ||
const vm = require("vm"); | ||
let sandbox = { | ||
require:require, | ||
module:module, | ||
__dirname:"./", | ||
__filename:"qcobjects-collab" | ||
}; | ||
global = require("qcobjects"); | ||
global.require = require.bind(global); | ||
global.module = module; | ||
global.__dirname = "./"; | ||
global.__filename = "qcobjects-collab"; | ||
global = vm.createContext(global); | ||
var net = require("net"), | ||
repl = require("repl"); | ||
global.connections = 0; | ||
function unlink_socket (){ | ||
try { | ||
logger.debug("Trying to delete the socket... "); | ||
fs.unlink(CONFIG.get("collab-unix-socket",unixsocket_default), (err) => { | ||
if (err) { | ||
logger.debug("Unix Socket does not exist"); | ||
} | ||
logger.debug("Unix Socket was deleted before start"); | ||
}); | ||
} catch (e){ | ||
// socket doesnt exists | ||
logger.debug("Unix Socket was not deleted"); | ||
} | ||
} | ||
}; | ||
let replServer = repl.start({ | ||
useColors: true, | ||
prompt:"QCObjects Collab> ", | ||
terminal: true, | ||
useGlobal: false | ||
}); | ||
replServer.context = global; | ||
replServer.on("exit", () => { | ||
unlink_socket(); | ||
console.log("Thank you for using QCObjects Collab for Data Science!"); | ||
console.log("Have a nice day!"); | ||
process.exit(); | ||
}); | ||
_defineReplCommands(replServer,collabServer.commands); | ||
let unixsocket_server = net.createServer(function (unixsocket) { | ||
unixsocket.on("end", () => { | ||
logger.debug("A Unix socket connection was ended"); | ||
var _defineReplCommands = function (_cmdReplServer,commands){ | ||
for (var _command in commands){ | ||
_cmdReplServer.defineCommand(_command, commands[_command]); | ||
} | ||
}; | ||
let replServer = repl.start({ | ||
useColors: true, | ||
prompt:"QCObjects Collab> ", | ||
terminal: true, | ||
useGlobal: false | ||
}); | ||
replServer.context = global; | ||
replServer.on("exit", () => { | ||
unlink_socket(); | ||
console.log("Thank you for using QCObjects Collab for Data Science!"); | ||
console.log("Have a nice day!"); | ||
process.exit(); | ||
}); | ||
global.connections += 1; | ||
let unixReplServer = repl.start({ | ||
prompt: "QCObjects Collab> " | ||
, input: unixsocket | ||
, output: unixsocket | ||
, terminal: true | ||
, useGlobal: false | ||
_defineReplCommands(replServer,collabServer.commands); | ||
let unixsocket_server = net.createServer(function (unixsocket) { | ||
unixsocket.on("end", () => { | ||
logger.debug("A Unix socket connection was ended"); | ||
}); | ||
global.connections += 1; | ||
let unixReplServer = repl.start({ | ||
prompt: "QCObjects Collab> " | ||
, input: unixsocket | ||
, output: unixsocket | ||
, terminal: true | ||
, useGlobal: false | ||
}); | ||
unixReplServer.on("exit", function () { | ||
unixsocket.end(); | ||
}); | ||
unixReplServer.context=global; | ||
_defineReplCommands(unixReplServer,collabServer.commands); | ||
}).listen(CONFIG.get("collab-unix-socket",unixsocket_default)); | ||
let http_server = net.createServer(function (httpsocket) { | ||
httpsocket.on("end", () => { | ||
logger.debug("A http connection was ended"); | ||
}); | ||
global.connections += 1; | ||
let httpReplServer = repl.start({ | ||
prompt: "QCObjects Collab> " | ||
, input: httpsocket | ||
, output: httpsocket | ||
, terminal: true | ||
, useGlobal: false | ||
}); | ||
httpReplServer.on("exit", function () { | ||
httpsocket.end(); | ||
}); | ||
httpReplServer.context=global; | ||
_defineReplCommands(httpReplServer,collabServer.commands); | ||
}).listen(CONFIG.get("collab-port",collab_port_default),CONFIG.get("collab-domain",collab_domain_default)); | ||
http_server.on("error", function (e) { | ||
if (e.code == "EADDRINUSE") { | ||
console.log("Collab HTTP Address in use, retrying..."); | ||
setTimeout(function () { | ||
http_server.close(); | ||
http_server.listen(CONFIG.get("collab-port",collab_port_default),CONFIG.get("collab-domain",collab_domain_default)); | ||
}, 1000); | ||
} | ||
}); | ||
unixReplServer.on("exit", function () { | ||
unixsocket.end(); | ||
unixsocket_server.on("error", function (e) { | ||
if (e.code == "EADDRINUSE") { | ||
console.log("Collab Unix Socket Address in use, retrying..."); | ||
setTimeout(function () { | ||
unixsocket_server.close(); | ||
unixsocket_server.listen(CONFIG.get("collab-unix-socket",unixsocket_default)); | ||
}, 1000); | ||
} | ||
}); | ||
unixReplServer.context=global; | ||
_defineReplCommands(unixReplServer,collabServer.commands); | ||
}).listen(CONFIG.get("collab-unix-socket",unixsocket_default)); | ||
let http_server = net.createServer(function (httpsocket) { | ||
httpsocket.on("end", () => { | ||
logger.debug("A http connection was ended"); | ||
}); | ||
global.connections += 1; | ||
let httpReplServer = repl.start({ | ||
prompt: "QCObjects Collab> " | ||
, input: httpsocket | ||
, output: httpsocket | ||
, terminal: true | ||
, useGlobal: false | ||
}); | ||
httpReplServer.on("exit", function () { | ||
httpsocket.end(); | ||
}); | ||
httpReplServer.context=global; | ||
_defineReplCommands(httpReplServer,collabServer.commands); | ||
}).listen(CONFIG.get("collab-port",collab_port_default),CONFIG.get("collab-domain",collab_domain_default)); | ||
http_server.on("error", function (e) { | ||
if (e.code == "EADDRINUSE") { | ||
console.log("Collab HTTP Address in use, retrying..."); | ||
setTimeout(function () { | ||
http_server.close(); | ||
http_server.listen(CONFIG.get("collab-port",collab_port_default),CONFIG.get("collab-domain",collab_domain_default)); | ||
}, 1000); | ||
} | ||
}); | ||
unixsocket_server.on("error", function (e) { | ||
if (e.code == "EADDRINUSE") { | ||
console.log("Collab Unix Socket Address in use, retrying..."); | ||
setTimeout(function () { | ||
unixsocket_server.close(); | ||
unixsocket_server.listen(CONFIG.get("collab-unix-socket",unixsocket_default)); | ||
}, 1000); | ||
} | ||
}); | ||
} | ||
} | ||
}); | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -4,0 +4,0 @@ * |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -36,22 +36,72 @@ * | ||
const absolutePath = path.resolve( __dirname, "./" ); | ||
const absolutePath = path.resolve(__dirname, "./"); | ||
Package("org.quickcorp.qcobjects.main.file",[ | ||
Class("FileDispatcher",{ | ||
name:CONFIG.get("documentRootFileIndex"), | ||
template:"", | ||
templateURI:CONFIG.get("documentRootFileIndex"), | ||
headers:{}, | ||
body:"", | ||
filename:"", | ||
file_extension:function (){ | ||
Package("org.quickcorp.qcobjects.main.file", [ | ||
class FileDispatcher extends InheritClass { | ||
constructor({ | ||
name = CONFIG.get("documentRootFileIndex"), | ||
template = "", | ||
templateURI = CONFIG.get("documentRootFileIndex"), | ||
headers = {}, | ||
body = "", | ||
filename = "" | ||
}) { | ||
super(...arguments); | ||
var o = this; | ||
var scriptname = o.scriptname; | ||
this.filename = scriptname; | ||
var pathname = (o.pathname !== "") ? (o.pathname + "/") : (""); | ||
var appTemplateInstance = this; | ||
if (typeof appTemplateInstance.headers === "undefined"){ | ||
appTemplateInstance.headers = { | ||
":status": 500, | ||
"content-type": "text/html" | ||
}; | ||
} | ||
appTemplateInstance.done = o.done; | ||
appTemplateInstance.templateURI = CONFIG.get("documentRoot") + pathname + scriptname; | ||
appTemplateInstance.templateURI = appTemplateInstance.templateURI.replace("//", "/"); | ||
if (appTemplateInstance.isTemplate()) { | ||
fs.readFile(appTemplateInstance.templateURI, function (err, data) { | ||
logger.debug("reading data from " + appTemplateInstance.templateURI); | ||
if (typeof data !== "undefined") { | ||
appTemplateInstance.template = data.toString(); | ||
appTemplateInstance._done.call(appTemplateInstance); | ||
} else { | ||
appTemplateInstance.headers = { | ||
":status": 404, | ||
"content-type": "text/html" | ||
}; | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
appTemplateInstance.headers, | ||
"FILE NOT FOUND", "notfound.html", false); | ||
logger.debug("file not found"); | ||
} | ||
}); | ||
} else { | ||
appTemplateInstance.headers[":status"] = 200; | ||
appTemplateInstance.headers["content-type"] = mime.getType(appTemplateInstance.templateURI); | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
appTemplateInstance.headers, | ||
"", appTemplateInstance.templateURI, false); | ||
} | ||
logger.info("FileDispatcher initialized"); | ||
} | ||
file_extension() { | ||
return this.filename.substr(this.filename.indexOf(".")); | ||
}, | ||
isTemplate:function (){ | ||
return CONFIG.get("useTemplate") && (this.file_extension()==".html" || this.file_extension() == ".tpl.html"); | ||
}, | ||
_done:function (){ | ||
} | ||
isTemplate() { | ||
return CONFIG.get("useTemplate") && (this.file_extension() == ".html" || this.file_extension() == ".tpl.html"); | ||
} | ||
_done() { | ||
var appTemplateInstance = this; | ||
const source = appTemplateInstance.template; | ||
if (appTemplateInstance.isTemplate()){ | ||
if (appTemplateInstance.isTemplate()) { | ||
@@ -61,3 +111,3 @@ (New(Component, { | ||
template: source, | ||
cached:false, | ||
cached: false, | ||
tplsource: "inline", | ||
@@ -67,5 +117,11 @@ data: { | ||
}, | ||
done ({request, component}) { | ||
done({ | ||
request, | ||
component | ||
}) { | ||
appTemplateInstance.body = component.parsedAssignmentText; | ||
return Promise.resolve({request, component}); | ||
return Promise.resolve({ | ||
request, | ||
component | ||
}); | ||
} | ||
@@ -79,64 +135,29 @@ })); | ||
if ([".png", | ||
".jpg", | ||
".jpeg", | ||
".json", | ||
".html", | ||
".tpl.html", | ||
".css", | ||
".js", | ||
".svg"].includes(appTemplateInstance.file_extension())){ | ||
appTemplateInstance.headers["content-type"]=mime.getType(appTemplateInstance.templateURI); | ||
appTemplateInstance.headers["cache-control"]=CONFIG.get("cacheControl", "max-age=31536000"); | ||
".jpg", | ||
".jpeg", | ||
".json", | ||
".html", | ||
".tpl.html", | ||
".css", | ||
".js", | ||
".svg" | ||
].includes(appTemplateInstance.file_extension())) { | ||
appTemplateInstance.headers["content-type"] = mime.getType(appTemplateInstance.templateURI); | ||
appTemplateInstance.headers["cache-control"] = CONFIG.get("cacheControl", "max-age=31536000"); | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
appTemplateInstance.headers, | ||
appTemplateInstance.body, | ||
appTemplateInstance.templateURI, | ||
appTemplateInstance.isTemplate()); | ||
appTemplateInstance.headers, | ||
appTemplateInstance.body, | ||
appTemplateInstance.templateURI, | ||
appTemplateInstance.isTemplate()); | ||
} else { | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
{ | ||
":status": 403, | ||
"content-type": "text/plain" | ||
}, | ||
"FORBIDDEN","notfound.html",false); | ||
appTemplateInstance.done.call(appTemplateInstance, { | ||
":status": 403, | ||
"content-type": "text/plain" | ||
}, | ||
"FORBIDDEN", "notfound.html", false); | ||
} | ||
}, | ||
done:function (headers,body){}, | ||
_new_:function (o){ | ||
var scriptname = o.scriptname; | ||
this.filename = scriptname; | ||
var pathname = (o.pathname !== "")?(o.pathname+"/"):(""); | ||
var appTemplateInstance = this; | ||
appTemplateInstance.done = o.done; | ||
appTemplateInstance.templateURI = CONFIG.get("documentRoot")+pathname+scriptname; | ||
appTemplateInstance.templateURI = appTemplateInstance.templateURI.replace("//","/"); | ||
} | ||
done(headers, body) {} | ||
if (appTemplateInstance.isTemplate()){ | ||
fs.readFile(appTemplateInstance.templateURI, function(err, data) { | ||
logger.debug("reading data from "+appTemplateInstance.templateURI); | ||
if (typeof data !== "undefined"){ | ||
appTemplateInstance.template = data.toString(); | ||
appTemplateInstance._done.call(appTemplateInstance); | ||
} else { | ||
appTemplateInstance.headers = { | ||
":status": 404, | ||
"content-type": "text/html" | ||
}; | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
appTemplateInstance.headers, | ||
"FILE NOT FOUND","notfound.html",false); | ||
logger.debug("file not found"); | ||
} | ||
}); | ||
} else { | ||
appTemplateInstance.headers[":status"]=200; | ||
appTemplateInstance.headers["content-type"]=mime.getType(appTemplateInstance.templateURI); | ||
appTemplateInstance.done.call(appTemplateInstance, | ||
appTemplateInstance.headers, | ||
"",appTemplateInstance.templateURI,false); | ||
} | ||
logger.info("FileDispatcher initialized"); | ||
} | ||
}) | ||
]); | ||
} | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -34,35 +34,76 @@ * | ||
const path = require("path"); | ||
const absolutePath = path.resolve( __dirname, "./" ); | ||
const absolutePath = path.resolve(__dirname, "./"); | ||
const fs = require("fs"); | ||
const mime = require("mime"); | ||
require(absolutePath+"/org.quickcorp.qcobjects.main.file.js"); | ||
require(absolutePath + "/org.quickcorp.qcobjects.main.file.js"); | ||
require(absolutePath+ "/org.qcobjects.common.pipelog.js"); | ||
let ImportMicroservice = function (microservicePackage){ | ||
var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage+".js"); | ||
if (standardPath !== null){ | ||
Import (microservicePackage); | ||
let ImportMicroservice = function (microservicePackage) { | ||
var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage + ".js"); | ||
if (standardPath !== null) { | ||
Import(microservicePackage); | ||
} else { | ||
Import (absolutePath+"/backend/"+microservicePackage); | ||
Import(absolutePath + "/backend/" + microservicePackage); | ||
} | ||
}; | ||
Package("org.quickcorp.qcobjects.main.http.gae.server",[ | ||
Class("BackendMicroservice",Object,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
body:null, | ||
stream:null, | ||
server:null, | ||
request:null, | ||
cors: function (){ | ||
if (this.route.cors){ | ||
let {allow_origins,allow_credentials,allow_methods,allow_headers} = this.route.cors; | ||
Package("org.quickcorp.qcobjects.main.http.gae.server", [ | ||
class BackendMicroservice extends InheritClass { | ||
constructor(o) { | ||
super(...arguments); | ||
this.domain = CONFIG.get("domain"); | ||
this.basePath = CONFIG.get("basePath"); | ||
logger.debug("Executing GAE HTTP BackendMicroservice "); | ||
let microservice = this; | ||
let server = microservice.server; | ||
let request = microservice.request; | ||
this.cors(); | ||
microservice.req.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = { | ||
"post": microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods, requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice, data); | ||
} | ||
}); | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = { | ||
"get": microservice.get, | ||
"head": microservice.head, | ||
"put": microservice.put, | ||
"delete": microservice.delete, | ||
"connect": microservice.connect, | ||
"options": microservice.options, | ||
"trace": microservice.trace, | ||
"patch": microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods, requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
} | ||
cors() { | ||
if (this.route.cors) { | ||
let { | ||
allow_origins, | ||
allow_credentials, | ||
allow_methods, | ||
allow_headers | ||
} = this.route.cors; | ||
var microservice = this; | ||
if (typeof microservice.headers !== "object"){ | ||
if (typeof microservice.headers !== "object") { | ||
microservice.headers = {}; | ||
} | ||
if (typeof allow_origins !== "undefined"){ | ||
if (typeof allow_origins !== "undefined") { | ||
// an example of allow_origins is ['https://example.com','http://www.example.com'] | ||
if (allow_origins =="*" || (typeof microservice.request.headers.origin == "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin)!== -1){ | ||
if (allow_origins == "*" || (typeof microservice.request.headers.origin == "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin) !== -1) { | ||
// for compatibility with all browsers allways return a wildcard when the origin is allowed | ||
@@ -76,3 +117,3 @@ microservice.headers["Access-Control-Allow-Origin"] = "*"; | ||
this.done(); | ||
} catch (e){} | ||
} catch (e) {} | ||
} | ||
@@ -82,3 +123,3 @@ } else { | ||
} | ||
if (typeof allow_credentials !== "undefined"){ | ||
if (typeof allow_credentials !== "undefined") { | ||
microservice.headers["Access-Control-Allow-Credentials"] = allow_credentials.toString(); | ||
@@ -88,3 +129,3 @@ } else { | ||
} | ||
if (typeof allow_methods !== "undefined"){ | ||
if (typeof allow_methods !== "undefined") { | ||
microservice.headers["Access-Control-Allow-Methods"] = [...allow_methods].join(","); | ||
@@ -94,3 +135,3 @@ } else { | ||
} | ||
if (typeof allow_headers !== "undefined"){ | ||
if (typeof allow_headers !== "undefined") { | ||
microservice.headers["Access-Control-Allow-Headers"] = [...allow_headers].join(","); | ||
@@ -101,52 +142,38 @@ } else { | ||
} | ||
}, | ||
_new_:function (o){ | ||
logger.debug("Executing GAE HTTP BackendMicroservice "); | ||
let microservice = this; | ||
let server = microservice.server; | ||
let request = microservice.request; | ||
this.cors(); | ||
microservice.req.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"post":microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice,data); | ||
} | ||
}); | ||
} | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"get":microservice.get, | ||
"head":microservice.head, | ||
"put":microservice.put, | ||
"delete":microservice.delete, | ||
"connect":microservice.connect, | ||
"options":microservice.options, | ||
"trace":microservice.trace, | ||
"patch":microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
}, | ||
head:function (formData){this.done();}, | ||
post:function (formData){this.done();}, | ||
put:function (formData){this.done();}, | ||
delete:function (formData){this.done();}, | ||
connect:function (formData){this.done();}, | ||
options:function (formData){this.done();}, | ||
trace:function (formData){this.done();}, | ||
patch:function (formData){this.done();}, | ||
finishWithBody:function (stream){ | ||
head(formData) { | ||
this.done(); | ||
} | ||
post(formData) { | ||
this.done(); | ||
} | ||
put(formData) { | ||
this.done(); | ||
} | ||
delete(formData) { | ||
this.done(); | ||
} | ||
connect(formData) { | ||
this.done(); | ||
} | ||
options(formData) { | ||
this.done(); | ||
} | ||
trace(formData) { | ||
this.done(); | ||
} | ||
patch(formData) { | ||
this.done(); | ||
} | ||
finishWithBody(stream) { | ||
try { | ||
stream.write(JSON.stringify(this.body)); | ||
stream.end(); | ||
} catch (e){ | ||
logger.debug("Something wrong writing the response for microservice"+e.toString()); | ||
} catch (e) { | ||
logger.debug("Something wrong writing the response for microservice" + e.toString()); | ||
} | ||
}, | ||
done: function(){ | ||
} | ||
done() { | ||
var microservice = this; | ||
@@ -156,41 +183,31 @@ var stream = microservice.stream; | ||
stream.writeHead(200, microservice.headers); | ||
} catch (e){ | ||
} catch (e) { | ||
logger.debug("Something went wront while sending headers in http..."); | ||
logger.debug(e.toString()); | ||
} | ||
if (microservice.body != null){ | ||
microservice.finishWithBody.call(microservice,stream); | ||
if (microservice.body != null) { | ||
microservice.finishWithBody.call(microservice, stream); | ||
} | ||
} | ||
}), | ||
Class("PipeLog",{ | ||
pipe:(o)=>{ | ||
var _o = []; | ||
for (var k in o){ | ||
if (typeof o[k] !== "undefined" | ||
&& o[k] !== null | ||
&& typeof o[k] !== "function"){ | ||
try { | ||
_o.push(""+k+"="+o[k].toString()); | ||
} catch (e){ | ||
// error logging, do nothing | ||
} | ||
} | ||
} | ||
return _o.join(" "); | ||
}, | ||
class HTTPServerResponse extends InheritClass { | ||
constructor(o) { | ||
super(...arguments); | ||
var self = this; | ||
self.body = ""; | ||
self.stream = o.stream; | ||
self._generateResponse(); | ||
this.headers = { | ||
":status": 200, | ||
"content-type": "text/html" | ||
}; | ||
} | ||
}), | ||
Class("HTTPServerResponse",{ | ||
headers:{ | ||
":status": 200, | ||
"content-type": "text/html" | ||
}, | ||
body:"", | ||
request:null, | ||
fileDispatcher:null, | ||
sendFile: function (stream, fileName) { | ||
sendFile(stream, fileName) { | ||
// read and send file content in the stream | ||
try { | ||
console.log("trying to read "+ fileName); | ||
console.log("trying to read " + fileName); | ||
const fd = fs.openSync(fileName, "r"); | ||
@@ -220,3 +237,3 @@ const stat = fs.fstatSync(fd); | ||
readStream.on("end",function (){ | ||
readStream.on("end", function () { | ||
stream.end(); | ||
@@ -226,8 +243,8 @@ }); | ||
// This catches any errors that happen while creating the readable stream (usually invalid names) | ||
readStream.on("error", function(err) { | ||
readStream.on("error", function (err) { | ||
stream.end(err); | ||
}); | ||
} catch (e){ | ||
if (e.errno==-2){ | ||
} catch (e) { | ||
if (e.errno == -2) { | ||
const headers = { | ||
@@ -244,22 +261,23 @@ ":status": 404, | ||
} | ||
}, | ||
_generateResponse:function (){ | ||
} | ||
_generateResponse() { | ||
var response = this; | ||
response.fileDispatcher = New(FileDispatcher,{ | ||
scriptname:response.request.scriptname, | ||
pathname:response.request.pathname, | ||
done:function (headers,body,templateURI,isTemplate){ | ||
response.fileDispatcher = New(FileDispatcher, { | ||
scriptname: response.request.scriptname, | ||
pathname: response.request.pathname, | ||
done(headers, body, templateURI, isTemplate) { | ||
response.headers = headers; | ||
var stream = response.stream; | ||
if (isTemplate){ | ||
if (isTemplate) { | ||
logger.debug("TEMPLATE"); | ||
response.body = body; | ||
// stream.respond(response.headers); | ||
// stream.respond(response.headers); | ||
stream.write(response.body); | ||
stream.end(); | ||
} else if (headers[":status"]==200){ | ||
response.sendFile(stream,templateURI); | ||
} else if (headers[":status"] == 200) { | ||
response.sendFile(stream, templateURI); | ||
} else { | ||
logger.debug("NONE "); | ||
// stream.respond(response.headers); | ||
// stream.respond(response.headers); | ||
stream.end(); | ||
@@ -270,65 +288,42 @@ } | ||
}, | ||
_new_:function (o){ | ||
var self = this; | ||
self.body = ""; | ||
self.stream = o.stream; | ||
self._generateResponse(); | ||
} | ||
}, | ||
class HTTPServerRequest extends InheritClass { | ||
constructor({ | ||
scriptname = "", | ||
path = "", | ||
method = "", | ||
url = "", | ||
headers = null, | ||
flags = null, | ||
protocol = null, | ||
slashes = null, | ||
auth = null, | ||
host = null, | ||
port = null, | ||
hostname = null, | ||
hash = null, | ||
search = "", | ||
query = "", | ||
pathname = "", | ||
href = "" | ||
}) { | ||
super(...arguments); | ||
} | ||
}), | ||
Class("HTTPServerRequest",{ | ||
scriptname:"", | ||
path:"", | ||
method:"", | ||
url:"", | ||
headers:null, | ||
flags:null, | ||
protocol: null, | ||
slashes: null, | ||
auth: null, | ||
host: null, | ||
port: null, | ||
hostname: null, | ||
hash: null, | ||
search: "", | ||
query: "", | ||
pathname: "", | ||
href: "" | ||
}), | ||
Class("HTTPServer",{ | ||
request:null, | ||
response:"", | ||
server:null, | ||
scriptname:"", | ||
interceptorInstances:[], | ||
showIPAddress:function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
_ret_ += iface +": " + PipeLog.pipe(ipGroup)+"\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
showPossibleURL: function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
if (ipGroup["family"].toLowerCase()=="ipv4"){ | ||
_ret_ += "http://"+ipGroup["address"]+":"+CONFIG.get("serverPortHTTP").toString()+"/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
start:function (){ | ||
var server = this.server; | ||
server.listen(process.env.PORT || CONFIG.get("serverPortHTTP")); | ||
}, | ||
_new_:function (){ | ||
}, | ||
class HTTPServer extends InheritClass { | ||
constructor({ | ||
request = null, | ||
response = "", | ||
server = null, | ||
scriptname = "", | ||
interceptorInstances = [] | ||
}) { | ||
super(...arguments); | ||
let oHTTPServer = this; | ||
@@ -342,4 +337,4 @@ const welcometo = "Welcome to \n"; | ||
logger.debug(this.showIPAddress()); | ||
logger.info("Listening on HTTP PORT: "+CONFIG.get("serverPortHTTP").toString()); | ||
logger.info("Go to: \n"+this.showPossibleURL()); | ||
logger.info("Listening on HTTP PORT: " + CONFIG.get("serverPortHTTP").toString()); | ||
logger.info("Go to: \n" + this.showPossibleURL()); | ||
@@ -356,16 +351,16 @@ const http = require("http"); | ||
if (global.get("backendAvailable")){ | ||
if (global.get("backendAvailable")) { | ||
logger.info("Loading backend interceptors..."); | ||
let interceptors = CONFIG.get("backend",{}).interceptors; | ||
if (typeof interceptors !== "undefined"){ | ||
let interceptors = CONFIG.get("backend", {}).interceptors; | ||
if (typeof interceptors !== "undefined") { | ||
logger.info("Backend Interceptors Available"); | ||
interceptors.map(interceptor=>{ | ||
ImportMicroservice (interceptor.microservice); | ||
var interceptorClassFactory = ClassFactory(interceptor.microservice+".Interceptor"); | ||
var interceptorInstance = New(interceptorClassFactory,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
interceptor:interceptor, | ||
server:server | ||
interceptors.map(interceptor => { | ||
ImportMicroservice(interceptor.microservice); | ||
var interceptorClassFactory = ClassFactory(interceptor.microservice + ".Interceptor"); | ||
var interceptorInstance = New(interceptorClassFactory, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
interceptor: interceptor, | ||
server: server | ||
}); | ||
@@ -379,3 +374,3 @@ oHTTPServer.interceptorInstances.push(interceptorInstance); | ||
let request = Object.assign(New(HTTPServerRequest),require("url").parse(req.url)); | ||
let request = Object.assign(New(HTTPServerRequest), require("url").parse(req.url)); | ||
request.headers = req.headers; | ||
@@ -386,14 +381,14 @@ this.request = request; | ||
server.setMaxListeners(9999999999); | ||
CONFIG.set("backendTimeout",CONFIG.get("backendTimeout") || 20000); | ||
var timeoutHandler = ()=>{ | ||
CONFIG.set("backendTimeout", CONFIG.get("backendTimeout") || 20000); | ||
var timeoutHandler = () => { | ||
// end the stream on timeout | ||
try { | ||
if (!res.destroyed){ | ||
if (!res.destroyed) { | ||
logger.info("A timeout occurred..." + CONFIG.get("backendTimeout").toString()); | ||
logger.info("Killing session..."); | ||
res.writeHeader( 500, { | ||
res.writeHeader(500, { | ||
"content-type": "text/html" | ||
}); | ||
res.on("error",()=>{}); | ||
res.on("error", () => {}); | ||
res.write("<h1>500 - INTERNAL SERVER ERROR (TIMEOUT)</h1>"); | ||
@@ -404,49 +399,54 @@ res.end(); | ||
} | ||
}catch (e){ | ||
} catch (e) { | ||
logger.debug("An unhandled error occurred during timeout catching..."); | ||
logger.debug(e.message); | ||
} | ||
server.removeListener("timeout",timeoutHandler); | ||
server.removeListener("timeout", timeoutHandler); | ||
}; | ||
if (!res.destroyed){ | ||
if (!res.destroyed) { | ||
server.setTimeout(CONFIG.get("backendTimeout"), timeoutHandler); | ||
} | ||
if (this.request.pathname.indexOf(".")<0){ | ||
this.request.scriptname = CONFIG.get("documentRootFileIndex"); | ||
if (this.request.pathname.indexOf(".") < 0) { | ||
this.request.scriptname = CONFIG.get("documentRootFileIndex"); | ||
} else { | ||
this.request.scriptname = this.request.pathname.split("/").reverse()[0]; | ||
} | ||
this.request.pathname = this.request.pathname.substr(0,this.request.pathname.lastIndexOf("/")); | ||
this.request.pathname = this.request.pathname.substr(0, this.request.pathname.lastIndexOf("/")); | ||
logger.debug(PipeLog.pipe(this.request)); | ||
logger.debug((new PipeLog()).pipe(this.request)); | ||
if (global.get("backendAvailable")){ | ||
if (global.get("backendAvailable")) { | ||
logger.info("Backend GAE Microservices Available"); | ||
let routes = CONFIG.get("backend").routes; | ||
let selectedRoute = routes.filter(route=>{let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)");return (new RegExp(standardRoutePath,"g")).test(request.path);}); | ||
if (selectedRoute.length>0){ | ||
selectedRoute.map(route=>{ | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)"); //allowing {param} | ||
let selectedRouteParams = {...[...request.path.matchAll((new RegExp( standardRoutePath ,"g")))][0]["groups"]}; | ||
ImportMicroservice (route.microservice); | ||
var microServiceClassFactory = ClassFactory(route.microservice+".Microservice"); | ||
this.response = New(microServiceClassFactory,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
route:route, | ||
routeParams:selectedRouteParams, | ||
server:server, | ||
stream:res, | ||
req:req, | ||
request:request | ||
let selectedRoute = routes.filter(route => { | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)"); | ||
return (new RegExp(standardRoutePath, "g")).test(request.path); | ||
}); | ||
if (selectedRoute.length > 0) { | ||
selectedRoute.map(route => { | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)"); //allowing {param} | ||
let selectedRouteParams = { | ||
...[...request.path.matchAll((new RegExp(standardRoutePath, "g")))][0]["groups"] | ||
}; | ||
ImportMicroservice(route.microservice); | ||
var microServiceClassFactory = ClassFactory(route.microservice + ".Microservice"); | ||
this.response = New(microServiceClassFactory, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
route: route, | ||
routeParams: selectedRouteParams, | ||
server: server, | ||
stream: res, | ||
req: req, | ||
request: request | ||
}); | ||
}); | ||
} else { | ||
this.response = New(HTTPServerResponse,{ | ||
server:server, | ||
stream:res, | ||
request:this.request | ||
this.response = New(HTTPServerResponse, { | ||
server: server, | ||
stream: res, | ||
request: this.request | ||
}); | ||
@@ -458,6 +458,6 @@ } | ||
this.response = New(HTTPServerResponse,{ | ||
server:server, | ||
stream:res, | ||
request:this.request | ||
this.response = New(HTTPServerResponse, { | ||
server: server, | ||
stream: res, | ||
request: this.request | ||
}); | ||
@@ -470,3 +470,35 @@ | ||
} | ||
}) | ||
]); | ||
showIPAddress() { | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface) { | ||
ifaces[iface].map(function (ipGroup) { | ||
_ret_ += iface + ": " + (new PipeLog()).pipe(ipGroup) + "\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
showPossibleURL() { | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface) { | ||
ifaces[iface].map(function (ipGroup) { | ||
if (ipGroup["family"].toLowerCase() == "ipv4") { | ||
_ret_ += "http://" + ipGroup["address"] + ":" + CONFIG.get("serverPortHTTP").toString() + "/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
start() { | ||
var server = this.server; | ||
server.listen(process.env.PORT || CONFIG.get("serverPortHTTP")); | ||
} | ||
} | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -39,3 +39,5 @@ * | ||
require(absolutePath+"/org.quickcorp.qcobjects.main.file.js"); | ||
require(absolutePath+ "/org.qcobjects.common.pipelog.js"); | ||
let ImportMicroservice = function (microservicePackage){ | ||
@@ -51,10 +53,46 @@ var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage+".js"); | ||
Package("org.quickcorp.qcobjects.main.http.server",[ | ||
Class("BackendMicroservice",Object,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
body:null, | ||
stream:null, | ||
server:null, | ||
request:null, | ||
cors: function (){ | ||
class BackendMicroservice extends InheritClass { | ||
constructor({ | ||
domain=CONFIG.get("domain"), | ||
basePath=CONFIG.get("basePath"), | ||
body=null, | ||
stream=null, | ||
server=null, | ||
request=null | ||
}){ | ||
super(...arguments); | ||
logger.debug("Executing Legacy HTTP BackendMicroservice "); | ||
let microservice = this; | ||
this.cors(); | ||
microservice.req.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"post":microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice,data); | ||
} | ||
}); | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"get":microservice.get, | ||
"head":microservice.head, | ||
"put":microservice.put, | ||
"delete":microservice.delete, | ||
"connect":microservice.connect, | ||
"options":microservice.options, | ||
"trace":microservice.trace, | ||
"patch":microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
} | ||
cors(){ | ||
if (this.route.cors){ | ||
@@ -98,44 +136,12 @@ let {allow_origins,allow_credentials,allow_methods,allow_headers} = this.route.cors; | ||
} | ||
}, | ||
_new_:function (o){ | ||
logger.debug("Executing Legacy HTTP BackendMicroservice "); | ||
let microservice = this; | ||
let server = microservice.server; | ||
let request = microservice.request; | ||
this.cors(); | ||
microservice.req.on("data", (data) => { | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"post":microservice.post, | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice,data); | ||
} | ||
}); | ||
// data from POST, GET | ||
var requestMethod = request.method.toLowerCase(); | ||
var supportedMethods = {"get":microservice.get, | ||
"head":microservice.head, | ||
"put":microservice.put, | ||
"delete":microservice.delete, | ||
"connect":microservice.connect, | ||
"options":microservice.options, | ||
"trace":microservice.trace, | ||
"patch":microservice.patch | ||
}; | ||
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) { | ||
supportedMethods[requestMethod].call(microservice); | ||
} | ||
}, | ||
head:function (formData){this.done();}, | ||
post:function (formData){this.done();}, | ||
put:function (formData){this.done();}, | ||
delete:function (formData){this.done();}, | ||
connect:function (formData){this.done();}, | ||
options:function (formData){this.done();}, | ||
trace:function (formData){this.done();}, | ||
patch:function (formData){this.done();}, | ||
finishWithBody:function (stream){ | ||
} | ||
head(formData){this.done();} | ||
post(formData){this.done();} | ||
put(formData){this.done();} | ||
delete(formData){this.done();} | ||
connect(formData){this.done();} | ||
options(formData){this.done();} | ||
trace(formData){this.done();} | ||
patch(formData){this.done();} | ||
finishWithBody(stream){ | ||
try { | ||
@@ -147,4 +153,4 @@ stream.write(JSON.stringify(this.body)); | ||
} | ||
}, | ||
done: function(){ | ||
} | ||
done(){ | ||
var microservice = this; | ||
@@ -162,29 +168,26 @@ var stream = microservice.stream; | ||
} | ||
}), | ||
Class("PipeLog",{ | ||
pipe:(o)=>{ | ||
var _o = []; | ||
for (var k in o){ | ||
if (typeof o[k] !== "undefined" | ||
&& o[k] !== null | ||
&& typeof o[k] !== "function"){ | ||
try { | ||
_o.push(""+k+"="+o[k].toString()); | ||
} catch (e){ | ||
// error logging, do nothing | ||
} | ||
} | ||
} | ||
return _o.join(" "); | ||
}, | ||
class HTTPServerResponse extends InheritClass { | ||
constructor ({ | ||
headers={ | ||
":status": 200, | ||
"content-type": "text/html" | ||
}, | ||
body="", | ||
request=null, | ||
fileDispatcher=null, | ||
stream=null | ||
}){ | ||
super(...arguments); | ||
var self = this; | ||
self.stream = self.stream; | ||
self._generateResponse(); | ||
} | ||
}), | ||
Class("HTTPServerResponse",{ | ||
headers:{ | ||
":status": 200, | ||
"content-type": "text/html" | ||
}, | ||
body:"", | ||
request:null, | ||
fileDispatcher:null, | ||
sendFile: function (stream, fileName) { | ||
sendFile(stream, fileName) { | ||
// read and send file content in the stream | ||
@@ -240,4 +243,4 @@ | ||
} | ||
}, | ||
_generateResponse:function (){ | ||
} | ||
_generateResponse(){ | ||
var response = this; | ||
@@ -247,3 +250,3 @@ response.fileDispatcher = New(FileDispatcher,{ | ||
pathname:response.request.pathname, | ||
done:function (headers,body,templateURI,isTemplate){ | ||
done(headers,body,templateURI,isTemplate){ | ||
response.headers = headers; | ||
@@ -267,65 +270,40 @@ var stream = response.stream; | ||
}, | ||
_new_:function (o){ | ||
var self = this; | ||
self.body = ""; | ||
self.stream = o.stream; | ||
self._generateResponse(); | ||
} | ||
}, | ||
class HTTPServerRequest extends InheritClass { | ||
constructor ({ | ||
scriptname="", | ||
path="", | ||
method="", | ||
url="", | ||
headers=null, | ||
flags=null, | ||
protocol= null, | ||
slashes= null, | ||
auth= null, | ||
host= null, | ||
port= null, | ||
hostname= null, | ||
hash= null, | ||
search= "", | ||
query= "", | ||
pathname= "", | ||
href= "" | ||
}){ | ||
super(...arguments); | ||
} | ||
}), | ||
Class("HTTPServerRequest",{ | ||
scriptname:"", | ||
path:"", | ||
method:"", | ||
url:"", | ||
headers:null, | ||
flags:null, | ||
protocol: null, | ||
slashes: null, | ||
auth: null, | ||
host: null, | ||
port: null, | ||
hostname: null, | ||
hash: null, | ||
search: "", | ||
query: "", | ||
pathname: "", | ||
href: "" | ||
}), | ||
Class("HTTPServer",{ | ||
request:null, | ||
response:"", | ||
server:null, | ||
scriptname:"", | ||
interceptorInstances:[], | ||
showIPAddress:function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
_ret_ += iface +": " + PipeLog.pipe(ipGroup)+"\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
showPossibleURL: function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
if (ipGroup["family"].toLowerCase()=="ipv4"){ | ||
_ret_ += "http://"+ipGroup["address"]+":"+CONFIG.get("serverPortHTTP").toString()+"/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
start:function (){ | ||
var server = this.server; | ||
server.listen(process.env.PORT || CONFIG.get("serverPortHTTP")); | ||
}, | ||
_new_:function (){ | ||
}, | ||
class HTTPServer extends InheritClass { | ||
constructor ({ | ||
request=null, | ||
response="", | ||
server=null, | ||
scriptname="", | ||
interceptorInstances=[] | ||
}){ | ||
super(...arguments); | ||
let oHTTPServer = this; | ||
@@ -415,3 +393,3 @@ const welcometo = "Welcome to \n"; | ||
logger.debug(PipeLog.pipe(this.request)); | ||
logger.debug((new PipeLog()).pipe(this.request)); | ||
@@ -462,3 +440,35 @@ if (global.get("backendAvailable")){ | ||
} | ||
}) | ||
showIPAddress(){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
_ret_ += iface +": " + (new PipeLog()).pipe(ipGroup)+"\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
showPossibleURL(){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
if (ipGroup["family"].toLowerCase()=="ipv4"){ | ||
_ret_ += "http://"+ipGroup["address"]+":"+CONFIG.get("serverPortHTTP").toString()+"/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
start(){ | ||
var server = this.server; | ||
server.listen(process.env.PORT || CONFIG.get("serverPortHTTP")); | ||
} | ||
} | ||
]); |
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -24,3 +24,3 @@ * | ||
* license document, but changing it is not allowed. | ||
*/ | ||
*/ | ||
/*eslint no-unused-vars: "off"*/ | ||
@@ -35,3 +35,3 @@ /*eslint no-redeclare: "off"*/ | ||
const path = require("path"); | ||
const absolutePath = path.resolve( __dirname, "./" ); | ||
const absolutePath = path.resolve(__dirname, "./"); | ||
@@ -41,41 +41,35 @@ const http2 = require("http2"); | ||
const mime = require("mime"); | ||
require(absolutePath+"/org.quickcorp.qcobjects.main.file.js"); | ||
require(absolutePath + "/org.quickcorp.qcobjects.main.file.js"); | ||
require(absolutePath + "/org.qcobjects.common.pipelog.js"); | ||
let ImportMicroservice = function (microservicePackage){ | ||
var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage+".js"); | ||
if (standardPath !== null){ | ||
Import (microservicePackage); | ||
let ImportMicroservice = function (microservicePackage) { | ||
var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage + ".js"); | ||
if (standardPath !== null) { | ||
Import(microservicePackage); | ||
} else { | ||
Import (absolutePath+"/backend/"+microservicePackage); | ||
Import(absolutePath + "/backend/" + microservicePackage); | ||
} | ||
}; | ||
Package("org.quickcorp.qcobjects.main.http2.server",[ | ||
Class("PipeLog",{ | ||
pipe:(o)=>{ | ||
var _o = []; | ||
for (var k in o){ | ||
if (typeof o[k] !== "undefined" | ||
&& o[k] !== null | ||
&& typeof o[k] !== "function"){ | ||
try { | ||
_o.push(""+k+"="+o[k].toString()); | ||
} catch (e){ | ||
// error logging, do nothing | ||
} | ||
} | ||
} | ||
return _o.join(" "); | ||
Package("org.quickcorp.qcobjects.main.http2.server", [ | ||
class HTTP2ServerResponse extends InheritClass { | ||
constructor({ | ||
headers = { | ||
":status": 200, | ||
"content-type": "text/html", | ||
"cache-control": CONFIG.get("cacheControl", "max-age=31536000") | ||
}, | ||
body = "", | ||
request = null, | ||
fileDispatcher = null, | ||
stream = null | ||
}) { | ||
super(...arguments); | ||
var self = this; | ||
self._generateResponse(); | ||
} | ||
}), | ||
Class("HTTP2ServerResponse",{ | ||
headers:{ | ||
":status": 200, | ||
"content-type": "text/html", | ||
"cache-control": CONFIG.get("cacheControl", "max-age=31536000") | ||
}, | ||
body:"", | ||
request:null, | ||
fileDispatcher:null, | ||
sendFile: function (stream, fileName) { | ||
sendFile(stream, fileName) { | ||
// read and send file content in the stream | ||
@@ -99,5 +93,5 @@ | ||
} catch (e){ | ||
logger.debug("[ERROR] something went wrong when trying to send the response as file "+fileName); | ||
if (e.errno==-2){ | ||
} catch (e) { | ||
logger.debug("[ERROR] something went wrong when trying to send the response as file " + fileName); | ||
if (e.errno == -2) { | ||
const headers = { | ||
@@ -107,3 +101,3 @@ ":status": 404, | ||
}; | ||
stream.respond (headers); | ||
stream.respond(headers); | ||
stream.write("<h1>404 - FILE NOT FOUND</h1>"); | ||
@@ -116,12 +110,12 @@ stream.on("close", () => { | ||
} | ||
}, | ||
_generateResponse:function (){ | ||
} | ||
_generateResponse() { | ||
var response = this; | ||
response.fileDispatcher = New(FileDispatcher,{ | ||
scriptname:response.request.scriptname, | ||
pathname:response.request.pathname, | ||
done:function (headers,body,templateURI,isTemplate){ | ||
response.fileDispatcher = New(FileDispatcher, { | ||
scriptname: response.request.scriptname, | ||
pathname: response.request.pathname, | ||
done(headers, body, templateURI, isTemplate) { | ||
response.headers = headers; | ||
var stream = response.stream; | ||
if (isTemplate){ | ||
if (isTemplate) { | ||
response.body = body; | ||
@@ -131,4 +125,4 @@ stream.respond(response.headers); | ||
stream.end(); | ||
} else if (headers[":status"]==200){ | ||
response.sendFile(stream,templateURI); | ||
} else if (headers[":status"] == 200) { | ||
response.sendFile(stream, templateURI); | ||
} else { | ||
@@ -141,77 +135,40 @@ stream.respond(response.headers); | ||
}, | ||
_new_:function (o){ | ||
var self = this; | ||
self.body = ""; | ||
self.stream = o.stream; | ||
self._generateResponse(); | ||
} | ||
}), | ||
Class("HTTP2ServerRequest",{ | ||
scriptname:"", | ||
path:"", | ||
method:"", | ||
url:"", | ||
headers:null, | ||
flags:null, | ||
protocol: null, | ||
slashes: null, | ||
auth: null, | ||
host: null, | ||
port: null, | ||
hostname: null, | ||
hash: null, | ||
search: "", | ||
query: "", | ||
pathname: "", | ||
href: "" | ||
}), | ||
Class("HTTP2Server",{ | ||
request:null, | ||
response:"", | ||
server:null, | ||
scriptname:"", | ||
interceptorInstances:[], | ||
showIPAddress:function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
_ret_ += iface +": " + PipeLog.pipe(ipGroup)+"\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
showPossibleURL: function (){ | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface){ | ||
ifaces[iface].map(function (ipGroup){ | ||
if (ipGroup["family"].toLowerCase()=="ipv4"){ | ||
_ret_ += "http://"+ipGroup["address"]+":"+CONFIG.get("serverPortHTTP").toString()+"/\n"; | ||
_ret_ += "https://"+ipGroup["address"]+":"+CONFIG.get("serverPortHTTPS").toString()+"/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
}, | ||
start:function (){ | ||
var server = this.server; | ||
// http2 port is 8443 but normally is used 443 by replacing current https | ||
}, | ||
const http = require("http"); | ||
class HTTP2ServerRequest extends InheritClass { | ||
constructor({ | ||
scriptname = "", | ||
path = "", | ||
method = "", | ||
url = "", | ||
headers = null, | ||
flags = null, | ||
protocol = null, | ||
slashes = null, | ||
auth = null, | ||
host = null, | ||
port = null, | ||
hostname = null, | ||
hash = null, | ||
search = "", | ||
query = "", | ||
pathname = "", | ||
href = "" | ||
}) { | ||
super(...arguments); | ||
} | ||
}, | ||
const httpServer = http.createServer((req, res) => { | ||
res.writeHead(301,{Location: `https://${req.headers.host}${req.url}`}); | ||
res.end(); | ||
}); | ||
class HTTP2Server extends InheritClass { | ||
constructor({ | ||
request = null, | ||
response = "", | ||
server = null, | ||
scriptname = "", | ||
interceptorInstances = [] | ||
}) { | ||
super(...arguments); | ||
httpServer.listen(CONFIG.get("serverPortHTTP")); | ||
server.listen(CONFIG.get("serverPortHTTPS")); | ||
}, | ||
_new_:function (){ | ||
const welcometo = "Welcome to \n"; | ||
@@ -224,5 +181,5 @@ const instructions = "HTTP2Server \n"; | ||
logger.debug(this.showIPAddress()); | ||
logger.info("Listening on HTTP PORT: "+CONFIG.get("serverPortHTTP").toString()); | ||
logger.info("Listening on HTTPS PORT: "+CONFIG.get("serverPortHTTPS").toString()); | ||
logger.info("Go to: \n"+this.showPossibleURL()); | ||
logger.info("Listening on HTTP PORT: " + CONFIG.get("serverPortHTTP").toString()); | ||
logger.info("Listening on HTTPS PORT: " + CONFIG.get("serverPortHTTPS").toString()); | ||
logger.info("Go to: \n" + this.showPossibleURL()); | ||
@@ -233,4 +190,4 @@ let http2ServerInstance = this; | ||
cert: fs.readFileSync(CONFIG.get("private-cert-pem")), | ||
allowHTTP1:CONFIG.get("allowHTTP1"), | ||
origins:["https://"+CONFIG.get("domain"),"http://"+CONFIG.get("domain")] | ||
allowHTTP1: CONFIG.get("allowHTTP1"), | ||
origins: ["https://" + CONFIG.get("domain"), "http://" + CONFIG.get("domain")] | ||
}); | ||
@@ -243,23 +200,23 @@ var server = http2ServerInstance.server; | ||
// Set altsvc for origin https://example.org:80 | ||
session.altsvc("h2=\":8000\"", "https://"+CONFIG.get("domain")); | ||
session.altsvc("https=\":"+CONFIG.get("serverPortHTTPS")+"\"","https://"+CONFIG.get("domain")); | ||
session.altsvc("http=\":"+CONFIG.get("serverPortHTTP")+"\"","http://"+CONFIG.get("domain")); | ||
session.origin("https://"+CONFIG.get("domain"),"http://"+CONFIG.get("domain")); | ||
session.altsvc("h2=\":8000\"", "https://" + CONFIG.get("domain")); | ||
session.altsvc("https=\":" + CONFIG.get("serverPortHTTPS") + "\"", "https://" + CONFIG.get("domain")); | ||
session.altsvc("http=\":" + CONFIG.get("serverPortHTTP") + "\"", "http://" + CONFIG.get("domain")); | ||
session.origin("https://" + CONFIG.get("domain"), "http://" + CONFIG.get("domain")); | ||
}); | ||
if (global.get("backendAvailable")){ | ||
if (global.get("backendAvailable")) { | ||
logger.info("Loading backend interceptors..."); | ||
let interceptors = CONFIG.get("backend",{}).interceptors; | ||
if (typeof interceptors !== "undefined"){ | ||
let interceptors = CONFIG.get("backend", {}).interceptors; | ||
if (typeof interceptors !== "undefined") { | ||
logger.info("Backend Interceptors Available"); | ||
interceptors.map(interceptor=>{ | ||
ImportMicroservice (interceptor.microservice); | ||
var interceptorClassFactory = ClassFactory(interceptor.microservice+".Interceptor"); | ||
var interceptorInstance = New(interceptorClassFactory,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
interceptor:interceptor, | ||
server:server | ||
interceptors.map(interceptor => { | ||
ImportMicroservice(interceptor.microservice); | ||
var interceptorClassFactory = ClassFactory(interceptor.microservice + ".Interceptor"); | ||
var interceptorInstance = New(interceptorClassFactory, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
interceptor: interceptor, | ||
server: server | ||
}); | ||
@@ -272,3 +229,3 @@ http2ServerInstance.interceptorInstances.push(interceptorInstance); | ||
server.on("stream", (stream, headers, flags) => { | ||
CONFIG.set("backendTimeout",CONFIG.get("backendTimeout") || 20000); | ||
CONFIG.set("backendTimeout", CONFIG.get("backendTimeout") || 20000); | ||
stream.session.setTimeout(CONFIG.get("backendTimeout")); | ||
@@ -279,4 +236,4 @@ stream.session.setMaxListeners(9999999999); | ||
try { | ||
if (!stream.destroyed){ | ||
logger.info("A timeout occurred... "+CONFIG.get("backendTimeout").toString()); | ||
if (!stream.destroyed) { | ||
logger.info("A timeout occurred... " + CONFIG.get("backendTimeout").toString()); | ||
logger.info("Killing session..."); | ||
@@ -287,3 +244,3 @@ stream.respond({ | ||
}); | ||
stream.on("error",()=>{}); | ||
stream.on("error", () => {}); | ||
stream.write("<h1>500 - INTERNAL SERVER ERROR (TIMEOUT)</h1>"); | ||
@@ -294,3 +251,3 @@ stream.end(); | ||
} | ||
}catch(e){ | ||
} catch (e) { | ||
logger.debug("An unhandled error occurred during timeout catching..."); | ||
@@ -300,17 +257,17 @@ logger.debug(e.message); | ||
if (!stream.destroyed){ | ||
stream.session.removeListener("timeout",timeoutHandler); | ||
if (!stream.destroyed) { | ||
stream.session.removeListener("timeout", timeoutHandler); | ||
} else { | ||
server.removeListener("timeout",timeoutHandler); | ||
server.removeListener("timeout", timeoutHandler); | ||
} | ||
}; | ||
if (!stream.destroyed){ | ||
stream.session.on("timeout", timeoutHandler ); | ||
if (!stream.destroyed) { | ||
stream.session.on("timeout", timeoutHandler); | ||
} | ||
stream.session.altsvc("h2=\":8000\"", stream.id); | ||
stream.session.altsvc("https=\":"+CONFIG.get("serverPortHTTPS")+"\"", stream.id); | ||
stream.session.altsvc("http=\":"+CONFIG.get("serverPortHTTP")+"\"",stream.id); | ||
let request = Object.assign(New(HTTP2ServerRequest),require("url").parse(headers[":path"])); | ||
stream.session.altsvc("https=\":" + CONFIG.get("serverPortHTTPS") + "\"", stream.id); | ||
stream.session.altsvc("http=\":" + CONFIG.get("serverPortHTTP") + "\"", stream.id); | ||
let request = Object.assign(New(HTTP2ServerRequest), require("url").parse(headers[":path"])); | ||
request.headers = headers; | ||
@@ -323,43 +280,48 @@ request.flags = flags; | ||
if (http2ServerInstance.request.pathname.indexOf(".")<0){ | ||
http2ServerInstance.request.scriptname = CONFIG.get("documentRootFileIndex"); | ||
if (http2ServerInstance.request.pathname.indexOf(".") < 0) { | ||
http2ServerInstance.request.scriptname = CONFIG.get("documentRootFileIndex"); | ||
} else { | ||
http2ServerInstance.request.scriptname = http2ServerInstance.request.pathname.split("/").reverse()[0]; | ||
} | ||
http2ServerInstance.request.pathname = this.request.pathname.substr(0,http2ServerInstance.request.pathname.lastIndexOf("/")); | ||
http2ServerInstance.request.pathname = this.request.pathname.substr(0, http2ServerInstance.request.pathname.lastIndexOf("/")); | ||
logger.debug(PipeLog.pipe(this.request)); | ||
logger.debug((new PipeLog()).pipe(this.request)); | ||
if (global.get("backendAvailable")){ | ||
if (global.get("backendAvailable")) { | ||
logger.info("Backend Microservices Available..."); | ||
logger.info("Loading backend routes..."); | ||
let routes = CONFIG.get("backend",{}).routes; | ||
let selectedRoute = routes.filter(route=>{let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)");return (new RegExp(standardRoutePath,"g")).test(request.path);}); | ||
if (selectedRoute.length>0){ | ||
selectedRoute.map(route=>{ | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)"); //allowing {param} | ||
let routes = CONFIG.get("backend", {}).routes; | ||
let selectedRoute = routes.filter(route => { | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)"); | ||
return (new RegExp(standardRoutePath, "g")).test(request.path); | ||
}); | ||
if (selectedRoute.length > 0) { | ||
selectedRoute.map(route => { | ||
let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)"); //allowing {param} | ||
console.log(standardRoutePath); | ||
let selectedRouteParams = {...[...request.path.matchAll((new RegExp( standardRoutePath ,"g")))][0]["groups"]}; | ||
ImportMicroservice (route.microservice); | ||
var microServiceClassFactory = ClassFactory(route.microservice+".Microservice"); | ||
http2ServerInstance.response = New(microServiceClassFactory,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
route:route, | ||
routeParams:selectedRouteParams, | ||
server:server, | ||
stream:stream, | ||
request:request | ||
let selectedRouteParams = { | ||
...[...request.path.matchAll((new RegExp(standardRoutePath, "g")))][0]["groups"] | ||
}; | ||
ImportMicroservice(route.microservice); | ||
var microServiceClassFactory = ClassFactory(route.microservice + ".Microservice"); | ||
http2ServerInstance.response = New(microServiceClassFactory, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
route: route, | ||
routeParams: selectedRouteParams, | ||
server: server, | ||
stream: stream, | ||
request: request | ||
}); | ||
}); | ||
} else { | ||
this.response = New(HTTP2ServerResponse,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
server:server, | ||
stream:stream, | ||
request:request | ||
this.response = New(HTTP2ServerResponse, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
server: server, | ||
stream: stream, | ||
request: request | ||
}); | ||
@@ -371,9 +333,9 @@ } | ||
this.response = New(HTTP2ServerResponse,{ | ||
domain:CONFIG.get("domain"), | ||
basePath:CONFIG.get("basePath"), | ||
projectPath:CONFIG.get("projectPath"), | ||
server:server, | ||
stream:stream, | ||
request:request | ||
this.response = New(HTTP2ServerResponse, { | ||
domain: CONFIG.get("domain"), | ||
basePath: CONFIG.get("basePath"), | ||
projectPath: CONFIG.get("projectPath"), | ||
server: server, | ||
stream: stream, | ||
request: request | ||
}); | ||
@@ -386,3 +348,48 @@ | ||
} | ||
}) | ||
]); | ||
showIPAddress() { | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface) { | ||
ifaces[iface].map(function (ipGroup) { | ||
_ret_ += iface + ": " + (new PipeLog()).pipe(ipGroup) + "\n"; | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
showPossibleURL() { | ||
var _ret_ = ""; | ||
var os = require("os"); | ||
var ifaces = os.networkInterfaces(); | ||
Object.keys(ifaces).forEach(function (iface) { | ||
ifaces[iface].map(function (ipGroup) { | ||
if (ipGroup["family"].toLowerCase() == "ipv4") { | ||
_ret_ += "http://" + ipGroup["address"] + ":" + CONFIG.get("serverPortHTTP").toString() + "/\n"; | ||
_ret_ += "https://" + ipGroup["address"] + ":" + CONFIG.get("serverPortHTTPS").toString() + "/\n"; | ||
} | ||
}); | ||
}); | ||
return _ret_; | ||
} | ||
start() { | ||
var server = this.server; | ||
// http2 port is 8443 but normally is used 443 by replacing current https | ||
const http = require("http"); | ||
const httpServer = http.createServer((req, res) => { | ||
res.writeHead(301, { | ||
Location: `https://${req.headers.host}${req.url}` | ||
}); | ||
res.end(); | ||
}); | ||
httpServer.listen(CONFIG.get("serverPortHTTP")); | ||
server.listen(CONFIG.get("serverPortHTTPS")); | ||
} | ||
} | ||
]); |
{ | ||
"name": "qcobjects-cli", | ||
"version": "2.3.50", | ||
"version": "2.4.21", | ||
"description": "qcobjects cli command line tool", | ||
@@ -8,4 +8,4 @@ "main": "qcobjects-cli.js", | ||
"sync": "git add . && git commit -am ", | ||
"test": "npx eslint **/*.js --fix && $(npm bin)/jasmine", | ||
"preversion": "npm i --upgrade && npm test", | ||
"test": "npx eslint **/*.js --fix && jasmine", | ||
"preversion": "npm cache verify && npm test", | ||
"postversion": "git push && git push --tags" | ||
@@ -16,13 +16,17 @@ }, | ||
"mime": "^2.4.7", | ||
"qcobjects": "^2.3.66-lts", | ||
"qcobjects-sdk": "latest", | ||
"qcobjects": "^2.4.32-beta", | ||
"qcobjects-sdk": "^2.4.25", | ||
"yaml": "^1.10.2" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^8.2.0", | ||
"eslint-config-qcobjects": "^0.0.13", | ||
"jasmine": "^3.7.0", | ||
"qcobjects": "^2.3.66-lts", | ||
"qcobjects-cli": "latest" | ||
"eslint": "^8.35.0", | ||
"eslint-config-qcobjects": "^0.0.23", | ||
"jasmine": "^3.99.0", | ||
"qcobjects": "^2.4.32-beta", | ||
"qcobjects-sdk": "^2.4.25" | ||
}, | ||
"peerDependencies": { | ||
"qcobjects": "^2.4.32-beta", | ||
"qcobjects-sdk": "^2.4.25" | ||
}, | ||
"repository": { | ||
@@ -66,3 +70,7 @@ "type": "file", | ||
"qcobjects-collab": "./qcobjects-collab.js" | ||
}, | ||
"engines": { | ||
"node": ">=14", | ||
"npm": ">=9" | ||
} | ||
} |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -68,14 +68,10 @@ * | ||
Class("Main",Object,{ | ||
_new_:(o)=>{ | ||
class Main extends InheritClass { | ||
constructor (){ | ||
super(...arguments); | ||
let main = this; | ||
switchCommander = New(SwitchCommander); | ||
switchCommander = new SwitchCommander(); | ||
switchCommander.initCommand(); | ||
/* | ||
let template = New(AppTemplate,{ | ||
compileAndSave:true | ||
}); | ||
*/ | ||
logger.debug("initialized"); | ||
@@ -85,4 +81,5 @@ | ||
} | ||
}); | ||
let __main__ = New(Main,{}); | ||
} | ||
let __main__ = new Main (); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -42,11 +42,13 @@ * | ||
Class("Main",{ | ||
_new_:()=>{ | ||
const app = New(CollabServer); | ||
class Main extends InheritClass { | ||
constructor (){ | ||
super (...arguments); | ||
const app = new CollabServer(); | ||
app.start(); | ||
logger.debug("initialized"); | ||
} | ||
}); | ||
} | ||
let __main__ = New(Main); | ||
let __main__ = new Main(); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -41,18 +41,30 @@ * | ||
const { execSync } = require("child_process"); | ||
const { execSync } = require("child_process"); | ||
const certificate_provider = CONFIG.get("certificate_provider","self_signed"); | ||
let stdout; | ||
switch (certificate_provider) { | ||
case "self_signed": | ||
// stderr is sent to stderr of parent process | ||
// you can set options.stdio if you want it to go elsewhere | ||
stdout = execSync("openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN="+CONFIG.get("domain")+"' -keyout "+CONFIG.get("private-key-pem")+" -out "+CONFIG.get("private-cert-pem")); | ||
break; | ||
case "letsencrypt": | ||
var prehook_posthook = "--pre-hook \"service qcobjects stop\" --post-hook=\"service qcobjects start\""; | ||
stdout = execSync(`certbot -n -d ${CONFIG.get("domain")} certonly --standalone ${prehook_posthook}`); | ||
break; | ||
default: | ||
break; | ||
class Main extends InheritClass { | ||
constructor (){ | ||
super(...arguments); | ||
this.start(); | ||
} | ||
start (){ | ||
const certificate_provider = CONFIG.get("certificate_provider","self_signed"); | ||
let stdout; | ||
switch (certificate_provider) { | ||
case "self_signed": | ||
// stderr is sent to stderr of parent process | ||
// you can set options.stdio if you want it to go elsewhere | ||
stdout = execSync("openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN="+CONFIG.get("domain")+"' -keyout "+CONFIG.get("private-key-pem")+" -out "+CONFIG.get("private-cert-pem")); | ||
break; | ||
case "letsencrypt": | ||
var prehook_posthook = "--pre-hook \"service qcobjects stop\" --post-hook=\"service qcobjects start\""; | ||
stdout = execSync(`certbot -n -d ${CONFIG.get("domain")} certonly --standalone ${prehook_posthook}`); | ||
break; | ||
default: | ||
break; | ||
} | ||
} | ||
} | ||
let __main__ = new Main(); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -42,4 +42,6 @@ * | ||
Class("Main",{ | ||
_new_:()=>{ | ||
class Main extends InheritClass { | ||
constructor (){ | ||
super(...arguments); | ||
const app = New(HTTPServer); | ||
@@ -49,5 +51,6 @@ app.start(); | ||
logger.debug("initialized"); | ||
} | ||
}); | ||
} | ||
let __main__ = New(Main); | ||
let __main__ = new Main (); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -42,4 +42,5 @@ * | ||
Class("Main",{ | ||
_new_:()=>{ | ||
class Main extends InheritClass { | ||
constructor(){ | ||
super(...arguments); | ||
const app = New(HTTPServer); | ||
@@ -49,5 +50,6 @@ app.start(); | ||
logger.debug("initialized"); | ||
} | ||
}); | ||
} | ||
let __main__ = New(Main); | ||
let __main__ = new Main(); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -46,4 +46,5 @@ * | ||
Class("Main",{ | ||
_new_:()=>{ | ||
class Main extends InheritClass { | ||
constructor (){ | ||
super(...arguments); | ||
const _ServerClass_ = (CONFIG.get("useLegacyHTTP",false))? (HTTPServer): (HTTP2Server); | ||
@@ -54,5 +55,7 @@ const app = New(_ServerClass_); | ||
logger.debug("initialized"); | ||
} | ||
}); | ||
let __main__ = New(Main); | ||
} | ||
let __main__ = new Main(); |
#!/usr/bin/env node | ||
/** | ||
* QCObjects CLI 2.3.x | ||
* QCObjects CLI 2.4.x | ||
* ________________ | ||
@@ -46,4 +46,4 @@ * | ||
require(absolutePath+"/org.quickcorp.qcobjects.defaultsettings.js"); | ||
const readline = require("readline"); | ||
const package_config = require(absolutePath+"/package.json"); | ||
@@ -53,110 +53,116 @@ const qcobjects_pkg_config = require("qcobjects/package.json"); | ||
let sandbox = { | ||
require:require, | ||
module:module, | ||
__dirname:"./", | ||
__filename:"qcobjects-shell-file.js" | ||
}; | ||
global.context = vm.createContext(sandbox); | ||
const runScript = (code,logOutput=false)=>{ | ||
const options = {filename:sandbox.__filename}; | ||
const backgroundRunScript = (code)=>{ | ||
var output = vm.runInContext(code,global.context,options); | ||
return output; | ||
}; | ||
var output = backgroundRunScript(code); | ||
if (logOutput && typeof output !== "undefined"){ | ||
console.log(output); | ||
class Main extends InheritClass { | ||
constructor(){ | ||
super(...arguments); | ||
this.start(); | ||
} | ||
}; | ||
const syncGlobal = ()=>{ | ||
var s = "Object.assign(this,this.constructor.constructor('return this')())"; | ||
runScript(s); | ||
}; | ||
const readline = require("readline"); | ||
readline.emitKeypressEvents(process.stdin); | ||
if (process.stdin.isTTY) | ||
process.stdin.setRawMode(true); | ||
let qcobjects_version = global.__get_version_string__(); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout, | ||
prompt: qcobjects_version + " >" | ||
}); | ||
const protected_symbols = [ "clearInterval", | ||
"clearTimeout", | ||
"setInterval", | ||
"setTimeout", "queueMicrotask", | ||
"clearImmediate", "setImmediate", "_asyncLoad", | ||
"_fireAsyncLoad", "asyncLoad", "logger", | ||
"_Crypt", "CONFIG", "waitUntil", | ||
"_super_", "ComplexStorageCache", "TagElements", | ||
"onload", "InheritClass", "Component", | ||
"Controller", "View", "Service", | ||
"JSONService", "ConfigService", "VO", | ||
"serviceLoader", "componentLoader", "ComponentURI", | ||
"SourceJS", "SourceCSS", "ArrayList", | ||
"ArrayCollection", "Effect", "Timer", | ||
"Export", "Import", "Package", | ||
"Class", "New", "Tag", | ||
"Ready", "Contact", "FormField", | ||
"ButtonField", "InputField", "TextField", | ||
"EmailField", "GridComponent", "GridController", | ||
"GridView", "Move", "RotateX", | ||
"RotateY", "RotateZ", "Rotate", | ||
"Fade", "Radius", "CanvasTool", | ||
"BasicLayout" | ||
]; | ||
const preloaded_scripts = [ | ||
"require('qcobjects')", | ||
"Object.assign(this,this.constructor.constructor('return this')())" | ||
]; | ||
preloaded_scripts.map(preloaded_script => | ||
runScript(preloaded_script.trim()) | ||
); | ||
console.log(welcometo); | ||
console.log(logo); | ||
console.log(instructions); | ||
rl.prompt(true); | ||
rl.on("line", (line) => { | ||
var codeline = line.trim(); | ||
switch (true) { | ||
case codeline=="hello": | ||
console.log("world!"); | ||
break; | ||
case codeline==".exit": | ||
rl.close(); | ||
break; | ||
default: | ||
try{ | ||
runScript(codeline,true); | ||
syncGlobal(sandbox); | ||
}catch (e){ | ||
console.log("An exeption ocurred while trying to run your awesome code! "); | ||
console.log(e); | ||
start (){ | ||
let sandbox = { | ||
require:require, | ||
module:module, | ||
__dirname:"./", | ||
__filename:"qcobjects-shell-file.js" | ||
}; | ||
global.context = vm.createContext(sandbox); | ||
const runScript = (code,logOutput=false)=>{ | ||
const options = {filename:sandbox.__filename}; | ||
const backgroundRunScript = (code)=>{ | ||
var output = vm.runInContext(code,global.context,options); | ||
return output; | ||
}; | ||
var output = backgroundRunScript(code); | ||
if (logOutput && typeof output !== "undefined"){ | ||
console.log(output); | ||
} | ||
break; | ||
}; | ||
const syncGlobal = ()=>{ | ||
var s = "Object.assign(this,this.constructor.constructor('return this')())"; | ||
runScript(s); | ||
}; | ||
readline.emitKeypressEvents(process.stdin); | ||
if (process.stdin.isTTY) | ||
process.stdin.setRawMode(true); | ||
let qcobjects_version = global.__get_version_string__(); | ||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout, | ||
prompt: qcobjects_version + " >" | ||
}); | ||
const protected_symbols = [ "clearInterval", | ||
"clearTimeout", | ||
"setInterval", | ||
"setTimeout", "queueMicrotask", | ||
"clearImmediate", "setImmediate", "_asyncLoad", | ||
"_fireAsyncLoad", "asyncLoad", "logger", | ||
"_Crypt", "CONFIG", "waitUntil", | ||
"_super_", "ComplexStorageCache", "TagElements", | ||
"onload", "InheritClass", "Component", | ||
"Controller", "View", "Service", | ||
"JSONService", "ConfigService", "VO", | ||
"serviceLoader", "componentLoader", "ComponentURI", | ||
"SourceJS", "SourceCSS", "ArrayList", | ||
"ArrayCollection", "Effect", "Timer", | ||
"Export", "Import", "Package", | ||
"Class", "New", "Tag", | ||
"Ready", "Contact", "FormField", | ||
"ButtonField", "InputField", "TextField", | ||
"EmailField", "GridComponent", "GridController", | ||
"GridView", "Move", "RotateX", | ||
"RotateY", "RotateZ", "Rotate", | ||
"Fade", "Radius", "CanvasTool", | ||
"BasicLayout" | ||
]; | ||
const preloaded_scripts = [ | ||
"require('qcobjects')", | ||
"Object.assign(this,this.constructor.constructor('return this')())" | ||
]; | ||
preloaded_scripts.map(preloaded_script => | ||
runScript(preloaded_script.trim()) | ||
); | ||
console.log(welcometo); | ||
console.log(logo); | ||
console.log(instructions); | ||
rl.prompt(true); | ||
rl.on("line", (line) => { | ||
var codeline = line.trim(); | ||
switch (true) { | ||
case codeline=="hello": | ||
console.log("world!"); | ||
break; | ||
case codeline==".exit": | ||
rl.close(); | ||
break; | ||
default: | ||
try{ | ||
runScript(codeline,true); | ||
syncGlobal(sandbox); | ||
}catch (e){ | ||
console.log("An exeption ocurred while trying to run your awesome code! "); | ||
console.log(e); | ||
} | ||
break; | ||
} | ||
rl.prompt(); | ||
}).on("close", () => { | ||
console.log("Thank you for using QCObjects."); | ||
console.log("Have a nice day!"); | ||
process.exit(0); | ||
}); | ||
} | ||
rl.prompt(); | ||
}).on("close", () => { | ||
console.log("Thank you for using QCObjects."); | ||
console.log("Have a nice day!"); | ||
process.exit(0); | ||
}); | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
191430
44
4310
7
61
Updatedqcobjects@^2.4.32-beta
Updatedqcobjects-sdk@^2.4.25