index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. 'use strict';
  2. // Load modules
  3. const Assert = require('assert');
  4. const Crypto = require('crypto');
  5. const Path = require('path');
  6. const DeepEqual = require('./deep-equal');
  7. const Escape = require('./escape');
  8. const Types = require('./types');
  9. // Declare internals
  10. const internals = {
  11. needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap])
  12. };
  13. // Deep object or array comparison
  14. exports.deepEqual = DeepEqual;
  15. // Clone object or array
  16. exports.clone = function (obj, options = {}, _seen = null) {
  17. if (typeof obj !== 'object' ||
  18. obj === null) {
  19. return obj;
  20. }
  21. const seen = _seen || new Map();
  22. const lookup = seen.get(obj);
  23. if (lookup) {
  24. return lookup;
  25. }
  26. const baseProto = Types.getInternalProto(obj);
  27. let newObj;
  28. switch (baseProto) {
  29. case Types.buffer:
  30. return Buffer.from(obj);
  31. case Types.date:
  32. return new Date(obj.getTime());
  33. case Types.regex:
  34. return new RegExp(obj);
  35. case Types.array:
  36. newObj = [];
  37. break;
  38. default:
  39. if (options.prototype !== false) { // Defaults to true
  40. const proto = Object.getPrototypeOf(obj);
  41. if (proto &&
  42. proto.isImmutable) {
  43. return obj;
  44. }
  45. if (internals.needsProtoHack.has(baseProto)) {
  46. newObj = new proto.constructor();
  47. if (proto !== baseProto) {
  48. Object.setPrototypeOf(newObj, proto);
  49. }
  50. }
  51. else {
  52. newObj = Object.create(proto);
  53. }
  54. }
  55. else if (internals.needsProtoHack.has(baseProto)) {
  56. newObj = new baseProto.constructor();
  57. }
  58. else {
  59. newObj = {};
  60. }
  61. }
  62. seen.set(obj, newObj); // Set seen, since obj could recurse
  63. if (baseProto === Types.set) {
  64. for (const value of obj) {
  65. newObj.add(exports.clone(value, options, seen));
  66. }
  67. }
  68. else if (baseProto === Types.map) {
  69. for (const [key, value] of obj) {
  70. newObj.set(key, exports.clone(value, options, seen));
  71. }
  72. }
  73. const keys = internals.keys(obj, options);
  74. for (let i = 0; i < keys.length; ++i) {
  75. const key = keys[i];
  76. if (baseProto === Types.array &&
  77. key === 'length') {
  78. continue;
  79. }
  80. const descriptor = Object.getOwnPropertyDescriptor(obj, key);
  81. if (descriptor &&
  82. (descriptor.get ||
  83. descriptor.set)) {
  84. Object.defineProperty(newObj, key, descriptor);
  85. }
  86. else {
  87. Object.defineProperty(newObj, key, {
  88. enumerable: descriptor ? descriptor.enumerable : true,
  89. writable: true,
  90. configurable: true,
  91. value: exports.clone(obj[key], options, seen)
  92. });
  93. }
  94. }
  95. if (baseProto === Types.array) {
  96. newObj.length = obj.length;
  97. }
  98. return newObj;
  99. };
  100. internals.keys = function (obj, options = {}) {
  101. return options.symbols ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj);
  102. };
  103. // Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
  104. exports.merge = function (target, source, isNullOverride = true, isMergeArrays = true) {
  105. exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
  106. exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
  107. if (!source) {
  108. return target;
  109. }
  110. if (Array.isArray(source)) {
  111. exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
  112. if (!isMergeArrays) {
  113. target.length = 0; // Must not change target assignment
  114. }
  115. for (let i = 0; i < source.length; ++i) {
  116. target.push(exports.clone(source[i]));
  117. }
  118. return target;
  119. }
  120. const keys = internals.keys(source);
  121. for (let i = 0; i < keys.length; ++i) {
  122. const key = keys[i];
  123. if (key === '__proto__' ||
  124. !Object.prototype.propertyIsEnumerable.call(source, key)) {
  125. continue;
  126. }
  127. const value = source[key];
  128. if (value &&
  129. typeof value === 'object') {
  130. if (!target[key] ||
  131. typeof target[key] !== 'object' ||
  132. (Array.isArray(target[key]) !== Array.isArray(value)) ||
  133. value instanceof Date ||
  134. Buffer.isBuffer(value) ||
  135. value instanceof RegExp) {
  136. target[key] = exports.clone(value);
  137. }
  138. else {
  139. exports.merge(target[key], value, isNullOverride, isMergeArrays);
  140. }
  141. }
  142. else {
  143. if (value !== null &&
  144. value !== undefined) { // Explicit to preserve empty strings
  145. target[key] = value;
  146. }
  147. else if (isNullOverride) {
  148. target[key] = value;
  149. }
  150. }
  151. }
  152. return target;
  153. };
  154. // Apply options to a copy of the defaults
  155. exports.applyToDefaults = function (defaults, options, isNullOverride = false) {
  156. exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
  157. exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
  158. if (!options) { // If no options, return null
  159. return null;
  160. }
  161. const copy = exports.clone(defaults);
  162. if (options === true) { // If options is set to true, use defaults
  163. return copy;
  164. }
  165. return exports.merge(copy, options, isNullOverride, false);
  166. };
  167. // Clone an object except for the listed keys which are shallow copied
  168. exports.cloneWithShallow = function (source, keys, options) {
  169. if (!source ||
  170. typeof source !== 'object') {
  171. return source;
  172. }
  173. const storage = internals.store(source, keys); // Move shallow copy items to storage
  174. const copy = exports.clone(source, options); // Deep copy the rest
  175. internals.restore(copy, source, storage); // Shallow copy the stored items and restore
  176. return copy;
  177. };
  178. internals.store = function (source, keys) {
  179. const storage = new Map();
  180. for (let i = 0; i < keys.length; ++i) {
  181. const key = keys[i];
  182. const value = exports.reach(source, key);
  183. if (typeof value === 'object' ||
  184. typeof value === 'function') {
  185. storage.set(key, value);
  186. internals.reachSet(source, key, undefined);
  187. }
  188. }
  189. return storage;
  190. };
  191. internals.restore = function (copy, source, storage) {
  192. for (const [key, value] of storage) {
  193. internals.reachSet(copy, key, value);
  194. internals.reachSet(source, key, value);
  195. }
  196. };
  197. internals.reachSet = function (obj, key, value) {
  198. const path = Array.isArray(key) ? key : key.split('.');
  199. let ref = obj;
  200. for (let i = 0; i < path.length; ++i) {
  201. const segment = path[i];
  202. if (i + 1 === path.length) {
  203. ref[segment] = value;
  204. }
  205. ref = ref[segment];
  206. }
  207. };
  208. // Apply options to defaults except for the listed keys which are shallow copied from option without merging
  209. exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
  210. exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
  211. exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
  212. exports.assert(keys && Array.isArray(keys), 'Invalid keys');
  213. if (!options) { // If no options, return null
  214. return null;
  215. }
  216. const copy = exports.cloneWithShallow(defaults, keys);
  217. if (options === true) { // If options is set to true, use defaults
  218. return copy;
  219. }
  220. const storage = internals.store(options, keys); // Move shallow copy items to storage
  221. exports.merge(copy, options, false, false); // Deep copy the rest
  222. internals.restore(copy, options, storage); // Shallow copy the stored items and restore
  223. return copy;
  224. };
  225. // Find the common unique items in two arrays
  226. exports.intersect = function (array1, array2, justFirst = false) {
  227. if (!array1 ||
  228. !array2) {
  229. return (justFirst ? null : []);
  230. }
  231. const common = [];
  232. const hash = (Array.isArray(array1) ? new Set(array1) : array1);
  233. const found = new Set();
  234. for (const value of array2) {
  235. if (internals.has(hash, value) &&
  236. !found.has(value)) {
  237. if (justFirst) {
  238. return value;
  239. }
  240. common.push(value);
  241. found.add(value);
  242. }
  243. }
  244. return (justFirst ? null : common);
  245. };
  246. internals.has = function (ref, key) {
  247. if (typeof ref.has === 'function') {
  248. return ref.has(key);
  249. }
  250. return ref[key] !== undefined;
  251. };
  252. // Test if the reference contains the values
  253. exports.contain = function (ref, values, options = {}) { // options: { deep, once, only, part, symbols }
  254. /*
  255. string -> string(s)
  256. array -> item(s)
  257. object -> key(s)
  258. object -> object (key:value)
  259. */
  260. let valuePairs = null;
  261. if (typeof ref === 'object' &&
  262. typeof values === 'object' &&
  263. !Array.isArray(ref) &&
  264. !Array.isArray(values)) {
  265. valuePairs = values;
  266. const symbols = Object.getOwnPropertySymbols(values).filter(Object.prototype.propertyIsEnumerable.bind(values));
  267. values = [...Object.keys(values), ...symbols];
  268. }
  269. else {
  270. values = [].concat(values);
  271. }
  272. exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
  273. exports.assert(values.length, 'Values array cannot be empty');
  274. let compare;
  275. let compareFlags;
  276. if (options.deep) {
  277. compare = exports.deepEqual;
  278. const hasOnly = options.only !== undefined;
  279. const hasPart = options.part !== undefined;
  280. compareFlags = {
  281. prototype: hasOnly ? options.only : hasPart ? !options.part : false,
  282. part: hasOnly ? !options.only : hasPart ? options.part : false
  283. };
  284. }
  285. else {
  286. compare = (a, b) => a === b;
  287. }
  288. let misses = false;
  289. const matches = new Array(values.length);
  290. for (let i = 0; i < matches.length; ++i) {
  291. matches[i] = 0;
  292. }
  293. if (typeof ref === 'string') {
  294. let pattern = '(';
  295. for (let i = 0; i < values.length; ++i) {
  296. const value = values[i];
  297. exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
  298. pattern += (i ? '|' : '') + exports.escapeRegex(value);
  299. }
  300. const regex = new RegExp(pattern + ')', 'g');
  301. const leftovers = ref.replace(regex, ($0, $1) => {
  302. const index = values.indexOf($1);
  303. ++matches[index];
  304. return ''; // Remove from string
  305. });
  306. misses = !!leftovers;
  307. }
  308. else if (Array.isArray(ref)) {
  309. const onlyOnce = !!(options.only && options.once);
  310. if (onlyOnce && ref.length !== values.length) {
  311. return false;
  312. }
  313. for (let i = 0; i < ref.length; ++i) {
  314. let matched = false;
  315. for (let j = 0; j < values.length && matched === false; ++j) {
  316. if (!onlyOnce || matches[j] === 0) {
  317. matched = compare(values[j], ref[i], compareFlags) && j;
  318. }
  319. }
  320. if (matched !== false) {
  321. ++matches[matched];
  322. }
  323. else {
  324. misses = true;
  325. }
  326. }
  327. }
  328. else {
  329. const keys = internals.keys(ref, options);
  330. for (let i = 0; i < keys.length; ++i) {
  331. const key = keys[i];
  332. const pos = values.indexOf(key);
  333. if (pos !== -1) {
  334. if (valuePairs &&
  335. !compare(valuePairs[key], ref[key], compareFlags)) {
  336. return false;
  337. }
  338. ++matches[pos];
  339. }
  340. else {
  341. misses = true;
  342. }
  343. }
  344. }
  345. if (options.only) {
  346. if (misses || !options.once) {
  347. return !misses;
  348. }
  349. }
  350. let result = false;
  351. for (let i = 0; i < matches.length; ++i) {
  352. result = result || !!matches[i];
  353. if ((options.once && matches[i] > 1) ||
  354. (!options.part && !matches[i])) {
  355. return false;
  356. }
  357. }
  358. return result;
  359. };
  360. // Flatten array
  361. exports.flatten = function (array, target) {
  362. const result = target || [];
  363. for (let i = 0; i < array.length; ++i) {
  364. if (Array.isArray(array[i])) {
  365. exports.flatten(array[i], result);
  366. }
  367. else {
  368. result.push(array[i]);
  369. }
  370. }
  371. return result;
  372. };
  373. // Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
  374. exports.reach = function (obj, chain, options) {
  375. if (chain === false ||
  376. chain === null ||
  377. chain === undefined) {
  378. return obj;
  379. }
  380. options = options || {};
  381. if (typeof options === 'string') {
  382. options = { separator: options };
  383. }
  384. const isChainArray = Array.isArray(chain);
  385. exports.assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain');
  386. const path = isChainArray ? chain : chain.split(options.separator || '.');
  387. let ref = obj;
  388. for (let i = 0; i < path.length; ++i) {
  389. let key = path[i];
  390. if (Array.isArray(ref)) {
  391. const number = Number(key);
  392. if (Number.isInteger(number) && number < 0) {
  393. key = ref.length + number;
  394. }
  395. }
  396. if (!ref ||
  397. !((typeof ref === 'object' || typeof ref === 'function') && key in ref) ||
  398. (typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties
  399. exports.assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain);
  400. exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
  401. ref = options.default;
  402. break;
  403. }
  404. ref = ref[key];
  405. }
  406. return ref;
  407. };
  408. exports.reachTemplate = function (obj, template, options) {
  409. return template.replace(/{([^}]+)}/g, ($0, chain) => {
  410. const value = exports.reach(obj, chain, options);
  411. return (value === undefined || value === null ? '' : value);
  412. });
  413. };
  414. exports.assert = function (condition, ...args) {
  415. if (condition) {
  416. return;
  417. }
  418. if (args.length === 1 && args[0] instanceof Error) {
  419. throw args[0];
  420. }
  421. const msgs = args
  422. .filter((arg) => arg !== '')
  423. .map((arg) => {
  424. return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : exports.stringify(arg);
  425. });
  426. throw new Assert.AssertionError({
  427. message: msgs.join(' ') || 'Unknown error',
  428. actual: false,
  429. expected: true,
  430. operator: '==',
  431. stackStartFunction: exports.assert
  432. });
  433. };
  434. exports.Bench = class {
  435. constructor() {
  436. this.ts = 0;
  437. this.reset();
  438. }
  439. reset() {
  440. this.ts = exports.Bench.now();
  441. }
  442. elapsed() {
  443. return exports.Bench.now() - this.ts;
  444. }
  445. static now() {
  446. const ts = process.hrtime();
  447. return (ts[0] * 1e3) + (ts[1] / 1e6);
  448. }
  449. };
  450. // Escape string for Regex construction
  451. exports.escapeRegex = function (string) {
  452. // Escape ^$.*+-?=!:|\/()[]{},
  453. return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
  454. };
  455. // Escape attribute value for use in HTTP header
  456. exports.escapeHeaderAttribute = function (attribute) {
  457. // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
  458. exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
  459. return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash
  460. };
  461. exports.escapeHtml = function (string) {
  462. return Escape.escapeHtml(string);
  463. };
  464. exports.escapeJson = function (string) {
  465. return Escape.escapeJson(string);
  466. };
  467. exports.once = function (method) {
  468. if (method._hoekOnce) {
  469. return method;
  470. }
  471. let once = false;
  472. const wrapped = function (...args) {
  473. if (!once) {
  474. once = true;
  475. method(...args);
  476. }
  477. };
  478. wrapped._hoekOnce = true;
  479. return wrapped;
  480. };
  481. exports.ignore = function () { };
  482. exports.uniqueFilename = function (path, extension) {
  483. if (extension) {
  484. extension = extension[0] !== '.' ? '.' + extension : extension;
  485. }
  486. else {
  487. extension = '';
  488. }
  489. path = Path.resolve(path);
  490. const name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
  491. return Path.join(path, name);
  492. };
  493. exports.stringify = function (...args) {
  494. try {
  495. return JSON.stringify.apply(null, args);
  496. }
  497. catch (err) {
  498. return '[Cannot display object: ' + err.message + ']';
  499. }
  500. };
  501. exports.wait = function (timeout) {
  502. return new Promise((resolve) => setTimeout(resolve, timeout));
  503. };
  504. exports.block = function () {
  505. return new Promise(exports.ignore);
  506. };