How to use configFile method in Cypress

Best JavaScript code snippet using cypress

config.js

Source:config.js Github

copy

Full Screen

1const debug = require('debug')('utils:config')2const crypto = require("crypto")3const Ajv = require('ajv')4const ajv = new Ajv({ useDefaults: true })5const NodeRSA = require('node-rsa')6const validateConfig = ajv.compile(require("./schema/config.json"));7const VERSION_ORDER = ["schema", "privKey", "profile", "info", "settings", "payment", "meta"]8const PRIVAT_KEY_BIT = 10249const DEFAULT_PATH = "./config.json"10const stringify = require('fast-json-stable-stringify')11let persistence = {}12let config = {}13config.version = {}14config.version.component = {}15VERSION_ORDER.forEach((configuration) => config.version.component[configuration] = {})16config.settings = {}17config.meta = {}18/** 19 * Initialisises the config and reads it the first time20 */21config.init = async function (path = DEFAULT_PATH) {22 config.file = new Promise(async (resolve, reject) => {23 try {24 if (typeof path === 'string') {25 persistence = require('./storage/filesystem')26 let configFile = JSON.parse(await persistence.read(path))27 let valid = validateConfig(configFile)28 if (!valid)29 throw new Error(validateConfig.errors[0].dataPath + " " + validateConfig.errors[0].message)30 new URL(configFile.url)31 config.path = path32 } else if (typeof path === 'object') {33 persistence = require('./storage/inMemory')34 let configFile = path35 let valid = validateConfig(configFile)36 if (!valid)37 throw new Error(validateConfig.errors[0].dataPath + " " + validateConfig.errors[0].message)38 new URL(configFile.url)39 persistence.write('./env/description/input.md', configFile.info.input.description)40 configFile.info.input.description = './env/description/input.md'41 persistence.write('./env/description/output.md', configFile.info.output.description)42 configFile.info.output.description = './env/description/output.md'43 persistence.write('./env/description/worker.md', configFile.info.worker.description)44 configFile.info.worker.description = './env/description/worker.md'45 persistence.write('./env/schema/output.json', JSON.stringify(configFile.schema.output))46 configFile.schema.output = './env/schema/output.json'47 persistence.write('./env/schema/input.json', JSON.stringify(configFile.schema.input))48 configFile.schema.input = './env/schema/input.json'49 persistence.write('./env/key.pem', configFile.privKey)50 configFile.privKey = './env/key.pem'51 persistence.write('./config.json', JSON.stringify(configFile))52 new URL(configFile.url)53 config.path = DEFAULT_PATH54 }55 resolve(await config.get("full", { fromFile: true }))56 } catch (error) {57 reject(error)58 }59 })60 return config.file61}62/** 63 * Return a specified field fully resolved or get the full config with 'full'64 * @param request The field or full config to resolve 65*/66config.get = async function (request, { fromFile = false } = {}) {67 debug("Retrieve from config: " + request)68 if (fromFile) {69 let configFile = JSON.parse(await persistence.read(config.path))70 if (request === "full") {71 return {72 "credentials": await config.resolve(configFile, "credentials"),73 "payment": await config.resolve(configFile, "payment"),74 "url": await config.resolve(configFile, "url"),75 "schema": await config.resolve(configFile, "schema"),76 "privKey": await config.resolve(configFile, "privKey"),77 "profile": await config.resolve(configFile, "profile"),78 "info": await config.resolve(configFile, "info"),79 "settings": await config.resolve(configFile, "settings"),80 "meta": await config.resolve(configFile, "meta"),81 }82 } else {83 return await config.resolve(configFile, request)84 }85 } else {86 if (request === "full") {87 return await config.file88 } else {89 return (await config.file)[request]90 }91 }92}93/** 94 * Resolving a specified field of a given config with the correct files95 * @param configFile Given config object 96 * @param field The field to resolve97*/98config.resolve = async function (configFile, field) {99 debug("Resolve from file: " + field)100 switch (field) {101 case "privKey":102 try {103 configFile.privKey = await persistence.read(configFile.privKey)104 } catch (err) {105 if (err.code === "ENOENT") {106 debug("Could not find private key. Creating one...")107 await persistence.directory(configFile.privKey)108 let privKeyLocation = configFile.privKey109 configFile.privKey = (new NodeRSA({ b: PRIVAT_KEY_BIT })).exportKey('private')110 await persistence.write(privKeyLocation, configFile.privKey)111 } else {112 throw err113 }114 }115 break;116 case "schema":117 try {118 configFile.schema.input = JSON.parse(await persistence.read(configFile.schema.input))119 } catch (err) {120 if (err.code === "ENOENT") {121 debug("Could not find input schema. Creating one...")122 await persistence.directory(configFile.schema.input)123 await persistence.write(configFile.schema.input, JSON.stringify({}))124 configFile.schema.input = {}125 } else {126 throw err127 }128 }129 try {130 configFile.schema.output = JSON.parse(await persistence.read(configFile.schema.output))131 } catch (err) {132 if (err.code === "ENOENT") {133 debug("Could not find output schema. Creating one...")134 await persistence.directory(configFile.schema.output)135 await persistence.write(configFile.schema.output, JSON.stringify({}))136 configFile.schema.output = {}137 } else {138 throw err139 }140 }141 break;142 case "info":143 try {144 configFile.info.worker.description = await persistence.read(configFile.info.worker.description)145 } catch (err) {146 if (err.code === "ENOENT") {147 debug("Could not find worker description. Creating one...")148 await persistence.directory(configFile.info.worker.description)149 await persistence.write(configFile.info.worker.description, "")150 configFile.info.worker.description = ""151 } else {152 throw err153 }154 }155 try {156 configFile.info.input.description = await persistence.read(configFile.info.input.description)157 } catch (err) {158 if (err.code === "ENOENT") {159 debug("Could not find input description. Creating one...")160 await persistence.directory(configFile.info.input.description)161 await persistence.write(configFile.info.input.description, "")162 configFile.info.input.description = ""163 } else {164 throw err165 }166 }167 try {168 configFile.info.output.description = await persistence.read(configFile.info.output.description)169 } catch (err) {170 if (err.code === "ENOENT") {171 debug("Could not find output description. Creating one...")172 await persistence.directory(configFile.info.output.description)173 await persistence.write(configFile.info.output.description, "")174 configFile.info.output.description = ""175 } else {176 throw err177 }178 }179 break;180 default:181 break;182 }183 if (VERSION_ORDER.includes(field))184 await config.version.update(field, configFile[field])185 return configFile[field]186}187/** 188 * Updating specific field with a configuration189 * @param field The field to update190 * @param configuration The update configuration191*/192config.update = async function (field, configuration, { recursive = false, spacing = 2 } = {}) {193 let managedConfig = await config.file194 config.file = new Promise(async (resolve, reject) => {195 debug("Updating: " + field)196 try {197 let configFile = JSON.parse(await persistence.read(config.path))198 // Check against schema -- Too Hacky199 // Copy to not mess with actual work later200 let configCopy = JSON.parse(JSON.stringify(configFile))201 debug(configuration)202 let configurationCopy = JSON.parse(JSON.stringify(configuration))203 // Rewrite fields to be comparable204 if (recursive) {205 switch (field) {206 case "privKey":207 break;208 case "schema":209 configurationCopy.output = configCopy.schema.output210 configurationCopy.input = configCopy.schema.input211 configCopy.schema = configurationCopy212 break;213 case "info":214 configurationCopy.output.description = configCopy.info.output.description215 configurationCopy.input.description = configCopy.info.input.description216 configurationCopy.worker.description = configCopy.info.worker.description217 // Overwrite old file with new file ( tags missing in old file )218 configCopy.info = configurationCopy219 break;220 default:221 configCopy[field] = configurationCopy222 break;223 }224 } else {225 configCopy[field] = configurationCopy226 }227 // Check against schema228 let valid = validateConfig(configCopy)229 if (!valid) {230 throw new Error(validateConfig.errors[0].dataPath + " " + validateConfig.errors[0].message)231 }232 if (recursive) {233 switch (field) {234 case "privKey":235 await persistence.write(configFile.privKey, configuration)236 break;237 case "schema":238 // Recursive write schenmas239 await persistence.write(configFile.schema.output, JSON.stringify(configuration.output, null, spacing))240 await persistence.write(configFile.schema.input, JSON.stringify(configuration.input, null, spacing))241 // Overwrite old file with new file 242 configFile.schema = {243 output: configFile.schema.output,244 input: configFile.schema.input245 }246 // Write to config247 await persistence.write(config.path, JSON.stringify(configFile, null, spacing))248 break;249 case "info":250 // Recursive write descriptions251 await persistence.write(configFile.info.worker.description, configuration.worker.description)252 await persistence.write(configFile.info.input.description, configuration.input.description)253 await persistence.write(configFile.info.output.description, configuration.output.description)254 // Overwrite old file with new file ( tags missing in old file )255 configFile.info = {256 output: configFile.info.output,257 input: configFile.info.input,258 worker: configFile.info.worker259 }260 // Write to config261 await persistence.write(config.path, JSON.stringify(configFile, null, spacing))262 break;263 default:264 configFile[field] = configuration265 await persistence.write(config.path, JSON.stringify(configFile, null, spacing))266 break;267 }268 } else {269 configFile[field] = configuration270 await persistence.write(config.path, JSON.stringify(configFile, null, spacing))271 switch (field) {272 case "privKey":273 break;274 case "schema":275 delete configuration.schema.output276 delete configuration.schema.input277 break;278 case "info":279 delete configuration.output.description280 delete configuration.input.description281 delete configuration.worker.description282 break;283 }284 }285 managedConfig[field] = configuration286 if (VERSION_ORDER.includes(field))287 await config.version.update(field, managedConfig[field])288 resolve(managedConfig)289 } catch (error) {290 reject(error)291 }292 })293 return config.file294}295/***296 * Returns the current verison297 */298config.version.get = async function () {299 await config.file300 let versions = []301 VERSION_ORDER.forEach((field) => {302 versions.push(config.version.component[field].hash + "@" + config.version.component[field].timestamp)303 })304 return versions.join(".")305}306/**307 * @param configuration the full config opject308 * @param field the field to update e.g. schema, info etc.309*/310config.version.update = async function (field, configuration) {311 let configFile = JSON.parse(await persistence.read(config.path))312 let configurationHash313 if (field === "privKey") {314 let key = (new NodeRSA(configuration)).exportKey('public')315 configurationHash = crypto.createHash('sha256').update(key).digest('base64')316 } else {317 configurationHash = crypto.createHash('sha256').update(stringify(configuration)).digest('base64')318 }319 let configurationTimestamp = await persistence.time(config.path)320 let valid = validateConfig(configFile)321 if (!valid)322 throw new Error(validateConfig.errors[0].dataPath + " " + validateConfig.errors[0].message)323 switch (field) {324 case "privKey":325 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.privKey))326 break;327 case "schema":328 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.schema.input))329 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.schema.output))330 break;331 case "info":332 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.info.input.description))333 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.info.output.description))334 configurationTimestamp = Math.max(configurationTimestamp, await persistence.time(configFile.info.worker.description))335 default:336 break;337 }338 config.version.component[field].hash = configurationHash339 config.version.component[field].timestamp = configurationTimestamp340}341/** 342 * Comparing a version ( every number is mapped to the corresponding hash ) to the underlying files343 * @param version The version e.g. ( 'qI7[...]FwA=.qI7[...]FwA=.qI7[...]FwA=' )344*/345config.version.compare = async function (version) {346 debug("Compare the version with: " + version)347 await config.file348 let hashes = version.split(".")349 let change = []350 for (const [index, version] of hashes.entries()) {351 let [hash, timestamp] = version.split("@")352 if (hash === config.version.component[VERSION_ORDER[index]].hash) {353 change[index] = 0354 } else {355 if (timestamp >= config.version.component[VERSION_ORDER[index]].timestamp) {356 change[index] = 1357 } else {358 change[index] = -1359 }360 }361 }362 return change.join(".")363}364/**365 * Returns the requested changes366 * @param changes Requested changes e.g. 1.1.1.1.1367 */368config.version.changes = async function (changes) {369 let result = {}370 for (const [index, change] of (changes.split(".")).entries()) {371 if (change === "1") {372 if (VERSION_ORDER[index] !== "privKey") {373 result[VERSION_ORDER[index]] = await config.get(VERSION_ORDER[index])374 } else {375 result["pubkey"] = (new NodeRSA(await config.get(VERSION_ORDER[index]))).exportKey('public')376 }377 }378 }379 return result380}381/**382 * Returns the settings383 */384config.settings.get = async function () {385 return await config.get("settings")386}387/**388 * Updates the settings object389 * @param settings The value to update390 */391config.settings.update = async function (settings) {392 await config.update("settings", settings)393}394/**395 * Returns the current meta data396 */397config.meta.get = async function () {398 return await config.get("meta")399}400/**401 * Updates the meta object402 * @param meta The value to update403 */404config.meta.update = async function (meta) {405 await config.update("meta", meta)406}407module.exports = {408 version: {409 compare: config.version.compare,410 get: config.version.get,411 changes: config.version.changes412 },413 settings: {414 get: config.settings.get,415 update: config.settings.update416 },417 meta: {418 get: config.meta.get,419 update: config.meta.update420 },421 get: config.get,422 init: config.init,423 update: config.update,424 VERSION_ORDER,...

Full Screen

Full Screen

bot.js

Source:bot.js Github

copy

Full Screen

1// Required libraries/files/variables2var Discord = require('discord.io');3var logger = require('winston');4var auth = require('./auth.json');5var configFile = require('./config.js');6var isRolling = false;7var numMonsters = 0;8var monsterRolls = [];9var failedToRoll = [];1011// Configure logger settings12logger.remove(logger.transports.Console);13logger.add(new logger.transports.Console, {14 colorize: true15});16logger.level = 'debug';1718// Initialize Discord Bot19var bot = new Discord.Client({20 token: auth.token,21 autorun: true22});2324bot.on('ready', function (evt) {25 logger.info('Connected');26 logger.info('Logged in as: ');27 logger.info(bot.username + ' - (' + bot.id + ')');28});2930bot.on('message', function (user, userID, channelID, message, evt) {31 // Listen for messages that will start with `!`32 if (message.substring(0, 1) == '!') {33 var args = message.substring(1).split(' ');34 var cmd = args[0];35 36 args = args.splice(1);37 switch(cmd) {38 case 'hi':39 bot.sendMessage({40 to: channelID,41 message: 'Hello to you too.'42 });43 break;44 case 'help':45 bot.sendMessage({46 to: channelID,47 message: getHelpMessage()48 });49 break;50 case "config":51 bot.sendMessage({52 to: channelID,53 message: getConfigMessage()54 });55 break;56 case "start": 57 bot.sendMessage({58 to: channelID,59 message: getThePartyStarted(user, args[0])60 });61 break;62 case "end": 63 bot.sendMessage({64 to: channelID,65 message: rageQuit(user)66 });67 break;68 case "toggle":69 bot.sendMessage({70 to: channelID,71 message: toggleRollMethod(user, args.join(" "))72 });73 break;74 default:75 var initRoll = Number(cmd);76 if (!isNaN(initRoll)) {77 bot.sendMessage({78 to: channelID,79 message: rollForCharacter(user, initRoll)80 }); 81 } else {82 bot.sendMessage({83 to: channelID,84 message: "I haven't coded that pathway yet."85 }); 86 } 87 break;88 }89 }90});9192// Get a message describing the commands for this bot93function getHelpMessage() { 94 var message = "**The following commands are available to all users**";95 message += "\n**!config**: shows the default players and their roll method";96 message += "\n**!toggle [character name]**: switches the given character between automatic or manual rolls";97 message += "\n**![number]**: the user rolls for the characters they control, in order listed by !config";98 message += "\n\n**The following commands are available only to the DM " + configFile.DMName + "**";99 message += "\n**!start [number]**: starts a round of initiative rolls, including [number] monsters.";100 message += "\n**!end**: finishes a round of initiative rolls, rolling automatically for those who haven't rolled yet";101 message += "\n**![number]**: rolls for the next monster";102 message += "\n**!toggle monsters**: switches the monsters between automatic or manual rolls (automatic by default)";103 104 return message;105}106107// Get a message describing the players noted in the config108function getConfigMessage() {109 var message = "";110 var numChar = 0;111 for( var i = 0; i < configFile.config.length; i++) {112 for( var y = 0; y < configFile.config[i].characters.length; y++) {113 numChar++;114 message += "\n**" + configFile.config[i].characters[y].name + "** (played by " + configFile.config[i].username + ", rolls are ";115 message += configFile.config[i].characters[y].auto ? "automatic)" : "manual)";116 }117 }118 message = numChar != 1 ? "There are " + numChar + " players in the config." + message : "There is " + numChar + " player in the config." + message; 119 message = configFile.autoMonsters ? "**DM " + configFile.DMName + "** is allowing the monsters to control their own destiny.\n" + message:120 "**DM " + configFile.DMName + "** is rolling for the monsters.\n" + message; 121 return message;122}123124// Begin an initiative roll round (only DM is allowed to begin this) and return a message saying who's rolling.125function getThePartyStarted(user, monsters) {126 if (user != configFile.DMName) {127 return "Only **DM " + configFile.DMName + "** can start rolls.";128 }129 130 isRolling = true;131 numMonsters = Number(monsters);132 numMonsters = isNaN(numMonsters) ? 0 : numMonsters;133 message = "Starting initiative rolls, there ";134 message += numMonsters == 0 ? "are no enemies." : numMonsters == 1 ? "is 1 enemy." : "are " + numMonsters + " enemies."; 135 monsterRolls = [];136 failedToRoll = [];137 138 for( var i = 0; i < configFile.config.length; i++) {139 message += "\n**" + configFile.config[i].username + ":** ";140 characterRolls = [configFile.config[i].characters.length];141 for( var y = 0; y < configFile.config[i].characters.length; y++) {142 if (configFile.config[i].characters[y].auto) {143 characterRolls[y] = configFile.config[i].characters[y].name + " is auto-rolling"; 144 configFile.config[i].characters[y].result = getRandomRoll();145 } else {146 characterRolls[y] = "roll for " + configFile.config[i].characters[y].name;147 configFile.config[i].characters[y].result = 0;148 }149 }150 message += characterRolls.join(", ");151 }152 if (configFile.autoMonsters) {153 for(var i = 0; i < numMonsters; i++) {154 monsterRolls.push(getRandomRoll());155 }156 } else {157 message += "\n**DM " + configFile.DMName + "**, please roll for the monsters.";158 }159 160 // Check if everyone is auto-rolling161 var doneMessage = checkDone();162 if (doneMessage == "") {163 isRolling = false;164 return "Everyone is auto-rolling, including the " + numMonsters + " enemies.\n"+ showInitiative();165 } else { 166 return message;167 }168}169170// Finish the initiative roll round. Anyone who hasn't rolled will be rolled for automatically. Return the results.171function rageQuit(user) {172 if (!isRolling) { 173 return "But we're not... even... rolling?";174 } 175 if (user != configFile.DMName) { 176 return "YOU'RE NOT MY SUPERVISOR.";177 }178 179 // Roll for remaining characters. Anyone who was supposed to manually roll gets a bonus.180 var message = "Y'all took too long. Remaining rolls have been done automatically.";181 for( var i = 0; i < configFile.config.length; i++) {182 for( var y = 0; y < configFile.config[i].characters.length; y++) {183 if (configFile.config[i].characters[y].result == 0) {184 configFile.config[i].characters[y].result = getRandomRoll();185 failedToRoll.push(configFile.config[i].characters[y].name);186 }187 }188 } 189 for (var i = monsterRolls.length; i < numMonsters; i++) {190 monsterRolls.push(getRandomRoll());191 }192 193 isRolling = false;194 doneMessage = showInitiative();195 return message + "\n" + doneMessage;196}197198// Toggle if someone is auto-rolling or not199function toggleRollMethod(user, charName) {200 if (isRolling) { 201 return "Wait until after rolls, please. I didn't bother to logic that out.";202 }203 204 var message = "";205 if (charName == "monsters") {206 if (user == configFile.DMName) {207 configFile.autoMonsters = !configFile.autoMonsters;208 message = "Monsters are now";209 message += configFile.autoMonsters ? " auto-rolled." : " manually rolled.";210 } else {211 message = "You're not the DM, leave the monsters alone.";212 }213 } else { 214 for( var i = 0; i < configFile.config.length; i++) {215 for( var y = 0; y < configFile.config[i].characters.length; y++) {216 if (configFile.config[i].characters[y].name == charName) {217 if ( user == configFile.DMName || user == configFile.config[i].username) { 218 configFile.config[i].characters[y].auto = !configFile.config[i].characters[y].auto;219 message = charName + " is now";220 message += configFile.config[i].characters[y].auto ? " auto-rolling." : " manually rolling.";221 } else {222 return "Don't touch what isn't yours, " + user + ". It's rude.";223 }224 }225 }226 }227 }228 return message == "" ? "I don't know this '" + charName + "' you're talking about." : message;229}230231// Return a string calling out who still hasn't rolled, or empty string if all rolling is complete.232function checkDone() {233 var remainingRolls = "";234 for( var i = 0; i < configFile.config.length; i++) {235 for( var y = 0; y < configFile.config[i].characters.length; y++) {236 if (configFile.config[i].characters[y].result == 0) {237 remainingRolls += configFile.config[i].characters[y].name + " (**" + configFile.config[i].username + "**), ";238 }239 }240 }241 if (remainingRolls != "") {242 remainingRolls = "Waiting for " + remainingRolls.slice(0, -2) + "\n";243 }244 245 if (numMonsters > monsterRolls.length) {246 var monstersLeft = numMonsters - monsterRolls.length;247 remainingRolls += "Waiting for DM **" + configFile.DMName + "** to roll for ";248 remainingRolls += monstersLeft > 1 ? monstersLeft + " monsters." : monstersLeft + " monster.";249 }250 251 return remainingRolls;252}253254// Return a string with the sorted initiative results255function showInitiative() {256 message = "**INITIATIVE RESULTS:**```" 257 var tableResults = [];258 for( var i = 0; i < configFile.config.length; i++) {259 for( var y = 0; y < configFile.config[i].characters.length; y++) {260 if (configFile.config[i].characters[y].auto || failedToRoll.includes(configFile.config[i].characters[y].name)) {261 tableResults.push({262 desc: configFile.config[i].characters[y].name + " (" +263 configFile.config[i].characters[y].result + "+" + configFile.config[i].characters[y].bonus + " auto-roll)",264 roll: configFile.config[i].characters[y].result + configFile.config[i].characters[y].bonus265 });266 } else {267 tableResults.push({268 desc: configFile.config[i].characters[y].name + " (manual roll, includes +" + configFile.config[i].characters[y].bonus + ")",269 roll: configFile.config[i].characters[y].result270 });271 }272 }273 }274 for( var m = 0; m < monsterRolls.length; m++) {275 tableResults.push({276 desc: "MONSTER " + (m+1),277 roll: monsterRolls[m]278 });279 }280 281 tableResults = tableResults.sort((a, b) => { return b.roll - a.roll ; });282 for (var l = 0; l < tableResults.length; l++) {283 message += tableResults[l].roll < 10 ? "\n " : "\n";284 message += tableResults[l].roll + " " + tableResults[l].desc;285 }286 287 return message + "```";288}289290// Attempt to assign a roll to a character controlled by the user and return confirmation291function rollForCharacter(user, initRoll) {292 if (!isRolling) {293 return "We're not doing rolls yet, hold your horses.";294 }295 296 var message = "";297 if (user == configFile.DMName) {298 if (monsterRolls.length < numMonsters) {299 monsterRolls.push(initRoll);300 message = user + " rolled a " + initRoll + " for monster " + monsterRolls.length;301 } else {302 return "You've rolled for all " + numMonsters + " monsters already.";303 }304 }305 306 for( var i = 0; i < configFile.config.length; i++) {307 if (configFile.config[i].username == user) {308 for( var y = 0; y < configFile.config[i].characters.length; y++) {309 if (configFile.config[i].characters[y].result == 0) {310 configFile.config[i].characters[y].result = initRoll; 311 message = user + " rolled a " + initRoll + " for " + configFile.config[i].characters[y].name;312 }313 }314 return user + " you already rolled, no take-backs.";315 }316 }317 if (message == "") {318 return user + " you're not even playing, go away.";319 } 320 321 var doneMessage = checkDone();322 if (doneMessage == "") {323 isRolling = false;324 doneMessage = showInitiative();325 }326 return message + "\n" + doneMessage;327}328329// Get a random number between 1 and 20 inclusive330function getRandomRoll() {331 return Math.floor(Math.random() * 20) + 1; ...

Full Screen

Full Screen

cli-config.js

Source:cli-config.js Github

copy

Full Screen

1var path = require('path');2var expect = require('chai').expect;3var rewire = require('rewire');4var configFile = rewire('../../lib/cli-config');5describe('cli-config', function() {6 describe('load method', function() {7 it('should load a config from a package.json file', function() {8 var config = configFile.load('package.json', './test/data/configs/package');9 expect(config).to.be.a('object');10 });11 it('should ignore a package.json file if no config is found in it', function() {12 var config = configFile.load('package.json', './test/data/configs/emptyPackage');13 expect(config).to.be.a('undefined');14 });15 it('should load a config from a .jscs.json file', function() {16 var config = configFile.load('.jscs.json', './test/data/configs/json');17 expect(config).to.be.a('object');18 });19 it('should load a config from a .jscs.yaml file', function() {20 var config = configFile.load('.jscs.yaml', './test/data/configs/yaml');21 expect(config).to.be.a('object');22 expect(config.type).to.equal('yaml');23 });24 it('should load a JSON config from a .jscsrc file', function() {25 var config = configFile.load('.jscsrc', './test/data/configs/jscsrc');26 expect(config).to.be.a('object');27 });28 it('should load a YAML config from a .jscsrc file', function() {29 var config = configFile.load('.jscsrc', './test/data/configs/yaml');30 expect(config).to.be.a('object');31 expect(config.type).to.equal('yaml');32 });33 it('should load a config from upper .jscsrc file', function() {34 var config = configFile.load(null, './test/data/configs/jscsrc/empty');35 expect(config).to.be.a('object');36 expect(config.from).to.equal('jscsrc');37 });38 it('should load a .jscsrc config from a relative path', function() {39 var config = configFile.load('jscsrc/.jscsrc', './test/data/configs');40 expect(config.from).to.equal('jscsrc');41 });42 it('should load a custom config file', function() {43 var config = configFile.load('config.js', './test/data/configs/custom');44 expect(config.from).to.equal('js');45 });46 it('should prefer package.json over .jscs.json and .jscsrc', function() {47 var config = configFile.load(null, './test/data/configs/mixedWithPkg');48 expect(config).to.be.a('object');49 expect(config.from).to.equal('package.json');50 });51 it('should use another config source if package.json contains no config', function() {52 var config = configFile.load(null, './test/data/configs/mixedWithEmptyPkg');53 expect(config.from).to.equal('.jscsrc');54 });55 it('should prefer .jscsrc over .jscs.json', function() {56 var config = configFile.load(null, './test/data/configs/mixedWithoutPkg');57 expect(config).to.be.a('object');58 expect(config.from).to.equal('.jscsrc');59 });60 it('should not fall back to defaults if custom config is missing', function() {61 var config = configFile.load('custom.js', './test/data/configs/mixedWithPkg');62 expect(config).to.equal(undefined);63 });64 it('should load config from lower .jscsrc file instead of package.json', function() {65 var config = configFile.load(null, './test/data/configs/mixedWithUpperPkg/jscsrc');66 expect(config.from).to.equal('.jscsrc');67 });68 it('should fail load json config with comments', function() {69 try {70 configFile.load('./test/data/configs/json/withComments.json');71 throw new Error();72 } catch (e) {73 }74 });75 it('should load json config with BOM', function() {76 try {77 configFile.load('./test/data/configs/json/withBOM.json');78 } catch (e) {79 throw new Error();80 }81 });82 it('should load config from home path: HOME', function() {83 var oldHome = process.env.HOME;84 var oldHOMEPATH = process.env.HOMEPATH;85 var oldUSERPROFILE = process.env.USERPROFILE;86 process.env.HOMEPATH = process.env.USERPROFILE = null;87 process.env.HOME = './test/data/configs/jscsrc';88 expect(configFile.load(null, '/').from).to.equal('jscsrc');89 process.env.HOME = oldHome;90 process.env.HOMEPATH = oldHOMEPATH;91 process.env.USERPROFILE = oldUSERPROFILE;92 });93 it('should load a config from the available home path: HOMEPATH', function() {94 var oldHome = process.env.HOME;95 var oldHOMEPATH = process.env.HOMEPATH;96 var oldUSERPROFILE = process.env.USERPROFILE;97 delete process.env.USERPROFILE;98 delete process.env.HOME;99 process.env.HOMEPATH = './test/data/configs/jscsrc';100 expect(configFile.load(null, '/').from).to.equal('jscsrc');101 process.env.HOME = oldHome;102 process.env.HOMEPATH = oldHOMEPATH;103 process.env.USERPROFILE = oldUSERPROFILE;104 });105 it('should load a config from the available home path: USERPROFILE', function() {106 var oldHome = process.env.HOME;107 var oldHOMEPATH = process.env.HOMEPATH;108 var oldUSERPROFILE = process.env.USERPROFILE;109 process.env.HOME = process.env.HOMEPATH = null;110 process.env.USERPROFILE = './test/data/configs/jscsrc';111 expect(configFile.load(null, '/').from).to.equal('jscsrc');112 process.env.HOME = oldHome;113 process.env.HOMEPATH = oldHOMEPATH;114 process.env.USERPROFILE = oldUSERPROFILE;115 });116 });117 describe('getContent method', function() {118 it('should get content from node module', function() {119 var config = configFile.getContent('path');120 expect(config).to.be.a('object');121 });122 it('should get content from "node_modules"', function() {123 var dir = path.resolve('./test/data/configs/modules');124 var config = configFile.getContent('test', path.resolve('./test/data/configs/modules'));125 expect(config.configPath).to.equal(path.join(dir, 'node_modules/test/index.json'));126 expect(!!config.test).to.equal(true);127 });128 });129 describe('getReporter method', function() {130 it('should get console reporter if called without arguments', function() {131 var reporter = configFile.getReporter();132 expect(reporter.writer).to.be.a('function');133 expect(reporter.path).to.equal(path.resolve('./lib/reporters/console'));134 });135 it('should get console reporter if called with arguments with default values', function() {136 var reporter = configFile.getReporter(undefined, true);137 expect(reporter.writer).to.be.a('function');138 expect(reporter.path).to.equal(path.resolve('./lib/reporters/console'));139 });140 it('should get text reporter if called with colors = false', function() {141 var reporter = configFile.getReporter(undefined, false);142 expect(reporter.writer).to.be.a('function');143 expect(reporter.path).to.equal(path.resolve('./lib/reporters/text'));144 });145 it('should get junit reporter with the name', function() {146 var reporter = configFile.getReporter('junit');147 expect(reporter.writer).to.be.a('function');148 expect(reporter.path).to.equal(path.resolve('./lib/reporters/junit'));149 });150 it('should get reporter with partial path', function() {151 var reporter = configFile.getReporter('./test/data/reporter/test-reporter.js');152 expect(reporter.writer).to.be.a('function');153 expect(reporter.path).to.equal(path.resolve('./test/data/reporter/test-reporter.js'));154 });155 it('should get null instead of function if reporter does not exist', function() {156 var reporter = configFile.getReporter('./test');157 expect(reporter.writer).to.equal(null);158 expect(reporter.path).to.equal(path.resolve('./test'));159 });160 it('should get text reporter if tty does not support colors', function() {161 var old = configFile.__get__('supportsColor');162 configFile.__set__('supportsColor', false);163 var reporter = configFile.getReporter();164 expect(reporter.writer).to.be.a('function');165 expect(reporter.path).to.equal(path.resolve('./lib/reporters/text'));166 configFile.__set__('supportsColor', old);167 });168 it('should fake reporter from node', function() {169 var reporter = configFile.getReporter('path');170 expect(reporter.writer).to.be.a('object');171 expect(reporter.path).to.equal('path');172 });173 it('should fake reporter from node_modules', function() {174 var reporter = configFile.getReporter('sinon');175 expect(reporter.writer).to.be.a('object');176 expect(reporter.path).to.equal('sinon');177 });178 });...

Full Screen

Full Screen

sequelize-auto

Source:sequelize-auto Github

copy

Full Screen

1#!/usr/bin/env node2const SequelizeAuto = require('../');3const path = require('path');4const readline = require('readline');5const _ = require('lodash');6const argv = require('yargs')7 .parserConfiguration({8 "parse-numbers": false // disabled because of password field, other option can still be explicitly defined as number type9 })10 .usage(11 'Usage: sequelize-auto -h <host> -d <database> -u <user> -x [password] -p [port] --dialect [dialect] -c [/path/to/config] -o [/path/to/models] -t [tableName]'12 )13 .option('host', {14 description: 'IP/Hostname for the database.',15 type: 'string',16 alias: 'h'17 })18 .option('database', {19 description: 'Database name.',20 type: 'string',21 alias: 'd'22 })23 .option('user', {24 description: 'Username for database.',25 type: 'string',26 alias: 'u'27 })28 .option('pass', {29 description: 'Password for database. If specified without providing a password, it will be requested interactively from the terminal.',30 alias: 'x'31 })32 .option('port', {33 description: 'Port number for database (not for sqlite). Ex: MySQL/MariaDB: 3306, Postgres: 5432, MSSQL: 1433',34 type: 'number',35 alias: 'p'36 })37 .option('config', {38 description: 'Path to JSON file for Sequelize-Auto options and Sequelize\'s constructor "options" flag object as defined here: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor',39 type: 'string',40 alias: 'c'41 })42 .option('output', {43 description: 'What directory to place the models.',44 type: 'string',45 alias: 'o'46 })47 .option('dialect', {48 description: "The dialect/engine that you're using: postgres, mysql, sqlite, mssql",49 type: 'string',50 alias: 'e'51 })52 .option('additional', {53 description: "Path to JSON file containing model options (for all tables). See the options: https://sequelize.org/master/class/lib/model.js~Model.html#static-method-init",54 type: 'string',55 alias: 'a'56 })57 .option('indentation', {58 description: 'Number of spaces to indent',59 type: 'number'60 })61 .option('tables', {62 description: 'Space-separated names of tables to import',63 array: true,64 type: 'string',65 alias: 't'66 })67 .option('skipTables', {68 description: 'Space-separated names of tables to skip',69 array: true,70 type: 'string',71 alias: 'T'72 })73 .option('skipFields', {74 description: 'Space-separated names of fields to skip',75 array: true,76 type: 'string',77 alias: 'F'78 })79 .option('pkSuffixes', {80 description: 'Space-separated names of primary key suffixes to trim (default is "id")',81 array: true,82 type: 'string'83 })84 .option('caseModel', {85 description: 'Set case of model names: c|l|o|p|u \n c = camelCase \n l = lower_case \n o = original (default) \n p = PascalCase \n u = UPPER_CASE',86 alias: 'cm'87 })88 .option('caseProp', {89 description: 'Set case of property names: c|l|o|p|u',90 alias: 'cp'91 })92 .option('caseFile', {93 description: 'Set case of file names: c|l|o|p|u|k \n k = kebab-case',94 alias: 'cf'95 })96 .option('noAlias', {97 description: 'Avoid creating alias `as` property in relations',98 type: 'boolean'99 })100 .option('noIndexes', {101 description: 'Prevent writing index information in the models',102 type: 'boolean'103 })104 .option('noInitModels', {105 description: 'Prevent writing the init-models file',106 type: 'boolean'107 })108 .option('noWrite', {109 description: 'Prevent writing the models to disk',110 type: 'boolean',111 alias: 'n'112 })113 .option('schema', {114 description: 'Database schema from which to retrieve tables',115 type: 'string',116 alias: 's'117 })118 .option('views', {119 description: 'Include database views in generated models',120 type: 'boolean',121 alias: 'v'122 })123 .option('lang', {124 description: 'Language for Model output: es5|es6|esm|ts \n es5 = ES5 CJS modules (default) \n es6 = ES6 CJS modules \n esm = ES6 ESM modules \n ts = TypeScript ',125 type: 'string',126 alias: 'l'127 })128 .option('useDefine', {129 description: 'Use `sequelize.define` instead of `init` for es6|esm|ts',130 type: 'boolean'131 })132 .option('singularize', {133 description: 'Singularize model and file names from plural table names',134 type: 'boolean',135 alias: 'sg'136 })137 .check(argv => Boolean((argv.database && (argv.host || argv.dialect === 'sqlite')) || argv.config))138 .argv;139function getDefaultPort(dialect) {140 switch (dialect.toLowerCase()) {141 case 'mssql':142 return 1433;143 case 'postgres':144 return 5432;145 default:146 return 3306;147 }148}149async function readPassword() {150 let rl = readline.createInterface({151 input: process.stdin,152 terminal: true153 });154 process.stdout.write('Password: ');155 let pwd = await new Promise(resolve => rl.question('', pwd => resolve(pwd)));156 rl.close();157 process.stdout.write('\n');158 return pwd;159}160/* eslint-disable complexity, max-statements */161(async function() {162 let password;163 if (typeof argv.pass === 'boolean' && argv.pass) {164 password = await readPassword();165 } else if (typeof argv.pass === 'string') {166 console.warn('Warning: using a password on the command line interface can be insecure.');167 password = argv.pass;168 }169 const dir = !argv.noWrite && (argv.output || path.resolve(process.cwd() + '/models'));170 /** @type {import('../types').AutoOptions} */171 let configFile = {172 spaces: true,173 indentation: 2174 };175 if (argv.config) {176 configFile = require(path.resolve(argv.config));177 }178 configFile.directory = configFile.directory || dir;179 let additional = {};180 if (argv.additional) {181 additional = require(path.resolve(argv.additional));182 } else if (configFile.additional) {183 additional = configFile.additional;184 }185 configFile.additional = additional;186 configFile.dialect = argv.dialect || configFile.dialect || 'mysql';187 configFile.port = argv.port || configFile.port || getDefaultPort(configFile.dialect);188 configFile.host = argv.host || configFile.host || 'localhost';189 configFile.database = argv.database || configFile.database;190 configFile.storage = configFile.storage || configFile.database;191 configFile.tables = argv.tables || configFile.tables || null;192 configFile.skipTables = argv.skipTables || configFile.skipTables || null;193 configFile.skipFields = argv.skipFields || configFile.skipFields || null;194 configFile.pkSuffixes = argv.pkSuffixes || configFile.pkSuffixes || null;195 configFile.schema = argv.schema || configFile.schema;196 configFile.lang = argv.lang || configFile.lang || 'es5';197 configFile.caseModel = argv.caseModel || configFile.caseModel || 'o';198 configFile.caseFile = argv.caseFile || configFile.caseFile || 'o';199 configFile.caseProp = argv.caseProp || configFile.caseProp || 'o';200 configFile.noAlias = argv.noAlias || configFile.noAlias || false;201 configFile.noInitModels = argv.noInitModels || configFile.noInitModels || false;202 configFile.noWrite = argv.noWrite || configFile.noWrite || false;203 configFile.views = argv.views || configFile.views || false;204 configFile.singularize = argv.singularize || configFile.singularize || false;205 configFile.password = password || configFile.password || null;206 configFile.username = argv.user || configFile.username;207 configFile.useDefine = argv.useDefine || configFile.useDefine || false;208 configFile.indentation = argv.indentation || configFile.indentation || 2;209 configFile.noIndexes = argv.noIndexes || configFile.noIndexes || false;210 console.log(_.omit(configFile, 'password'));211 /** @type {import('../types').SequelizeAuto} */212 const auto = new SequelizeAuto(configFile.database, configFile.username, configFile.password, configFile);213 await auto.run();214 console.log("Done!");215}()).catch(err => {216 if (err.stack) {217 console.error(err.stack);218 } else if (err.message) {219 console.error(err.message);220 } else {221 console.error(err);222 }223 process.exitCode = 1;...

Full Screen

Full Screen

site.js

Source:site.js Github

copy

Full Screen

1var geometryFile = configFile.data.analysisLayer.geometry;2var datasetFile = configFile.data.analysisLayer.epiDataset.fieldsForAnalysis;3// Draw layers listed in the 'otherLayers' config object.4$.each(configFile.data.otherLayers, function(i, v){5 if (v.display) {6 $.getJSON(v.source, function(data){7 var name = "otherLayer" + i;8 window[name] = new ol.layer.Vector({9 name: name,10 source: new ol.source.Vector({}),11 style: new ol.style.Style({12 fill: new ol.style.Fill({13 color: v.style.fillColor14 }),15 stroke: new ol.style.Stroke({16 color: v.style.strokeColor,17 width: v.style.strokeWidth18 })19 }),20 zIndex : 121 }); 22 var formatOthers = v.format;23 if(configFile.format.indexOf(formatOthers) === -1){24 window[formatOthers] = new ol.format[formatOthers];25 configFile.format.push(formatOthers);26 } 27 window[name].getSource().addFeatures(window[formatOthers].readFeatures(data));28 map.addLayer(window[name]); 29 });30 }31});32function setSource (points, polygons, epi) {33 var dsv = d3.dsv(configFile.data.analysisLayer.epiDataset.delimiter);34 if (configFile.data.analysisLayer.epiDataset.remote) {35 runEpiMap(epi, dsv, points, polygons, true);36 } else {37 runEpiMap(epi, dsv, points, polygons, false)38 }39}40var remainingSources = 141var points, polygons, epi42if (configFile.data.analysisLayer.geometryPoints.display) {43 remainingSources ++44 $.getJSON(configFile.data.analysisLayer.geometryPoints.source, function(data) {45 points = data46 remainingSources--47 if (remainingSources === 0) {48 setSource(points, polygons, epi)49 }50 })51} else {52 points = false53}54if (configFile.data.analysisLayer.geometry.display) {55 remainingSources ++56 $.getJSON(configFile.data.analysisLayer.geometry.source, function(data) {57 polygons = data58 remainingSources--59 if (remainingSources === 0) {60 setSource(points, polygons, epi)61 }62 })63} else {64 polygons = false65}66var dsv = d3.dsv(configFile.data.analysisLayer.epiDataset.delimiter);67var remoteSource = configFile.data.analysisLayer.epiDataset.remote;68if (remoteSource) {69 $.ajax({70 type: "GET",71 url: configFile.data.analysisLayer.epiDataset.source,72 // Set header for ajax request (to be used for password-protected datasets on CKAN).73 beforeSend: function (xhr) {74 xhr.setRequestHeader (configFile.data.analysisLayer.epiDataset.XMLHttpRequestHeader.header, configFile.data.analysisLayer.epiDataset.XMLHttpRequestHeader.value);75 },76 success : function(data3raw) {77 epi = data3raw78 remainingSources--79 if (remainingSources === 0) {80 setSource(points, polygons, epi)81 }82 },83 error: function(){console.log("error : counldn't retrieve data from remote repository");} 84 }); 85} else {86 dsv(configFile.data.analysisLayer.epiDataset.source, function(data3raw){87 epi = data3raw88 remainingSources--89 if (remainingSources === 0) {90 setSource(points, polygons, epi)91 }92 });93}94// // Interlocks requests to data.95// // 1 - Get the 'points' layer for analysis.96// $.getJSON(configFile.data.analysisLayer.geometryPoints.source, function(data) {97// // 2 - Get the 'polygons' layer for analysis.98// $.getJSON(configFile.data.analysisLayer.geometry.source, function(data2) {99// // 3 - Get EPI dataset from .csv file.100// // Define delimiter for .csv file parser.101 102// // console.log(data2)103// // var testObjAdm = [];104// // $.each(data2.objects.cod_hltbnd_lvl2_a_msf.geometries, function(i, v){105// // if (testObjAdm.indexOf(v.properties.pcode) === -1){106// // testObjAdm.push(v.properties.pcode);107// // } else {108// // console.log(v.properties.pcode);109// // }110// // });111 112 113 114 115// var dsv = d3.dsv(configFile.data.analysisLayer.epiDataset.delimiter);116// var remoteSource = configFile.data.analysisLayer.epiDataset.remote;117// if (remoteSource) {118// $.ajax({119// type: "GET",120// url: configFile.data.analysisLayer.epiDataset.source,121// // Set header for ajax request (to be used for password-protected datasets on CKAN).122// beforeSend: function (xhr) {123// xhr.setRequestHeader (configFile.data.analysisLayer.epiDataset.XMLHttpRequestHeader.header, configFile.data.analysisLayer.epiDataset.XMLHttpRequestHeader.value);124// },125// success : function(data3raw) {126// runEpiMap(data3raw, dsv, data, data2, true);127// },128// error: function(){console.log("error : counldn't retrieve data from remote repository");} 129// }); 130// } else {131// dsv(configFile.data.analysisLayer.epiDataset.source, function(data3raw){132// runEpiMap(data3raw, dsv, data, data2, false);133// });134// }135 136// });...

Full Screen

Full Screen

config-file-spec.js

Source:config-file-spec.js Github

copy

Full Screen

1const {it, fit, ffit, beforeEach, afterEach, conditionPromise} = require('./async-spec-helpers')2const fs = require('fs-plus')3const path = require('path')4const temp = require('temp').track()5const dedent = require('dedent')6const ConfigFile = require('../src/config-file')7describe('ConfigFile', () => {8 let filePath, configFile, subscription9 beforeEach(async () => {10 jasmine.useRealClock()11 const tempDir = fs.realpathSync(temp.mkdirSync())12 filePath = path.join(tempDir, 'the-config.cson')13 })14 afterEach(() => {15 subscription.dispose()16 })17 describe('when the file does not exist', () => {18 it('returns an empty object from .get()', async () => {19 configFile = new ConfigFile(filePath)20 subscription = await configFile.watch()21 expect(configFile.get()).toEqual({})22 })23 })24 describe('when the file is empty', () => {25 it('returns an empty object from .get()', async () => {26 writeFileSync(filePath, '')27 configFile = new ConfigFile(filePath)28 subscription = await configFile.watch()29 expect(configFile.get()).toEqual({})30 })31 })32 describe('when the file is updated with valid CSON', () => {33 it('notifies onDidChange observers with the data', async () => {34 configFile = new ConfigFile(filePath)35 subscription = await configFile.watch()36 const event = new Promise(resolve => configFile.onDidChange(resolve))37 writeFileSync(filePath, dedent `38 '*':39 foo: 'bar'40 'javascript':41 foo: 'baz'42 `)43 expect(await event).toEqual({44 '*': {foo: 'bar'},45 'javascript': {foo: 'baz'}46 })47 expect(configFile.get()).toEqual({48 '*': {foo: 'bar'},49 'javascript': {foo: 'baz'}50 })51 })52 })53 describe('when the file is updated with invalid CSON', () => {54 it('notifies onDidError observers', async () => {55 configFile = new ConfigFile(filePath)56 subscription = await configFile.watch()57 const message = new Promise(resolve => configFile.onDidError(resolve))58 writeFileSync(filePath, dedent `59 um what?60 `, 2)61 expect(await message).toContain('Failed to load `the-config.cson`')62 const event = new Promise(resolve => configFile.onDidChange(resolve))63 writeFileSync(filePath, dedent `64 '*':65 foo: 'bar'66 'javascript':67 foo: 'baz'68 `, 4)69 expect(await event).toEqual({70 '*': {foo: 'bar'},71 'javascript': {foo: 'baz'}72 })73 })74 })75 describe('ConfigFile.at()', () => {76 let path0, path177 beforeEach(() => {78 path0 = filePath79 path1 = path.join(fs.realpathSync(temp.mkdirSync()), 'the-config.cson')80 configFile = ConfigFile.at(path0)81 })82 it('returns an existing ConfigFile', () => {83 const cf = ConfigFile.at(path0)84 expect(cf).toEqual(configFile)85 })86 it('creates a new ConfigFile for unrecognized paths', () => {87 const cf = ConfigFile.at(path1)88 expect(cf).not.toEqual(configFile)89 })90 })91})92function writeFileSync (filePath, content, seconds = 2) {93 const utime = (Date.now() / 1000) + seconds94 fs.writeFileSync(filePath, content)95 fs.utimesSync(filePath, utime, utime)...

Full Screen

Full Screen

addGreengrassConfigFile.js

Source:addGreengrassConfigFile.js Github

copy

Full Screen

1'use strict'2var AWS = require('aws-sdk/global');3var IoT = require('aws-sdk/clients/iot');4var S3 = require('aws-sdk/clients/s3');5AWS.config.region = process.env.AWS_REGION;6var iot = new IoT();7var s3 = new S3();8module.exports = {9 addGreengrassConfigFile: async (event, context) => {10 var configFile = {11 "coreThing": {12 "caPath": "root.ca.pem",13 "certPath": "PREFIX.cert.pem",14 "keyPath": "PREFIX.private.key",15 "thingArn": "THING_ARN",16 "iotHost": "ENDPOINT",17 "ggHost": "greengrass-ats.iot.REGION.amazonaws.com",18 "keepAlive": 60019 },20 "runtime": {21 "cgroup": {22 "useSystemd": "yes"23 }24 },25 "managedRespawn": false,26 "crypto": {27 "principals": {28 "SecretsManager": {29 "privateKeyPath": "file:///greengrass/certs/PREFIX.private.key"30 },31 "IoTCertificate": {32 "privateKeyPath": "file:///greengrass/certs/PREFIX.private.key",33 "certificatePath": "file:///greengrass/certs/PREFIX.cert.pem"34 }35 },36 "caPath": "file:///greengrass/certs/root.ca.pem"37 }38 }39 var params = {40 endpointType: "iot:Data-ATS"41 }42 var data = await iot.describeEndpoint(params).promise();43 var certificateId = event.certificateId;44 var thingArn = event.thingArn;45 var iotHost = data.endpointAddress;46 // var prefix = certificateId.substring(0, 10)47 var prefix = 'core';48 configFile.coreThing.thingArn = thingArn;49 configFile.coreThing.iotHost = iotHost;50 configFile.coreThing.ggHost = configFile.coreThing.ggHost.replace("REGION", process.env.AWS_REGION);51 configFile.coreThing.certPath = configFile.coreThing.certPath.replace("PREFIX", prefix);52 configFile.coreThing.keyPath = configFile.coreThing.keyPath.replace("PREFIX", prefix);53 configFile.crypto.principals.SecretsManager.privateKeyPath = configFile.crypto.principals.SecretsManager.privateKeyPath.replace("PREFIX", prefix);54 configFile.crypto.principals.IoTCertificate.privateKeyPath = configFile.crypto.principals.IoTCertificate.privateKeyPath.replace("PREFIX", prefix);55 configFile.crypto.principals.IoTCertificate.certificatePath = configFile.crypto.principals.IoTCertificate.certificatePath.replace("PREFIX", prefix);56 params = {57 Bucket: process.env.S3_BUCKET,58 Key: certificateId59 };60 data = await s3.getObject(params).promise();61 var json = JSON.parse(data.Body);62 json.configFile = configFile;63 params = {64 Bucket: process.env.S3_BUCKET,65 Key: certificateId,66 Body: JSON.stringify(json, null, 4)67 };68 data = await s3.putObject(params).promise();69 return data;70 }...

Full Screen

Full Screen

getConfig.js

Source:getConfig.js Github

copy

Full Screen

1module.exports = async function getConfiguration (context) {2 if (!context) return3 const configFile = await context.config('starrycake.yml')4 if (!configFile) return configFile5 configFile.configMaster = (configFile && configFile.starrycake) ? configFile.starrycake : {};6 configFile.configAssigner = (configFile && configFile.assigner) ? configFile.assigner : {};7 configFile.configDeleteBranch = (configFile && configFile.deletebranch) ? configFile.deletebranch : {};8 configFile.configReminder = (configFile && configFile.reminder) ? configFile.reminder : {};9 configFile.configRespond = (configFile && configFile.responder) ? configFile.responder : {};10 configFile.configStale = (configFile && configFile.stale) ? configFile.stale : {};11 configFile.configTodo = (configFile && configFile.todo) ? configFile.todo : {};12 configFile.configTriage = (configFile && configFile.triage) ? configFile.triage : {};13 configFile.configUnfurl = (configFile && configFile.unfurl) ? configFile.unfurl : {};14 return configFile...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs-extra');2const path = require('path');3const cypress = require('cypress');4const { merge } = require('mochawesome-merge');5const { generate } = require('mochawesome-report-generator');6const { mergeReports } = require('mochawesome-merge');7const { merge } = require('mochawesome-merge');8const { generate } = require('mochawesome-report-generator');9const { mergeReports } = require('mochawesome-merge');10const { merge } = require('mochawesome-merge');11const { generate } = require('mochawesome-report-generator');12const { mergeReports } = require('mochawesome-merge');13const { merge } = require('mochawesome-merge');14const { generate } = require('mochawesome-report-generator');15const { mergeReports } = require('mochawesome-merge');16const { merge } = require('mochawesome-merge');17const { generate } = require('mochawesome-report-generator');18const { mergeReports } = require('mochawesome-merge');19const { merge } = require('mochawesome-merge');20const { generate } = require('mochawesome-report-generator');21const { mergeReports } = require('mochawesome-merge');22const { merge } = require('mochawesome-merge');23const { generate } = require('mochawesome-report-generator');24const { mergeReports } = require('mochawesome-merge');25const { merge } = require('mochawesome-merge');26const { generate } = require('mochawesome-report-generator');27const { mergeReports } = require('mochawesome-merge');28const { merge } = require('mochawesome-merge');29const { generate } = require('mochawesome-report-generator');30const { mergeReports } = require('mochawesome-merge');31const { merge } = require('mochawesome-merge');32const { generate } = require('mochawesome-report-generator');33const { mergeReports } = require('mochawesome-merge');34const { merge } = require('mochawesome-merge');35const { generate } = require('mochawesome-report-generator');36const { mergeReports } = require('mochawesome-merge');37const { merge } = require('mochawesome-merge');38const { generate } = require('mochawesome-report-generator');39const { mergeReports } = require('m

Full Screen

Using AI Code Generation

copy

Full Screen

1const config = require('../cypress.json');2Cypress.config('baseUrl', config.baseUrl);3Cypress.config('defaultCommandTimeout', config.defaultCommandTimeout);4Cypress.config('requestTimeout', config.requestTimeout);5Cypress.config('responseTimeout', config.responseTimeout);6Cypress.config('viewportHeight', config.viewportHeight);7Cypress.config('viewportWidth', config.viewportWidth);8{9}10describe('Test', () => {11 it('Test', () => {12 cy.visit('/');13 });14});15Platform: win32 (10.0.18363)

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 })4})5{6}7{8 "env": {9 }10}11{12 "env": {13 },14}15{16 "env": {17 },18}19{20 "env": {21 },22}23{24 "env": {25 },26}27{28 "env": {29 },30}31{32 "env": {33 },

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = (on, config) => {2 on('file:preprocessor', cucumber())3 require('cypress-log-to-output').install(on, (type, event) => {4 })5}6module.exports = (on, config) => {7 on('file:preprocessor', cucumber())8 require('cypress-log-to-output').install(on, (type, event) => {9 })10}11const cucumber = require('cypress-cucumber-preprocessor').default12module.exports = (on, config) => {13 on('file:preprocessor', cucumber())14 require('cypress-log-to-output').install(on, (type, event) => {15 })16}17const cucumber = require('cypress-cucumber-preprocessor').default18module.exports = (on, config) => {19 on('file:preprocessor', cucumber())20 require('cypress-log-to-output').install(on, (type, event) => {21 })22}23import 'cypress-log-to-output'24import 'cypress-log-to-output'25import 'cypress-log-to-output'26import 'cypress-log-to-output'

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful