Best JavaScript code snippet using istanbul
forcedroid.js
Source:forcedroid.js
1#!/usr/bin/env node2/*3 * Copyright (c) 2013, salesforce.com, inc.4 * All rights reserved.5 * Redistribution and use of this software in source and binary forms, with or6 * without modification, are permitted provided that the following conditions7 * are met:8 * - Redistributions of source code must retain the above copyright notice, this9 * list of conditions and the following disclaimer.10 * - Redistributions in binary form must reproduce the above copyright notice,11 * this list of conditions and the following disclaimer in the documentation12 * and/or other materials provided with the distribution.13 * - Neither the name of salesforce.com, inc. nor the names of its contributors14 * may be used to endorse or promote products derived from this software without15 * specific prior written permission of salesforce.com, inc.16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE26 * POSSIBILITY OF SUCH DAMAGE.27 */28 // node.js application for working with projects that use the Salesforce Mobile29 // SDK for Android. Currently supports the creation of new apps from different30 // app templates and running sample apps.31var exec = require('child_process').exec;32var path = require('path');33var shellJs = require('shelljs');34var fs = require('fs');35var commandLineUtils = require('../external/shared/node/commandLineUtils');36var outputColors = require('../external/shared/node/outputColors');37var packageSdkRootDir = path.resolve(__dirname, '..');38var commandLineArgs = process.argv.slice(2, process.argv.length);39var command = commandLineArgs.shift();40if (typeof command !== 'string') {41 usage();42 process.exit(1);43}44var commandLineArgsMap = {};45if (command === 'samples') {46 var argProcessorList = samplesArgProcessorList();47 commandLineUtils.processArgsInteractive(commandLineArgs, argProcessorList, function (outputArgsMap) {48 var outputDir = outputArgsMap.targetdir;49 fetchSamples(outputDir);50 });51} else {52 // Set up the input argument processing / validation.53 var argProcessorList = createArgProcessorList();54 commandLineUtils.processArgsInteractive(commandLineArgs, argProcessorList, function (outputArgsMap) {55 commandLineArgsMap = outputArgsMap;56 switch (command) {57 case 'create':58 create();59 break;60 default:61 console.log('Unknown option: \'' + command + '\'.');62 usage();63 process.exit(2);64 }65 });66}67function fetchSamples(outputDir) {68 var inputProperties = {};69 var projectDir;70 // Sets properties and copies over the 'FileExplorer' app.71 commandLineArgsMap.apptype = 'native';72 commandLineArgsMap.appname = 'FileExplorer';73 commandLineArgsMap.targetdir = outputDir;74 commandLineArgsMap.packagename = 'com.salesforce.samples.fileexplorer';75 commandLineArgsMap.boolusesmartstore = false;76 inputProperties.templateDir = path.join(packageSdkRootDir, 'native/SampleApps/FileExplorer');77 inputProperties.templateAppName = 'FileExplorer';78 inputProperties.templatePackageName = 'com.salesforce.samples.fileexplorer';79 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);80 inputProperties.bootConfigPath = path.join(projectDir, 'res', 'values', 'bootconfig.xml');81 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';82 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);83 create(inputProperties);84 // Sets properties and copies over the 'NativeSqlAggregator' app.85 commandLineArgsMap.apptype = 'native';86 commandLineArgsMap.appname = 'NativeSqlAggregator';87 commandLineArgsMap.targetdir = outputDir;88 commandLineArgsMap.packagename = 'com.salesforce.samples.nativesqlaggregator';89 commandLineArgsMap.boolusesmartstore = true;90 inputProperties.templateDir = path.join(packageSdkRootDir, 'native/SampleApps/NativeSqlAggregator');91 inputProperties.templateAppName = 'NativeSqlAggregator';92 inputProperties.templatePackageName = 'com.salesforce.samples.nativesqlaggregator';93 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);94 inputProperties.bootConfigPath = path.join(projectDir, 'res', 'values', 'bootconfig.xml');95 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';96 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);97 create(inputProperties);98 // Sets properties and copies over the 'RestExplorer' app.99 commandLineArgsMap.apptype = 'native';100 commandLineArgsMap.appname = 'RestExplorer';101 commandLineArgsMap.targetdir = outputDir;102 commandLineArgsMap.packagename = 'com.salesforce.samples.restexplorer';103 commandLineArgsMap.boolusesmartstore = true;104 inputProperties.templateDir = path.join(packageSdkRootDir, 'native/SampleApps/RestExplorer');105 inputProperties.templateAppName = 'RestExplorer';106 inputProperties.templatePackageName = 'com.salesforce.samples.restexplorer';107 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);108 inputProperties.bootConfigPath = path.join(projectDir, 'res', 'values', 'bootconfig.xml');109 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';110 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);111 create(inputProperties);112 // Sets properties and copies over the 'AccountEditor' app.113 commandLineArgsMap.apptype = 'hybrid_local';114 commandLineArgsMap.appname = 'AccountEditor';115 commandLineArgsMap.targetdir = outputDir;116 commandLineArgsMap.packagename = 'com.salesforce.samples.accounteditor';117 commandLineArgsMap.boolusesmartstore = true;118 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/AccountEditor');119 inputProperties.templateAppName = 'AccountEditor';120 inputProperties.templatePackageName = 'com.salesforce.samples.accounteditor';121 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);122 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');123 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';124 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);125 create(inputProperties);126 // Sets properties and copies over the 'ContactExplorer' app.127 commandLineArgsMap.apptype = 'hybrid_local';128 commandLineArgsMap.appname = 'ContactExplorer';129 commandLineArgsMap.targetdir = outputDir;130 commandLineArgsMap.packagename = 'com.salesforce.samples.contactexplorer';131 commandLineArgsMap.boolusesmartstore = false;132 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/ContactExplorer');133 inputProperties.templateAppName = 'ContactExplorer';134 inputProperties.templatePackageName = 'com.salesforce.samples.contactexplorer';135 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);136 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');137 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';138 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);139 create(inputProperties);140 // Sets properties and copies over the 'HybridFileExplorer' app.141 commandLineArgsMap.apptype = 'hybrid_local';142 commandLineArgsMap.appname = 'HybridFileExplorer';143 commandLineArgsMap.targetdir = outputDir;144 commandLineArgsMap.packagename = 'com.salesforce.samples.hybridfileexplorer';145 commandLineArgsMap.boolusesmartstore = true;146 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/HybridFileExplorer');147 inputProperties.templateAppName = 'HybridFileExplorer';148 inputProperties.templatePackageName = 'com.salesforce.samples.hybridfileexplorer';149 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);150 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');151 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';152 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);153 create(inputProperties);154 // Sets properties and copies over the 'SmartStoreExplorer' app.155 commandLineArgsMap.apptype = 'hybrid_local';156 commandLineArgsMap.appname = 'SmartStoreExplorer';157 commandLineArgsMap.targetdir = outputDir;158 commandLineArgsMap.packagename = 'com.salesforce.samples.smartstoreexplorer';159 commandLineArgsMap.boolusesmartstore = true;160 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/SmartStoreExplorer');161 inputProperties.templateAppName = 'SmartStoreExplorer';162 inputProperties.templatePackageName = 'com.salesforce.samples.smartstoreexplorer';163 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);164 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');165 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';166 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);167 create(inputProperties);168 // Sets properties and copies over the 'VFConnector' app.169 commandLineArgsMap.apptype = 'hybrid_remote';170 commandLineArgsMap.appname = 'VFConnector';171 commandLineArgsMap.targetdir = outputDir;172 commandLineArgsMap.packagename = 'com.salesforce.samples.vfconnector';173 commandLineArgsMap.startpage = '/apex/BasicVFPage';174 commandLineArgsMap.boolusesmartstore = true;175 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/VFConnector');176 inputProperties.templateAppName = 'VFConnector';177 inputProperties.templatePackageName = 'com.salesforce.samples.vfconnector';178 projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);179 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');180 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';181 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);182 create(inputProperties);183}184function usage() {185 console.log(outputColors.cyan + 'Usage:');186 console.log('\n');187 console.log(outputColors.magenta + 'forcedroid create');188 console.log(' --apptype=<Application Type> (native, hybrid_remote, hybrid_local)');189 console.log(' --appname=<Application Name>');190 console.log(' --targetdir=<Target App Folder>');191 console.log(' --packagename=<App Package Identifier> (com.my_company.my_app)');192 console.log(' --startpage=<Path to the remote start page> (/apex/MyPage â Only required/used for \'hybrid_remote\')');193 console.log(' [--usesmartstore=<Whether or not to use SmartStore> (\'true\' or \'false\'. false by default)]');194 console.log(outputColors.cyan + '\nOR\n');195 console.log(outputColors.magenta + 'forcedroid samples');196 console.log(' --targetdir=<Target Samples Folder>' + outputColors.reset);197}198function create(sampleAppInputProperties) {199 200 // The destination project directory, in the target directory.201 var projectDir = path.join(commandLineArgsMap.targetdir, commandLineArgsMap.appname);202 if (fs.existsSync(projectDir)) {203 console.log('App folder path \'' + projectDir + '\' already exists. Cannot continue.');204 process.exit(3);205 }206 var appInputProperties;207 if (sampleAppInputProperties === undefined) {208 appInputProperties = configureInputAppProperties(projectDir);209 } else {210 appInputProperties = sampleAppInputProperties;211 }212 createApp(appInputProperties, projectDir);213}214function createApp(appInputProperties, projectDir) {215 // Copy the template files to the destination directory.216 shellJs.mkdir('-p', projectDir);217 shellJs.cp('-R', path.join(appInputProperties.templateDir, '*'), projectDir);218 shellJs.cp(path.join(appInputProperties.templateDir, '.project'), projectDir);219 shellJs.cp(path.join(appInputProperties.templateDir, '.classpath'), projectDir);220 if (shellJs.error()) {221 console.log('There was an error copying the template files from \'' + appInputProperties.templateDir + '\' to \'' + projectDir + '\': ' + shellJs.error());222 process.exit(4);223 }224 // Copy the SDK into the app folder as well, if it's not already there.225 var destSdkDir = path.join(commandLineArgsMap.targetdir, path.basename(packageSdkRootDir));226 if (!fs.existsSync(destSdkDir)) {227 shellJs.cp('-R', packageSdkRootDir, commandLineArgsMap.targetdir);228 if (shellJs.error()) {229 console.log('There was an error copying the SDK directory from \'' + packageSdkRootDir + '\' to \'' + commandLineArgsMap.targetdir + '\': ' + shellJs.error());230 process.exit(5);231 }232 } else {233 console.log(outputColors.cyan + 'INFO:' + outputColors.reset + ' SDK directory \'' + destSdkDir + '\' already exists. Skipping copy.');234 }235 var contentFilesWithReplacements = makeContentReplacementPathsArray(appInputProperties, projectDir);236 // Library project reference237 console.log(outputColors.yellow + 'Adjusting SalesforceSDK library project reference in project.properties.');238 var absNativeSdkPath = path.join(destSdkDir, 'native', 'SalesforceSDK');239 var nativeSdkPathRelativeToProject = path.relative(projectDir, absNativeSdkPath);240 var projectPropertiesFilePath = path.join(projectDir, 'project.properties');241 shellJs.sed('-i', /=.*SalesforceSDK/g, '=' + nativeSdkPathRelativeToProject, projectPropertiesFilePath);242 // Substitute app class name243 var appClassName = commandLineArgsMap.appname + 'App';244 console.log('Renaming application class to ' + appClassName + ' in source.');245 contentFilesWithReplacements.forEach(function(file) {246 var templateAppClassNameRegExp = new RegExp(appInputProperties.templateAppClassName, 'g');247 shellJs.sed('-i', templateAppClassNameRegExp, appClassName, file);248 });249 // Substitute app name250 console.log('Renaming application to ' + commandLineArgsMap.appname + ' in source.');251 contentFilesWithReplacements.forEach(function(file) {252 var templateAppNameRegExp = new RegExp(appInputProperties.templateAppName, 'g');253 shellJs.sed('-i', templateAppNameRegExp, commandLineArgsMap.appname, file);254 });255 // Substitute package name.256 console.log('Renaming package name to ' + commandLineArgsMap.packagename + ' in source.');257 contentFilesWithReplacements.forEach(function(file) {258 var templatePackageNameRegExp = new RegExp(appInputProperties.templatePackageName.replace(/\./g, '\\.'), 'g');259 shellJs.sed('-i', templatePackageNameRegExp, commandLineArgsMap.packagename, file);260 });261 // Rename source package folders.262 console.log('Moving source files to proper package path.')263 var srcFilePaths = getTemplateSourceFilePaths(appInputProperties, projectDir);264 srcFilePaths.forEach(function(srcFile) {265 fs.renameSync(srcFile.path, path.join(projectDir, 'src', srcFile.name)); // Temporary location266 });267 shellJs.rm('-rf', path.join(projectDir, 'src', 'com'));268 var packageDir = commandLineArgsMap.packagename.replace(/\./g, path.sep);269 shellJs.mkdir('-p', path.resolve(projectDir, 'src', packageDir));270 srcFilePaths.forEach(function(srcFile) {271 fs.renameSync(path.join(projectDir, 'src', srcFile.name), path.resolve(projectDir, 'src', packageDir, srcFile.name));272 });273 // Rename the app class name.274 console.log('Renaming the app class filename to ' + appClassName + '.java.');275 var appClassDir = path.join(projectDir, 'src', packageDir);276 var templateAppClassPath = path.join(appClassDir, appInputProperties.templateAppClassName) + '.java';277 var appClassPath = path.join(appClassDir, appClassName) + '.java';278 fs.renameSync(templateAppClassPath, appClassPath);279 // If SmartStore is configured, set it up.280 if (commandLineArgsMap.usesmartstore) {281 console.log('Adding SmartStore support.');282 shellJs.mkdir('-p', path.join(projectDir, 'assets')); // May not exist for native.283 shellJs.cp(path.join(packageSdkRootDir, 'external', 'sqlcipher', 'assets', 'icudt46l.zip'), path.join(projectDir, 'assets', 'icudt46l.zip'));284 console.log('Adding SmartStore library reference in project.properties.');285 var projectPropertiesContent = shellJs.cat(projectPropertiesFilePath);286 var smartStoreAbsPath = path.join(destSdkDir, 'hybrid', 'SmartStore');287 var smartStorePathRelativeToProject = path.relative(projectDir, smartStoreAbsPath);288 var smartStoreProjectPropertyContent = 'android.library.reference.1=' + smartStorePathRelativeToProject + '\n';289 projectPropertiesContent = smartStoreProjectPropertyContent;290 projectPropertiesContent.to(projectPropertiesFilePath);291 console.log('Extending SalesforceSDKManagerWithSmartStore instead of SalesforceSDKManager.');292 shellJs.sed('-i', /SalesforceSDKManager/g, 'SalesforceSDKManagerWithSmartStore', appClassPath);293 shellJs.sed('-i',294 /com\.salesforce\.androidsdk\.app\.SalesforceSDKManagerWithSmartStore/g,295 'com.salesforce.androidsdk.smartstore.app.SalesforceSDKManagerWithSmartStore',296 appClassPath);297 }298 // If it's a hybrid remote app, replace the start page.299 if (commandLineArgsMap.apptype === 'hybrid_remote') {300 console.log('Changing remote page reference in ' + appInputProperties.bootConfigPath + '.');301 var templateRemotePageRegExp = /\/apex\/BasicVFPage/g;302 shellJs.sed('-i', templateRemotePageRegExp, commandLineArgsMap.startpage, appInputProperties.bootConfigPath);303 }304 // Inform the user of next steps.305 var sdkLibrariesToIncludeMsg = 'the ' + outputColors.magenta + path.join(path.basename(destSdkDir), 'native', 'SalesforceSDK')306 + outputColors.reset + ' library project';307 if (commandLineArgsMap.usesmartstore) {308 sdkLibrariesToIncludeMsg += ', the ' + outputColors.magenta + path.join(path.basename(destSdkDir), 'hybrid', 'SmartStore')309 + outputColors.reset + ' library project';310 }311 var nextStepsOutput =312 ['',313 outputColors.green + 'Your application project is ready in ' + commandLineArgsMap.targetdir + '.',314 '',315 outputColors.cyan + 'To build the new application, do the following:' + outputColors.reset,316 ' - cd ' + projectDir,317 ' - $ANDROID_SDK_DIR/android update project -p .',318 ' - ant clean debug',319 '',320 outputColors.cyan + 'To run the application, start an emulator or plug in your device and run:' + outputColors.reset,321 ' - ant installd',322 '',323 outputColors.cyan + 'To use your new application in Eclipse, do the following:' + outputColors.reset,324 ' - Import ' + sdkLibrariesToIncludeMsg + ',',325 ' and the ' + outputColors.magenta + commandLineArgsMap.appname + outputColors.reset + ' project into your workspace',326 ' - Choose \'Build All\' from the Project menu',327 ' - Run your application by choosing "Run as Android application"',328 ''].join('\n');329 console.log(nextStepsOutput);330 var relativeBootConfigPath = path.relative(commandLineArgsMap.targetdir, appInputProperties.bootConfigPath);331 console.log(outputColors.cyan + 'Before you ship, make sure to plug your OAuth Client ID,\nCallback URI, and OAuth Scopes into '332 + outputColors.magenta + relativeBootConfigPath + '.' + outputColors.reset);333}334function configureInputAppProperties(projectDir) {335 var inputProperties = {};336 switch (commandLineArgsMap.apptype) {337 case 'native':338 inputProperties.templateDir = path.join(packageSdkRootDir, 'native/TemplateApp');339 inputProperties.templateAppName = 'Template';340 inputProperties.templatePackageName = 'com.salesforce.samples.templateapp';341 inputProperties.bootConfigPath = path.join(projectDir, 'res', 'values', 'bootconfig.xml');342 break;343 case 'hybrid_local':344 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/ContactExplorer');345 inputProperties.templateAppName = 'ContactExplorer';346 inputProperties.templatePackageName = 'com.salesforce.samples.contactexplorer';347 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');348 break;349 case 'hybrid_remote':350 inputProperties.templateDir = path.join(packageSdkRootDir, 'hybrid/SampleApps/VFConnector');351 inputProperties.templateAppName = 'VFConnector';352 inputProperties.templatePackageName = 'com.salesforce.samples.vfconnector';353 inputProperties.bootConfigPath = path.join(projectDir, 'assets', 'www', 'bootconfig.json');354 break;355 }356 inputProperties.templateAppClassName = inputProperties.templateAppName + 'App';357 inputProperties.templatePackageDir = inputProperties.templatePackageName.replace(/\./g, path.sep);358 return inputProperties;359}360function makeContentReplacementPathsArray(appInputProperties, projectDir) {361 var returnArray = [];362 returnArray.push(path.join(projectDir, 'AndroidManifest.xml'));363 returnArray.push(path.join(projectDir, '.project'));364 returnArray.push(path.join(projectDir, 'build.xml'));365 returnArray.push(path.join(projectDir, 'res', 'values', 'strings.xml'));366 returnArray.push(appInputProperties.bootConfigPath);367 var srcFilePaths = getTemplateSourceFilePaths(appInputProperties, projectDir);368 srcFilePaths.forEach(function(srcFile) {369 returnArray.push(srcFile.path);370 });371 return returnArray;372}373function getTemplateSourceFilePaths(appInputProperties, projectDir) {374 var srcFilesArray = [];375 var srcDir = path.join(projectDir, 'src', appInputProperties.templatePackageDir);376 fs.readdirSync(srcDir).forEach(function(srcFile) {377 if (/\.java$/.test(srcFile))378 srcFilesArray.push({ 'name': srcFile, 'path': path.join(srcDir, srcFile) });379 });380 return srcFilesArray;381}382// -----383// Input argument validation / processing.384// -----385function createArgProcessorList() {386 var argProcessorList = new commandLineUtils.ArgProcessorList();387 // App type388 argProcessorList.addArgProcessor('apptype', 'Enter your application type (native, hybrid_remote, or hybrid_local):', function(appType) {389 appType = appType.trim();390 if (appType !== 'native' && appType !== 'hybrid_remote' && appType !== 'hybrid_local')391 return new commandLineUtils.ArgProcessorOutput(false, 'App type must be native, hybrid_remote, or hybrid_local.');392 return new commandLineUtils.ArgProcessorOutput(true, appType);393 });394 // App name395 argProcessorList.addArgProcessor('appname', 'Enter your application name:', function(appName) {396 if (appName.trim() === '')397 return new commandLineUtils.ArgProcessorOutput(false, 'Invalid value for app name: \'' + appName + '\'');398 399 return new commandLineUtils.ArgProcessorOutput(true, appName.trim());400 });401 // Target dir402 argProcessorList.addArgProcessor('targetdir', 'Enter the target directory of your app:', function(targetDir) {403 if (targetDir.trim() === '')404 return new commandLineUtils.ArgProcessorOutput(false, 'Invalid value for target dir: \'' + targetDir + '\'');405 406 return new commandLineUtils.ArgProcessorOutput(true, targetDir.trim());407 });408 // Package name409 argProcessorList.addArgProcessor('packagename', 'Enter the package name for your app (com.mycompany.my_app):', function(packageName) {410 if (packageName.trim() === '')411 return new commandLineUtils.ArgProcessorOutput(false, 'Invalid value for package name: \'' + packageName + '\'');412 packageName = packageName.trim();413 var validPackageRegExp = /^[a-z]+[a-z0-9_]*(\.[a-z]+[a-z0-9_]*)*$/;414 if (!validPackageRegExp.test(packageName)) {415 return new commandLineUtils.ArgProcessorOutput(false, '\'' + packageName + '\' is not a valid Java package name.');416 }417 418 return new commandLineUtils.ArgProcessorOutput(true, packageName);419 });420 // Start page421 argProcessorList.addArgProcessor(422 'startpage',423 'Enter the start page for your app (only applicable for hybrid_remote apps):',424 function(startPage, argsMap) {425 if (argsMap && argsMap.apptype === 'hybrid_remote') {426 if (startPage.trim() === '')427 return new commandLineUtils.ArgProcessorOutput(false, 'Invalid value for start page: \'' + startPage + '\'');428 return new commandLineUtils.ArgProcessorOutput(true, startPage.trim());429 }430 // Unset any value here, as it doesn't apply for non-remote apps.431 return new commandLineUtils.ArgProcessorOutput(true, undefined);432 },433 function (argsMap) {434 return (argsMap['apptype'] === 'hybrid_remote');435 }436 );437 // Use SmartStore438 argProcessorList.addArgProcessor('usesmartstore', 'Do you want to use SmartStore in your app? [yes/NO] (\'No\' by default)', function(useSmartStore) {439 var boolUseSmartStore = (useSmartStore.trim().toLowerCase() === 'yes');440 return new commandLineUtils.ArgProcessorOutput(true, boolUseSmartStore);441 });442 return argProcessorList;443}444function samplesArgProcessorList() {445 var argProcessorList = new commandLineUtils.ArgProcessorList();446 // Target dir447 argProcessorList.addArgProcessor('targetdir', 'Enter the target directory of samples:', function(targetDir) {448 if (targetDir.trim() === '')449 return new commandLineUtils.ArgProcessorOutput(false, 'Invalid value for target dir: \'' + targetDir + '\'');450 451 return new commandLineUtils.ArgProcessorOutput(true, targetDir.trim());452 });453 return argProcessorList;...
plugin.js
Source:plugin.js
1/**2 * plugin.js3 *4 * Copyright, Moxiecode Systems AB5 * Released under LGPL License.6 *7 * License: http://www.tinymce.com/license8 * Contributing: http://www.tinymce.com/contributing9 */10/*global tinymce:true, console:true */11/**12 * This plugin adds missing events form the 4.x API back. Not every event is13 * properly supported but most things should work.14 *15 * Unsupported things:16 * - No editor.onEvent17 * - Can't cancel execCommands with beforeExecCommand18 */19(function(tinymce) {20 var reported;21 function log(apiCall) {22 if (!reported && window && window.console) {23 reported = true;24 console.log("Deprecated TinyMCE API call: " + apiCall);25 }26 }27 function Dispatcher(target, newEventName, argsMap, defaultScope) {28 target = target || this;29 this.add = function(callback, scope) {30 log('<target>.on' + newEventName + ".add(..)");31 // Convert callback({arg1:x, arg2:x}) -> callback(arg1, arg2)32 function patchedEventCallback(e) {33 var callbackArgs = [];34 if (typeof argsMap == "string") {35 argsMap = argsMap.split(" ");36 }37 if (argsMap && typeof argsMap != "function") {38 for (var i = 0; i < argsMap.length; i++) {39 callbackArgs.push(e[argsMap[i]]);40 }41 }42 if (typeof argsMap == "function") {43 callbackArgs = argsMap(newEventName, e, target);44 if (!callbackArgs) {45 return;46 }47 }48 if (!argsMap) {49 callbackArgs = [e];50 }51 callbackArgs.unshift(defaultScope || target);52 if (callback.apply(scope || defaultScope || target, callbackArgs) === false) {53 e.stopImmediatePropagation();54 }55 }56 target.on(newEventName, patchedEventCallback);57 return patchedEventCallback;58 };59 // Not supported to just use add60 this.addToTop = this.add;61 this.remove = function(callback) {62 return target.off(newEventName, callback);63 };64 this.dispatch = function() {65 target.fire(newEventName);66 return true;67 };68 }69 tinymce.onBeforeUnload = new Dispatcher(tinymce, "BeforeUnload");70 tinymce.onAddEditor = new Dispatcher(tinymce, "AddEditor", "editor");71 tinymce.onRemoveEditor = new Dispatcher(tinymce, "RemoveEditor", "editor");72 function patchEditor(editor) {73 function patchEditorEvents(oldEventNames, argsMap) {74 tinymce.each(oldEventNames.split(" "), function(oldName) {75 editor["on" + oldName] = new Dispatcher(editor, oldName, argsMap);76 });77 }78 function convertUndoEventArgs(type, event, target) {79 return [80 event.level,81 target82 ];83 }84 function filterSelectionEvents(needsSelection) {85 return function(type, e) {86 if ((!e.selection && !needsSelection) || e.selection == needsSelection) {87 return [e];88 }89 };90 }91 if (editor.controlManager) {92 return;93 }94 editor.controlManager = {95 buttons: {},96 setDisabled: function(name, state) {97 log("controlManager.setDisabled(..)");98 if (this.buttons[name]) {99 this.buttons[name].disabled(state);100 }101 },102 setActive: function(name, state) {103 log("controlManager.setActive(..)");104 if (this.buttons[name]) {105 this.buttons[name].active(state);106 }107 },108 };109 patchEditorEvents("PreInit BeforeRenderUI PostRender Load Init Remove Activate Deactivate", "editor");110 patchEditorEvents("Click MouseUp MouseDown DblClick KeyDown KeyUp KeyPress ContextMenu Paste Submit Reset");111 patchEditorEvents("BeforeExecCommand ExecCommand", "command ui value args"); // args.terminate not supported112 patchEditorEvents("PreProcess PostProcess LoadContent SaveContent Change");113 patchEditorEvents("BeforeSetContent BeforeGetContent SetContent GetContent", filterSelectionEvents(false));114 patchEditorEvents("SetProgressState", "state time");115 patchEditorEvents("VisualAid", "element hasVisual");116 patchEditorEvents("Undo Redo", convertUndoEventArgs);117 patchEditorEvents("NodeChange", function(type, e) {118 return [119 editor.controlManager,120 e.element,121 editor.selection.isCollapsed(),122 e123 ];124 });125 var originalAddButton = editor.addButton;126 editor.addButton = function(name, settings) {127 var originalOnPostRender;128 function patchedPostRender() {129 editor.controlManager.buttons[name] = this;130 if (originalOnPostRender) {131 return originalOnPostRender.call(this);132 }133 }134 for (var key in settings) {135 if (key.toLowerCase() === "onpostrender") {136 originalOnPostRender = settings[key];137 settings.onPostRender = patchedPostRender;138 }139 }140 if (!originalOnPostRender) {141 settings.onPostRender = patchedPostRender;142 }143 settings.title = tinymce.i18n.translate((editor.settings.language || "en") + "." + settings.title);144 return originalAddButton.call(this, name, settings);145 };146 editor.on('init', function() {147 var undoManager = editor.undoManager, selection = editor.selection;148 undoManager.onUndo = new Dispatcher(editor, "Undo", convertUndoEventArgs, null, undoManager);149 undoManager.onRedo = new Dispatcher(editor, "Redo", convertUndoEventArgs, null, undoManager);150 undoManager.onBeforeAdd = new Dispatcher(editor, "BeforeAddUndo", null, undoManager);151 undoManager.onAdd = new Dispatcher(editor, "AddUndo", null, undoManager);152 selection.onBeforeGetContent = new Dispatcher(editor, "BeforeGetContent", filterSelectionEvents(true), selection);153 selection.onGetContent = new Dispatcher(editor, "GetContent", filterSelectionEvents(true), selection);154 selection.onBeforeSetContent = new Dispatcher(editor, "BeforeSetContent", filterSelectionEvents(true), selection);155 selection.onSetContent = new Dispatcher(editor, "SetContent", filterSelectionEvents(true), selection);156 editor.windowManager.createInstance = function(className, a, b, c, d, e) {157 log("windowManager.createInstance(..)");158 var constr = tinymce.resolve(className);159 return new constr(a, b, c, d, e);160 };161 });162 }163 tinymce.on('SetupEditor', patchEditor);164 tinymce.PluginManager.add("compat3x", patchEditor);165 tinymce.addI18n = function(prefix, o) {166 var I18n = tinymce.util.I18n, each = tinymce.each;167 if (typeof(prefix) == "string" && prefix.indexOf('.') === -1) {168 I18n.add(prefix, o);169 return;170 }171 if (!tinymce.is(prefix, 'string')) {172 each(prefix, function(o, lc) {173 each(o, function(o, g) {174 each(o, function(o, k) {175 if (g === 'common') {176 I18n.data[lc + '.' + k] = o;177 } else {178 I18n.data[lc + '.' + g + '.' + k] = o;179 }180 });181 });182 });183 } else {184 each(o, function(o, k) {185 I18n.data[prefix + '.' + k] = o;186 });187 }188 };...
main-page.js
Source:main-page.js
1var vmModule = require("./main-view-model");2function pageLoaded(args) {3 var page = args.object;4 page.bindingContext = vmModule.mainViewModel;5}6exports.pageLoaded = pageLoaded;7var mapbox = require("nativescript-mapbox");8function onMapReady(args) {9 args.map.addMarkers([10 {11 id: 2,12 lat: 52.3602160,13 lng: 4.8891680,14 title: 'One-line title here', // no popup unless set15 subtitle: 'Really really nice location',16 iconPath: 'res/markers/green_pin_marker.png',17 onTap: function(){console.log("'Nice location' marker tapped");},18 onCalloutTap: function(){console.log("'Nice location' marker callout tapped");}19 }]20 );21 22 setTimeout(function() {23 args.map.setOnMapClickListener(function(point) {24 console.log("Map clicked: " + JSON.stringify(point));25 });26 args.map.setViewport(27 {28 bounds: {29 north: 52.4820,30 east: 5.1087,31 south: 52.2581,32 west: 4.681633 },34 animated: true35 }36 );37 }, 3000);38 setTimeout(function() {39 args.map.setMapStyle(mapbox.MapStyle.DARK);40 }, 5000);41/*42 setTimeout(function() {43 args.map.addPolyline({44 id: 10,45 color: 0xffff0000,46 points: [47 {48 lat: 52.4,49 lng: 550 },51 {52 lat: 51.9,53 lng: 5.154 },55 {56 lat: 51.8,57 lng: 4.9558 }59 ]60 });61 }, 6000);62 */63 setTimeout(function() {64 args.map.setCenter({65 lat: 52.4820,66 lng: 5.1087,67 animated: true68 });69 }, 6100);70 setTimeout(function() {71 args.map.setZoomLevel({72 level: 8,73 animated: true74 });75 }, 8000);76 // setTimeout(function() {77 // args.map.removeMarkers([2]);78 // }, 10000);79 setTimeout(function() {80 args.map.setTilt({81 tilt: 85,82 duration: 250083 });84 }, 10000);85/*86 setTimeout(function() {87 args.map.animateCamera({88 target: {89 lat: 51.8,90 lng: 591 },92 tilt: 80,93 zoomLevel: 9,94 duration: 400095 });96 }, 13000);97*/98 // setTimeout(function() {99 // args.map.removePolylines([10]);100 // }, 15000);101}...
Using AI Code Generation
1module.exports = function(args) {2 return args.map(function(arg) { return arg * 2; });3};4var assert = require('assert');5var test = require('./test');6describe('test', function() {7 it('should double each element of an array', function() {8 assert.deepEqual(test([1, 2, 3]), [2, 4, 6]);9 });10});
Using AI Code Generation
1var args = require('yargs').argv;2var x = args._[0];3var y = args._[1];4var z = args._[2];5function add(x, y) {6 return x + y;7}8function addThree(x, y, z) {9 return x + y + z;10}11console.log(add(x, y));12console.log(addThree(x, y, z));13var expect = require('chai').expect;14var exec = require('child_process').exec;15describe('add()', function() {16 it('should add two numbers', function(done) {17 exec('node test.js 5 5', function(err, stdout) {18 expect(stdout).to.equal('10');19 done();20 });21 });22});23describe('addThree()', function() {24 it('should add three numbers', function(done) {25 exec('node test.js 5 5 5', function(err, stdout) {26 expect(stdout).to.equal('15');27 done();28 });29 });30});31{32 "scripts": {33 },34 "devDependencies": {35 }36}37"scripts": {38}
Using AI Code Generation
1var args = require('system').args;2var page = require('webpage').create();3var url = args[1];4page.open(url, function () {5 var result = page.evaluate(function () {6 return document.body.innerHTML;7 });8 console.log(result);9 phantom.exit();10});11var a = 1;12var b = 2;13var c = a + b;14document.write(c);15var a = 1;16var b = 2;17var c = a + b;18document.write(c);19var a = 1;20var b = 2;21var c = a + b;22document.write(c);23var a = 1;24var b = 2;25var c = a + b;26document.write(c);27var a = 1;28var b = 2;29var c = a + b;30document.write(c);31var a = 1;32var b = 2;33var c = a + b;34document.write(c);35var a = 1;36var b = 2;37var c = a + b;38document.write(c);39var a = 1;40var b = 2;41var c = a + b;42document.write(c);43var a = 1;44var b = 2;45var c = a + b;46document.write(c);47var a = 1;48var b = 2;49var c = a + b;50document.write(c);51var a = 1;52var b = 2;53var c = a + b;54document.write(c);55var a = 1;56var b = 2;
Using AI Code Generation
1var args = process.argv;2args.map(function (val, index) {3 console.log(index + ': ' + val);4});5var args = process.argv;6args.map(function (val, index) {7 console.log(index + ': ' + val);8});9var args = process.argv;10args.map(function (val, index) {11 console.log(index + ': ' + val);12});13{14 "scripts": {15 },16}
Using AI Code Generation
1var args = require('yargs').argv;2var path = require('path');3var coverage = require('istanbul');4var collector = new coverage.Collector();5var reporter = new coverage.Reporter();6var sync = false;7var reports = ['text', 'lcov'];8var files = args._;9collector.add(args);10reporter.addAll(reports);11reporter.write(collector, sync, function() {12 console.log('done');13});14{15 "scripts": {16 }17}
Using AI Code Generation
1var args = process.argv.slice(2);2args.map(function(val, index, array) {3 console.log(index + ': ' + val);4});5var args = process.argv.slice(2);6var sum = args.reduce(function(a, b) {7 return parseInt(a) + parseInt(b);8});9console.log(sum);10var args = process.argv.slice(2);11var filtered = args.filter(function(val) {12 return val.length > 1;13});14console.log(filtered);15var args = process.argv.slice(2);16var some = args.some(function(val) {17 return val.length > 1;18});19console.log(some);20var args = process.argv.slice(2);21var every = args.every(function(val) {22 return val.length > 1;23});24console.log(every);25var args = process.argv.slice(2);26args.forEach(function(val, index, array) {27 console.log(index + ': ' + val);28});29var args = process.argv.slice(2);30var index = args.indexOf('2');31console.log(index);
Using AI Code Generation
1require('babel/register')({2});3require('./src/test.js');4import _ from 'lodash';5import {expect} from 'chai';6describe('Test', function(){7 it('should work', function(){8 expect(_.map([1,2,3], function(n){9 return n + 1;10 })).to.eql([2,3,4]);11 });12});13(function (exports, require, module, __filename, __dirname) { import _ from 'lodash';14 at exports.runInThisContext (vm.js:53:16)15 at Module._compile (module.js:411:25)16 at Object.Module._extensions..js (module.js:446:10)17 at Module.load (module.js:353:32)18 at Function.Module._load (module.js:308:12)19 at Function.Module.runMain (module.js:469:10)20 at startup (node.js:117:18)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!