UNPKG

14.1 kBJavaScriptView Raw
1"use strict";
2/**
3 * This file is part of the @egodigital/egoose distribution.
4 * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
5 *
6 * @egodigital/egoose is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * @egodigital/egoose is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18function __export(m) {
19 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20}
21Object.defineProperty(exports, "__esModule", { value: true });
22const child_process_1 = require("child_process");
23const _ = require("lodash");
24const crypto = require("crypto");
25const path = require("path");
26const moment = require("moment-timezone");
27const util = require("util");
28const UUID = require("uuid");
29const UUID_v5 = require("uuid/v5");
30const yargs = require("yargs-parser");
31/**
32 * Applies an object or value to a function.
33 *
34 * @param {TFunc} func The function to apply 'thisArg' to.
35 * @param {any} thisArg The object or value to apply to 'func'.
36 *
37 * @return {TFunc} The new function.
38 */
39function applyFuncFor(func, thisArg) {
40 return function () {
41 return func.apply(thisArg, arguments);
42 };
43}
44exports.applyFuncFor = applyFuncFor;
45/**
46 * Returns an input value as array.
47 *
48 * @param {T|T[]} val The input value.
49 * @param {boolean} [noEmpty] Remove values, which are (null) or (undefined).
50 *
51 * @return {T[]} The input value as array.
52 */
53function asArray(val, noEmpty = true) {
54 if (!Array.isArray(val)) {
55 val = [val];
56 }
57 return val.filter(x => {
58 if (noEmpty) {
59 return !_.isNil(x);
60 }
61 return true;
62 });
63}
64exports.asArray = asArray;
65/**
66 * Keeps sure that a value is a Moment instance (local timezone).
67 *
68 * @param {any} time The input value.
69 *
70 * @return {moment.Moment} The Moment instance.
71 */
72function asLocal(time) {
73 let result = asMoment(time);
74 if (!_.isNil(result)) {
75 if (result.isValid()) {
76 if (!result.isLocal()) {
77 result = result.local();
78 }
79 }
80 }
81 return result;
82}
83exports.asLocal = asLocal;
84/**
85 * Keeps sure that a value is a Moment instance.
86 *
87 * @param {any} val The input value.
88 *
89 * @return {moment.Moment} The Moment instance.
90 */
91function asMoment(val) {
92 if (_.isNil(val)) {
93 return val;
94 }
95 let result;
96 if (moment.isMoment(val)) {
97 result = val;
98 }
99 else if (moment.isDate(val)) {
100 result = moment(val);
101 }
102 else {
103 let unix = parseInt(toStringSafe(val).trim());
104 if (isNaN(unix)) {
105 result = moment(toStringSafe(val));
106 }
107 else {
108 result = moment(unix);
109 }
110 }
111 return result;
112}
113exports.asMoment = asMoment;
114/**
115 * Keeps sure that a value is a Moment instance (UTC timezone).
116 *
117 * @param {any} time The input value.
118 *
119 * @return {moment.Moment} The Moment instance.
120 */
121function asUTC(time) {
122 let result = asMoment(time);
123 if (!_.isNil(result)) {
124 if (result.isValid()) {
125 if (!result.isUTC()) {
126 result = result.utc();
127 }
128 }
129 }
130 return result;
131}
132exports.asUTC = asUTC;
133/**
134 * Clones an object / value.
135 *
136 * @param {T} obj The value to clone.
137 *
138 * @return {T} The cloned value.
139 */
140function cloneObj(obj) {
141 if (!obj) {
142 return obj;
143 }
144 return JSON.parse(JSON.stringify(obj));
145}
146exports.cloneObj = cloneObj;
147/**
148 * Compare to values for sorting.
149 *
150 * @param {any} x The "left" value.
151 * @param {any} y The "right" value.
152 *
153 * @return {number} The sort value.
154 */
155function compareValues(x, y) {
156 return compareValuesBy(x, y, i => i);
157}
158exports.compareValues = compareValues;
159/**
160 * Compare to values for sorting by using a selector.
161 *
162 * @param {any} x The "left" value.
163 * @param {any} y The "right" value.
164 * @param {Function} selector The selector.
165 *
166 * @return {number} The sort value.
167 */
168function compareValuesBy(x, y, selector) {
169 const VAL_X = selector(x);
170 const VAL_Y = selector(y);
171 if (VAL_X !== VAL_Y) {
172 if (VAL_X < VAL_Y) {
173 return -1;
174 }
175 if (VAL_X > VAL_Y) {
176 return 1;
177 }
178 }
179 return 0;
180}
181exports.compareValuesBy = compareValuesBy;
182/**
183 * Creates a simple 'completed' callback for a promise.
184 *
185 * @param {Function} resolve The 'succeeded' callback.
186 * @param {Function} reject The 'error' callback.
187 *
188 * @return {CompletedAction<TResult>} The created action.
189 */
190function createCompletedAction(resolve, reject) {
191 let completedInvoked = false;
192 return (err, result) => {
193 if (completedInvoked) {
194 return;
195 }
196 completedInvoked = true;
197 if (err) {
198 if (reject) {
199 reject(err);
200 }
201 }
202 else {
203 if (resolve) {
204 resolve(result);
205 }
206 }
207 };
208}
209exports.createCompletedAction = createCompletedAction;
210/**
211 * Promise version of `child_process.exec()` function.
212 *
213 * @param {string} command The command to execute.
214 *
215 * @return {Promise<ExecResult>} The promise with the result.
216 */
217async function exec(command) {
218 command = toStringSafe(command);
219 return new Promise((resolve, reject) => {
220 try {
221 child_process_1.exec(command, (err, stdout, stderr) => {
222 if (err) {
223 reject(err);
224 }
225 else {
226 resolve({
227 stderr: stderr,
228 stdout: stdout,
229 });
230 }
231 });
232 }
233 catch (e) {
234 reject(e);
235 }
236 });
237}
238exports.exec = exec;
239/**
240 * An async 'forEach'.
241 *
242 * @param {Enumerable.Sequence<T>} seq The sequence or array to iterate.
243 * @param {ForEachAsyncAction<T>} action The action to invoke.
244 */
245async function forEachAsync(seq, action) {
246 let i = -1;
247 for (const ITEM of seq) {
248 ++i;
249 await Promise.resolve(action(ITEM, i));
250 }
251}
252exports.forEachAsync = forEachAsync;
253/**
254 * Detects version information about the current app via Git (synchronous).
255 *
256 * @param {GetAppVersionOptions} [opts] Custom options.
257 *
258 * @return {AppVersion} Version information.
259 */
260function getAppVersionSync(opts) {
261 if (!opts) {
262 opts = {};
263 }
264 // working directory
265 let cwd = toStringSafe(opts.cwd);
266 if (isEmptyString(cwd)) {
267 cwd = process.cwd();
268 }
269 if (!path.isAbsolute(cwd)) {
270 cwd = path.join(process.cwd(), cwd);
271 }
272 cwd = path.resolve(cwd);
273 const VERSION = {};
274 try {
275 VERSION.date = asUTC(moment(child_process_1.execSync('git log -n1 --pretty=%cI HEAD', {
276 cwd: cwd,
277 }).toString('utf8')
278 .trim()));
279 }
280 catch (_a) {
281 VERSION.date = false;
282 }
283 try {
284 VERSION.hash = normalizeString(child_process_1.execSync('git log --pretty="%H" -n1 HEAD', {
285 cwd: cwd,
286 }).toString('utf8'));
287 }
288 catch (_b) {
289 VERSION.hash = false;
290 }
291 return VERSION;
292}
293exports.getAppVersionSync = getAppVersionSync;
294/**
295 * Alias of 'uuid()' function.
296 */
297function guid(version) {
298 return uuid.apply(null, arguments);
299}
300exports.guid = guid;
301/**
302 * Checks if the string representation of a value is an empty string or not.
303 *
304 * @param {any} val The value to check.
305 *
306 * @return {boolean} If empty string or not.
307 */
308function isEmptyString(val) {
309 return '' === toStringSafe(val)
310 .trim();
311}
312exports.isEmptyString = isEmptyString;
313/**
314 * Normalizes a value to a string, which is comparable.
315 *
316 * @param {any} val The value to normalize.
317 *
318 * @return {string} The normalized string.
319 */
320function normalizeString(val) {
321 return toStringSafe(val).toLowerCase()
322 .trim();
323}
324exports.normalizeString = normalizeString;
325/**
326 * Returns the current time.
327 *
328 * @param {string} [timezone] The custom timezone to use.
329 *
330 * @return {Moment.Moment} The current time.
331 */
332function now(timezone) {
333 timezone = toStringSafe(timezone).trim();
334 const NOW = moment();
335 return '' === timezone ? NOW
336 : NOW.tz(timezone);
337}
338exports.now = now;
339/**
340 * Parses a value as string of a command line input.
341 *
342 * @param {any} cmd The command line input.
343 *
344 * @return {ParsedCommandLine} The parsed data.
345 */
346function parseCommandLine(cmd) {
347 cmd = toStringSafe(cmd).trim();
348 const ARGS = yargs(cmd);
349 cmd = normalizeString(ARGS._[0]);
350 ARGS._ = ARGS._.filter((a, i) => i > 0).map((a) => {
351 if (_.isString(a)) {
352 if (a.startsWith('"') && a.endsWith('"')) {
353 a = a.substr(1, a.length - 2);
354 a = a.split('\\"')
355 .join('"');
356 }
357 }
358 return a;
359 });
360 if ('' === cmd) {
361 cmd = undefined;
362 }
363 return {
364 arguments: ARGS,
365 command: cmd,
366 };
367}
368exports.parseCommandLine = parseCommandLine;
369/**
370 * Generates a random string.
371 *
372 * @param {number} size The size of the result string.
373 * @param {string} [chars] The custom list of characters.
374 *
375 * @return {Promise<string>} The promise with the random string.
376 */
377async function randChars(size, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
378 return randCharsInner(await util.promisify(crypto.randomBytes)(size), chars);
379}
380exports.randChars = randChars;
381function randCharsInner(randBlob, chars) {
382 chars = toStringSafe(chars);
383 let str = '';
384 for (let i = 0; i < randBlob.length; i++) {
385 str += chars.substr(randBlob.readInt8(i) % chars.length, 1);
386 }
387 return str;
388}
389/**
390 * Generates a random string.
391 *
392 * @param {number} size The size of the result string.
393 * @param {string} [chars] The custom list of characters.
394 *
395 * @return {string} The random string.
396 */
397function randCharsSync(size, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
398 return randCharsInner(crypto.randomBytes(size), chars);
399}
400exports.randCharsSync = randCharsSync;
401/**
402 * Returns a value as "real" boolean.
403 *
404 * @param {any} val The input value.
405 * @param {boolean} [defaultValue] The value to return if 'val' is (null) or (undefined).
406 *
407 * @return {boolean} The output value.
408 */
409function toBooleanSafe(val, defaultValue = false) {
410 if (_.isBoolean(val)) {
411 return val;
412 }
413 if (_.isNil(val)) {
414 return !!defaultValue;
415 }
416 return !!val;
417}
418exports.toBooleanSafe = toBooleanSafe;
419/**
420 * Converts a value to a string (if needed), which is not (null) and not (undefined).
421 *
422 * @param {any} val The value to convert.
423 * @param {string} [defaultValue] The custom default value if 'val' is (null) or (undefined).
424 *
425 * @return {string} 'val' as string.
426 */
427function toStringSafe(val, defaultValue = '') {
428 if (_.isString(val)) {
429 return val;
430 }
431 if (_.isNil(val)) {
432 return '' + defaultValue;
433 }
434 if (val instanceof Error) {
435 return `[${val.name}] ${val.message}${_.isNil(val.stack) ? '' : ("\n\n" + val.stack)}`;
436 }
437 if (_.isFunction(val['toString'])) {
438 return '' + val.toString();
439 }
440 if (Array.isArray(val) || _.isObjectLike(val)) {
441 return JSON.stringify(val);
442 }
443 return '' + val;
444}
445exports.toStringSafe = toStringSafe;
446/**
447 * Returns the current time in UTC.
448 *
449 * @return {moment.Moment} The current UTC time.
450 */
451function utc() {
452 return moment.utc();
453}
454exports.utc = utc;
455/**
456 * Generates an unique ID.
457 *
458 * @param {string} [version] The custom version to use. Default: 4
459 * @param {any[]} []
460 *
461 * @return {string} The new GUID / unique ID.
462 */
463function uuid(version, ...args) {
464 version = normalizeString(version);
465 switch (version) {
466 case '':
467 case '4':
468 case 'v4':
469 return UUID.v4
470 .apply(null, args);
471 case '1':
472 case 'v1':
473 return UUID.v1
474 .apply(null, args);
475 case '5':
476 case 'v5':
477 return UUID_v5.apply(null, args);
478 }
479 throw new Error(`Version '${version}' is not supported`);
480}
481exports.uuid = uuid;
482__export(require("./apis/host"));
483__export(require("./apis/index"));
484__export(require("./apis/statistics"));
485__export(require("./apis/validation"));
486__export(require("./azure/storage"));
487__export(require("./cache"));
488__export(require("./cache/redis"));
489__export(require("./dev"));
490__export(require("./diagnostics/logger"));
491__export(require("./diagnostics/stopwatch"));
492__export(require("./env"));
493__export(require("./events"));
494__export(require("./fs"));
495__export(require("./geo"));
496__export(require("./http"));
497__export(require("./http/websockets"));
498__export(require("./mail"));
499__export(require("./mongo/index"));
500__export(require("./mongo/statistics"));
501__export(require("./oauth/microsoft"));
502__export(require("./queues/index"));
503__export(require("./schemas"));
504__export(require("./statistics"));
505__export(require("./streams"));
506__export(require("./strings"));
507__export(require("./system"));
508__export(require("./zip/builder"));
509var node_enumerable_1 = require("node-enumerable");
510exports.asEnumerable = node_enumerable_1.asEnumerable;
511exports.from = node_enumerable_1.from;
512exports.isEnumerable = node_enumerable_1.isEnumerable;
513exports.isSequence = node_enumerable_1.isSequence;
514exports.popFrom = node_enumerable_1.popFrom;
515exports.random = node_enumerable_1.random;
516exports.range = node_enumerable_1.range;
517exports.repeat = node_enumerable_1.repeat;
518exports.shiftFrom = node_enumerable_1.shiftFrom;
519var swagger_jsdoc_express_1 = require("swagger-jsdoc-express");
520exports.setupSwaggerUIFromSourceFiles = swagger_jsdoc_express_1.setupSwaggerUIFromSourceFiles;
521//# sourceMappingURL=index.js.map
\No newline at end of file