tnp-core 13.1.17 → 13.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +3 -3
  2. package/app.d.ts +1 -1
  3. package/app.js +6 -6
  4. package/browser/README.md +24 -24
  5. package/browser/esm2020/lib/core-config.mjs +5 -5
  6. package/browser/esm2020/lib/core-imports.mjs +107 -107
  7. package/browser/esm2020/lib/core-models.mjs +1 -1
  8. package/browser/esm2020/lib/helpers-isomorphic.mjs +34 -53
  9. package/browser/esm2020/lib/helpers-messages.mjs +434 -434
  10. package/browser/esm2020/lib/helpers.mjs +939 -939
  11. package/browser/esm2020/lib/index.mjs +7 -7
  12. package/browser/esm2020/lib/progress-data.mjs +50 -50
  13. package/browser/esm2020/public-api.mjs +1 -1
  14. package/browser/esm2020/tnp-core.mjs +4 -4
  15. package/browser/fesm2015/tnp-core.mjs +1553 -1571
  16. package/browser/fesm2015/tnp-core.mjs.map +1 -1
  17. package/browser/fesm2020/tnp-core.mjs +1551 -1569
  18. package/browser/fesm2020/tnp-core.mjs.map +1 -1
  19. package/browser/lib/core-config.d.ts +5 -5
  20. package/browser/lib/core-imports.d.ts +6 -6
  21. package/browser/lib/core-models.d.ts +42 -42
  22. package/browser/lib/helpers-isomorphic.d.ts +6 -7
  23. package/browser/lib/helpers-messages.d.ts +11 -11
  24. package/browser/lib/helpers.d.ts +33 -33
  25. package/browser/lib/index.d.ts +7 -7
  26. package/browser/lib/progress-data.d.ts +18 -18
  27. package/browser/public-api.d.ts +1 -1
  28. package/browser/tnp-core.d.ts +5 -5
  29. package/client/README.md +24 -24
  30. package/client/esm2020/lib/core-config.mjs +5 -5
  31. package/client/esm2020/lib/core-imports.mjs +107 -107
  32. package/client/esm2020/lib/core-models.mjs +1 -1
  33. package/client/esm2020/lib/helpers-isomorphic.mjs +34 -53
  34. package/client/esm2020/lib/helpers-messages.mjs +434 -434
  35. package/client/esm2020/lib/helpers.mjs +939 -939
  36. package/client/esm2020/lib/index.mjs +7 -7
  37. package/client/esm2020/lib/progress-data.mjs +50 -50
  38. package/client/esm2020/public-api.mjs +1 -1
  39. package/client/esm2020/tnp-core.mjs +4 -4
  40. package/client/fesm2015/tnp-core.mjs +1553 -1571
  41. package/client/fesm2015/tnp-core.mjs.map +1 -1
  42. package/client/fesm2020/tnp-core.mjs +1551 -1569
  43. package/client/fesm2020/tnp-core.mjs.map +1 -1
  44. package/client/lib/core-config.d.ts +5 -5
  45. package/client/lib/core-imports.d.ts +6 -6
  46. package/client/lib/core-models.d.ts +42 -42
  47. package/client/lib/helpers-isomorphic.d.ts +6 -7
  48. package/client/lib/helpers-messages.d.ts +11 -11
  49. package/client/lib/helpers.d.ts +33 -33
  50. package/client/lib/index.d.ts +7 -7
  51. package/client/lib/progress-data.d.ts +18 -18
  52. package/client/public-api.d.ts +1 -1
  53. package/client/tnp-core.d.ts +5 -5
  54. package/index.d.ts +1 -1
  55. package/index.js +5 -5
  56. package/lib/core-config.d.ts +5 -5
  57. package/lib/core-config.js +9 -9
  58. package/lib/core-imports.d.ts +31 -31
  59. package/lib/core-imports.js +113 -113
  60. package/lib/core-models.d.ts +42 -42
  61. package/lib/core-models.js +3 -3
  62. package/lib/helpers-isomorphic.d.ts +6 -9
  63. package/lib/helpers-isomorphic.js +56 -74
  64. package/lib/helpers-isomorphic.js.map +1 -1
  65. package/lib/helpers-messages.d.ts +11 -11
  66. package/lib/helpers-messages.js +474 -474
  67. package/lib/helpers.d.ts +111 -111
  68. package/lib/helpers.js +1127 -1127
  69. package/lib/index.d.ts +7 -7
  70. package/lib/index.js +13 -13
  71. package/lib/progress-data.d.ts +18 -18
  72. package/lib/progress-data.js +59 -59
  73. package/lib/public-api.d.ts +7 -7
  74. package/lib/public-api.js +13 -13
  75. package/package.json +2 -2
  76. package/package.json_devDependencies.json +202 -202
  77. package/package.json_tnp.json5 +62 -62
  78. package/tmp-environment.json +13 -12
  79. package/websql/README.md +24 -24
  80. package/websql/esm2020/lib/core-config.mjs +5 -5
  81. package/websql/esm2020/lib/core-imports.mjs +108 -108
  82. package/websql/esm2020/lib/core-models.mjs +1 -1
  83. package/websql/esm2020/lib/helpers-isomorphic.mjs +35 -55
  84. package/websql/esm2020/lib/helpers-messages.mjs +434 -434
  85. package/websql/esm2020/lib/helpers.mjs +939 -939
  86. package/websql/esm2020/lib/index.mjs +7 -7
  87. package/websql/esm2020/lib/progress-data.mjs +50 -50
  88. package/websql/esm2020/public-api.mjs +1 -1
  89. package/websql/esm2020/tnp-core.mjs +4 -4
  90. package/websql/fesm2015/tnp-core.mjs +1548 -1567
  91. package/websql/fesm2015/tnp-core.mjs.map +1 -1
  92. package/websql/fesm2020/tnp-core.mjs +1546 -1565
  93. package/websql/fesm2020/tnp-core.mjs.map +1 -1
  94. package/websql/lib/core-config.d.ts +5 -5
  95. package/websql/lib/core-imports.d.ts +8 -8
  96. package/websql/lib/core-models.d.ts +42 -42
  97. package/websql/lib/helpers-isomorphic.d.ts +6 -9
  98. package/websql/lib/helpers-messages.d.ts +11 -11
  99. package/websql/lib/helpers.d.ts +33 -33
  100. package/websql/lib/index.d.ts +7 -7
  101. package/websql/lib/progress-data.d.ts +18 -18
  102. package/websql/public-api.d.ts +1 -1
  103. package/websql/tnp-core.d.ts +5 -5
package/lib/helpers.js CHANGED
@@ -1,1127 +1,1127 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HelpersCore = void 0;
4
- var tslib_1 = require("tslib");
5
- var core_imports_1 = require("./core-imports");
6
- var index_1 = require("./index");
7
- var helpers_messages_1 = require("./helpers-messages");
8
- var encoding = 'utf8';
9
- var HelpersCore = /** @class */ (function (_super) {
10
- tslib_1.__extends(HelpersCore, _super);
11
- function HelpersCore() {
12
- var _this = _super.call(this) || this;
13
- //#endregion
14
- _this.bigMaxBuffer = 2024 * 500;
15
- //#region @backend
16
- _this.processes = [];
17
- return _this;
18
- // //#region @backend
19
- // process.on('SIGINT', this.cleanExit); // catch ctrl-c
20
- // process.on('SIGTERM', this.cleanExit); // catch kill
21
- // //#endregion
22
- }
23
- Object.defineProperty(HelpersCore, "InstanceCore", {
24
- get: function () {
25
- if (!HelpersCore._instanceCore) {
26
- HelpersCore._instanceCore = new HelpersCore();
27
- }
28
- return HelpersCore._instanceCore;
29
- },
30
- enumerable: false,
31
- configurable: true
32
- });
33
- //#endregion
34
- //#region @backend
35
- HelpersCore.prototype.cleanExit = function () {
36
- index_1.Helpers.processes.forEach(function (p) {
37
- p.kill('SIGINT');
38
- p.kill('SIGTERM');
39
- index_1.Helpers.log("Killing child process on ".concat(p.pid));
40
- });
41
- index_1.Helpers.log("Killing parent on ".concat(process.pid));
42
- process.exit();
43
- };
44
- ;
45
- HelpersCore.prototype.removeSlashAtEnd = function (s) {
46
- s = (s === null || s === void 0 ? void 0 : s.endsWith("/")) ? s.slice(0, s.length - 1) : s;
47
- return s;
48
- };
49
- HelpersCore.prototype.removeSlashAtBegin = function (s) {
50
- s = (s === null || s === void 0 ? void 0 : s.startsWith("/")) ? s.slice(1) : s;
51
- return s;
52
- };
53
- HelpersCore.prototype.stringify = function (inputObject) {
54
- // if (_.isString(inputObject)) {
55
- // return inputObject;
56
- // }
57
- // if (_.isObject(inputObject)) {
58
- // config.log(inputObject)
59
- // Helpers.error(`[tnp-helpers] trying to stringify not a object`, false, true);
60
- // }
61
- return JSON.stringify(inputObject, null, 2);
62
- };
63
- HelpersCore.prototype.runSyncOrAsync = function (fn) {
64
- var firstArg = [];
65
- for (var _i = 1; _i < arguments.length; _i++) {
66
- firstArg[_i - 1] = arguments[_i];
67
- }
68
- return tslib_1.__awaiter(this, void 0, void 0, function () {
69
- var promisOrValue;
70
- var _a;
71
- return tslib_1.__generator(this, function (_b) {
72
- if (core_imports_1._.isUndefined(fn)) {
73
- return [2 /*return*/];
74
- }
75
- promisOrValue = core_imports_1._.isArray(fn) ? (_a = fn[1])[fn[0]].apply(_a, tslib_1.__spreadArray([], tslib_1.__read(firstArg), false)) : fn.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(firstArg), false));
76
- if (promisOrValue instanceof Promise) {
77
- // wasPromise = true;
78
- promisOrValue = Promise.resolve(promisOrValue);
79
- }
80
- // console.log('was promis ', wasPromise)
81
- return [2 /*return*/, promisOrValue];
82
- });
83
- });
84
- };
85
- //#endregion
86
- //#region @backend
87
- HelpersCore.prototype.createSymLink = function (existedFileOrFolder, destinationPath, options) {
88
- //#region fix parameters
89
- existedFileOrFolder = (0, core_imports_1.crossPlatformPath)(existedFileOrFolder);
90
- destinationPath = (0, core_imports_1.crossPlatformPath)(destinationPath);
91
- index_1.Helpers.log("[tnp-helpers][create link] exited -> dest\n ".concat(existedFileOrFolder, " ").concat(destinationPath));
92
- options = options ? options : {};
93
- if (core_imports_1._.isUndefined(options.continueWhenExistedFolderDoesntExists)) {
94
- options.continueWhenExistedFolderDoesntExists = false;
95
- }
96
- if (core_imports_1._.isUndefined(options.dontRenameWhenSlashAtEnd)) {
97
- options.dontRenameWhenSlashAtEnd = false;
98
- }
99
- if (core_imports_1._.isUndefined(options.windowsHardLink)) {
100
- options.windowsHardLink = false;
101
- }
102
- if (core_imports_1._.isUndefined(options.speedUpProcess)) {
103
- options.speedUpProcess = false;
104
- }
105
- if (core_imports_1._.isUndefined(options.allowNotAbsolutePathes)) {
106
- options.allowNotAbsolutePathes = false;
107
- }
108
- //#endregion
109
- var continueWhenExistedFolderDoesntExists = options.continueWhenExistedFolderDoesntExists, windowsHardLink = options.windowsHardLink, speedUpProcess = options.speedUpProcess;
110
- // console.log('Create link!')
111
- var targetExisted = existedFileOrFolder;
112
- var linkDest = destinationPath;
113
- if (!core_imports_1.fse.existsSync(existedFileOrFolder)) {
114
- if (continueWhenExistedFolderDoesntExists) {
115
- // just continue and create link to not existed folder
116
- }
117
- else {
118
- index_1.Helpers.error("[helpers.createLink] target path doesn't exist: ".concat(existedFileOrFolder, "\n use option \"continueWhenExistedFolderDoesntExists\" to fix this if you know that\n file will be eventually in place\n "));
119
- }
120
- }
121
- /**
122
- * support for
123
- * pwd -> /mysource
124
- * ln -s . /test/inside -> /test/inside/mysource
125
- * ln -s ./ /test/inside -> /test/inside/mysource
126
- */
127
- if (options.allowNotAbsolutePathes) {
128
- if (linkDest === '.' || linkDest === './') {
129
- linkDest = (0, core_imports_1.crossPlatformPath)(process.cwd());
130
- }
131
- if (!core_imports_1.path.isAbsolute(linkDest)) {
132
- linkDest = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join((0, core_imports_1.crossPlatformPath)(process.cwd()), linkDest));
133
- }
134
- if (!core_imports_1.path.isAbsolute(targetExisted)) {
135
- targetExisted = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join((0, core_imports_1.crossPlatformPath)(process.cwd()), targetExisted));
136
- }
137
- }
138
- else {
139
- if (!core_imports_1.path.isAbsolute(linkDest)) {
140
- index_1.Helpers.error("[createsymlink] path is not absolute:\n targetExisted: ".concat(targetExisted, "\n linkDest: ").concat(linkDest, "\n "));
141
- }
142
- if (!core_imports_1.path.isAbsolute(targetExisted)) {
143
- index_1.Helpers.error("[createsymlink] path is not absolute:\n targetExisted: ".concat(targetExisted, "\n linkDest: ").concat(linkDest, "\n "));
144
- }
145
- }
146
- if (linkDest.endsWith('/')) {
147
- linkDest = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join(linkDest, core_imports_1.path.basename(targetExisted)));
148
- }
149
- var parentFolderLinkDest = core_imports_1.path.dirname(linkDest);
150
- if (index_1.Helpers.isSymlinkFileExitedOrUnexisted(parentFolderLinkDest)) {
151
- core_imports_1.fse.unlinkSync(parentFolderLinkDest);
152
- }
153
- if (!index_1.Helpers.isFolder(parentFolderLinkDest)) {
154
- core_imports_1.rimraf.sync(parentFolderLinkDest);
155
- index_1.Helpers.mkdirp(parentFolderLinkDest);
156
- }
157
- if (!speedUpProcess) {
158
- core_imports_1.rimraf.sync(linkDest);
159
- }
160
- if (process.platform === 'win32') {
161
- // const resolvedTarget = crossPlatformPath(path.resolve(targetExisted));
162
- // console.log(`resolved target from ${targetExisted} = ${resolvedTarget}, isFile: ${targetIsFile}`)
163
- if (index_1.Helpers.isSymlinkFileExitedOrUnexisted(targetExisted)) {
164
- // Helpers.info(`FIXING TARGET FOR WINDOWS`)
165
- targetExisted = (0, core_imports_1.crossPlatformPath)(core_imports_1.fse.realpathSync(targetExisted));
166
- // TODO QUICK_FIX on windows you can't create link to link
167
- }
168
- // targetExisted = path.win32.normalize(targetExisted).replace(/\\$/, '');
169
- // linkDest = path.win32.normalize(linkDest).replace(/\\$/, '');
170
- var targetIsFile = index_1.Helpers.isFile(targetExisted);
171
- // const destIsLink = Helpers.isExistedSymlink(linkDest) || Helpers.isUnexistedLink(linkDest)
172
- // console.log({
173
- // targetExisted,
174
- // linkDest,
175
- // destIsLink
176
- // });
177
- // if (destIsLink) {
178
- // fse.unlinkSync(linkDest)
179
- // }
180
- if (windowsHardLink) { // ADMIN RIGHT REQURED??
181
- core_imports_1.fse.symlinkSync(targetExisted, linkDest, 'dir');
182
- }
183
- else {
184
- if (targetIsFile) {
185
- core_imports_1.fse.linkSync(targetExisted, linkDest);
186
- }
187
- else {
188
- core_imports_1.fse.symlinkSync(targetExisted, linkDest, 'junction');
189
- }
190
- }
191
- //#region old windows linking
192
- /*
193
- // const winLinkCommand = `cmd /c "mklink /D ${link} ${target}"`;
194
- // const winLinkCommand = `export MSYS=winsymlinks:nativestrict && ln -s ${target} ${link}`;
195
- const winLinkCommand = `mklink ${windowsHardLink ? '/D' : (targetIsFile ? '/H' : '/j')} "${linkDest}" "${targetExisted}"`;
196
- Helpers.log(`windows link: lnk ${targetExisted} ${linkDest}
197
-
198
-
199
- "${winLinkCommand}'
200
- `);
201
- try {
202
- Helpers.run(winLinkCommand, { biggerBuffer: false }).sync();
203
- } catch (error) {
204
- Helpers.error(error, true, false);
205
- Helpers.error(`
206
- command: "${winLinkCommand}"
207
- [tnp-helpers] windows link error
208
- target: "${targetExisted}"
209
- link: "${linkDest}"
210
- command: "${winLinkCommand}"
211
- `, true, false)
212
- }
213
- */
214
- //#endregion
215
- }
216
- else {
217
- core_imports_1.fse.symlinkSync(targetExisted, linkDest);
218
- }
219
- };
220
- //#endregion
221
- //#region @backend
222
- HelpersCore.prototype.mkdirp = function (folderPath) {
223
- if (core_imports_1._.isArray(folderPath)) {
224
- folderPath = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(folderPath), false));
225
- }
226
- if (!core_imports_1.path.isAbsolute(folderPath)) {
227
- index_1.Helpers.warn("[helpers][mkdirp] Path is not absolute, abort ".concat(folderPath), true);
228
- return;
229
- }
230
- if (core_imports_1._.isString(folderPath) && folderPath.startsWith('/tmp ') && core_imports_1.os.platform() === 'darwin') {
231
- index_1.Helpers.warn("[helpers][mkdirp] On mac osx /tmp is changed to /private/tmp", false);
232
- folderPath = folderPath.replace("/tmp/", '/private/tmp/');
233
- }
234
- if (core_imports_1.fse.existsSync(folderPath)) {
235
- index_1.Helpers.warn("[helpers][mkdirp] folder path already exists: ".concat(folderPath), false);
236
- }
237
- else {
238
- core_imports_1.fse.mkdirpSync(folderPath);
239
- }
240
- };
241
- //#endregion
242
- /**
243
- * symlink may have existed or unexisted destiantion url
244
- * @param destUrl M
245
- */
246
- HelpersCore.prototype.isSymlinkThatMatchesUrl = function (possibleSymlink, destUrl, absoluteFileMatch) {
247
- if (absoluteFileMatch === void 0) { absoluteFileMatch = false; }
248
- //#region @backendFunc
249
- destUrl = (0, core_imports_1.crossPlatformPath)(destUrl);
250
- if (index_1.Helpers.exists(possibleSymlink)) {
251
- if (index_1.Helpers.isExistedSymlink(possibleSymlink)) {
252
- var fileLink = core_imports_1.fse.readlinkSync(possibleSymlink);
253
- if (absoluteFileMatch) {
254
- fileLink = core_imports_1.fse.realpathSync(fileLink);
255
- }
256
- fileLink = (0, core_imports_1.crossPlatformPath)(fileLink);
257
- return fileLink === destUrl;
258
- }
259
- if (index_1.Helpers.isFolder(possibleSymlink)) {
260
- return false;
261
- }
262
- }
263
- try {
264
- var linkToUnexitedLink = core_imports_1.fse.lstatSync(possibleSymlink).isSymbolicLink();
265
- if (linkToUnexitedLink) {
266
- var fileLink = core_imports_1.fse.readlinkSync(possibleSymlink);
267
- if (absoluteFileMatch) {
268
- fileLink = core_imports_1.fse.realpathSync(fileLink);
269
- }
270
- fileLink = (0, core_imports_1.crossPlatformPath)(fileLink);
271
- return (fileLink === destUrl);
272
- }
273
- return false;
274
- }
275
- catch (error) {
276
- return false;
277
- }
278
- //#endregion
279
- };
280
- HelpersCore.prototype.isSymlinkFileExitedOrUnexisted = function (filePath) {
281
- //#region @backendFunc
282
- try {
283
- var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
284
- return linkToUnexitedLink;
285
- }
286
- catch (error) {
287
- return false;
288
- }
289
- //#endregion
290
- };
291
- /**
292
- * If symbolnk link that target file does not exits
293
- */
294
- HelpersCore.prototype.isUnexistedLink = function (filePath) {
295
- //#region @backendFunc
296
- filePath = index_1.Helpers.removeSlashAtEnd(filePath);
297
- if (process.platform === 'win32') {
298
- filePath = core_imports_1.path.win32.normalize(filePath);
299
- }
300
- try {
301
- var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
302
- return linkToUnexitedLink && !core_imports_1.fse.existsSync(core_imports_1.fse.readlinkSync(filePath));
303
- }
304
- catch (error) {
305
- return false;
306
- }
307
- //#endregion
308
- };
309
- /**
310
- * @param existedLink check if source of link exists
311
- */
312
- HelpersCore.prototype.isExistedSymlink = function (filePath) {
313
- //#region @backendFunc
314
- filePath = index_1.Helpers.removeSlashAtEnd(filePath);
315
- if (process.platform === 'win32') {
316
- filePath = core_imports_1.path.win32.normalize(filePath);
317
- }
318
- try {
319
- var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
320
- return linkToUnexitedLink && core_imports_1.fse.existsSync(core_imports_1.fse.readlinkSync(filePath));
321
- }
322
- catch (error) {
323
- return false;
324
- }
325
- //#endregion
326
- };
327
- //#region @backend
328
- HelpersCore.prototype.pathContainLink = function (p) {
329
- var previous;
330
- while (true) {
331
- p = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.dirname(p));
332
- if (p === previous) {
333
- return false;
334
- }
335
- if (index_1.Helpers.isExistedSymlink(p)) {
336
- return true;
337
- }
338
- if (!index_1.Helpers.exists(p)) {
339
- return false;
340
- }
341
- previous = p;
342
- }
343
- };
344
- //#endregion
345
- HelpersCore.prototype.exists = function (folderOrFilePath
346
- // , allowUnexistedLinks = false
347
- ) {
348
- //#region @backendFunc
349
- if (core_imports_1._.isArray(folderOrFilePath)) {
350
- folderOrFilePath = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(folderOrFilePath), false));
351
- }
352
- if (!folderOrFilePath) {
353
- index_1.Helpers.warn("[helpers][exists] Path is not a string, abort.. \"".concat(folderOrFilePath, "\""), true);
354
- return false;
355
- }
356
- if (!core_imports_1.path.isAbsolute(folderOrFilePath)) {
357
- index_1.Helpers.warn("\n\n ".concat(folderOrFilePath, "\n\n "), true);
358
- return false;
359
- }
360
- return core_imports_1.fse.existsSync(folderOrFilePath);
361
- //#endregion
362
- };
363
- HelpersCore.prototype.command = function (command) {
364
- // console.log({ command })
365
- return {
366
- //#region @backend
367
- getherOutput: function (options) {
368
- if (!options) {
369
- options = {};
370
- }
371
- return new Promise(function (resolve) {
372
- var ommitStder = options.ommitStder, cwd = options.cwd, biggerBuffer = options.biggerBuffer, gatherColors = options.gatherColors;
373
- if (!cwd) {
374
- cwd = process.cwd();
375
- }
376
- var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : void 0;
377
- var env = gatherColors ? tslib_1.__assign(tslib_1.__assign({}, process.env), { FORCE_COLOR: '1' }) : {};
378
- var proc = core_imports_1.child_process.exec(command, {
379
- cwd: cwd,
380
- maxBuffer: maxBuffer,
381
- env: env
382
- });
383
- var gatheredData = '';
384
- proc.on('exit', function (code) {
385
- resolve(gatheredData);
386
- });
387
- proc.stdout.on('data', function (data) {
388
- gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
389
- });
390
- proc.stdout.on('error', function (data) {
391
- gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
392
- });
393
- if (!ommitStder) {
394
- proc.stderr.on('data', function (data) {
395
- gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
396
- });
397
- proc.stderr.on('error', function (data) {
398
- gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
399
- });
400
- }
401
- });
402
- }
403
- //#endregion
404
- };
405
- };
406
- HelpersCore.prototype.run = function (command, options) {
407
- // console.log({ command })
408
- //#region @backend
409
- if (!options)
410
- options = {};
411
- if (options.output === undefined)
412
- options.output = true;
413
- if (options.biggerBuffer === undefined)
414
- options.biggerBuffer = false;
415
- if (options.cwd === undefined)
416
- options.cwd = (0, core_imports_1.crossPlatformPath)(process.cwd());
417
- if (!core_imports_1._.isString(command)) {
418
- index_1.Helpers.error("[tnp-helper] command is not a string");
419
- }
420
- //#endregion
421
- return {
422
- //#region @backend
423
- sync: function () {
424
- if (core_imports_1._.isArray(options.extractFromLine)) {
425
- index_1.Helpers.error("[tnp-helper] extractFromLine only for:\n - asyncAsPromise\n - async\n - unitlOutputContains\n\n ", false, true);
426
- }
427
- if (core_imports_1._.isNumber(options.tryAgainWhenFailAfter) && options.tryAgainWhenFailAfter > 0) {
428
- // TODO try again when fail
429
- // try {
430
- var proc = index_1.Helpers.runSyncIn(command, options);
431
- return proc;
432
- // } catch (error) {
433
- // TODO: WAIT FUNCTION HERE
434
- // return Helpers.run(command, options).sync()
435
- // }
436
- }
437
- return index_1.Helpers.runSyncIn(command, options);
438
- },
439
- async: function (detach) {
440
- if (detach === void 0) { detach = false; }
441
- options.detach = detach;
442
- return index_1.Helpers.runAsyncIn(command, options);
443
- },
444
- asyncAsPromise: function () {
445
- var isResolved = false;
446
- return new Promise(function (resolve, reject) {
447
- var proc = index_1.Helpers.runAsyncIn(command, options);
448
- proc.on('exit', function () {
449
- if (!isResolved) {
450
- isResolved = true;
451
- resolve(void 0);
452
- }
453
- });
454
- proc.on('error', function () {
455
- if (!isResolved) {
456
- isResolved = true;
457
- reject();
458
- }
459
- });
460
- });
461
- },
462
- unitlOutputContains: function (stdoutMsg, stderMsg) {
463
- var isResolved = false;
464
- return new Promise(function (resolve, reject) {
465
- if (core_imports_1._.isString(stdoutMsg)) {
466
- stdoutMsg = [stdoutMsg];
467
- }
468
- if (core_imports_1._.isString(stderMsg)) {
469
- stderMsg = [stderMsg];
470
- }
471
- if (!core_imports_1._.isArray(stdoutMsg)) {
472
- reject("[unitlOutputContains] Message not a array");
473
- }
474
- var proc = index_1.Helpers.runAsyncIn(command, options);
475
- proc.stderr.on('data', function (message) {
476
- var data = message.toString().trim();
477
- if (!isResolved && core_imports_1._.isArray(stderMsg)) {
478
- for (var index = 0; index < stderMsg.length; index++) {
479
- var rejectm = stderMsg[index];
480
- if ((data.search(rejectm) !== -1)) {
481
- index_1.Helpers.info("[unitlOutputContains] Rejected move to next step...");
482
- isResolved = true;
483
- reject();
484
- proc.kill('SIGINT');
485
- break;
486
- }
487
- }
488
- }
489
- });
490
- proc.stdout.on('data', function (message) {
491
- var data = message.toString().trim();
492
- if (!isResolved) {
493
- for (var index = 0; index < stdoutMsg.length; index++) {
494
- var m = stdoutMsg[index];
495
- if ((data.search(m) !== -1)) {
496
- index_1.Helpers.info("[unitlOutputContains] Move to next step...");
497
- isResolved = true;
498
- resolve(void 0);
499
- break;
500
- }
501
- }
502
- }
503
- if (!isResolved && core_imports_1._.isArray(stderMsg)) {
504
- for (var index = 0; index < stderMsg.length; index++) {
505
- var rejectm = stderMsg[index];
506
- if ((data.search(rejectm) !== -1)) {
507
- index_1.Helpers.info("[unitlOutputContains] Rejected move to next step...");
508
- isResolved = true;
509
- reject();
510
- proc.kill('SIGINT');
511
- break;
512
- }
513
- }
514
- }
515
- });
516
- });
517
- }
518
- //#endregion
519
- };
520
- };
521
- Object.defineProperty(HelpersCore.prototype, "isRunningIn", {
522
- //#region @backend
523
- get: function () {
524
- return {
525
- mochaTest: function () {
526
- return (typeof global['it'] === 'function');
527
- },
528
- cliMode: function () {
529
- return !!global['globalSystemToolMode'];
530
- },
531
- };
532
- },
533
- enumerable: false,
534
- configurable: true
535
- });
536
- //#endregion
537
- //#region @backend
538
- HelpersCore.prototype.getStdio = function (options) {
539
- var output = options.output, silence = options.silence, stdio = options.stdio
540
- // pipeToParentProcerss = false,
541
- // inheritFromParentProcerss = false
542
- ;
543
- if (typeof stdio !== 'undefined') {
544
- return stdio;
545
- }
546
- var resstdio = output ? [0, 1, 2] : ((core_imports_1._.isBoolean(silence) && silence) ? 'ignore' : undefined);
547
- // if (pipeToParentProcerss) {
548
- // stdio = ['pipe', 'pipe', 'pipe'] as any;
549
- // }
550
- // if (inheritFromParentProcerss) {
551
- // stdio = ['inherit', 'inherit', 'inherit'] as any;
552
- // }
553
- return resstdio;
554
- };
555
- //#endregion
556
- //#region @backend
557
- HelpersCore.prototype.runSyncIn = function (command, options) {
558
- var cwd = options.cwd, biggerBuffer = options.biggerBuffer;
559
- var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : undefined;
560
- var stdio = index_1.Helpers.getStdio(options);
561
- index_1.Helpers.checkProcess(cwd, command);
562
- return core_imports_1.child_process.execSync(command, { stdio: stdio, cwd: cwd, maxBuffer: maxBuffer });
563
- };
564
- //#endregion
565
- //#region @backend
566
- HelpersCore.prototype.runAsyncIn = function (command, options) {
567
- var output = options.output, cwd = options.cwd, biggerBuffer = options.biggerBuffer, outputLineReplace = options.outputLineReplace, extractFromLine = options.extractFromLine, detach = options.detach;
568
- var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : undefined;
569
- var stdio = index_1.Helpers.getStdio(options);
570
- index_1.Helpers.checkProcess(cwd, command);
571
- var proc;
572
- if (detach) {
573
- var cmd = core_imports_1._.first(command.split(' '));
574
- var argsForCmd = command.split(' ').slice(1);
575
- index_1.Helpers.log("cmd: \"".concat(cmd, "\", args: \"").concat(argsForCmd.join(' '), "\""));
576
- if (process.platform === 'win32') {
577
- proc = (0, core_imports_1.spawn)(cmd, argsForCmd, { cwd: cwd, detached: true });
578
- // proc = child_process.spawn(cmd, argsForCmd, {
579
- // cwd,
580
- // detached: true,
581
- // // windowsVerbatimArguments: true,
582
- // shell: true,
583
- // // env: {
584
- // // NODE_ENV: 'production',
585
- // // PATH: process.env.PATH
586
- // // }
587
- // });
588
- }
589
- else {
590
- proc = core_imports_1.child_process.spawn(cmd, argsForCmd, { cwd: cwd, detached: true });
591
- }
592
- index_1.Helpers.log("\n\n DETACHED PROCESS IS WORKING ON PID: ".concat(proc.pid, "\n\n "));
593
- // proc = child.exec(`${command} &`, { cwd, maxBuffer, });
594
- }
595
- else {
596
- // Helpers.log(`Command to execture: ${command}`)
597
- var env = tslib_1.__assign(tslib_1.__assign({}, process.env), { FORCE_COLOR: '1' });
598
- proc = core_imports_1.child_process.exec(command, { cwd: cwd, maxBuffer: maxBuffer, env: env });
599
- if (global.globalSystemToolMode) {
600
- proc.on('exit', function (code) {
601
- index_1.Helpers.log('EXITING BIG PROCESS');
602
- process.exit(code);
603
- });
604
- }
605
- }
606
- return index_1.Helpers.logProc(proc, detach ? true : output, detach ? void 0 : stdio, outputLineReplace, options.prefix, extractFromLine, command);
607
- };
608
- //#endregion
609
- //#region @backend
610
- HelpersCore.prototype.logProc = function (proc, output, stdio, outputLineReplace, prefix, extractFromLine, command) {
611
- if (output === void 0) { output = true; }
612
- index_1.Helpers.processes.push(proc);
613
- if (stdio) {
614
- // @ts-ignore
615
- proc.stdio = stdio;
616
- }
617
- if (!prefix) {
618
- prefix = '';
619
- }
620
- if (output) {
621
- proc.stdout.on('data', function (data) {
622
- // if (data?.toString().search('was unexpected at this time') !== -1) {
623
- // console.log('!!!COMMAND',command)
624
- // }
625
- process.stdout.write(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
626
- });
627
- proc.stdout.on('error', function (data) {
628
- // if (data?.toString().search('was unexpected at this time') !== -1) {
629
- // console.log('!!!COMMAND',command)
630
- // }
631
- console.log(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
632
- });
633
- proc.stderr.on('data', function (data) {
634
- // if (data?.toString().search('was unexpected at this time') !== -1) {
635
- // console.log('!!!COMMAND',command)
636
- // }
637
- process.stderr.write(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
638
- });
639
- proc.stderr.on('error', function (data) {
640
- // if (data?.toString().search('was unexpected at this time') !== -1) {
641
- // console.log('!!!COMMAND',command)
642
- // }
643
- console.log(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
644
- });
645
- }
646
- return proc;
647
- };
648
- HelpersCore.prototype.execute = function (childProcess, options) {
649
- var _this = this;
650
- var _a = options || {}, hideOutput = _a.hideOutput, resolvePromiseMsg = _a.resolvePromiseMsg, outputLineReplace = _a.outputLineReplace, prefix = _a.prefix, extractFromLine = _a.extractFromLine, exitOnError = _a.exitOnError, exitOnErrorCallback = _a.exitOnErrorCallback;
651
- // let {
652
- // stderMsgForPromiseResolve,
653
- // stdoutMsgForPromiseResolve
654
- // } = resolvePromiseMsg || {};
655
- // processes.push(proc);
656
- if (!resolvePromiseMsg) {
657
- resolvePromiseMsg = {};
658
- }
659
- if (!hideOutput) {
660
- hideOutput = {};
661
- }
662
- var isResolved = false;
663
- if (core_imports_1._.isString(resolvePromiseMsg.stdout)) {
664
- resolvePromiseMsg.stdout = [resolvePromiseMsg.stdout];
665
- }
666
- if (core_imports_1._.isString(resolvePromiseMsg.stderr)) {
667
- resolvePromiseMsg.stderr = [resolvePromiseMsg.stderr];
668
- }
669
- return new Promise(function (resolve, reject) {
670
- // let stdio = [0,1,2]
671
- childProcess.stdout.on('data', function (rawData) {
672
- var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
673
- data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
674
- if (!hideOutput.stdout) {
675
- process.stdout.write(data);
676
- }
677
- if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stdout)) {
678
- for (var index = 0; index < resolvePromiseMsg.stdout.length; index++) {
679
- var m = resolvePromiseMsg.stdout[index];
680
- if ((data.search(m) !== -1)) {
681
- // Helpers.info(`[unitlOutputContains] Move to next step...`)
682
- isResolved = true;
683
- resolve(void 0);
684
- break;
685
- }
686
- }
687
- }
688
- if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stderr)) {
689
- for (var index = 0; index < resolvePromiseMsg.stderr.length; index++) {
690
- var rejectm = resolvePromiseMsg.stderr[index];
691
- if ((data.search(rejectm) !== -1)) {
692
- // Helpers.info(`[unitlOutputContains] Rejected move to next step...`);
693
- isResolved = true;
694
- reject();
695
- childProcess.kill('SIGINT');
696
- break;
697
- }
698
- }
699
- }
700
- // console.log(data.toString());
701
- });
702
- childProcess.on('exit', function (code) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
703
- var error_1;
704
- return tslib_1.__generator(this, function (_a) {
705
- switch (_a.label) {
706
- case 0:
707
- if (!(exitOnError && code !== 0)) return [3 /*break*/, 5];
708
- if (!core_imports_1._.isFunction(exitOnErrorCallback)) return [3 /*break*/, 4];
709
- _a.label = 1;
710
- case 1:
711
- _a.trys.push([1, 3, , 4]);
712
- return [4 /*yield*/, this.runSyncOrAsync(exitOnErrorCallback, code)];
713
- case 2:
714
- _a.sent();
715
- return [3 /*break*/, 4];
716
- case 3:
717
- error_1 = _a.sent();
718
- return [3 /*break*/, 4];
719
- case 4:
720
- process.exit(code);
721
- _a.label = 5;
722
- case 5:
723
- resolve(void 0);
724
- return [2 /*return*/];
725
- }
726
- });
727
- }); });
728
- childProcess.stdout.on('error', function (rawData) {
729
- var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
730
- data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
731
- if (!hideOutput.stdout) {
732
- process.stdout.write(JSON.stringify(data));
733
- }
734
- // console.log(data);
735
- });
736
- childProcess.stderr.on('data', function (rawData) {
737
- var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
738
- data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
739
- if (!hideOutput.stderr) {
740
- process.stderr.write(data);
741
- }
742
- if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stderr)) {
743
- for (var index = 0; index < resolvePromiseMsg.stderr.length; index++) {
744
- var rejectm = resolvePromiseMsg.stderr[index];
745
- if ((data.search(rejectm) !== -1)) {
746
- // Helpers.info(`[unitlOutputContains] Rejected move to next step...`);
747
- isResolved = true;
748
- reject();
749
- childProcess.kill('SIGINT');
750
- break;
751
- }
752
- }
753
- }
754
- });
755
- childProcess.stderr.on('error', function (rawData) {
756
- var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
757
- data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
758
- if (!hideOutput.stderr) {
759
- process.stderr.write(JSON.stringify(data));
760
- }
761
- // console.log(data);
762
- });
763
- });
764
- };
765
- //#endregion
766
- //#region @backend
767
- HelpersCore.prototype.checkProcess = function (dirPath, command) {
768
- if (!core_imports_1.fse.existsSync(dirPath)) {
769
- index_1.Helpers.error("\nPath for process cwd doesn't exist: ".concat(dirPath, "\ncommand: ").concat(command, "\n"));
770
- }
771
- if (!command) {
772
- index_1.Helpers.error("Bad command: ".concat(command));
773
- }
774
- };
775
- //#endregion
776
- //#region @backend
777
- HelpersCore.prototype.modifyLineByLine = function (data, outputLineReplace, prefix, extractFromLine) {
778
- var checkExtract = (core_imports_1._.isArray(extractFromLine) && extractFromLine.length > 0);
779
- var modifyOutput = core_imports_1._.isFunction(outputLineReplace);
780
- if (modifyOutput && core_imports_1._.isString(data)) {
781
- data = data.split(/\r?\n/).map(function (line) { return outputLineReplace(line // .replace(chalkCharactersRegex, '')
782
- ); }).join('\n');
783
- }
784
- if (prefix && core_imports_1._.isString(data)) {
785
- return data.split('\n').map(function (singleLine) {
786
- if (!singleLine || singleLine.trim().length === 0 || singleLine.trim() === '.') {
787
- return singleLine;
788
- }
789
- if (checkExtract) {
790
- var sFuncs = extractFromLine
791
- .filter(function (f) { return core_imports_1._.isString(f); });
792
- if (sFuncs.filter(function (f) { return (singleLine.search(f) !== -1); }).length === sFuncs.length) {
793
- var fun = extractFromLine.find(function (f) { return core_imports_1._.isFunction(f); });
794
- if (fun) {
795
- var s_1 = singleLine;
796
- sFuncs.forEach(function (f) { s_1 = s_1.replace(f, ''); });
797
- fun(s_1.trim());
798
- }
799
- }
800
- }
801
- return "".concat(prefix, " ").concat(singleLine);
802
- }).join('\n');
803
- }
804
- return data;
805
- };
806
- //#endregion
807
- //#region @backend
808
- HelpersCore.prototype.isFolder = function (pathToFileOrMaybeFolder) {
809
- return pathToFileOrMaybeFolder && core_imports_1.fse.existsSync(pathToFileOrMaybeFolder) &&
810
- core_imports_1.fse.lstatSync(pathToFileOrMaybeFolder).isDirectory();
811
- };
812
- //#endregion
813
- /**
814
- * Quick fix for object values
815
- */
816
- HelpersCore.prototype.values = function (obj) {
817
- if (core_imports_1._.isObject(obj) && !Array.isArray(obj)) {
818
- var values = [];
819
- for (var key in obj) {
820
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
821
- values.push(obj[key]);
822
- }
823
- }
824
- return values;
825
- }
826
- return [];
827
- };
828
- //#region @backend
829
- /**
830
- * does not make sense
831
- */
832
- HelpersCore.prototype.isFile = function (pathToFileOrMaybeFolder) {
833
- return pathToFileOrMaybeFolder && core_imports_1.fse.existsSync(pathToFileOrMaybeFolder) &&
834
- !core_imports_1.fse.lstatSync(pathToFileOrMaybeFolder).isDirectory();
835
- };
836
- //#endregion
837
- //#region @backend
838
- /**
839
- * wrapper for fs.readFileSync
840
- */
841
- HelpersCore.prototype.readFile = function (absoluteFilePath, defaultValueWhenNotExists) {
842
- if (defaultValueWhenNotExists === void 0) { defaultValueWhenNotExists = void 0; }
843
- if (core_imports_1._.isArray(absoluteFilePath)) {
844
- absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
845
- }
846
- absoluteFilePath = absoluteFilePath;
847
- if (!core_imports_1.fse.existsSync(absoluteFilePath)) {
848
- return defaultValueWhenNotExists;
849
- }
850
- if (core_imports_1.fse.lstatSync(absoluteFilePath).isDirectory()) {
851
- return defaultValueWhenNotExists;
852
- }
853
- return core_imports_1.fse.readFileSync(absoluteFilePath, {
854
- encoding: encoding
855
- }).toString().trim();
856
- };
857
- //#endregion
858
- //#region @backend
859
- HelpersCore.prototype.readJson = function (absoluteFilePath, defaultValue, useJson5) {
860
- if (defaultValue === void 0) { defaultValue = {}; }
861
- if (useJson5 === void 0) { useJson5 = false; }
862
- if (core_imports_1._.isArray(absoluteFilePath)) {
863
- absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
864
- }
865
- absoluteFilePath = absoluteFilePath;
866
- if (!core_imports_1.fse.existsSync(absoluteFilePath)) {
867
- return {};
868
- }
869
- try {
870
- var fileContent = index_1.Helpers.readFile(absoluteFilePath);
871
- var json = void 0;
872
- json = index_1.Helpers.parse(fileContent, useJson5 || absoluteFilePath.endsWith('.json5'));
873
- return json;
874
- }
875
- catch (error) {
876
- return defaultValue;
877
- }
878
- };
879
- //#endregion
880
- //#region @backend
881
- HelpersCore.prototype.parse = function (jsonInstring, useJson5) {
882
- if (useJson5 === void 0) { useJson5 = false; }
883
- if (!core_imports_1._.isString(jsonInstring)) {
884
- index_1.Helpers.log(jsonInstring);
885
- index_1.Helpers.warn("[tnp-helpers] Trying to parse no a string...");
886
- return jsonInstring;
887
- }
888
- return (useJson5 ? core_imports_1.json5.parse(jsonInstring) : JSON.parse(jsonInstring));
889
- };
890
- //#endregion
891
- //#region @backend
892
- HelpersCore.prototype.compilationWrapper = function (fn, taskName, executionType) {
893
- if (taskName === void 0) { taskName = 'Task'; }
894
- if (executionType === void 0) { executionType = 'Compilation of'; }
895
- return tslib_1.__awaiter(this, void 0, void 0, function () {
896
- // global?.spinner?.start();
897
- function currentDate() {
898
- return "[".concat((0, core_imports_1.dateformat)(new Date(), 'HH:MM:ss'), "]");
899
- }
900
- var error_2;
901
- return tslib_1.__generator(this, function (_a) {
902
- switch (_a.label) {
903
- case 0:
904
- if (!fn || !core_imports_1._.isFunction(fn)) {
905
- index_1.Helpers.error("".concat(executionType, " wrapper: \"").concat(fn, "\" is not a function."));
906
- process.exit(1);
907
- }
908
- _a.label = 1;
909
- case 1:
910
- _a.trys.push([1, 3, , 4]);
911
- index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " \"").concat(taskName, "\" Started.."));
912
- return [4 /*yield*/, index_1.Helpers.runSyncOrAsync(fn)];
913
- case 2:
914
- _a.sent();
915
- index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " \"").concat(taskName, "\" Done\u2713"));
916
- return [3 /*break*/, 4];
917
- case 3:
918
- error_2 = _a.sent();
919
- index_1.Helpers.error(core_imports_1.chalk.red(error_2), false, true);
920
- index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " ").concat(taskName, " ERROR"));
921
- process.exit(1);
922
- return [3 /*break*/, 4];
923
- case 4: return [2 /*return*/];
924
- }
925
- });
926
- });
927
- };
928
- //#endregion
929
- //#region @backend
930
- /**
931
- * wrapper for fs.writeFileSync
932
- */
933
- HelpersCore.prototype.writeFile = function (absoluteFilePath, input, options) {
934
- if (core_imports_1._.isArray(absoluteFilePath)) {
935
- absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
936
- }
937
- absoluteFilePath = absoluteFilePath;
938
- if (index_1.Helpers.isExistedSymlink(absoluteFilePath)) {
939
- var beforePath = absoluteFilePath;
940
- absoluteFilePath = core_imports_1.fse.realpathSync(absoluteFilePath);
941
- index_1.Helpers.warn("WRITTING JSON into real path:\n original: ".concat(beforePath, "\n real : ").concat(absoluteFilePath, "\n "));
942
- }
943
- var _a = options || {}, preventParentFile = _a.preventParentFile, overrideSameFile = _a.overrideSameFile;
944
- var dontWriteSameFile = !overrideSameFile;
945
- if (preventParentFile) {
946
- if (index_1.Helpers.isFile(core_imports_1.path.dirname(absoluteFilePath)) && core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
947
- core_imports_1.fse.unlinkSync(core_imports_1.path.dirname(absoluteFilePath));
948
- }
949
- }
950
- if (!core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
951
- index_1.Helpers.mkdirp(core_imports_1.path.dirname(absoluteFilePath));
952
- }
953
- if (core_imports_1._.isObject(input)) {
954
- input = index_1.Helpers.stringify(input);
955
- }
956
- else if (!core_imports_1._.isString(input)) {
957
- input = '';
958
- }
959
- if (dontWriteSameFile) {
960
- if (core_imports_1.fse.existsSync(absoluteFilePath)) {
961
- var existedInput = index_1.Helpers.readFile(absoluteFilePath);
962
- if (input === existedInput) {
963
- // Helpers.log(`[helpers][writeFile] not writing same file (good thing): ${absoluteFilePath}`);
964
- return false;
965
- }
966
- }
967
- }
968
- core_imports_1.fse.writeFileSync(absoluteFilePath, input, {
969
- encoding: encoding
970
- });
971
- return true;
972
- };
973
- //#endregion
974
- //#region @backend
975
- /**
976
- * wrapper for fs.writeFileSync
977
- */
978
- HelpersCore.prototype.writeJson = function (absoluteFilePath, input, optoins) {
979
- if (core_imports_1._.isArray(absoluteFilePath)) {
980
- absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
981
- }
982
- absoluteFilePath = absoluteFilePath;
983
- var preventParentFile = (optoins || {}).preventParentFile;
984
- if (preventParentFile) {
985
- if (index_1.Helpers.isFile(core_imports_1.path.dirname(absoluteFilePath)) && core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
986
- core_imports_1.fse.unlinkSync(core_imports_1.path.dirname(absoluteFilePath));
987
- }
988
- }
989
- if (!core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
990
- index_1.Helpers.mkdirp(core_imports_1.path.dirname(absoluteFilePath));
991
- }
992
- core_imports_1.fse.writeJSONSync(absoluteFilePath, input, {
993
- encoding: encoding,
994
- spaces: 2
995
- });
996
- return true;
997
- };
998
- //#endregion
999
- //#region @backend
1000
- /**
1001
- * return absolute paths for folders inside folders
1002
- */
1003
- HelpersCore.prototype.foldersFrom = function (pathToFolder) {
1004
- if (core_imports_1._.isArray(pathToFolder)) {
1005
- pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1006
- }
1007
- if (!index_1.Helpers.exists(pathToFolder)) {
1008
- return [];
1009
- }
1010
- return core_imports_1.fse.readdirSync(pathToFolder)
1011
- .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1012
- .filter(function (f) { return core_imports_1.fse.lstatSync(f).isDirectory(); });
1013
- };
1014
- HelpersCore.prototype.linksToFoldersFrom = function (pathToFolder, outputRealPath) {
1015
- if (outputRealPath === void 0) { outputRealPath = false; }
1016
- if (core_imports_1._.isArray(pathToFolder)) {
1017
- pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1018
- }
1019
- if (!index_1.Helpers.exists(pathToFolder)) {
1020
- return [];
1021
- }
1022
- return core_imports_1.fse.readdirSync(pathToFolder)
1023
- .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1024
- .filter(function (f) { return core_imports_1.fse.existsSync(f) && core_imports_1.fse.lstatSync(f).isSymbolicLink(); })
1025
- .map(function (f) {
1026
- var realPath = core_imports_1.fse.realpathSync(f);
1027
- var isFolder = index_1.Helpers.isFolder(realPath);
1028
- if (isFolder) {
1029
- if (outputRealPath) {
1030
- return realPath;
1031
- }
1032
- else {
1033
- return f;
1034
- }
1035
- }
1036
- }).filter(function (f) { return !!f; });
1037
- };
1038
- //#endregion
1039
- //#region @backend
1040
- /**
1041
- * return absolute paths for folders inside folders
1042
- */
1043
- HelpersCore.prototype.linksToFolderFrom = function (pathToFolder) {
1044
- // options = (options || {}) as any;
1045
- // if (_.isUndefined(options.linksOnlyTo)) {
1046
- // options.linksOnlyTo = 'both';
1047
- // }
1048
- if (core_imports_1._.isArray(pathToFolder)) {
1049
- pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1050
- }
1051
- if (!index_1.Helpers.exists(pathToFolder)) {
1052
- return [];
1053
- }
1054
- return core_imports_1.fse.readdirSync(pathToFolder)
1055
- .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1056
- .filter(function (f) {
1057
- var res = false;
1058
- if (index_1.Helpers.isExistedSymlink(f)) {
1059
- var realPath = core_imports_1.fse.realpathSync(f);
1060
- return index_1.Helpers.isFolder(realPath);
1061
- }
1062
- return res;
1063
- });
1064
- };
1065
- //#endregion
1066
- //#region @backend
1067
- /**
1068
- * return absolute paths for folders inside folders
1069
- */
1070
- HelpersCore.prototype.filesFrom = function (pathToFolder, recrusive) {
1071
- var _this = this;
1072
- if (recrusive === void 0) { recrusive = false; }
1073
- if (core_imports_1._.isArray(pathToFolder)) {
1074
- pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1075
- }
1076
- if (!index_1.Helpers.exists(pathToFolder)) {
1077
- return [];
1078
- }
1079
- if (recrusive) {
1080
- var all = core_imports_1.fse.readdirSync(pathToFolder)
1081
- .map(function (f) { return core_imports_1.path.join(pathToFolder, f); });
1082
- var folders_1 = [];
1083
- var files = all.filter(function (f) {
1084
- if (core_imports_1.fse.lstatSync(f).isDirectory()) {
1085
- folders_1.push(f);
1086
- return false;
1087
- }
1088
- return true;
1089
- });
1090
- return tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(files), false), tslib_1.__read(folders_1
1091
- .map(function (f) { return _this.filesFrom(f, recrusive); })
1092
- .reduce(function (a, b) {
1093
- return a.concat(b);
1094
- }, [])), false);
1095
- }
1096
- return core_imports_1.fse.readdirSync(pathToFolder)
1097
- .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1098
- .filter(function (f) { return !core_imports_1.fse.lstatSync(f).isDirectory(); });
1099
- };
1100
- //#endregion
1101
- //#region @backend
1102
- HelpersCore.prototype.openFolderInFileExploer = function (folderPath) {
1103
- if (process.platform === 'win32') {
1104
- folderPath = (0, core_imports_1.win32Path)(folderPath);
1105
- }
1106
- try {
1107
- index_1.Helpers.info("Opening path in file explorer: \"".concat(folderPath, "\""));
1108
- if (process.platform === 'win32') {
1109
- index_1.Helpers.run("explorer ".concat(folderPath)).sync();
1110
- return;
1111
- }
1112
- if (process.platform === 'darwin') {
1113
- index_1.Helpers.run("open ".concat(folderPath)).sync();
1114
- return;
1115
- }
1116
- index_1.Helpers.run("xdg-open ".concat(folderPath)).sync();
1117
- }
1118
- catch (error) {
1119
- if (process.platform !== 'win32') { // TODO QUICK fix explorer with path is triggering errro
1120
- index_1.Helpers.error("Not able to open in file explorer: \"".concat(folderPath, "\""), false, true);
1121
- }
1122
- }
1123
- };
1124
- return HelpersCore;
1125
- }(helpers_messages_1.HelpersMessages));
1126
- exports.HelpersCore = HelpersCore;
1127
- //# sourceMappingURL=C:/Users/darek/projects/npm/tnp-core/tmp-bundle-release/bundle/project/tnp-core/bundle-nocutsrc/lib/helpers.js.map
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HelpersCore = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var core_imports_1 = require("./core-imports");
6
+ var index_1 = require("./index");
7
+ var helpers_messages_1 = require("./helpers-messages");
8
+ var encoding = 'utf8';
9
+ var HelpersCore = /** @class */ (function (_super) {
10
+ tslib_1.__extends(HelpersCore, _super);
11
+ function HelpersCore() {
12
+ var _this = _super.call(this) || this;
13
+ //#endregion
14
+ _this.bigMaxBuffer = 2024 * 500;
15
+ //#region @backend
16
+ _this.processes = [];
17
+ return _this;
18
+ // //#region @backend
19
+ // process.on('SIGINT', this.cleanExit); // catch ctrl-c
20
+ // process.on('SIGTERM', this.cleanExit); // catch kill
21
+ // //#endregion
22
+ }
23
+ Object.defineProperty(HelpersCore, "InstanceCore", {
24
+ get: function () {
25
+ if (!HelpersCore._instanceCore) {
26
+ HelpersCore._instanceCore = new HelpersCore();
27
+ }
28
+ return HelpersCore._instanceCore;
29
+ },
30
+ enumerable: false,
31
+ configurable: true
32
+ });
33
+ //#endregion
34
+ //#region @backend
35
+ HelpersCore.prototype.cleanExit = function () {
36
+ index_1.Helpers.processes.forEach(function (p) {
37
+ p.kill('SIGINT');
38
+ p.kill('SIGTERM');
39
+ index_1.Helpers.log("Killing child process on ".concat(p.pid));
40
+ });
41
+ index_1.Helpers.log("Killing parent on ".concat(process.pid));
42
+ process.exit();
43
+ };
44
+ ;
45
+ HelpersCore.prototype.removeSlashAtEnd = function (s) {
46
+ s = (s === null || s === void 0 ? void 0 : s.endsWith("/")) ? s.slice(0, s.length - 1) : s;
47
+ return s;
48
+ };
49
+ HelpersCore.prototype.removeSlashAtBegin = function (s) {
50
+ s = (s === null || s === void 0 ? void 0 : s.startsWith("/")) ? s.slice(1) : s;
51
+ return s;
52
+ };
53
+ HelpersCore.prototype.stringify = function (inputObject) {
54
+ // if (_.isString(inputObject)) {
55
+ // return inputObject;
56
+ // }
57
+ // if (_.isObject(inputObject)) {
58
+ // config.log(inputObject)
59
+ // Helpers.error(`[tnp-helpers] trying to stringify not a object`, false, true);
60
+ // }
61
+ return JSON.stringify(inputObject, null, 2);
62
+ };
63
+ HelpersCore.prototype.runSyncOrAsync = function (fn) {
64
+ var firstArg = [];
65
+ for (var _i = 1; _i < arguments.length; _i++) {
66
+ firstArg[_i - 1] = arguments[_i];
67
+ }
68
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
69
+ var promisOrValue;
70
+ var _a;
71
+ return tslib_1.__generator(this, function (_b) {
72
+ if (core_imports_1._.isUndefined(fn)) {
73
+ return [2 /*return*/];
74
+ }
75
+ promisOrValue = core_imports_1._.isArray(fn) ? (_a = fn[1])[fn[0]].apply(_a, tslib_1.__spreadArray([], tslib_1.__read(firstArg), false)) : fn.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(firstArg), false));
76
+ if (promisOrValue instanceof Promise) {
77
+ // wasPromise = true;
78
+ promisOrValue = Promise.resolve(promisOrValue);
79
+ }
80
+ // console.log('was promis ', wasPromise)
81
+ return [2 /*return*/, promisOrValue];
82
+ });
83
+ });
84
+ };
85
+ //#endregion
86
+ //#region @backend
87
+ HelpersCore.prototype.createSymLink = function (existedFileOrFolder, destinationPath, options) {
88
+ //#region fix parameters
89
+ existedFileOrFolder = (0, core_imports_1.crossPlatformPath)(existedFileOrFolder);
90
+ destinationPath = (0, core_imports_1.crossPlatformPath)(destinationPath);
91
+ index_1.Helpers.log("[tnp-helpers][create link] exited -> dest\n ".concat(existedFileOrFolder, " ").concat(destinationPath));
92
+ options = options ? options : {};
93
+ if (core_imports_1._.isUndefined(options.continueWhenExistedFolderDoesntExists)) {
94
+ options.continueWhenExistedFolderDoesntExists = false;
95
+ }
96
+ if (core_imports_1._.isUndefined(options.dontRenameWhenSlashAtEnd)) {
97
+ options.dontRenameWhenSlashAtEnd = false;
98
+ }
99
+ if (core_imports_1._.isUndefined(options.windowsHardLink)) {
100
+ options.windowsHardLink = false;
101
+ }
102
+ if (core_imports_1._.isUndefined(options.speedUpProcess)) {
103
+ options.speedUpProcess = false;
104
+ }
105
+ if (core_imports_1._.isUndefined(options.allowNotAbsolutePathes)) {
106
+ options.allowNotAbsolutePathes = false;
107
+ }
108
+ //#endregion
109
+ var continueWhenExistedFolderDoesntExists = options.continueWhenExistedFolderDoesntExists, windowsHardLink = options.windowsHardLink, speedUpProcess = options.speedUpProcess;
110
+ // console.log('Create link!')
111
+ var targetExisted = existedFileOrFolder;
112
+ var linkDest = destinationPath;
113
+ if (!core_imports_1.fse.existsSync(existedFileOrFolder)) {
114
+ if (continueWhenExistedFolderDoesntExists) {
115
+ // just continue and create link to not existed folder
116
+ }
117
+ else {
118
+ index_1.Helpers.error("[helpers.createLink] target path doesn't exist: ".concat(existedFileOrFolder, "\n use option \"continueWhenExistedFolderDoesntExists\" to fix this if you know that\n file will be eventually in place\n "));
119
+ }
120
+ }
121
+ /**
122
+ * support for
123
+ * pwd -> /mysource
124
+ * ln -s . /test/inside -> /test/inside/mysource
125
+ * ln -s ./ /test/inside -> /test/inside/mysource
126
+ */
127
+ if (options.allowNotAbsolutePathes) {
128
+ if (linkDest === '.' || linkDest === './') {
129
+ linkDest = (0, core_imports_1.crossPlatformPath)(process.cwd());
130
+ }
131
+ if (!core_imports_1.path.isAbsolute(linkDest)) {
132
+ linkDest = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join((0, core_imports_1.crossPlatformPath)(process.cwd()), linkDest));
133
+ }
134
+ if (!core_imports_1.path.isAbsolute(targetExisted)) {
135
+ targetExisted = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join((0, core_imports_1.crossPlatformPath)(process.cwd()), targetExisted));
136
+ }
137
+ }
138
+ else {
139
+ if (!core_imports_1.path.isAbsolute(linkDest)) {
140
+ index_1.Helpers.error("[createsymlink] path is not absolute:\n targetExisted: ".concat(targetExisted, "\n linkDest: ").concat(linkDest, "\n "));
141
+ }
142
+ if (!core_imports_1.path.isAbsolute(targetExisted)) {
143
+ index_1.Helpers.error("[createsymlink] path is not absolute:\n targetExisted: ".concat(targetExisted, "\n linkDest: ").concat(linkDest, "\n "));
144
+ }
145
+ }
146
+ if (linkDest.endsWith('/')) {
147
+ linkDest = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.join(linkDest, core_imports_1.path.basename(targetExisted)));
148
+ }
149
+ var parentFolderLinkDest = core_imports_1.path.dirname(linkDest);
150
+ if (index_1.Helpers.isSymlinkFileExitedOrUnexisted(parentFolderLinkDest)) {
151
+ core_imports_1.fse.unlinkSync(parentFolderLinkDest);
152
+ }
153
+ if (!index_1.Helpers.isFolder(parentFolderLinkDest)) {
154
+ core_imports_1.rimraf.sync(parentFolderLinkDest);
155
+ index_1.Helpers.mkdirp(parentFolderLinkDest);
156
+ }
157
+ if (!speedUpProcess) {
158
+ core_imports_1.rimraf.sync(linkDest);
159
+ }
160
+ if (process.platform === 'win32') {
161
+ // const resolvedTarget = crossPlatformPath(path.resolve(targetExisted));
162
+ // console.log(`resolved target from ${targetExisted} = ${resolvedTarget}, isFile: ${targetIsFile}`)
163
+ if (index_1.Helpers.isSymlinkFileExitedOrUnexisted(targetExisted)) {
164
+ // Helpers.info(`FIXING TARGET FOR WINDOWS`)
165
+ targetExisted = (0, core_imports_1.crossPlatformPath)(core_imports_1.fse.realpathSync(targetExisted));
166
+ // TODO QUICK_FIX on windows you can't create link to link
167
+ }
168
+ // targetExisted = path.win32.normalize(targetExisted).replace(/\\$/, '');
169
+ // linkDest = path.win32.normalize(linkDest).replace(/\\$/, '');
170
+ var targetIsFile = index_1.Helpers.isFile(targetExisted);
171
+ // const destIsLink = Helpers.isExistedSymlink(linkDest) || Helpers.isUnexistedLink(linkDest)
172
+ // console.log({
173
+ // targetExisted,
174
+ // linkDest,
175
+ // destIsLink
176
+ // });
177
+ // if (destIsLink) {
178
+ // fse.unlinkSync(linkDest)
179
+ // }
180
+ if (windowsHardLink) { // ADMIN RIGHT REQURED??
181
+ core_imports_1.fse.symlinkSync(targetExisted, linkDest, 'dir');
182
+ }
183
+ else {
184
+ if (targetIsFile) {
185
+ core_imports_1.fse.linkSync(targetExisted, linkDest);
186
+ }
187
+ else {
188
+ core_imports_1.fse.symlinkSync(targetExisted, linkDest, 'junction');
189
+ }
190
+ }
191
+ //#region old windows linking
192
+ /*
193
+ // const winLinkCommand = `cmd /c "mklink /D ${link} ${target}"`;
194
+ // const winLinkCommand = `export MSYS=winsymlinks:nativestrict && ln -s ${target} ${link}`;
195
+ const winLinkCommand = `mklink ${windowsHardLink ? '/D' : (targetIsFile ? '/H' : '/j')} "${linkDest}" "${targetExisted}"`;
196
+ Helpers.log(`windows link: lnk ${targetExisted} ${linkDest}
197
+
198
+
199
+ "${winLinkCommand}'
200
+ `);
201
+ try {
202
+ Helpers.run(winLinkCommand, { biggerBuffer: false }).sync();
203
+ } catch (error) {
204
+ Helpers.error(error, true, false);
205
+ Helpers.error(`
206
+ command: "${winLinkCommand}"
207
+ [tnp-helpers] windows link error
208
+ target: "${targetExisted}"
209
+ link: "${linkDest}"
210
+ command: "${winLinkCommand}"
211
+ `, true, false)
212
+ }
213
+ */
214
+ //#endregion
215
+ }
216
+ else {
217
+ core_imports_1.fse.symlinkSync(targetExisted, linkDest);
218
+ }
219
+ };
220
+ //#endregion
221
+ //#region @backend
222
+ HelpersCore.prototype.mkdirp = function (folderPath) {
223
+ if (core_imports_1._.isArray(folderPath)) {
224
+ folderPath = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(folderPath), false));
225
+ }
226
+ if (!core_imports_1.path.isAbsolute(folderPath)) {
227
+ index_1.Helpers.warn("[helpers][mkdirp] Path is not absolute, abort ".concat(folderPath), true);
228
+ return;
229
+ }
230
+ if (core_imports_1._.isString(folderPath) && folderPath.startsWith('/tmp ') && core_imports_1.os.platform() === 'darwin') {
231
+ index_1.Helpers.warn("[helpers][mkdirp] On mac osx /tmp is changed to /private/tmp", false);
232
+ folderPath = folderPath.replace("/tmp/", '/private/tmp/');
233
+ }
234
+ if (core_imports_1.fse.existsSync(folderPath)) {
235
+ index_1.Helpers.warn("[helpers][mkdirp] folder path already exists: ".concat(folderPath), false);
236
+ }
237
+ else {
238
+ core_imports_1.fse.mkdirpSync(folderPath);
239
+ }
240
+ };
241
+ //#endregion
242
+ /**
243
+ * symlink may have existed or unexisted destiantion url
244
+ * @param destUrl M
245
+ */
246
+ HelpersCore.prototype.isSymlinkThatMatchesUrl = function (possibleSymlink, destUrl, absoluteFileMatch) {
247
+ if (absoluteFileMatch === void 0) { absoluteFileMatch = false; }
248
+ //#region @backendFunc
249
+ destUrl = (0, core_imports_1.crossPlatformPath)(destUrl);
250
+ if (index_1.Helpers.exists(possibleSymlink)) {
251
+ if (index_1.Helpers.isExistedSymlink(possibleSymlink)) {
252
+ var fileLink = core_imports_1.fse.readlinkSync(possibleSymlink);
253
+ if (absoluteFileMatch) {
254
+ fileLink = core_imports_1.fse.realpathSync(fileLink);
255
+ }
256
+ fileLink = (0, core_imports_1.crossPlatformPath)(fileLink);
257
+ return fileLink === destUrl;
258
+ }
259
+ if (index_1.Helpers.isFolder(possibleSymlink)) {
260
+ return false;
261
+ }
262
+ }
263
+ try {
264
+ var linkToUnexitedLink = core_imports_1.fse.lstatSync(possibleSymlink).isSymbolicLink();
265
+ if (linkToUnexitedLink) {
266
+ var fileLink = core_imports_1.fse.readlinkSync(possibleSymlink);
267
+ if (absoluteFileMatch) {
268
+ fileLink = core_imports_1.fse.realpathSync(fileLink);
269
+ }
270
+ fileLink = (0, core_imports_1.crossPlatformPath)(fileLink);
271
+ return (fileLink === destUrl);
272
+ }
273
+ return false;
274
+ }
275
+ catch (error) {
276
+ return false;
277
+ }
278
+ //#endregion
279
+ };
280
+ HelpersCore.prototype.isSymlinkFileExitedOrUnexisted = function (filePath) {
281
+ //#region @backendFunc
282
+ try {
283
+ var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
284
+ return linkToUnexitedLink;
285
+ }
286
+ catch (error) {
287
+ return false;
288
+ }
289
+ //#endregion
290
+ };
291
+ /**
292
+ * If symbolnk link that target file does not exits
293
+ */
294
+ HelpersCore.prototype.isUnexistedLink = function (filePath) {
295
+ //#region @backendFunc
296
+ filePath = index_1.Helpers.removeSlashAtEnd(filePath);
297
+ if (process.platform === 'win32') {
298
+ filePath = core_imports_1.path.win32.normalize(filePath);
299
+ }
300
+ try {
301
+ var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
302
+ return linkToUnexitedLink && !core_imports_1.fse.existsSync(core_imports_1.fse.readlinkSync(filePath));
303
+ }
304
+ catch (error) {
305
+ return false;
306
+ }
307
+ //#endregion
308
+ };
309
+ /**
310
+ * @param existedLink check if source of link exists
311
+ */
312
+ HelpersCore.prototype.isExistedSymlink = function (filePath) {
313
+ //#region @backendFunc
314
+ filePath = index_1.Helpers.removeSlashAtEnd(filePath);
315
+ if (process.platform === 'win32') {
316
+ filePath = core_imports_1.path.win32.normalize(filePath);
317
+ }
318
+ try {
319
+ var linkToUnexitedLink = core_imports_1.fse.lstatSync(filePath).isSymbolicLink();
320
+ return linkToUnexitedLink && core_imports_1.fse.existsSync(core_imports_1.fse.readlinkSync(filePath));
321
+ }
322
+ catch (error) {
323
+ return false;
324
+ }
325
+ //#endregion
326
+ };
327
+ //#region @backend
328
+ HelpersCore.prototype.pathContainLink = function (p) {
329
+ var previous;
330
+ while (true) {
331
+ p = (0, core_imports_1.crossPlatformPath)(core_imports_1.path.dirname(p));
332
+ if (p === previous) {
333
+ return false;
334
+ }
335
+ if (index_1.Helpers.isExistedSymlink(p)) {
336
+ return true;
337
+ }
338
+ if (!index_1.Helpers.exists(p)) {
339
+ return false;
340
+ }
341
+ previous = p;
342
+ }
343
+ };
344
+ //#endregion
345
+ HelpersCore.prototype.exists = function (folderOrFilePath
346
+ // , allowUnexistedLinks = false
347
+ ) {
348
+ //#region @backendFunc
349
+ if (core_imports_1._.isArray(folderOrFilePath)) {
350
+ folderOrFilePath = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(folderOrFilePath), false));
351
+ }
352
+ if (!folderOrFilePath) {
353
+ index_1.Helpers.warn("[helpers][exists] Path is not a string, abort.. \"".concat(folderOrFilePath, "\""), true);
354
+ return false;
355
+ }
356
+ if (!core_imports_1.path.isAbsolute(folderOrFilePath)) {
357
+ index_1.Helpers.warn("\n\n ".concat(folderOrFilePath, "\n\n "), true);
358
+ return false;
359
+ }
360
+ return core_imports_1.fse.existsSync(folderOrFilePath);
361
+ //#endregion
362
+ };
363
+ HelpersCore.prototype.command = function (command) {
364
+ // console.log({ command })
365
+ return {
366
+ //#region @backend
367
+ getherOutput: function (options) {
368
+ if (!options) {
369
+ options = {};
370
+ }
371
+ return new Promise(function (resolve) {
372
+ var ommitStder = options.ommitStder, cwd = options.cwd, biggerBuffer = options.biggerBuffer, gatherColors = options.gatherColors;
373
+ if (!cwd) {
374
+ cwd = process.cwd();
375
+ }
376
+ var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : void 0;
377
+ var env = gatherColors ? tslib_1.__assign(tslib_1.__assign({}, process.env), { FORCE_COLOR: '1' }) : {};
378
+ var proc = core_imports_1.child_process.exec(command, {
379
+ cwd: cwd,
380
+ maxBuffer: maxBuffer,
381
+ env: env
382
+ });
383
+ var gatheredData = '';
384
+ proc.on('exit', function (code) {
385
+ resolve(gatheredData);
386
+ });
387
+ proc.stdout.on('data', function (data) {
388
+ gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
389
+ });
390
+ proc.stdout.on('error', function (data) {
391
+ gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
392
+ });
393
+ if (!ommitStder) {
394
+ proc.stderr.on('data', function (data) {
395
+ gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
396
+ });
397
+ proc.stderr.on('error', function (data) {
398
+ gatheredData = "".concat(gatheredData).concat((data === null || data === void 0 ? void 0 : data.toString()) || '');
399
+ });
400
+ }
401
+ });
402
+ }
403
+ //#endregion
404
+ };
405
+ };
406
+ HelpersCore.prototype.run = function (command, options) {
407
+ // console.log({ command })
408
+ //#region @backend
409
+ if (!options)
410
+ options = {};
411
+ if (options.output === undefined)
412
+ options.output = true;
413
+ if (options.biggerBuffer === undefined)
414
+ options.biggerBuffer = false;
415
+ if (options.cwd === undefined)
416
+ options.cwd = (0, core_imports_1.crossPlatformPath)(process.cwd());
417
+ if (!core_imports_1._.isString(command)) {
418
+ index_1.Helpers.error("[tnp-helper] command is not a string");
419
+ }
420
+ //#endregion
421
+ return {
422
+ //#region @backend
423
+ sync: function () {
424
+ if (core_imports_1._.isArray(options.extractFromLine)) {
425
+ index_1.Helpers.error("[tnp-helper] extractFromLine only for:\n - asyncAsPromise\n - async\n - unitlOutputContains\n\n ", false, true);
426
+ }
427
+ if (core_imports_1._.isNumber(options.tryAgainWhenFailAfter) && options.tryAgainWhenFailAfter > 0) {
428
+ // TODO try again when fail
429
+ // try {
430
+ var proc = index_1.Helpers.runSyncIn(command, options);
431
+ return proc;
432
+ // } catch (error) {
433
+ // TODO: WAIT FUNCTION HERE
434
+ // return Helpers.run(command, options).sync()
435
+ // }
436
+ }
437
+ return index_1.Helpers.runSyncIn(command, options);
438
+ },
439
+ async: function (detach) {
440
+ if (detach === void 0) { detach = false; }
441
+ options.detach = detach;
442
+ return index_1.Helpers.runAsyncIn(command, options);
443
+ },
444
+ asyncAsPromise: function () {
445
+ var isResolved = false;
446
+ return new Promise(function (resolve, reject) {
447
+ var proc = index_1.Helpers.runAsyncIn(command, options);
448
+ proc.on('exit', function () {
449
+ if (!isResolved) {
450
+ isResolved = true;
451
+ resolve(void 0);
452
+ }
453
+ });
454
+ proc.on('error', function () {
455
+ if (!isResolved) {
456
+ isResolved = true;
457
+ reject();
458
+ }
459
+ });
460
+ });
461
+ },
462
+ unitlOutputContains: function (stdoutMsg, stderMsg) {
463
+ var isResolved = false;
464
+ return new Promise(function (resolve, reject) {
465
+ if (core_imports_1._.isString(stdoutMsg)) {
466
+ stdoutMsg = [stdoutMsg];
467
+ }
468
+ if (core_imports_1._.isString(stderMsg)) {
469
+ stderMsg = [stderMsg];
470
+ }
471
+ if (!core_imports_1._.isArray(stdoutMsg)) {
472
+ reject("[unitlOutputContains] Message not a array");
473
+ }
474
+ var proc = index_1.Helpers.runAsyncIn(command, options);
475
+ proc.stderr.on('data', function (message) {
476
+ var data = message.toString().trim();
477
+ if (!isResolved && core_imports_1._.isArray(stderMsg)) {
478
+ for (var index = 0; index < stderMsg.length; index++) {
479
+ var rejectm = stderMsg[index];
480
+ if ((data.search(rejectm) !== -1)) {
481
+ index_1.Helpers.info("[unitlOutputContains] Rejected move to next step...");
482
+ isResolved = true;
483
+ reject();
484
+ proc.kill('SIGINT');
485
+ break;
486
+ }
487
+ }
488
+ }
489
+ });
490
+ proc.stdout.on('data', function (message) {
491
+ var data = message.toString().trim();
492
+ if (!isResolved) {
493
+ for (var index = 0; index < stdoutMsg.length; index++) {
494
+ var m = stdoutMsg[index];
495
+ if ((data.search(m) !== -1)) {
496
+ index_1.Helpers.info("[unitlOutputContains] Move to next step...");
497
+ isResolved = true;
498
+ resolve(void 0);
499
+ break;
500
+ }
501
+ }
502
+ }
503
+ if (!isResolved && core_imports_1._.isArray(stderMsg)) {
504
+ for (var index = 0; index < stderMsg.length; index++) {
505
+ var rejectm = stderMsg[index];
506
+ if ((data.search(rejectm) !== -1)) {
507
+ index_1.Helpers.info("[unitlOutputContains] Rejected move to next step...");
508
+ isResolved = true;
509
+ reject();
510
+ proc.kill('SIGINT');
511
+ break;
512
+ }
513
+ }
514
+ }
515
+ });
516
+ });
517
+ }
518
+ //#endregion
519
+ };
520
+ };
521
+ Object.defineProperty(HelpersCore.prototype, "isRunningIn", {
522
+ //#region @backend
523
+ get: function () {
524
+ return {
525
+ mochaTest: function () {
526
+ return (typeof global['it'] === 'function');
527
+ },
528
+ cliMode: function () {
529
+ return !!global['globalSystemToolMode'];
530
+ },
531
+ };
532
+ },
533
+ enumerable: false,
534
+ configurable: true
535
+ });
536
+ //#endregion
537
+ //#region @backend
538
+ HelpersCore.prototype.getStdio = function (options) {
539
+ var output = options.output, silence = options.silence, stdio = options.stdio
540
+ // pipeToParentProcerss = false,
541
+ // inheritFromParentProcerss = false
542
+ ;
543
+ if (typeof stdio !== 'undefined') {
544
+ return stdio;
545
+ }
546
+ var resstdio = output ? [0, 1, 2] : ((core_imports_1._.isBoolean(silence) && silence) ? 'ignore' : undefined);
547
+ // if (pipeToParentProcerss) {
548
+ // stdio = ['pipe', 'pipe', 'pipe'] as any;
549
+ // }
550
+ // if (inheritFromParentProcerss) {
551
+ // stdio = ['inherit', 'inherit', 'inherit'] as any;
552
+ // }
553
+ return resstdio;
554
+ };
555
+ //#endregion
556
+ //#region @backend
557
+ HelpersCore.prototype.runSyncIn = function (command, options) {
558
+ var cwd = options.cwd, biggerBuffer = options.biggerBuffer;
559
+ var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : undefined;
560
+ var stdio = index_1.Helpers.getStdio(options);
561
+ index_1.Helpers.checkProcess(cwd, command);
562
+ return core_imports_1.child_process.execSync(command, { stdio: stdio, cwd: cwd, maxBuffer: maxBuffer });
563
+ };
564
+ //#endregion
565
+ //#region @backend
566
+ HelpersCore.prototype.runAsyncIn = function (command, options) {
567
+ var output = options.output, cwd = options.cwd, biggerBuffer = options.biggerBuffer, outputLineReplace = options.outputLineReplace, extractFromLine = options.extractFromLine, detach = options.detach;
568
+ var maxBuffer = biggerBuffer ? index_1.Helpers.bigMaxBuffer : undefined;
569
+ var stdio = index_1.Helpers.getStdio(options);
570
+ index_1.Helpers.checkProcess(cwd, command);
571
+ var proc;
572
+ if (detach) {
573
+ var cmd = core_imports_1._.first(command.split(' '));
574
+ var argsForCmd = command.split(' ').slice(1);
575
+ index_1.Helpers.log("cmd: \"".concat(cmd, "\", args: \"").concat(argsForCmd.join(' '), "\""));
576
+ if (process.platform === 'win32') {
577
+ proc = (0, core_imports_1.spawn)(cmd, argsForCmd, { cwd: cwd, detached: true });
578
+ // proc = child_process.spawn(cmd, argsForCmd, {
579
+ // cwd,
580
+ // detached: true,
581
+ // // windowsVerbatimArguments: true,
582
+ // shell: true,
583
+ // // env: {
584
+ // // NODE_ENV: 'production',
585
+ // // PATH: process.env.PATH
586
+ // // }
587
+ // });
588
+ }
589
+ else {
590
+ proc = core_imports_1.child_process.spawn(cmd, argsForCmd, { cwd: cwd, detached: true });
591
+ }
592
+ index_1.Helpers.log("\n\n DETACHED PROCESS IS WORKING ON PID: ".concat(proc.pid, "\n\n "));
593
+ // proc = child.exec(`${command} &`, { cwd, maxBuffer, });
594
+ }
595
+ else {
596
+ // Helpers.log(`Command to execture: ${command}`)
597
+ var env = tslib_1.__assign(tslib_1.__assign({}, process.env), { FORCE_COLOR: '1' });
598
+ proc = core_imports_1.child_process.exec(command, { cwd: cwd, maxBuffer: maxBuffer, env: env });
599
+ if (global.globalSystemToolMode) {
600
+ proc.on('exit', function (code) {
601
+ index_1.Helpers.log('EXITING BIG PROCESS');
602
+ process.exit(code);
603
+ });
604
+ }
605
+ }
606
+ return index_1.Helpers.logProc(proc, detach ? true : output, detach ? void 0 : stdio, outputLineReplace, options.prefix, extractFromLine, command);
607
+ };
608
+ //#endregion
609
+ //#region @backend
610
+ HelpersCore.prototype.logProc = function (proc, output, stdio, outputLineReplace, prefix, extractFromLine, command) {
611
+ if (output === void 0) { output = true; }
612
+ index_1.Helpers.processes.push(proc);
613
+ if (stdio) {
614
+ // @ts-ignore
615
+ proc.stdio = stdio;
616
+ }
617
+ if (!prefix) {
618
+ prefix = '';
619
+ }
620
+ if (output) {
621
+ proc.stdout.on('data', function (data) {
622
+ // if (data?.toString().search('was unexpected at this time') !== -1) {
623
+ // console.log('!!!COMMAND',command)
624
+ // }
625
+ process.stdout.write(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
626
+ });
627
+ proc.stdout.on('error', function (data) {
628
+ // if (data?.toString().search('was unexpected at this time') !== -1) {
629
+ // console.log('!!!COMMAND',command)
630
+ // }
631
+ console.log(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
632
+ });
633
+ proc.stderr.on('data', function (data) {
634
+ // if (data?.toString().search('was unexpected at this time') !== -1) {
635
+ // console.log('!!!COMMAND',command)
636
+ // }
637
+ process.stderr.write(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
638
+ });
639
+ proc.stderr.on('error', function (data) {
640
+ // if (data?.toString().search('was unexpected at this time') !== -1) {
641
+ // console.log('!!!COMMAND',command)
642
+ // }
643
+ console.log(index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine));
644
+ });
645
+ }
646
+ return proc;
647
+ };
648
+ HelpersCore.prototype.execute = function (childProcess, options) {
649
+ var _this = this;
650
+ var _a = options || {}, hideOutput = _a.hideOutput, resolvePromiseMsg = _a.resolvePromiseMsg, outputLineReplace = _a.outputLineReplace, prefix = _a.prefix, extractFromLine = _a.extractFromLine, exitOnError = _a.exitOnError, exitOnErrorCallback = _a.exitOnErrorCallback;
651
+ // let {
652
+ // stderMsgForPromiseResolve,
653
+ // stdoutMsgForPromiseResolve
654
+ // } = resolvePromiseMsg || {};
655
+ // processes.push(proc);
656
+ if (!resolvePromiseMsg) {
657
+ resolvePromiseMsg = {};
658
+ }
659
+ if (!hideOutput) {
660
+ hideOutput = {};
661
+ }
662
+ var isResolved = false;
663
+ if (core_imports_1._.isString(resolvePromiseMsg.stdout)) {
664
+ resolvePromiseMsg.stdout = [resolvePromiseMsg.stdout];
665
+ }
666
+ if (core_imports_1._.isString(resolvePromiseMsg.stderr)) {
667
+ resolvePromiseMsg.stderr = [resolvePromiseMsg.stderr];
668
+ }
669
+ return new Promise(function (resolve, reject) {
670
+ // let stdio = [0,1,2]
671
+ childProcess.stdout.on('data', function (rawData) {
672
+ var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
673
+ data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
674
+ if (!hideOutput.stdout) {
675
+ process.stdout.write(data);
676
+ }
677
+ if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stdout)) {
678
+ for (var index = 0; index < resolvePromiseMsg.stdout.length; index++) {
679
+ var m = resolvePromiseMsg.stdout[index];
680
+ if ((data.search(m) !== -1)) {
681
+ // Helpers.info(`[unitlOutputContains] Move to next step...`)
682
+ isResolved = true;
683
+ resolve(void 0);
684
+ break;
685
+ }
686
+ }
687
+ }
688
+ if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stderr)) {
689
+ for (var index = 0; index < resolvePromiseMsg.stderr.length; index++) {
690
+ var rejectm = resolvePromiseMsg.stderr[index];
691
+ if ((data.search(rejectm) !== -1)) {
692
+ // Helpers.info(`[unitlOutputContains] Rejected move to next step...`);
693
+ isResolved = true;
694
+ reject();
695
+ childProcess.kill('SIGINT');
696
+ break;
697
+ }
698
+ }
699
+ }
700
+ // console.log(data.toString());
701
+ });
702
+ childProcess.on('exit', function (code) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
703
+ var error_1;
704
+ return tslib_1.__generator(this, function (_a) {
705
+ switch (_a.label) {
706
+ case 0:
707
+ if (!(exitOnError && code !== 0)) return [3 /*break*/, 5];
708
+ if (!core_imports_1._.isFunction(exitOnErrorCallback)) return [3 /*break*/, 4];
709
+ _a.label = 1;
710
+ case 1:
711
+ _a.trys.push([1, 3, , 4]);
712
+ return [4 /*yield*/, this.runSyncOrAsync(exitOnErrorCallback, code)];
713
+ case 2:
714
+ _a.sent();
715
+ return [3 /*break*/, 4];
716
+ case 3:
717
+ error_1 = _a.sent();
718
+ return [3 /*break*/, 4];
719
+ case 4:
720
+ process.exit(code);
721
+ _a.label = 5;
722
+ case 5:
723
+ resolve(void 0);
724
+ return [2 /*return*/];
725
+ }
726
+ });
727
+ }); });
728
+ childProcess.stdout.on('error', function (rawData) {
729
+ var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
730
+ data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
731
+ if (!hideOutput.stdout) {
732
+ process.stdout.write(JSON.stringify(data));
733
+ }
734
+ // console.log(data);
735
+ });
736
+ childProcess.stderr.on('data', function (rawData) {
737
+ var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
738
+ data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
739
+ if (!hideOutput.stderr) {
740
+ process.stderr.write(data);
741
+ }
742
+ if (!isResolved && core_imports_1._.isArray(resolvePromiseMsg.stderr)) {
743
+ for (var index = 0; index < resolvePromiseMsg.stderr.length; index++) {
744
+ var rejectm = resolvePromiseMsg.stderr[index];
745
+ if ((data.search(rejectm) !== -1)) {
746
+ // Helpers.info(`[unitlOutputContains] Rejected move to next step...`);
747
+ isResolved = true;
748
+ reject();
749
+ childProcess.kill('SIGINT');
750
+ break;
751
+ }
752
+ }
753
+ }
754
+ });
755
+ childProcess.stderr.on('error', function (rawData) {
756
+ var data = ((rawData === null || rawData === void 0 ? void 0 : rawData.toString()) || '');
757
+ data = index_1.Helpers.modifyLineByLine(data, outputLineReplace, prefix, extractFromLine);
758
+ if (!hideOutput.stderr) {
759
+ process.stderr.write(JSON.stringify(data));
760
+ }
761
+ // console.log(data);
762
+ });
763
+ });
764
+ };
765
+ //#endregion
766
+ //#region @backend
767
+ HelpersCore.prototype.checkProcess = function (dirPath, command) {
768
+ if (!core_imports_1.fse.existsSync(dirPath)) {
769
+ index_1.Helpers.error("\nPath for process cwd doesn't exist: ".concat(dirPath, "\ncommand: ").concat(command, "\n"));
770
+ }
771
+ if (!command) {
772
+ index_1.Helpers.error("Bad command: ".concat(command));
773
+ }
774
+ };
775
+ //#endregion
776
+ //#region @backend
777
+ HelpersCore.prototype.modifyLineByLine = function (data, outputLineReplace, prefix, extractFromLine) {
778
+ var checkExtract = (core_imports_1._.isArray(extractFromLine) && extractFromLine.length > 0);
779
+ var modifyOutput = core_imports_1._.isFunction(outputLineReplace);
780
+ if (modifyOutput && core_imports_1._.isString(data)) {
781
+ data = data.split(/\r?\n/).map(function (line) { return outputLineReplace(line // .replace(chalkCharactersRegex, '')
782
+ ); }).join('\n');
783
+ }
784
+ if (prefix && core_imports_1._.isString(data)) {
785
+ return data.split('\n').map(function (singleLine) {
786
+ if (!singleLine || singleLine.trim().length === 0 || singleLine.trim() === '.') {
787
+ return singleLine;
788
+ }
789
+ if (checkExtract) {
790
+ var sFuncs = extractFromLine
791
+ .filter(function (f) { return core_imports_1._.isString(f); });
792
+ if (sFuncs.filter(function (f) { return (singleLine.search(f) !== -1); }).length === sFuncs.length) {
793
+ var fun = extractFromLine.find(function (f) { return core_imports_1._.isFunction(f); });
794
+ if (fun) {
795
+ var s_1 = singleLine;
796
+ sFuncs.forEach(function (f) { s_1 = s_1.replace(f, ''); });
797
+ fun(s_1.trim());
798
+ }
799
+ }
800
+ }
801
+ return "".concat(prefix, " ").concat(singleLine);
802
+ }).join('\n');
803
+ }
804
+ return data;
805
+ };
806
+ //#endregion
807
+ //#region @backend
808
+ HelpersCore.prototype.isFolder = function (pathToFileOrMaybeFolder) {
809
+ return pathToFileOrMaybeFolder && core_imports_1.fse.existsSync(pathToFileOrMaybeFolder) &&
810
+ core_imports_1.fse.lstatSync(pathToFileOrMaybeFolder).isDirectory();
811
+ };
812
+ //#endregion
813
+ /**
814
+ * Quick fix for object values
815
+ */
816
+ HelpersCore.prototype.values = function (obj) {
817
+ if (core_imports_1._.isObject(obj) && !Array.isArray(obj)) {
818
+ var values = [];
819
+ for (var key in obj) {
820
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
821
+ values.push(obj[key]);
822
+ }
823
+ }
824
+ return values;
825
+ }
826
+ return [];
827
+ };
828
+ //#region @backend
829
+ /**
830
+ * does not make sense
831
+ */
832
+ HelpersCore.prototype.isFile = function (pathToFileOrMaybeFolder) {
833
+ return pathToFileOrMaybeFolder && core_imports_1.fse.existsSync(pathToFileOrMaybeFolder) &&
834
+ !core_imports_1.fse.lstatSync(pathToFileOrMaybeFolder).isDirectory();
835
+ };
836
+ //#endregion
837
+ //#region @backend
838
+ /**
839
+ * wrapper for fs.readFileSync
840
+ */
841
+ HelpersCore.prototype.readFile = function (absoluteFilePath, defaultValueWhenNotExists) {
842
+ if (defaultValueWhenNotExists === void 0) { defaultValueWhenNotExists = void 0; }
843
+ if (core_imports_1._.isArray(absoluteFilePath)) {
844
+ absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
845
+ }
846
+ absoluteFilePath = absoluteFilePath;
847
+ if (!core_imports_1.fse.existsSync(absoluteFilePath)) {
848
+ return defaultValueWhenNotExists;
849
+ }
850
+ if (core_imports_1.fse.lstatSync(absoluteFilePath).isDirectory()) {
851
+ return defaultValueWhenNotExists;
852
+ }
853
+ return core_imports_1.fse.readFileSync(absoluteFilePath, {
854
+ encoding: encoding
855
+ }).toString().trim();
856
+ };
857
+ //#endregion
858
+ //#region @backend
859
+ HelpersCore.prototype.readJson = function (absoluteFilePath, defaultValue, useJson5) {
860
+ if (defaultValue === void 0) { defaultValue = {}; }
861
+ if (useJson5 === void 0) { useJson5 = false; }
862
+ if (core_imports_1._.isArray(absoluteFilePath)) {
863
+ absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
864
+ }
865
+ absoluteFilePath = absoluteFilePath;
866
+ if (!core_imports_1.fse.existsSync(absoluteFilePath)) {
867
+ return {};
868
+ }
869
+ try {
870
+ var fileContent = index_1.Helpers.readFile(absoluteFilePath);
871
+ var json = void 0;
872
+ json = index_1.Helpers.parse(fileContent, useJson5 || absoluteFilePath.endsWith('.json5'));
873
+ return json;
874
+ }
875
+ catch (error) {
876
+ return defaultValue;
877
+ }
878
+ };
879
+ //#endregion
880
+ //#region @backend
881
+ HelpersCore.prototype.parse = function (jsonInstring, useJson5) {
882
+ if (useJson5 === void 0) { useJson5 = false; }
883
+ if (!core_imports_1._.isString(jsonInstring)) {
884
+ index_1.Helpers.log(jsonInstring);
885
+ index_1.Helpers.warn("[tnp-helpers] Trying to parse no a string...");
886
+ return jsonInstring;
887
+ }
888
+ return (useJson5 ? core_imports_1.json5.parse(jsonInstring) : JSON.parse(jsonInstring));
889
+ };
890
+ //#endregion
891
+ //#region @backend
892
+ HelpersCore.prototype.compilationWrapper = function (fn, taskName, executionType) {
893
+ if (taskName === void 0) { taskName = 'Task'; }
894
+ if (executionType === void 0) { executionType = 'Compilation of'; }
895
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
896
+ // global?.spinner?.start();
897
+ function currentDate() {
898
+ return "[".concat((0, core_imports_1.dateformat)(new Date(), 'HH:MM:ss'), "]");
899
+ }
900
+ var error_2;
901
+ return tslib_1.__generator(this, function (_a) {
902
+ switch (_a.label) {
903
+ case 0:
904
+ if (!fn || !core_imports_1._.isFunction(fn)) {
905
+ index_1.Helpers.error("".concat(executionType, " wrapper: \"").concat(fn, "\" is not a function."));
906
+ process.exit(1);
907
+ }
908
+ _a.label = 1;
909
+ case 1:
910
+ _a.trys.push([1, 3, , 4]);
911
+ index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " \"").concat(taskName, "\" Started.."));
912
+ return [4 /*yield*/, index_1.Helpers.runSyncOrAsync(fn)];
913
+ case 2:
914
+ _a.sent();
915
+ index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " \"").concat(taskName, "\" Done\u2713"));
916
+ return [3 /*break*/, 4];
917
+ case 3:
918
+ error_2 = _a.sent();
919
+ index_1.Helpers.error(core_imports_1.chalk.red(error_2), false, true);
920
+ index_1.Helpers.log("".concat(currentDate(), " ").concat(executionType, " ").concat(taskName, " ERROR"));
921
+ process.exit(1);
922
+ return [3 /*break*/, 4];
923
+ case 4: return [2 /*return*/];
924
+ }
925
+ });
926
+ });
927
+ };
928
+ //#endregion
929
+ //#region @backend
930
+ /**
931
+ * wrapper for fs.writeFileSync
932
+ */
933
+ HelpersCore.prototype.writeFile = function (absoluteFilePath, input, options) {
934
+ if (core_imports_1._.isArray(absoluteFilePath)) {
935
+ absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
936
+ }
937
+ absoluteFilePath = absoluteFilePath;
938
+ if (index_1.Helpers.isExistedSymlink(absoluteFilePath)) {
939
+ var beforePath = absoluteFilePath;
940
+ absoluteFilePath = core_imports_1.fse.realpathSync(absoluteFilePath);
941
+ index_1.Helpers.warn("WRITTING JSON into real path:\n original: ".concat(beforePath, "\n real : ").concat(absoluteFilePath, "\n "));
942
+ }
943
+ var _a = options || {}, preventParentFile = _a.preventParentFile, overrideSameFile = _a.overrideSameFile;
944
+ var dontWriteSameFile = !overrideSameFile;
945
+ if (preventParentFile) {
946
+ if (index_1.Helpers.isFile(core_imports_1.path.dirname(absoluteFilePath)) && core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
947
+ core_imports_1.fse.unlinkSync(core_imports_1.path.dirname(absoluteFilePath));
948
+ }
949
+ }
950
+ if (!core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
951
+ index_1.Helpers.mkdirp(core_imports_1.path.dirname(absoluteFilePath));
952
+ }
953
+ if (core_imports_1._.isObject(input)) {
954
+ input = index_1.Helpers.stringify(input);
955
+ }
956
+ else if (!core_imports_1._.isString(input)) {
957
+ input = '';
958
+ }
959
+ if (dontWriteSameFile) {
960
+ if (core_imports_1.fse.existsSync(absoluteFilePath)) {
961
+ var existedInput = index_1.Helpers.readFile(absoluteFilePath);
962
+ if (input === existedInput) {
963
+ // Helpers.log(`[helpers][writeFile] not writing same file (good thing): ${absoluteFilePath}`);
964
+ return false;
965
+ }
966
+ }
967
+ }
968
+ core_imports_1.fse.writeFileSync(absoluteFilePath, input, {
969
+ encoding: encoding
970
+ });
971
+ return true;
972
+ };
973
+ //#endregion
974
+ //#region @backend
975
+ /**
976
+ * wrapper for fs.writeFileSync
977
+ */
978
+ HelpersCore.prototype.writeJson = function (absoluteFilePath, input, optoins) {
979
+ if (core_imports_1._.isArray(absoluteFilePath)) {
980
+ absoluteFilePath = core_imports_1.path.join.apply(this, absoluteFilePath);
981
+ }
982
+ absoluteFilePath = absoluteFilePath;
983
+ var preventParentFile = (optoins || {}).preventParentFile;
984
+ if (preventParentFile) {
985
+ if (index_1.Helpers.isFile(core_imports_1.path.dirname(absoluteFilePath)) && core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
986
+ core_imports_1.fse.unlinkSync(core_imports_1.path.dirname(absoluteFilePath));
987
+ }
988
+ }
989
+ if (!core_imports_1.fse.existsSync(core_imports_1.path.dirname(absoluteFilePath))) {
990
+ index_1.Helpers.mkdirp(core_imports_1.path.dirname(absoluteFilePath));
991
+ }
992
+ core_imports_1.fse.writeJSONSync(absoluteFilePath, input, {
993
+ encoding: encoding,
994
+ spaces: 2
995
+ });
996
+ return true;
997
+ };
998
+ //#endregion
999
+ //#region @backend
1000
+ /**
1001
+ * return absolute paths for folders inside folders
1002
+ */
1003
+ HelpersCore.prototype.foldersFrom = function (pathToFolder) {
1004
+ if (core_imports_1._.isArray(pathToFolder)) {
1005
+ pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1006
+ }
1007
+ if (!index_1.Helpers.exists(pathToFolder)) {
1008
+ return [];
1009
+ }
1010
+ return core_imports_1.fse.readdirSync(pathToFolder)
1011
+ .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1012
+ .filter(function (f) { return core_imports_1.fse.lstatSync(f).isDirectory(); });
1013
+ };
1014
+ HelpersCore.prototype.linksToFoldersFrom = function (pathToFolder, outputRealPath) {
1015
+ if (outputRealPath === void 0) { outputRealPath = false; }
1016
+ if (core_imports_1._.isArray(pathToFolder)) {
1017
+ pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1018
+ }
1019
+ if (!index_1.Helpers.exists(pathToFolder)) {
1020
+ return [];
1021
+ }
1022
+ return core_imports_1.fse.readdirSync(pathToFolder)
1023
+ .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1024
+ .filter(function (f) { return core_imports_1.fse.existsSync(f) && core_imports_1.fse.lstatSync(f).isSymbolicLink(); })
1025
+ .map(function (f) {
1026
+ var realPath = core_imports_1.fse.realpathSync(f);
1027
+ var isFolder = index_1.Helpers.isFolder(realPath);
1028
+ if (isFolder) {
1029
+ if (outputRealPath) {
1030
+ return realPath;
1031
+ }
1032
+ else {
1033
+ return f;
1034
+ }
1035
+ }
1036
+ }).filter(function (f) { return !!f; });
1037
+ };
1038
+ //#endregion
1039
+ //#region @backend
1040
+ /**
1041
+ * return absolute paths for folders inside folders
1042
+ */
1043
+ HelpersCore.prototype.linksToFolderFrom = function (pathToFolder) {
1044
+ // options = (options || {}) as any;
1045
+ // if (_.isUndefined(options.linksOnlyTo)) {
1046
+ // options.linksOnlyTo = 'both';
1047
+ // }
1048
+ if (core_imports_1._.isArray(pathToFolder)) {
1049
+ pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1050
+ }
1051
+ if (!index_1.Helpers.exists(pathToFolder)) {
1052
+ return [];
1053
+ }
1054
+ return core_imports_1.fse.readdirSync(pathToFolder)
1055
+ .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1056
+ .filter(function (f) {
1057
+ var res = false;
1058
+ if (index_1.Helpers.isExistedSymlink(f)) {
1059
+ var realPath = core_imports_1.fse.realpathSync(f);
1060
+ return index_1.Helpers.isFolder(realPath);
1061
+ }
1062
+ return res;
1063
+ });
1064
+ };
1065
+ //#endregion
1066
+ //#region @backend
1067
+ /**
1068
+ * return absolute paths for folders inside folders
1069
+ */
1070
+ HelpersCore.prototype.filesFrom = function (pathToFolder, recrusive) {
1071
+ var _this = this;
1072
+ if (recrusive === void 0) { recrusive = false; }
1073
+ if (core_imports_1._.isArray(pathToFolder)) {
1074
+ pathToFolder = core_imports_1.path.join.apply(core_imports_1.path, tslib_1.__spreadArray([], tslib_1.__read(pathToFolder), false));
1075
+ }
1076
+ if (!index_1.Helpers.exists(pathToFolder)) {
1077
+ return [];
1078
+ }
1079
+ if (recrusive) {
1080
+ var all = core_imports_1.fse.readdirSync(pathToFolder)
1081
+ .map(function (f) { return core_imports_1.path.join(pathToFolder, f); });
1082
+ var folders_1 = [];
1083
+ var files = all.filter(function (f) {
1084
+ if (core_imports_1.fse.lstatSync(f).isDirectory()) {
1085
+ folders_1.push(f);
1086
+ return false;
1087
+ }
1088
+ return true;
1089
+ });
1090
+ return tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(files), false), tslib_1.__read(folders_1
1091
+ .map(function (f) { return _this.filesFrom(f, recrusive); })
1092
+ .reduce(function (a, b) {
1093
+ return a.concat(b);
1094
+ }, [])), false);
1095
+ }
1096
+ return core_imports_1.fse.readdirSync(pathToFolder)
1097
+ .map(function (f) { return core_imports_1.path.join(pathToFolder, f); })
1098
+ .filter(function (f) { return !core_imports_1.fse.lstatSync(f).isDirectory(); });
1099
+ };
1100
+ //#endregion
1101
+ //#region @backend
1102
+ HelpersCore.prototype.openFolderInFileExploer = function (folderPath) {
1103
+ if (process.platform === 'win32') {
1104
+ folderPath = (0, core_imports_1.win32Path)(folderPath);
1105
+ }
1106
+ try {
1107
+ index_1.Helpers.info("Opening path in file explorer: \"".concat(folderPath, "\""));
1108
+ if (process.platform === 'win32') {
1109
+ index_1.Helpers.run("explorer ".concat(folderPath)).sync();
1110
+ return;
1111
+ }
1112
+ if (process.platform === 'darwin') {
1113
+ index_1.Helpers.run("open ".concat(folderPath)).sync();
1114
+ return;
1115
+ }
1116
+ index_1.Helpers.run("xdg-open ".concat(folderPath)).sync();
1117
+ }
1118
+ catch (error) {
1119
+ if (process.platform !== 'win32') { // TODO QUICK fix explorer with path is triggering errro
1120
+ index_1.Helpers.error("Not able to open in file explorer: \"".concat(folderPath, "\""), false, true);
1121
+ }
1122
+ }
1123
+ };
1124
+ return HelpersCore;
1125
+ }(helpers_messages_1.HelpersMessages));
1126
+ exports.HelpersCore = HelpersCore;
1127
+ //# sourceMappingURL=/Users/dfilipiak/projects/npm/tnp-core/tmp-bundle-release/bundle/project/tnp-core/bundle-nocutsrc/lib/helpers.js.map