common/scripts

Scripting control module for the Total Control automation system.

This module provides high-level helpers to run, monitor, and stop automation scripts
across the Total Control environment. It supports executing JavaScript (.js) files
and test scenario files (.tst), passing arguments and device hints, resolving
script paths from multiple locations, and capturing/propagating exit codes in a
consistent way (via exit() or quit() semantics).

It also exposes utilities to list running scripts, kill one or all scripts, and
run inline test functions with argument passing (sigmaRun) to simplify debugging.
Internally it integrates with the Total Control task context (sigmaConstItemId)
so logs, device managers, and utilities are correctly bound to the current run.

Key Features

  • Run JS or TST files with aliasing and argument passing (scriptRun)
  • Poll script status by alias (scriptWait) and terminate runs (scriptKill, scriptKillAll)
  • Enumerate currently running scripts and their metadata (scriptList)
  • Execute an in-memory function with arguments, capturing exit codes (sigmaRun)
  • Load and execute a script file with path fallback and exit-code capture (sigmaLoad, alias tcLoad)
  • Explicit script termination helpers:
    • exit(code): throws a special, catchable signal used by runners to return code
    • quit(code): immediately aborts the script with a ||quit||<code> marker
  • Configure and query script context (setScriptFileName / getScriptFileName,
    setSigmaConstItemId / getSigmaConstItemId, getExitCode)

Path Resolution (when a relative path is provided)

  1. User-defined scriptPath (via define('scriptPath', '...'))
  2. Environment variable TCSCRIPTPATH
  3. Default Total Control script directory: “/Scripts”
    Absolute paths are used as-is and must exist or an error is returned.

Return Codes & Status

  • scriptRun returns a positive run ID on success; negative values indicate failure
  • scriptWait(name) returns:
    • 0 → error (e.g., alias not found)
    • -1 → running
    • -2 → ended
    • -3 → aborted
    • -4 → paused
  • scriptKill / scriptKillAll return 0 on success, -1 on failure
  • sigmaRun / sigmaLoad return the captured exit code (default 0 if none)

Usage Examples

var scripts = require("sigma/common/scripts");

// 1) Run a JS file with arguments and an alias
var args = { arguments: [1, "mobile2", "test.js"], deviceName: "mobile1" };
var runId = scripts.scriptRun("setMobileName", "setName.js", args);
if (runId > 0) print("run id: " + runId); else print(lastError());

// 2) Wait for status by alias
var status = scripts.scriptWait("setMobileName");
print("status: " + status); // e.g. -1 (running)

// 3) List and kill running scripts
var list = scripts.scriptList();
if (list) list.forEach(s => print(`${s.name} #${s.id} @ ${s.path}`));
scripts.scriptKillAll();

// 4) Load a file directly and capture exit code
//    (supports relative paths and .tst execution)
var code = scripts.sigmaLoad("tests/login.tst");
print("exit code: " + code);

// 5) Inline test function with exit code capture
function checkTitle(expected) {
  const { equal } = require("assert");
  const query = "TP:textInput&&IX:0";
  device.sendAai({ query, action: `setText('${expected}')` });
  const got = device.sendAai({ query, action: "getText" }).retval;
  equal(got, expected);
  return 0; // or call exit(0)
}
var rc = scripts.sigmaRun(checkTitle, "Hello");
print("rc = " + rc);

Integration Notes

  • .tst runs initialize test device values (initTstDevicesValue) before execution.
  • setSigmaConstItemId(id) wires the current task ID into dependent utilities
    (device manager, color/excel utils, script executor) to ensure correct scoping.

(inner) getScriptFileName() → {string}

Get the current script file name.

Example
var { getScriptFileName } = require('sigma/common/scripts');
console.log(getScriptFileName()); // "terminal"
Returns:
string

The current script file name.

(inner) getSigmaConstItemId() → {number}

Get the current sigma constant item ID.

Example
console.log(getSigmaConstItemId()); // 0
Returns:
number

The current sigma constant item ID.

(inner) quit(code)

Terminates the current script execution and throws a special string to indicate the exit code.

Parameters:
number code

The exit code to throw, typically 0 for success or 1 for failure.

Throws:
string

A string in the format '||quit||' that signals script termination.

This function is used to stop the script immediately and return a specific status code
to the script runner (e.g., scriptRun or Testrun). Any code after quit() will not be executed.

Example 1: Used in a standalone script executed via scriptRun()

// Contents of script1.js:
print('OK');
quit(0);
print('Now'); // This line will never be executed

// Contents of script2.js:
print('OK');
quit(1);
print('Now'); // This line will also be skipped

Example script:
var ret = scriptRun("fileBinaryReader1", "E:/script/script1.js");
if (ret > 0) {
print("script run id :" + ret);
} else {
print(lastError());
}

// Output:
OK
||quit||0 (src/resources/Sigmalib.js#907)
script run id :1584943307397

Example 2: Used in a test case executed with Testrun

// mte.tpf contains:
Testname quittest
deviceSN:'7N2SQL154X038444'
username:'45178763'
End

// script1.js:
var {Testrun} = = require("./mte");
print("Device SN is: " + Testrun.getContext().get('deviceSN'));
quit(0);

// script2.js:
var {Testrun} = = require("./mte");
print("Device SN is: " + Testrun.getContext().get('deviceSN'));
quit(1);

// Execution script:
var {Testrun} = = require("./mte");
try {
var testrunObj = new Testrun('quittest1', 'mte.tpf', 'script1.js', 'quittest');
testrunObj.stop('quittest1');
} catch (e) {
print("Error:" + e);
print(lastError());
}

// Output:
runTest ...
Device SN is: 7N2SQL154X038444
||quit||0 (src/resources/Sigmalib.js#907)

(inner) scriptKill(id) → {number}

Stop the script executed by the Total Control server.

Example
var { scriptKill } = require("sigma/common/scripts");

// Use scriptRun to run the script testScript.js, the script's alias is set to TEST02.
var id = scriptRun('TEST02', 'testScript.js');
if (id > 0) {
 print("script id :" + id + "\n Kill script");
 // Terminate testScript.js script execution
 scriptKill(id);
}

// If it executes successfully, it will return:
script id :1536446845804
Kill script
Parameters:
number id

The ID of the script execution.

Returns:
number

This function returns 0 on success or -1 on failure, you can use the lastError() function to get the specific error message.

(inner) scriptKillAll() → {number}

Terminate all scripts that are executing.

Example
// Start multiple scripts using scriptRun
scriptRun('runApp1', 'runAppjs1.js');
scriptRun('runApp2', 'runAppjs2.js');
scriptRun('runApp3', 'runAppjs3.js');

// Kill all running scripts
var ret = scriptKillAll();
if (ret !== -1) {
    print("Congratulations, this API executes successfully.\nReturn value: " + ret);
} else {
    print("Sorry! " + lastError() + "\nReturn value: " + ret);
}

// Operation Result (on success):
Congratulations, this API executes successfully.
Return value: 0
Returns:
number

This function returns 0 on success or -1 on failure, you can use the lastError() function to get the specific error message.

(inner) scriptList() → {Array|null}

Retrieves a list of all currently running scripts that were launched using scriptRun().

Each entry in the returned list contains metadata about the running script:

  • name (string): The alias name assigned in scriptRun(name, scriptFile)
  • id (number): A unique ID representing the running instance
  • path (string): The full file path of the script being executed
Example
// Start a script with an alias
scriptRun('TEST1', 'testScript.js');

// Retrieve the list of currently running scripts
var list = scriptList();
if (list != null) {
    for (let i = 0; i < list.length; i++) {
        print("scriptList name: " + list[i].name);
        print("scriptList ID: " + list[i].id);
        print("scriptList Path: " + list[i].path);
    }
} else {
    print("No Script!!!!");
}

// Example Output (if a script is running):
// scriptList name: TEST1
// scriptList ID: 1562329959238
// scriptList Path: C:\Users\sigma\Documents\Scripts\testScript.js
Returns:
Array | null

This function returns an array on success or null on failure, you can use the lastError() function to get the specific error message.

(inner) scriptRun(name, scriptFile, argumentsopt) → {number}

Run the script file.
Run the specified script file, which can be used to run multiple scripts at the same time. The script file can be either a JS file or an SCP file.

Supports:
scriptRun(name, scriptFile)
scriptRun(name, scriptFile, arguments)

Description of the script path:

  • Absolute path:
    Specify the absolute path to scriptFile, which is the full path to the file.
  • Relative path:
    There are two kinds of relative paths, one is the user predefined path, and the other is the default path of the Total Control script.
    1. User predefined path:
      If the user's script has the following definition: define('scriptPath', 'c:\File');
    2. Total Control environment variable path:
      If the user does not define scriptPath in the script, it will be searched by the environment variable TCSCRIPTPATH. If there is a corresponding JS or SCP file in the path, if it is, execute it;
    3. Total Control script default path ("&lt:My Documents>/Scripts"):
      If the scriptPath is not defined in the user's script and the corresponding file is not found in the path specified by the environment variable TCSCRIPTPATH, it will be found in the default path "&lt:My Documents>/Scripts" of the Total Control script to see if there is a corresponding JS or SCP file. If yes, execute it, if not, exit execution;

Note:
Execute the script to find the path of the script in the following order:

  • If it is an absolute path, execute the specified script and report an error if it does not exist.
  • If it is a relative path, first find the script file under the user's predefined path, then find the script file under the path of the Total Control environment variable, and finally find the script under the default path of the Total Control script. If the script is still not found in the default path of the Total Control script. , return an error message;
Examples
// Example 1: Run a script using absolute path
var ret = scriptRun('fileBinaryReader1', 'E:/File/JScripts/Public/fileBinaryReader.js');
if (ret > 0) {
    print("script run id: " + ret);
} else {
    print(lastError());
}
// Example 2: Run a script using relative path with predefined scriptPath
define('scriptPath', 'E:/File/JScripts/Public/');
var ret = scriptRun('fileBinaryReader2', 'fileBinaryReader.js');
if (ret > 0) {
    print("script run id: " + ret);
} else {
    print(lastError());
}
// Example 3: Run a script with arguments (e.g., rename a device)
var args = {
  arguments: [1, 'mobile2', 'test.js'],  // Positional arguments
  deviceName: 'mobile1'                  // Custom parameter
};
var ret = scriptRun('setMobileName', 'setName.js', args);
if (ret > 0) {
    print("script run id: " + ret);
} else {
    print(lastError());
}

// The contents of setName.js:
var device = Device.searchObject(tcConst.DevSelectOne);
var ret = device.setName(arguments[1]);
if (ret == 0) print("Successfully set the phone name");
else print(lastError());

If it executes successfully, it will return:
script run id :1537301948136
Parameters:
string name

alias, an alias for the script to run.

string scriptFile

The path to the script file. It can be an be an absolute path to a file, or it can be a user-defined path, an environment variable path, or the default relative path of the Total Control script.

Object arguments <optional>
{arguments: []}

Sets the parameters needed to execute the script. When the script starts, the variables in "arguments" will provide the available information, which means that the parameters provided by "arguments" can be directly used in the script, for example: {arguments:['test .jpg', tcConst.IMG_JPG, 0,0,100,100]},arguments.length = 7,arguments [0] ='test.js',arguments [1] ='tcConst.IMG_JPG'...
The optional parameter {deviceName:} is also provided in arguments. When this option is specified, Device.searchObject(tcConst.DevSelectOne) will return the device object of the specified name in the "deviceName" option, if the specified device name is found, the device does not pop up the window for the user to select the device. If the device with the specified device name is not found, a pop-up window is displayed.
For example: {arguments:['test.jpg',tcConst.IMG_JPG,0,0 ,100,100], deviceName:'Mobile1'}

Returns:
number

If successful, returns the ID value of the script run, which is greater than 0. If it fails, its return value is less than 0., specific error information can be obtained by the lastError() function.

(inner) scriptWait(scriptname) → {number}

Get the status of the script.

Example
// Run a script with alias "TEST1"
scriptRun('TEST1', 'testScript.js');

// Get the script task execution status
var status = scriptWait("TEST1");
print(status);

// If it executes successfully, it will return:
-1
Parameters:
string scriptname

The name of the execution script.

Returns:
number

Returns the status of the script:

  • 0:(tcConst.StatusError): Error, for example: There is no such name or other error when checking the status.
  • -1:(tcConst.StatusRunning): The script is running.
  • -2:(tcConst.StatusEnd): The script has stopped running.
  • -3:(tcConst.StatusAbort): The script stopped abnormally.
  • -4:(tcConst.StatusPause): The script is paused.

(inner) setScriptFileName(name)

Update the script file name stored in the module.

Example
var { setScriptFileName } = require('sigma/common/scripts');
setScriptFileName("login");
Parameters:
string name

The new script file name.

(inner) setSigmaConstItemId(id)

Update the sigmaConstItemId stored in the module.

Example
setSigmaConstItemId(12345);
Parameters:
number id

The new item ID.

(inner) sigmaLoad(file) → {number}

sigmaLoad accept one argument, JavaScript filename, it will perform the execution of the script and return the exit code, if the script does not call exit(), zero will be returned. If the filename does not specify any path, it will run the script in the TC working directory.

This function supports both regular script files (e.g., .js) and test configuration files (.tst).
If the script throws a special quit code (e.g., throw ">>> 1 <<<"), the code is captured and returned.

Parameters:
string file

Relative or absolute path or file name of the script or ".tst" file to load.

Throws:
Error

If the file does not exist or the script throws a non-quit error.

Example:
// A script file (test.js) contains:
print("Running...");
quit(1);

var result = sigmaLoad("test.js");
print("Exit code is: " + result);

// Output:
Running...
Exit code is: 1

Returns:
number

The exit code returned by the script (default is 0). If quit(code) is used, the code is extracted and returned.

(inner) sigmaRun(fn, …args) → {number}

sigmaRun will accept first argument as function, the remaining arguments are arguments to the specified function. If exit(<exit code>) is called, It will return the exit code, otherwise zero will be returned. Similar to sigmaLoad except this can pass arguments to the function. sigmaRun() is for ease of debugging, can run in Terminal. Can also pass the exit code by returning an integer.

Parameters:
function fn

The function to execute.

any args <repeatable>

Arguments to pass to the function.

Throws:
string | Error

If no function is passed or a non-exit error is thrown during execution.

Example:
// A sample test function that sets and verifies text input
function testSetGetText(input) {
const { equal } = require('assert');
const query = "TP:textInput&&IX:0";
device.sendAai({ query: query, action: setText('${input}') });
const obtainInput = device.sendAai({ query: query, action: "getText" }).retval;
equal(obtainInput, input);
exit(0); // Successful
}

// Call sigmaRun to execute the function and get the exit code
var code = sigmaRun(testSetGetText, "Hello, how are you?");
print(code);

//If it executes successfully, it will return:
0

If an error occurs (e.g. input doesn't match):
// Output:
[AssertionError: Expected "Hello, how are you?", got "Hello, how"]

Returns:
number

The exit code returned by the function (or passed via exit(code)).

(inner) tcLoad(scriptFile) → {void}

Load the specified JS and class file.

The specific description of the script path is as follows:
Absolute path — Specify the absolute path of the scriptFile, for example: E: /File/Public/fileBinaryReader.js
Relative paths — There are two types of relative paths, one is the user-defined path, and the other is the default path of the Total Control script.

    1. Load the JS or class file in this path by using define('scriptPath', 'path address') in the script, for example: define('scriptPath', 'E:/File/JScripts/Public/').
    1. Load the JS or class file in this path by setting the environment variable TCSCRIPTPATH
    1. Load the JS or class file under /this computer/document/Scripts/ path.
Example
// Example 1: Load from absolute path
tcLoad("E:/File/JScripts/Public/fileBinaryReader.js");
tcLoad("E:/File/JScripts/Public/fileBinaryReader.class");


// Example 2: Load from user-defined path
define("scriptPath", "E:/File/JScripts/Public/");
tcLoad("fileBinaryReader.js");
tcLoad("fileBinaryReader.class");


// Example 3: Load from TCSCRIPTPATH environment variable
// If TCSCRIPTPATH is set to "E:/File/"
tcLoad("fileBinaryReader.js");
tcLoad("fileBinaryReader.class");


// Example 4: Load from default Total Control script directory (<My Documents>/Scripts)
tcLoad("fileBinaryReader.js");
tcLoad("fileBinaryReader.class");
Parameters:
string scriptFile

Script file. Supports absolute and relative paths.

Returns:
void