forked from StephenGregory/TaskerJavaScriptHelpers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsandbox.tasker.js
More file actions
54 lines (47 loc) · 2.08 KB
/
sandbox.tasker.js
File metadata and controls
54 lines (47 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const vm = require('vm');
const fs = require('fs');
const path = require('path');
function convertVariablesToWhatTaskerWouldSend(taskerLocalVariables) {
const convertedTaskerLocalVariables = {};
Object.getOwnPropertyNames(taskerLocalVariables).forEach((propertyName) => {
const propertyValue = taskerLocalVariables[propertyName];
if (propertyValue instanceof Array) {
convertedTaskerLocalVariables[propertyName] = propertyValue;
}
else if (propertyValue instanceof Function) {
console.info(`Converting function ${propertyName} to String before passing it to JavaScript helper`);
convertedTaskerLocalVariables[propertyName] = propertyValue.toString();
}
else if (propertyValue instanceof Object) {
console.info(`Converting Object ${propertyName} to String before passing it to JavaScript helper`);
convertedTaskerLocalVariables[propertyName] = JSON.stringify(propertyValue);
}
else {
convertedTaskerLocalVariables[propertyName] = propertyValue;
}
});
return convertedTaskerLocalVariables;
}
/**
* Run a JavaScript helper with a set of local Tasker variables
* @param {String} fileNameUnderTest - The filename of the helper to test
* @param {Object} taskerLocalVariables - key-value pairs of local variable values
*/
function runScript(fileNameUnderTest, taskerLocalVariables) {
const fileUnderTest = path.join(__dirname, fileNameUnderTest);
const doesFileUnderTestExist = fs.existsSync(fileUnderTest);
if (!doesFileUnderTestExist) {
console.error(`File you are testing does not exist: ${fileUnderTest}`);
return;
}
const file = fs.readFileSync(fileUnderTest);
const convertedTaskerLocalVariables = convertVariablesToWhatTaskerWouldSend(taskerLocalVariables);
const context = {
...convertedTaskerLocalVariables,
require: require
};
vm.createContext(context);
const script = new vm.Script(file, { filename: fileUnderTest });
script.runInContext(context);
}
exports.default = runScript;