ci: Add lint rule for mandatory curly braces (#9348)

This commit is contained in:
Manuel
2024-10-16 19:57:42 +02:00
committed by GitHub
parent 714acaa906
commit dfd5a8edbf
22 changed files with 145 additions and 137 deletions

View File

@@ -25,7 +25,9 @@
"space-infix-ops": "error", "space-infix-ops": "error",
"no-useless-escape": "off", "no-useless-escape": "off",
"require-atomic-updates": "off", "require-atomic-updates": "off",
"object-curly-spacing": ["error", "always"] "object-curly-spacing": ["error", "always"],
"curly": ["error", "all"],
"block-spacing": ["error", "always"]
}, },
"globals": { "globals": {
"Parse": true "Parse": true

View File

@@ -11,7 +11,7 @@ function newServer(port, dn, provokeSearchError = false, ssl = false) {
server.bind('o=example', function (req, res, next) { server.bind('o=example', function (req, res, next) {
if (req.dn.toString() !== dn || req.credentials !== 'secret') if (req.dn.toString() !== dn || req.credentials !== 'secret')
return next(new ldapjs.InvalidCredentialsError()); { return next(new ldapjs.InvalidCredentialsError()); }
res.end(); res.end();
return next(); return next();
}); });

View File

@@ -122,7 +122,7 @@ OAuth.nonce = function () {
var text = ''; var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < 30; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); for (var i = 0; i < 30; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); }
return text; return text;
}; };

View File

@@ -215,7 +215,7 @@ module.exports = function (authOptions = {}, enableAnonymousUsers = true) {
return { validator: undefined }; return { validator: undefined };
} }
const authAdapter = loadAuthAdapter(provider, authOptions); const authAdapter = loadAuthAdapter(provider, authOptions);
if (!authAdapter) return; if (!authAdapter) { return; }
const { adapter, appIds, providerOptions } = authAdapter; const { adapter, appIds, providerOptions } = authAdapter;
return { validator: authDataValidator(provider, adapter, appIds, providerOptions), adapter }; return { validator: authDataValidator(provider, adapter, appIds, providerOptions), adapter };
}; };

View File

@@ -37,13 +37,13 @@ const { Parse } = require('parse/node');
const httpsRequest = require('./httpsRequest'); const httpsRequest = require('./httpsRequest');
const arraysEqual = (_arr1, _arr2) => { const arraysEqual = (_arr1, _arr2) => {
if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length) return false; if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length) { return false; }
var arr1 = _arr1.concat().sort(); var arr1 = _arr1.concat().sort();
var arr2 = _arr2.concat().sort(); var arr2 = _arr2.concat().sort();
for (var i = 0; i < arr1.length; i++) { for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false; if (arr1[i] !== arr2[i]) { return false; }
} }
return true; return true;

View File

@@ -434,11 +434,11 @@ const findUsersWithAuthData = (config, authData) => {
}; };
const hasMutatedAuthData = (authData, userAuthData) => { const hasMutatedAuthData = (authData, userAuthData) => {
if (!userAuthData) return { hasMutatedAuthData: true, mutatedAuthData: authData }; if (!userAuthData) { return { hasMutatedAuthData: true, mutatedAuthData: authData }; }
const mutatedAuthData = {}; const mutatedAuthData = {};
Object.keys(authData).forEach(provider => { Object.keys(authData).forEach(provider => {
// Anonymous provider is not handled this way // Anonymous provider is not handled this way
if (provider === 'anonymous') return; if (provider === 'anonymous') { return; }
const providerData = authData[provider]; const providerData = authData[provider];
const userProviderAuthData = userAuthData[provider]; const userProviderAuthData = userAuthData[provider];
if (!isDeepStrictEqual(providerData, userProviderAuthData)) { if (!isDeepStrictEqual(providerData, userProviderAuthData)) {

View File

@@ -139,7 +139,7 @@ export class Config {
} }
static validateCustomPages(customPages) { static validateCustomPages(customPages) {
if (!customPages) return; if (!customPages) { return; }
if (Object.prototype.toString.call(customPages) !== '[object Object]') { if (Object.prototype.toString.call(customPages) !== '[object Object]') {
throw Error('Parse Server option customPages must be an object.'); throw Error('Parse Server option customPages must be an object.');
@@ -209,7 +209,7 @@ export class Config {
} }
static validateSchemaOptions(schema: SchemaOptions) { static validateSchemaOptions(schema: SchemaOptions) {
if (!schema) return; if (!schema) { return; }
if (Object.prototype.toString.call(schema) !== '[object Object]') { if (Object.prototype.toString.call(schema) !== '[object Object]') {
throw 'Parse Server option schema must be an object.'; throw 'Parse Server option schema must be an object.';
} }

View File

@@ -142,7 +142,7 @@ const filterSensitiveData = (
object: any object: any
) => { ) => {
let userId = null; let userId = null;
if (auth && auth.user) userId = auth.user.id; if (auth && auth.user) { userId = auth.user.id; }
// replace protectedFields when using pointer-permissions // replace protectedFields when using pointer-permissions
const perms = const perms =
@@ -1592,12 +1592,12 @@ class DatabaseController {
schema && schema.getClassLevelPermissions schema && schema.getClassLevelPermissions
? schema.getClassLevelPermissions(className) ? schema.getClassLevelPermissions(className)
: schema; : schema;
if (!perms) return null; if (!perms) { return null; }
const protectedFields = perms.protectedFields; const protectedFields = perms.protectedFields;
if (!protectedFields) return null; if (!protectedFields) { return null; }
if (aclGroup.indexOf(query.objectId) > -1) return null; if (aclGroup.indexOf(query.objectId) > -1) { return null; }
// for queries where "keys" are set and do not include all 'userField':{field}, // for queries where "keys" are set and do not include all 'userField':{field},
// we have to transparently include it, and then remove before returning to client // we have to transparently include it, and then remove before returning to client

View File

@@ -666,10 +666,10 @@ const VolatileClassesSchemas = [
]; ];
const dbTypeMatchesObjectType = (dbType: SchemaField | string, objectType: SchemaField) => { const dbTypeMatchesObjectType = (dbType: SchemaField | string, objectType: SchemaField) => {
if (dbType.type !== objectType.type) return false; if (dbType.type !== objectType.type) { return false; }
if (dbType.targetClass !== objectType.targetClass) return false; if (dbType.targetClass !== objectType.targetClass) { return false; }
if (dbType === objectType.type) return true; if (dbType === objectType.type) { return true; }
if (dbType.type === objectType.type) return true; if (dbType.type === objectType.type) { return true; }
return false; return false;
}; };
@@ -1020,7 +1020,7 @@ export default class SchemaController {
} }
const fieldType = fields[fieldName]; const fieldType = fields[fieldName];
const error = fieldTypeIsInvalid(fieldType); const error = fieldTypeIsInvalid(fieldType);
if (error) return { code: error.code, error: error.message }; if (error) { return { code: error.code, error: error.message }; }
if (fieldType.defaultValue !== undefined) { if (fieldType.defaultValue !== undefined) {
let defaultValueType = getType(fieldType.defaultValue); let defaultValueType = getType(fieldType.defaultValue);
if (typeof defaultValueType === 'string') { if (typeof defaultValueType === 'string') {

View File

@@ -122,7 +122,7 @@ export class UserController extends AdaptableController {
if (expiresDate && expiresDate.__type == 'Date') { if (expiresDate && expiresDate.__type == 'Date') {
expiresDate = new Date(expiresDate.iso); expiresDate = new Date(expiresDate.iso);
} }
if (expiresDate < new Date()) throw 'The password reset link has expired'; if (expiresDate < new Date()) { throw 'The password reset link has expired'; }
} }
return results[0]; return results[0];
}); });

View File

@@ -76,7 +76,7 @@ const load = function (parseGraphQLSchema, parseClass, parseClassConfig: ?ParseG
mutateAndGetPayload: async (args, context, mutationInfo) => { mutateAndGetPayload: async (args, context, mutationInfo) => {
try { try {
let { fields } = deepcopy(args); let { fields } = deepcopy(args);
if (!fields) fields = {}; if (!fields) { fields = {}; }
const { config, auth, info } = context; const { config, auth, info } = context;
const parseFields = await transformTypes('create', fields, { const parseFields = await transformTypes('create', fields, {
@@ -179,7 +179,7 @@ const load = function (parseGraphQLSchema, parseClass, parseClassConfig: ?ParseG
mutateAndGetPayload: async (args, context, mutationInfo) => { mutateAndGetPayload: async (args, context, mutationInfo) => {
try { try {
let { id, fields } = deepcopy(args); let { id, fields } = deepcopy(args);
if (!fields) fields = {}; if (!fields) { fields = {}; }
const { config, auth, info } = context; const { config, auth, info } = context;
const globalIdObject = fromGlobalId(id); const globalIdObject = fromGlobalId(id);

View File

@@ -453,7 +453,7 @@ const load = (parseGraphQLSchema, parseClass, parseClassConfig: ?ParseGraphQLCla
description: `Use Inline Fragment on Array to get results: https://graphql.org/learn/queries/#inline-fragments`, description: `Use Inline Fragment on Array to get results: https://graphql.org/learn/queries/#inline-fragments`,
type: parseClass.fields[field].required ? new GraphQLNonNull(type) : type, type: parseClass.fields[field].required ? new GraphQLNonNull(type) : type,
async resolve(source) { async resolve(source) {
if (!source[field]) return null; if (!source[field]) { return null; }
return source[field].map(async elem => { return source[field].map(async elem => {
if (elem.className && elem.objectId && elem.__type === 'Object') { if (elem.className && elem.objectId && elem.__type === 'Object') {
return elem; return elem;

View File

@@ -57,7 +57,7 @@ const load = parseGraphQLSchema => {
'viewer.user.', 'viewer.user.',
objectId objectId
); );
if (authDataResponse && viewer.user) viewer.user.authDataResponse = authDataResponse; if (authDataResponse && viewer.user) { viewer.user.authDataResponse = authDataResponse; }
return { return {
viewer, viewer,
}; };
@@ -134,7 +134,7 @@ const load = parseGraphQLSchema => {
'viewer.user.', 'viewer.user.',
objectId objectId
); );
if (authDataResponse && viewer.user) viewer.user.authDataResponse = authDataResponse; if (authDataResponse && viewer.user) { viewer.user.authDataResponse = authDataResponse; }
return { return {
viewer, viewer,
}; };
@@ -198,7 +198,7 @@ const load = parseGraphQLSchema => {
'viewer.user.', 'viewer.user.',
objectId objectId
); );
if (authDataResponse && viewer.user) viewer.user.authDataResponse = authDataResponse; if (authDataResponse && viewer.user) { viewer.user.authDataResponse = authDataResponse; }
return { return {
viewer, viewer,
}; };

View File

@@ -23,7 +23,7 @@ export const extractKeysAndInclude = selectedFields => {
selectedFields = selectedFields.filter(field => !field.includes('__typename')); selectedFields = selectedFields.filter(field => !field.includes('__typename'));
// Handles "id" field for both current and included objects // Handles "id" field for both current and included objects
selectedFields = selectedFields.map(field => { selectedFields = selectedFields.map(field => {
if (field === 'id') return 'objectId'; if (field === 'id') { return 'objectId'; }
return field.endsWith('.id') return field.endsWith('.id')
? `${field.substring(0, field.lastIndexOf('.id'))}.objectId` ? `${field.substring(0, field.lastIndexOf('.id'))}.objectId`
: field; : field;

View File

@@ -82,7 +82,7 @@ const transformTypes = async (
} }
}); });
await Promise.all(promises); await Promise.all(promises);
if (fields.ACL) fields.ACL = transformers.ACL(fields.ACL); if (fields.ACL) { fields.ACL = transformers.ACL(fields.ACL); }
} }
return fields; return fields;
}; };
@@ -148,10 +148,10 @@ const transformers = {
{ config, auth, info } { config, auth, info }
) => { ) => {
if (Object.keys(value).length === 0) if (Object.keys(value).length === 0)
throw new Parse.Error( { throw new Parse.Error(
Parse.Error.INVALID_POINTER, Parse.Error.INVALID_POINTER,
`You need to provide at least one operation on the relation mutation of field ${field}` `You need to provide at least one operation on the relation mutation of field ${field}`
); ); }
const op = { const op = {
__op: 'Batch', __op: 'Batch',
@@ -180,7 +180,7 @@ const transformers = {
} }
if (value.add || nestedObjectsToAdd.length > 0) { if (value.add || nestedObjectsToAdd.length > 0) {
if (!value.add) value.add = []; if (!value.add) { value.add = []; }
value.add = value.add.map(input => { value.add = value.add.map(input => {
const globalIdObject = fromGlobalId(input); const globalIdObject = fromGlobalId(input);
if (globalIdObject.type === targetClass) { if (globalIdObject.type === targetClass) {
@@ -225,10 +225,10 @@ const transformers = {
{ config, auth, info } { config, auth, info }
) => { ) => {
if (Object.keys(value).length > 1 || Object.keys(value).length === 0) if (Object.keys(value).length > 1 || Object.keys(value).length === 0)
throw new Parse.Error( { throw new Parse.Error(
Parse.Error.INVALID_POINTER, Parse.Error.INVALID_POINTER,
`You need to provide link OR createLink on the pointer mutation of field ${field}` `You need to provide link OR createLink on the pointer mutation of field ${field}`
); ); }
let nestedObjectToAdd; let nestedObjectToAdd;
if (value.createAndLink) { if (value.createAndLink) {

View File

@@ -88,7 +88,7 @@ class ParseServer {
if (!Object.prototype.hasOwnProperty.call(ref, key)) { if (!Object.prototype.hasOwnProperty.call(ref, key)) {
result.push(prefix + key); result.push(prefix + key);
} else { } else {
if (ref[key] === '') continue; if (ref[key] === '') { continue; }
let res = []; let res = [];
if (Array.isArray(original[key]) && Array.isArray(ref[key])) { if (Array.isArray(original[key]) && Array.isArray(ref[key])) {
const type = ref[key][0]; const type = ref[key][0];

View File

@@ -505,7 +505,7 @@ RestWrite.prototype.ensureUniqueAuthDataId = async function () {
key => this.data.authData[key] && this.data.authData[key].id key => this.data.authData[key] && this.data.authData[key].id
); );
if (!hasAuthDataId) return; if (!hasAuthDataId) { return; }
const r = await Auth.findUsersWithAuthData(this.config, this.data.authData); const r = await Auth.findUsersWithAuthData(this.config, this.data.authData);
const results = this.filteredObjectsByACL(r); const results = this.filteredObjectsByACL(r);
@@ -810,7 +810,7 @@ RestWrite.prototype._validateEmail = function () {
}; };
RestWrite.prototype._validatePasswordPolicy = function () { RestWrite.prototype._validatePasswordPolicy = function () {
if (!this.config.passwordPolicy) return Promise.resolve(); if (!this.config.passwordPolicy) { return Promise.resolve(); }
return this._validatePasswordRequirements().then(() => { return this._validatePasswordRequirements().then(() => {
return this._validatePasswordHistory(); return this._validatePasswordHistory();
}); });
@@ -845,7 +845,7 @@ RestWrite.prototype._validatePasswordRequirements = function () {
if (this.data.username) { if (this.data.username) {
// username is not passed during password reset // username is not passed during password reset
if (this.data.password.indexOf(this.data.username) >= 0) if (this.data.password.indexOf(this.data.username) >= 0)
return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)); { return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)); }
} else { } else {
// retrieve the User object using objectId during password reset // retrieve the User object using objectId during password reset
return this.config.database.find('_User', { objectId: this.objectId() }).then(results => { return this.config.database.find('_User', { objectId: this.objectId() }).then(results => {
@@ -853,9 +853,9 @@ RestWrite.prototype._validatePasswordRequirements = function () {
throw undefined; throw undefined;
} }
if (this.data.password.indexOf(results[0].username) >= 0) if (this.data.password.indexOf(results[0].username) >= 0)
return Promise.reject( { return Promise.reject(
new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError) new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)
); ); }
return Promise.resolve(); return Promise.resolve();
}); });
} }
@@ -880,18 +880,18 @@ RestWrite.prototype._validatePasswordHistory = function () {
const user = results[0]; const user = results[0];
let oldPasswords = []; let oldPasswords = [];
if (user._password_history) if (user._password_history)
oldPasswords = _.take( { oldPasswords = _.take(
user._password_history, user._password_history,
this.config.passwordPolicy.maxPasswordHistory - 1 this.config.passwordPolicy.maxPasswordHistory - 1
); ); }
oldPasswords.push(user.password); oldPasswords.push(user.password);
const newPassword = this.data.password; const newPassword = this.data.password;
// compare the new password hash with all old password hashes // compare the new password hash with all old password hashes
const promises = oldPasswords.map(function (hash) { const promises = oldPasswords.map(function (hash) {
return passwordCrypto.compare(newPassword, hash).then(result => { return passwordCrypto.compare(newPassword, hash).then(result => {
if (result) if (result)
// reject if there is a match // reject if there is a match
return Promise.reject('REPEAT_PASSWORD'); { return Promise.reject('REPEAT_PASSWORD'); }
return Promise.resolve(); return Promise.resolve();
}); });
}); });
@@ -902,13 +902,13 @@ RestWrite.prototype._validatePasswordHistory = function () {
}) })
.catch(err => { .catch(err => {
if (err === 'REPEAT_PASSWORD') if (err === 'REPEAT_PASSWORD')
// a match was found // a match was found
return Promise.reject( { return Promise.reject(
new Parse.Error( new Parse.Error(
Parse.Error.VALIDATION_ERROR, Parse.Error.VALIDATION_ERROR,
`New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.` `New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.`
) )
); ); }
throw err; throw err;
}); });
}); });

View File

@@ -253,11 +253,11 @@ export class UsersRouter extends ClassesRouter {
changedAt.getTime() + 86400000 * req.config.passwordPolicy.maxPasswordAge changedAt.getTime() + 86400000 * req.config.passwordPolicy.maxPasswordAge
); );
if (expiresAt < new Date()) if (expiresAt < new Date())
// fail of current time is past password expiry time // fail of current time is past password expiry time
throw new Parse.Error( { throw new Parse.Error(
Parse.Error.OBJECT_NOT_FOUND, Parse.Error.OBJECT_NOT_FOUND,
'Your password has expired. Please reset your password.' 'Your password has expired. Please reset your password.'
); ); }
} }
} }

View File

@@ -80,7 +80,7 @@ export class DefinedSchemas {
logger.info('Running Migrations Completed'); logger.info('Running Migrations Completed');
} catch (e) { } catch (e) {
logger.error(`Failed to run migrations: ${e}`); logger.error(`Failed to run migrations: ${e}`);
if (process.env.NODE_ENV === 'production') process.exit(1); if (process.env.NODE_ENV === 'production') { process.exit(1); }
} }
} }
@@ -108,7 +108,7 @@ export class DefinedSchemas {
this.checkForMissingSchemas(); this.checkForMissingSchemas();
await this.enforceCLPForNonProvidedClass(); await this.enforceCLPForNonProvidedClass();
} catch (e) { } catch (e) {
if (timeout) clearTimeout(timeout); if (timeout) { clearTimeout(timeout); }
if (this.retries < this.maxRetries) { if (this.retries < this.maxRetries) {
this.retries++; this.retries++;
// first retry 1sec, 2sec, 3sec total 6sec retry sequence // first retry 1sec, 2sec, 3sec total 6sec retry sequence
@@ -118,7 +118,7 @@ export class DefinedSchemas {
await this.executeMigrations(); await this.executeMigrations();
} else { } else {
logger.error(`Failed to run migrations: ${e}`); logger.error(`Failed to run migrations: ${e}`);
if (process.env.NODE_ENV === 'production') process.exit(1); if (process.env.NODE_ENV === 'production') { process.exit(1); }
} }
} }
} }
@@ -428,7 +428,7 @@ export class DefinedSchemas {
const keysB: string[] = Object.keys(objB); const keysB: string[] = Object.keys(objB);
// Check key name // Check key name
if (keysA.length !== keysB.length) return false; if (keysA.length !== keysB.length) { return false; }
return keysA.every(k => objA[k] === objB[k]); return keysA.every(k => objA[k] === objB[k]);
} }

View File

@@ -24,7 +24,7 @@ const getMountForRequest = function (req) {
}; };
const getBlockList = (ipRangeList, store) => { const getBlockList = (ipRangeList, store) => {
if (store.get('blockList')) return store.get('blockList'); if (store.get('blockList')) { return store.get('blockList'); }
const blockList = new BlockList(); const blockList = new BlockList();
ipRangeList.forEach(fullIp => { ipRangeList.forEach(fullIp => {
if (fullIp === '::/0' || fullIp === '::') { if (fullIp === '::/0' || fullIp === '::') {
@@ -50,9 +50,9 @@ export const checkIp = (ip, ipRangeList, store) => {
const incomingIpIsV4 = isIPv4(ip); const incomingIpIsV4 = isIPv4(ip);
const blockList = getBlockList(ipRangeList, store); const blockList = getBlockList(ipRangeList, store);
if (store.get(ip)) return true; if (store.get(ip)) { return true; }
if (store.get('allowAllIpv4') && incomingIpIsV4) return true; if (store.get('allowAllIpv4') && incomingIpIsV4) { return true; }
if (store.get('allowAllIpv6') && !incomingIpIsV4) return true; if (store.get('allowAllIpv6') && !incomingIpIsV4) { return true; }
const result = blockList.check(ip, incomingIpIsV4 ? 'ipv4' : 'ipv6'); const result = blockList.check(ip, incomingIpIsV4 ? 'ipv4' : 'ipv6');
// If the ip is in the list, we store the result in the store // If the ip is in the list, we store the result in the store
@@ -386,7 +386,7 @@ function getClientIp(req) {
} }
function httpAuth(req) { function httpAuth(req) {
if (!(req.req || req).headers.authorization) return; if (!(req.req || req).headers.authorization) { return; }
var header = (req.req || req).headers.authorization; var header = (req.req || req).headers.authorization;
var appId, masterKey, javascriptKey; var appId, masterKey, javascriptKey;

View File

@@ -859,7 +859,7 @@ export function maybeRunTrigger(
} }
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var trigger = getTrigger(parseObject.className, triggerType, config.applicationId); var trigger = getTrigger(parseObject.className, triggerType, config.applicationId);
if (!trigger) return resolve(); if (!trigger) { return resolve(); }
var request = getRequestObject( var request = getRequestObject(
triggerType, triggerType,
auth, auth,

View File

@@ -66,7 +66,7 @@ const querystring = require('querystring');
/* istanbul ignore next: improve coverage */ /* istanbul ignore next: improve coverage */
function urlParse(url, parseQueryString, slashesDenoteHost) { function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url instanceof Url) return url; if (url instanceof Url) { return url; }
var u = new Url(); var u = new Url();
u.parse(url, parseQueryString, slashesDenoteHost); u.parse(url, parseQueryString, slashesDenoteHost);
@@ -101,7 +101,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
code === 160 /*\u00A0*/ || code === 160 /*\u00A0*/ ||
code === 65279; /*\uFEFF*/ code === 65279; /*\uFEFF*/
if (start === -1) { if (start === -1) {
if (isWs) continue; if (isWs) { continue; }
lastPos = start = i; lastPos = start = i;
} else { } else {
if (inWs) { if (inWs) {
@@ -125,7 +125,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
split = true; split = true;
break; break;
case 92: // '\\' case 92: // '\\'
if (i - lastPos > 0) rest += url.slice(lastPos, i); if (i - lastPos > 0) { rest += url.slice(lastPos, i); }
rest += '/'; rest += '/';
lastPos = i + 1; lastPos = i + 1;
break; break;
@@ -141,8 +141,8 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
// We didn't convert any backslashes // We didn't convert any backslashes
if (end === -1) { if (end === -1) {
if (start === 0) rest = url; if (start === 0) { rest = url; }
else rest = url.slice(start); else { rest = url.slice(start); }
} else { } else {
rest = url.slice(start, end); rest = url.slice(start, end);
} }
@@ -235,13 +235,13 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
case 124: // '|' case 124: // '|'
case 125: // '}' case 125: // '}'
// Characters that are never ever allowed in a hostname from RFC 2396 // Characters that are never ever allowed in a hostname from RFC 2396
if (nonHost === -1) nonHost = i; if (nonHost === -1) { nonHost = i; }
break; break;
case 35: // '#' case 35: // '#'
case 47: // '/' case 47: // '/'
case 63: // '?' case 63: // '?'
// Find the first instance of any host-ending characters // Find the first instance of any host-ending characters
if (nonHost === -1) nonHost = i; if (nonHost === -1) { nonHost = i; }
hostEnd = i; hostEnd = i;
break; break;
case 64: // '@' case 64: // '@'
@@ -251,7 +251,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
nonHost = -1; nonHost = -1;
break; break;
} }
if (hostEnd !== -1) break; if (hostEnd !== -1) { break; }
} }
start = 0; start = 0;
if (atSign !== -1) { if (atSign !== -1) {
@@ -271,7 +271,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
// we've indicated that there is a hostname, // we've indicated that there is a hostname,
// so even if it's empty, it has to be present. // so even if it's empty, it has to be present.
if (typeof this.hostname !== 'string') this.hostname = ''; if (typeof this.hostname !== 'string') { this.hostname = ''; }
var hostname = this.hostname; var hostname = this.hostname;
@@ -283,7 +283,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
// validate a little. // validate a little.
if (!ipv6Hostname) { if (!ipv6Hostname) {
const result = validateHostname(this, rest, hostname); const result = validateHostname(this, rest, hostname);
if (result !== undefined) rest = result; if (result !== undefined) { rest = result; }
} }
// hostnames are always lower case. // hostnames are always lower case.
@@ -318,7 +318,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
// escaped, even if encodeURIComponent doesn't think they // escaped, even if encodeURIComponent doesn't think they
// need to be. // need to be.
const result = autoEscapeStr(rest); const result = autoEscapeStr(rest);
if (result !== undefined) rest = result; if (result !== undefined) { rest = result; }
} }
var questionIdx = -1; var questionIdx = -1;
@@ -354,7 +354,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
var firstIdx = var firstIdx =
questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx) ? questionIdx : hashIdx; questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx) ? questionIdx : hashIdx;
if (firstIdx === -1) { if (firstIdx === -1) {
if (rest.length > 0) this.pathname = rest; if (rest.length > 0) { this.pathname = rest; }
} else if (firstIdx > 0) { } else if (firstIdx > 0) {
this.pathname = rest.slice(0, firstIdx); this.pathname = rest.slice(0, firstIdx);
} }
@@ -378,7 +378,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
function validateHostname(self, rest, hostname) { function validateHostname(self, rest, hostname) {
for (var i = 0, lastPos; i <= hostname.length; ++i) { for (var i = 0, lastPos; i <= hostname.length; ++i) {
var code; var code;
if (i < hostname.length) code = hostname.charCodeAt(i); if (i < hostname.length) { code = hostname.charCodeAt(i); }
if (code === 46 /*.*/ || i === hostname.length) { if (code === 46 /*.*/ || i === hostname.length) {
if (i - lastPos > 0) { if (i - lastPos > 0) {
if (i - lastPos > 63) { if (i - lastPos > 63) {
@@ -405,7 +405,7 @@ function validateHostname(self, rest, hostname) {
} }
// Invalid host character // Invalid host character
self.hostname = hostname.slice(0, i); self.hostname = hostname.slice(0, i);
if (i < hostname.length) return '/' + hostname.slice(i) + rest; if (i < hostname.length) { return '/' + hostname.slice(i) + rest; }
break; break;
} }
} }
@@ -419,80 +419,80 @@ function autoEscapeStr(rest) {
// Also escape single quotes in case of an XSS attack // Also escape single quotes in case of an XSS attack
switch (rest.charCodeAt(i)) { switch (rest.charCodeAt(i)) {
case 9: // '\t' case 9: // '\t'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%09'; newRest += '%09';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 10: // '\n' case 10: // '\n'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%0A'; newRest += '%0A';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 13: // '\r' case 13: // '\r'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%0D'; newRest += '%0D';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 32: // ' ' case 32: // ' '
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%20'; newRest += '%20';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 34: // '"' case 34: // '"'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%22'; newRest += '%22';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 39: // '\'' case 39: // '\''
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%27'; newRest += '%27';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 60: // '<' case 60: // '<'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%3C'; newRest += '%3C';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 62: // '>' case 62: // '>'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%3E'; newRest += '%3E';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 92: // '\\' case 92: // '\\'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%5C'; newRest += '%5C';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 94: // '^' case 94: // '^'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%5E'; newRest += '%5E';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 96: // '`' case 96: // '`'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%60'; newRest += '%60';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 123: // '{' case 123: // '{'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%7B'; newRest += '%7B';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 124: // '|' case 124: // '|'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%7C'; newRest += '%7C';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 125: // '}' case 125: // '}'
if (i - lastPos > 0) newRest += rest.slice(lastPos, i); if (i - lastPos > 0) { newRest += rest.slice(lastPos, i); }
newRest += '%7D'; newRest += '%7D';
lastPos = i + 1; lastPos = i + 1;
break; break;
} }
} }
if (lastPos === 0) return; if (lastPos === 0) { return; }
if (lastPos < rest.length) return newRest + rest.slice(lastPos); if (lastPos < rest.length) { return newRest + rest.slice(lastPos); }
else return newRest; else { return newRest; }
} }
// format a parsed object into a url string // format a parsed object into a url string
@@ -502,12 +502,12 @@ function urlFormat(obj) {
// If it's an obj, this is a no-op. // If it's an obj, this is a no-op.
// this way, you can call url_format() on strings // this way, you can call url_format() on strings
// to clean up potentially wonky urls. // to clean up potentially wonky urls.
if (typeof obj === 'string') obj = urlParse(obj); if (typeof obj === 'string') { obj = urlParse(obj); }
else if (typeof obj !== 'object' || obj === null) else if (typeof obj !== 'object' || obj === null)
throw new TypeError( { throw new TypeError(
'Parameter "urlObj" must be an object, not ' + obj === null ? 'null' : typeof obj 'Parameter "urlObj" must be an object, not ' + obj === null ? 'null' : typeof obj
); ); }
else if (!(obj instanceof Url)) return Url.prototype.format.call(obj); else if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }
return obj.format(); return obj.format();
} }
@@ -536,46 +536,46 @@ Url.prototype.format = function () {
} }
if (this.query !== null && typeof this.query === 'object') if (this.query !== null && typeof this.query === 'object')
query = querystring.stringify(this.query); { query = querystring.stringify(this.query); }
var search = this.search || (query && '?' + query) || ''; var search = this.search || (query && '?' + query) || '';
if (protocol && protocol.charCodeAt(protocol.length - 1) !== 58 /*:*/) protocol += ':'; if (protocol && protocol.charCodeAt(protocol.length - 1) !== 58 /*:*/) { protocol += ':'; }
var newPathname = ''; var newPathname = '';
var lastPos = 0; var lastPos = 0;
for (var i = 0; i < pathname.length; ++i) { for (var i = 0; i < pathname.length; ++i) {
switch (pathname.charCodeAt(i)) { switch (pathname.charCodeAt(i)) {
case 35: // '#' case 35: // '#'
if (i - lastPos > 0) newPathname += pathname.slice(lastPos, i); if (i - lastPos > 0) { newPathname += pathname.slice(lastPos, i); }
newPathname += '%23'; newPathname += '%23';
lastPos = i + 1; lastPos = i + 1;
break; break;
case 63: // '?' case 63: // '?'
if (i - lastPos > 0) newPathname += pathname.slice(lastPos, i); if (i - lastPos > 0) { newPathname += pathname.slice(lastPos, i); }
newPathname += '%3F'; newPathname += '%3F';
lastPos = i + 1; lastPos = i + 1;
break; break;
} }
} }
if (lastPos > 0) { if (lastPos > 0) {
if (lastPos !== pathname.length) pathname = newPathname + pathname.slice(lastPos); if (lastPos !== pathname.length) { pathname = newPathname + pathname.slice(lastPos); }
else pathname = newPathname; else { pathname = newPathname; }
} }
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with. // unless they had them to begin with.
if (this.slashes || ((!protocol || slashedProtocol[protocol]) && host !== false)) { if (this.slashes || ((!protocol || slashedProtocol[protocol]) && host !== false)) {
host = '//' + (host || ''); host = '//' + (host || '');
if (pathname && pathname.charCodeAt(0) !== 47 /*/*/) pathname = '/' + pathname; if (pathname && pathname.charCodeAt(0) !== 47 /*/*/) { pathname = '/' + pathname; }
} else if (!host) { } else if (!host) {
host = ''; host = '';
} }
search = search.replace('#', '%23'); search = search.replace('#', '%23');
if (hash && hash.charCodeAt(0) !== 35 /*#*/) hash = '#' + hash; if (hash && hash.charCodeAt(0) !== 35 /*#*/) { hash = '#' + hash; }
if (search && search.charCodeAt(0) !== 63 /*?*/) search = '?' + search; if (search && search.charCodeAt(0) !== 63 /*?*/) { search = '?' + search; }
return protocol + host + pathname + search + hash; return protocol + host + pathname + search + hash;
}; };
@@ -592,7 +592,7 @@ Url.prototype.resolve = function (relative) {
/* istanbul ignore next: improve coverage */ /* istanbul ignore next: improve coverage */
function urlResolveObject(source, relative) { function urlResolveObject(source, relative) {
if (!source) return relative; if (!source) { return relative; }
return urlParse(source, false, true).resolveObject(relative); return urlParse(source, false, true).resolveObject(relative);
} }
@@ -627,7 +627,7 @@ Url.prototype.resolveObject = function (relative) {
var rkeys = Object.keys(relative); var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) { for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk]; var rkey = rkeys[rk];
if (rkey !== 'protocol') result[rkey] = relative[rkey]; if (rkey !== 'protocol') { result[rkey] = relative[rkey]; }
} }
//urlParse appends trailing / to urls like http://www.example.com //urlParse appends trailing / to urls like http://www.example.com
@@ -665,11 +665,17 @@ Url.prototype.resolveObject = function (relative) {
!hostlessProtocol[relative.protocol] !hostlessProtocol[relative.protocol]
) { ) {
const relPath = (relative.pathname || '').split('/'); const relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift())); while (relPath.length) {
if (!relative.host) relative.host = ''; const shifted = relPath.shift();
if (!relative.hostname) relative.hostname = ''; if (shifted) {
if (relPath[0] !== '') relPath.unshift(''); relative.host = shifted;
if (relPath.length < 2) relPath.unshift(''); break;
}
}
if (!relative.host) { relative.host = ''; }
if (!relative.hostname) { relative.hostname = ''; }
if (relPath[0] !== '') { relPath.unshift(''); }
if (relPath.length < 2) { relPath.unshift(''); }
result.pathname = relPath.join('/'); result.pathname = relPath.join('/');
} else { } else {
result.pathname = relative.pathname; result.pathname = relative.pathname;
@@ -708,16 +714,16 @@ Url.prototype.resolveObject = function (relative) {
result.hostname = ''; result.hostname = '';
result.port = null; result.port = null;
if (result.host) { if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host; if (srcPath[0] === '') { srcPath[0] = result.host; }
else srcPath.unshift(result.host); else { srcPath.unshift(result.host); }
} }
result.host = ''; result.host = '';
if (relative.protocol) { if (relative.protocol) {
relative.hostname = null; relative.hostname = null;
relative.port = null; relative.port = null;
if (relative.host) { if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host; if (relPath[0] === '') { relPath[0] = relative.host; }
else relPath.unshift(relative.host); else { relPath.unshift(relative.host); }
} }
relative.host = null; relative.host = null;
} }
@@ -736,7 +742,7 @@ Url.prototype.resolveObject = function (relative) {
} else if (relPath.length) { } else if (relPath.length) {
// it's relative // it's relative
// throw away the existing file, and take the new path instead. // throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = []; if (!srcPath) { srcPath = []; }
srcPath.pop(); srcPath.pop();
srcPath = srcPath.concat(relPath); srcPath = srcPath.concat(relPath);
result.search = relative.search; result.search = relative.search;
@@ -873,19 +879,19 @@ Url.prototype.parseHost = function () {
} }
host = host.slice(0, host.length - port.length); host = host.slice(0, host.length - port.length);
} }
if (host) this.hostname = host; if (host) { this.hostname = host; }
}; };
// About 1.5x faster than the two-arg version of Array#splice(). // About 1.5x faster than the two-arg version of Array#splice().
/* istanbul ignore next: improve coverage */ /* istanbul ignore next: improve coverage */
function spliceOne(list, index) { function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; }
list.pop(); list.pop();
} }
var hexTable = new Array(256); var hexTable = new Array(256);
for (var i = 0; i < 256; ++i) for (var i = 0; i < 256; ++i)
hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); { hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); }
/* istanbul ignore next: improve coverage */ /* istanbul ignore next: improve coverage */
function encodeAuth(str) { function encodeAuth(str) {
// faster encodeURIComponent alternative for encoding auth uri components // faster encodeURIComponent alternative for encoding auth uri components
@@ -914,7 +920,7 @@ function encodeAuth(str) {
continue; continue;
} }
if (i - lastPos > 0) out += str.slice(lastPos, i); if (i - lastPos > 0) { out += str.slice(lastPos, i); }
lastPos = i + 1; lastPos = i + 1;
@@ -939,8 +945,8 @@ function encodeAuth(str) {
// Surrogate pair // Surrogate pair
++i; ++i;
var c2; var c2;
if (i < str.length) c2 = str.charCodeAt(i) & 0x3ff; if (i < str.length) { c2 = str.charCodeAt(i) & 0x3ff; }
else c2 = 0; else { c2 = 0; }
c = 0x10000 + (((c & 0x3ff) << 10) | c2); c = 0x10000 + (((c & 0x3ff) << 10) | c2);
out += out +=
hexTable[0xf0 | (c >> 18)] + hexTable[0xf0 | (c >> 18)] +
@@ -948,7 +954,7 @@ function encodeAuth(str) {
hexTable[0x80 | ((c >> 6) & 0x3f)] + hexTable[0x80 | ((c >> 6) & 0x3f)] +
hexTable[0x80 | (c & 0x3f)]; hexTable[0x80 | (c & 0x3f)];
} }
if (lastPos === 0) return str; if (lastPos === 0) { return str; }
if (lastPos < str.length) return out + str.slice(lastPos); if (lastPos < str.length) { return out + str.slice(lastPos); }
return out; return out;
} }