How to use packageConfig method in ava

Best JavaScript code snippet using ava

package.js

Source:package.js Github

copy

Full Screen

1/*2 * Copyright 2014-2016 Guy Bedford (http://guybedford.com)3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16require('core-js/es6/string');17var request = require('request');18var ui = require('./ui');19var semver = require('./semver');20var asp = require('bluebird').Promise.promisify;21var config = require('./config');22var mkdirp = require('mkdirp');23var rimraf = require('rimraf');24var path = require('path');25var registry = require('./registry');26var PackageName = require('./package-name');27var globalConfig = require('./config/global-config');28var readJSON = require('./common').readJSON;29var ncp = require('ncp');30var fs = require('graceful-fs');31var glob = require('glob');32var minimatch = require('minimatch');33var md5 = require('./common').md5;34var processDeps = require('./common').processDeps;35var extend = require('./common').extend;36var HOME = require('./common').HOME;37var Promise = require('bluebird');38var newLine = require('./common').newLine;39var jspmVersion = require('../package.json').version.split('.').splice(0, 2).join('.');40// we cache registry lookups here to allow reductions in config saving41var registryCache = exports.registryCache = {};42// given a name like 'jquery', 'github:repo/thatwasmoved'43// add the default registry endpoint to the name44// so we now have 'jspm:jquery', 'github:repo/thatwasmoved'45// then run the locate hook (if provided) of the registry46// following redirects until the locate hook converges47// getting 'github:components/jquery' and 'github:repo/redirected'48// at this point, we have the final name for the target49var locateCache = {};50// target is a PackageName object51exports.locate = locate;52function locate(target) {53 if (!target.registry) {54 target = new PackageName(target.exactName);55 target.setRegistry(globalConfig.config.defaultRegistry);56 }57 var endpoint = registry.load(target.registry);58 if (!endpoint.locate)59 return Promise.resolve(target);60 locateCache[target.registry] = locateCache[target.registry] || {};61 // NB enable versioned locate62 return Promise.resolve()63 .then(function() {64 if (locateCache[target.registry][target.package])65 return locateCache[target.registry][target.package];66 return (locateCache[target.registry][target.package] = Promise.resolve(endpoint.locate(target.package))67 .then(function(located) {68 // NB support versioned registry69 if (target.registry === globalConfig.config.defaultRegistry)70 registryCache[target.package] = located.redirect;71 return located;72 }));73 })74 .then(function(located) {75 if (!located)76 return target;77 if (located.redirect) {78 var redirectPkg = new PackageName(located.redirect);79 // mutate the target by the redirect80 // this ensures we always store resolved targets81 target.setRegistry(redirectPkg.registry);82 target.setPackage(redirectPkg.package);83 return locate(target);84 }85 if (located.notfound)86 throw 'Repo `' + target.name + '` not found.' +87 (target.registry != 'npm' && target.package.split('/').length == 1 ? ' Perhaps try %jspm install npm:' + target.package + '%.' : '');88 throw 'Invalid registry locate response for %' + target.registry + '%';89 }, function(e) {90 if (e)91 ui.log('err', e.stack || e);92 throw 'Error locating `' + target.name + '`.';93 });94}95var lookupPromises = {};96var lookups = {};97exports.lookup = lookup;98function lookup(pkg, edge) {99 return Promise.resolve()100 // load the version map101 .then(function() {102 // already loaded103 if (lookups[pkg.name])104 return { versions: lookups[pkg.name] };105 // already loading106 if (lookupPromises[pkg.name])107 return lookupPromises[pkg.name];108 ui.log('debug', 'Looking up `' + pkg.name + '`');109 return (lookupPromises[pkg.name] = Promise.resolve(registry.load(pkg.registry).lookup(pkg.package)));110 })111 .then(function(lookup) {112 if (lookup.notfound)113 throw 'Repo `' + pkg.name + '` not found!';114 if (!lookup.versions)115 throw 'Invalid registry lookup response for %' + pkg.registry + '%';116 lookups[pkg.name] = lookup.versions;117 return function(version) {118 var opts = {edge: edge, latestVersion: lookup.latest};119 var lookupObj = getVersionMatch(version, lookup.versions, opts);120 if (!lookupObj)121 return;122 return new PackageName(pkg.name + '@' + lookupObj.version);123 };124 }, function(e) {125 if (e)126 ui.log('err', e.stack || e);127 throw 'Error looking up `' + pkg.name + '`.';128 });129}130// exported for unit testing131exports.getVersionMatch = getVersionMatch;132function getVersionMatch(pkgVersion, versions, options) {133 // unescape pkgVersion for comparison134 if (pkgVersion)135 pkgVersion = decodeURIComponent(pkgVersion);136 if (versions[pkgVersion]) {137 versions[pkgVersion].version = pkgVersion;138 return versions[pkgVersion];139 }140 var version;141 var stableSemver = [];142 var unstableSemver = [];143 var stableExact = [];144 var unstableExact = [];145 var edge = options && options.edge;146 Object.keys(versions).forEach(function(v) {147 version = versions[v];148 var stable = version.stable;149 var semverMatch = v.match(semver.semverRegEx);150 var valid = semverMatch && semverMatch[1] && semverMatch[2] && semverMatch[3];151 var pre = valid && semverMatch[4];152 // store a reverse lookup153 version.version = v;154 // ignore non-semver or prerelease, unless explictly marked as stable155 if (!valid) {156 // unstable unless explicitly stable. in --edge prioritize all after 'master'157 if (stable && !edge)158 stableExact.push(v);159 else160 unstableExact.push(v);161 }162 // stable unless explicitly unstable or indetermate and a prerelease163 // --edge considers all semver to be stable164 else if (!edge && (stable === false || (stable !== true && pre)))165 unstableSemver.push(v);166 else167 stableSemver.push(v);168 });169 function compareDesc(a, b) {170 return semver.compare(b, a);171 }172 if (!pkgVersion) {173 var latest = options && options.latestVersion && versions[options.latestVersion];174 if (!edge && latest)175 return latest;176 stableSemver.sort(compareDesc);177 if (stableSemver[0])178 return versions[stableSemver[0]];179 unstableSemver.sort(compareDesc);180 if (unstableSemver[0])181 return versions[unstableSemver[0]];182 if (latest)183 return latest;184 stableExact.sort();185 if (stableExact[0])186 return versions[stableExact[0]];187 // an ugly practicality. ideally designed out in future.188 if (versions.master)189 return versions.master;190 unstableExact.sort();191 if (unstableExact[0])192 return versions[unstableExact[0]];193 }194 else {195 var i, ver;196 stableSemver.sort(compareDesc);197 // find highest stable match in tags198 for (i = 0; i < stableSemver.length; i++) {199 ver = stableSemver[i];200 var match = edge ? semver.matchUnstable : semver.match;201 if (match(pkgVersion, ver))202 return versions[ver];203 }204 unstableSemver.sort(compareDesc);205 for (i = 0; i < unstableSemver.length; i++) {206 ver = unstableSemver[i];207 if (semver.match(pkgVersion, ver))208 return versions[ver];209 }210 }211}212function getOverride(pkg, manualOverride, alreadyInstalled) {213 return Promise.resolve()214 .then(function() {215 // if the package is not installed, but we have a local override match, then use that216 var existingOverride = config.pjson.overrides[pkg.exactName];217 if (!alreadyInstalled && !existingOverride) {218 var existingOverrideVersion = Object.keys(config.pjson.overrides)219 .filter(function(overrideName) {220 return overrideName.startsWith(pkg.name + '@');221 })222 .map(function(overrideName) {223 return overrideName.split('@').pop();224 })225 .filter(function(overrideVersion) {226 return semver.match('^' + overrideVersion, pkg.version);227 })228 .sort(semver.compare).pop();229 if (existingOverrideVersion)230 existingOverride = JSON.parse(JSON.stringify(config.pjson.overrides[pkg.name + '@' + existingOverrideVersion]));231 }232 if ((alreadyInstalled || existingOverride) && !manualOverride)233 return Promise.resolve(config.pjson.overrides[pkg.exactName] = existingOverride || {});234 // otherwise use the registry override + manual override235 var endpoint = registry.load(globalConfig.config.defaultRegistry);236 return endpoint.getOverride(pkg.registry, pkg.package, pkg.version, manualOverride)237 .then(function(override) {238 for (var p in override)239 if (override[p] === undefined)240 delete override[p];241 override = override || {};242 // persist the override for reproducibility243 config.pjson.overrides[pkg.exactName] = override;244 return override;245 });246 })247 .then(function(override) {248 var packageConfig = typeof override.systemjs == 'object' ? override.systemjs : override;249 upgradePackageConfig(packageConfig);250 return override;251 });252}253exports.upgradePackageConfig = upgradePackageConfig;254function upgradePackageConfig(packageConfig) {255 // 0.16 Package Config Override Upgrade Path:256 // shim becomes meta257 if (packageConfig.shim) {258 packageConfig.meta = packageConfig.meta || {};259 for (var s in packageConfig.shim) {260 // ignore shim if there is any meta config for this module261 if (packageConfig.meta[s + '.js'])262 continue;263 var curShim = packageConfig.shim[s];264 var curMeta = packageConfig.meta[s + '.js'] = {};265 if (curShim instanceof Array) {266 curMeta.deps = curShim;267 }268 else if (typeof curShim == 'object') {269 if (curShim.deps)270 curMeta.deps = curShim.deps;271 else if (curShim.imports)272 curMeta.deps = curShim.imports;273 if (curShim.exports)274 curMeta.exports = curShim.exports;275 }276 curMeta.format = 'global';277 if (typeof curMeta.deps === 'string')278 curMeta.deps = [curMeta.deps];279 }280 delete packageConfig.shim;281 }282}283var injecting = {};284exports.inject = function(pkg, depLoad) {285 if (injecting[pkg.exactName]) {286 injecting[pkg.exactName].depLoad.then(function(depMap) {287 depLoad(depMap);288 return depMap;289 });290 return injecting[pkg.exactName].promise;291 }292 injecting[pkg.exactName] = {};293 var depResolve, depReject;294 injecting[pkg.exactName].depLoad = new Promise(function(resolve, reject) {295 depResolve = resolve;296 depReject = reject;297 })298 .then(function(depMap) {299 depLoad(depMap);300 return depMap;301 });302 var remote = registry.load(pkg.registry).remote;303 if (!remote)304 throw 'Cannot inject from registry %' + pkg.registry + '% as it has no remote.';305 // NB remove rejectUnauthorized306 var url = remote + (remote.endsWith('/') ? '' : '/') + pkg.exactName.substr(pkg.exactName.indexOf(':') + 1) + '/.jspm.json';307 injecting[pkg.exactName].promise = asp(request)({308 method: 'get',309 url: url,310 rejectUnauthorized: false311 }).then(function(res) {312 if (res.statusCode !== 200)313 throw new Error('Error requesting package config for `' + pkg.exactName + '` at %' + url + '%.');314 try {315 return JSON.parse(res.body);316 }317 catch(e) {318 throw new Error('Unable to parse package config');319 }320 })321 .then(function(pjson) {322 depResolve(processDeps(pjson.dependencies, pjson.registry));323 return pjson;324 }, depReject);325 return injecting[pkg.exactName].promise;326};327// note if it is a symlink, we leave it unaltered328var downloading = {};329// options.override330// options.quick331// options.force332// options.linked333exports.download = function(pkg, options, depsCallback) {334 // download queue335 if (downloading[pkg.exactName]) {336 downloading[pkg.exactName].preloadCallbacks.push(depsCallback);337 downloading[pkg.exactName].postloadCallbacks.push(depsCallback);338 return downloading[pkg.exactName].promise;339 }340 // track the deps sent to the deps callback to avoid duplication between preload and postload341 var sentDeps = [];342 function doDepsCallback(depRanges) {343 var sendRanges = { deps: {}, peerDeps: {} };344 Object.keys(depRanges.deps).forEach(function(dep) {345 if (sentDeps.indexOf(dep) == -1)346 sendRanges.deps[dep] = depRanges.deps[dep];347 });348 Object.keys(depRanges.peerDeps).forEach(function(dep) {349 if (sentDeps.indexOf(dep) == -1)350 sendRanges.peerDeps[dep] = depRanges.peerDeps[dep];351 });352 sentDeps = sentDeps.concat(Object.keys(sendRanges.deps)).concat(Object.keys(sendRanges.peerDeps));353 depsCallback(sendRanges);354 }355 // callbacks as we need a synchronous guarantee of resolution356 // before the download promise357 var preloadCallbacks = [doDepsCallback];358 var postloadCallbacks = [doDepsCallback];359 function preloadResolve(depRanges) {360 preloadCallbacks.forEach(function(cb) {361 cb(depRanges);362 });363 }364 function postloadResolve(depRanges) {365 postloadCallbacks.forEach(function(cb) {366 cb(depRanges);367 });368 }369 downloading[pkg.exactName] = {370 preloadCallbacks: preloadCallbacks,371 postloadCallbacks: postloadCallbacks372 };373 // download374 var downloadDir = pkg.getPath();375 var getPackageConfigError;376 var getPackageConfigPromise;377 var override;378 return (downloading[pkg.exactName].promise = Promise.resolve()379 .then(function() {380 // determine the override381 return getOverride(pkg, options.override, options.alreadyInstalled);382 })383 .then(function(_override) {384 override = _override;385 // check if the folder exists386 return new Promise(function(resolve) {387 fs.exists(downloadDir, resolve);388 });389 })390 .then(function(dirExists) {391 // quick skips actual hash checks and dependency reinstalls392 if (options.quick && !options.override && dirExists)393 return true;394 var fullHash, cfgHash;395 // check freshness396 return Promise.resolve()397 .then(function() {398 // ensure lookup data is present399 if (!lookups[pkg.name] && !options.linked)400 return lookup(pkg);401 })402 .then(function() {403 if ((!lookups[pkg.name] || !lookups[pkg.name][pkg.version]) && !options.linked)404 throw 'Unable to resolve version %' + pkg.version + '% for `' + pkg.package + '`.';405 return getPackageHash(downloadDir);406 })407 .then(function(hashes) {408 // if the package exists locally, hash the package@x.y.z.json file to see if it has been changed409 // if it has been changed then add the altered package@x.y.z.json contents410 // to the overrides as an override, and note that we have done this411 if (hashes[1]) {412 return readJSON(downloadDir + '.json')413 .then(function(pkgConfig) {414 if (computeConfigHash(pkgConfig) == hashes[1])415 return;416 for (var c in pkgConfig) {417 if (JSON.stringify(pkgConfig[c]) !== JSON.stringify(override[c]))418 override[c] = pkgConfig[c];419 }420 // overrides usually extend, so to indicate that we want this to be the final override421 // we set empty values explicitly422 // if (!override.defaultExtension)423 // override.defaultExtension = false;424 if (!override.format)425 override.format = 'detect';426 if (!override.meta)427 override.meta = {};428 if (!override.map)429 override.map = {};430 ui.log('ok', 'The package configuration file `' + path.relative(path.dirname(config.pjsonPath), downloadDir + '.json') +431 '` has been edited manually. To avoid overwriting the change, it has been added to the package.json overrides.');432 return hashes[0];433 }, function(err) {434 if (typeof err === 'string' && err.startsWith('Error parsing') || err.code == 'ENOENT')435 return null;436 throw err;437 });438 }439 return hashes[0];440 })441 .then(function(pkgHash) {442 if (options.force)443 return false;444 fullHash = computePackageHash(pkg, override);445 return pkgHash === fullHash;446 })447 .then(function(fresh) {448 if (fresh && config[pkg.exactName]) {449 // this can't trigger twice, so if its a second call its just a noop450 preloadResolve(config.deps[pkg.exactName]);451 return true;452 }453 // clear stored dependency cache for download454 delete config.deps[pkg.exactName];455 // if linked, process the symlinked folder456 if (options.linked && !options.unlink) {457 ui.log('info', 'Processing linked package `' + pkg.exactName + '`');458 return Promise.resolve(readJSON(path.resolve(downloadDir, 'package.json')))459 .then(function(packageConfig) {460 return derivePackageConfig(pkg, packageConfig, override);461 })462 .then(function(packageConfig) {463 return processPackage(pkg, downloadDir, packageConfig, options.linked);464 }, function(err) {465 if (err)466 ui.log('err', err && err.stack || err);467 throw 'Error processing linked package `' + pkg.exactName + '`.';468 })469 .then(function(packageConfig) {470 return createLoaderConfig(pkg, packageConfig, downloadDir)471 .then(function() {472 postloadResolve(getDepRanges(pkg, packageConfig));473 });474 })475 .then(function() {476 return false;477 });478 }479 if (pkg.registry == 'local')480 throw '`' + pkg.exactName + '` must be linked to be used in installs.';481 var cacheDir = pkg.getPath(path.resolve(HOME, '.jspm', 'packages'));482 // ensure global cache is fresh / download if not483 return Promise.resolve()484 .then(function() {485 if (config.force)486 return false;487 return getPackageHash(cacheDir)488 .then(function(hashes) {489 return hashes[0] && hashes[0] === fullHash;490 });491 })492 .then(function(cacheFresh) {493 // global cache is fresh494 // read the cache .deps.json file containing the deps ranges495 if (cacheFresh)496 return readJSON(cacheDir + '.deps.json')497 .then(function(depJSON) {498 var depRanges = getDepRanges(pkg, depJSON);499 if (!depRanges.deps)500 throw new TypeError('Invalid deps format!');501 preloadResolve(depRanges);502 return null;503 });504 ui.log('info', 'Downloading `' + pkg.exactName + '`');505 var endpoint = registry.load(pkg.registry);506 var lookupObj = lookups[pkg.name][pkg.version];507 getPackageConfigPromise = Promise.resolve()508 .then(function() {509 if (endpoint.getPackageConfig)510 return endpoint.getPackageConfig(pkg.package, pkg.version, lookupObj.hash, lookupObj.meta);511 })512 .then(function(packageConfig) {513 if (!packageConfig)514 return;515 return derivePackageConfig(pkg, packageConfig, override)516 .then(function(packageConfig) {517 preloadResolve(getDepRanges(pkg, packageConfig));518 return packageConfig;519 });520 })521 .catch(function(err) {522 getPackageConfigError = err;523 });524 return Promise.resolve(cacheDir)525 // ensure the download directory exists526 .then(asp(mkdirp))527 // clear the directory528 .then(function() {529 return asp(rimraf)(cacheDir);530 })531 .then(function() {532 try {533 fs.unlinkSync(cacheDir + '.js');534 }535 catch(e) {}536 })537 // create it538 .then(function() {539 return asp(mkdirp)(cacheDir);540 })541 // do the download542 .then(function() {543 return endpoint.download(pkg.package, pkg.version, lookupObj.hash, lookupObj.meta, cacheDir);544 })545 // process the package fully546 .then(function(downloadPackageConfig) {547 if (getPackageConfigError)548 return Promise.reject(getPackageConfigError);549 return getPackageConfigPromise550 .then(function(packageConfig) {551 // if we have a getPackageConfig, we always use that packageConfig552 if (packageConfig)553 return packageConfig;554 // otherwise get from the repo555 return Promise.resolve(downloadPackageConfig || readJSON(path.resolve(cacheDir, 'package.json')))556 .then(function(packageConfig) {557 return derivePackageConfig(pkg, packageConfig, override)558 .then(function(packageConfig) {559 preloadResolve(getDepRanges(pkg, packageConfig));560 return packageConfig;561 });562 });563 });564 })565 .then(function(packageConfig) {566 // recompute hash in case override was deduped567 fullHash = computePackageHash(pkg, override);568 return processPackage(pkg, cacheDir, packageConfig);569 })570 // create the config file in the cache folder571 .then(function(packageConfig) {572 return createLoaderConfig(pkg, packageConfig, cacheDir)573 .then(function(loaderConfig) {574 cfgHash = computeConfigHash(loaderConfig);575 return packageConfig;576 });577 })578 // create the deps file in the cache folder579 .then(function(packageConfig) {580 var depRanges = getDepRanges(pkg, packageConfig);581 var rangeMap = { dependencies: {}, peerDependencies: {} };582 Object.keys(depRanges.deps).forEach(function(dep) {583 rangeMap.dependencies[dep] = depRanges.deps[dep].exactName;584 });585 Object.keys(depRanges.peerDeps).forEach(function(dep) {586 rangeMap.peerDependencies[dep] = depRanges.peerDeps[dep].exactName;587 });588 fs.writeFileSync(cacheDir + '.deps.json', JSON.stringify(rangeMap, null, 2));589 fs.writeFileSync(path.resolve(cacheDir, '.jspm-hash'), fullHash + newLine + cfgHash);590 // postloadResolve creates a promise so we need to return null for Bluebird warnings591 postloadResolve(depRanges);592 return null;593 });594 })595 // copy global cache to local install596 // clear the directory597 .then(function() {598 // in case it was linked, try and remove599 try {600 fs.unlinkSync(downloadDir);601 }602 catch(e) {603 if (e.code === 'EISDIR' || e.code === 'EPERM' || e.code === 'ENOENT')604 return;605 throw e;606 }607 })608 .then(function() {609 return asp(mkdirp)(downloadDir);610 })611 .then(function() {612 return asp(rimraf)(downloadDir);613 })614 .then(function() {615 return asp(ncp)(cacheDir, downloadDir);616 })617 .then(function() {618 // copy config file from cached folder619 return asp(ncp)(cacheDir + '.json', downloadDir + '.json');620 })621 .then(function() {622 // bump the modified time of the .jspm-hash so that it matches the config file time623 return asp(fs.utimes)(path.resolve(downloadDir, '.jspm-hash'), new Date() / 1000, new Date() / 1000);624 })625 .then(function() {626 return fresh;627 });628 });629 }));630};631function getPackageHash(dir) {632 return new Promise(function(resolve) {633 fs.exists(dir + '.json', function(exists) {634 resolve(exists);635 });636 })637 .then(function(hasConfig) {638 if (!hasConfig)639 return [];640 // otherwise do the hash check641 return asp(fs.readFile)(path.resolve(dir, '.jspm-hash'))642 .then(function(hash) {643 return hash.toString().split(/\n|\r/);644 }, function(err) {645 if (err.code === 'ENOENT')646 return [];647 throw err;648 });649 });650}651function computePackageHash(pkg, override) {652 // determine the full hash of the package653 var hash = lookups[pkg.name] && lookups[pkg.name][pkg.version].hash || 'link';654 var endpoint = registry.load(pkg.registry);655 return hash + md5(JSON.stringify(override)) + endpoint.versionString + 'jspm@' + jspmVersion;656}657function computeConfigHash(pkgConfig) {658 return md5(JSON.stringify(pkgConfig));659}660// return the dependency install range object661// while also setting it on the config.deps cache662// note it is important that we return the config.deps by reference663// that is because when installed, locate redirects mutate this to ensure664// targets all resolve out of registry mappings for reproducibility665function getDepRanges(pkg, packageConfig) {666 var depRanges = config.deps[pkg.exactName] = config.deps[pkg.exactName] || { deps: {}, peerDeps: {} };667 var mainDepRanges = processDeps(packageConfig.dependencies, packageConfig.registry, pkg.exactName);668 var peerDepRanges = processDeps(packageConfig.peerDependencies, packageConfig.registry, pkg.exactName);669 // treat optional dependencies as peerDependencies670 // when supported in jspm via https://github.com/jspm/jspm-cli/issues/1441,671 // optionalDependencies will be optional peer dependencies672 var optionalDepRanges = processDeps(packageConfig.optionalDependencies, packageConfig.registry, pkg.exactName);673 Object.keys(optionalDepRanges).forEach(function(dep) {674 if (!peerDepRanges[dep])675 peerDepRanges[dep] = optionalDepRanges[dep];676 });677 // deps that are both normal deps and peer deps treated as just peer deps678 Object.keys(peerDepRanges).forEach(function(dep) {679 if (mainDepRanges[dep])680 delete mainDepRanges[dep];681 });682 // ensure depRanges is an exact reference to the config.deps ranges683 // so we can mutate the resolutions684 Object.keys(mainDepRanges).forEach(function(dep) {685 if (depRanges.deps[dep])686 return;687 depRanges.deps[dep] = mainDepRanges[dep];688 });689 Object.keys(peerDepRanges).forEach(function(dep) {690 if (depRanges.peerDeps[dep])691 return;692 depRanges.peerDeps[dep] = peerDepRanges[dep];693 });694 return depRanges;695}696// like config.derivePackageConfig, but applies the697// registry processPackageConfig operation as well698function derivePackageConfig(pkg, packageConfig, override) {699 packageConfig = extend({}, packageConfig);700 // first derive the override701 if (override || packageConfig.jspm)702 packageConfig.jspm = extend({}, packageConfig.jspm || {});703 if (override) {704 // override is by reference, so we remove properties that don't apply705 // and clone properties that do706 for (var p in override) {707 var stringified = JSON.stringify(override[p]);708 if (p in packageConfig.jspm ? JSON.stringify(packageConfig.jspm[p]) !== stringified : JSON.stringify(packageConfig[p]) !== stringified)709 packageConfig.jspm[p] = JSON.parse(stringified);710 else711 delete override[p];712 }713 }714 // then apply the override715 if (packageConfig.jspm)716 extend(packageConfig, packageConfig.jspm);717 var endpoint = registry.load(packageConfig.registry || pkg.registry);718 return Promise.resolve()719 .then(function() {720 if (endpoint.processPackageConfig)721 return endpoint.processPackageConfig(packageConfig, pkg.exactName);722 return packageConfig;723 })724 .then(function(packageConfig) {725 if (!packageConfig)726 throw new Error('processPackageConfig must return the processed configuration object.');727 packageConfig.registry = packageConfig.registry || pkg.registry || 'jspm';728 return packageConfig;729 });730}731// apply registry process to package config given completed download folder and config732function processPackage(pkg, dir, packageConfig, linked) {733 // any package which takes longer than 10 seconds to process734 var timeout = setTimeout(function() {735 ui.log('warn', 'It\'s taking a long time to process the dependencies of `' + pkg.exactName + '`.\n' +736 'This package may need an %ignore% property to indicate test or example folders for jspm to skip.\n');737 }, 10000);738 var endpoint = registry.load(packageConfig.registry || pkg.registry);739 return Promise.resolve()740 .then(function() {741 if (linked)742 return;743 return filterIgnoreAndFiles(dir, packageConfig.ignore, packageConfig.files);744 })745 .then(function() {746 if (linked)747 return;748 var distDir;749 if (packageConfig.directories)750 distDir = packageConfig.directories.dist || packageConfig.directories.lib;751 if (distDir)752 return collapseDistDir(dir, distDir);753 })754 .then(function() {755 // now that we have the derived packageConfig, do the registry build756 if (endpoint.processPackage)757 return endpoint.processPackage(packageConfig, pkg.exactName, dir)758 .catch(function(e) {759 throw 'Error building package `' + pkg.exactName + '`.\n' + (e && e.stack || e);760 })761 .then(function(packageConfig) {762 if (!packageConfig)763 throw new Error('Registry endpoint processPackage of ' + pkg.exactName + ' did not return package config.');764 return packageConfig;765 });766 else767 return packageConfig;768 })769 .then(function(packageConfig) {770 upgradePackageConfig(packageConfig);771 clearTimeout(timeout);772 return packageConfig;773 });774}775// filter files in a downloaded package to just the [files] and [ignore]776var inDir = require('./common').inDir;777function filterIgnoreAndFiles(dir, ignore, files) {778 if (!ignore && !files)779 return Promise.resolve();780 return asp(glob)(dir + path.sep + '**' + path.sep + '*', {dot: true})781 .then(function(allFiles) {782 var removeFiles = [];783 allFiles.forEach(function(file) {784 var fileName = path.relative(dir, file).replace(/\\/g, '/');785 // if files, remove all files except those in the files list786 if (files && !files.some(function(keepFile) {787 if (typeof keepFile != 'string')788 return;789 if (keepFile.startsWith('./'))790 keepFile = keepFile.substr(2);791 if (keepFile.endsWith('/*') && keepFile[keepFile.length - 3] != '*')792 keepFile = keepFile.substr(0, keepFile.length - 2) + '/**/*';793 // this file is in a keep dir, or a keep file, don't exclude794 if (inDir(fileName, keepFile, false, '/') || minimatch(fileName, keepFile, { dot: true }))795 return true;796 }))797 return removeFiles.push(fileName);798 // if ignore, ensure removed799 if (ignore && ignore.some(function(ignoreFile) {800 if (typeof ignoreFile != 'string')801 return;802 if (ignoreFile.startsWith('./'))803 ignoreFile = ignoreFile.substr(2);804 // this file is in an ignore dir or an ignore file, ignore805 if (inDir(fileName, ignoreFile, false) || minimatch(fileName, ignoreFile))806 return true;807 }))808 removeFiles.push(fileName);809 });810 // do removal811 return Promise.all(removeFiles.map(function(removeFile) {812 return asp(fs.unlink)(path.resolve(dir, removeFile)).catch(function(e) {813 if (e.code === 'EPERM' || e.code === 'EISDIR' || e.code === 'ENOENT')814 return;815 throw e;816 });817 }));818 });819}820function collapseDistDir(dir, subDir) {821 if (subDir.endsWith('/'))822 subDir = subDir.substr(0, subDir.length - 1);823 var tmpDir = path.resolve(dir, '..', '.tmp-' + dir.split(path.sep).pop());824 // move subDir to tmpDir825 fs.renameSync(path.normalize(dir + path.sep + subDir), tmpDir);826 // remove everything in dir827 return asp(rimraf)(dir)828 .then(function() {829 fs.renameSync(tmpDir, dir);830 });831}832var loaderConfigProperties = ['baseDir', 'defaultExtension', 'format', 'meta', 'map', 'main'];833function createLoaderConfig(pkg, packageConfig, downloadDir) {834 // systemjs prefix property in package.json takes preference835 if (typeof packageConfig.systemjs == 'object')836 packageConfig = packageConfig.systemjs;837 var loaderConfig = {};838 for (var p in packageConfig)839 if (loaderConfigProperties.indexOf(p) != -1)840 loaderConfig[p] = packageConfig[p];841 if (packageConfig.modules && !packageConfig.meta)842 loaderConfig.meta = packageConfig.modules;843 if (!packageConfig.main) {844 if (packageConfig.main === false)845 delete loaderConfig.main;846 else847 ui.log('warn', 'Package `' + pkg.exactName + '` has no "main" entry point set in its package config.');848 }849 fs.writeFileSync(downloadDir + '.json', JSON.stringify(loaderConfig, null, 2));850 return Promise.resolve(loaderConfig);...

Full Screen

Full Screen

validateFilename.js

Source:validateFilename.js Github

copy

Full Screen

1import createPackageURL from '../utils/createPackageURL.js';2function filenameRedirect(req, res) {3 let filename;4 if (req.query.module != null) {5 // See https://github.com/rollup/rollup/wiki/pkg.module6 filename = req.packageConfig.module || req.packageConfig['jsnext:main'];7 if (!filename) {8 // https://nodejs.org/api/esm.html#esm_code_package_json_code_code_type_code_field9 if (req.packageConfig.type === 'module') {10 // Use whatever is in pkg.main or index.js11 filename = req.packageConfig.main || '/index.js';12 } else if (13 req.packageConfig.main &&14 /\.mjs$/.test(req.packageConfig.main)15 ) {16 // Use .mjs file in pkg.main17 filename = req.packageConfig.main;18 }19 }20 if (!filename) {21 return res22 .status(404)23 .type('text')24 .send(`Package ${req.packageSpec} does not contain an ES module`);25 }26 } else if (27 req.query.main &&28 req.packageConfig[req.query.main] &&29 typeof req.packageConfig[req.query.main] === 'string'30 ) {31 // Deprecated, see #6332 filename = req.packageConfig[req.query.main];33 } else if (34 req.packageConfig.unpkg &&35 typeof req.packageConfig.unpkg === 'string'36 ) {37 filename = req.packageConfig.unpkg;38 } else if (39 req.packageConfig.browser &&40 typeof req.packageConfig.browser === 'string'41 ) {42 // Deprecated, see #6343 filename = req.packageConfig.browser;44 } else {45 filename = req.packageConfig.main || '/index.js';46 }47 // Redirect to the exact filename so relative imports48 // and URLs resolve correctly.49 res50 .set({51 'Cache-Control': 'public, max-age=31536000', // 1 year52 'Cache-Tag': 'redirect, filename-redirect'53 })54 .redirect(55 302,56 createPackageURL(57 req.packageName,58 req.packageVersion,59 filename.replace(/^\/*/, '/'),60 req.query61 )62 );63}64/**65 * Redirect to the exact filename if the request omits one.66 */67export default async function validateFilename(req, res, next) {68 if (!req.filename) {69 return filenameRedirect(req, res);70 }71 next();...

Full Screen

Full Screen

bundle-config.js

Source:bundle-config.js Github

copy

Full Screen

1const fs = require('fs');2class BundleConfig {3 constructor(workDir) {4 this.templateFilename = 'src/template.carafe';5 this.configFilename = 'src/config.json';6 this.dataFilename = 'src/data.json';7 this.metaFilename = 'src/meta.json';8 this.previewFilename = 'src/preview.jpg';9 this.librariesDirname = 'src/libraries';10 this.sendFmpUrl = 'fmp://$/Carafe%20Kitchen?script=Send%20Carafe%20Bundle&param={sendConfig}';11 this.watchedFiles = {};12 if (!fs.existsSync(workDir + '/' + 'package.json')) {13 return;14 }15 const packageConfig = JSON.parse(fs.readFileSync(workDir + '/' + 'package.json'));16 if (!packageConfig.carafe) {17 return;18 }19 if (packageConfig.carafe.templateFilename) {20 this.templateFilename = packageConfig.carafe.templateFilename;21 }22 if (packageConfig.carafe.configFilename) {23 this.configFilename = packageConfig.carafe.configFilename;24 }25 if (packageConfig.carafe.dataFilename) {26 this.dataFilename = packageConfig.carafe.dataFilename;27 }28 if (packageConfig.carafe.metaFilename) {29 this.metaFilename = packageConfig.carafe.metaFilename;30 }31 if (packageConfig.carafe.previewFilename) {32 this.previewFilename = packageConfig.carafe.previewFilename;33 }34 if (packageConfig.carafe.librariesDirname) {35 this.librariesDirname = packageConfig.carafe.librariesDirname;36 }37 if (packageConfig.carafe.sendFmpUrl) {38 this.sendFmpUrl = packageConfig.carafe.sendFmpUrl;39 }40 if (packageConfig.carafe.watchedFiles) {41 this.watchedFiles = packageConfig.carafe.watchedFiles;42 }43 }44}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import {packageConfig} from 'ava';2const test = packageConfig({3});4test('test1', (t) => {5 t.pass();6});7test('test2', (t) => {8 t.pass();9});10import test from './test.js';11test('test1', (t) => {12 t.pass();13});14import test from './test.js';15test('test2', (t) => {16 t.pass();17});

Full Screen

Using AI Code Generation

copy

Full Screen

1var availablePackages = require('available-packages');2var packages = availablePackages.packageConfig();3console.log(packages);4var availablePackages = require('available-packages');5var packages = availablePackages.packageConfig();6console.log(packages);7var availablePackages = require('available-packages');8var packages = availablePackages.packageConfig();9console.log(packages);10var availablePackages = require('available-packages');11var packages = availablePackages.packageConfig();12console.log(packages);13var availablePackages = require('available-packages');14var packages = availablePackages.packageConfig();15console.log(packages);16var availablePackages = require('available-packages');17var packages = availablePackages.packageConfig();18console.log(packages);19var availablePackages = require('available-packages');20var packages = availablePackages.packageConfig();21console.log(packages);22var availablePackages = require('available-packages');23var packages = availablePackages.packageConfig();24console.log(packages);25var availablePackages = require('available-packages');26var packages = availablePackages.packageConfig();27console.log(packages);28var availablePackages = require('available-packages');29var packages = availablePackages.packageConfig();30console.log(packages);

Full Screen

Using AI Code Generation

copy

Full Screen

1const test = require('ava');2const packageConfig = require('package-config');3test('test', t => {4 const config = packageConfig('test');5 t.is(config.foo, 'bar');6});7{8 "ava": {9 },10 "config": {11 "test": {12 }13 }14}15const test = require('ava');16const packageConfig = require('package-config');17test('test', t => {18 const config = packageConfig('test');19 t.is(config.foo, 'bar');20});21{22 "ava": {23 },24 "config": {25 "test": {26 }27 }28}29const test = require('ava');30const packageConfig = require('package-config');31test('test', t => {32 const config = packageConfig('test');33 t.is(config.foo, 'bar');34});35{36 "ava": {37 },38 "config": {39 "test": {40 }41 }42}43const test = require('ava');44const packageConfig = require('package-config');45test('test', t => {46 const config = packageConfig('test');47 t.is(config.foo, 'bar');48});49{50 "ava": {51 },52 "config": {53 "test": {54 }55 }56}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { availablePackages } = require('package-config')2const packageConfig = require('package-config').availablePackages.packageConfig3const { availablePackages: { packageConfig } } = require('package-config')4const packageConfig = require('package-config').availablePackages.packageConfig5const { availablePackages: { packageConfig } } = require('package-config')6const packageConfig = require('package-config').availablePackages.packageConfig7const { availablePackages: { packageConfig } } = require('package-config')8const packageConfig = require('package-config').availablePackages.packageConfig9const { availablePackages: { packageConfig } } = require('package-config')10const packageConfig = require('package-config').availablePackages.packageConfig11const { availablePackages: { packageConfig } } = require('package-config')12const packageConfig = require('package-config').availablePackages.packageConfig13const { availablePackages: { packageConfig } } = require('package-config')14const packageConfig = require('package-config').availablePackages.packageConfig15const { availablePackages: { packageConfig } } = require('package-config')16const packageConfig = require('package-config').availablePackages.packageConfig17const { availablePackages: { packageConfig } } = require('package-config')18const packageConfig = require('package-config').availablePackages.packageConfig19const { availablePackages: { packageConfig } } = require('package-config')20const packageConfig = require('package-config').availablePackages.packageConfig21const { availablePackages: { packageConfig } } = require('package-config')22const packageConfig = require('package-config').availablePackages.packageConfig23const { availablePackages: { packageConfig } } = require('package-config')24const packageConfig = require('package-config').availablePackages.packageConfig

Full Screen

Using AI Code Generation

copy

Full Screen

1var packagemanager = require('packagemanager');2packagemanager.availablepackagelist.packageConfig('org.webosports.app.contacts', function (err, data) {3 console.log('packageConfig returned: ' + JSON.stringify(data));4});5var packagemanager = require('packagemanager');6packagemanager.availablepackagelist.packageConfig('org.webosports.app.contacts', function (err, data) {7 console.log('packageConfig returned: ' + JSON.stringify(data));8});

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 ava 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