array.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. 'use strict';
  2. // Load modules
  3. const Any = require('./any');
  4. const Cast = require('./cast');
  5. const Hoek = require('hoek');
  6. // Declare internals
  7. const internals = {};
  8. internals.fastSplice = function (arr, i) {
  9. let pos = i;
  10. while (pos < arr.length) {
  11. arr[pos++] = arr[pos];
  12. }
  13. --arr.length;
  14. };
  15. internals.Array = class extends Any {
  16. constructor() {
  17. super();
  18. this._type = 'array';
  19. this._inner.items = [];
  20. this._inner.ordereds = [];
  21. this._inner.inclusions = [];
  22. this._inner.exclusions = [];
  23. this._inner.requireds = [];
  24. this._flags.sparse = false;
  25. }
  26. _base(value, state, options) {
  27. const result = {
  28. value
  29. };
  30. if (typeof value === 'string' &&
  31. options.convert) {
  32. internals.safeParse(value, result);
  33. }
  34. let isArray = Array.isArray(result.value);
  35. const wasArray = isArray;
  36. if (options.convert && this._flags.single && !isArray) {
  37. result.value = [result.value];
  38. isArray = true;
  39. }
  40. if (!isArray) {
  41. result.errors = this.createError('array.base', null, state, options);
  42. return result;
  43. }
  44. if (this._inner.inclusions.length ||
  45. this._inner.exclusions.length ||
  46. this._inner.requireds.length ||
  47. this._inner.ordereds.length ||
  48. !this._flags.sparse) {
  49. // Clone the array so that we don't modify the original
  50. if (wasArray) {
  51. result.value = result.value.slice(0);
  52. }
  53. result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
  54. if (result.errors && wasArray && options.convert && this._flags.single) {
  55. // Attempt a 2nd pass by putting the array inside one.
  56. const previousErrors = result.errors;
  57. result.value = [result.value];
  58. result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
  59. if (result.errors) {
  60. // Restore previous errors and value since this didn't validate either.
  61. result.errors = previousErrors;
  62. result.value = result.value[0];
  63. }
  64. }
  65. }
  66. return result;
  67. }
  68. _checkItems(items, wasArray, state, options) {
  69. const errors = [];
  70. let errored;
  71. const requireds = this._inner.requireds.slice();
  72. const ordereds = this._inner.ordereds.slice();
  73. const inclusions = this._inner.inclusions.concat(requireds);
  74. let il = items.length;
  75. for (let i = 0; i < il; ++i) {
  76. errored = false;
  77. const item = items[i];
  78. let isValid = false;
  79. const key = wasArray ? i : state.key;
  80. const path = wasArray ? (state.path ? state.path + '.' : '') + i : state.path;
  81. const localState = { key, path, parent: state.parent, reference: state.reference };
  82. let res;
  83. // Sparse
  84. if (!this._flags.sparse && item === undefined) {
  85. errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
  86. if (options.abortEarly) {
  87. return errors;
  88. }
  89. continue;
  90. }
  91. // Exclusions
  92. for (let j = 0; j < this._inner.exclusions.length; ++j) {
  93. res = this._inner.exclusions[j]._validate(item, localState, {}); // Not passing options to use defaults
  94. if (!res.errors) {
  95. errors.push(this.createError(wasArray ? 'array.excludes' : 'array.excludesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
  96. errored = true;
  97. if (options.abortEarly) {
  98. return errors;
  99. }
  100. break;
  101. }
  102. }
  103. if (errored) {
  104. continue;
  105. }
  106. // Ordered
  107. if (this._inner.ordereds.length) {
  108. if (ordereds.length > 0) {
  109. const ordered = ordereds.shift();
  110. res = ordered._validate(item, localState, options);
  111. if (!res.errors) {
  112. if (ordered._flags.strip) {
  113. internals.fastSplice(items, i);
  114. --i;
  115. --il;
  116. }
  117. else if (!this._flags.sparse && res.value === undefined) {
  118. errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
  119. if (options.abortEarly) {
  120. return errors;
  121. }
  122. continue;
  123. }
  124. else {
  125. items[i] = res.value;
  126. }
  127. }
  128. else {
  129. errors.push(this.createError('array.ordered', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
  130. if (options.abortEarly) {
  131. return errors;
  132. }
  133. }
  134. continue;
  135. }
  136. else if (!this._inner.items.length) {
  137. errors.push(this.createError('array.orderedLength', { pos: i, limit: this._inner.ordereds.length }, { key: state.key, path: localState.path }, options));
  138. if (options.abortEarly) {
  139. return errors;
  140. }
  141. continue;
  142. }
  143. }
  144. // Requireds
  145. const requiredChecks = [];
  146. let jl = requireds.length;
  147. for (let j = 0; j < jl; ++j) {
  148. res = requiredChecks[j] = requireds[j]._validate(item, localState, options);
  149. if (!res.errors) {
  150. items[i] = res.value;
  151. isValid = true;
  152. internals.fastSplice(requireds, j);
  153. --j;
  154. --jl;
  155. if (!this._flags.sparse && res.value === undefined) {
  156. errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
  157. if (options.abortEarly) {
  158. return errors;
  159. }
  160. }
  161. break;
  162. }
  163. }
  164. if (isValid) {
  165. continue;
  166. }
  167. // Inclusions
  168. const stripUnknown = options.stripUnknown
  169. ? (options.stripUnknown === true ? true : !!options.stripUnknown.arrays)
  170. : false;
  171. jl = inclusions.length;
  172. for (let j = 0; j < jl; ++j) {
  173. const inclusion = inclusions[j];
  174. // Avoid re-running requireds that already didn't match in the previous loop
  175. const previousCheck = requireds.indexOf(inclusion);
  176. if (previousCheck !== -1) {
  177. res = requiredChecks[previousCheck];
  178. }
  179. else {
  180. res = inclusion._validate(item, localState, options);
  181. if (!res.errors) {
  182. if (inclusion._flags.strip) {
  183. internals.fastSplice(items, i);
  184. --i;
  185. --il;
  186. }
  187. else if (!this._flags.sparse && res.value === undefined) {
  188. errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
  189. errored = true;
  190. }
  191. else {
  192. items[i] = res.value;
  193. }
  194. isValid = true;
  195. break;
  196. }
  197. }
  198. // Return the actual error if only one inclusion defined
  199. if (jl === 1) {
  200. if (stripUnknown) {
  201. internals.fastSplice(items, i);
  202. --i;
  203. --il;
  204. isValid = true;
  205. break;
  206. }
  207. errors.push(this.createError(wasArray ? 'array.includesOne' : 'array.includesOneSingle', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
  208. errored = true;
  209. if (options.abortEarly) {
  210. return errors;
  211. }
  212. break;
  213. }
  214. }
  215. if (errored) {
  216. continue;
  217. }
  218. if (this._inner.inclusions.length && !isValid) {
  219. if (stripUnknown) {
  220. internals.fastSplice(items, i);
  221. --i;
  222. --il;
  223. continue;
  224. }
  225. errors.push(this.createError(wasArray ? 'array.includes' : 'array.includesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
  226. if (options.abortEarly) {
  227. return errors;
  228. }
  229. }
  230. }
  231. if (requireds.length) {
  232. this._fillMissedErrors.call(this, errors, requireds, state, options);
  233. }
  234. if (ordereds.length) {
  235. this._fillOrderedErrors.call(this, errors, ordereds, state, options);
  236. }
  237. return errors.length ? errors : null;
  238. }
  239. describe() {
  240. const description = Any.prototype.describe.call(this);
  241. if (this._inner.ordereds.length) {
  242. description.orderedItems = [];
  243. for (let i = 0; i < this._inner.ordereds.length; ++i) {
  244. description.orderedItems.push(this._inner.ordereds[i].describe());
  245. }
  246. }
  247. if (this._inner.items.length) {
  248. description.items = [];
  249. for (let i = 0; i < this._inner.items.length; ++i) {
  250. description.items.push(this._inner.items[i].describe());
  251. }
  252. }
  253. return description;
  254. }
  255. items() {
  256. const obj = this.clone();
  257. Hoek.flatten(Array.prototype.slice.call(arguments)).forEach((type, index) => {
  258. try {
  259. type = Cast.schema(type);
  260. }
  261. catch (castErr) {
  262. if (castErr.hasOwnProperty('path')) {
  263. castErr.path = index + '.' + castErr.path;
  264. }
  265. else {
  266. castErr.path = index;
  267. }
  268. castErr.message = castErr.message + '(' + castErr.path + ')';
  269. throw castErr;
  270. }
  271. obj._inner.items.push(type);
  272. if (type._flags.presence === 'required') {
  273. obj._inner.requireds.push(type);
  274. }
  275. else if (type._flags.presence === 'forbidden') {
  276. obj._inner.exclusions.push(type.optional());
  277. }
  278. else {
  279. obj._inner.inclusions.push(type);
  280. }
  281. });
  282. return obj;
  283. }
  284. ordered() {
  285. const obj = this.clone();
  286. Hoek.flatten(Array.prototype.slice.call(arguments)).forEach((type, index) => {
  287. try {
  288. type = Cast.schema(type);
  289. }
  290. catch (castErr) {
  291. if (castErr.hasOwnProperty('path')) {
  292. castErr.path = index + '.' + castErr.path;
  293. }
  294. else {
  295. castErr.path = index;
  296. }
  297. castErr.message = castErr.message + '(' + castErr.path + ')';
  298. throw castErr;
  299. }
  300. obj._inner.ordereds.push(type);
  301. });
  302. return obj;
  303. }
  304. min(limit) {
  305. Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
  306. return this._test('min', limit, function (value, state, options) {
  307. if (value.length >= limit) {
  308. return value;
  309. }
  310. return this.createError('array.min', { limit, value }, state, options);
  311. });
  312. }
  313. max(limit) {
  314. Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
  315. return this._test('max', limit, function (value, state, options) {
  316. if (value.length <= limit) {
  317. return value;
  318. }
  319. return this.createError('array.max', { limit, value }, state, options);
  320. });
  321. }
  322. length(limit) {
  323. Hoek.assert(Hoek.isInteger(limit) && limit >= 0, 'limit must be a positive integer');
  324. return this._test('length', limit, function (value, state, options) {
  325. if (value.length === limit) {
  326. return value;
  327. }
  328. return this.createError('array.length', { limit, value }, state, options);
  329. });
  330. }
  331. unique(comparator) {
  332. const isCustom = !!comparator;
  333. comparator = comparator || Hoek.deepEqual;
  334. Hoek.assert(typeof comparator === 'function', 'comparator must be a function');
  335. return this._test('unique', undefined, function (value, state, options) {
  336. const found = {
  337. string: {},
  338. number: {},
  339. undefined: {},
  340. boolean: {},
  341. object: [],
  342. function: [],
  343. custom: []
  344. };
  345. for (let i = 0; i < value.length; ++i) {
  346. const item = value[i];
  347. const type = typeof item;
  348. const records = isCustom ? found.custom : found[type];
  349. // All available types are supported, so it's not possible to reach 100% coverage without ignoring this line.
  350. // I still want to keep the test for future js versions with new types (eg. Symbol).
  351. if (/* $lab:coverage:off$ */ records /* $lab:coverage:on$ */) {
  352. if (Array.isArray(records)) {
  353. for (let j = 0; j < records.length; ++j) {
  354. if (comparator(records[j], item)) {
  355. return this.createError('array.unique', { pos: i, value: item }, state, options);
  356. }
  357. }
  358. records.push(item);
  359. }
  360. else {
  361. if (records[item]) {
  362. return this.createError('array.unique', { pos: i, value: item }, state, options);
  363. }
  364. records[item] = true;
  365. }
  366. }
  367. }
  368. return value;
  369. });
  370. }
  371. sparse(enabled) {
  372. const obj = this.clone();
  373. obj._flags.sparse = enabled === undefined ? true : !!enabled;
  374. return obj;
  375. }
  376. single(enabled) {
  377. const obj = this.clone();
  378. obj._flags.single = enabled === undefined ? true : !!enabled;
  379. return obj;
  380. }
  381. _fillMissedErrors(errors, requireds, state, options) {
  382. const knownMisses = [];
  383. let unknownMisses = 0;
  384. for (let i = 0; i < requireds.length; ++i) {
  385. const label = requireds[i]._getLabel();
  386. if (label) {
  387. knownMisses.push(label);
  388. }
  389. else {
  390. ++unknownMisses;
  391. }
  392. }
  393. if (knownMisses.length) {
  394. if (unknownMisses) {
  395. errors.push(this.createError('array.includesRequiredBoth', { knownMisses, unknownMisses }, { key: state.key, path: state.path }, options));
  396. }
  397. else {
  398. errors.push(this.createError('array.includesRequiredKnowns', { knownMisses }, { key: state.key, path: state.path }, options));
  399. }
  400. }
  401. else {
  402. errors.push(this.createError('array.includesRequiredUnknowns', { unknownMisses }, { key: state.key, path: state.path }, options));
  403. }
  404. }
  405. _fillOrderedErrors(errors, ordereds, state, options) {
  406. const requiredOrdereds = [];
  407. for (let i = 0; i < ordereds.length; ++i) {
  408. const presence = Hoek.reach(ordereds[i], '_flags.presence');
  409. if (presence === 'required') {
  410. requiredOrdereds.push(ordereds[i]);
  411. }
  412. }
  413. if (requiredOrdereds.length) {
  414. this._fillMissedErrors.call(this, errors, requiredOrdereds, state, options);
  415. }
  416. }
  417. };
  418. internals.safeParse = function (value, result) {
  419. try {
  420. const converted = JSON.parse(value);
  421. if (Array.isArray(converted)) {
  422. result.value = converted;
  423. }
  424. }
  425. catch (e) { }
  426. };
  427. module.exports = new internals.Array();