Skip to content

Commit

Permalink
♻️ Change the way compiled template functions are exported
Browse files Browse the repository at this point in the history
  • Loading branch information
skerit committed Apr 29, 2024
1 parent 43c3a9c commit 40ca7a7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
20 changes: 12 additions & 8 deletions lib/core/hawkejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ let vm = require('vm');
*
* @author Jelle De Loecker <[email protected]>
* @since 2.0.0
* @version 2.2.0
* @version 2.4.0
*
* @param {String} code
*
Expand All @@ -547,34 +547,38 @@ let vm = require('vm');
Main.setMethod(function compileCodeToFunction(code, options) {

let compiled,
exports,
error;

if (Blast.isNode) {

if (code[0] != '(') {
code = '(' + code + ')';
}

// The function statements have to be wrapped in another scope because
// we always reuse the same VM instance. If we didn't do this,
// creating newer function statements would overwrite older ones.
// We also have to define Blast & Hawkejs, because `runInThisContext`
// does not have access to the local scope
code = `(function() { const Blast = __Protoblast, Hawkejs = Blast.Classes.Hawkejs; return ${code} }())`;
code = `(function() { const Blast = __Protoblast, Hawkejs = Blast.Classes.Hawkejs, exports = {}; ${code}; return exports; }())`;

try {
compiled = vm.runInThisContext(code, options);
exports = vm.runInThisContext(code, options);
} catch (err) {
error = err;
}
} else {
try {
eval('compiled = ' + code);
exports = {};
eval(code);
} catch (err) {
error = err;
}
}

if (exports?.compiled) {
compiled = exports.compiled;
} else if (!error) {
error = new Error('No compiled function found');
}

if (error) {
error.code = code;
throw error;
Expand Down
11 changes: 7 additions & 4 deletions lib/parser/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,7 @@ Builder.setMethod(function closeElement(entry) {
*
* @author Jelle De Loecker <[email protected]>
* @since 2.2.0
* @version 2.2.0
* @version 2.4.0
*
* @return {string}
*/
Expand All @@ -594,16 +594,19 @@ Builder.setMethod(function toCode() {

let functions = {},
result = '',
header = '',
sr;

for (sr of this._subroutines) {
functions[sr.name] = R(sr.name);
result += '\n\n';

if (result) {
result += '\n\n';
}

result += sr.toString();
}

result = '(' + Hawkejs.Parser.Parser.uneval(functions) + ');\n' + result;
result += '\n\nexports.compiled = ' + Hawkejs.Parser.Parser.uneval(functions) + ';\n';

return result;
});
Expand Down

0 comments on commit 40ca7a7

Please sign in to comment.