Skip to content

Commit

Permalink
feat: STRF-10408 Categorize validaiton error as ValidationError (#249)
Browse files Browse the repository at this point in the history
  • Loading branch information
jairo-bc authored Mar 14, 2023
1 parent 9d50416 commit 9917efe
Show file tree
Hide file tree
Showing 21 changed files with 97 additions and 52 deletions.
3 changes: 2 additions & 1 deletion helpers/3p/utils/lib/arrayFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
'use strict';

const iterator = require('./makeIterator');
const { ValidationError } = require('../../../../lib/errors');

module.exports = function filter(arr, cb, thisArg) {
if (!arr) {
return [];
}

if (typeof cb !== 'function') {
throw new TypeError('arr-filter expects a callback function.');
throw new ValidationError('arr-filter expects a callback function.');
}

cb = iterator(cb, thisArg);
Expand Down
3 changes: 2 additions & 1 deletion helpers/3p/utils/lib/arraySort.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
const kindOf = require('./kindOf');
const { getValue } = require('../../../lib/common');
const { ValidationError } = require('../../../../lib/errors');

/**
* Sort an array of objects by one or more properties.
Expand All @@ -24,7 +25,7 @@ function arraySort(arr, props, opts) {
}

if (!Array.isArray(arr)) {
throw new TypeError('array-sort expects an array.');
throw new ValidationError('array-sort expects an array.');
}

if (arguments.length === 1) {
Expand Down
9 changes: 6 additions & 3 deletions helpers/3p/utils/lib/createFrame.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
* https://github.com/jonschlinkert/define-property/blob/master/index.js
*/


const { ValidationError } = require('../../../../lib/errors');

function extend(obj /* , ...source */) {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
Expand All @@ -18,11 +21,11 @@ function extend(obj /* , ...source */) {

function defineProperty(obj, prop, val) {
if (typeof obj !== 'object' && typeof obj !== 'function') {
throw new TypeError('expected an object or function.');
throw new ValidationError('expected an object or function.');
}

if (typeof prop !== 'string') {
throw new TypeError('expected `prop` to be a string.');
throw new ValidationError('expected `prop` to be a string.');
}


Expand All @@ -36,7 +39,7 @@ function defineProperty(obj, prop, val) {

module.exports = function createFrame(data) {
if (typeof data !== 'object') {
throw new TypeError('createFrame expects data to be an object');
throw new ValidationError('createFrame expects data to be an object');
}

var frame = extend({}, data);
Expand Down
5 changes: 3 additions & 2 deletions helpers/3p/utils/lib/isOdd.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ Copy form https://github.com/i-voted-for-trump/is-odd/blob/0.1.2/index.js
*/
'use strict';

const { ValidationError } = require('../../../../lib/errors');
const isNumber = require('./isNumber');

module.exports = function isOdd(i) {
if (!isNumber(i)) {
throw new TypeError('is-odd expects a number.');
throw new ValidationError('is-odd expects a number.');
}
if (Number(i) !== Math.floor(i)) {
throw new RangeError('is-odd expects an integer.');
throw new ValidationError('is-odd expects an integer.');
}
return !!(~~i & 1);
};
9 changes: 5 additions & 4 deletions helpers/assignVar.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@
const utils = require('./3p/utils');
const max_length = 1024;
const max_keys = 50;
const { ValidationError } = require('../lib/errors');

const factory = globals => {
return function (key, value) {

// Validate that key is a string
if (!utils.isString(key)) {
throw new Error("assignVar helper key must be a string");
throw new ValidationError("assignVar helper key must be a string");
}

// Validate that value is a string or Number (int/float)
if (!utils.isString(value) && !Number.isFinite(value)) {
throw new Error("assignVar helper value must be a string or a number (integer/float)");
throw new ValidationError("assignVar helper value must be a string or a number (integer/float)");
}

// Validate that string is not longer than the max length
if (utils.isString(value) && value.length >= max_length) {
throw new Error(`assignVar helper value must be less than ${max_length} characters,
throw new ValidationError(`assignVar helper value must be less than ${max_length} characters,
but a ${value.length} character value was set to ${key}`);
}

Expand All @@ -29,7 +30,7 @@ const factory = globals => {

// Make sure the number of total keys is within the limit
if (Object.keys(globals.storage.variables).length >= max_keys) {
throw new Error(`Unique keys in variable storage may not exceed ${max_keys} in total`);
throw new ValidationError(`Unique keys in variable storage may not exceed ${max_keys} in total`);
}

// Store value for later use by getVar helper
Expand Down
5 changes: 3 additions & 2 deletions helpers/compare.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict';
const { ValidationError } = require('../lib/errors');

const factory = () => {
return function(lvalue, rvalue) {
Expand All @@ -8,7 +9,7 @@ const factory = () => {
var result;

if (arguments.length < 3) {
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
throw new ValidationError("Handlerbars Helper 'compare' needs 2 parameters");
}

operator = options.hash.operator || "==";
Expand All @@ -29,7 +30,7 @@ const factory = () => {
// directly (like operators[x]) is insecure
// (we could use switch instead)
if (Object.getOwnPropertyNames(operators).indexOf(operator) === -1) {
throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator);
throw new ValidationError("Handlerbars Helper 'compare' doesn't know the operator " + operator);
}

result = operators[operator](lvalue, rvalue);
Expand Down
6 changes: 4 additions & 2 deletions helpers/decrementVar.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use strict';
const utils = require('./3p/utils');
const { ValidationError } = require('../lib/errors');

const max_keys = 50;

const factory = globals => {
return function (key) {
if (!utils.isString(key)) {
throw new Error("decrementVar helper key must be a string");
throw new ValidationError("decrementVar helper key must be a string");
}

// Setup storage
Expand All @@ -19,7 +21,7 @@ const factory = globals => {
} else {
// Make sure the number of total keys is within the limit
if (Object.keys(globals.storage.variables).length >= max_keys) {
throw new Error(`Unique keys in variable storage may not exceed ${max_keys} in total`);
throw new ValidationError(`Unique keys in variable storage may not exceed ${max_keys} in total`);
}
// Initialize or re-initialize value
globals.storage.variables[key] = 0;
Expand Down
5 changes: 3 additions & 2 deletions helpers/encodeHtmlEntities.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
const he = require('he');
const utils = require('./3p/utils');
const common = require('./lib/common.js');
const { ValidationError } = require('../lib/errors');

const factory = globals => {
return function (string) {
string = common.unwrapIfSafeString(globals.handlebars, string);
if (!utils.isString(string)) {
throw new TypeError("Non-string passed to encodeHtmlEntities");
throw new ValidationError("Non-string passed to encodeHtmlEntities");
}

const options = arguments[arguments.length - 1];
Expand All @@ -28,7 +29,7 @@ const factory = globals => {
// Make sure all named arguments from options hash are in the whitelist and have boolean (string) values
if (Object.keys(args).some(key => !allowedArguments.includes(key))
|| !Object.keys(args).map(key => args[key]).every(val => ['true', 'false'].includes(val))) {
throw new TypeError("Invalid named argument passed to encodeHtmlEntities");
throw new ValidationError("Invalid named argument passed to encodeHtmlEntities");
}
}

Expand Down
5 changes: 3 additions & 2 deletions helpers/getImageSrcset1x2x.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
const utils = require('./3p/utils');
const common = require('./lib/common');
const { ValidationError } = require('../lib/errors');

const factory = globals => {
return function (image, size1x) {
Expand All @@ -11,11 +12,11 @@ const factory = globals => {

if (!utils.isObject(image) || !utils.isString(image.data)
|| !common.isValidURL(image.data) || image.data.indexOf('{:size}') === -1) {
throw new Error("Invalid StencilImage passed to getImageSrcset1x2x")
throw new ValidationError("Invalid StencilImage passed to getImageSrcset1x2x")
}

if (!pixelDimensionsRegex.test(size1x)) {
throw new Error("Invalid size argument passed to getImageSrcset1x2x, must be a set of pixel dimensions of the format '123x123'")
throw new ValidationError("Invalid size argument passed to getImageSrcset1x2x, must be a set of pixel dimensions of the format '123x123'")
}

if (!image.width || !image.height || !Number.isInteger(image.width) || !Number.isInteger(image.height)) {
Expand Down
3 changes: 2 additions & 1 deletion helpers/getVar.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
'use strict';

const utils = require('./3p/utils');
const { ValidationError } = require('../lib/errors');

const factory = globals => {
return function (key) {
if (!utils.isString(key)) {
throw new Error("getVar helper key must be a string");
throw new ValidationError("getVar helper key must be a string");
}

return globals.storage.variables && globals.storage.variables.hasOwnProperty(key) ? globals.storage.variables[key] : undefined
Expand Down
5 changes: 3 additions & 2 deletions helpers/if.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const utils = require('./3p/utils');
const { ValidationError } = require('../lib/errors');

const factory = globals => {
return function (lvalue, operator, rvalue) {
Expand Down Expand Up @@ -67,7 +68,7 @@ const factory = globals => {
if (typeof lvalue === 'string' && typeof (rvalue) === 'string' && !isNaN(lvalue) && !isNaN(rvalue)) {
result = parseInt(lvalue) > parseInt(rvalue);
} else {
throw new Error("if gtnum only accepts numbers (as strings)");
throw new ValidationError("if gtnum only accepts numbers (as strings)");
}
break;

Expand All @@ -76,7 +77,7 @@ const factory = globals => {
break;

default:
throw new Error("Handlerbars Helper 'if' doesn't know the operator " + operator);
throw new ValidationError("Handlerbars Helper 'if' doesn't know the operator " + operator);
}
}

Expand Down
6 changes: 4 additions & 2 deletions helpers/incrementVar.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use strict';
const utils = require('./3p/utils');
const { ValidationError } = require('../lib/errors');

const max_keys = 50;

const factory = globals => {
return function (key) {
if (!utils.isString(key)) {
throw new Error("incrementVar helper key must be a string");
throw new ValidationError("incrementVar helper key must be a string");
}

// Setup storage
Expand All @@ -19,7 +21,7 @@ const factory = globals => {
} else {
// Make sure the number of total keys is within the limit
if (Object.keys(globals.storage.variables).length >= max_keys) {
throw new Error(`Unique keys in variable storage may not exceed ${max_keys} in total`);
throw new ValidationError(`Unique keys in variable storage may not exceed ${max_keys} in total`);
}
// Initialize or re-initialize value
globals.storage.variables[key] = 0;
Expand Down
3 changes: 2 additions & 1 deletion helpers/lib/fonts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const URL = require('url')
const utils = require('../3p/utils');
const { ValidationError } = require('../../lib/errors');

const {resourceHintAllowedTypes, addResourceHint, defaultResourceHintState} = require('../lib/resourceHints');

Expand Down Expand Up @@ -64,7 +65,7 @@ const fontProviders = {
const url = URL.parse(uri);
return `<link href="${url.format()}" rel="stylesheet">`;
} catch (error) {
throw new Error(`Invalid URL [${uri}]. Check configured fonts.`)
throw new ValidationError(`Invalid URL [${uri}]. Check configured fonts.`)
}
},

Expand Down
6 changes: 4 additions & 2 deletions helpers/lib/getObjectStorageImage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
const utils = require('../3p/utils');
const common = require('./common');

const { ValidationError } = require('../../lib/errors');

const srcsets = {
'80w': '80w',
'160w': '160w',
Expand All @@ -15,7 +17,7 @@ const srcsets = {

function getObjectStorageImage(handlebars, cdnUrl, source, path, options) {
if (!utils.isString(path) || common.isValidURL(path)) {
throw new TypeError("Invalid image path - please use a filename or folder path starting from the appropriate folder");
throw new ValidationError("Invalid image path - please use a filename or folder path starting from the appropriate folder");
}

// Return original image if there are no arguments
Expand All @@ -36,7 +38,7 @@ function getObjectStorageImage(handlebars, cdnUrl, source, path, options) {

function getObjectStorageImageSrcset(handlebars, cdnUrl, source, path) {
if (!utils.isString(path) || common.isValidURL(path)) {
throw new TypeError("Invalid image path - please use a filename or folder path starting from the appropriate folder");
throw new ValidationError("Invalid image path - please use a filename or folder path starting from the appropriate folder");
}

return new handlebars.SafeString(Object.keys(srcsets).map(descriptor => {
Expand Down
10 changes: 6 additions & 4 deletions helpers/lib/resourceHints.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const utils = require("../3p/utils");
const URL = require('url');

const { ValidationError } = require('../../lib/errors');

const resourceHintsLimit = 50;

const preloadResourceHintState = 'preload';
Expand Down Expand Up @@ -29,17 +31,17 @@ const allowedCors = [noCors, anonymousCors, useCredentialsCors];
function addResourceHint(globals, path, rel, type, cors) {

if (!utils.isString(path)) {
throw new Error('Invalid path provided. path should be a non empty string');
throw new ValidationError('Invalid path provided. path should be a non empty string');
}
path = path.trim();
try {
path = URL.parse(path).format();
} catch (error) {
throw new Error(`Invalid value (resource URL) provided: ${path}`)
throw new ValidationError(`Invalid value (resource URL) provided: ${path}`)
}

if (!utils.isString(rel) || !resourceHintStates.includes(rel)) {
throw new Error(`resourceHint attribute received invalid value. Valid values are: ${resourceHintStates}`);
throw new ValidationError(`resourceHint attribute received invalid value. Valid values are: ${resourceHintStates}`);
}

if (typeof globals.resourceHints === 'undefined') {
Expand All @@ -63,7 +65,7 @@ function addResourceHint(globals, path, rel, type, cors) {
}

if (utils.isString(cors) && !allowedCors.includes(cors)) {
throw new Error(`Invalid cors value provided. Valid values are: ${allowedCors}`);
throw new ValidationError(`Invalid cors value provided. Valid values are: ${allowedCors}`);
} else if (!utils.isString(cors)) {
cors = noCors;
}
Expand Down
5 changes: 3 additions & 2 deletions helpers/money.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict';
const { ValidationError } = require('../lib/errors');

/**
* Format numbers
Expand All @@ -25,13 +26,13 @@ const factory = globals => {
let value = args[0];

if (isNaN(value)) {
throw new TypeError("money helper accepts only Number's as first parameter");
throw new ValidationError("money helper accepts only Number's as first parameter");
}

const decimalPlaces = args[1] || money.decimal_places;

if (isNaN(decimalPlaces)) {
throw new TypeError("money helper accepts only Number's for decimal places");
throw new ValidationError("money helper accepts only Number's for decimal places");
}
const thousandsToken = args[2] || money.thousands_token;
const decimalToken = args[3] || money.decimal_token;
Expand Down
Loading

0 comments on commit 9917efe

Please sign in to comment.