79a8f4aca5891cd7e91713857c6190c9cf95b6dfb85b6df70df13b66044d644cb8e86924198aed65634b446fa63ebce39b204264752d69ed098aa648292dfc-exec 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. 'use strict';
  2. const Bourne = require('@hapi/bourne');
  3. const Hoek = require('@hapi/hoek');
  4. const Topo = require('@hapi/topo');
  5. const Any = require('../any');
  6. const Errors = require('../../errors');
  7. const Cast = require('../../cast');
  8. const State = require('../state');
  9. const internals = {};
  10. internals.Object = class extends Any {
  11. constructor() {
  12. super();
  13. this._type = 'object';
  14. this._inner.children = null;
  15. this._inner.renames = [];
  16. this._inner.dependencies = [];
  17. this._inner.patterns = [];
  18. }
  19. _init(...args) {
  20. return args.length ? this.keys(...args) : this;
  21. }
  22. _base(value, state, options) {
  23. let target = value;
  24. const errors = [];
  25. const finish = () => {
  26. return {
  27. value: target,
  28. errors: errors.length ? errors : null
  29. };
  30. };
  31. if (typeof value === 'string' &&
  32. options.convert) {
  33. if (value.length > 1 &&
  34. (value[0] === '{' || /^\s*\{/.test(value))) {
  35. try {
  36. value = Bourne.parse(value);
  37. }
  38. catch (e) { }
  39. }
  40. }
  41. const type = this._flags.func ? 'function' : 'object';
  42. if (!value ||
  43. typeof value !== type ||
  44. Array.isArray(value)) {
  45. errors.push(this.createError(type + '.base', { value }, state, options));
  46. return finish();
  47. }
  48. // Skip if there are no other rules to test
  49. if (!this._inner.renames.length &&
  50. !this._inner.dependencies.length &&
  51. !this._inner.children && // null allows any keys
  52. !this._inner.patterns.length) {
  53. target = value;
  54. return finish();
  55. }
  56. // Ensure target is a local copy (parsed) or shallow copy
  57. if (target === value) {
  58. if (type === 'object') {
  59. target = Object.create(Object.getPrototypeOf(value));
  60. }
  61. else {
  62. target = function (...args) {
  63. return value.apply(this, args);
  64. };
  65. target.prototype = Hoek.clone(value.prototype);
  66. }
  67. const valueKeys = Object.keys(value);
  68. for (let i = 0; i < valueKeys.length; ++i) {
  69. target[valueKeys[i]] = value[valueKeys[i]];
  70. }
  71. }
  72. else {
  73. target = value;
  74. }
  75. // Rename keys
  76. const renamed = {};
  77. for (let i = 0; i < this._inner.renames.length; ++i) {
  78. const rename = this._inner.renames[i];
  79. if (rename.isRegExp) {
  80. const targetKeys = Object.keys(target);
  81. const matchedTargetKeys = [];
  82. for (let j = 0; j < targetKeys.length; ++j) {
  83. if (rename.from.test(targetKeys[j])) {
  84. matchedTargetKeys.push(targetKeys[j]);
  85. }
  86. }
  87. const allUndefined = matchedTargetKeys.every((key) => target[key] === undefined);
  88. if (rename.options.ignoreUndefined && allUndefined) {
  89. continue;
  90. }
  91. if (!rename.options.multiple &&
  92. renamed[rename.to]) {
  93. errors.push(this.createError('object.rename.regex.multiple', { from: matchedTargetKeys, to: rename.to }, state, options));
  94. if (options.abortEarly) {
  95. return finish();
  96. }
  97. }
  98. if (Object.prototype.hasOwnProperty.call(target, rename.to) &&
  99. !rename.options.override &&
  100. !renamed[rename.to]) {
  101. errors.push(this.createError('object.rename.regex.override', { from: matchedTargetKeys, to: rename.to }, state, options));
  102. if (options.abortEarly) {
  103. return finish();
  104. }
  105. }
  106. if (allUndefined) {
  107. delete target[rename.to];
  108. }
  109. else {
  110. target[rename.to] = target[matchedTargetKeys[matchedTargetKeys.length - 1]];
  111. }
  112. renamed[rename.to] = true;
  113. if (!rename.options.alias) {
  114. for (let j = 0; j < matchedTargetKeys.length; ++j) {
  115. delete target[matchedTargetKeys[j]];
  116. }
  117. }
  118. }
  119. else {
  120. if (rename.options.ignoreUndefined && target[rename.from] === undefined) {
  121. continue;
  122. }
  123. if (!rename.options.multiple &&
  124. renamed[rename.to]) {
  125. errors.push(this.createError('object.rename.multiple', { from: rename.from, to: rename.to }, state, options));
  126. if (options.abortEarly) {
  127. return finish();
  128. }
  129. }
  130. if (Object.prototype.hasOwnProperty.call(target, rename.to) &&
  131. !rename.options.override &&
  132. !renamed[rename.to]) {
  133. errors.push(this.createError('object.rename.override', { from: rename.from, to: rename.to }, state, options));
  134. if (options.abortEarly) {
  135. return finish();
  136. }
  137. }
  138. if (target[rename.from] === undefined) {
  139. delete target[rename.to];
  140. }
  141. else {
  142. target[rename.to] = target[rename.from];
  143. }
  144. renamed[rename.to] = true;
  145. if (!rename.options.alias) {
  146. delete target[rename.from];
  147. }
  148. }
  149. }
  150. // Validate schema
  151. if (!this._inner.children && // null allows any keys
  152. !this._inner.patterns.length &&
  153. !this._inner.dependencies.length) {
  154. return finish();
  155. }
  156. const unprocessed = new Set(Object.keys(target));
  157. if (this._inner.children) {
  158. const stripProps = [];
  159. for (let i = 0; i < this._inner.children.length; ++i) {
  160. const child = this._inner.children[i];
  161. const key = child.key;
  162. const item = target[key];
  163. unprocessed.delete(key);
  164. const localState = new State(key, [...state.path, key], target, state.reference);
  165. const result = child.schema._validate(item, localState, options);
  166. if (result.errors) {
  167. errors.push(this.createError('object.child', { key, child: child.schema._getLabel(key), reason: result.errors }, localState, options));
  168. if (options.abortEarly) {
  169. return finish();
  170. }
  171. }
  172. else {
  173. if (child.schema._flags.strip || (result.value === undefined && result.value !== item)) {
  174. stripProps.push(key);
  175. target[key] = result.finalValue;
  176. }
  177. else if (result.value !== undefined) {
  178. target[key] = result.value;
  179. }
  180. }
  181. }
  182. for (let i = 0; i < stripProps.length; ++i) {
  183. delete target[stripProps[i]];
  184. }
  185. }
  186. // Unknown keys
  187. if (unprocessed.size && this._inner.patterns.length) {
  188. for (const key of unprocessed) {
  189. const localState = new State(key, [...state.path, key], target, state.reference);
  190. const item = target[key];
  191. for (let i = 0; i < this._inner.patterns.length; ++i) {
  192. const pattern = this._inner.patterns[i];
  193. if (pattern.regex ?
  194. pattern.regex.test(key) :
  195. !pattern.schema._validate(key, state, { ...options, abortEarly:true }).errors) {
  196. unprocessed.delete(key);
  197. const result = pattern.rule._validate(item, localState, options);
  198. if (result.errors) {
  199. errors.push(this.createError('object.child', {
  200. key,
  201. child: pattern.rule._getLabel(key),
  202. reason: result.errors
  203. }, localState, options));
  204. if (options.abortEarly) {
  205. return finish();
  206. }
  207. }
  208. target[key] = result.value;
  209. }
  210. }
  211. }
  212. }
  213. if (unprocessed.size && (this._inner.children || this._inner.patterns.length)) {
  214. if ((options.stripUnknown && this._flags.allowUnknown !== true) ||
  215. options.skipFunctions) {
  216. const stripUnknown = options.stripUnknown
  217. ? (options.stripUnknown === true ? true : !!options.stripUnknown.objects)
  218. : false;
  219. for (const key of unprocessed) {
  220. if (stripUnknown) {
  221. delete target[key];
  222. unprocessed.delete(key);
  223. }
  224. else if (typeof target[key] === 'function') {
  225. unprocessed.delete(key);
  226. }
  227. }
  228. }
  229. if ((this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) {
  230. for (const unprocessedKey of unprocessed) {
  231. errors.push(this.createError('object.allowUnknown', { child: unprocessedKey, value: target[unprocessedKey] }, {
  232. key: unprocessedKey,
  233. path: [...state.path, unprocessedKey]
  234. }, options, {}));
  235. }
  236. }
  237. }
  238. // Validate dependencies
  239. for (let i = 0; i < this._inner.dependencies.length; ++i) {
  240. const dep = this._inner.dependencies[i];
  241. const hasKey = dep.key !== null;
  242. const splitKey = hasKey && dep.key.split('.');
  243. const localState = hasKey ? new State(splitKey[splitKey.length - 1], [...state.path, ...splitKey]) : new State(null, state.path);
  244. const err = internals[dep.type].call(this, dep.key, hasKey && Hoek.reach(target, dep.key, { functions: true }), dep.peers, target, localState, options);
  245. if (err instanceof Errors.Err) {
  246. errors.push(err);
  247. if (options.abortEarly) {
  248. return finish();
  249. }
  250. }
  251. }
  252. return finish();
  253. }
  254. keys(schema) {
  255. Hoek.assert(schema === null || schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
  256. Hoek.assert(!schema || !(schema instanceof Any), 'Object schema cannot be a joi schema');
  257. const obj = this.clone();
  258. if (!schema) {
  259. obj._inner.children = null;
  260. return obj;
  261. }
  262. const children = Object.keys(schema);
  263. if (!children.length) {
  264. obj._inner.children = [];
  265. return obj;
  266. }
  267. const topo = new Topo();
  268. if (obj._inner.children) {
  269. for (let i = 0; i < obj._inner.children.length; ++i) {
  270. const child = obj._inner.children[i];
  271. // Only add the key if we are not going to replace it later
  272. if (!children.includes(child.key)) {
  273. topo.add(child, { after: child._refs, group: child.key });
  274. }
  275. }
  276. }
  277. for (let i = 0; i < children.length; ++i) {
  278. const key = children[i];
  279. const child = schema[key];
  280. try {
  281. const cast = Cast.schema(this._currentJoi, child);
  282. topo.add({ key, schema: cast }, { after: cast._refs, group: key });
  283. }
  284. catch (castErr) {
  285. if (castErr.hasOwnProperty('path')) {
  286. castErr.path = key + '.' + castErr.path;
  287. }
  288. else {
  289. castErr.path = key;
  290. }
  291. throw castErr;
  292. }
  293. }
  294. obj._inner.children = topo.nodes;
  295. return obj;
  296. }
  297. append(schema) {
  298. // Skip any changes
  299. if (schema === null || schema === undefined || Object.keys(schema).length === 0) {
  300. return this;
  301. }
  302. return this.keys(schema);
  303. }
  304. unknown(allow) {
  305. const value = allow !== false;
  306. if (this._flags.allowUnknown === value) {
  307. return this;
  308. }
  309. const obj = this.clone();
  310. obj._flags.allowUnknown = value;
  311. return obj;
  312. }
  313. length(limit) {
  314. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  315. return this._test('length', limit, function (value, state, options) {
  316. if (Object.keys(value).length === limit) {
  317. return value;
  318. }
  319. return this.createError('object.length', { limit, value }, state, options);
  320. });
  321. }
  322. min(limit) {
  323. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  324. return this._test('min', limit, function (value, state, options) {
  325. if (Object.keys(value).length >= limit) {
  326. return value;
  327. }
  328. return this.createError('object.min', { limit, value }, state, options);
  329. });
  330. }
  331. max(limit) {
  332. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  333. return this._test('max', limit, function (value, state, options) {
  334. if (Object.keys(value).length <= limit) {
  335. return value;
  336. }
  337. return this.createError('object.max', { limit, value }, state, options);
  338. });
  339. }
  340. pattern(pattern, schema) {
  341. const isRegExp = pattern instanceof RegExp;
  342. Hoek.assert(isRegExp || pattern instanceof Any, 'pattern must be a regex or schema');
  343. Hoek.assert(schema !== undefined, 'Invalid rule');
  344. if (isRegExp) {
  345. Hoek.assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode');
  346. }
  347. try {
  348. schema = Cast.schema(this._currentJoi, schema);
  349. }
  350. catch (castErr) {
  351. if (castErr.hasOwnProperty('path')) {
  352. castErr.message = `${castErr.message}(${castErr.path})`;
  353. }
  354. throw castErr;
  355. }
  356. const obj = this.clone();
  357. if (isRegExp) {
  358. obj._inner.patterns.push({ regex: pattern, rule: schema });
  359. }
  360. else {
  361. obj._inner.patterns.push({ schema: pattern, rule: schema });
  362. }
  363. return obj;
  364. }
  365. schema() {
  366. return this._test('schema', null, function (value, state, options) {
  367. if (value instanceof Any) {
  368. return value;
  369. }
  370. return this.createError('object.schema', null, state, options);
  371. });
  372. }
  373. with(key, peers) {
  374. Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.');
  375. return this._dependency('with', key, peers);
  376. }
  377. without(key, peers) {
  378. Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.');
  379. return this._dependency('without', key, peers);
  380. }
  381. xor(...peers) {
  382. peers = Hoek.flatten(peers);
  383. return this._dependency('xor', null, peers);
  384. }
  385. oxor(...peers) {
  386. return this._dependency('oxor', null, peers);
  387. }
  388. or(...peers) {
  389. peers = Hoek.flatten(peers);
  390. return this._dependency('or', null, peers);
  391. }
  392. and(...peers) {
  393. peers = Hoek.flatten(peers);
  394. return this._dependency('and', null, peers);
  395. }
  396. nand(...peers) {
  397. peers = Hoek.flatten(peers);
  398. return this._dependency('nand', null, peers);
  399. }
  400. requiredKeys(...children) {
  401. children = Hoek.flatten(children);
  402. return this.applyFunctionToChildren(children, 'required');
  403. }
  404. optionalKeys(...children) {
  405. children = Hoek.flatten(children);
  406. return this.applyFunctionToChildren(children, 'optional');
  407. }
  408. forbiddenKeys(...children) {
  409. children = Hoek.flatten(children);
  410. return this.applyFunctionToChildren(children, 'forbidden');
  411. }
  412. rename(from, to, options) {
  413. Hoek.assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument');
  414. Hoek.assert(typeof to === 'string', 'Rename missing the to argument');
  415. Hoek.assert(to !== from, 'Cannot rename key to same name:', from);
  416. for (let i = 0; i < this._inner.renames.length; ++i) {
  417. Hoek.assert(this._inner.renames[i].from !== from, 'Cannot rename the same key multiple times');
  418. }
  419. const obj = this.clone();
  420. obj._inner.renames.push({
  421. from,
  422. to,
  423. options: Hoek.applyToDefaults(internals.renameDefaults, options || {}),
  424. isRegExp: from instanceof RegExp
  425. });
  426. return obj;
  427. }
  428. applyFunctionToChildren(children, fn, args = [], root) {
  429. children = [].concat(children);
  430. Hoek.assert(children.length > 0, 'expected at least one children');
  431. const groupedChildren = internals.groupChildren(children);
  432. let obj;
  433. if ('' in groupedChildren) {
  434. obj = this[fn](...args);
  435. delete groupedChildren[''];
  436. }
  437. else {
  438. obj = this.clone();
  439. }
  440. if (obj._inner.children) {
  441. root = root ? (root + '.') : '';
  442. for (let i = 0; i < obj._inner.children.length; ++i) {
  443. const child = obj._inner.children[i];
  444. const group = groupedChildren[child.key];
  445. if (group) {
  446. obj._inner.children[i] = {
  447. key: child.key,
  448. _refs: child._refs,
  449. schema: child.schema.applyFunctionToChildren(group, fn, args, root + child.key)
  450. };
  451. delete groupedChildren[child.key];
  452. }
  453. }
  454. }
  455. const remaining = Object.keys(groupedChildren);
  456. Hoek.assert(remaining.length === 0, 'unknown key(s)', remaining.join(', '));
  457. return obj;
  458. }
  459. _dependency(type, key, peers) {
  460. peers = [].concat(peers);
  461. for (let i = 0; i < peers.length; ++i) {
  462. Hoek.assert(typeof peers[i] === 'string', type, 'peers must be a string or array of strings');
  463. }
  464. const obj = this.clone();
  465. obj._inner.dependencies.push({ type, key, peers });
  466. return obj;
  467. }
  468. describe(shallow) {
  469. const description = super.describe();
  470. if (description.rules) {
  471. for (let i = 0; i < description.rules.length; ++i) {
  472. const rule = description.rules[i];
  473. // Coverage off for future-proof descriptions, only object().assert() is use right now
  474. if (/* $lab:coverage:off$ */rule.arg &&
  475. typeof rule.arg === 'object' &&
  476. rule.arg.schema &&
  477. rule.arg.ref /* $lab:coverage:on$ */) {
  478. rule.arg = {
  479. schema: rule.arg.schema.describe(),
  480. ref: rule.arg.ref.toString()
  481. };
  482. }
  483. }
  484. }
  485. if (this._inner.children &&
  486. !shallow) {
  487. description.children = {};
  488. for (let i = 0; i < this._inner.children.length; ++i) {
  489. const child = this._inner.children[i];
  490. description.children[child.key] = child.schema.describe();
  491. }
  492. }
  493. if (this._inner.dependencies.length) {
  494. description.dependencies = Hoek.clone(this._inner.dependencies);
  495. }
  496. if (this._inner.patterns.length) {
  497. description.patterns = [];
  498. for (let i = 0; i < this._inner.patterns.length; ++i) {
  499. const pattern = this._inner.patterns[i];
  500. if (pattern.regex) {
  501. description.patterns.push({ regex: pattern.regex.toString(), rule: pattern.rule.describe() });
  502. }
  503. else {
  504. description.patterns.push({ schema: pattern.schema.describe(), rule: pattern.rule.describe() });
  505. }
  506. }
  507. }
  508. if (this._inner.renames.length > 0) {
  509. description.renames = Hoek.clone(this._inner.renames);
  510. }
  511. return description;
  512. }
  513. assert(ref, schema, message) {
  514. ref = Cast.ref(ref);
  515. Hoek.assert(ref.isContext || ref.depth > 1, 'Cannot use assertions for root level references - use direct key rules instead');
  516. message = message || 'pass the assertion test';
  517. Hoek.assert(typeof message === 'string', 'Message must be a string');
  518. try {
  519. schema = Cast.schema(this._currentJoi, schema);
  520. }
  521. catch (castErr) {
  522. if (castErr.hasOwnProperty('path')) {
  523. castErr.message = `${castErr.message}(${castErr.path})`;
  524. }
  525. throw castErr;
  526. }
  527. const key = ref.path[ref.path.length - 1];
  528. const path = ref.path.join('.');
  529. return this._test('assert', { schema, ref }, function (value, state, options) {
  530. const result = schema._validate(ref(value), null, options, value);
  531. if (!result.errors) {
  532. return value;
  533. }
  534. const localState = new State(key, ref.path, state.parent, state.reference);
  535. return this.createError('object.assert', { ref: path, message }, localState, options);
  536. });
  537. }
  538. type(constructor, name = constructor.name) {
  539. Hoek.assert(typeof constructor === 'function', 'type must be a constructor function');
  540. const typeData = {
  541. name,
  542. ctor: constructor
  543. };
  544. return this._test('type', typeData, function (value, state, options) {
  545. if (value instanceof constructor) {
  546. return value;
  547. }
  548. return this.createError('object.type', { type: typeData.name, value }, state, options);
  549. });
  550. }
  551. };
  552. internals.renameDefaults = {
  553. alias: false, // Keep old value in place
  554. multiple: false, // Allow renaming multiple keys into the same target
  555. override: false // Overrides an existing key
  556. };
  557. internals.groupChildren = function (children) {
  558. children.sort();
  559. const grouped = {};
  560. for (let i = 0; i < children.length; ++i) {
  561. const child = children[i];
  562. Hoek.assert(typeof child === 'string', 'children must be strings');
  563. const group = child.split('.')[0];
  564. const childGroup = grouped[group] = (grouped[group] || []);
  565. childGroup.push(child.substring(group.length + 1));
  566. }
  567. return grouped;
  568. };
  569. internals.keysToLabels = function (schema, keys) {
  570. const children = schema._inner.children;
  571. if (!children) {
  572. return keys;
  573. }
  574. const findLabel = function (key) {
  575. const matchingChild = schema._currentJoi.reach(schema, key);
  576. return matchingChild ? matchingChild._getLabel(key) : key;
  577. };
  578. if (Array.isArray(keys)) {
  579. return keys.map(findLabel);
  580. }
  581. return findLabel(keys);
  582. };
  583. internals.with = function (key, value, peers, parent, state, options) {
  584. if (value === undefined) {
  585. return;
  586. }
  587. for (let i = 0; i < peers.length; ++i) {
  588. const peer = peers[i];
  589. const keysExist = Hoek.reach(parent, peer, { functions: true });
  590. if (keysExist === undefined) {
  591. return this.createError('object.with', {
  592. main: key,
  593. mainWithLabel: internals.keysToLabels(this, key),
  594. peer,
  595. peerWithLabel: internals.keysToLabels(this, peer)
  596. }, state, options);
  597. }
  598. }
  599. };
  600. internals.without = function (key, value, peers, parent, state, options) {
  601. if (value === undefined) {
  602. return;
  603. }
  604. for (let i = 0; i < peers.length; ++i) {
  605. const peer = peers[i];
  606. const keysExist = Hoek.reach(parent, peer, { functions: true });
  607. if (keysExist !== undefined) {
  608. return this.createError('object.without', {
  609. main: key,
  610. mainWithLabel: internals.keysToLabels(this, key),
  611. peer,
  612. peerWithLabel: internals.keysToLabels(this, peer)
  613. }, state, options);
  614. }
  615. }
  616. };
  617. internals.xor = function (key, value, peers, parent, state, options) {
  618. const present = [];
  619. for (let i = 0; i < peers.length; ++i) {
  620. const peer = peers[i];
  621. const keysExist = Hoek.reach(parent, peer, { functions: true });
  622. if (keysExist !== undefined) {
  623. present.push(peer);
  624. }
  625. }
  626. if (present.length === 1) {
  627. return;
  628. }
  629. const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) };
  630. if (present.length === 0) {
  631. return this.createError('object.missing', context, state, options);
  632. }
  633. context.present = present;
  634. context.presentWithLabels = internals.keysToLabels(this, present);
  635. return this.createError('object.xor', context, state, options);
  636. };
  637. internals.oxor = function (key, value, peers, parent, state, options) {
  638. const present = [];
  639. for (let i = 0; i < peers.length; ++i) {
  640. const peer = peers[i];
  641. const keysExist = Hoek.reach(parent, peer, { functions: true });
  642. if (keysExist !== undefined) {
  643. present.push(peer);
  644. }
  645. }
  646. if (!present.length ||
  647. present.length === 1) {
  648. return;
  649. }
  650. const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) };
  651. context.present = present;
  652. context.presentWithLabels = internals.keysToLabels(this, present);
  653. return this.createError('object.oxor', context, state, options);
  654. };
  655. internals.or = function (key, value, peers, parent, state, options) {
  656. for (let i = 0; i < peers.length; ++i) {
  657. const peer = peers[i];
  658. const keysExist = Hoek.reach(parent, peer, { functions: true });
  659. if (keysExist !== undefined) {
  660. return;
  661. }
  662. }
  663. return this.createError('object.missing', {
  664. peers,
  665. peersWithLabels: internals.keysToLabels(this, peers)
  666. }, state, options);
  667. };
  668. internals.and = function (key, value, peers, parent, state, options) {
  669. const missing = [];
  670. const present = [];
  671. const count = peers.length;
  672. for (let i = 0; i < count; ++i) {
  673. const peer = peers[i];
  674. const keysExist = Hoek.reach(parent, peer, { functions: true });
  675. if (keysExist === undefined) {
  676. missing.push(peer);
  677. }
  678. else {
  679. present.push(peer);
  680. }
  681. }
  682. const aon = (missing.length === count || present.length === count);
  683. if (!aon) {
  684. return this.createError('object.and', {
  685. present,
  686. presentWithLabels: internals.keysToLabels(this, present),
  687. missing,
  688. missingWithLabels: internals.keysToLabels(this, missing)
  689. }, state, options);
  690. }
  691. };
  692. internals.nand = function (key, value, peers, parent, state, options) {
  693. const present = [];
  694. for (let i = 0; i < peers.length; ++i) {
  695. const peer = peers[i];
  696. const keysExist = Hoek.reach(parent, peer, { functions: true });
  697. if (keysExist !== undefined) {
  698. present.push(peer);
  699. }
  700. }
  701. const main = peers[0];
  702. const values = peers.slice(1);
  703. const allPresent = (present.length === peers.length);
  704. return allPresent ? this.createError('object.nand', {
  705. main,
  706. mainWithLabel: internals.keysToLabels(this, main),
  707. peers: values,
  708. peersWithLabels: internals.keysToLabels(this, values)
  709. }, state, options) : null;
  710. };
  711. module.exports = new internals.Object();