tnp-core 13.1.19 → 13.1.21

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