How to use version method in Puppeteer

Best JavaScript code snippet using puppeteer

VersionController.js

Source:VersionController.js Github

copy

Full Screen

1/**2 * VersionController3 *4 * @description :: Server-side logic for handling version requests5 * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers6 */7var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');8var url = require('url');9var Promise = require('bluebird');10var semver = require('semver');11var compareVersions = require('compare-versions');12const availabilityFilter = () => ({ '<=': (new Date()).toISOString() });13module.exports = {14 /**15 * Set availability date of specified version16 *17 * (PUT /version/availability/:version/:timestamp)18 */19 availability: (req, res) => {20 const { version, timestamp } = req.params;21 if (!version) return res.badRequest('Requires `version` parameter');22 if (!timestamp) return res.badRequest('Requires `timestamp` parameter');23 const availability = new Date(parseInt(timestamp, 10));24 if (isNaN(availability) || availability.getTime().toString() !== timestamp) {25 return res.badRequest('Parameter `timestamp` must be a valid unix timestamp in milliseconds');26 }27 Version28 .findOne(version)29 .then(foundVersion => {30 if (!foundVersion) return res.notFound('The specified `version` does not exist');31 if (availability < new Date(foundVersion.createdAt)) {32 return res.badRequest(33 'Parameter `timestamp` must be greater than or equal to the version creation date'34 );35 }36 return Version37 .update(version, { availability })38 .then(([updatedVersion]) => {39 Version.publishUpdate(version, updatedVersion, req);40 res.send(updatedVersion);41 });42 })43 .catch(res.negotiate);44 },45 /**46 * Redirect the update request to the appropriate endpoint47 * (GET /update)48 */49 redirect: function(req, res) {50 var platform = req.param('platform');51 var version = req.param('version');52 if (!version) {53 return res.badRequest('Requires "version" parameter');54 }55 if (!platform) {56 return res.badRequest('Requires "platform" parameter');57 }58 return res.redirect('/update/' + platform + '/' + version);59 },60 /**61 * Sorts versions and returns pages sorted by by sermver62 *63 * ( GET /versions/sorted )64 */65 list: function (req, res) {66 Version67 .find()68 .then(versions => {69 var count = versions.length;70 var page = req.param('page') || req.query.page || 0;71 var start = page * sails.config.views.pageSize;72 var end = start + sails.config.views.pageSize;73 var items = versions74 .sort(function (a, b) {75 return -compareVersions(a.name, b.name);76 })77 .slice(start, end);78 const response = {79 total: count,80 offset: start,81 page: page,82 items: items83 }84 return Promise.all([85 // load channels86 new Promise(function (resolve, reject) {87 Promise.all(items.map(function (version) {88 return Channel.findOne({89 name: version.channel90 })91 }))92 .then(resolve)93 .catch(reject)94 }),95 // load assets96 new Promise(function (resolve, reject) {97 Promise.all(items.map(function (version) {98 return Asset.find({99 version: version.id100 })101 }))102 .then(resolve)103 .catch(reject)104 }),105 // load flavors106 new Promise((resolve, reject) => Promise107 .map(items, version => Flavor.findOne(version.flavor))108 .then(resolve)109 .catch(reject)110 )111 ])112 .then(function (results) {113 response.items = response.items.map(function (item, index) {114 return {115 id: item.id,116 channel: results[0][index],117 assets: results[1][index].map(function (asset) {118 return {119 id: asset.id,120 name: asset.name,121 platform: asset.platform,122 filetype: asset.filetype,123 hash: asset.hash,124 size: asset.size,125 download_count: asset.download_count,126 fd: asset.fd,127 createdAt: asset.createdAt,128 updatedAt: asset.updatedAt129 }130 }),131 flavor: results[2][index],132 name: item.name,133 notes: item.notes,134 createdAt: item.createdAt,135 updatedAt: item.updatedAt,136 availability: item.availability137 }138 })139 return response140 })141 })142 .then(response => {143 res.send(response);144 })145 .catch(res.negotiate);146 },147 /**148 * Serves auto-updates: Status and Squirrel.Mac149 *150 * Assumes stable channel & default flavor unless specified151 *152 * (GET /update/:platform/:version/:channel)153 * (GET /update/flavor/:flavor/:platform/:version/:channel?)154 */155 general: function(req, res) {156 var platform = req.param('platform');157 var version = req.param('version');158 var channel = req.param('channel') || 'stable';159 const flavor = req.params.flavor || 'default';160 if (!version) {161 return res.badRequest('Requires `version` parameter');162 }163 if (!platform) {164 return res.badRequest('Requires `platform` parameter');165 }166 var platforms = PlatformService.detect(platform, true);167 sails.log.debug('Update Search Query', {168 platform: platforms,169 version: version,170 channel: channel,171 flavor172 });173 // Get specified version object, it's time will be used for the general174 // cutoff.175 Version176 .findOne({177 name: version,178 flavor179 })180 .then(function(currentVersion) {181 var applicableChannels, createdAtFilter;182 applicableChannels = ChannelService.getApplicableChannels(channel);183 sails.log.debug('Applicable Channels', applicableChannels);184 if (currentVersion) {185 createdAtFilter = {186 '>': currentVersion.createdAt187 };188 } else {189 sails.log.debug('The specified `version` does not exist');190 }191 sails.log.debug('Time Filter', createdAtFilter);192 return Version193 .find(UtilityService.getTruthyObject({194 channel: applicableChannels,195 createdAt: createdAtFilter,196 availability: availabilityFilter(),197 flavor198 }))199 .populate('assets', {200 platform: platforms201 })202 .then(function(newerVersions) {203 // Sort versions which were added after the current one by semver in204 // descending order.205 newerVersions.sort(UtilityService.compareVersion);206 var latestVersion;207 sails.log.debug('Newer Versions', newerVersions);208 var releaseNotes = _.reduce(209 newerVersions,210 function(prevNotes, newVersion) {211 newVersion.assets = _.filter(newVersion.assets, function(asset) {212 return asset.filetype === '.zip';213 });214 // If one of the assets for this verison apply to our desired215 // platform then we will skip this version216 if (!newVersion.assets.length) {217 return prevNotes;218 }219 if (!latestVersion && semver.lt(version, newVersion.name)) {220 latestVersion = newVersion;221 }222 // Skip if no notes available for this version223 if (!newVersion.notes || !newVersion.notes.length) {224 return prevNotes;225 }226 // If not the first changenote, prefix with new line227 var newChangeNote = !prevNotes.length ? '' : '\n';228 newChangeNote += '## ' + newVersion.name + '\n' + newVersion.notes;229 return prevNotes + newChangeNote;230 },231 '');232 var currentVersionName = _.get(currentVersion, 'name');233 sails.log.debug('Version candidate', latestVersion);234 sails.log.debug('Current version', currentVersionName);235 if (!latestVersion || latestVersion.name === currentVersionName) {236 sails.log.debug('Version candidate denied');237 return res.status(204).send('No updates.');238 }239 sails.log.debug('Version candidate accepted');240 return res.ok({241 url: url.resolve(242 sails.config.appUrl,243 `/download/flavor/${flavor}/${latestVersion.name}/` +244 latestVersion.assets[0].platform + '?filetype=zip'245 ),246 name: latestVersion.name,247 notes: releaseNotes,248 pub_date: latestVersion.availability.toISOString()249 });250 });251 })252 .catch(res.negotiate);253 },254 /**255 * Serves auto-updates: Squirrel.Windows: serve RELEASES from latest version256 * Currently, it will only serve a full.nupkg of the latest release with a257 * normalized filename (for pre-release)258 *259 * (GET /update/:platform/:version/:channel/RELEASES)260 * (GET /update/flavor/:flavor/:platform/:version/:channel/RELEASES)261 */262 windows: function(req, res) {263 var platform = req.param('platform');264 var version = req.param('version');265 var channel = req.param('channel') || 'stable';266 const flavor = req.params.flavor || 'default';267 if (!version) {268 return res.badRequest('Requires `version` parameter');269 }270 if (!platform) {271 return res.badRequest('Requires `platform` parameter');272 }273 var platforms = PlatformService.detect(platform, true);274 sails.log.debug('Windows Update Search Query', {275 platform: platforms,276 version: version,277 channel: channel,278 flavor279 });280 // Get specified version object, it's time will be used for the general281 // cutoff.282 Version283 .findOne({284 name: version,285 flavor286 })287 .then(function(currentVersion) {288 var applicableChannels, createdAtFilter;289 applicableChannels = ChannelService.getApplicableChannels(channel);290 sails.log.debug('Applicable Channels', applicableChannels);291 if (currentVersion) {292 createdAtFilter = {293 '>=': currentVersion.createdAt294 };295 } else {296 sails.log.debug('The specified `version` does not exist');297 }298 sails.log.debug('Time Filter', createdAtFilter);299 return Version300 .find(UtilityService.getTruthyObject({301 channel: applicableChannels,302 createdAt: createdAtFilter,303 availability: availabilityFilter(),304 flavor305 }))306 .populate('assets', {307 platform: platforms308 })309 .then(function(newerVersions) {310 // Sort versions which were added after the current one by semver in311 // descending order.312 newerVersions.sort(UtilityService.compareVersion);313 var latestVersion = _.find(314 newerVersions,315 function(newVersion) {316 _.remove(newVersion.assets, function(o) {317 return o.filetype !== '.nupkg' || !o.hash;318 });319 // Make sure the last version is a version with full asset320 // so RELEASES contains at least one full asset (which is mandatory for Squirrel.Windows)321 let v = _.filter(322 newVersion.assets,323 function(o) {324 return _.includes(o.name.toLowerCase(), '-full');325 }326 );327 return v.length && semver.lte(328 version, newVersion.name329 );330 });331 if (!latestVersion) {332 sails.log.debug('Version not found');333 return res.status(500).send('Version not found');334 }335 // Add Delta assets from other versions336 var deltaAssets = _.reduce(337 newerVersions,338 function(assets, newVersion) {339 return assets.concat(340 _.filter(341 newVersion.assets,342 function(asset) {343 return asset.filetype === '.nupkg'344 && _.includes(asset.name.toLowerCase(), '-delta')345 && semver.lte(version, asset.version)346 && semver.gt(latestVersion.name, asset.version);347 }));348 }, []);349 Array.prototype.unshift.apply(latestVersion.assets, deltaAssets);350 latestVersion.assets.sort(function(a1, a2) {351 return semver.compare(a1.version, a2.version);352 });353 sails.log.debug('Latest Windows Version', latestVersion);354 // Change asset name to use full download link355 const assets = _.map(latestVersion.assets, function(asset) {356 asset.name = url.resolve(357 sails.config.appUrl,358 `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +359 asset.name360 );361 return asset;362 });363 var output = WindowsReleaseService.generate(assets);364 res.header('Content-Length', output.length);365 res.attachment('RELEASES');366 return res.send(output);367 });368 })369 .catch(res.negotiate);370 },371 /**372 * Get electron-updater win yml for a specific channel373 * (GET /update/:platform/latest.yml)374 * (GET /update/:platform/:channel.yml)375 * (GET /update/:platform/:channel/latest.yml)376 * (GET /update/flavor/:flavor/:platform/latest.yml)377 * (GET /update/flavor/:flavor/:platform/:channel.yml)378 * (GET /update/flavor/:flavor/:platform/:channel/latest.yml)379 */380 electronUpdaterWin: function(req, res) {381 var platform = req.param('platform');382 var channel = req.param('channel') || 'stable';383 const flavor = req.params.flavor || 'default';384 if (!platform) {385 return res.badRequest('Requires `platform` parameter');386 }387 var platforms = PlatformService.detect(platform, true);388 sails.log.debug('NSIS electron-updater Search Query', {389 platform: platforms,390 channel: channel,391 flavor392 });393 var applicableChannels = ChannelService.getApplicableChannels(channel);394 sails.log.debug('Applicable Channels', applicableChannels);395 // Get latest version that has a windows asset396 Version397 .find({398 channel: applicableChannels,399 availability: availabilityFilter(),400 flavor401 })402 .populate('assets')403 .then(function(versions) {404 // TODO: Implement method to get latest version with available asset405 var sortedVersions = versions.sort(UtilityService.compareVersion);406 var latestVersion = null;407 var asset = null;408 for (var i = 0; i < sortedVersions.length; i++) {409 var currentVersion = sortedVersions[i];410 if (currentVersion.assets) {411 for (var j = 0; j < currentVersion.assets.length; j++) {412 var currentAsset = currentVersion.assets[j];413 if (currentAsset.filetype === '.exe' && _.includes(platforms, currentAsset.platform)) {414 latestVersion = currentVersion;415 asset = currentAsset;416 break;417 }418 }419 if (latestVersion) {420 break;421 }422 }423 }424 if (latestVersion) {425 var downloadPath = url.resolve(426 //sails.config.appUrl,427 "",428 `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +429 asset.name430 );431 const sha512 = asset.hash ? asset.hash : null;432 var latestYml = "version: " + latestVersion.name433 + "\nfiles:"434 + "\n - url: " + downloadPath435 + "\n sha512: " + sha512436 + "\n size: " + asset.size437 + "\nreleaseDate: " + latestVersion.updatedAt438 + "\npath: " + downloadPath439 + "\nsha512: " + sha512440 + "\nsize: " + asset.size;441 res.ok(latestYml);442 } else {443 res.notFound();444 }445 });446 },447 /**448 * Get electron-updater mac yml for a specific channel449 * (GET /update/:platform/latest-mac.yml)450 * (GET /update/:platform/:channel-mac.yml)451 * (GET /update/:platform/:channel/latest-mac.yml)452 * (GET /update/flavor/:flavor/:platform/latest-mac.yml)453 * (GET /update/flavor/:flavor/:platform/:channel-mac.yml)454 * (GET /update/flavor/:flavor/:platform/:channel/latest-mac.yml)455 */456 electronUpdaterMac: function(req, res) {457 var platform = req.param('platform');458 var channel = req.param('channel') || 'stable';459 const flavor = req.params.flavor || 'default';460 if (!platform) {461 return res.badRequest('Requires `platform` parameter');462 }463 var platforms = PlatformService.detect(platform, true);464 sails.log.debug('Mac electron-updater Search Query', {465 platform: platforms,466 channel: channel,467 flavor468 });469 var applicableChannels = ChannelService.getApplicableChannels(channel);470 sails.log.debug('Applicable Channels', applicableChannels);471 // Get latest version that has a mac asset472 Version473 .find({474 channel: applicableChannels,475 availability: availabilityFilter(),476 flavor477 })478 .populate('assets')479 .then(function(versions) {480 // TODO: Implement method to get latest version with available asset481 var sortedVersions = versions.sort(UtilityService.compareVersion);482 var latestVersion = null;483 var asset = null;484 for (var i = 0; i < sortedVersions.length; i++) {485 var currentVersion = sortedVersions[i];486 if (currentVersion.assets) {487 for (var j = 0; j < currentVersion.assets.length; j++) {488 var currentAsset = currentVersion.assets[j];489 if (currentAsset.filetype === '.zip' && _.includes(platforms, currentAsset.platform)) {490 latestVersion = currentVersion;491 asset = currentAsset;492 break;493 }494 }495 if (latestVersion) {496 break;497 }498 }499 }500 if (latestVersion) {501 var downloadPath = url.resolve(502 //sails.config.appUrl,503 "",504 `/download/flavor/${flavor}/${latestVersion.name}/${asset.platform}/` +505 asset.name506 );507 const sha512 = asset.hash ? asset.hash : null;508 var latestYml = "version: " + latestVersion.name509 + "\nfiles:"510 + "\n - url: " + downloadPath511 + "\n sha512: " + sha512512 + "\n size: " + asset.size513 + "\nreleaseDate: " + latestVersion.updatedAt514 + "\npath: " + downloadPath515 + "\nsha512: " + sha512516 + "\nsize: " + asset.size;517 res.ok(latestYml);518 } else {519 res.notFound();520 }521 });522 },523 /**524 * Get release notes for a specific version525 * (GET /notes/:version/:flavor?)526 */527 releaseNotes: function(req, res) {528 var version = req.params.version;529 const flavor = req.params.flavor || 'default';530 Version531 .findOne({532 name: version,533 availability: availabilityFilter(),534 flavor535 })536 .then(function(currentVersion) {537 if (!currentVersion) {538 return res.notFound('The specified version does not exist');539 }540 return res.format({541 'application/json': function() {542 res.send({543 'notes': currentVersion.notes,544 'pub_date': currentVersion.availability.toISOString()545 });546 },547 'default': function() {548 res.send(currentVersion.notes);549 }550 });551 })552 .catch(res.negotiate);553 },554 /**555 * Overloaded blueprint function556 * Changes:557 * - Delete all associated assets & their files558 * @param {[type]} req [description]559 * @param {[type]} res [description]560 * @return {[type]} [description]561 */562 destroy: function(req, res) {563 var pk = actionUtil.requirePk(req);564 var query = Version.findOne(pk);565 query.populate('assets');566 query.exec(function foundRecord(err, record) {567 if (err) return res.serverError(err);568 if (!record) return res.notFound(569 'No record found with the specified `name`.'570 );571 var deletePromises = _.map(record.assets, function(asset) {572 return Promise.join(573 AssetService.destroy(asset, req),574 AssetService.deleteFile(asset),575 function() {576 sails.log.info('Destroyed asset: ', asset);577 });578 });579 Promise.all(deletePromises)580 .then(function allDeleted() {581 return Version.destroy(pk)582 .then(function destroyedRecord() {583 if (sails.hooks.pubsub) {584 Version.publishDestroy(585 pk, !req._sails.config.blueprints.mirror && req, {586 previous: record587 }588 );589 if (req.isSocket) {590 Version.unsubscribe(req, record);591 Version.retire(record);592 }593 }594 sails.log.info('Destroyed version: ', record);595 return res.ok(record);596 });597 })598 .error(res.negotiate);599 });600 }...

Full Screen

Full Screen

check_reqs.js

Source:check_reqs.js Github

copy

Full Screen

1/*2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17/*jshint node:true*/18var Q = require('q');19var os = require('os');20var path = require('path');21var shell = require('shelljs');22var spawn = require('cordova-common').superspawn.spawn;23var CordovaError = require('cordova-common').CordovaError;24var ConfigParser, MSBuildTools, Version;25try {26 ConfigParser = require('../../template/cordova/lib/ConfigParser');27 MSBuildTools = require('../../template/cordova/lib/MSBuildTools');28 Version = require('../../template/cordova/lib/Version');29} catch (ex) {30 // If previous import fails, we're probably running this script31 // from installed platform and the module location is different.32 ConfigParser = require('./ConfigParser');33 MSBuildTools = require('./MSBuildTools');34 Version = require('./Version');35}36// The constant for VS2013 Upd2 PackageVersion. See MSDN for37// reference: https://msdn.microsoft.com/en-us/library/bb164659(v=vs.120).aspx38var VS2013_UPDATE2_RC = new Version(12, 0, 30324);39var REQUIRED_VERSIONS = {40 '8.0': {41 os: '6.2',42 msbuild: '11.0',43 visualstudio: '11.0',44 windowssdk: '8.0'45 },46 '8.1': {47 os: '6.3',48 msbuild: '12.0',49 visualstudio: '12.0',50 windowssdk: '8.1',51 phonesdk: '8.1'52 },53 '10.0': {54 // Note that Windows 10 target is also supported on Windows 7, so this should look55 // like '6.1 || >=6.3', but due to Version module restricted functionality we handle56 // this case separately in checkOS function below.57 os: '6.3',58 msbuild: '14.0',59 visualstudio: '14.0',60 windowssdk: '10.0',61 phonesdk: '10.0'62 }63};64function getConfig() {65 try {66 return new ConfigParser(path.join(__dirname, '../../config.xml'));67 } catch (e) {68 throw new CordovaError('Can\'t check requirements for Windows platform.' +69 'The config.xml file is either missing or malformed.');70 }71}72function getMinimalRequiredVersionFor (requirement) {73 var config = getConfig();74 var windowsTargetVersion = config.getWindowsTargetVersion();75 var windowsPhoneTargetVersion = config.getWindowsPhoneTargetVersion();76 var windowsReqVersion = Version.tryParse(REQUIRED_VERSIONS[windowsTargetVersion][requirement]);77 var phoneReqVersion = Version.tryParse(REQUIRED_VERSIONS[windowsPhoneTargetVersion][requirement]);78 // If we're searching for Windows SDK, we're not79 // interested in Phone's version and and vice versa.80 if (requirement === 'windowssdk') return windowsReqVersion;81 if (requirement === 'phonesdk') return phoneReqVersion;82 // If both windowsReqVersion and phoneReqVersion is valid Versions, choose the max one83 if (windowsReqVersion && phoneReqVersion) {84 return windowsReqVersion.gt(phoneReqVersion) ?85 windowsReqVersion :86 phoneReqVersion;87 }88 // Otherwise return that one which is defined and valid89 return windowsReqVersion || phoneReqVersion;90}91function getHighestAppropriateVersion (versions, requiredVersion) {92 return versions.map(function (version) {93 return Version.tryParse(version);94 })95 .sort(Version.comparer)96 .filter(function (toolVersion) {97 return toolVersion.gte(requiredVersion);98 })[0];99}100/**101 * Return Version object for current Windows version. User 'ver' binary or102 * os.release() in case of errors.103 *104 * @return {Version} Version information for current OS.105 */106function getWindowsVersion() {107 return spawn('ver').then(function (output) {108 var match = /\[Version (.*)\]\s*$/.exec(output);109 return Version.fromString(match[1]);110 }).fail(function () {111 return Version.fromString(os.release());112 });113}114/**115 * Lists all Visual Studio versions insalled. For VS 2013 if it present, alao116 * checks if Update 2 is installed.117 *118 * @return {String[]} List of installed Visual Studio versions.119 */120function getInstalledVSVersions() {121 // Query all keys with Install value equal to 1, then filter out122 // those, which are not related to VS itself123 return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\DevDiv\\vs\\Servicing', '/s', '/v', 'Install', '/f', '1', '/d', '/e', '/reg:32'])124 .fail(function () { return ''; })125 .then(function (output) {126 return output.split('\n')127 .reduce(function (installedVersions, line) {128 var match = /(\d+\.\d+)\\(ultimate|professional|premium|community)/.exec(line);129 if (match && match[1] && installedVersions.indexOf(match[1]) === -1)130 installedVersions.push(match[1]);131 return installedVersions;132 }, []);133 })134 .then(function (installedVersions) {135 // If there is no VS2013 installed, the we have nothing to do136 if (installedVersions.indexOf('12.0') === -1) return installedVersions;137 // special case for VS 2013. We need to check if VS2013 update 2 is installed138 return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Updates\\Microsoft Visual Studio 2013\\vsupdate_KB2829760','/v','PackageVersion','/reg:32'])139 .then(function (output) {140 var updateVer = Version.fromString(/PackageVersion\s+REG_SZ\s+(.*)/i.exec(output)[1]);141 // if update version is lover than Update2, reject the promise142 if (VS2013_UPDATE2_RC.gte(updateVer)) return Q.reject();143 return installedVersions;144 })145 .fail(function () {146 // if we got any errors on previous steps, we're assuming that147 // required VS update is not installed.148 installedVersions.splice(installedVersions.indexOf('12.0'));149 return installedVersions;150 });151 });152}153/**154 * Gets list of installed Windows SDKs155 *156 * @return {Version[]} List of installed SDKs' versions157 */158function getInstalledWindowsSdks () {159 var installedSdks = [];160 return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows','/s','/v','InstallationFolder','/reg:32'])161 .fail(function () { return ''; })162 .then(function (output) {163 var re = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim;164 var match;165 while ((match = re.exec(output))){166 var sdkPath = match[2];167 // Verify that SDKs is really installed by checking SDKManifest file at SDK root168 if (shell.test('-e', path.join(sdkPath, 'SDKManifest.xml'))) {169 installedSdks.push(Version.tryParse(match[1]));170 }171 }172 })173 .thenResolve(installedSdks);174}175/**176 * Gets list of installed Windows Phone SDKs. Separately searches for 8.1 Phone177 * SDK and Windows 10 SDK, because the latter is needed for both Windows and178 * Windows Phone applications.179 *180 * @return {Version[]} List of installed Phone SDKs' versions.181 */182function getInstalledPhoneSdks () {183 var installedSdks = [];184 return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows Phone\\v8.1','/v','InstallationFolder','/reg:32'])185 .fail(function () { return ''; })186 .then(function (output) {187 var match = /\\Microsoft SDKs\\Windows Phone\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output);188 if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) {189 installedSdks.push(Version.tryParse(match[1]));190 }191 })192 .then(function () {193 return spawn('reg', ['query','HKLM\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v10.0','/v','InstallationFolder','/reg:32']);194 })195 .fail(function () { return ''; })196 .then(function (output) {197 var match = /\\Microsoft SDKs\\Windows\\v(\d+\.\d+)\s*InstallationFolder\s+REG_SZ\s+(.*)/gim.exec(output);198 if (match && shell.test('-e', path.join(match[2], 'SDKManifest.xml'))) {199 installedSdks.push(Version.tryParse(match[1]));200 }201 })202 .thenResolve(installedSdks);203}204/**205 * Shortens version string or Version object by leaving only first two segments206 * (major and minor).207 * @param {String|Version} version The version identifier. Either Version208 * object or string that looks like "12.5.6"209 * @return {String} Shortened version, or undefined if provided210 * parameter is not a valid version211 */212function shortenVersion (version) {213 return /^(\d+(?:\.\d+)?)/.exec(version.toString())[1];214}215function mapWindowsVersionToName(version) {216 var map = {217 '6.2': 'Windows 8',218 '6.3': 'Windows 8.1',219 '10.0': 'Windows 10'220 };221 var majorMinor = shortenVersion(version);222 return map[majorMinor];223}224function mapVSVersionToName(version) {225 var map = {226 '11.0': '2012 Express for Windows',227 '12.0': '2013 Express for Windows Update2',228 '14.0': '2015 Community'229 };230 var majorMinor = shortenVersion(version);231 return map[majorMinor];232}233/**234 * Check if current OS is supports building windows platform235 * @return {Promise} Promise either fullfilled or rejected with error message.236 */237var checkOS = function () {238 if (process.platform !== 'win32') {239 // Build Universal windows apps available for windows platform only, so we reject on others platforms240 return Q.reject('Cordova tooling for Windows requires Windows OS to build project');241 }242 return getWindowsVersion().then(function (actualVersion) {243 var requiredOsVersion = getMinimalRequiredVersionFor('os');244 if (actualVersion.gte(requiredOsVersion) ||245 // Special case for Windows 10/Phone 10 targets which can be built on Windows 7 (version 6.1)246 actualVersion.major === 6 && actualVersion.minor === 1 && getConfig().getWindowsTargetVersion() === '10.0') {247 return mapWindowsVersionToName(actualVersion);248 }249 return Q.reject('Current Windows version doesn\'t support building this project. ' +250 'Consider upgrading your OS to ' + mapWindowsVersionToName(requiredOsVersion));251 });252};253/**254 * Checks if MSBuild tools is available.255 * @return {Promise} Promise either fullfilled with MSBuild version256 * or rejected with error message.257 */258var checkMSBuild = function () {259 return MSBuildTools.findAllAvailableVersions()260 .then(function (msbuildToolsVersions) {261 var msbuildRequiredVersion = getMinimalRequiredVersionFor('msbuild');262 msbuildToolsVersions = msbuildToolsVersions.map(function (msbuildToolsVersion) {263 return msbuildToolsVersion.version;264 });265 var appropriateVersion = getHighestAppropriateVersion(msbuildToolsVersions, msbuildRequiredVersion);266 return appropriateVersion ?267 shortenVersion(appropriateVersion) :268 Q.reject('MSBuild tools v.' + shortenVersion(msbuildRequiredVersion) + ' not found. ' +269 'Please install Visual Studio ' + mapVSVersionToName(getMinimalRequiredVersionFor('visualstudio')) +270 ' from https://www.visualstudio.com/downloads/download-visual-studio-vs');271 });272};273var checkVS = function () {274 var vsRequiredVersion = getMinimalRequiredVersionFor('visualstudio');275 return getInstalledVSVersions()276 .then(function (installedVersions) {277 var appropriateVersion = getHighestAppropriateVersion(installedVersions, vsRequiredVersion);278 return appropriateVersion ?279 shortenVersion(appropriateVersion) :280 Q.reject('Required version of Visual Studio not found. Please install Visual Studio ' +281 mapVSVersionToName(vsRequiredVersion) +282 ' from https://www.visualstudio.com/downloads/download-visual-studio-vs');283 });284};285var checkWinSdk = function () {286 return getInstalledWindowsSdks()287 .then(function (installedSdks) {288 var requiredVersion = getMinimalRequiredVersionFor('windowssdk');289 var hasSdkInstalled = installedSdks.some(function (installedSdk) {290 return installedSdk.eq(requiredVersion);291 });292 if (!hasSdkInstalled) {293 return Q.reject('Windows SDK not found. Please ensure that you have installed ' +294 'Windows ' + shortenVersion(requiredVersion) + ' SDK along with Visual Studio or install ' +295 'Windows ' + shortenVersion(requiredVersion) + ' SDK separately from ' +296 'https://dev.windows.com/en-us/downloads');297 }298 return shortenVersion(requiredVersion);299 });300};301var checkPhoneSdk = function () {302 var requiredVersion = getMinimalRequiredVersionFor('phonesdk');303 return getInstalledPhoneSdks()304 .then(function (installedSdks) {305 var requiredVersion = getMinimalRequiredVersionFor('phonesdk');306 var hasSdkInstalled = installedSdks.some(function (installedSdk) {307 return installedSdk.eq(requiredVersion);308 });309 return hasSdkInstalled ?310 shortenVersion(requiredVersion) :311 Q.reject();312 })313 .fail(function () {314 return Q.reject('Windows Phone SDK not found. Please ensure that you have installed ' +315 'Windows Phone ' + shortenVersion(requiredVersion) + ' SDK along with Visual Studio or install ' +316 'Windows Phone ' + shortenVersion(requiredVersion) + ' SDK separately from ' +317 'https://dev.windows.com/develop/download-phone-sdk');318 });319};320module.exports.run = function () {321 return checkOS().then(function () {322 return MSBuildTools.findAvailableVersion();323 });324};325/**326 * Object that represents one of requirements for current platform.327 * @param {String} id The unique identifier for this requirements.328 * @param {String} name The name of requirements. Human-readable field.329 * @param {Boolean} isFatal Marks the requirement as fatal. If such requirement will fail330 * next requirements' checks will be skipped.331 */332var Requirement = function (id, name, isFatal) {333 this.id = id;334 this.name = name;335 this.installed = false;336 this.metadata = {};337 this.isFatal = isFatal || false;338};339var requirements = [340 new Requirement('os', 'Windows OS', true),341 new Requirement('msbuild', 'MSBuild Tools'),342 new Requirement('visualstudio', 'Visual Studio'),343 new Requirement('windowssdk', 'Windows SDK'),344 new Requirement('phonesdk', 'Windows Phone SDK')345];346// Define list of checks needs to be performed347var checkFns = [checkOS, checkMSBuild, checkVS, checkWinSdk, checkPhoneSdk];348/**349 * Methods that runs all checks one by one and returns a result of checks350 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method.351 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.352 */353module.exports.check_all = function() {354 var result = [];355 var fatalIsHit = false;356 // Then execute requirement checks one-by-one357 return checkFns.reduce(function (promise, checkFn, idx) {358 return promise.then(function () {359 // If fatal requirement is failed,360 // we don't need to check others361 if (fatalIsHit) return Q();362 var requirement = requirements[idx];363 return checkFn()364 .then(function (version) {365 requirement.installed = true;366 requirement.metadata.version = version;367 result.push(requirement);368 }, function (err) {369 if (requirement.isFatal) fatalIsHit = true;370 requirement.metadata.reason = err;371 result.push(requirement);372 });373 });374 }, Q())375 .then(function () {376 // When chain is completed, return requirements array to upstream API377 return result;378 });379};380module.exports.help = function () {381 console.log('Usage: check_reqs or node check_reqs');...

Full Screen

Full Screen

Version.js

Source:Version.js Github

copy

Full Screen

1/**2 * @author Jacky Nguyen <jacky@sencha.com>3 * @docauthor Jacky Nguyen <jacky@sencha.com>4 * @class Ext.Version5 *6 * A utility class that wrap around a string version number and provide convenient7 * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:8 var version = new Ext.Version('1.0.2beta');9 console.log("Version is " + version); // Version is 1.0.2beta10 console.log(version.getMajor()); // 111 console.log(version.getMinor()); // 012 console.log(version.getPatch()); // 213 console.log(version.getBuild()); // 014 console.log(version.getRelease()); // beta15 console.log(version.isGreaterThan('1.0.1')); // True16 console.log(version.isGreaterThan('1.0.2alpha')); // True17 console.log(version.isGreaterThan('1.0.2RC')); // False18 console.log(version.isGreaterThan('1.0.2')); // False19 console.log(version.isLessThan('1.0.2')); // True20 console.log(version.match(1.0)); // True21 console.log(version.match('1.0.2')); // True22 * @markdown23 */24(function() {25// Current core version26var version = '4.1.0', Version;27 Ext.Version = Version = Ext.extend(Object, {28 /**29 * Creates new Version object.30 * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]31 * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC32 * @return {Ext.Version} this33 */34 constructor: function(version) {35 var toNumber = this.toNumber,36 parts, releaseStartIndex;37 if (version instanceof Version) {38 return version;39 }40 this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');41 releaseStartIndex = this.version.search(/([^\d\.])/);42 if (releaseStartIndex !== -1) {43 this.release = this.version.substr(releaseStartIndex, version.length);44 this.shortVersion = this.version.substr(0, releaseStartIndex);45 }46 this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');47 parts = this.version.split('.');48 this.major = toNumber(parts.shift());49 this.minor = toNumber(parts.shift());50 this.patch = toNumber(parts.shift());51 this.build = toNumber(parts.shift());52 return this;53 },54 toNumber: function(value) {55 value = parseInt(value || 0, 10);56 if (isNaN(value)) {57 value = 0;58 }59 return value;60 },61 /**62 * Override the native toString method63 * @private64 * @return {String} version65 */66 toString: function() {67 return this.version;68 },69 /**70 * Override the native valueOf method71 * @private72 * @return {String} version73 */74 valueOf: function() {75 return this.version;76 },77 /**78 * Returns the major component value79 * @return {Number} major80 */81 getMajor: function() {82 return this.major || 0;83 },84 /**85 * Returns the minor component value86 * @return {Number} minor87 */88 getMinor: function() {89 return this.minor || 0;90 },91 /**92 * Returns the patch component value93 * @return {Number} patch94 */95 getPatch: function() {96 return this.patch || 0;97 },98 /**99 * Returns the build component value100 * @return {Number} build101 */102 getBuild: function() {103 return this.build || 0;104 },105 /**106 * Returns the release component value107 * @return {Number} release108 */109 getRelease: function() {110 return this.release || '';111 },112 /**113 * Returns whether this version if greater than the supplied argument114 * @param {String/Number} target The version to compare with115 * @return {Boolean} True if this version if greater than the target, false otherwise116 */117 isGreaterThan: function(target) {118 return Version.compare(this.version, target) === 1;119 },120 /**121 * Returns whether this version if greater than or equal to the supplied argument122 * @param {String/Number} target The version to compare with123 * @return {Boolean} True if this version if greater than or equal to the target, false otherwise124 */125 isGreaterThanOrEqual: function(target) {126 return Version.compare(this.version, target) >= 0;127 },128 /**129 * Returns whether this version if smaller than the supplied argument130 * @param {String/Number} target The version to compare with131 * @return {Boolean} True if this version if smaller than the target, false otherwise132 */133 isLessThan: function(target) {134 return Version.compare(this.version, target) === -1;135 },136 /**137 * Returns whether this version if less than or equal to the supplied argument138 * @param {String/Number} target The version to compare with139 * @return {Boolean} True if this version if less than or equal to the target, false otherwise140 */141 isLessThanOrEqual: function(target) {142 return Version.compare(this.version, target) <= 0;143 },144 /**145 * Returns whether this version equals to the supplied argument146 * @param {String/Number} target The version to compare with147 * @return {Boolean} True if this version equals to the target, false otherwise148 */149 equals: function(target) {150 return Version.compare(this.version, target) === 0;151 },152 /**153 * Returns whether this version matches the supplied argument. Example:154 * <pre><code>155 * var version = new Ext.Version('1.0.2beta');156 * console.log(version.match(1)); // True157 * console.log(version.match(1.0)); // True158 * console.log(version.match('1.0.2')); // True159 * console.log(version.match('1.0.2RC')); // False160 * </code></pre>161 * @param {String/Number} target The version to compare with162 * @return {Boolean} True if this version matches the target, false otherwise163 */164 match: function(target) {165 target = String(target);166 return this.version.substr(0, target.length) === target;167 },168 /**169 * Returns this format: [major, minor, patch, build, release]. Useful for comparison170 * @return {Number[]}171 */172 toArray: function() {173 return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];174 },175 /**176 * Returns shortVersion version without dots and release177 * @return {String}178 */179 getShortVersion: function() {180 return this.shortVersion;181 },182 /**183 * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}184 * @param {String/Number} target185 * @return {Boolean}186 */187 gt: function() {188 return this.isGreaterThan.apply(this, arguments);189 },190 /**191 * Convenient alias to {@link Ext.Version#isLessThan isLessThan}192 * @param {String/Number} target193 * @return {Boolean}194 */195 lt: function() {196 return this.isLessThan.apply(this, arguments);197 },198 /**199 * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}200 * @param {String/Number} target201 * @return {Boolean}202 */203 gtEq: function() {204 return this.isGreaterThanOrEqual.apply(this, arguments);205 },206 /**207 * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}208 * @param {String/Number} target209 * @return {Boolean}210 */211 ltEq: function() {212 return this.isLessThanOrEqual.apply(this, arguments);213 }214 });215 Ext.apply(Version, {216 // @private217 releaseValueMap: {218 'dev': -6,219 'alpha': -5,220 'a': -5,221 'beta': -4,222 'b': -4,223 'rc': -3,224 '#': -2,225 'p': -1,226 'pl': -1227 },228 /**229 * Converts a version component to a comparable value230 *231 * @static232 * @param {Object} value The value to convert233 * @return {Object}234 */235 getComponentValue: function(value) {236 return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));237 },238 /**239 * Compare 2 specified versions, starting from left to right. If a part contains special version strings,240 * they are handled in the following order:241 * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'242 *243 * @static244 * @param {String} current The current version to compare to245 * @param {String} target The target version to compare to246 * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent247 */248 compare: function(current, target) {249 var currentValue, targetValue, i;250 current = new Version(current).toArray();251 target = new Version(target).toArray();252 for (i = 0; i < Math.max(current.length, target.length); i++) {253 currentValue = this.getComponentValue(current[i]);254 targetValue = this.getComponentValue(target[i]);255 if (currentValue < targetValue) {256 return -1;257 } else if (currentValue > targetValue) {258 return 1;259 }260 }261 return 0;262 }263 });264 Ext.apply(Ext, {265 /**266 * @private267 */268 versions: {},269 /**270 * @private271 */272 lastRegisteredVersion: null,273 /**274 * Set version number for the given package name.275 *276 * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'277 * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'278 * @return {Ext}279 */280 setVersion: function(packageName, version) {281 Ext.versions[packageName] = new Version(version);282 Ext.lastRegisteredVersion = Ext.versions[packageName];283 return this;284 },285 /**286 * Get the version number of the supplied package name; will return the last registered version287 * (last Ext.setVersion call) if there's no package name given.288 *289 * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'290 * @return {Ext.Version} The version291 */292 getVersion: function(packageName) {293 if (packageName === undefined) {294 return Ext.lastRegisteredVersion;295 }296 return Ext.versions[packageName];297 },298 /**299 * Create a closure for deprecated code.300 *301 // This means Ext.oldMethod is only supported in 4.0.0beta and older.302 // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',303 // the closure will not be invoked304 Ext.deprecate('extjs', '4.0.0beta', function() {305 Ext.oldMethod = Ext.newMethod;306 ...307 });308 * @param {String} packageName The package name309 * @param {String} since The last version before it's deprecated310 * @param {Function} closure The callback function to be executed with the specified version is less than the current version311 * @param {Object} scope The execution scope (<tt>this</tt>) if the closure312 * @markdown313 */314 deprecate: function(packageName, since, closure, scope) {315 if (Version.compare(Ext.getVersion(packageName), since) < 1) {316 closure.call(scope);317 }318 }319 }); // End Versioning320 Ext.setVersion('core', version);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1var _ = require('underscore'),2 when = require('when'),3 series = require('when/sequence'),4 errors = require('../../errorHandling'),5 knex = require('../../models/base').knex,6 defaultSettings = require('../default-settings'),7 Settings = require('../../models/settings').Settings,8 fixtures = require('../fixtures'),9 initialVersion = '000',10 defaultDatabaseVersion;11// Default Database Version12// The migration version number according to the hardcoded default settings13// This is the version the database should be at or migrated to14function getDefaultDatabaseVersion() {15 if (!defaultDatabaseVersion) {16 // This be the current version according to the software17 defaultDatabaseVersion = _.find(defaultSettings.core, function (setting) {18 return setting.key === 'databaseVersion';19 }).defaultValue;20 }21 return defaultDatabaseVersion;22}23// Database Current Version24// The migration version number according to the database25// This is what the database is currently at and may need to be updated26function getDatabaseVersion() {27 return knex.schema.hasTable('settings').then(function (exists) {28 // Check for the current version from the settings table29 if (exists) {30 // Temporary code to deal with old databases with currentVersion settings31 return knex('settings')32 .where('key', 'databaseVersion')33 .orWhere('key', 'currentVersion')34 .select('value')35 .then(function (versions) {36 var databaseVersion = _.reduce(versions, function (memo, version) {37 if (isNaN(version.value)) {38 errors.throwError('Database version is not recognised');39 }40 return parseInt(version.value, 10) > parseInt(memo, 10) ? version.value : memo;41 }, initialVersion);42 if (!databaseVersion || databaseVersion.length === 0) {43 // we didn't get a response we understood, assume initialVersion44 databaseVersion = initialVersion;45 }46 return databaseVersion;47 });48 }49 return when.reject('Settings table does not exist');50 });51}52function setDatabaseVersion() {53 return knex('settings')54 .where('key', 'databaseVersion')55 .update({ 'value': defaultDatabaseVersion });56}57module.exports = {58 getDatabaseVersion: getDatabaseVersion,59 // Check for whether data is needed to be bootstrapped or not60 init: function () {61 var self = this;62 // There are 4 possibilities:63 // 1. The database exists and is up-to-date64 // 2. The database exists but is out of date65 // 3. The database exists but the currentVersion setting does not or cannot be understood66 // 4. The database has not yet been created67 return getDatabaseVersion().then(function (databaseVersion) {68 var defaultVersion = getDefaultDatabaseVersion();69 if (databaseVersion === defaultVersion) {70 // 1. The database exists and is up-to-date71 return when.resolve();72 }73 if (databaseVersion < defaultVersion) {74 // 2. The database exists but is out of date75 return self.migrateUpFromVersion(databaseVersion);76 }77 if (databaseVersion > defaultVersion) {78 // 3. The database exists but the currentVersion setting does not or cannot be understood79 // In this case we don't understand the version because it is too high80 errors.logErrorAndExit(81 'Your database is not compatible with this version of Ghost',82 'You will need to create a new database'83 );84 }85 }, function (err) {86 if (err === 'Settings table does not exist') {87 // 4. The database has not yet been created88 // Bring everything up from initial version.89 return self.migrateUpFreshDb();90 }91 // 3. The database exists but the currentVersion setting does not or cannot be understood92 // In this case the setting was missing or there was some other problem93 errors.logErrorAndExit('There is a problem with the database', err.message || err);94 });95 },96 // ### Reset97 // Migrate from where we are down to nothing.98 reset: function () {99 var self = this;100 return getDatabaseVersion().then(function (databaseVersion) {101 // bring everything down from the current version102 return self.migrateDownFromVersion(databaseVersion);103 }, function () {104 // If the settings table doesn't exist, bring everything down from initial version.105 return self.migrateDownFromVersion(initialVersion);106 });107 },108 // Only do this if we have no database at all109 migrateUpFreshDb: function () {110 var migration = require('./' + initialVersion);111 return migration.up().then(function () {112 // Load the fixtures113 return fixtures.populateFixtures();114 }).then(function () {115 // Initialise the default settings116 return Settings.populateDefaults();117 });118 },119 // Migrate from a specific version to the latest120 migrateUpFromVersion: function (version, max) {121 var versions = [],122 maxVersion = max || this.getVersionAfter(getDefaultDatabaseVersion()),123 currVersion = version,124 tasks = [];125 // Aggregate all the versions we need to do migrations for126 while (currVersion !== maxVersion) {127 versions.push(currVersion);128 currVersion = this.getVersionAfter(currVersion);129 }130 // Aggregate all the individual up calls to use in the series(...) below131 tasks = _.map(versions, function (taskVersion) {132 return function () {133 try {134 var migration = require('./' + taskVersion);135 return migration.up();136 } catch (e) {137 errors.logError(e);138 return when.reject(e);139 }140 };141 });142 // Run each migration in series143 return series(tasks).then(function () {144 // Finally update the databases current version145 return setDatabaseVersion();146 });147 },148 migrateDownFromVersion: function (version) {149 var self = this,150 versions = [],151 minVersion = this.getVersionBefore(initialVersion),152 currVersion = version,153 tasks = [];154 // Aggregate all the versions we need to do migrations for155 while (currVersion !== minVersion) {156 versions.push(currVersion);157 currVersion = this.getVersionBefore(currVersion);158 }159 // Aggregate all the individual up calls to use in the series(...) below160 tasks = _.map(versions, function (taskVersion) {161 return function () {162 try {163 var migration = require('./' + taskVersion);164 return migration.down();165 } catch (e) {166 errors.logError(e);167 return self.migrateDownFromVersion(initialVersion);168 }169 };170 });171 // Run each migration in series172 return series(tasks);173 },174 // Get the following version based on the current175 getVersionAfter: function (currVersion) {176 var currVersionNum = parseInt(currVersion, 10),177 nextVersion;178 // Default to initialVersion if not parsed179 if (isNaN(currVersionNum)) {180 currVersionNum = parseInt(initialVersion, 10);181 }182 currVersionNum += 1;183 nextVersion = String(currVersionNum);184 // Pad with 0's until 3 digits185 while (nextVersion.length < 3) {186 nextVersion = "0" + nextVersion;187 }188 return nextVersion;189 },190 getVersionBefore: function (currVersion) {191 var currVersionNum = parseInt(currVersion, 10),192 prevVersion;193 if (isNaN(currVersionNum)) {194 currVersionNum = parseInt(initialVersion, 10);195 }196 currVersionNum -= 1;197 prevVersion = String(currVersionNum);198 // Pad with 0's until 3 digits199 while (prevVersion.length < 3) {200 prevVersion = "0" + prevVersion;201 }202 return prevVersion;203 }...

Full Screen

Full Screen

AC_RunActiveContent.js

Source:AC_RunActiveContent.js Github

copy

Full Screen

1//v1.72// Flash Player Version Detection3// Detect Client Browser type4// Copyright 2005-2007 Adobe Systems Incorporated. All rights reserved.5var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;6var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;7var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;8function ControlVersion()9{10 var version;11 var axo;12 var e;13 // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry14 try {15 // version will be set for 7.X or greater players16 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");17 version = axo.GetVariable("$version");18 } catch (e) {19 }20 if (!version)21 {22 try {23 // version will be set for 6.X players only24 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");25 26 // installed player is some revision of 6.027 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,28 // so we have to be careful. 29 30 // default to the first public version31 version = "WIN 6,0,21,0";32 // throws if AllowScripAccess does not exist (introduced in 6.0r47) 33 axo.AllowScriptAccess = "always";34 // safe to call for 6.0r47 or greater35 version = axo.GetVariable("$version");36 } catch (e) {37 }38 }39 if (!version)40 {41 try {42 // version will be set for 4.X or 5.X player43 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");44 version = axo.GetVariable("$version");45 } catch (e) {46 }47 }48 if (!version)49 {50 try {51 // version will be set for 3.X player52 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");53 version = "WIN 3,0,18,0";54 } catch (e) {55 }56 }57 if (!version)58 {59 try {60 // version will be set for 2.X player61 axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");62 version = "WIN 2,0,0,11";63 } catch (e) {64 version = -1;65 }66 }67 68 return version;69}70// JavaScript helper required to detect Flash Player PlugIn version information71function GetSwfVer(){72 // NS/Opera version >= 3 check for Flash plugin in plugin array73 var flashVer = -1;74 75 if (navigator.plugins != null && navigator.plugins.length > 0) {76 if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {77 var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";78 var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;79 var descArray = flashDescription.split(" ");80 var tempArrayMajor = descArray[2].split("."); 81 var versionMajor = tempArrayMajor[0];82 var versionMinor = tempArrayMajor[1];83 var versionRevision = descArray[3];84 if (versionRevision == "") {85 versionRevision = descArray[4];86 }87 if (versionRevision[0] == "d") {88 versionRevision = versionRevision.substring(1);89 } else if (versionRevision[0] == "r") {90 versionRevision = versionRevision.substring(1);91 if (versionRevision.indexOf("d") > 0) {92 versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));93 }94 }95 var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;96 }97 }98 // MSN/WebTV 2.6 supports Flash 499 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;100 // WebTV 2.5 supports Flash 3101 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;102 // older WebTV supports Flash 2103 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;104 else if ( isIE && isWin && !isOpera ) {105 flashVer = ControlVersion();106 } 107 return flashVer;108}109// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available110function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)111{112 versionStr = GetSwfVer();113 if (versionStr == -1 ) {114 return false;115 } else if (versionStr != 0) {116 if(isIE && isWin && !isOpera) {117 // Given "WIN 2,0,0,11"118 tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"]119 tempString = tempArray[1]; // "2,0,0,11"120 versionArray = tempString.split(","); // ['2', '0', '0', '11']121 } else {122 versionArray = versionStr.split(".");123 }124 var versionMajor = versionArray[0];125 var versionMinor = versionArray[1];126 var versionRevision = versionArray[2];127 // is the major.revision >= requested major.revision AND the minor version >= requested minor128 if (versionMajor > parseFloat(reqMajorVer)) {129 return true;130 } else if (versionMajor == parseFloat(reqMajorVer)) {131 if (versionMinor > parseFloat(reqMinorVer))132 return true;133 else if (versionMinor == parseFloat(reqMinorVer)) {134 if (versionRevision >= parseFloat(reqRevision))135 return true;136 }137 }138 return false;139 }140}141function AC_AddExtension(src, ext)142{143 if (src.indexOf('?') != -1)144 return src.replace(/\?/, ext+'?'); 145 else146 return src + ext;147}148function AC_Generateobj(objAttrs, params, embedAttrs) 149{ 150 var str = '';151 if (isIE && isWin && !isOpera)152 {153 str += '<object ';154 for (var i in objAttrs)155 {156 str += i + '="' + objAttrs[i] + '" ';157 }158 str += '>';159 for (var i in params)160 {161 str += '<param name="' + i + '" value="' + params[i] + '" /> ';162 }163 str += '</object>';164 }165 else166 {167 str += '<embed ';168 for (var i in embedAttrs)169 {170 str += i + '="' + embedAttrs[i] + '" ';171 }172 str += '> </embed>';173 }174 document.write(str);175}176function AC_FL_RunContent(){177 var ret = 178 AC_GetArgs179 ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"180 , "application/x-shockwave-flash"181 );182 AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);183}184function AC_SW_RunContent(){185 var ret = 186 AC_GetArgs187 ( arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"188 , null189 );190 AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);191}192function AC_GetArgs(args, ext, srcParamName, classid, mimeType){193 var ret = new Object();194 ret.embedAttrs = new Object();195 ret.params = new Object();196 ret.objAttrs = new Object();197 for (var i=0; i < args.length; i=i+2){198 var currArg = args[i].toLowerCase(); 199 switch (currArg){ 200 case "classid":201 break;202 case "pluginspage":203 ret.embedAttrs[args[i]] = args[i+1];204 break;205 case "src":206 case "movie": 207 args[i+1] = AC_AddExtension(args[i+1], ext);208 ret.embedAttrs["src"] = args[i+1];209 ret.params[srcParamName] = args[i+1];210 break;211 case "onafterupdate":212 case "onbeforeupdate":213 case "onblur":214 case "oncellchange":215 case "onclick":216 case "ondblclick":217 case "ondrag":218 case "ondragend":219 case "ondragenter":220 case "ondragleave":221 case "ondragover":222 case "ondrop":223 case "onfinish":224 case "onfocus":225 case "onhelp":226 case "onmousedown":227 case "onmouseup":228 case "onmouseover":229 case "onmousemove":230 case "onmouseout":231 case "onkeypress":232 case "onkeydown":233 case "onkeyup":234 case "onload":235 case "onlosecapture":236 case "onpropertychange":237 case "onreadystatechange":238 case "onrowsdelete":239 case "onrowenter":240 case "onrowexit":241 case "onrowsinserted":242 case "onstart":243 case "onscroll":244 case "onbeforeeditfocus":245 case "onactivate":246 case "onbeforedeactivate":247 case "ondeactivate":248 case "type":249 case "codebase":250 case "id":251 ret.objAttrs[args[i]] = args[i+1];252 break;253 case "width":254 case "height":255 case "align":256 case "vspace": 257 case "hspace":258 case "class":259 case "title":260 case "accesskey":261 case "name":262 case "tabindex":263 ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];264 break;265 default:266 ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];267 }268 }269 ret.objAttrs["classid"] = classid;270 if (mimeType) ret.embedAttrs["type"] = mimeType;271 return ret;...

Full Screen

Full Screen

ConfigParser.js

Source:ConfigParser.js Github

copy

Full Screen

1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17/* jshint sub:true */18var util = require('util');19var Version = require('./Version');20var ConfigParser = require('cordova-common').ConfigParser;21var BASE_UAP_VERSION = new Version(10, 0, 10240, 0);22/**23 * A wrapper arount config.xml file, based on cordova-common implementation,24 * extended with some windows-specific methods.25 *26 * @constructor27 * @extends {ConfigParser}28 *29 * @param {String} path Path to config.xml file30 */31function WindowsConfigParser(path) {32 ConfigParser.call(this, path);33}34util.inherits(WindowsConfigParser, ConfigParser);35WindowsConfigParser.prototype.startPage = function() {36 var content = this.doc.find('content');37 if (content) {38 return content.attrib.src;39 }40 return null;41};42WindowsConfigParser.prototype.windows_packageVersion = function() {43 return this.doc.getroot().attrib['windows-packageVersion'];44};45WindowsConfigParser.prototype.getMatchingPreferences = function(regexp) {46 var preferences = this.doc.findall('preference');47 var result = [];48 preferences.forEach(function(preference) {49 if (regexp.test(preference.attrib.name)) {50 result.push({ name: preference.attrib.name, value: preference.attrib.value });51 }52 });53 return result;54};55WindowsConfigParser.prototype.getWindowsTargetVersion = function() {56 var preference = this.getPreference('windows-target-version');57 if (!preference)58 preference = '8.1'; // default is 8.1.59 return preference;60};61WindowsConfigParser.prototype.getWindowsPhoneTargetVersion = function() {62 // This is a little more complicated than the previous one.63 // 1. Check for an explicit preference. If the preference is set explicitly, return that, irrespective of whether it is valid64 // 2. Get the Windows baseline version. If it's equivalent to 8.0, bump it to 8.1.65 // 3. Return the Windows baseline version.66 var explicitPreference = this.getPreference('windows-phone-target-version');67 if (explicitPreference)68 return explicitPreference;69 var windowsTargetVersion = this.getWindowsTargetVersion();70 if (windowsTargetVersion === '8' || windowsTargetVersion === '8.0')71 windowsTargetVersion = '8.1';72 return windowsTargetVersion;73};74/**75 * Gets min/max UAP versions from the configuration. If no version preferences76 * are in the configuration file, this will provide Windows.Universal at77 * BASE_UAP_VERSION for both min and max. This will always return a rational78 * object or will fail; for example, if a platform expects a higher79 * min-version than max-version, it will raise the max version to the min80 * version.81 *82 * @return {Object[]} An array of objects in the shape of:83 * [ {'Name': 'Windows.Mobile', 'MinVersion': Version, 'MaxVersion': Version } ] (where84 * Version is a Version object)85 *86 * @exception {RangeError} Thrown if a Version string is badly formed.87 */88WindowsConfigParser.prototype.getAllMinMaxUAPVersions = function () {89 var uapVersionPreferenceTest = /(Microsoft.+?|Windows.+?)\-(MinVersion|MaxVersionTested)/i;90 var platformBag = Object.create(null);91 this.getMatchingPreferences(uapVersionPreferenceTest)92 .forEach(function(verPref) {93 var matches = uapVersionPreferenceTest.exec(verPref.name);94 // 'matches' should look like: ['Windows.Universal-MinVersion', 'Windows.Universal', 'MinVersion']95 var platformName = matches[1];96 var versionPropertyName = matches[2];97 var platformVersionSet = platformBag[platformName];98 if (typeof platformVersionSet === 'undefined') {99 platformVersionSet = { };100 platformBag[platformName] = platformVersionSet;101 }102 var versionTest = Version.tryParse(verPref.value);103 if (!versionTest) {104 throw new RangeError('Could not comprehend a valid version from the string "' + verPref.value + '" of platform-boundary "' + verPref.name + '".');105 }106 platformVersionSet[versionPropertyName] = versionTest;107 });108 for (var platformName in platformBag) {109 // Go through each and make sure there are min/max set110 var versionPref = platformBag[platformName];111 if (!versionPref.MaxVersionTested && !!versionPref.MinVersion) { // min is set, but max is not112 versionPref.MaxVersionTested = versionPref.MinVersion;113 }114 else if (!versionPref.MinVersion && !!versionPref.MaxVersionTested) { // max is set, min is not115 versionPref.MinVersion = versionPref.MaxVersionTested;116 }117 else if (!versionPref.MinVersion && !versionPref.MaxVersionTested) { // neither are set118 versionPref.MinVersion = BASE_UAP_VERSION;119 versionPref.MaxVersionTested = BASE_UAP_VERSION;120 }121 else { // both are set122 if (versionPref.MinVersion.gt(versionPref.MaxVersionTested)) {123 versionPref.MaxVersionTested = versionPref.MinVersion;124 }125 }126 }127 if (Object.keys(platformBag).length === 0) {128 platformBag['Windows.Universal'] = { MinVersion: BASE_UAP_VERSION, MaxVersionTested: BASE_UAP_VERSION };129 }130 return Object.keys(platformBag).map(function (platformName) {131 return {132 Name: platformName,133 MinVersion: platformBag[platformName].MinVersion.toString(),134 MaxVersionTested: platformBag[platformName].MaxVersionTested.toString(),135 };136 });137};138// Returns the widget defaultLocale139WindowsConfigParser.prototype.defaultLocale = function() {140 return this.doc.getroot().attrib['defaultlocale'];141};142/**143 * Checks to see whether access rules or144 * @return {boolean} True if the config specifies remote URIs for access or start; false otherwise.145 */146WindowsConfigParser.prototype.hasRemoteUris = function() {147 var test = /(https?|ms-appx-web):\/\//i;148 return test.test(this.startPage) ||149 this.getAllowNavigations()150 .some(function(rule) {151 return test.test(rule.href);152 });153};...

Full Screen

Full Screen

version-from-git.js

Source:version-from-git.js Github

copy

Full Screen

...16 createTag(t, version, runVersion)17 function runVersion (er) {18 t.ifError(er, 'git tag ran without error')19 npm.config.set('sign-git-tag', false)20 npm.commands.version(['from-git'], checkVersion)21 }22 function checkVersion (er) {23 var git = require('../../lib/utils/git.js')24 t.ifError(er, 'version command ran without error')25 git.whichAndExec(26 ['log'],27 { cwd: pkg, env: process.env },28 checkCommit29 )30 }31 function checkCommit (er, log, stderr) {32 t.ifError(er, 'git log ran without issue')33 t.notOk(stderr, 'no error output')34 t.ok(log.indexOf(version) !== -1, 'commit was created')35 t.end()36 }37})38test('npm version from-git with a valid tag updates the package.json version', function (t) {39 var version = '1.2.3'40 setup()41 createTag(t, version, runVersion)42 function runVersion (er) {43 t.ifError(er, 'git tag ran without error')44 npm.config.set('sign-git-tag', false)45 npm.commands.version(['from-git'], checkManifest)46 }47 function checkManifest (er) {48 t.ifError(er, 'npm run version ran without error')49 fs.readFile(path.resolve(pkg, 'package.json'), 'utf8', function (er, data) {50 t.ifError(er, 'read manifest without error')51 var manifest = JSON.parse(data)52 t.equal(manifest.version, version, 'updated the package.json version')53 t.done()54 })55 }56})57test('npm version from-git strips tag-version-prefix', function (t) {58 var version = '1.2.3'59 var prefix = 'custom-'60 var tag = prefix + version61 setup()62 createTag(t, tag, runVersion)63 function runVersion (er) {64 t.ifError(er, 'git tag ran without error')65 npm.config.set('sign-git-tag', false)66 npm.config.set('tag-version-prefix', prefix)67 npm.commands.version(['from-git'], checkVersion)68 }69 function checkVersion (er) {70 var git = require('../../lib/utils/git.js')71 t.ifError(er, 'version command ran without error')72 git.whichAndExec(73 ['log', '--pretty=medium'],74 { cwd: pkg, env: process.env },75 checkCommit76 )77 }78 function checkCommit (er, log, stderr) {79 t.ifError(er, 'git log ran without issue')80 t.notOk(stderr, 'no error output')81 t.ok(log.indexOf(tag) === -1, 'commit should not include prefix')82 t.ok(log.indexOf(version) !== -1, 'commit should include version')83 t.end()84 }85})86test('npm version from-git only strips tag-version-prefix if it is a prefix', function (t) {87 var prefix = 'test'88 var version = '1.2.3-' + prefix89 setup()90 createTag(t, version, runVersion)91 function runVersion (er) {92 t.ifError(er, 'git tag ran without error')93 npm.config.set('sign-git-tag', false)94 npm.config.set('tag-version-prefix', prefix)95 npm.commands.version(['from-git'], checkVersion)96 }97 function checkVersion (er) {98 var git = require('../../lib/utils/git.js')99 t.ifError(er, 'version command ran without error')100 git.whichAndExec(101 ['log'],102 { cwd: pkg, env: process.env },103 checkCommit104 )105 }106 function checkCommit (er, log, stderr) {107 t.ifError(er, 'git log ran without issue')108 t.notOk(stderr, 'no error output')109 t.ok(log.indexOf(version) !== -1, 'commit should include the full version')110 t.end()111 }112})113test('npm version from-git with an existing version', function (t) {114 var tag = 'v' + json.version115 setup()116 createTag(t, tag, runVersion)117 function runVersion (er) {118 t.ifError(er, 'git tag ran without error')119 npm.config.set('sign-git-tag', false)120 npm.commands.version(['from-git'], checkVersion)121 }122 function checkVersion (er) {123 t.equal(er.message, 'Version not changed')124 t.done()125 }126})127test('npm version from-git with an invalid version tag', function (t) {128 var tag = 'invalidversion'129 setup()130 createTag(t, tag, runVersion)131 function runVersion (er) {132 t.ifError(er, 'git tag ran without error')133 npm.config.set('sign-git-tag', false)134 npm.commands.version(['from-git'], checkVersion)135 }136 function checkVersion (er) {137 t.equal(er.message, tag + ' is not a valid version')138 t.done()139 }140})141test('npm version from-git without any versions', function (t) {142 setup()143 createGitRepo(t, runVersion)144 function runVersion (er) {145 t.ifError(er, 'created git repo without errors')146 npm.config.set('sign-git-tag', false)147 npm.commands.version(['from-git'], checkVersion)148 }149 function checkVersion (er) {150 t.equal(er.message, 'No tags found')151 t.done()152 }153})154test('cleanup', function (t) {155 cleanup()156 t.end()157})158function cleanup () {159 // windows fix for locked files160 process.chdir(osenv.tmpdir())161 rimraf.sync(pkg)...

Full Screen

Full Screen

edit-version-modal-controller.js

Source:edit-version-modal-controller.js Github

copy

Full Screen

1angular.module('app.admin.edit-version-modal', [])2 .controller('EditVersionModalController', ['$scope', 'DataService', 'Notification', '$uibModalInstance', '$uibModal', 'version', 'moment',3 ($scope, DataService, Notification, $uibModalInstance, $uibModal, version, moment) => {4 $scope.DataService = DataService;5 // Clone so not to polute the original6 $scope.version = _.cloneDeep(version);7 $scope.version.availability = new Date(version.availability);8 $scope.createdAt = new Date(version.createdAt);9 $scope.isAvailable = DataService.checkAvailability(version);10 /**11 * Updates the modal's knowlege of this version's assets from the one12 * maintained by DataService (which should be up to date with the server13 * because of SocketIO's awesomeness.14 */15 var updateVersionAssets = function() {16 var updatedVersion = _.find(DataService.data, {17 id: version.id18 });19 if (!updatedVersion) {20 // The version no longer exists21 return $uibModalInstance.close();22 }23 $scope.version.assets = updatedVersion.assets;24 };25 $scope.openAddAssetModal = function() {26 var modalInstance = $uibModal.open({27 animation: true,28 templateUrl: 'js/admin/add-version-asset-modal/add-version-asset-modal.html',29 controller: 'AddVersionAssetModalController',30 resolve: {31 version: () => version32 }33 });34 modalInstance.result.then(function() {35 // An asset should have been added, so we will update our modal's36 // knowledge of the version.37 updateVersionAssets();38 }, function() {});39 };40 $scope.openEditAssetModal = function(asset) {41 var modalInstance = $uibModal.open({42 animation: true,43 templateUrl: 'js/admin/edit-version-asset-modal/edit-version-asset-modal.html',44 controller: 'EditVersionAssetModalController',45 resolve: {46 asset: function() {47 return asset;48 }49 }50 });51 modalInstance.result.then(function() {52 // An asset should have been modified or deleted, so we will update53 // our modal's knowledge of the version.54 updateVersionAssets();55 }, function() {});56 };57 $scope.acceptEdit = function() {58 DataService.updateVersion($scope.version)59 .then(function success(response) {60 $uibModalInstance.close();61 }, () => {62 if (!$scope.version.availability) {63 $scope.version.availability = new Date(version.availability);64 }65 });66 };67 $scope.makeAvailable = () => {68 const updatedVersion = {69 ...$scope.version,70 availability: moment().startOf('second').toDate()71 };72 DataService73 .updateVersion(updatedVersion)74 .then($uibModalInstance.close, () => {});75 };76 $scope.deleteVersion = function() {77 DataService.deleteVersion(version.id)78 .then(function success(response) {79 $uibModalInstance.close();80 }, function error(response) {});81 };82 $scope.closeModal = function() {83 $uibModalInstance.dismiss();84 };85 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const version = await browser.version();6 console.log(version);7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 await browser.close();13})();14const puppeteer = require('puppeteer');15(async () => {16 const browser = await puppeteer.launch({ headless: false });17 await browser.close();18})();19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch({22 });23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch({ executablePath: '/path/to/Chrome' });28 await browser.close();29})();30const puppeteer = require('puppeteer');

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.pdf({path: 'google.pdf', format: 'A4'});6 await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const version = await browser.version();5 console.log('Version: ' + version);6 await browser.close();7})();

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer 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