Example Script
This example shell script demonstrates how to use the Corellium JavaScript v2 API to:
- Search for a device with a specified instance ID.
- If it's found, ensure the device is powered on.
- If it's not found, create a new device with a desired hardware and firmware and wait for it to be ready.
- Wait for the device to boot.
- Wait for the device's app subsystem to be ready.
- List the running apps on the device.
Pre-Requisites
- 
Ensure the following npm dependencies are installed on your local environment: - @corellium/client-api
 
- 
Set an environmental variable CORELLIUM_API_TOKENwith your API token.
- 
Set another environmental variable CORELLIUM_API_ENDPOINT.- For On-Premise customers, use https://<your_hostname>/api, where<your_hostname>is either the hostname or IP address of your Corellium appliance.
- For Enterprise Cloud customers, use https://<your_domain>.enterprise.corellium.com/api, where<your_domain>is taken from the URL you use to access the Corellium web interface.
- For Solo Cloud customers, use https://app.corellium.com/api.
 
- For On-Premise customers, use 
Example Script
const CorelliumClient = require('@corellium/client-api');
const CORELLIUM_API_ENDPOINT = process.env.CORELLIUM_API_ENDPOINT;
const CORELLIUM_API_TOKEN = process.env.CORELLIUM_API_TOKEN;
// Define the default values
const DEFAULT_INSTANCE_ID = 'YOUR_INSTANCE_IDENTIFIER';
const DEFAULT_INSTANCE_FIRMWARE = '18.0';
const DEFAULT_INSTANCE_HARDWARE = 'iphone16pm';
const DEFAULT_INSTANCE_NAME = 'JavaScript_v2_API_demo_device';
const DEFAULT_PROJECT_ID = 'YOUR_PROJECT_IDENTIFIER';
// Define the time constants
const SLEEP_TIME_SECONDS = 60;
// Define constants for instance states and task states
const INSTANCE_STATE_OFF = 'off';
const INSTANCE_STATE_ON = 'on';
const INSTANCE_STATE_BOOTING = 'booting';
const INSTANCE_STATE_CREATING = 'creating';
const INSTANCE_STATE_REBOOTING = 'rebooting';
const INSTANCE_TASK_STATE_NONE = 'none';
function checkEnvironmentVariables() {            
    if (!CORELLIUM_API_ENDPOINT) {
        handleError('Environmental variable CORELLIUM_API_ENDPOINT must be set.');
    } else if (!CORELLIUM_API_TOKEN) {
        handleError('Environmental variable CORELLIUM_API_TOKEN must be set.');
    }
}
async function handleUnexpectedState(instanceId, instanceState, instanceTaskState) {
    console.error(`Unexpected state - instance ${instanceId} is ${instanceState} with taskState ${instanceTaskState}.`);
    process.exit(1);
}
function handleError(error, message = 'An error was thrown.') {
    console.error('ERROR:', message, error);
    process.exit(1);
}
async function listInstalledApps(apiInstance, instanceId) {
    try {
        const data = await apiInstance.v1AgentListApps(instanceId);
        const runningApps = data.apps.filter(app => app.running);        runningApps.sort((a, b) => a.bundleID.localeCompare(b.bundleID));
        console.log('Running apps:');
        runningApps.forEach(app => console.log(app.bundleID + ' (' + app.name + ')'));
    } catch (error) {
        handleError(error, 'Exception when listing installed apps.');
    }
}
async function sleepForSeconds(seconds) {
    await new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
async function turnInstanceOnOrCreateNewInstance(apiInstance) {
    let instId;
    try {
        const data = await apiInstance.v1GetInstance(DEFAULT_INSTANCE_ID);
        console.log(`Instance ${DEFAULT_INSTANCE_ID} was found.`);
        let instanceState = data.state;
        if (instanceState === INSTANCE_STATE_OFF) {
            console.log(`Instance ${DEFAULT_INSTANCE_ID} is off.`);
            await apiInstance.v1StartInstance(DEFAULT_INSTANCE_ID);
            console.log(`Instance ${DEFAULT_INSTANCE_ID} is powering on.`);
        }
        instId = DEFAULT_INSTANCE_ID;
    } catch (error) {
        if (error.response.status === 404) {
            try {
                console.log(`Instance ${DEFAULT_INSTANCE_ID} was not found.`);
                let instanceCreateOptions = {
                    "project": DEFAULT_PROJECT_ID,
                    "name": DEFAULT_INSTANCE_NAME,
                    "flavor": DEFAULT_INSTANCE_HARDWARE,
                    "os": DEFAULT_INSTANCE_FIRMWARE
                };
                console.log(`Creating a new instance of ${instanceCreateOptions.flavor} hardware with ${instanceCreateOptions.os} firmware.`);
                const data = await apiInstance.v1CreateInstance(instanceCreateOptions);
                instId = data.id;
            } catch (createError) {
                if (createError.status === 400 && createError.body.error === 'Domain does not have enough resources to complete, insufficient resource: cores') {
                    handleError(createError.body, '');
                } else if (createError.status === 404 && createError.body.error === 'project with project=' + DEFAULT_PROJECT_ID + ' not found') {
                    handleError(createError.body, '');
                } else {    
                    handleError(createError, 'Exception when creating instance');
                }
            }
        } else {
            handleError(error, 'Exception when getting instance');
        }
    }
    return instId;
}
async function waitForInstanceAgentToBeReady(apiInstance, instanceId) {
    let agentStatus;
    while (!agentStatus) {
        try {
            console.log('Checking if the app subsystem is ready.');
            const data = await apiInstance.v1AgentAppReady(instanceId);
            agentStatus = data.ready;
            if (!agentStatus) { await sleepForSeconds(SLEEP_TIME_SECONDS); }
        } catch (error) {
            handleError(error, 'Exception when checking agent status.');
        }
    }
    console.log(`The app subsystem on instance ${instanceId} is ready.`);
}
async function waitForInstanceToTurnOn(apiInstance, instanceId) {
    let instanceState;
    let instanceTaskState;
    while (instanceState !== INSTANCE_STATE_ON || instanceTaskState !== INSTANCE_TASK_STATE_NONE) {
        try {
            const data = await apiInstance.v1GetInstance(instanceId);
            instanceState = data.state;
            instanceTaskState = data.taskState;
            if ([INSTANCE_STATE_BOOTING, INSTANCE_STATE_CREATING, INSTANCE_STATE_REBOOTING].includes(instanceState)) {
                console.log(`Waiting for instance to finish ${instanceState}.`);
                await sleepForSeconds(SLEEP_TIME_SECONDS);
            } else if (instanceState === INSTANCE_STATE_ON) {
                (instanceTaskState === INSTANCE_TASK_STATE_NONE)
                    ? console.log(`Instance ${instanceId} is on.`)
                    : handleUnexpectedState(instanceId, instanceState, instanceTaskState);
            } else {
                handleUnexpectedState(instanceId, instanceState, instanceTaskState);
            }
        } catch(error) {
            handleError(error, 'Exception in waitForInstanceToTurnOn()');
        };
    }
}
async function main() {    
    try {
        console.log(`Starting the script at ${new Date().toISOString()}.`);
        checkEnvironmentVariables();
        const apiInstance = new CorelliumClient.CorelliumApi();
        CorelliumClient.ApiClient.instance.basePath = CORELLIUM_API_ENDPOINT;
        CorelliumClient.ApiClient.instance.authentications['BearerAuth'].accessToken = CORELLIUM_API_TOKEN;
        const instanceId = await turnInstanceOnOrCreateNewInstance(apiInstance);
        await waitForInstanceToTurnOn(apiInstance, instanceId);
        await waitForInstanceAgentToBeReady(apiInstance, instanceId);
        await listInstalledApps(apiInstance, instanceId);
        console.log(`Script finished at ${new Date().toISOString()}.`);
    } catch (error) {
        handleError(error, 'Exception in main');
    }
}
main();