123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556 |
- 'use strict';
- // Load modules
- const Any = require('./any');
- const Cast = require('./cast');
- const Hoek = require('hoek');
- // Declare internals
- const internals = {};
- internals.fastSplice = function (arr, i) {
- let pos = i;
- while (pos < arr.length) {
- arr[pos++] = arr[pos];
- }
- --arr.length;
- };
- internals.Array = class extends Any {
- constructor() {
- super();
- this._type = 'array';
- this._inner.items = [];
- this._inner.ordereds = [];
- this._inner.inclusions = [];
- this._inner.exclusions = [];
- this._inner.requireds = [];
- this._flags.sparse = false;
- }
- _base(value, state, options) {
- const result = {
- value
- };
- if (typeof value === 'string' &&
- options.convert) {
- internals.safeParse(value, result);
- }
- let isArray = Array.isArray(result.value);
- const wasArray = isArray;
- if (options.convert && this._flags.single && !isArray) {
- result.value = [result.value];
- isArray = true;
- }
- if (!isArray) {
- result.errors = this.createError('array.base', null, state, options);
- return result;
- }
- if (this._inner.inclusions.length ||
- this._inner.exclusions.length ||
- this._inner.requireds.length ||
- this._inner.ordereds.length ||
- !this._flags.sparse) {
- // Clone the array so that we don't modify the original
- if (wasArray) {
- result.value = result.value.slice(0);
- }
- result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
- if (result.errors && wasArray && options.convert && this._flags.single) {
- // Attempt a 2nd pass by putting the array inside one.
- const previousErrors = result.errors;
- result.value = [result.value];
- result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
- if (result.errors) {
- // Restore previous errors and value since this didn't validate either.
- result.errors = previousErrors;
- result.value = result.value[0];
- }
- }
- }
- return result;
- }
- _checkItems(items, wasArray, state, options) {
- const errors = [];
- let errored;
- const requireds = this._inner.requireds.slice();
- const ordereds = this._inner.ordereds.slice();
- const inclusions = this._inner.inclusions.concat(requireds);
- let il = items.length;
- for (let i = 0; i < il; ++i) {
- errored = false;
- const item = items[i];
- let isValid = false;
- const key = wasArray ? i : state.key;
- const path = wasArray ? (state.path ? state.path + '.' : '') + i : state.path;
- const localState = { key, path, parent: state.parent, reference: state.reference };
- let res;
- // Sparse
- if (!this._flags.sparse && item === undefined) {
- errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
- if (options.abortEarly) {
- return errors;
- }
- continue;
- }
- // Exclusions
- for (let j = 0; j < this._inner.exclusions.length; ++j) {
- res = this._inner.exclusions[j]._validate(item, localState, {}); // Not passing options to use defaults
- if (!res.errors) {
- errors.push(this.createError(wasArray ? 'array.excludes' : 'array.excludesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
- errored = true;
- if (options.abortEarly) {
- return errors;
- }
- break;
- }
- }
- if (errored) {
- continue;
- }
- // Ordered
- if (this._inner.ordereds.length) {
- if (ordereds.length > 0) {
- const ordered = ordereds.shift();
- res = ordered._validate(item, localState, options);
- if (!res.errors) {
- if (ordered._flags.strip) {
- internals.fastSplice(items, i);
- --i;
- --il;
- }
- else if (!this._flags.sparse && res.value === undefined) {
- errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
- if (options.abortEarly) {
- return errors;
- }
- continue;
- }
- else {
- items[i] = res.value;
- }
- }
- else {
- errors.push(this.createError('array.ordered', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
- if (options.abortEarly) {
- return errors;
- }
- }
- continue;
- }
- else if (!this._inner.items.length) {
- errors.push(this.createError('array.orderedLength', { pos: i, limit: this._inner.ordereds.length }, { key: state.key, path: localState.path }, options));
- if (options.abortEarly) {
- return errors;
- }
- continue;
- }
- }
- // Requireds
- const requiredChecks = [];
- let jl = requireds.length;
- for (let j = 0; j < jl; ++j) {
- res = requiredChecks[j] = requireds[j]._validate(item, localState, options);
- if (!res.errors) {
- items[i] = res.value;
- isValid = true;
- internals.fastSplice(requireds, j);
- --j;
- --jl;
- if (!this._flags.sparse && res.value === undefined) {
- errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
- if (options.abortEarly) {
- return errors;
- }
- }
- break;
- }
- }
- if (isValid) {
- continue;
- }
- // Inclusions
- const stripUnknown = options.stripUnknown
- ? (options.stripUnknown === true ? true : !!options.stripUnknown.arrays)
- : false;
- jl = inclusions.length;
- for (let j = 0; j < jl; ++j) {
- const inclusion = inclusions[j];
- // Avoid re-running requireds that already didn't match in the previous loop
- const previousCheck = requireds.indexOf(inclusion);
- if (previousCheck !== -1) {
- res = requiredChecks[previousCheck];
- }
- else {
- res = inclusion._validate(item, localState, options);
- if (!res.errors) {
- if (inclusion._flags.strip) {
- internals.fastSplice(items, i);
- --i;
- --il;
- }
- else if (!this._flags.sparse && res.value === undefined) {
- errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
- errored = true;
- }
- else {
- items[i] = res.value;
- }
- isValid = true;
- break;
- }
- }
- // Return the actual error if only one inclusion defined
- if (jl === 1) {
- if (stripUnknown) {
- internals.fastSplice(items, i);
- --i;
- --il;
- isValid = true;
- break;
- }
- errors.push(this.createError(wasArray ? 'array.includesOne' : 'array.includesOneSingle', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
- errored = true;
- if (options.abortEarly) {
- return errors;
- }
- break;
- }
- }
- if (errored) {
- continue;
- }
- if (this._inner.inclusions.length && !isValid) {
- if (stripUnknown) {
- internals.fastSplice(items, i);
- --i;
- --il;
- continue;
- }
- errors.push(this.createError(wasArray ? 'array.includes' : 'array.includesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
- if (options.abortEarly) {
- return errors;
- }
- }
- }
- if (requireds.length) {
- this._fillMissedErrors.call(this, errors, requireds, state, options);
- }
- if (ordereds.length) {
- this._fillOrderedErrors.call(this, errors, ordereds, state, options);
- }
- return errors.length ? errors : null;
- }
- describe() {
- const description = Any.prototype.describe.call(this);
- if (this._inner.ordereds.length) {
- description.orderedItems = [];
- for (let i = 0; i < this._inner.ordereds.length; ++i) {
- description.orderedItems.push(this._inner.ordereds[i].describe());
- }
- }
- if (this._inner.items.length) {
- description.items = [];
- for (let i = 0; i < this._inner.items.length; ++i) {
- description.items.push(this._inner.items[i].describe());
- }
- }
- return description;
- }
- items() {
- const obj = this.clone();
- Hoek.flatten(Array.prototype.slice.call(arguments)).forEach((type, index) => {
- try {
- type = Cast.schema(type);
- }
- catch (castErr) {
- if (castErr.hasOwnProperty('path')) {
- castErr.path = index + '.' + castErr.path;
- }
- else {
- castErr.path = index;
- }
- castErr.message = castErr.message + '(' + castErr.path + ')';
- throw castErr;
- }
- obj._inner.items.push(type);
- if (type._flags.presence === 'required') {
- obj._inner.requireds.push(type);
- }
- else if (type._flags.presence === 'forbidden') {
- obj._inner.exclusions.push(type.optional());
- }
- else {
- obj._inner.inclusions.push(type);
- }
- });
- return obj;
- }
- ordered() {
- const obj = this.clone();
- Hoek.flatten(Array.prototype.slice.call(arguments)).forEach((type, index) => {
- try {
- type = Cast.schema(type);
- }
- catch (castErr) {
- if (castErr.hasOwnProperty('path')) {
- castErr.path = index + '.' + castErr.path;
- }
- else {
- castErr.path = index;
- }
- castErr.message = castErr.message + '(' + castErr.path + ')';
- throw castErr;
- }
- obj._inner.ordereds.push(type);
- });
- return obj;
- }
- min(limit) {
- Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('min', limit, function (value, state, options) {
- if (value.length >= limit) {
- return value;
- }
- return this.createError('array.min', { limit, value }, state, options);
- });
- }
- max(limit) {
- Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('max', limit, function (value, state, options) {
- if (value.length <= limit) {
- return value;
- }
- return this.createError('array.max', { limit, value }, state, options);
- });
- }
- length(limit) {
- Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
- return this._test('length', limit, function (value, state, options) {
- if (value.length === limit) {
- return value;
- }
- return this.createError('array.length', { limit, value }, state, options);
- });
- }
- unique(comparator) {
- const isCustom = !!comparator;
- comparator = comparator || Hoek.deepEqual;
- Hoek.assert(typeof comparator === 'function', 'comparator must be a function');
- return this._test('unique', undefined, function (value, state, options) {
- const found = {
- string: {},
- number: {},
- undefined: {},
- boolean: {},
- object: [],
- function: [],
- custom: []
- };
- for (let i = 0; i < value.length; ++i) {
- const item = value[i];
- const type = typeof item;
- const records = isCustom ? found.custom : found[type];
- // All available types are supported, so it's not possible to reach 100% coverage without ignoring this line.
- // I still want to keep the test for future js versions with new types (eg. Symbol).
- if (/* $lab:coverage:off$ */ records /* $lab:coverage:on$ */) {
- if (Array.isArray(records)) {
- for (let j = 0; j < records.length; ++j) {
- if (comparator(records[j], item)) {
- return this.createError('array.unique', { pos: i, value: item }, state, options);
- }
- }
- records.push(item);
- }
- else {
- if (records[item]) {
- return this.createError('array.unique', { pos: i, value: item }, state, options);
- }
- records[item] = true;
- }
- }
- }
- return value;
- });
- }
- sparse(enabled) {
- const obj = this.clone();
- obj._flags.sparse = enabled === undefined ? true : !!enabled;
- return obj;
- }
- single(enabled) {
- const obj = this.clone();
- obj._flags.single = enabled === undefined ? true : !!enabled;
- return obj;
- }
- _fillMissedErrors(errors, requireds, state, options) {
- const knownMisses = [];
- let unknownMisses = 0;
- for (let i = 0; i < requireds.length; ++i) {
- const label = requireds[i]._getLabel();
- if (label) {
- knownMisses.push(label);
- }
- else {
- ++unknownMisses;
- }
- }
- if (knownMisses.length) {
- if (unknownMisses) {
- errors.push(this.createError('array.includesRequiredBoth', { knownMisses, unknownMisses }, { key: state.key, path: state.path }, options));
- }
- else {
- errors.push(this.createError('array.includesRequiredKnowns', { knownMisses }, { key: state.key, path: state.path }, options));
- }
- }
- else {
- errors.push(this.createError('array.includesRequiredUnknowns', { unknownMisses }, { key: state.key, path: state.path }, options));
- }
- }
- _fillOrderedErrors(errors, ordereds, state, options) {
- const requiredOrdereds = [];
- for (let i = 0; i < ordereds.length; ++i) {
- const presence = Hoek.reach(ordereds[i], '_flags.presence');
- if (presence === 'required') {
- requiredOrdereds.push(ordereds[i]);
- }
- }
- if (requiredOrdereds.length) {
- this._fillMissedErrors.call(this, errors, requiredOrdereds, state, options);
- }
- }
- };
- internals.safeParse = function (value, result) {
- try {
- const converted = JSON.parse(value);
- if (Array.isArray(converted)) {
- result.value = converted;
- }
- }
- catch (e) { }
- };
- module.exports = new internals.Array();
|