0
Fork 0
mirror of https://github.com/verdaccio/verdaccio.git synced 2024-12-30 22:34:10 -05:00

refactor: no tabs, only spaces

disallow tabs over spaces
This commit is contained in:
Juan Picado @jotadeveloper 2018-04-30 18:34:55 +02:00
parent 101fd78b0d
commit 16fc854f57
No known key found for this signature in database
GPG key ID: 18AC54485952D158
7 changed files with 467 additions and 467 deletions

View file

@ -30,7 +30,7 @@
"__APP_VERSION__": true "__APP_VERSION__": true
}, },
"rules": { "rules": {
"no-tabs": 0, "no-tabs": 2,
"keyword-spacing": 0, "keyword-spacing": 0,
"padded-blocks": 0, "padded-blocks": 0,
"no-useless-escape": 0, "no-useless-escape": 0,

View file

@ -11,15 +11,15 @@ const pkgJSON = require('../../package.json');
* @return {String} security level * @return {String} security level
*/ */
function getlvl(x) { function getlvl(x) {
switch(true) { switch(true) {
case x < 15: return 'trace'; case x < 15: return 'trace';
case x < 25: return 'debug'; case x < 25: return 'debug';
case x < 35: return 'info'; case x < 35: return 'info';
case x == 35: return 'http'; case x == 35: return 'http';
case x < 45: return 'warn'; case x < 45: return 'warn';
case x < 55: return 'error'; case x < 55: return 'error';
default: return 'fatal'; default: return 'fatal';
} }
} }
/** /**
@ -27,75 +27,75 @@ function getlvl(x) {
* @param {*} logs list of log configuration * @param {*} logs list of log configuration
*/ */
function setup(logs) { function setup(logs) {
let streams = []; let streams = [];
if (logs == null) { if (logs == null) {
logs = [{type: 'stdout', format: 'pretty', level: 'http'}]; logs = [{type: 'stdout', format: 'pretty', level: 'http'}];
} }
logs.forEach(function(target) { logs.forEach(function(target) {
// create a stream for each log configuration // create a stream for each log configuration
const stream = new Stream(); const stream = new Stream();
stream.writable = true; stream.writable = true;
if (target.type === 'stdout' || target.type === 'stderr') { if (target.type === 'stdout' || target.type === 'stderr') {
// destination stream // destination stream
const dest = target.type === 'stdout' ? process.stdout : process.stderr; const dest = target.type === 'stdout' ? process.stdout : process.stderr;
if (target.format === 'pretty') { if (target.format === 'pretty') {
// making fake stream for prettypritting // making fake stream for prettypritting
stream.write = function(obj) { stream.write = function(obj) {
dest.write(print(obj.level, obj.msg, obj, dest.isTTY) + '\n'); dest.write(print(obj.level, obj.msg, obj, dest.isTTY) + '\n');
}; };
} else if (target.format === 'pretty-timestamped') { } else if (target.format === 'pretty-timestamped') {
// making fake stream for prettypritting // making fake stream for prettypritting
stream.write = function(obj) { stream.write = function(obj) {
dest.write(obj.time.toISOString() + print(obj.level, obj.msg, obj, dest.isTTY) + '\n'); dest.write(obj.time.toISOString() + print(obj.level, obj.msg, obj, dest.isTTY) + '\n');
}; };
} else { } else {
stream.write = function(obj) { stream.write = function(obj) {
dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n'); dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n');
}; };
} }
} else if (target.type === 'file') { } else if (target.type === 'file') {
const dest = require('fs').createWriteStream(target.path, {flags: 'a', encoding: 'utf8'}); const dest = require('fs').createWriteStream(target.path, {flags: 'a', encoding: 'utf8'});
dest.on('error', function(err) { dest.on('error', function(err) {
Logger.emit('error', err); Logger.emit('error', err);
}); });
stream.write = function(obj) { stream.write = function(obj) {
if (target.format === 'pretty') { if (target.format === 'pretty') {
dest.write(print(obj.level, obj.msg, obj, false) + '\n'); dest.write(print(obj.level, obj.msg, obj, false) + '\n');
} else { } else {
dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n'); dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n');
} }
}; };
} else { } else {
throw Error('wrong target type for a log'); throw Error('wrong target type for a log');
} }
if (target.level === 'http') target.level = 35; if (target.level === 'http') target.level = 35;
streams.push({ streams.push({
type: 'raw', type: 'raw',
level: target.level || 35, level: target.level || 35,
stream: stream, stream: stream,
}); });
}); });
// buyan default configuration // buyan default configuration
const logger = new Logger({ const logger = new Logger({
name: pkgJSON.name, name: pkgJSON.name,
streams: streams, streams: streams,
serializers: { serializers: {
err: Logger.stdSerializers.err, err: Logger.stdSerializers.err,
req: Logger.stdSerializers.req, req: Logger.stdSerializers.req,
res: Logger.stdSerializers.res, res: Logger.stdSerializers.res,
}, },
}); });
process.on('SIGUSR2', function() { process.on('SIGUSR2', function() {
Logger.reopenFileStreams(); Logger.reopenFileStreams();
}); });
module.exports.logger = logger; module.exports.logger = logger;
} }
// adopted from socket.io // adopted from socket.io
@ -104,20 +104,20 @@ function setup(logs) {
// level to color // level to color
const levels = { const levels = {
fatal: chalk.red, fatal: chalk.red,
error: chalk.red, error: chalk.red,
warn: chalk.yellow, warn: chalk.yellow,
http: chalk.magenta, http: chalk.magenta,
info: chalk.cyan, info: chalk.cyan,
debug: chalk.green, debug: chalk.green,
trace: chalk.white, trace: chalk.white,
}; };
let max = 0; let max = 0;
for (let l in levels) { for (let l in levels) {
if (Object.prototype.hasOwnProperty.call(levels, l)) { if (Object.prototype.hasOwnProperty.call(levels, l)) {
max = Math.max(max, l.length); max = Math.max(max, l.length);
} }
} }
/** /**
@ -126,10 +126,10 @@ for (let l in levels) {
* @return {String} * @return {String}
*/ */
function pad(str) { function pad(str) {
if (str.length < max) { if (str.length < max) {
return str + ' '.repeat(max - str.length); return str + ' '.repeat(max - str.length);
} }
return str; return str;
} }
/** /**
@ -141,58 +141,58 @@ function pad(str) {
* @return {String} * @return {String}
*/ */
function print(type, msg, obj, colors) { function print(type, msg, obj, colors) {
if (typeof type === 'number') { if (typeof type === 'number') {
type = getlvl(type); type = getlvl(type);
} }
let finalmsg = msg.replace(/@{(!?[$A-Za-z_][$0-9A-Za-z\._]*)}/g, function(_, name) { let finalmsg = msg.replace(/@{(!?[$A-Za-z_][$0-9A-Za-z\._]*)}/g, function(_, name) {
let str = obj; let str = obj;
let is_error; let is_error;
if (name[0] === '!') { if (name[0] === '!') {
name = name.substr(1); name = name.substr(1);
is_error = true; is_error = true;
} }
let _ref = name.split('.'); let _ref = name.split('.');
for (let _i = 0; _i < _ref.length; _i++) { for (let _i = 0; _i < _ref.length; _i++) {
let id = _ref[_i]; let id = _ref[_i];
if (Utils.isObject(str) || Array.isArray(str)) { if (Utils.isObject(str) || Array.isArray(str)) {
str = str[id]; str = str[id];
} else { } else {
str = undefined; str = undefined;
} }
} }
if (typeof(str) === 'string') { if (typeof(str) === 'string') {
if (!colors || str.includes('\n')) { if (!colors || str.includes('\n')) {
return str; return str;
} else if (is_error) { } else if (is_error) {
return chalk.red(str); return chalk.red(str);
} else { } else {
return chalk.green(str); return chalk.green(str);
} }
} else { } else {
return require('util').inspect(str, null, null, colors); return require('util').inspect(str, null, null, colors);
} }
}); });
const subsystems = [{ const subsystems = [{
in: chalk.green('<--'), in: chalk.green('<--'),
out: chalk.yellow('-->'), out: chalk.yellow('-->'),
fs: chalk.black('-=-'), fs: chalk.black('-=-'),
default: chalk.blue('---'), default: chalk.blue('---'),
}, { }, {
in: '<--', in: '<--',
out: '-->', out: '-->',
fs: '-=-', fs: '-=-',
default: '---', default: '---',
}]; }];
const sub = subsystems[colors ? 0 : 1][obj.sub] || subsystems[+!colors].default; const sub = subsystems[colors ? 0 : 1][obj.sub] || subsystems[+!colors].default;
if (colors) { if (colors) {
return ` ${levels[type]((pad(type)))}${chalk.white(`${sub} ${finalmsg}`)}`; return ` ${levels[type]((pad(type)))}${chalk.white(`${sub} ${finalmsg}`)}`;
} else { } else {
return ` ${(pad(type))}${sub} ${finalmsg}`; return ` ${(pad(type))}${sub} ${finalmsg}`;
} }
} }
module.exports.setup = setup; module.exports.setup = setup;

View file

@ -9,11 +9,11 @@ import type {Package} from '@verdaccio/types';
/** /**
* Function gets a local info and an info from uplinks and tries to merge it * Function gets a local info and an info from uplinks and tries to merge it
exported for unit tests only. exported for unit tests only.
* @param {*} local * @param {*} local
* @param {*} up * @param {*} up
* @param {*} config * @param {*} config
* @static * @static
*/ */
export function mergeVersions(local: Package, up: Package) { export function mergeVersions(local: Package, up: Package) {
// copy new versions to a cache // copy new versions to a cache
// NOTE: if a certain version was updated, we can't refresh it reliably // NOTE: if a certain version was updated, we can't refresh it reliably

View file

@ -32,7 +32,7 @@ class Search implements IWebSearch {
* @return {Array} list of results. * @return {Array} list of results.
*/ */
query(query: string) { query(query: string) {
return query === '*' return query === '*'
? this.storage.localStorage.localData.get((items) => { ? this.storage.localStorage.localData.get((items) => {
items.map( function( pkg ) { items.map( function( pkg ) {
return {ref: pkg, score: 1}; return {ref: pkg, score: 1};

View file

@ -9,99 +9,99 @@ import type {IProxy, ProxyList} from '../../types';
/** /**
* Set up the Up Storage for each link. * Set up the Up Storage for each link.
*/ */
export function setupUpLinks(config: Config): ProxyList { export function setupUpLinks(config: Config): ProxyList {
const uplinks: ProxyList = {}; const uplinks: ProxyList = {};
for (let uplinkName in config.uplinks) { for (let uplinkName in config.uplinks) {
if (Object.prototype.hasOwnProperty.call(config.uplinks, uplinkName)) { if (Object.prototype.hasOwnProperty.call(config.uplinks, uplinkName)) {
// instance for each up-link definition // instance for each up-link definition
const proxy: IProxy = new ProxyStorage(config.uplinks[uplinkName], config); const proxy: IProxy = new ProxyStorage(config.uplinks[uplinkName], config);
proxy.upname = uplinkName; proxy.upname = uplinkName;
uplinks[uplinkName] = proxy; uplinks[uplinkName] = proxy;
} }
} }
return uplinks; return uplinks;
} }
export function updateVersionsHiddenUpLink(versions: Versions, upLink: IProxy) { export function updateVersionsHiddenUpLink(versions: Versions, upLink: IProxy) {
for (let i in versions) { for (let i in versions) {
if (Object.prototype.hasOwnProperty.call(versions, i)) { if (Object.prototype.hasOwnProperty.call(versions, i)) {
const version = versions[i]; const version = versions[i];
// holds a "hidden" value to be used by the package storage. // holds a "hidden" value to be used by the package storage.
// $FlowFixMe // $FlowFixMe
version[Symbol.for('__verdaccio_uplink')] = upLink.upname; version[Symbol.for('__verdaccio_uplink')] = upLink.upname;
} }
} }
} }
export function fetchUplinkMetadata(name: string, packageInfo: Package, export function fetchUplinkMetadata(name: string, packageInfo: Package,
options: any, upLink: any, logger: Logger): Promise<any> { options: any, upLink: any, logger: Logger): Promise<any> {
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
const _options = Object.assign({}, options); const _options = Object.assign({}, options);
const upLinkMeta = packageInfo._uplinks[upLink.upname]; const upLinkMeta = packageInfo._uplinks[upLink.upname];
if (isObject(upLinkMeta)) { if (isObject(upLinkMeta)) {
const fetched = upLinkMeta.fetched; const fetched = upLinkMeta.fetched;
// check whether is too soon to ask for metadata // check whether is too soon to ask for metadata
if (fetched && (Date.now() - fetched) < upLink.maxage) { if (fetched && (Date.now() - fetched) < upLink.maxage) {
return resolve(false); return resolve(false);
} }
_options.etag = upLinkMeta.etag; _options.etag = upLinkMeta.etag;
} }
upLink.getRemoteMetadata(name, _options, function handleUplinkMetadataResponse(err, upLinkResponse, eTag) { upLink.getRemoteMetadata(name, _options, function handleUplinkMetadataResponse(err, upLinkResponse, eTag) {
if (err && err.remoteStatus === 304) { if (err && err.remoteStatus === 304) {
upLinkMeta.fetched = Date.now(); upLinkMeta.fetched = Date.now();
} }
if (err || !upLinkResponse) { if (err || !upLinkResponse) {
// $FlowFixMe // $FlowFixMe
return reject(err || ErrorCode.get500('no data')); return reject(err || ErrorCode.get500('no data'));
} }
try { try {
validate_metadata(upLinkResponse, name); validate_metadata(upLinkResponse, name);
} catch(err) { } catch(err) {
logger.error({ logger.error({
sub: 'out', sub: 'out',
err: err, err: err,
}, 'package.json validating error @{!err.message}\n@{err.stack}'); }, 'package.json validating error @{!err.message}\n@{err.stack}');
return reject(err); return reject(err);
} }
packageInfo._uplinks[upLink.upname] = { packageInfo._uplinks[upLink.upname] = {
etag: eTag, etag: eTag,
fetched: Date.now(), fetched: Date.now(),
}; };
// added to fix verdaccio#73 // added to fix verdaccio#73
if ('time' in upLinkResponse) { if ('time' in upLinkResponse) {
packageInfo.time = upLinkResponse.time; packageInfo.time = upLinkResponse.time;
} }
updateVersionsHiddenUpLink(upLinkResponse.versions, upLink); updateVersionsHiddenUpLink(upLinkResponse.versions, upLink);
try { try {
mergeVersions(packageInfo, upLinkResponse); mergeVersions(packageInfo, upLinkResponse);
} catch(err) { } catch(err) {
logger.error({ logger.error({
sub: 'out', sub: 'out',
err: err, err: err,
}, 'package.json parsing error @{!err.message}\n@{err.stack}'); }, 'package.json parsing error @{!err.message}\n@{err.stack}');
return reject(err); return reject(err);
} }
// if we got to this point, assume that the correct package exists // if we got to this point, assume that the correct package exists
// on the uplink // on the uplink
resolve(true); resolve(true);
}); });
}); });
} }

View file

@ -21,16 +21,16 @@ export const DIST_TAGS = 'dist-tags';
* @return {Boolean} whether the package is valid or not * @return {Boolean} whether the package is valid or not
*/ */
function validate_package(name: any): boolean { function validate_package(name: any): boolean {
name = name.split('/', 2); name = name.split('/', 2);
if (name.length === 1) { if (name.length === 1) {
// normal package // normal package
return module.exports.validate_name(name[0]); return module.exports.validate_name(name[0]);
} else { } else {
// scoped package // scoped package
return name[0][0] === '@' return name[0][0] === '@'
&& module.exports.validate_name(name[0].slice(1)) && module.exports.validate_name(name[0].slice(1))
&& module.exports.validate_name(name[1]); && module.exports.validate_name(name[1]);
} }
} }
/** /**
@ -39,20 +39,20 @@ function validate_package(name: any): boolean {
* @return {Boolean} whether is valid or not * @return {Boolean} whether is valid or not
*/ */
function validate_name(name: string): boolean { function validate_name(name: string): boolean {
if (_.isString(name) === false) { if (_.isString(name) === false) {
return false; return false;
} }
name = name.toLowerCase(); name = name.toLowerCase();
// all URL-safe characters and "@" for issue #75 // all URL-safe characters and "@" for issue #75
return !(!name.match(/^[-a-zA-Z0-9_.!~*'()@]+$/) return !(!name.match(/^[-a-zA-Z0-9_.!~*'()@]+$/)
|| name.charAt(0) === '.' // ".bin", etc. || name.charAt(0) === '.' // ".bin", etc.
|| name.charAt(0) === '-' // "-" is reserved by couchdb || name.charAt(0) === '-' // "-" is reserved by couchdb
|| name === 'node_modules' || name === 'node_modules'
|| name === '__proto__' || name === '__proto__'
|| name === 'package.json' || name === 'package.json'
|| name === 'favicon.ico' || name === 'favicon.ico'
); );
} }
/** /**
@ -61,7 +61,7 @@ function validate_name(name: string): boolean {
* @return {Boolean} * @return {Boolean}
*/ */
function isObject(obj: any): boolean { function isObject(obj: any): boolean {
return _.isObject(obj) && _.isNull(obj) === false && _.isArray(obj) === false; return _.isObject(obj) && _.isNull(obj) === false && _.isArray(obj) === false;
} }
/** /**
@ -72,18 +72,18 @@ function isObject(obj: any): boolean {
* @return {Object} the object with additional properties as dist-tags ad versions * @return {Object} the object with additional properties as dist-tags ad versions
*/ */
function validate_metadata(object: Package, name: string) { function validate_metadata(object: Package, name: string) {
assert(isObject(object), 'not a json object'); assert(isObject(object), 'not a json object');
assert.equal(object.name, name); assert.equal(object.name, name);
if (!isObject(object[DIST_TAGS])) { if (!isObject(object[DIST_TAGS])) {
object[DIST_TAGS] = {}; object[DIST_TAGS] = {};
} }
if (!isObject(object['versions'])) { if (!isObject(object['versions'])) {
object['versions'] = {}; object['versions'] = {};
} }
return object; return object;
} }
/** /**
@ -91,17 +91,17 @@ function validate_metadata(object: Package, name: string) {
* @return {String} base registry url * @return {String} base registry url
*/ */
function combineBaseUrl(protocol: string, host: string, prefix?: string): string { function combineBaseUrl(protocol: string, host: string, prefix?: string): string {
let result = `${protocol}://${host}`; let result = `${protocol}://${host}`;
if (prefix) { if (prefix) {
prefix = prefix.replace(/\/$/, ''); prefix = prefix.replace(/\/$/, '');
result = (prefix.indexOf('/') === 0) result = (prefix.indexOf('/') === 0)
? `${result}${prefix}` ? `${result}${prefix}`
: prefix; : prefix;
} }
return result; return result;
} }
/** /**
@ -112,31 +112,31 @@ function combineBaseUrl(protocol: string, host: string, prefix?: string): string
* @return {String} a filtered package * @return {String} a filtered package
*/ */
function filter_tarball_urls(pkg: Package, req: $Request, config: Config) { function filter_tarball_urls(pkg: Package, req: $Request, config: Config) {
/** /**
* Filter a tarball url. * Filter a tarball url.
* @param {*} _url * @param {*} _url
* @return {String} a parsed url * @return {String} a parsed url
*/ */
const filter = function(_url) { const filter = function(_url) {
if (!req.headers.host) { if (!req.headers.host) {
return _url; return _url;
} }
// $FlowFixMe // $FlowFixMe
const filename = URL.parse(_url).pathname.replace(/^.*\//, ''); const filename = URL.parse(_url).pathname.replace(/^.*\//, '');
const base = combineBaseUrl(getWebProtocol(req), req.headers.host, config.url_prefix); const base = combineBaseUrl(getWebProtocol(req), req.headers.host, config.url_prefix);
return `${base}/${pkg.name.replace(/\//g, '%2f')}/-/${filename}`; return `${base}/${pkg.name.replace(/\//g, '%2f')}/-/${filename}`;
}; };
for (let ver in pkg.versions) { for (let ver in pkg.versions) {
if (Object.prototype.hasOwnProperty.call(pkg.versions, ver)) { if (Object.prototype.hasOwnProperty.call(pkg.versions, ver)) {
const dist = pkg.versions[ver].dist; const dist = pkg.versions[ver].dist;
if (_.isNull(dist) === false && _.isNull(dist.tarball) === false) { if (_.isNull(dist) === false && _.isNull(dist.tarball) === false) {
dist.tarball = filter(dist.tarball); dist.tarball = filter(dist.tarball);
} }
} }
} }
return pkg; return pkg;
} }
/** /**
@ -147,20 +147,20 @@ function filter_tarball_urls(pkg: Package, req: $Request, config: Config) {
* @return {Boolean} whether a package has been tagged * @return {Boolean} whether a package has been tagged
*/ */
function tagVersion(data: Package, version: string, tag: StringValue) { function tagVersion(data: Package, version: string, tag: StringValue) {
if (tag) { if (tag) {
if (data[DIST_TAGS][tag] !== version) { if (data[DIST_TAGS][tag] !== version) {
if (semver.parse(version, true)) { if (semver.parse(version, true)) {
// valid version - store // valid version - store
data[DIST_TAGS][tag] = version; data[DIST_TAGS][tag] = version;
return true; return true;
} }
} }
Logger.logger.warn({ver: version, tag: tag}, 'ignoring bad version @{ver} in @{tag}'); Logger.logger.warn({ver: version, tag: tag}, 'ignoring bad version @{ver} in @{tag}');
if (tag && data[DIST_TAGS][tag]) { if (tag && data[DIST_TAGS][tag]) {
delete data[DIST_TAGS][tag]; delete data[DIST_TAGS][tag];
} }
} }
return false; return false;
} }
/** /**
@ -168,63 +168,63 @@ function tagVersion(data: Package, version: string, tag: StringValue) {
* @return {String} return the semantic version of a package * @return {String} return the semantic version of a package
*/ */
function get_version(pkg: Package, version: any) { function get_version(pkg: Package, version: any) {
// this condition must allow cast // this condition must allow cast
if (pkg.versions[version] != null) { if (pkg.versions[version] != null) {
return pkg.versions[version]; return pkg.versions[version];
} }
try { try {
version = semver.parse(version, true); version = semver.parse(version, true);
for (let versionItem in pkg.versions) { for (let versionItem in pkg.versions) {
// $FlowFixMe // $FlowFixMe
if (version.compare(semver.parse(versionItem, true)) === 0) { if (version.compare(semver.parse(versionItem, true)) === 0) {
return pkg.versions[versionItem]; return pkg.versions[versionItem];
} }
} }
} catch (err) { } catch (err) {
return undefined; return undefined;
} }
} }
/** /**
* Parse an internet address * Parse an internet address
* Allow: * Allow:
- https:localhost:1234 - protocol + host + port - https:localhost:1234 - protocol + host + port
- localhost:1234 - host + port - localhost:1234 - host + port
- 1234 - port - 1234 - port
- http::1234 - protocol + port - http::1234 - protocol + port
- https://localhost:443/ - full url + https - https://localhost:443/ - full url + https
- http://[::1]:443/ - ipv6 - http://[::1]:443/ - ipv6
- unix:/tmp/http.sock - unix sockets - unix:/tmp/http.sock - unix sockets
- https://unix:/tmp/http.sock - unix sockets (https) - https://unix:/tmp/http.sock - unix sockets (https)
* @param {*} urlAddress the internet address definition * @param {*} urlAddress the internet address definition
* @return {Object|Null} literal object that represent the address parsed * @return {Object|Null} literal object that represent the address parsed
*/ */
function parse_address(urlAddress: any) { function parse_address(urlAddress: any) {
// //
// TODO: refactor it to something more reasonable? // TODO: refactor it to something more reasonable?
// //
// protocol : // ( host )|( ipv6 ): port / // protocol : // ( host )|( ipv6 ): port /
let urlPattern = /^((https?):(\/\/)?)?((([^\/:]*)|\[([^\[\]]+)\]):)?(\d+)\/?$/.exec(urlAddress); let urlPattern = /^((https?):(\/\/)?)?((([^\/:]*)|\[([^\[\]]+)\]):)?(\d+)\/?$/.exec(urlAddress);
if (urlPattern) { if (urlPattern) {
return { return {
proto: urlPattern[2] || 'http', proto: urlPattern[2] || 'http',
host: urlPattern[6] || urlPattern[7] || 'localhost', host: urlPattern[6] || urlPattern[7] || 'localhost',
port: urlPattern[8] || '4873', port: urlPattern[8] || '4873',
}; };
} }
urlPattern = /^((https?):(\/\/)?)?unix:(.*)$/.exec(urlAddress); urlPattern = /^((https?):(\/\/)?)?unix:(.*)$/.exec(urlAddress);
if (urlPattern) { if (urlPattern) {
return { return {
proto: urlPattern[2] || 'http', proto: urlPattern[2] || 'http',
path: urlPattern[4], path: urlPattern[4],
}; };
} }
return null; return null;
} }
/** /**
@ -232,15 +232,15 @@ function parse_address(urlAddress: any) {
* @return {Array} sorted Array * @return {Array} sorted Array
*/ */
function semverSort(listVersions: Array<string>) { function semverSort(listVersions: Array<string>) {
return listVersions.filter(function(x) { return listVersions.filter(function(x) {
if (!semver.parse(x, true)) { if (!semver.parse(x, true)) {
Logger.logger.warn( {ver: x}, 'ignoring bad version @{ver}' ); Logger.logger.warn( {ver: x}, 'ignoring bad version @{ver}' );
return false; return false;
} }
return true; return true;
}) })
.sort(semver.compareLoose) .sort(semver.compareLoose)
.map(String); .map(String);
} }
/** /**
@ -248,35 +248,35 @@ function semverSort(listVersions: Array<string>) {
* @param {*} data * @param {*} data
*/ */
export function normalizeDistTags(pkg: Package) { export function normalizeDistTags(pkg: Package) {
let sorted; let sorted;
if (!pkg[DIST_TAGS].latest) { if (!pkg[DIST_TAGS].latest) {
// overwrite latest with highest known version based on semver sort // overwrite latest with highest known version based on semver sort
sorted = semverSort(Object.keys(pkg.versions)); sorted = semverSort(Object.keys(pkg.versions));
if (sorted && sorted.length) { if (sorted && sorted.length) {
pkg[DIST_TAGS].latest = sorted.pop(); pkg[DIST_TAGS].latest = sorted.pop();
} }
} }
for (let tag in pkg[DIST_TAGS]) { for (let tag in pkg[DIST_TAGS]) {
if (_.isArray(pkg[DIST_TAGS][tag])) { if (_.isArray(pkg[DIST_TAGS][tag])) {
if (pkg[DIST_TAGS][tag].length) { if (pkg[DIST_TAGS][tag].length) {
// sort array // sort array
// $FlowFixMe // $FlowFixMe
sorted = semverSort(pkg[DIST_TAGS][tag]); sorted = semverSort(pkg[DIST_TAGS][tag]);
if (sorted.length) { if (sorted.length) {
// use highest version based on semver sort // use highest version based on semver sort
pkg[DIST_TAGS][tag] = sorted.pop(); pkg[DIST_TAGS][tag] = sorted.pop();
} }
} else { } else {
delete pkg[DIST_TAGS][tag]; delete pkg[DIST_TAGS][tag];
} }
} else if (_.isString(pkg[DIST_TAGS][tag] )) { } else if (_.isString(pkg[DIST_TAGS][tag] )) {
if (!semver.parse(pkg[DIST_TAGS][tag], true)) { if (!semver.parse(pkg[DIST_TAGS][tag], true)) {
// if the version is invalid, delete the dist-tag entry // if the version is invalid, delete the dist-tag entry
delete pkg[DIST_TAGS][tag]; delete pkg[DIST_TAGS][tag];
} }
} }
} }
} }
const parseIntervalTable = { const parseIntervalTable = {
@ -350,10 +350,10 @@ const ErrorCode = {
}, },
get404: (customMessage?: string) => { get404: (customMessage?: string) => {
return createError(404, customMessage || 'no such package available'); return createError(404, customMessage || 'no such package available');
}, },
getCode: (statusCode: number, customMessage: string) => { getCode: (statusCode: number, customMessage: string) => {
return createError(statusCode, customMessage); return createError(statusCode, customMessage);
}, },
}; };
const parseConfigFile = (configPath: string) => YAML.safeLoad(fs.readFileSync(configPath, 'utf8')); const parseConfigFile = (configPath: string) => YAML.safeLoad(fs.readFileSync(configPath, 'utf8'));
@ -433,25 +433,25 @@ function addGravatarSupport(pkgInfo: any) {
} }
export { export {
addGravatarSupport, addGravatarSupport,
deleteProperties, deleteProperties,
addScope, addScope,
sortByName, sortByName,
folder_exists, folder_exists,
fileExists, fileExists,
parseInterval, parseInterval,
semverSort, semverSort,
parse_address, parse_address,
get_version, get_version,
tagVersion, tagVersion,
combineBaseUrl, combineBaseUrl,
filter_tarball_urls, filter_tarball_urls,
validate_metadata, validate_metadata,
isObject, isObject,
validate_name, validate_name,
validate_package, validate_package,
getWebProtocol, getWebProtocol,
getLatestVersion, getLatestVersion,
ErrorCode, ErrorCode,
parseConfigFile, parseConfigFile,
}; };

View file

@ -1,17 +1,17 @@
// @flow // @flow
import type { import type {
UpLinkConf, UpLinkConf,
Callback, Callback,
Versions, Versions,
Version, Version,
MergeTags, MergeTags,
Config, Config,
Logger, Logger,
Package} from '@verdaccio/types'; Package} from '@verdaccio/types';
import type { import type {
IUploadTarball, IUploadTarball,
IReadTarball, IReadTarball,
} from '@verdaccio/streams'; } from '@verdaccio/streams';
import type {ILocalData} from '@verdaccio/local-storage'; import type {ILocalData} from '@verdaccio/local-storage';
import type {NextFunction, $Request, $Response} from 'request'; import type {NextFunction, $Request, $Response} from 'request';
@ -19,98 +19,98 @@ import type {NextFunction, $Request, $Response} from 'request';
export type StringValue = string | void | null; export type StringValue = string | void | null;
export interface IAuth { export interface IAuth {
config: Config; config: Config;
logger: Logger; logger: Logger;
secret: string; secret: string;
plugins: Array<any>; plugins: Array<any>;
aes_encrypt(buf: Buffer): Buffer; aes_encrypt(buf: Buffer): Buffer;
apiJWTmiddleware(): $NextFunctionVer; apiJWTmiddleware(): $NextFunctionVer;
webUIJWTmiddleware(): $NextFunctionVer; webUIJWTmiddleware(): $NextFunctionVer;
authenticate(user: string, password: string, cb: Callback): void; authenticate(user: string, password: string, cb: Callback): void;
allow_access(packageName: string, user: string, callback: Callback): void; allow_access(packageName: string, user: string, callback: Callback): void;
issueUIjwt(user: string, time: string): string; issueUIjwt(user: string, time: string): string;
add_user(user: string, password: string, cb: Callback): any; add_user(user: string, password: string, cb: Callback): any;
} }
export interface IWebSearch { export interface IWebSearch {
index: any; index: any;
storage: IStorageHandler; storage: IStorageHandler;
query(query: string): any; query(query: string): any;
add(pkg: Version): void; add(pkg: Version): void;
remove(name: string): void; remove(name: string): void;
reindex(): void; reindex(): void;
configureStorage(storage: IStorageHandler): void; configureStorage(storage: IStorageHandler): void;
} }
export interface IProxy { export interface IProxy {
config: UpLinkConf; config: UpLinkConf;
failed_requests: number; failed_requests: number;
userAgent: string; userAgent: string;
ca?: string | void; ca?: string | void;
logger: Logger; logger: Logger;
server_id: string; server_id: string;
url: any; url: any;
maxage: number; maxage: number;
timeout: number; timeout: number;
max_fails: number; max_fails: number;
fail_timeout: number; fail_timeout: number;
upname: string; upname: string;
fetchTarball(url: string): IReadTarball; fetchTarball(url: string): IReadTarball;
isUplinkValid(url: string): boolean; isUplinkValid(url: string): boolean;
getRemoteMetadata(name: string, options: any, callback: Callback): void; getRemoteMetadata(name: string, options: any, callback: Callback): void;
} }
export type ProxyList = { export type ProxyList = {
[key: string]: IProxy; [key: string]: IProxy;
} }
export type Utils = { export type Utils = {
ErrorCode: any; ErrorCode: any;
getLatestVersion: Callback; getLatestVersion: Callback;
isObject: (value: any) => boolean; isObject: (value: any) => boolean;
validate_name: (value: any) => boolean; validate_name: (value: any) => boolean;
tag_version: (value: any, version: string, tag: string) => void; tag_version: (value: any, version: string, tag: string) => void;
normalizeDistTags: (pkg: Package) => void; normalizeDistTags: (pkg: Package) => void;
semverSort: (keys: Array<string>) => Array<string>; semverSort: (keys: Array<string>) => Array<string>;
} }
export interface IStorageHandler { export interface IStorageHandler {
config: Config; config: Config;
localStorage: IStorage; localStorage: IStorage;
logger: Logger; logger: Logger;
uplinks: ProxyList; uplinks: ProxyList;
addPackage(name: string, metadata: any, callback: Function): Promise<any>; addPackage(name: string, metadata: any, callback: Function): Promise<any>;
init(config: Config): Promise<any>; init(config: Config): Promise<any>;
addVersion(name: string, version: string, metadata: Version, tag: StringValue, callback: Callback): void; addVersion(name: string, version: string, metadata: Version, tag: StringValue, callback: Callback): void;
mergeTags(name: string, tagHash: MergeTags, callback: Callback): void; mergeTags(name: string, tagHash: MergeTags, callback: Callback): void;
replaceTags(name: string, tagHash: MergeTags, callback: Callback): void; replaceTags(name: string, tagHash: MergeTags, callback: Callback): void;
changePackage(name: string, metadata: Package, revision: string, callback: Callback): void; changePackage(name: string, metadata: Package, revision: string, callback: Callback): void;
removePackage(name: string, callback: Callback): void; removePackage(name: string, callback: Callback): void;
removeTarball(name: string, filename: string, revision: string, callback: Callback): void; removeTarball(name: string, filename: string, revision: string, callback: Callback): void;
addTarball(name: string, filename: string): IUploadTarball; addTarball(name: string, filename: string): IUploadTarball;
getTarball(name: string, filename: string): IReadTarball; getTarball(name: string, filename: string): IReadTarball;
getPackage(options: any): void; getPackage(options: any): void;
search(startkey: string, options: any): void; search(startkey: string, options: any): void;
getLocalDatabase(callback: Callback): void; getLocalDatabase(callback: Callback): void;
_syncUplinksMetadata(name: string, packageInfo: Package, options: any, callback: Callback): void; _syncUplinksMetadata(name: string, packageInfo: Package, options: any, callback: Callback): void;
_updateVersionsHiddenUpLink(versions: Versions, upLink: IProxy): void; _updateVersionsHiddenUpLink(versions: Versions, upLink: IProxy): void;
} }
export interface IStorage { export interface IStorage {
config: Config; config: Config;
localData: ILocalData; localData: ILocalData;
logger: Logger; logger: Logger;
addPackage(name: string, info: Package, callback: Callback): void; addPackage(name: string, info: Package, callback: Callback): void;
removePackage(name: string, callback: Callback): void; removePackage(name: string, callback: Callback): void;
updateVersions(name: string, packageInfo: Package, callback: Callback): void; updateVersions(name: string, packageInfo: Package, callback: Callback): void;
addVersion(name: string, version: string, metadata: Version, tag: StringValue, callback: Callback): void; addVersion(name: string, version: string, metadata: Version, tag: StringValue, callback: Callback): void;
mergeTags(name: string, tags: MergeTags, callback: Callback): void; mergeTags(name: string, tags: MergeTags, callback: Callback): void;
changePackage(name: string, metadata: Package, revision: string, callback: Callback): void; changePackage(name: string, metadata: Package, revision: string, callback: Callback): void;
removeTarball(name: string, filename: string, revision: string, callback: Callback): void; removeTarball(name: string, filename: string, revision: string, callback: Callback): void;
addTarball(name: string, filename: string): IUploadTarball; addTarball(name: string, filename: string): IUploadTarball;
getTarball(name: string, filename: string): IReadTarball; getTarball(name: string, filename: string): IReadTarball;
getPackageMetadata(name: string, callback: Callback): void; getPackageMetadata(name: string, callback: Callback): void;
search(startKey: string, options: any): IUploadTarball; search(startKey: string, options: any): IUploadTarball;
getSecret(config: Config): Promise<any>; getSecret(config: Config): Promise<any>;
} }