PageRenderTime 35ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/grunt-contrib-imagemin/node_modules/pngquant-bin/node_modules/bin-wrapper/node_modules/download/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js

https://gitlab.com/marvin1/soundcloud
JavaScript | 585 lines | 368 code | 188 blank | 29 comment | 79 complexity | 14e7dccb5eaed2ff9993ea8a35d77c87 MD5 | raw file
  1. // Load modules
  2. var Fs = require('fs');
  3. var Escape = require('./escape');
  4. // Declare internals
  5. var internals = {};
  6. // Clone object or array
  7. exports.clone = function (obj, seen) {
  8. if (typeof obj !== 'object' ||
  9. obj === null) {
  10. return obj;
  11. }
  12. seen = seen || { orig: [], copy: [] };
  13. var lookup = seen.orig.indexOf(obj);
  14. if (lookup !== -1) {
  15. return seen.copy[lookup];
  16. }
  17. var newObj = (obj instanceof Array) ? [] : {};
  18. seen.orig.push(obj);
  19. seen.copy.push(newObj);
  20. for (var i in obj) {
  21. if (obj.hasOwnProperty(i)) {
  22. if (obj[i] instanceof Buffer) {
  23. newObj[i] = new Buffer(obj[i]);
  24. }
  25. else if (obj[i] instanceof Date) {
  26. newObj[i] = new Date(obj[i].getTime());
  27. }
  28. else if (obj[i] instanceof RegExp) {
  29. var flags = '' + (obj[i].global ? 'g' : '') + (obj[i].ignoreCase ? 'i' : '') + (obj[i].multiline ? 'm' : '');
  30. newObj[i] = new RegExp(obj[i].source, flags);
  31. }
  32. else {
  33. newObj[i] = exports.clone(obj[i], seen);
  34. }
  35. }
  36. }
  37. return newObj;
  38. };
  39. // Merge all the properties of source into target, source wins in conflic, and by default null and undefined from source are applied
  40. exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
  41. exports.assert(target && typeof target == 'object', 'Invalid target value: must be an object');
  42. exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
  43. if (!source) {
  44. return target;
  45. }
  46. if (source instanceof Array) {
  47. exports.assert(target instanceof Array, 'Cannot merge array onto an object');
  48. if (isMergeArrays === false) { // isMergeArrays defaults to true
  49. target.length = 0; // Must not change target assignment
  50. }
  51. for (var i = 0, il = source.length; i < il; ++i) {
  52. target.push(source[i]);
  53. }
  54. return target;
  55. }
  56. var keys = Object.keys(source);
  57. for (var k = 0, kl = keys.length; k < kl; ++k) {
  58. var key = keys[k];
  59. var value = source[key];
  60. if (value &&
  61. typeof value === 'object') {
  62. if (!target[key] ||
  63. typeof target[key] !== 'object') {
  64. target[key] = exports.clone(value);
  65. }
  66. else {
  67. exports.merge(target[key], source[key], isNullOverride, isMergeArrays);
  68. }
  69. }
  70. else {
  71. if (value !== null && value !== undefined) { // Explicit to preserve empty strings
  72. target[key] = value;
  73. }
  74. else if (isNullOverride !== false) { // Defaults to true
  75. target[key] = value;
  76. }
  77. }
  78. }
  79. return target;
  80. };
  81. // Apply options to a copy of the defaults
  82. exports.applyToDefaults = function (defaults, options) {
  83. exports.assert(defaults && typeof defaults == 'object', 'Invalid defaults value: must be an object');
  84. exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
  85. if (!options) { // If no options, return null
  86. return null;
  87. }
  88. var copy = exports.clone(defaults);
  89. if (options === true) { // If options is set to true, use defaults
  90. return copy;
  91. }
  92. return exports.merge(copy, options, false, false);
  93. };
  94. // Remove duplicate items from array
  95. exports.unique = function (array, key) {
  96. var index = {};
  97. var result = [];
  98. for (var i = 0, il = array.length; i < il; ++i) {
  99. var id = (key ? array[i][key] : array[i]);
  100. if (index[id] !== true) {
  101. result.push(array[i]);
  102. index[id] = true;
  103. }
  104. }
  105. return result;
  106. };
  107. // Convert array into object
  108. exports.mapToObject = function (array, key) {
  109. if (!array) {
  110. return null;
  111. }
  112. var obj = {};
  113. for (var i = 0, il = array.length; i < il; ++i) {
  114. if (key) {
  115. if (array[i][key]) {
  116. obj[array[i][key]] = true;
  117. }
  118. }
  119. else {
  120. obj[array[i]] = true;
  121. }
  122. }
  123. return obj;
  124. };
  125. // Find the common unique items in two arrays
  126. exports.intersect = function (array1, array2, justFirst) {
  127. if (!array1 || !array2) {
  128. return [];
  129. }
  130. var common = [];
  131. var hash = (array1 instanceof Array ? exports.mapToObject(array1) : array1);
  132. var found = {};
  133. for (var i = 0, il = array2.length; i < il; ++i) {
  134. if (hash[array2[i]] && !found[array2[i]]) {
  135. if (justFirst) {
  136. return array2[i];
  137. }
  138. common.push(array2[i]);
  139. found[array2[i]] = true;
  140. }
  141. }
  142. return (justFirst ? null : common);
  143. };
  144. // Find which keys are present
  145. exports.matchKeys = function (obj, keys) {
  146. var matched = [];
  147. for (var i = 0, il = keys.length; i < il; ++i) {
  148. if (obj.hasOwnProperty(keys[i])) {
  149. matched.push(keys[i]);
  150. }
  151. }
  152. return matched;
  153. };
  154. // Flatten array
  155. exports.flatten = function (array, target) {
  156. var result = target || [];
  157. for (var i = 0, il = array.length; i < il; ++i) {
  158. if (Array.isArray(array[i])) {
  159. exports.flatten(array[i], result);
  160. }
  161. else {
  162. result.push(array[i]);
  163. }
  164. }
  165. return result;
  166. };
  167. // Remove keys
  168. exports.removeKeys = function (object, keys) {
  169. for (var i = 0, il = keys.length; i < il; i++) {
  170. delete object[keys[i]];
  171. }
  172. };
  173. // Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
  174. exports.reach = function (obj, chain) {
  175. var path = chain.split('.');
  176. var ref = obj;
  177. for (var i = 0, il = path.length; i < il; ++i) {
  178. if (ref) {
  179. ref = ref[path[i]];
  180. }
  181. }
  182. return ref;
  183. };
  184. // Inherits a selected set of methods from an object, wrapping functions in asynchronous syntax and catching errors
  185. exports.inheritAsync = function (self, obj, keys) {
  186. keys = keys || null;
  187. for (var i in obj) {
  188. if (obj.hasOwnProperty(i)) {
  189. if (keys instanceof Array &&
  190. keys.indexOf(i) < 0) {
  191. continue;
  192. }
  193. self.prototype[i] = (function (fn) {
  194. return function (next) {
  195. var result = null;
  196. try {
  197. result = fn();
  198. }
  199. catch (err) {
  200. return next(err);
  201. }
  202. return next(null, result);
  203. };
  204. })(obj[i]);
  205. }
  206. }
  207. };
  208. exports.formatStack = function (stack) {
  209. var trace = [];
  210. for (var i = 0, il = stack.length; i < il; ++i) {
  211. var item = stack[i];
  212. trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
  213. }
  214. return trace;
  215. };
  216. exports.formatTrace = function (trace) {
  217. var display = [];
  218. for (var i = 0, il = trace.length; i < il; ++i) {
  219. var row = trace[i];
  220. display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
  221. }
  222. return display;
  223. };
  224. exports.callStack = function (slice) {
  225. // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  226. var v8 = Error.prepareStackTrace;
  227. Error.prepareStackTrace = function (err, stack) {
  228. return stack;
  229. };
  230. var capture = {};
  231. Error.captureStackTrace(capture, arguments.callee);
  232. var stack = capture.stack;
  233. Error.prepareStackTrace = v8;
  234. var trace = exports.formatStack(stack);
  235. if (slice) {
  236. return trace.slice(slice);
  237. }
  238. return trace;
  239. };
  240. exports.displayStack = function (slice) {
  241. var trace = exports.callStack(slice === undefined ? 1 : slice + 1);
  242. return exports.formatTrace(trace);
  243. };
  244. exports.abortThrow = false;
  245. exports.abort = function (message, hideStack) {
  246. if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
  247. throw new Error(message || 'Unknown error');
  248. }
  249. var stack = '';
  250. if (!hideStack) {
  251. stack = exports.displayStack(1).join('\n\t');
  252. }
  253. console.log('ABORT: ' + message + '\n\t' + stack);
  254. process.exit(1);
  255. };
  256. exports.assert = function (condition /*, msg1, msg2, msg3 */) {
  257. if (condition) {
  258. return;
  259. }
  260. var msgs = Array.prototype.slice.call(arguments, 1);
  261. msgs = msgs.map(function (msg) {
  262. return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : JSON.stringify(msg);
  263. });
  264. throw new Error(msgs.join(' ') || 'Unknown error');
  265. };
  266. exports.loadDirModules = function (path, excludeFiles, target) { // target(filename, name, capName)
  267. var exclude = {};
  268. for (var i = 0, il = excludeFiles.length; i < il; ++i) {
  269. exclude[excludeFiles[i] + '.js'] = true;
  270. }
  271. var files = Fs.readdirSync(path);
  272. for (i = 0, il = files.length; i < il; ++i) {
  273. var filename = files[i];
  274. if (/\.js$/.test(filename) &&
  275. !exclude[filename]) {
  276. var name = filename.substr(0, filename.lastIndexOf('.'));
  277. var capName = name.charAt(0).toUpperCase() + name.substr(1).toLowerCase();
  278. if (typeof target !== 'function') {
  279. target[capName] = require(path + '/' + name);
  280. }
  281. else {
  282. target(path + '/' + name, name, capName);
  283. }
  284. }
  285. }
  286. };
  287. exports.rename = function (obj, from, to) {
  288. obj[to] = obj[from];
  289. delete obj[from];
  290. };
  291. exports.Timer = function () {
  292. this.reset();
  293. };
  294. exports.Timer.prototype.reset = function () {
  295. this.ts = Date.now();
  296. };
  297. exports.Timer.prototype.elapsed = function () {
  298. return Date.now() - this.ts;
  299. };
  300. // Load and parse package.json process root or given directory
  301. exports.loadPackage = function (dir) {
  302. var result = {};
  303. var filepath = (dir || process.env.PWD) + '/package.json';
  304. if (Fs.existsSync(filepath)) {
  305. try {
  306. result = JSON.parse(Fs.readFileSync(filepath));
  307. }
  308. catch (e) { }
  309. }
  310. return result;
  311. };
  312. // Escape string for Regex construction
  313. exports.escapeRegex = function (string) {
  314. // Escape ^$.*+-?=!:|\/()[]{},
  315. return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
  316. };
  317. // Return an error as first argument of a callback
  318. exports.toss = function (condition /*, [message], next */) {
  319. var message = (arguments.length === 3 ? arguments[1] : '');
  320. var next = (arguments.length === 3 ? arguments[2] : arguments[1]);
  321. var err = (message instanceof Error ? message : (message ? new Error(message) : (condition instanceof Error ? condition : new Error())));
  322. if (condition instanceof Error ||
  323. !condition) {
  324. return next(err);
  325. }
  326. };
  327. // Base64url (RFC 4648) encode
  328. exports.base64urlEncode = function (value) {
  329. return (new Buffer(value, 'binary')).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
  330. };
  331. // Base64url (RFC 4648) decode
  332. exports.base64urlDecode = function (encoded) {
  333. if (encoded &&
  334. !encoded.match(/^[\w\-]*$/)) {
  335. return new Error('Invalid character');
  336. }
  337. try {
  338. return (new Buffer(encoded.replace(/-/g, '+').replace(/:/g, '/'), 'base64')).toString('binary');
  339. }
  340. catch (err) {
  341. return err;
  342. }
  343. };
  344. // Escape attribute value for use in HTTP header
  345. exports.escapeHeaderAttribute = function (attribute) {
  346. // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
  347. exports.assert(attribute.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/), 'Bad attribute value (' + attribute + ')');
  348. return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash
  349. };
  350. exports.escapeHtml = function (string) {
  351. return Escape.escapeHtml(string);
  352. };
  353. exports.escapeJavaScript = function (string) {
  354. return Escape.escapeJavaScript(string);
  355. };
  356. /*
  357. var event = {
  358. timestamp: now.getTime(),
  359. tags: ['tag'],
  360. data: { some: 'data' }
  361. };
  362. */
  363. exports.consoleFunc = console.log;
  364. exports.printEvent = function (event) {
  365. var pad = function (value) {
  366. return (value < 10 ? '0' : '') + value;
  367. };
  368. var now = new Date(event.timestamp);
  369. var timestring = (now.getYear() - 100).toString() +
  370. pad(now.getMonth() + 1) +
  371. pad(now.getDate()) +
  372. '/' +
  373. pad(now.getHours()) +
  374. pad(now.getMinutes()) +
  375. pad(now.getSeconds()) +
  376. '.' +
  377. now.getMilliseconds();
  378. var data = event.data;
  379. if (typeof event.data !== 'string') {
  380. try {
  381. data = JSON.stringify(event.data);
  382. }
  383. catch (e) {
  384. data = 'JSON Error: ' + e.message;
  385. }
  386. }
  387. var output = timestring + ', ' + event.tags[0] + ', ' + data;
  388. exports.consoleFunc(output);
  389. };
  390. exports.nextTick = function (callback) {
  391. return function () {
  392. var args = arguments;
  393. process.nextTick(function () {
  394. callback.apply(null, args);
  395. });
  396. };
  397. };