ahegao 1.69.1

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.
@@ -0,0 +1,3221 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.classifyExt = exports.isImageSequence = exports.isModel = exports.isCode = exports.isDocument = exports.isArchive = exports.isFont = exports.isSubtitle = exports.isAudio = exports.isVideo = exports.isPicture = exports.getZeroBigInt = exports.getZero = exports.ZERO_BIG_INT = exports.geniusClient = exports.chalk = exports.musicMetadata = void 0;
40
+ exports.toExtension = toExtension;
41
+ exports.removeExtension = removeExtension;
42
+ exports.rtl = rtl;
43
+ exports.random = random;
44
+ exports.randomBoolean = randomBoolean;
45
+ exports.randomFromArray = randomFromArray;
46
+ exports.randomFromArrayButNot = randomFromArrayButNot;
47
+ exports.upsideMapDown = upsideMapDown;
48
+ exports.forEachInfo = forEachInfo;
49
+ exports.forEach = forEach;
50
+ exports.forEachFileInfo = forEachFileInfo;
51
+ exports.forEachFile = forEachFile;
52
+ exports.forEachDirInfo = forEachDirInfo;
53
+ exports.forEachDir = forEachDir;
54
+ exports.forEachInfoRecursive = forEachInfoRecursive;
55
+ exports.forEachRecursive = forEachRecursive;
56
+ exports.forEachFileInfoRecursive = forEachFileInfoRecursive;
57
+ exports.getEachFileInfoRecursive = getEachFileInfoRecursive;
58
+ exports.getEachFileInfo = getEachFileInfo;
59
+ exports.forEachFileRecursive = forEachFileRecursive;
60
+ exports.forEachDirInfoRecursive = forEachDirInfoRecursive;
61
+ exports.getEachDirInfoRecursive = getEachDirInfoRecursive;
62
+ exports.forEachDirRecursive = forEachDirRecursive;
63
+ exports.purgeEmptyDirectoriesRecursive = purgeEmptyDirectoriesRecursive;
64
+ exports.firstUpperLowerRest = firstUpperLowerRest;
65
+ exports.firstUpperLowerRestEachWord = firstUpperLowerRestEachWord;
66
+ exports.countChars = countChars;
67
+ exports.countWords = countWords;
68
+ exports.countEmoji = countEmoji;
69
+ exports.incrementMap = incrementMap;
70
+ exports.incrementObjNumber = incrementObjNumber;
71
+ exports.addObjs = addObjs;
72
+ exports.sumValues = sumValues;
73
+ exports.getOrDefaultObj = getOrDefaultObj;
74
+ exports.getOrDefaultMap = getOrDefaultMap;
75
+ exports.getOrDefault = getOrDefault;
76
+ exports.runSoft = runSoft;
77
+ exports.blacklistArray = blacklistArray;
78
+ exports.getChars = getChars;
79
+ exports.getDiff = getDiff;
80
+ exports.formatDate = formatDate;
81
+ exports.decide = decide;
82
+ exports.decideAsync = decideAsync;
83
+ exports.make = make;
84
+ exports.makeAsync = makeAsync;
85
+ exports.extractElementsIntoArray = extractElementsIntoArray;
86
+ exports.extractItemsIntoArray = extractItemsIntoArray;
87
+ exports.mapArrayOfObjsByElement = mapArrayOfObjsByElement;
88
+ exports.mapToArray = mapToArray;
89
+ exports.stringify = stringify;
90
+ exports.acronymStringIfTooLong = acronymStringIfTooLong;
91
+ exports.mkdirSoftRecursive = mkdirSoftRecursive;
92
+ exports.mkdirSoft = mkdirSoft;
93
+ exports.goUpDir = goUpDir;
94
+ exports.writeFileIfNotPresent = writeFileIfNotPresent;
95
+ exports.requireSoft = requireSoft;
96
+ exports.clone = clone;
97
+ exports.getBit = getBit;
98
+ exports.isBit = isBit;
99
+ exports.map = map;
100
+ exports.logMap = logMap;
101
+ exports.clamp = clamp;
102
+ exports.clamp0 = clamp0;
103
+ exports.datesDiff = datesDiff;
104
+ exports.datesDiffToStamp = datesDiffToStamp;
105
+ exports.datesGapToStamp = datesGapToStamp;
106
+ exports.dateToStamp = dateToStamp;
107
+ exports.toStamp = toStamp;
108
+ exports.convertNumberBase = convertNumberBase;
109
+ exports.moveSync = moveSync;
110
+ exports.download = download;
111
+ exports.isCharUpperCase = isCharUpperCase;
112
+ exports.isCharLowerCase = isCharLowerCase;
113
+ exports.isStandardLetter = isStandardLetter;
114
+ exports.getOrCreateAppendedLinesFile = getOrCreateAppendedLinesFile;
115
+ exports.rmSoft = rmSoft;
116
+ exports.saveAppendedLinesFile = saveAppendedLinesFile;
117
+ exports.getOrCreateFromKeys = getOrCreateFromKeys;
118
+ exports.getOrCreate = getOrCreate;
119
+ exports.getOrCreateObj = getOrCreateObj;
120
+ exports.appendObjArray = appendObjArray;
121
+ exports.organiseByKey = organiseByKey;
122
+ exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
123
+ exports.secondsToNanoseconds = secondsToNanoseconds;
124
+ exports.minutesToNanoseconds = minutesToNanoseconds;
125
+ exports.hoursToNanoseconds = hoursToNanoseconds;
126
+ exports.daysToNanoseconds = daysToNanoseconds;
127
+ exports.weeksToNanoseconds = weeksToNanoseconds;
128
+ exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
129
+ exports.secondsToMilliseconds = secondsToMilliseconds;
130
+ exports.minutesToMilliseconds = minutesToMilliseconds;
131
+ exports.hoursToMilliseconds = hoursToMilliseconds;
132
+ exports.daysToMilliseconds = daysToMilliseconds;
133
+ exports.weeksToMilliseconds = weeksToMilliseconds;
134
+ exports.nanosecondsToSeconds = nanosecondsToSeconds;
135
+ exports.millisecondsToSeconds = millisecondsToSeconds;
136
+ exports.minutesToSeconds = minutesToSeconds;
137
+ exports.hoursToSeconds = hoursToSeconds;
138
+ exports.daysToSeconds = daysToSeconds;
139
+ exports.weeksToSeconds = weeksToSeconds;
140
+ exports.nanosecondsToMinutes = nanosecondsToMinutes;
141
+ exports.millisecondsToMinutes = millisecondsToMinutes;
142
+ exports.secondsToMinutes = secondsToMinutes;
143
+ exports.hoursToMinutes = hoursToMinutes;
144
+ exports.daysToMinutes = daysToMinutes;
145
+ exports.weeksToMinutes = weeksToMinutes;
146
+ exports.nanosecondsToHours = nanosecondsToHours;
147
+ exports.millisecondsToHours = millisecondsToHours;
148
+ exports.secondsToHours = secondsToHours;
149
+ exports.minutesToHours = minutesToHours;
150
+ exports.daysToHours = daysToHours;
151
+ exports.weeksToHours = weeksToHours;
152
+ exports.nanosecondsToDays = nanosecondsToDays;
153
+ exports.millisecondsToDays = millisecondsToDays;
154
+ exports.secondsToDays = secondsToDays;
155
+ exports.minutesToDays = minutesToDays;
156
+ exports.hoursToDays = hoursToDays;
157
+ exports.weeksToDays = weeksToDays;
158
+ exports.nanosecondsToWeeks = nanosecondsToWeeks;
159
+ exports.millisecondsToWeeks = millisecondsToWeeks;
160
+ exports.secondsToWeeks = secondsToWeeks;
161
+ exports.minutesToWeeks = minutesToWeeks;
162
+ exports.hoursToWeeks = hoursToWeeks;
163
+ exports.daysToWeeks = daysToWeeks;
164
+ exports.minutesToHoursMinutes = minutesToHoursMinutes;
165
+ exports.parsedFileInfoNameToIntSort = parsedFileInfoNameToIntSort;
166
+ exports.parsedStringToIntSort = parsedStringToIntSort;
167
+ exports.degreesToRadians = degreesToRadians;
168
+ exports.toRads = toRads;
169
+ exports.radiansToDegrees = radiansToDegrees;
170
+ exports.toDegs = toDegs;
171
+ exports.getDayMonthYearDateString = getDayMonthYearDateString;
172
+ exports.touchSoft = touchSoft;
173
+ exports.increment = increment;
174
+ exports.readFileInt = readFileInt;
175
+ exports.hashCode = hashCode;
176
+ exports.chalkColor = chalkColor;
177
+ exports.chalkRainbowColor = chalkRainbowColor;
178
+ exports.seededChalkRainbowColor = seededChalkRainbowColor;
179
+ exports.randomChalkRainbowColor = randomChalkRainbowColor;
180
+ exports.padLeft = padLeft;
181
+ exports.padRight = padRight;
182
+ exports.getCuteAscii = getCuteAscii;
183
+ exports.isEmpty = isEmpty;
184
+ exports.singleSpacesOnly = singleSpacesOnly;
185
+ exports.getWeekDayString = getWeekDayString;
186
+ exports.getFirstRegexGroupMatchElse = getFirstRegexGroupMatchElse;
187
+ exports.getFirstRegexGroupMatchAsIntElse = getFirstRegexGroupMatchAsIntElse;
188
+ exports.getFirstRegexGroupMatchAsFloatElse = getFirstRegexGroupMatchAsFloatElse;
189
+ exports.getFirstRegexGroupMatchElseUndefined = getFirstRegexGroupMatchElseUndefined;
190
+ exports.getFirstRegexGroupMatchAsIntElseUndefined = getFirstRegexGroupMatchAsIntElseUndefined;
191
+ exports.getFirstRegexGroupMatchAsFloatElseUndefined = getFirstRegexGroupMatchAsFloatElseUndefined;
192
+ exports.allRegexesMatched = allRegexesMatched;
193
+ exports.countOccurrences = countOccurrences;
194
+ exports.occursAtleastTimes = occursAtleastTimes;
195
+ exports.removeColorCodes = removeColorCodes;
196
+ exports.replaceAllRegexAsGlobalArray = replaceAllRegexAsGlobalArray;
197
+ exports.replaceAllRegexAsGlobal = replaceAllRegexAsGlobal;
198
+ exports.setToJSON = setToJSON;
199
+ exports.mapToJSON = mapToJSON;
200
+ exports.toJSON = toJSON;
201
+ exports.jsonToSet = jsonToSet;
202
+ exports.jsonToMap = jsonToMap;
203
+ exports.fromJSON = fromJSON;
204
+ exports.htmlAsCheerio = htmlAsCheerio;
205
+ exports.getPageCheerio = getPageCheerio;
206
+ exports.getPageHtml = getPageHtml;
207
+ exports.humanReadableJsonToHumanReadableNextLineBracketsJson = humanReadableJsonToHumanReadableNextLineBracketsJson;
208
+ exports.toJson = toJson;
209
+ exports.charToRegexOrHomoglyphs = charToRegexOrHomoglyphs;
210
+ exports.stringToRegexOrHomoglyphs = stringToRegexOrHomoglyphs;
211
+ exports.toInsanelyAccurateRegex = toInsanelyAccurateRegex;
212
+ exports.noop = noop;
213
+ exports.noop1 = noop1;
214
+ exports.noop2 = noop2;
215
+ exports.noop3 = noop3;
216
+ exports.forEachKeyValue = forEachKeyValue;
217
+ exports.keyValueToOdt = keyValueToOdt;
218
+ exports.orElse = orElse;
219
+ exports.getClosestValue = getClosestValue;
220
+ exports.getClosestNumber = getClosestNumber;
221
+ exports.convertTime = convertTime;
222
+ exports.getNs = getNs;
223
+ exports.startTimer = startTimer;
224
+ exports.getTimer = getTimer;
225
+ exports.getTimerString = getTimerString;
226
+ exports.printTimer = printTimer;
227
+ exports.isString = isString;
228
+ exports.reverseString = reverseString;
229
+ exports.wipeAllLetters = wipeAllLetters;
230
+ exports.keepOnlyAllLetters = keepOnlyAllLetters;
231
+ exports.wipeNumbers = wipeNumbers;
232
+ exports.keepOnlyNumbers = keepOnlyNumbers;
233
+ exports.wipeAllLettersAndNumbers = wipeAllLettersAndNumbers;
234
+ exports.keepOnlyAllLettersAndNumbers = keepOnlyAllLettersAndNumbers;
235
+ exports.fromArrayOrNull = fromArrayOrNull;
236
+ exports.setClipboard = setClipboard;
237
+ exports.readClipboard = readClipboard;
238
+ exports.toDDMMYYYY = toDDMMYYYY;
239
+ exports.toMMDDYYYY = toMMDDYYYY;
240
+ exports.downloadItem = downloadItem;
241
+ exports.getChild = getChild;
242
+ exports.getDynamicContentCheerio = getDynamicContentCheerio;
243
+ exports.getDynamicContent = getDynamicContent;
244
+ exports.randomTimeout = randomTimeout;
245
+ exports.randomTimeoutVerbose = randomTimeoutVerbose;
246
+ exports.getLast = getLast;
247
+ exports.getLastX = getLastX;
248
+ exports.forLastX = forLastX;
249
+ exports.joinToXCounts = joinToXCounts;
250
+ exports.asyncMap = asyncMap;
251
+ exports.emptyIfEmpty = emptyIfEmpty;
252
+ exports.getRandomWeighedItem = getRandomWeighedItem;
253
+ exports.getWeightOfKeys = getWeightOfKeys;
254
+ exports.getWeightOfValues = getWeightOfValues;
255
+ exports.getSum = getSum;
256
+ exports.getCurrentMs = getCurrentMs;
257
+ exports.getCurrentSecond = getCurrentSecond;
258
+ exports.getCurrentMinute = getCurrentMinute;
259
+ exports.getCurrentHour = getCurrentHour;
260
+ exports.getCurrentDay = getCurrentDay;
261
+ exports.reverseMap = reverseMap;
262
+ exports.toArray = toArray;
263
+ exports.sortDateOldestFirst = sortDateOldestFirst;
264
+ exports.sortDateNewestFirst = sortDateNewestFirst;
265
+ exports.dateValuesMapToSortedKeysArray = dateValuesMapToSortedKeysArray;
266
+ exports.getCount = getCount;
267
+ exports.sumStringNumberObj = sumStringNumberObj;
268
+ exports.splitWords = splitWords;
269
+ exports.filterMap = filterMap;
270
+ exports.filterMapCopy = filterMapCopy;
271
+ exports.filterSet = filterSet;
272
+ exports.filterSetCopy = filterSetCopy;
273
+ exports.prismaDeleteIfExists = prismaDeleteIfExists;
274
+ exports.getWeekSince1980 = getWeekSince1980;
275
+ exports.getDaySince1980 = getDaySince1980;
276
+ exports.runCommand = runCommand;
277
+ exports.runCommandRejectAsResolve = runCommandRejectAsResolve;
278
+ exports.sanitizeStringForFFMPEG = sanitizeStringForFFMPEG;
279
+ exports.getArtistsFromFlacMetadata = getArtistsFromFlacMetadata;
280
+ exports.getTitleFromFlacMetadata = getTitleFromFlacMetadata;
281
+ exports.getAlbumFromFlacMetadata = getAlbumFromFlacMetadata;
282
+ exports.getAlbumArtistFromFlacMetadata = getAlbumArtistFromFlacMetadata;
283
+ exports.getLyricsFromFlacVorbisTags = getLyricsFromFlacVorbisTags;
284
+ exports.generateHash = generateHash;
285
+ exports.extensionHasAudio = extensionHasAudio;
286
+ exports.songTitleExtractSide = songTitleExtractSide;
287
+ exports.sanitizeStringForSeed = sanitizeStringForSeed;
288
+ exports.addAllSetToSet = addAllSetToSet;
289
+ exports.addAllArrayToSet = addAllArrayToSet;
290
+ exports.addAllSetToArray = addAllSetToArray;
291
+ exports.addAllArrayToArray = addAllArrayToArray;
292
+ exports.addAllArrayToMap = addAllArrayToMap;
293
+ exports.addSetArrayToMap = addSetArrayToMap;
294
+ exports.joinSet = joinSet;
295
+ exports.replaceAllArray = replaceAllArray;
296
+ exports.librarySplitMultipleArtists = librarySplitMultipleArtists;
297
+ exports.libraryFindFeaturing = libraryFindFeaturing;
298
+ exports.libraryCleanUpStartAndEndOfString = libraryCleanUpStartAndEndOfString;
299
+ exports.generateWeightedItemsGridString = generateWeightedItemsGridString;
300
+ exports.promptYesOrNo = promptYesOrNo;
301
+ exports.musicFileInfoToM3uEntry = musicFileInfoToM3uEntry;
302
+ exports.toM3uEntry = toM3uEntry;
303
+ exports.getStepString = getStepString;
304
+ exports.sliceOffLastSlash = sliceOffLastSlash;
305
+ exports.sliceOffLast = sliceOffLast;
306
+ exports.sliceOffUntil = sliceOffUntil;
307
+ exports.countOccurances = countOccurances;
308
+ exports.countPathDepth = countPathDepth;
309
+ exports.getPathEscapeString = getPathEscapeString;
310
+ exports.getFullPathEscapeString = getFullPathEscapeString;
311
+ exports.jsonLookupToMap = jsonLookupToMap;
312
+ exports.extractElementFromJsonAndRemove = extractElementFromJsonAndRemove;
313
+ exports.extractLookupFromJsonAndRemove = extractLookupFromJsonAndRemove;
314
+ exports.forEachValueAndPathOfObj = forEachValueAndPathOfObj;
315
+ exports.forEachLookUpValueAndPathOfObjRecursive = forEachLookUpValueAndPathOfObjRecursive;
316
+ exports.findGeniusSongs = findGeniusSongs;
317
+ exports.trimToCharNumbersOnly = trimToCharNumbersOnly;
318
+ exports.trimStartToCharNumbersOnly = trimStartToCharNumbersOnly;
319
+ exports.trimEndToCharNumbersOnly = trimEndToCharNumbersOnly;
320
+ exports.trim = trim;
321
+ exports.trimStart = trimStart;
322
+ exports.trimEnd = trimEnd;
323
+ exports.findGeniusLyrics = findGeniusLyrics;
324
+ exports.softSliceFrom = softSliceFrom;
325
+ exports.trimFirstLinesWhileIncludes = trimFirstLinesWhileIncludes;
326
+ exports.getFirstLine = getFirstLine;
327
+ exports.skyify = skyify;
328
+ exports.dateToFilename = dateToFilename;
329
+ exports.makeMap = makeMap;
330
+ exports.makeWeightedMap = makeWeightedMap;
331
+ exports.makeWeightedTextCompMap = makeWeightedTextCompMap;
332
+ exports.generateLinesUntilCharacterLimit = generateLinesUntilCharacterLimit;
333
+ exports.lastIndexOfSeparator = lastIndexOfSeparator;
334
+ exports.timestamp = timestamp;
335
+ exports.timestampWithMs = timestampWithMs;
336
+ exports.isSilent = isSilent;
337
+ exports.waitMs = waitMs;
338
+ exports.waitS = waitS;
339
+ exports.whileFalseAsyncS = whileFalseAsyncS;
340
+ exports.whileFalseAsyncMs = whileFalseAsyncMs;
341
+ exports.repeatForAsyncS = repeatForAsyncS;
342
+ exports.repeatForAsyncMs = repeatForAsyncMs;
343
+ exports.replaceLastTerminalLine = replaceLastTerminalLine;
344
+ exports.setTerminalOutput = setTerminalOutput;
345
+ exports.clearSetTerminalOutput = clearSetTerminalOutput;
346
+ exports.clearTerminalLines = clearTerminalLines;
347
+ exports.sIfNot1 = sIfNot1;
348
+ exports.if1Else = if1Else;
349
+ exports.makePath = makePath;
350
+ exports.makeUnixPath = makeUnixPath;
351
+ exports.makeWindowsPath = makeWindowsPath;
352
+ exports.overflow = overflow;
353
+ exports.overflow0 = overflow0;
354
+ exports.isWithin = isWithin;
355
+ exports.startShiftItemsMenu = startShiftItemsMenu;
356
+ exports.getRelativeOverflow = getRelativeOverflow;
357
+ exports.shiftMenuItemsFunction = shiftMenuItemsFunction;
358
+ exports.startNumbersEditMenu = startNumbersEditMenu;
359
+ exports.startMenu = startMenu;
360
+ exports.navigationKeysToNumber = navigationKeysToNumber;
361
+ exports.editNumberByInput = editNumberByInput;
362
+ exports.toMenuString = toMenuString;
363
+ exports.toPrintString = toPrintString;
364
+ exports.print = print;
365
+ exports.softToFixed = softToFixed;
366
+ exports.extractEpisodeNumber = extractEpisodeNumber;
367
+ exports.trashSoft = trashSoft;
368
+ exports.isOfType = isOfType;
369
+ exports.subtitlesStreamInfoToString = subtitlesStreamInfoToString;
370
+ exports.extractsubtitlesStreamsInfo = extractsubtitlesStreamsInfo;
371
+ exports.tryExtractSubtitles = tryExtractSubtitles;
372
+ exports.addSubtitles = addSubtitles;
373
+ const cheerio = __importStar(require("cheerio"));
374
+ const fs_1 = require("fs");
375
+ const https_1 = require("https");
376
+ const puppeteer_1 = __importDefault(require("puppeteer"));
377
+ const structs_1 = require("../structures/structs");
378
+ const chalk_1 = __importDefault(require("chalk"));
379
+ const child_process_1 = require("child_process");
380
+ const crypto_1 = require("crypto");
381
+ const fs_2 = require("fs");
382
+ const path_1 = __importStar(require("path"));
383
+ const classes_1 = require("../types/classes");
384
+ const fields_1 = require("../types/fields");
385
+ const util_1 = require("./util");
386
+ const os_1 = require("os");
387
+ var music_metadata_1 = require("music-metadata");
388
+ Object.defineProperty(exports, "musicMetadata", { enumerable: true, get: function () { return __importDefault(music_metadata_1).default; } });
389
+ const ncp = require('node-clipboardy');
390
+ exports.chalk = chalk_1.default;
391
+ const Genius = require("genius-lyrics");
392
+ exports.geniusClient = new Genius.Client(undefined);
393
+ const readline = require('readline');
394
+ //region Functions
395
+ function toExtension(input) {
396
+ const indexOfPeriod = input.lastIndexOf(".");
397
+ return indexOfPeriod == -1 ? "" : input.substring(indexOfPeriod + 1);
398
+ }
399
+ function removeExtension(input) {
400
+ if (input[0] == ".") {
401
+ return input;
402
+ }
403
+ const indexOfPeriod = input.lastIndexOf(".");
404
+ return indexOfPeriod == -1 ? input : input.substring(0, indexOfPeriod);
405
+ }
406
+ function rtl(text, amount, emptyChar = '') {
407
+ text = text.toString();
408
+ let temp = "";
409
+ for (let i = text.length; i < amount; ++i) {
410
+ temp += emptyChar;
411
+ }
412
+ return temp + text;
413
+ }
414
+ function random(min, max) {
415
+ if (min > max) {
416
+ const temp = min;
417
+ min = max;
418
+ max = temp;
419
+ }
420
+ return (Math.floor(Math.random() * (Math.floor(max) - Math.floor(min) + 1) + Math.floor(min)));
421
+ }
422
+ function randomBoolean(chance = 0.5) {
423
+ return Math.random() < chance;
424
+ }
425
+ function randomFromArray(array) {
426
+ return array[random(0, array.length - 1)];
427
+ }
428
+ function randomFromArrayButNot(array, not) {
429
+ while (true) {
430
+ const item = array[random(0, array.length - 1)];
431
+ if (item != not) {
432
+ return item;
433
+ }
434
+ }
435
+ }
436
+ const troublesomeupsideMapdown = ["[", "]", "{", "}", "<", ">", "\\", "/", "3", "Ɛ"];
437
+ function upsideMapDown(text, reverse) {
438
+ if (!text) {
439
+ return "You forgot the text!";
440
+ }
441
+ let returnText = "";
442
+ for (var i = 0; i < text.length; ++i) {
443
+ if (reverse) {
444
+ if (fields_1.UPSIDE_MAP[text[text.length - i - 1]])
445
+ returnText += fields_1.UPSIDE_MAP[text[text.length - i - 1]];
446
+ else if (fields_1.DOWNSIDE_MAP[text[text.length - i - 1]])
447
+ returnText += fields_1.DOWNSIDE_MAP[text[text.length - i - 1]];
448
+ else
449
+ returnText += text[text.length - i - 1];
450
+ }
451
+ else {
452
+ if (fields_1.UPSIDE_MAP[text[i]] && !troublesomeupsideMapdown.includes(text[i]))
453
+ returnText += fields_1.UPSIDE_MAP[text[i]];
454
+ else if (fields_1.DOWNSIDE_MAP[text[i]] && !troublesomeupsideMapdown.includes(text[i]))
455
+ returnText += fields_1.DOWNSIDE_MAP[text[i]];
456
+ else
457
+ returnText += text[i];
458
+ }
459
+ }
460
+ return returnText;
461
+ }
462
+ //START for each file/directory
463
+ function forEachInfo(basePath, func) {
464
+ forEach(basePath, filePath => func(new structs_1.FileInfo(filePath)));
465
+ }
466
+ function forEach(basePath, func) {
467
+ //Can only iterate through a directory
468
+ if (!(0, fs_1.statSync)(basePath).isDirectory())
469
+ return;
470
+ for (const file of (0, fs_1.readdirSync)(basePath)) {
471
+ const filePath = `${basePath}/${file}`;
472
+ if (!(0, fs_1.existsSync)(filePath)) //Nani the fuck?
473
+ continue;
474
+ func(filePath);
475
+ }
476
+ }
477
+ //END for each file/directory
478
+ //START for each file
479
+ function forEachFileInfo(basePath, func) {
480
+ forEachFile(basePath, filePath => func(new structs_1.FileInfo(filePath)));
481
+ }
482
+ function forEachFile(basePath, func) {
483
+ forEach(basePath, filePath => {
484
+ if ((0, fs_1.statSync)(filePath).isDirectory())
485
+ return;
486
+ func(filePath);
487
+ });
488
+ }
489
+ //END for each file
490
+ //START for each directory
491
+ function forEachDirInfo(basePath, func) {
492
+ forEachDir(basePath, filePath => func(new structs_1.FileInfo(filePath)));
493
+ }
494
+ function forEachDir(basePath, func) {
495
+ forEach(basePath, filePath => {
496
+ if (!(0, fs_1.statSync)(filePath).isDirectory())
497
+ return;
498
+ func(filePath);
499
+ });
500
+ }
501
+ //END for each directory
502
+ //START for each file/directory recursive
503
+ function forEachInfoRecursive(basePath, func) {
504
+ forEachRecursive(basePath, filePath => func(new structs_1.FileInfo(filePath)));
505
+ }
506
+ function forEachRecursive(basePath, func) {
507
+ forEach(basePath, filePath => {
508
+ const result = func(filePath);
509
+ if (result != null && !result)
510
+ return;
511
+ forEachRecursive(filePath, func);
512
+ });
513
+ }
514
+ //END for each file/directory recursive
515
+ //START for each file recursive
516
+ function forEachFileInfoRecursive(basePath, func) {
517
+ forEachFileRecursive(basePath, filePath => func(new structs_1.FileInfo(filePath)));
518
+ }
519
+ function getEachFileInfoRecursive(basePath) {
520
+ const fileInfos = [];
521
+ forEachFileInfoRecursive(basePath, fileInfo => fileInfos.push(fileInfo));
522
+ return fileInfos;
523
+ }
524
+ function getEachFileInfo(basePath) {
525
+ const fileInfos = [];
526
+ forEachFileInfo(basePath, fileInfo => fileInfos.push(fileInfo));
527
+ return fileInfos;
528
+ }
529
+ function forEachFileRecursive(basePath, func) {
530
+ forEachRecursive(basePath, filePath => {
531
+ if (!(0, fs_1.statSync)(filePath).isDirectory())
532
+ func(filePath);
533
+ });
534
+ }
535
+ //END for each file recursive
536
+ //START for each directory recursive
537
+ function forEachDirInfoRecursive(basePath, func) {
538
+ forEachDirRecursive(basePath, filePath => func(new structs_1.FileInfo(filePath)));
539
+ }
540
+ function getEachDirInfoRecursive(basePath) {
541
+ const fileInfos = [];
542
+ forEachDirInfoRecursive(basePath, fileInfo => {
543
+ fileInfos.push(fileInfo);
544
+ return;
545
+ });
546
+ return fileInfos;
547
+ }
548
+ function forEachDirRecursive(basePath, func) {
549
+ forEachDir(basePath, filePath => {
550
+ const result = func(filePath);
551
+ if (result != null && !result)
552
+ return;
553
+ forEachDirRecursive(filePath, func);
554
+ });
555
+ }
556
+ //END for each directory recursive
557
+ function purgeEmptyDirectoriesRecursive(basePath) {
558
+ let removedDirectoriesCount = 0;
559
+ getEachDirInfoRecursive(basePath).forEach(dirInfo => {
560
+ const stat = (0, fs_1.statSync)(dirInfo.path);
561
+ if (!stat.isDirectory()) {
562
+ return;
563
+ }
564
+ const items = (0, fs_1.readdirSync)(dirInfo.path);
565
+ if (items.length > 0) {
566
+ return;
567
+ }
568
+ ++removedDirectoriesCount;
569
+ (0, fs_1.rmdirSync)(dirInfo.path);
570
+ });
571
+ return removedDirectoriesCount;
572
+ }
573
+ function firstUpperLowerRest(input) {
574
+ return input[0].toUpperCase() + input.slice(1).toLowerCase();
575
+ }
576
+ function firstUpperLowerRestEachWord(input) {
577
+ return input.split(" ")
578
+ .filter(word => word.length > 0)
579
+ .map(word => firstUpperLowerRest(word))
580
+ .join(" ");
581
+ }
582
+ function countChars(input) {
583
+ const charCount = {};
584
+ for (const char of input)
585
+ incrementObjNumber(charCount, char);
586
+ return charCount;
587
+ }
588
+ function countWords(input) {
589
+ const wordCount = {};
590
+ for (const word of input.matchAll(fields_1.WORDS_REGEX))
591
+ incrementObjNumber(wordCount, word[0]);
592
+ return wordCount;
593
+ }
594
+ function countEmoji(input) {
595
+ const emojiCount = {};
596
+ for (const match of input.matchAll(fields_1.EMOJI_REGEX)) {
597
+ incrementObjNumber(emojiCount, match[0]);
598
+ }
599
+ for (const match of input.matchAll(fields_1.CUSTOM_EMOJI_REGEX)) {
600
+ incrementObjNumber(emojiCount, match[1]);
601
+ }
602
+ return emojiCount;
603
+ }
604
+ function incrementMap(map, key, incrementBy = 1) {
605
+ var _a;
606
+ const existingValue = (_a = map.get(key)) !== null && _a !== void 0 ? _a : 0;
607
+ if (incrementBy == 0) {
608
+ return existingValue;
609
+ }
610
+ const newValue = existingValue + incrementBy;
611
+ map.set(key, newValue);
612
+ return newValue;
613
+ }
614
+ function incrementObjNumber(obj, key, incrementBy = 1) {
615
+ var _a;
616
+ const existingValue = (_a = obj[key]) !== null && _a !== void 0 ? _a : 0;
617
+ if (incrementBy == 0) {
618
+ return existingValue;
619
+ }
620
+ const newValue = existingValue + incrementBy;
621
+ obj[key] = newValue;
622
+ return newValue;
623
+ }
624
+ function addObjs(obj1, obj2) {
625
+ for (const [key, value] of Object.entries(obj2)) {
626
+ incrementObjNumber(obj1, key, value);
627
+ }
628
+ return obj1;
629
+ }
630
+ function sumValues(obj) {
631
+ let sum = 0;
632
+ for (const key of Object.keys(obj))
633
+ sum += obj[key];
634
+ return sum;
635
+ }
636
+ function getOrDefaultObj(input, key, elseValue) {
637
+ if (input[key])
638
+ return input[key];
639
+ else
640
+ return elseValue;
641
+ }
642
+ function getOrDefaultMap(input, key, elseValue) {
643
+ if (input.has(key))
644
+ return input.get(key);
645
+ else
646
+ return elseValue;
647
+ }
648
+ function getOrDefault(input, ifNull) {
649
+ return input == undefined ? ifNull : input;
650
+ }
651
+ async function runSoft(func) {
652
+ try {
653
+ await func.apply(null);
654
+ }
655
+ catch (e) {
656
+ console.log(e);
657
+ }
658
+ }
659
+ function blacklistArray(elements, blacklist = []) {
660
+ const output = [];
661
+ for (const element of elements) {
662
+ if (blacklist.includes(element))
663
+ continue;
664
+ output.push(element);
665
+ }
666
+ return output;
667
+ }
668
+ function getChars(word) {
669
+ word = word.toLowerCase();
670
+ let chars = {};
671
+ for (let i = 0; i < word.length; ++i) {
672
+ let char = word[i];
673
+ incrementObjNumber(chars, char);
674
+ }
675
+ return chars;
676
+ }
677
+ function getDiff(mAChars, mBChars) {
678
+ let diff = 0;
679
+ const merged = {};
680
+ const mAKeys = Object.keys(mAChars);
681
+ const mBKeys = Object.keys(mBChars);
682
+ mAKeys.forEach(key => {
683
+ if (merged[key]) {
684
+ merged[key] -= mAChars[key];
685
+ if (merged[key] < 0)
686
+ merged[key] = -merged[key];
687
+ }
688
+ else
689
+ merged[key] = mAChars[key];
690
+ });
691
+ mBKeys.forEach(key => {
692
+ if (merged[key]) {
693
+ merged[key] -= mBChars[key];
694
+ if (merged[key] < 0)
695
+ merged[key] = -merged[key];
696
+ }
697
+ else
698
+ merged[key] = mBChars[key];
699
+ });
700
+ Object.keys(merged).forEach(key => {
701
+ diff += merged[key];
702
+ });
703
+ return diff;
704
+ }
705
+ function formatDate(date) {
706
+ return date.toISOString().replace(/T/, ' ').replace(/\..+/, '');
707
+ }
708
+ function decide(decision) {
709
+ return decision();
710
+ }
711
+ async function decideAsync(decision) {
712
+ return await decision();
713
+ }
714
+ function make(obj, init) {
715
+ init(obj);
716
+ return obj;
717
+ }
718
+ async function makeAsync(obj, init) {
719
+ await init(obj);
720
+ return obj;
721
+ }
722
+ function extractElementsIntoArray(obj, elementKey) {
723
+ const elements = [];
724
+ for (const key of Object.keys(obj)) {
725
+ const item = obj[key];
726
+ const element = item[elementKey];
727
+ if (item[elementKey])
728
+ elements.push(element);
729
+ }
730
+ return elements;
731
+ }
732
+ function extractItemsIntoArray(obj, predicate) {
733
+ const items = [];
734
+ for (const key of Object.keys(obj)) {
735
+ const item = obj[key];
736
+ if (predicate(item))
737
+ items.push(item);
738
+ }
739
+ return items;
740
+ }
741
+ function mapArrayOfObjsByElement(obj, elementKey) {
742
+ const map = new Map;
743
+ for (const key of Object.keys(obj)) {
744
+ const item = obj[key];
745
+ if (item[elementKey])
746
+ map.set(item[elementKey], item);
747
+ }
748
+ return map;
749
+ }
750
+ function mapToArray(items, mapFunction) {
751
+ return make([], (array) => {
752
+ for (const item of items)
753
+ array.push(mapFunction(item));
754
+ });
755
+ }
756
+ function stringify(obj, ignoreEmpty = false) {
757
+ for (const key of Object.keys(obj)) {
758
+ const value = obj[key];
759
+ const isBigInt = typeof value == "bigint";
760
+ if (isBigInt)
761
+ obj[key] = parseFloat(String(value));
762
+ if (ignoreEmpty) {
763
+ if (!value)
764
+ delete obj[key];
765
+ }
766
+ }
767
+ return JSON.stringify(obj, null, "\t").replace(/: ([{\[])\n([\t]*)\t/g, ":\n$2$1\n$2\t");
768
+ }
769
+ function acronymStringIfTooLong(input, limit = 10, includeFillers = true) {
770
+ let processedInput = input.replaceAll(/['"]/g, "").replaceAll(/[^\p{L}0-9]/giu, " ").trim();
771
+ if (!includeFillers) {
772
+ processedInput = processedInput.replaceAll(fields_1.ACRONYM_REGEXES, "");
773
+ }
774
+ if (processedInput.length <= 0) {
775
+ return processedInput;
776
+ }
777
+ if (processedInput.length >= limit) {
778
+ let output = "";
779
+ for (const result of processedInput.matchAll(fields_1.ACRONYM_REGEX)) {
780
+ const match = result[0];
781
+ output += match.charAt(match.length - 1);
782
+ }
783
+ return output;
784
+ }
785
+ return input;
786
+ }
787
+ function mkdirSoftRecursive(fullPath) {
788
+ let path = "";
789
+ const local = fullPath.length > 0 && fullPath.at(0) == ".";
790
+ if (local) {
791
+ fullPath = fullPath.slice(1);
792
+ path += ".";
793
+ }
794
+ for (const dir of fullPath.split(fields_1.SEP).filter(word => word.length > 0)) {
795
+ path += `/${dir}`;
796
+ mkdirSoft(path);
797
+ }
798
+ }
799
+ function mkdirSoft(path) {
800
+ if (!(0, fs_1.existsSync)(path)) {
801
+ (0, fs_1.mkdirSync)(path);
802
+ }
803
+ }
804
+ function goUpDir(dir, times = 1) {
805
+ for (let i = 0; i < times; ++i)
806
+ dir = dir.slice(0, lastIndexOfSeparator(dir));
807
+ return dir;
808
+ }
809
+ function writeFileIfNotPresent(path, data, options) {
810
+ if (!(0, fs_1.existsSync)(path))
811
+ (0, fs_1.writeFileSync)(path, data);
812
+ }
813
+ function requireSoft(path, data, options) {
814
+ writeFileIfNotPresent(path, data);
815
+ return require(path);
816
+ }
817
+ function clone(obj) {
818
+ return Object.assign({}, obj);
819
+ }
820
+ function getBit(number, bit) {
821
+ return (number >> bit) & 1;
822
+ }
823
+ function isBit(number, bit) {
824
+ return getBit(number, bit) == 1;
825
+ }
826
+ function map(input, min1, max1, min2, max2) {
827
+ return ((input - min1) / (max1 - min1)) * (max2 - min2) + min2;
828
+ }
829
+ function logMap(input, inputStart, inputEnd, outputStart, outputEnd, curveIntensity) {
830
+ // Validate and clamp curve intensity
831
+ // curveIntensity = Math.max(-1, Math.min(1, curveIntensity || 0))
832
+ // Handle linear case (curveIntensity = 0)
833
+ if (curveIntensity === 0) {
834
+ const linearProgress = (input - inputStart) / (inputEnd - inputStart);
835
+ return outputStart + linearProgress * (outputEnd - outputStart);
836
+ }
837
+ // Normalize input to 0-1 range
838
+ const normalizedInput = (input - inputStart) / (inputEnd - inputStart);
839
+ let mappedValue;
840
+ if (curveIntensity > 0) {
841
+ // Positive curve: starts fast, ends slow (logarithmic)
842
+ const base = 1 + curveIntensity * 9; // Base between 1-10 for positive intensity
843
+ mappedValue = Math.log(1 + normalizedInput * (base - 1)) / Math.log(base);
844
+ }
845
+ else {
846
+ // Negative curve: starts slow, ends fast (exponential)
847
+ const intensity = Math.abs(curveIntensity);
848
+ const base = 1 + intensity * 9; // Base between 1-10 for negative intensity
849
+ mappedValue = (Math.pow(base, normalizedInput) - 1) / (base - 1);
850
+ }
851
+ // Map to output range
852
+ return outputStart + mappedValue * (outputEnd - outputStart);
853
+ }
854
+ function clamp(input, min, max) {
855
+ return Math.max(min, Math.min(max, input));
856
+ }
857
+ function clamp0(input, max) {
858
+ return clamp(input, 0, max);
859
+ }
860
+ /**
861
+ * @param startDate in ms
862
+ * @param endDate in ms
863
+ */
864
+ function datesDiff(dates) {
865
+ return dates.endDate.valueOf() - (dates.startDate ? dates.startDate : new Date()).valueOf();
866
+ }
867
+ function datesDiffToStamp(dates) {
868
+ return toStamp(datesDiff(dates) / 1000);
869
+ }
870
+ function datesGapToStamp(startDate, endDate) {
871
+ return toStamp((endDate.valueOf() - startDate.valueOf()) / 1000);
872
+ }
873
+ function dateToStamp(date) {
874
+ return toStamp(date.valueOf() / 1000);
875
+ }
876
+ function toStamp(toStamp) {
877
+ if (isNaN(toStamp) || toStamp == Infinity || toStamp == -Infinity) {
878
+ toStamp = 0;
879
+ }
880
+ let stamped = '';
881
+ toStamp = Math.floor(toStamp);
882
+ let negative = false;
883
+ if (toStamp < 0) {
884
+ toStamp = -toStamp;
885
+ negative = true;
886
+ }
887
+ if (Math.floor(toStamp / 3600) >= 24) {
888
+ if (Math.floor(toStamp / 3600) < 48)
889
+ stamped += `[${Math.floor(toStamp / 86400)}] day, `;
890
+ else
891
+ stamped += `[${Math.floor(toStamp / 86400)}] days, `;
892
+ }
893
+ stamped +=
894
+ '[' +
895
+ Math.floor(toStamp % 86400 / 3600) + '\:' +
896
+ (Math.floor(toStamp % 3600 / 60) > 9 ? Math.floor(toStamp % 3600 / 60) : ('0' + Math.floor(toStamp % 3600 / 60))) + '\:' +
897
+ (Math.floor(toStamp % 60) > 9 ? toStamp % 60 : '0' + toStamp % 60) +
898
+ ']';
899
+ if (negative)
900
+ return `-${stamped}`;
901
+ else
902
+ return stamped;
903
+ }
904
+ function convertNumberBase(num, fromBase, toBase) {
905
+ const decimalValue = parseInt(num, fromBase);
906
+ let convertedValue = '';
907
+ let quotient = decimalValue;
908
+ while (quotient > 0) {
909
+ const remainder = quotient % toBase;
910
+ convertedValue = remainder.toString(toBase) + convertedValue;
911
+ quotient = Math.floor(quotient / toBase);
912
+ }
913
+ return convertedValue;
914
+ }
915
+ function moveSync(oldPath, newPath) {
916
+ try {
917
+ (0, fs_1.renameSync)(oldPath, newPath);
918
+ }
919
+ catch (err) {
920
+ if (err.code == "EXDEV") {
921
+ (0, fs_1.copyFileSync)(oldPath, newPath);
922
+ (0, fs_1.unlinkSync)(oldPath);
923
+ }
924
+ }
925
+ }
926
+ async function download(url, dir) {
927
+ return new Promise((resolve, reject) => {
928
+ const file = (0, fs_1.createWriteStream)(dir);
929
+ const request = (0, https_1.get)(url, function (response) {
930
+ response.pipe(file);
931
+ resolve(`success\nurl:${url}\ndir:${dir}`);
932
+ }).on("error", reject);
933
+ });
934
+ }
935
+ function isCharUpperCase(char) {
936
+ return char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90;
937
+ }
938
+ function isCharLowerCase(char) {
939
+ return char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
940
+ }
941
+ function isStandardLetter(char) {
942
+ return isCharLowerCase(char) || isCharUpperCase(char);
943
+ }
944
+ function getOrCreateAppendedLinesFile(path) {
945
+ writeFileIfNotPresent(path, "");
946
+ return new Set((0, fs_1.readFileSync)(path, "utf8").split(/[\r\n]/));
947
+ }
948
+ function rmSoft(path) {
949
+ if ((0, fs_1.existsSync)(path)) {
950
+ (0, fs_1.rmSync)(path);
951
+ }
952
+ }
953
+ function saveAppendedLinesFile(path, lines, excludeEmpty = true, trim = true) {
954
+ rmSoft(path);
955
+ const slashIndex = lastIndexOfSeparator(path);
956
+ if (slashIndex != -1) {
957
+ const dirPath = path.slice(0, slashIndex);
958
+ mkdirSoftRecursive(dirPath);
959
+ }
960
+ for (const line of lines) {
961
+ if (excludeEmpty && line.length <= 0) {
962
+ continue;
963
+ }
964
+ (0, fs_2.appendFileSync)(path, `${trim ? line.trim() : line}\n`);
965
+ }
966
+ }
967
+ function getOrCreateFromKeys(map, keys, maker) {
968
+ for (const key of keys) {
969
+ getOrCreate(map, key, maker);
970
+ }
971
+ return map;
972
+ }
973
+ function getOrCreate(map, key, maker) {
974
+ if (!map.has(key)) {
975
+ map.set(key, maker());
976
+ }
977
+ return map.get(key);
978
+ }
979
+ function getOrCreateObj(obj, key, ifNullMaker) {
980
+ if (obj[key] == null) {
981
+ obj[key] = ifNullMaker();
982
+ }
983
+ return obj[key];
984
+ }
985
+ function appendObjArray(obj, key, item) {
986
+ let array = obj[key];
987
+ if (array == null) {
988
+ array = [];
989
+ obj[key] = array;
990
+ }
991
+ array.push(item);
992
+ return obj[key];
993
+ }
994
+ function organiseByKey(items, keyRetriever) {
995
+ const obj = {};
996
+ for (const item of items) {
997
+ appendObjArray(obj, keyRetriever(item), item);
998
+ }
999
+ return obj;
1000
+ }
1001
+ //To Nanoseconds
1002
+ function millisecondsToNanoseconds(milliseconds) {
1003
+ return milliseconds * fields_1.NANOSECONDS_IN_MILLISECOND;
1004
+ }
1005
+ function secondsToNanoseconds(nanoseconds) {
1006
+ return nanoseconds * fields_1.NANOSECONDS_IN_SECOND;
1007
+ }
1008
+ function minutesToNanoseconds(minutes) {
1009
+ return minutes * fields_1.NANOSECONDS_IN_MINUTE;
1010
+ }
1011
+ function hoursToNanoseconds(hours) {
1012
+ return hours * fields_1.NANOSECONDS_IN_HOUR;
1013
+ }
1014
+ function daysToNanoseconds(days) {
1015
+ return days * fields_1.NANOSECONDS_IN_DAY;
1016
+ }
1017
+ function weeksToNanoseconds(weeks) {
1018
+ return weeks * fields_1.NANOSECONDS_IN_WEEK;
1019
+ }
1020
+ //!To Nanoseconds
1021
+ //To Milliseconds
1022
+ function nanosecondsToMilliseconds(nanoseconds) {
1023
+ return nanoseconds / fields_1.NANOSECONDS_IN_MILLISECOND;
1024
+ }
1025
+ function secondsToMilliseconds(milliseconds) {
1026
+ return milliseconds * fields_1.MILLISECONDS_IN_SECOND;
1027
+ }
1028
+ function minutesToMilliseconds(minutes) {
1029
+ return minutes * fields_1.MILLISECONDS_IN_MINUTE;
1030
+ }
1031
+ function hoursToMilliseconds(hours) {
1032
+ return hours * fields_1.MILLISECONDS_IN_HOUR;
1033
+ }
1034
+ function daysToMilliseconds(days) {
1035
+ return days * fields_1.MILLISECONDS_IN_DAY;
1036
+ }
1037
+ function weeksToMilliseconds(weeks) {
1038
+ return weeks * fields_1.MILLISECONDS_IN_WEEK;
1039
+ }
1040
+ //!To Milliseconds
1041
+ //To Seconds
1042
+ function nanosecondsToSeconds(nanoseconds) {
1043
+ return nanoseconds / fields_1.NANOSECONDS_IN_SECOND;
1044
+ }
1045
+ function millisecondsToSeconds(milliseconds) {
1046
+ return milliseconds / fields_1.MILLISECONDS_IN_SECOND;
1047
+ }
1048
+ function minutesToSeconds(minutes) {
1049
+ return minutes * fields_1.SECONDS_IN_MINUTE;
1050
+ }
1051
+ function hoursToSeconds(hours) {
1052
+ return hours * fields_1.SECONDS_IN_HOUR;
1053
+ }
1054
+ function daysToSeconds(days) {
1055
+ return days * fields_1.SECONDS_IN_DAY;
1056
+ }
1057
+ function weeksToSeconds(weeks) {
1058
+ return weeks * fields_1.SECONDS_IN_WEEK;
1059
+ }
1060
+ //!To Seconds
1061
+ //To Minutes
1062
+ function nanosecondsToMinutes(nanoseconds) {
1063
+ return nanoseconds / fields_1.NANOSECONDS_IN_MINUTE;
1064
+ }
1065
+ function millisecondsToMinutes(milliseconds) {
1066
+ return milliseconds / fields_1.MILLISECONDS_IN_MINUTE;
1067
+ }
1068
+ function secondsToMinutes(minutes) {
1069
+ return minutes / fields_1.SECONDS_IN_MINUTE;
1070
+ }
1071
+ function hoursToMinutes(hours) {
1072
+ return hours * fields_1.MINUTES_IN_HOUR;
1073
+ }
1074
+ function daysToMinutes(days) {
1075
+ return days * fields_1.MINUTES_IN_DAY;
1076
+ }
1077
+ function weeksToMinutes(weeks) {
1078
+ return weeks * fields_1.MINUTES_IN_WEEK;
1079
+ }
1080
+ //!To Minutes
1081
+ //To Hours
1082
+ function nanosecondsToHours(nanoseconds) {
1083
+ return nanoseconds / fields_1.NANOSECONDS_IN_HOUR;
1084
+ }
1085
+ function millisecondsToHours(milliseconds) {
1086
+ return milliseconds / fields_1.MILLISECONDS_IN_HOUR;
1087
+ }
1088
+ function secondsToHours(seconds) {
1089
+ return seconds / fields_1.SECONDS_IN_HOUR;
1090
+ }
1091
+ function minutesToHours(minutes) {
1092
+ return minutes / fields_1.MINUTES_IN_HOUR;
1093
+ }
1094
+ function daysToHours(days) {
1095
+ return days * fields_1.HOURS_IN_DAY;
1096
+ }
1097
+ function weeksToHours(weeks) {
1098
+ return weeks * fields_1.HOURS_IN_WEEK;
1099
+ }
1100
+ //!To Hours
1101
+ //To Days
1102
+ function nanosecondsToDays(nanoseconds) {
1103
+ return nanoseconds / fields_1.NANOSECONDS_IN_DAY;
1104
+ }
1105
+ function millisecondsToDays(milliseconds) {
1106
+ return milliseconds / fields_1.MILLISECONDS_IN_DAY;
1107
+ }
1108
+ function secondsToDays(seconds) {
1109
+ return seconds / fields_1.SECONDS_IN_DAY;
1110
+ }
1111
+ function minutesToDays(minutes) {
1112
+ return minutes / fields_1.MINUTES_IN_DAY;
1113
+ }
1114
+ function hoursToDays(hours) {
1115
+ return hours / fields_1.HOURS_IN_DAY;
1116
+ }
1117
+ function weeksToDays(weeks) {
1118
+ return weeks * fields_1.DAYS_IN_WEEK;
1119
+ }
1120
+ //!To Days
1121
+ //To Weeks
1122
+ function nanosecondsToWeeks(nanoseconds) {
1123
+ return nanoseconds / fields_1.NANOSECONDS_IN_WEEK;
1124
+ }
1125
+ function millisecondsToWeeks(milliseconds) {
1126
+ return milliseconds / fields_1.MILLISECONDS_IN_WEEK;
1127
+ }
1128
+ function secondsToWeeks(seconds) {
1129
+ return seconds / fields_1.SECONDS_IN_WEEK;
1130
+ }
1131
+ function minutesToWeeks(minutes) {
1132
+ return minutes / fields_1.MINUTES_IN_WEEK;
1133
+ }
1134
+ function hoursToWeeks(hours) {
1135
+ return hours / fields_1.HOURS_IN_WEEK;
1136
+ }
1137
+ function daysToWeeks(days) {
1138
+ return days / fields_1.DAYS_IN_WEEK;
1139
+ }
1140
+ //!To Weeks
1141
+ function minutesToHoursMinutes(totalMinutes) {
1142
+ let minutes = Math.floor(totalMinutes % 60);
1143
+ return padLeft("" + Math.floor(totalMinutes / 60), 2, "0") + ":" + padLeft("" + minutes, 2, "0");
1144
+ }
1145
+ function parsedFileInfoNameToIntSort(a, b, ascending = true) {
1146
+ return parsedStringToIntSort(a.name, b.name, ascending);
1147
+ }
1148
+ function parsedStringToIntSort(a, b, ascending = true) {
1149
+ const valueA = parseInt(a.replaceAll(fields_1.NON_NUMBER_REGEX, ""));
1150
+ const valueB = parseInt(b.replaceAll(fields_1.NON_NUMBER_REGEX, ""));
1151
+ return ascending ? valueA - valueB : valueB - valueA;
1152
+ }
1153
+ function degreesToRadians(degrees) {
1154
+ return degrees * fields_1.DEGREES_TO_RADIANS;
1155
+ }
1156
+ function toRads(degrees) {
1157
+ return degrees * fields_1.DEGREES_TO_RADIANS;
1158
+ }
1159
+ function radiansToDegrees(radians) {
1160
+ return radians * fields_1.RADIANS_TO_DEGREES;
1161
+ }
1162
+ function toDegs(radians) {
1163
+ return radians * fields_1.RADIANS_TO_DEGREES;
1164
+ }
1165
+ function getDayMonthYearDateString() {
1166
+ const nowDate = new Date();
1167
+ const dateStr = `${nowDate.getDate()}-${nowDate.getMonth() + 1}-${nowDate.getFullYear()}`;
1168
+ return dateStr;
1169
+ }
1170
+ function touchSoft(path, defaultContent = "") {
1171
+ if (!(0, fs_1.existsSync)(path)) {
1172
+ (0, fs_1.writeFileSync)(path, defaultContent);
1173
+ }
1174
+ }
1175
+ function increment(path, amount = 1, float = false) {
1176
+ if (!(0, fs_1.existsSync)(path)) {
1177
+ (0, fs_1.writeFileSync)(path, "" + amount);
1178
+ return amount;
1179
+ }
1180
+ const parsedNumber = float ? parseFloat((0, fs_1.readFileSync)(path, "utf8")) : parseInt((0, fs_1.readFileSync)(path, "utf8"));
1181
+ const newValue = (isNaN(parsedNumber) ? 0 : parsedNumber) + amount;
1182
+ (0, fs_1.writeFileSync)(path, "" + newValue);
1183
+ return newValue;
1184
+ }
1185
+ function readFileInt(path) {
1186
+ if ((0, fs_1.existsSync)(path)) {
1187
+ return parseInt((0, fs_1.readFileSync)(path, "utf8"));
1188
+ }
1189
+ return -1;
1190
+ }
1191
+ function hashCode(str) {
1192
+ let hash = 0;
1193
+ if (str.length === 0) {
1194
+ return hash;
1195
+ }
1196
+ for (let i = 0; i < str.length; ++i) {
1197
+ const char = str.charCodeAt(i);
1198
+ hash = ((hash << 5) - hash) + char;
1199
+ hash |= 0; // Convert to 32bit integer
1200
+ }
1201
+ return hash;
1202
+ }
1203
+ function chalkColor(input, color) {
1204
+ return exports.chalk.keyword(color)(input);
1205
+ }
1206
+ function chalkRainbowColor(input, color) {
1207
+ return exports.chalk.keyword(fields_1.CHALK_RAINBOW_COLORS[Math.abs(color) % fields_1.CHALK_RAINBOW_COLORS.length])(input);
1208
+ }
1209
+ function seededChalkRainbowColor(input) {
1210
+ return exports.chalk.keyword(randomFromArray(fields_1.CHALK_RAINBOW_COLORS))(input);
1211
+ }
1212
+ function randomChalkRainbowColor(input) {
1213
+ return chalkRainbowColor(input, hashCode(input));
1214
+ }
1215
+ function padLeft(input, leftPad, padCharacter = " ") {
1216
+ const padAmount = leftPad - input.length;
1217
+ for (let i = 0; i < padAmount; ++i) {
1218
+ input = padCharacter + input;
1219
+ }
1220
+ return input;
1221
+ }
1222
+ function padRight(input, rightPad, padCharacter = " ") {
1223
+ const padAmount = rightPad - input.length;
1224
+ for (let i = 0; i < padAmount; ++i) {
1225
+ input += padCharacter;
1226
+ }
1227
+ return input;
1228
+ }
1229
+ function getCuteAscii() {
1230
+ return randomFromArray(fields_1.CUTE_ASCII);
1231
+ }
1232
+ function isEmpty(char) {
1233
+ if (char === " ") {
1234
+ return true;
1235
+ }
1236
+ return false;
1237
+ }
1238
+ function singleSpacesOnly(input, trim = true) {
1239
+ input = input.replaceAll(/[ ]{2,}/g, " ");
1240
+ if (trim) {
1241
+ input = input.trim();
1242
+ }
1243
+ return input;
1244
+ }
1245
+ function getWeekDayString(date, lang = "en-US") {
1246
+ return date.toLocaleDateString(lang, fields_1.VERBOSE_DATE_TIME_FORMAT_OPTIONS);
1247
+ }
1248
+ function getFirstRegexGroupMatchElse(input, regex, defaultValue) {
1249
+ const match = input.match(regex);
1250
+ if (match == undefined || match[1] == undefined) {
1251
+ return defaultValue;
1252
+ }
1253
+ return match[1];
1254
+ }
1255
+ function getFirstRegexGroupMatchAsIntElse(input, regex, defaultValue) {
1256
+ const match = input.match(regex);
1257
+ if (match == undefined || match[1] == undefined) {
1258
+ return defaultValue;
1259
+ }
1260
+ return parseInt(match[1]);
1261
+ }
1262
+ function getFirstRegexGroupMatchAsFloatElse(input, regex, defaultValue) {
1263
+ const match = input.match(regex);
1264
+ if (match == undefined || match[1] == undefined) {
1265
+ return defaultValue;
1266
+ }
1267
+ return parseFloat(match[1]);
1268
+ }
1269
+ function getFirstRegexGroupMatchElseUndefined(input, regex) {
1270
+ const match = input.match(regex);
1271
+ if (match == undefined || match[1] == undefined) {
1272
+ return undefined;
1273
+ }
1274
+ return match[1];
1275
+ }
1276
+ function getFirstRegexGroupMatchAsIntElseUndefined(input, regex) {
1277
+ const match = input.match(regex);
1278
+ if (match == undefined || match[1] == undefined) {
1279
+ return undefined;
1280
+ }
1281
+ return parseInt(match[1]);
1282
+ }
1283
+ function getFirstRegexGroupMatchAsFloatElseUndefined(input, regex) {
1284
+ const match = input.match(regex);
1285
+ if (match == undefined || match[1] == undefined) {
1286
+ return undefined;
1287
+ }
1288
+ return parseFloat(match[1]);
1289
+ }
1290
+ function allRegexesMatched(regexes, toMatchOn) {
1291
+ for (const regex of regexes) {
1292
+ if (toMatchOn.match(regex) == undefined) {
1293
+ return false;
1294
+ }
1295
+ }
1296
+ return true;
1297
+ }
1298
+ function countOccurrences(stringToCountFrom, stringToCountOccurenceOf) {
1299
+ let count = 0;
1300
+ let lastIndex = -1;
1301
+ while ((lastIndex = stringToCountFrom.indexOf(stringToCountOccurenceOf, lastIndex + 1)) !== -1) {
1302
+ ++count;
1303
+ }
1304
+ return count;
1305
+ }
1306
+ function occursAtleastTimes(stringToCountFrom, stringToCountOccurenceOf, requiredOccuranceCount) {
1307
+ let count = 0;
1308
+ let lastIndex = -1;
1309
+ while ((lastIndex = stringToCountFrom.indexOf(stringToCountOccurenceOf, lastIndex + 1)) !== -1) {
1310
+ ++count;
1311
+ if (count >= requiredOccuranceCount) {
1312
+ return true;
1313
+ }
1314
+ }
1315
+ return false;
1316
+ }
1317
+ function removeColorCodes(input) {
1318
+ return input.replace(fields_1.COLOR_CODE_REGEX, '');
1319
+ }
1320
+ function replaceAllRegexAsGlobalArray(input, regexes, replaceWith) {
1321
+ for (const regex of regexes) {
1322
+ input = replaceAllRegexAsGlobal(input, regex, "**$&**");
1323
+ }
1324
+ return input;
1325
+ }
1326
+ function replaceAllRegexAsGlobal(input, regex, replaceWith) {
1327
+ return input.replaceAll(new RegExp(regex.source, "g"), replaceWith);
1328
+ }
1329
+ function setToJSON(set) {
1330
+ const array = [];
1331
+ set.forEach((value) => {
1332
+ if (value instanceof Set) {
1333
+ array.push(setToJSON(value));
1334
+ }
1335
+ else if (value instanceof Map) {
1336
+ array.push(mapToJSON(value));
1337
+ }
1338
+ else {
1339
+ array.push(value);
1340
+ }
1341
+ });
1342
+ return array;
1343
+ }
1344
+ function mapToJSON(map) {
1345
+ const obj = {};
1346
+ map.forEach((value, key) => {
1347
+ if (value instanceof Set) {
1348
+ obj[key] = setToJSON(value);
1349
+ }
1350
+ else if (value instanceof Map) {
1351
+ obj[key] = mapToJSON(value);
1352
+ }
1353
+ else {
1354
+ obj[key] = value;
1355
+ }
1356
+ });
1357
+ return obj;
1358
+ }
1359
+ function toJSON(input) {
1360
+ if (input instanceof Set) {
1361
+ return setToJSON(input);
1362
+ }
1363
+ else if (input instanceof Map) {
1364
+ return mapToJSON(input);
1365
+ }
1366
+ else {
1367
+ throw new Error('Input must be a Set or Map');
1368
+ }
1369
+ }
1370
+ function jsonToSet(jsonArray) {
1371
+ const set = new Set();
1372
+ jsonArray.forEach((item) => {
1373
+ if (Array.isArray(item)) {
1374
+ set.add(jsonToSet(item));
1375
+ }
1376
+ else if (typeof item === 'object') {
1377
+ set.add(jsonToMap(item));
1378
+ }
1379
+ else {
1380
+ set.add(item);
1381
+ }
1382
+ });
1383
+ return set;
1384
+ }
1385
+ function jsonToMap(jsonObject) {
1386
+ const map = new Map();
1387
+ Object.keys(jsonObject).forEach((key) => {
1388
+ const value = jsonObject[key];
1389
+ if (Array.isArray(value)) {
1390
+ map.set(key, jsonToSet(value));
1391
+ }
1392
+ else if (typeof value === 'object') {
1393
+ map.set(key, jsonToMap(value));
1394
+ }
1395
+ else {
1396
+ map.set(key, value);
1397
+ }
1398
+ });
1399
+ return map;
1400
+ }
1401
+ function fromJSON(json) {
1402
+ if (Array.isArray(json)) {
1403
+ return jsonToSet(json);
1404
+ }
1405
+ else if (typeof json === 'object') {
1406
+ return jsonToMap(json);
1407
+ }
1408
+ else {
1409
+ throw new Error('JSON must be an array or object');
1410
+ }
1411
+ }
1412
+ function htmlAsCheerio(html) {
1413
+ return cheerio.load(html);
1414
+ }
1415
+ async function getPageCheerio(url, options = fields_1.DEFAULT_HTTPS_CONNECTION_OPTIONS) {
1416
+ return htmlAsCheerio(await getPageHtml(url, options));
1417
+ }
1418
+ async function getPageHtml(url, options = fields_1.DEFAULT_HTTPS_CONNECTION_OPTIONS) {
1419
+ return new Promise((resolve, reject) => {
1420
+ (0, https_1.get)(url, options, (response) => {
1421
+ let data = '';
1422
+ response.on('data', (chunk) => {
1423
+ data += chunk;
1424
+ });
1425
+ response.on('end', () => {
1426
+ resolve(data);
1427
+ });
1428
+ }).on('error', (error) => {
1429
+ console.error(`Error making the request: ${error.message}`);
1430
+ resolve("");
1431
+ });
1432
+ });
1433
+ }
1434
+ function humanReadableJsonToHumanReadableNextLineBracketsJson(json) {
1435
+ return json.replaceAll(fields_1.JSON_NEXT_LINE_BRACKET_FROM_REGEX, fields_1.JSON_NEXT_LINE_BRACKET_TO);
1436
+ }
1437
+ /**
1438
+ * @returns Stringified JSON version of the object in Human Readable, Next Line Bracket string.
1439
+ */
1440
+ function toJson(obj) {
1441
+ return humanReadableJsonToHumanReadableNextLineBracketsJson(JSON.stringify(obj, null, "\t"));
1442
+ }
1443
+ function charToRegexOrHomoglyphs(char) {
1444
+ const homoglyphRegexpOr = fields_1.HOMOGLYPHS_AS_REGEXP_OR[char];
1445
+ if (homoglyphRegexpOr == undefined) {
1446
+ return char;
1447
+ }
1448
+ else {
1449
+ return homoglyphRegexpOr;
1450
+ }
1451
+ }
1452
+ function stringToRegexOrHomoglyphs(text, suffix = "+") {
1453
+ let output = "";
1454
+ let lastChar = "";
1455
+ const groupChars = suffix == "+" || suffix == "*";
1456
+ const textLength = text.length;
1457
+ for (let i = 0; i < textLength; ++i) {
1458
+ const char = text[i];
1459
+ const nextChar = text[i + 1];
1460
+ const nextCharSpecial = nextChar == "+" || nextChar == "*" || nextChar == "?";
1461
+ if (char == "+" || char == "*" || char == "?") {
1462
+ output += char;
1463
+ continue;
1464
+ }
1465
+ if (groupChars) {
1466
+ if (char == lastChar) {
1467
+ continue;
1468
+ }
1469
+ }
1470
+ output += charToRegexOrHomoglyphs(char);
1471
+ if (!nextCharSpecial) {
1472
+ output += suffix;
1473
+ }
1474
+ lastChar = char;
1475
+ }
1476
+ return output;
1477
+ }
1478
+ function toInsanelyAccurateRegex(regex, flags = "i") {
1479
+ return new RegExp(stringToRegexOrHomoglyphs(regex, "+"));
1480
+ }
1481
+ function noop() { }
1482
+ function noop1(arg1) { }
1483
+ function noop2(arg1, arg2) { }
1484
+ function noop3(arg1, arg2, arg3) { }
1485
+ function forEachKeyValue(obj, consumer) {
1486
+ for (const key of Object.keys(obj)) {
1487
+ consumer(obj[key], key);
1488
+ }
1489
+ }
1490
+ function keyValueToOdt(obj) {
1491
+ let output = "";
1492
+ forEachKeyValue(obj, (value, key) => {
1493
+ output += `${key}\t${value}\n`;
1494
+ });
1495
+ return output;
1496
+ }
1497
+ function orElse(item, orElse) {
1498
+ if (item == null) {
1499
+ return orElse();
1500
+ }
1501
+ return item;
1502
+ }
1503
+ function getClosestValue(map, input) {
1504
+ const closestKey = getClosestNumber(input, Array.from(map.keys()).sort());
1505
+ return map.get(closestKey);
1506
+ }
1507
+ function getClosestNumber(input, options) {
1508
+ if (options.length <= 0) {
1509
+ return input;
1510
+ }
1511
+ let value;
1512
+ let gap;
1513
+ let best = -1;
1514
+ let bestGap = Number.MAX_VALUE;
1515
+ for (let i = 0; i < options.length; ++i) {
1516
+ value = options[i];
1517
+ gap = Math.abs(input - value);
1518
+ if (gap == 0) {
1519
+ return value;
1520
+ }
1521
+ if (gap < bestGap) {
1522
+ bestGap = gap;
1523
+ best = value;
1524
+ }
1525
+ }
1526
+ return best;
1527
+ }
1528
+ const TIME_CONVERSION_TYPES = [
1529
+ "ns_to_ms",
1530
+ "ns_to_s",
1531
+ "ns_to_m",
1532
+ "ns_to_h",
1533
+ "ns_to_d",
1534
+ "ns_to_w",
1535
+ "ms_to_ns",
1536
+ "ms_to_s",
1537
+ "ms_to_m",
1538
+ "ms_to_h",
1539
+ "ms_to_d",
1540
+ "ms_to_w",
1541
+ "s_to_ns",
1542
+ "s_to_ms",
1543
+ "s_to_m",
1544
+ "s_to_h",
1545
+ "s_to_d",
1546
+ "s_to_w",
1547
+ "m_to_ns",
1548
+ "m_to_ms",
1549
+ "m_to_s",
1550
+ "m_to_h",
1551
+ "m_to_d",
1552
+ "m_to_w",
1553
+ "h_to_ns",
1554
+ "h_to_ms",
1555
+ "h_to_s",
1556
+ "h_to_m",
1557
+ "h_to_d",
1558
+ "h_to_w",
1559
+ "d_to_ns",
1560
+ "d_to_ms",
1561
+ "d_to_s",
1562
+ "d_to_m",
1563
+ "d_to_h",
1564
+ "d_to_w",
1565
+ "w_to_ns",
1566
+ "w_to_ms",
1567
+ "w_to_s",
1568
+ "w_to_m",
1569
+ "w_to_h",
1570
+ "w_to_d",
1571
+ ];
1572
+ //~~~~~From~~~~~
1573
+ const NANOSECOND_CONVERSION_TYPES = [
1574
+ "ns_to_ms",
1575
+ "ns_to_s",
1576
+ "ns_to_m",
1577
+ "ns_to_h",
1578
+ "ns_to_d",
1579
+ "ns_to_w",
1580
+ ];
1581
+ const MILLISECOND_CONVERSION_TYPES = [
1582
+ "ms_to_ms",
1583
+ "ms_to_s",
1584
+ "ms_to_m",
1585
+ "ms_to_h",
1586
+ "ms_to_d",
1587
+ "ms_to_w",
1588
+ ];
1589
+ const SECOND_CONVERSION_TYPES = [
1590
+ "s_to_ms",
1591
+ "s_to_s",
1592
+ "s_to_m",
1593
+ "s_to_h",
1594
+ "s_to_d",
1595
+ "s_to_w",
1596
+ ];
1597
+ const MINUTE_CONVERSION_TYPES = [
1598
+ "m_to_ms",
1599
+ "m_to_s",
1600
+ "m_to_m",
1601
+ "m_to_h",
1602
+ "m_to_d",
1603
+ "m_to_w",
1604
+ ];
1605
+ const HOUR_CONVERSION_TYPES = [
1606
+ "h_to_ms",
1607
+ "h_to_s",
1608
+ "h_to_m",
1609
+ "h_to_h",
1610
+ "h_to_d",
1611
+ "h_to_w",
1612
+ ];
1613
+ const DAY_CONVERSION_TYPES = [
1614
+ "d_to_ms",
1615
+ "d_to_s",
1616
+ "d_to_m",
1617
+ "d_to_h",
1618
+ "d_to_d",
1619
+ "d_to_w",
1620
+ ];
1621
+ const WEEK_CONVERSION_TYPES = [
1622
+ "w_to_ms",
1623
+ "w_to_s",
1624
+ "w_to_m",
1625
+ "w_to_h",
1626
+ "w_to_d",
1627
+ "w_to_w",
1628
+ ];
1629
+ //!~~~~~From~~~~~
1630
+ //~~~~~To~~~~~
1631
+ const TO_NANOSECOND_CONVERSION_TYPES = [
1632
+ "ms_to_ns",
1633
+ "s_to_ns",
1634
+ "m_to_ns",
1635
+ "h_to_ns",
1636
+ "d_to_ns",
1637
+ "w_to_ns",
1638
+ ];
1639
+ const TO_MILLISECOND_CONVERSION_TYPES = [
1640
+ "ms_to_ms",
1641
+ "s_to_ms",
1642
+ "m_to_ms",
1643
+ "h_to_ms",
1644
+ "d_to_ms",
1645
+ "w_to_ms",
1646
+ ];
1647
+ const TO_SECOND_CONVERSION_TYPES = [
1648
+ "ms_to_s",
1649
+ "s_to_s",
1650
+ "m_to_s",
1651
+ "h_to_s",
1652
+ "d_to_s",
1653
+ "w_to_s",
1654
+ ];
1655
+ const TO_MINUTE_CONVERSION_TYPES = [
1656
+ "ms_to_m",
1657
+ "s_to_m",
1658
+ "m_to_m",
1659
+ "h_to_m",
1660
+ "d_to_m",
1661
+ "w_to_m",
1662
+ ];
1663
+ const TO_HOUR_CONVERSION_TYPES = [
1664
+ "ms_to_h",
1665
+ "s_to_h",
1666
+ "m_to_h",
1667
+ "h_to_h",
1668
+ "d_to_h",
1669
+ "w_to_h",
1670
+ ];
1671
+ const TO_DAY_CONVERSION_TYPES = [
1672
+ "ms_to_d",
1673
+ "s_to_d",
1674
+ "m_to_d",
1675
+ "h_to_d",
1676
+ "d_to_d",
1677
+ "w_to_d",
1678
+ ];
1679
+ const TO_WEEK_CONVERSION_TYPES = [
1680
+ "ms_to_w",
1681
+ "s_to_w",
1682
+ "m_to_w",
1683
+ "h_to_w",
1684
+ "d_to_w",
1685
+ "w_to_w",
1686
+ ];
1687
+ //!~~~~~To~~~~~
1688
+ function convertTime(input, type) {
1689
+ switch (type) {
1690
+ case "ns_to_s":
1691
+ return nanosecondsToSeconds(input);
1692
+ case "ns_to_ms":
1693
+ return nanosecondsToMilliseconds(input);
1694
+ case "ns_to_m":
1695
+ return nanosecondsToMinutes(input);
1696
+ case "ns_to_h":
1697
+ return nanosecondsToHours(input);
1698
+ case "ns_to_d":
1699
+ return nanosecondsToDays(input);
1700
+ case "ns_to_w":
1701
+ return nanosecondsToWeeks(input);
1702
+ case "ms_to_ns":
1703
+ return millisecondsToNanoseconds(input);
1704
+ case "ms_to_s":
1705
+ return millisecondsToSeconds(input);
1706
+ case "ms_to_m":
1707
+ return millisecondsToMinutes(input);
1708
+ case "ms_to_h":
1709
+ return millisecondsToHours(input);
1710
+ case "ms_to_d":
1711
+ return millisecondsToDays(input);
1712
+ case "ms_to_w":
1713
+ return millisecondsToWeeks(input);
1714
+ case "s_to_ns":
1715
+ return secondsToNanoseconds(input);
1716
+ case "s_to_ms":
1717
+ return secondsToMilliseconds(input);
1718
+ case "s_to_m":
1719
+ return secondsToMinutes(input);
1720
+ case "s_to_h":
1721
+ return secondsToHours(input);
1722
+ case "s_to_d":
1723
+ return secondsToDays(input);
1724
+ case "s_to_w":
1725
+ return secondsToWeeks(input);
1726
+ case "m_to_ns":
1727
+ return minutesToNanoseconds(input);
1728
+ case "m_to_ms":
1729
+ return minutesToMilliseconds(input);
1730
+ case "m_to_s":
1731
+ return minutesToSeconds(input);
1732
+ case "m_to_h":
1733
+ return minutesToHours(input);
1734
+ case "m_to_d":
1735
+ return minutesToDays(input);
1736
+ case "m_to_w":
1737
+ return minutesToWeeks(input);
1738
+ case "h_to_ns":
1739
+ return hoursToNanoseconds(input);
1740
+ case "h_to_ms":
1741
+ return hoursToMilliseconds(input);
1742
+ case "h_to_s":
1743
+ return hoursToSeconds(input);
1744
+ case "h_to_m":
1745
+ return hoursToMinutes(input);
1746
+ case "h_to_d":
1747
+ return hoursToDays(input);
1748
+ case "h_to_w":
1749
+ return hoursToWeeks(input);
1750
+ case "d_to_ns":
1751
+ return daysToNanoseconds(input);
1752
+ case "d_to_ms":
1753
+ return daysToMilliseconds(input);
1754
+ case "d_to_s":
1755
+ return daysToSeconds(input);
1756
+ case "d_to_m":
1757
+ return daysToMinutes(input);
1758
+ case "d_to_h":
1759
+ return daysToHours(input);
1760
+ case "d_to_w":
1761
+ return daysToWeeks(input);
1762
+ case "w_to_ns":
1763
+ return weeksToNanoseconds(input);
1764
+ case "w_to_ms":
1765
+ return weeksToMilliseconds(input);
1766
+ case "w_to_s":
1767
+ return weeksToSeconds(input);
1768
+ case "w_to_m":
1769
+ return weeksToMinutes(input);
1770
+ case "w_to_h":
1771
+ return weeksToHours(input);
1772
+ case "w_to_d":
1773
+ return weeksToDays(input);
1774
+ }
1775
+ }
1776
+ exports.ZERO_BIG_INT = BigInt(0);
1777
+ const getZero = () => 0;
1778
+ exports.getZero = getZero;
1779
+ const getZeroBigInt = () => exports.ZERO_BIG_INT;
1780
+ exports.getZeroBigInt = getZeroBigInt;
1781
+ const timeTrackers = new Map();
1782
+ function getNs() {
1783
+ return process.hrtime.bigint();
1784
+ }
1785
+ function startTimer(key) {
1786
+ timeTrackers.set(key, getNs());
1787
+ }
1788
+ function getTimer(key) {
1789
+ return orElse(timeTrackers.get(key), exports.getZeroBigInt);
1790
+ }
1791
+ function getTimerString(key, format = "ns_to_s") {
1792
+ return `${key}: ${convertTime(Number(getTimer(key)), format)}`;
1793
+ }
1794
+ function printTimer(key, format = "ns_to_s") {
1795
+ console.log(getTimerString(key, format));
1796
+ }
1797
+ function isString(input) {
1798
+ return typeof input === 'string' || input instanceof String;
1799
+ }
1800
+ function reverseString(str) {
1801
+ return str.split('').reverse().join('');
1802
+ }
1803
+ function wipeAllLetters(input) {
1804
+ return input.replaceAll(fields_1.UNICODE_LETTERS_REGEX, "");
1805
+ }
1806
+ function keepOnlyAllLetters(input) {
1807
+ return input.replaceAll(fields_1.NOT_UNICODE_LETTERS_REGEX, "");
1808
+ }
1809
+ function wipeNumbers(input) {
1810
+ return input.replaceAll(fields_1.NUMBER_REGEX, "");
1811
+ }
1812
+ function keepOnlyNumbers(input) {
1813
+ return input.replaceAll(fields_1.NON_NUMBER_REGEX, "");
1814
+ }
1815
+ function wipeAllLettersAndNumbers(input) {
1816
+ return wipeAllLetters(wipeNumbers(input));
1817
+ }
1818
+ function keepOnlyAllLettersAndNumbers(input) {
1819
+ return keepOnlyAllLetters(keepOnlyNumbers(input));
1820
+ }
1821
+ function fromArrayOrNull(array, index) {
1822
+ if (index >= 0 && index < array.length) {
1823
+ return array[index];
1824
+ }
1825
+ return null;
1826
+ }
1827
+ function setClipboard(text) {
1828
+ ncp.writeSync(text);
1829
+ }
1830
+ function readClipboard() {
1831
+ return ncp.readSync();
1832
+ }
1833
+ function toDDMMYYYY(date = null) {
1834
+ if (date == null) {
1835
+ date = new Date();
1836
+ }
1837
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
1838
+ const day = date.getDate().toString().padStart(2, '0');
1839
+ const year = date.getFullYear().toString();
1840
+ return `${day}-${month}-${year}`;
1841
+ }
1842
+ function toMMDDYYYY(date = null) {
1843
+ if (date == null) {
1844
+ date = new Date();
1845
+ }
1846
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
1847
+ const day = date.getDate().toString().padStart(2, '0');
1848
+ const year = date.getFullYear().toString();
1849
+ return `${month}-${day}-${year}`;
1850
+ }
1851
+ async function downloadItem(url, destination) {
1852
+ const tempDestination = `${destination}_TEMP`;
1853
+ if ((0, fs_1.existsSync)(tempDestination)) {
1854
+ (0, fs_1.unlinkSync)(tempDestination);
1855
+ }
1856
+ return new Promise(resolve => {
1857
+ const file = (0, fs_1.createWriteStream)(tempDestination);
1858
+ (0, https_1.get)(url, (response) => {
1859
+ response.pipe(file);
1860
+ file.on('finish', () => {
1861
+ file.close();
1862
+ if ((0, fs_1.existsSync)(destination)) {
1863
+ (0, fs_1.unlinkSync)(destination);
1864
+ }
1865
+ if ((0, fs_1.existsSync)(tempDestination)) {
1866
+ (0, fs_1.renameSync)(tempDestination, destination);
1867
+ const stat = (0, fs_1.statSync)(destination);
1868
+ if (stat.size <= 0) {
1869
+ console.log(`low size: ${stat.size}`);
1870
+ resolve(false);
1871
+ return;
1872
+ }
1873
+ resolve(true);
1874
+ }
1875
+ else {
1876
+ resolve(false);
1877
+ }
1878
+ });
1879
+ }).on('error', (err) => {
1880
+ console.log(`Failed download ${destination}`);
1881
+ if ((0, fs_1.existsSync)(tempDestination)) {
1882
+ (0, fs_1.unlinkSync)(tempDestination);
1883
+ }
1884
+ resolve(false);
1885
+ });
1886
+ });
1887
+ }
1888
+ function getChild(element, childIndex = 0) {
1889
+ if (element.children.length <= childIndex) {
1890
+ return element.children[element.children.length - 1];
1891
+ }
1892
+ return element.children[childIndex];
1893
+ }
1894
+ async function getDynamicContentCheerio(url, options) {
1895
+ const html = await getDynamicContent(url, options);
1896
+ return cheerio.load(html);
1897
+ }
1898
+ async function getDynamicContent(url, options) {
1899
+ const browser = await puppeteer_1.default.launch();
1900
+ const page = await browser.newPage();
1901
+ try {
1902
+ await page.goto(url, options);
1903
+ const content = await page.content();
1904
+ return content;
1905
+ }
1906
+ catch (error) {
1907
+ console.error('Error retrieving dynamic content:', error);
1908
+ return '';
1909
+ }
1910
+ finally {
1911
+ await browser.close();
1912
+ }
1913
+ }
1914
+ async function randomTimeout(minMs = 1523, maxMs = 3251) {
1915
+ return await new Promise(resolve => setTimeout(resolve, random(minMs, maxMs)));
1916
+ }
1917
+ async function randomTimeoutVerbose(minMs, maxMs, timeoutGapMs = 1523) {
1918
+ const waitingForMs = random(minMs, maxMs);
1919
+ let waitedFor = 0;
1920
+ let waitFor = clamp(waitingForMs - waitedFor, 0, timeoutGapMs);
1921
+ while (waitedFor < waitingForMs) {
1922
+ console.log(`Waiting for ${exports.chalk.magentaBright(waitingForMs - waitedFor) + "ms"}...`);
1923
+ await new Promise(resolve => setTimeout(resolve, waitFor));
1924
+ waitedFor += timeoutGapMs;
1925
+ waitFor = clamp(waitingForMs - waitedFor, 0, timeoutGapMs);
1926
+ }
1927
+ return await new Promise(resolve => setTimeout(resolve, waitFor));
1928
+ }
1929
+ function getLast(items) {
1930
+ if (items.length <= 0) {
1931
+ return undefined;
1932
+ }
1933
+ return items[items.length - 1];
1934
+ }
1935
+ function getLastX(items, lastCount) {
1936
+ const startIndex = Math.max(0, items.length - lastCount);
1937
+ return items.slice(startIndex);
1938
+ }
1939
+ function forLastX(items, lastCount, consumer) {
1940
+ const itemsLength = items.length;
1941
+ const startIndex = Math.max(0, itemsLength - lastCount);
1942
+ for (let i = startIndex; i < itemsLength; ++i) {
1943
+ consumer(items[i]);
1944
+ }
1945
+ }
1946
+ function joinToXCounts(items, maxCount, joinWith = "\n") {
1947
+ const output = [];
1948
+ let msg = "";
1949
+ let count = 0;
1950
+ for (const item of items) {
1951
+ if (++count > maxCount) {
1952
+ count = 1;
1953
+ output.push(msg);
1954
+ msg = "";
1955
+ }
1956
+ msg += `${item}${joinWith}`;
1957
+ }
1958
+ if (msg.length > 0) {
1959
+ output.push(msg);
1960
+ }
1961
+ return output;
1962
+ }
1963
+ async function asyncMap(items, mapper) {
1964
+ const output = [];
1965
+ for (const item of items) {
1966
+ output.push(await mapper(item));
1967
+ }
1968
+ return output;
1969
+ }
1970
+ function emptyIfEmpty(text) {
1971
+ return text.trim().length == 0 ? fields_1.EMPTY : text.trim();
1972
+ }
1973
+ function getRandomWeighedItem(map, total = getWeightOfValues(map)) {
1974
+ let rand = Math.random() * total;
1975
+ let item = null;
1976
+ for (const [key, value] of map.entries()) {
1977
+ item = key;
1978
+ if (rand <= value) {
1979
+ break;
1980
+ }
1981
+ rand -= value;
1982
+ }
1983
+ return item;
1984
+ }
1985
+ function getWeightOfKeys(map) {
1986
+ return getSum(map.keys());
1987
+ }
1988
+ function getWeightOfValues(map) {
1989
+ return getSum(map.values());
1990
+ }
1991
+ function getSum(numbers) {
1992
+ let sum = 0;
1993
+ for (const number of numbers) {
1994
+ sum += number;
1995
+ }
1996
+ return sum;
1997
+ }
1998
+ function getCurrentMs() {
1999
+ return Date.now();
2000
+ }
2001
+ function getCurrentSecond() {
2002
+ return millisecondsToSeconds(getCurrentMs());
2003
+ }
2004
+ function getCurrentMinute() {
2005
+ return millisecondsToMinutes(getCurrentMs());
2006
+ }
2007
+ function getCurrentHour() {
2008
+ return millisecondsToHours(getCurrentMs());
2009
+ }
2010
+ function getCurrentDay() {
2011
+ return millisecondsToDays(getCurrentMs());
2012
+ }
2013
+ function reverseMap(map) {
2014
+ const reversedMap = new Map();
2015
+ for (const [key, value] of map.entries()) {
2016
+ reversedMap.set(value, key);
2017
+ }
2018
+ return reversedMap;
2019
+ }
2020
+ function toArray(iterator) {
2021
+ const array = [];
2022
+ let result = iterator.next();
2023
+ while (!result.done) {
2024
+ array.push(result.value);
2025
+ result = iterator.next();
2026
+ }
2027
+ return array;
2028
+ }
2029
+ function sortDateOldestFirst(a, b) {
2030
+ return a.getTime() - b.getTime();
2031
+ }
2032
+ function sortDateNewestFirst(a, b) {
2033
+ return b.getTime() - a.getTime();
2034
+ }
2035
+ function dateValuesMapToSortedKeysArray(map, newestFirst) {
2036
+ const sortedKeys = [];
2037
+ const reversedMap = reverseMap(map);
2038
+ const sortedDates = toArray(map.values());
2039
+ sortedDates.sort(newestFirst ? sortDateNewestFirst : sortDateOldestFirst);
2040
+ for (const date of sortedDates) {
2041
+ sortedKeys.push(reversedMap.get(date));
2042
+ }
2043
+ return sortedKeys;
2044
+ }
2045
+ function getCount(iterable) {
2046
+ let count = 0;
2047
+ for (const item of iterable) {
2048
+ ++count;
2049
+ }
2050
+ return count;
2051
+ }
2052
+ function sumStringNumberObj(obj) {
2053
+ let sum = 0;
2054
+ for (const [key, value] of Object.entries(obj)) {
2055
+ sum += value;
2056
+ }
2057
+ return sum;
2058
+ }
2059
+ function splitWords(input) {
2060
+ return input.split(/[ \r\n]/).filter(word => word.length > 0);
2061
+ }
2062
+ function filterMap(map, filter) {
2063
+ for (const [key, value] of map.entries()) {
2064
+ if (!filter(key, value)) {
2065
+ map.delete(key);
2066
+ }
2067
+ }
2068
+ }
2069
+ function filterMapCopy(map, filter) {
2070
+ const newMap = new Map();
2071
+ for (const [key, value] of map.entries()) {
2072
+ if (filter(key, value)) {
2073
+ newMap.set(key, value);
2074
+ }
2075
+ }
2076
+ return newMap;
2077
+ }
2078
+ function filterSet(set, filter) {
2079
+ for (const item of set) {
2080
+ if (!filter(item)) {
2081
+ set.delete(item);
2082
+ }
2083
+ }
2084
+ }
2085
+ function filterSetCopy(set, filter) {
2086
+ const newSet = new Set();
2087
+ for (const item of set) {
2088
+ if (!filter(item)) {
2089
+ newSet.add(item);
2090
+ }
2091
+ }
2092
+ return newSet;
2093
+ }
2094
+ async function prismaDeleteIfExists(db, where) {
2095
+ const item = await db.findFirst({ where });
2096
+ if (item == null) {
2097
+ return false;
2098
+ }
2099
+ await db.delete({ where });
2100
+ return true;
2101
+ }
2102
+ function getWeekSince1980() {
2103
+ return Math.floor(millisecondsToWeeks(Date.now()));
2104
+ }
2105
+ function getDaySince1980() {
2106
+ return Math.floor(millisecondsToDays(Date.now()));
2107
+ }
2108
+ async function runCommand(command, as_user) {
2109
+ return new Promise((resolve, reject) => {
2110
+ if (as_user != null) {
2111
+ command = `sudo -u ${as_user} sh -c '${command}'`;
2112
+ }
2113
+ (0, child_process_1.exec)(command, (error, stdout, stderr) => {
2114
+ if (error) {
2115
+ reject(stderr || error.message || error);
2116
+ }
2117
+ else {
2118
+ resolve(stdout);
2119
+ }
2120
+ });
2121
+ });
2122
+ }
2123
+ async function runCommandRejectAsResolve(command, as_user) {
2124
+ try {
2125
+ return await runCommand(command, as_user);
2126
+ }
2127
+ catch (error) {
2128
+ return String(error);
2129
+ }
2130
+ }
2131
+ function sanitizeStringForFFMPEG(input) {
2132
+ return input.replaceAll(/([$!"`])/g, "\\$1");
2133
+ }
2134
+ function getArtistsFromFlacMetadata(tags, aliases = classes_1.MUSIC_ALIASES) {
2135
+ const artists = new Set;
2136
+ if (tags.common != null) {
2137
+ if (tags.common.artists != null) {
2138
+ for (let allegedArtist of tags.common.artists) {
2139
+ allegedArtist = aliases.get(singleSpacesOnly(allegedArtist).trim());
2140
+ for (const artist of librarySplitMultipleArtists(allegedArtist, aliases)) {
2141
+ artists.add(artist);
2142
+ }
2143
+ }
2144
+ }
2145
+ if (tags.common.artist != null) {
2146
+ const allegedArtist = aliases.get(singleSpacesOnly(tags.common.artist).trim());
2147
+ for (const artist of librarySplitMultipleArtists(allegedArtist, aliases)) {
2148
+ artists.add(artist);
2149
+ }
2150
+ }
2151
+ if (artists.size == 0) {
2152
+ if (tags.common.albumartist != null) {
2153
+ const allegedArtist = aliases.get(singleSpacesOnly(tags.common.albumartist).trim());
2154
+ for (const artist of librarySplitMultipleArtists(allegedArtist, aliases)) {
2155
+ artists.add(artist);
2156
+ }
2157
+ }
2158
+ }
2159
+ }
2160
+ return artists;
2161
+ }
2162
+ function getTitleFromFlacMetadata(tags) {
2163
+ var _a;
2164
+ return (_a = tags.common.title) !== null && _a !== void 0 ? _a : "";
2165
+ }
2166
+ function getAlbumFromFlacMetadata(tags) {
2167
+ var _a;
2168
+ return (_a = tags.common.album) !== null && _a !== void 0 ? _a : "";
2169
+ }
2170
+ function getAlbumArtistFromFlacMetadata(tags) {
2171
+ var _a;
2172
+ return (_a = tags.common.albumartist) !== null && _a !== void 0 ? _a : "";
2173
+ }
2174
+ function getLyricsFromFlacVorbisTags(vorbisTags) {
2175
+ let lyrics = vorbisTags[fields_1.UNSYNCEDLYRICS_FLAC_ID];
2176
+ if (lyrics == null) {
2177
+ return "";
2178
+ }
2179
+ return lyrics.trim();
2180
+ }
2181
+ function generateHash(seed) {
2182
+ const hash = (0, crypto_1.createHash)('sha256');
2183
+ hash.update(seed);
2184
+ return hash.digest('hex');
2185
+ }
2186
+ function extensionHasAudio(extension) {
2187
+ return fields_1.AUDIO_CONTAINING_EXTENSION_TYPES.has(extension);
2188
+ }
2189
+ function songTitleExtractSide(input, doSides, side) {
2190
+ let output = input;
2191
+ if (doSides) {
2192
+ const indexOfDash = output.lastIndexOf(" - ");
2193
+ if (indexOfDash != -1) {
2194
+ if (side) {
2195
+ output = output.slice(indexOfDash + 3);
2196
+ }
2197
+ else {
2198
+ output = output.slice(0, indexOfDash);
2199
+ }
2200
+ }
2201
+ }
2202
+ while (output.includes(" ")) {
2203
+ output = output.replaceAll(" ", " ");
2204
+ }
2205
+ output = output.trim();
2206
+ return output;
2207
+ }
2208
+ function sanitizeStringForSeed(input) {
2209
+ let output = input.toLowerCase();
2210
+ for (const [name, regex] of fields_1.BEFORE_SIDES_SANITIZE_REGEXES) {
2211
+ output = output.replaceAll(regex, "");
2212
+ }
2213
+ for (const [name, regex] of fields_1.AFTER_SIDES_SANITIZE_REGEXES) {
2214
+ output = output.replaceAll(regex, "");
2215
+ }
2216
+ while (output.includes(" ")) {
2217
+ output = output.replaceAll(" ", " ");
2218
+ }
2219
+ output = output.trim();
2220
+ return output;
2221
+ }
2222
+ function addAllSetToSet(input, outputSet) {
2223
+ for (const item of input) {
2224
+ outputSet.add(item);
2225
+ }
2226
+ return outputSet;
2227
+ }
2228
+ function addAllArrayToSet(input, outputSet) {
2229
+ for (const item of input) {
2230
+ outputSet.add(item);
2231
+ }
2232
+ return outputSet;
2233
+ }
2234
+ function addAllSetToArray(input, outputArray) {
2235
+ for (const item of input) {
2236
+ outputArray.push(item);
2237
+ }
2238
+ return outputArray;
2239
+ }
2240
+ function addAllArrayToArray(input, outputArray) {
2241
+ for (const item of input) {
2242
+ outputArray.push(item);
2243
+ }
2244
+ return outputArray;
2245
+ }
2246
+ function addAllArrayToMap(items, map, keyGetter) {
2247
+ for (const item of items) {
2248
+ map.set(keyGetter(item), item);
2249
+ }
2250
+ }
2251
+ function addSetArrayToMap(items, map, keyGetter) {
2252
+ for (const item of items) {
2253
+ map.set(keyGetter(item), item);
2254
+ }
2255
+ }
2256
+ function joinSet(input, joinWith) {
2257
+ let output = "";
2258
+ if (input.size <= 0) {
2259
+ return output;
2260
+ }
2261
+ let first = true;
2262
+ for (const item of input) {
2263
+ output += item;
2264
+ if (first) {
2265
+ first = false;
2266
+ }
2267
+ else {
2268
+ output += joinWith;
2269
+ }
2270
+ }
2271
+ return output;
2272
+ }
2273
+ function replaceAllArray(input, replaceInputs, replaceWith) {
2274
+ let output = input;
2275
+ for (const replaceInput of replaceInputs) {
2276
+ output = output.replaceAll(replaceInput, replaceWith);
2277
+ }
2278
+ return output;
2279
+ }
2280
+ function librarySplitMultipleArtists(input, aliases = classes_1.MUSIC_ALIASES) {
2281
+ const inputs = input.split(/(?:[,+;]|\W(?:[&x]|and|with|fixes|befriends|vs\.?)\W|\/)/gi);
2282
+ return inputs.map(artist => {
2283
+ artist = aliases.get(singleSpacesOnly(artist.replaceAll("​", " ").replaceAll(" - Topic", ""))).trim();
2284
+ const parenthesisFeatMatch = artist.match(fields_1.FEAT_WITH_PARENTHESIS_REGEX);
2285
+ if (parenthesisFeatMatch != null) {
2286
+ artist = artist.slice(0, parenthesisFeatMatch.index).trim();
2287
+ }
2288
+ const indexOfParenthesis = artist.indexOf("(");
2289
+ if (indexOfParenthesis != -1) {
2290
+ artist = artist.slice(0, indexOfParenthesis).trim();
2291
+ }
2292
+ artist = libraryCleanUpStartAndEndOfString(artist);
2293
+ artist = artist.replaceAll("", "").replaceAll("[", "(").replaceAll("]", ")").trim();
2294
+ return singleSpacesOnly(artist);
2295
+ }).filter(artist => artist.length > 0);
2296
+ }
2297
+ function libraryFindFeaturing(originalInput, aliases = classes_1.MUSIC_ALIASES) {
2298
+ let input = originalInput;
2299
+ const featMatch = input.match(fields_1.FEAT_WITH_PARENTHESIS_REGEX);
2300
+ if (featMatch == null) {
2301
+ return { newName: input, artists: [] };
2302
+ }
2303
+ let newName = input;
2304
+ const featString = featMatch[0].trim();
2305
+ newName = singleSpacesOnly(originalInput.replace(featString, "")).trim();
2306
+ input = featMatch[1];
2307
+ const indexOfDash = input.indexOf(" - ");
2308
+ if (indexOfDash != -1) {
2309
+ input = input.slice(0, indexOfDash).trim();
2310
+ }
2311
+ const featuring = [];
2312
+ const regex = /([^\(\)\[\]]+)/gi;
2313
+ for (const match of input.matchAll(regex)) {
2314
+ for (const artist of librarySplitMultipleArtists(match[1], aliases)) {
2315
+ featuring.push(artist.trim());
2316
+ }
2317
+ }
2318
+ return {
2319
+ newName: aliases.get(newName),
2320
+ artists: featuring
2321
+ };
2322
+ }
2323
+ function libraryCleanUpStartAndEndOfString(input) {
2324
+ input = input.trim();
2325
+ if (input.length == 0) {
2326
+ return input;
2327
+ }
2328
+ let firstChar = input.at(0);
2329
+ while (firstChar == "-") {
2330
+ input = input.slice(1, input.length).trim();
2331
+ if (input.length == 0) {
2332
+ break;
2333
+ }
2334
+ firstChar = input.at(0);
2335
+ }
2336
+ let lastChar = input.at(input.length - 1);
2337
+ while (lastChar == "-" || lastChar == "(" || lastChar == "[") {
2338
+ input = input.slice(0, input.length - 1).trim();
2339
+ if (input.length == 0) {
2340
+ break;
2341
+ }
2342
+ lastChar = input.at(input.length - 1);
2343
+ }
2344
+ return singleSpacesOnly(input).trim();
2345
+ }
2346
+ function generateWeightedItemsGridString(width, height, symbols, totalWeight) {
2347
+ let grid = '';
2348
+ let lastItem = '';
2349
+ for (let y = 0; y < height; ++y) {
2350
+ let line = '';
2351
+ for (let x = 0; x < width; ++x) {
2352
+ do {
2353
+ const item = getRandomWeighedItem(symbols, totalWeight);
2354
+ if (item == lastItem) {
2355
+ if (randomBoolean(0.8)) {
2356
+ continue;
2357
+ }
2358
+ }
2359
+ line += item;
2360
+ lastItem = item;
2361
+ break;
2362
+ } while (true);
2363
+ }
2364
+ grid += `${line}\n`;
2365
+ }
2366
+ return grid;
2367
+ }
2368
+ async function promptYesOrNo(actionName = "Proceed?") {
2369
+ return new Promise(resolve => {
2370
+ process.stdout.write(`${actionName} [y/n]: `);
2371
+ process.stdin.setRawMode(true);
2372
+ process.stdin.resume();
2373
+ const onKeyPress = (buffer) => {
2374
+ const key = buffer.toString().toLowerCase();
2375
+ if (key === 'y') {
2376
+ cleanup();
2377
+ resolve(true);
2378
+ }
2379
+ else if (key === 'n') {
2380
+ cleanup();
2381
+ resolve(false);
2382
+ }
2383
+ };
2384
+ const cleanup = () => {
2385
+ process.stdin.setRawMode(false);
2386
+ process.stdin.pause();
2387
+ process.stdin.off('data', onKeyPress);
2388
+ };
2389
+ process.stdin.on('data', onKeyPress);
2390
+ });
2391
+ }
2392
+ async function musicFileInfoToM3uEntry(fileInfo) {
2393
+ var _a;
2394
+ const titleAndArtists = await classes_1.TitleAndArtists.fromFileInfo(fileInfo);
2395
+ const tags = await util_1.musicMetadata.parseFile(fileInfo.path, { skipCovers: true });
2396
+ const formatTags = tags.format;
2397
+ const durationS = (_a = formatTags.duration) !== null && _a !== void 0 ? _a : -1;
2398
+ return toM3uEntry(fileInfo.path, titleAndArtists.artistsDashTitle, durationS);
2399
+ }
2400
+ function toM3uEntry(path, title = "", durationS = -1) {
2401
+ const safeTitle = title.trim().length == 0 ? (0, path_1.basename)(path) : title;
2402
+ return `#EXTINF:${Math.floor(durationS)},${safeTitle}\n${path}`;
2403
+ }
2404
+ function getStepString(step, totalSteps = -1) {
2405
+ if (totalSteps > 0) {
2406
+ return `Step ${step}/${totalSteps}:`;
2407
+ }
2408
+ return `Step ${step}:`;
2409
+ }
2410
+ function sliceOffLastSlash(path, times = 1) {
2411
+ return sliceOffLast(path, fields_1.SEP, times);
2412
+ }
2413
+ function sliceOffLast(path, lastMatch, times = 1) {
2414
+ do {
2415
+ const lastSlashIndex = path.lastIndexOf(lastMatch);
2416
+ if (lastSlashIndex == -1) {
2417
+ break;
2418
+ }
2419
+ path = path.slice(0, lastSlashIndex);
2420
+ } while (--times > 0);
2421
+ return path;
2422
+ }
2423
+ function sliceOffUntil(text, lastMatch) {
2424
+ const lastSlashIndex = text.lastIndexOf(lastMatch);
2425
+ if (lastSlashIndex == -1) {
2426
+ return text;
2427
+ }
2428
+ text = text.slice(lastSlashIndex);
2429
+ return text;
2430
+ }
2431
+ function sliceOffNonProject(path) {
2432
+ const srcIndex = path.replaceAll("\\", "/").indexOf("/src/");
2433
+ if (srcIndex === -1) {
2434
+ return path;
2435
+ }
2436
+ const pathUntilSrc = path.substring(0, srcIndex);
2437
+ const lastSlashIndex = lastIndexOfSeparator(pathUntilSrc);
2438
+ if (lastSlashIndex === -1) {
2439
+ return path;
2440
+ }
2441
+ return path.substring(lastSlashIndex + 1);
2442
+ }
2443
+ function countOccurances(path, match) {
2444
+ let count = 0;
2445
+ let index = path.indexOf(match);
2446
+ while (index != -1) {
2447
+ ++count;
2448
+ index = path.indexOf(match, index + match.length);
2449
+ }
2450
+ return count;
2451
+ }
2452
+ function countPathDepth(path) {
2453
+ return countOccurances(path, "/");
2454
+ }
2455
+ function getPathEscapeString(depth) {
2456
+ let pathEscapeString = "";
2457
+ for (let i = 0; i < depth; ++i) {
2458
+ pathEscapeString += "../";
2459
+ }
2460
+ return pathEscapeString;
2461
+ }
2462
+ function getFullPathEscapeString(path) {
2463
+ const depth = countPathDepth(path);
2464
+ return getPathEscapeString(depth);
2465
+ }
2466
+ function jsonLookupToMap(json) {
2467
+ const map = new Map();
2468
+ for (const [key, value] of Object.entries(json)) {
2469
+ const numberKey = parseInt(key);
2470
+ if (isNaN(numberKey)) {
2471
+ console.error(`Invalid lookup: ${key}`);
2472
+ continue;
2473
+ }
2474
+ map.set(numberKey, value);
2475
+ }
2476
+ return map;
2477
+ }
2478
+ function extractElementFromJsonAndRemove(obj, key) {
2479
+ const element = obj[key];
2480
+ delete obj[key];
2481
+ return element;
2482
+ }
2483
+ function extractLookupFromJsonAndRemove(obj) {
2484
+ const keys = jsonLookupToMap(extractElementFromJsonAndRemove(obj, "lookup"));
2485
+ return keys;
2486
+ }
2487
+ function forEachValueAndPathOfObj(obj, callback, lookup = new Map) {
2488
+ return forEachLookUpValueAndPathOfObjRecursive(lookup, obj, callback);
2489
+ }
2490
+ function forEachLookUpValueAndPathOfObjRecursive(lookup, obj, callback, inputPath = "") {
2491
+ for (const [key, value] of Object.entries(obj)) {
2492
+ const path = inputPath.length == 0 ? key : `${inputPath}/${key}`;
2493
+ if (Array.isArray(value)) {
2494
+ for (const arrayValue of value) {
2495
+ callback(path, lookup.get(arrayValue));
2496
+ }
2497
+ }
2498
+ else if (typeof value === "object") {
2499
+ forEachLookUpValueAndPathOfObjRecursive(lookup, value, callback, path);
2500
+ }
2501
+ else {
2502
+ callback(path, lookup.get(value));
2503
+ }
2504
+ }
2505
+ }
2506
+ async function findGeniusSongs(search) {
2507
+ const songs = await exports.geniusClient.songs.search(search);
2508
+ return songs;
2509
+ }
2510
+ function trimToCharNumbersOnly(input) {
2511
+ return trim(input, fields_1.NON_NUMBER_OR_CHAR_REGEX);
2512
+ }
2513
+ function trimStartToCharNumbersOnly(input) {
2514
+ return trimStart(input, fields_1.NON_NUMBER_OR_CHAR_REGEX);
2515
+ }
2516
+ function trimEndToCharNumbersOnly(input) {
2517
+ return trimEnd(input, fields_1.NON_NUMBER_OR_CHAR_REGEX);
2518
+ }
2519
+ function trim(input, regex = fields_1.TRIM_REGEX) {
2520
+ return trimStart(trimEnd(input, regex), regex);
2521
+ }
2522
+ function trimStart(input, regex) {
2523
+ let startIndex = 0;
2524
+ while (startIndex < input.length && regex.test(input[startIndex])) {
2525
+ ++startIndex;
2526
+ }
2527
+ return input.slice(startIndex, input.length);
2528
+ }
2529
+ function trimEnd(input, regex) {
2530
+ let endIndex = input.length - 1;
2531
+ while (endIndex >= 0 && regex.test(input[endIndex])) {
2532
+ --endIndex;
2533
+ }
2534
+ return input.slice(0, endIndex + 1);
2535
+ }
2536
+ async function findGeniusLyrics(query, artistsToMatch = []) {
2537
+ const geniusSongs = await findGeniusSongs(query);
2538
+ for (const geniusSong of geniusSongs) {
2539
+ const geniusArtistsDashTitle = `${geniusSong.artist.name} - ${geniusSong.title}`;
2540
+ const geniusSongArtist = classes_1.MUSIC_ALIASES.get(geniusSong.artist.name);
2541
+ let correctArtist = false;
2542
+ if (artistsToMatch.length == 0) {
2543
+ correctArtist = true;
2544
+ }
2545
+ else {
2546
+ for (const artist of artistsToMatch) {
2547
+ if (geniusSongArtist === classes_1.MUSIC_ALIASES.get(artist)) {
2548
+ correctArtist = true;
2549
+ break;
2550
+ }
2551
+ }
2552
+ }
2553
+ if (correctArtist) {
2554
+ try {
2555
+ const geniusLyrics = (await geniusSong.lyrics()).replaceAll(fields_1.CONTRIBUTORS_REGEX, "");
2556
+ return geniusLyrics;
2557
+ }
2558
+ catch (err) {
2559
+ console.log(exports.chalk.redBright(`Error getting Genius lyrics for ${geniusArtistsDashTitle}:\n${err}`));
2560
+ }
2561
+ }
2562
+ }
2563
+ }
2564
+ function softSliceFrom(input, sliceFrom, anyCase = true, fromElseTo = true) {
2565
+ const regex = new RegExp(`(${sliceFrom})`, `${anyCase ? "i" : ""}`);
2566
+ const match = input.match(regex);
2567
+ if (match != null) {
2568
+ const lyricsIndex = match.index;
2569
+ if (lyricsIndex != null) {
2570
+ const lyricsStart = fromElseTo ?
2571
+ input.slice(0, lyricsIndex + match[1].length) :
2572
+ input.slice(lyricsIndex);
2573
+ input = input.replace(lyricsStart, "");
2574
+ }
2575
+ }
2576
+ return input.trim();
2577
+ }
2578
+ function trimFirstLinesWhileIncludes(input, blacklistLineTerm) {
2579
+ input = input.trim();
2580
+ do {
2581
+ const nextLineMatch = input.match(fields_1.NEW_LINE_REGEX);
2582
+ if (nextLineMatch == null) {
2583
+ break;
2584
+ }
2585
+ const nextLineIndex = nextLineMatch.index;
2586
+ const firstLine = input.slice(0, nextLineIndex);
2587
+ if (firstLine.toLowerCase().includes(blacklistLineTerm)) {
2588
+ input = input.slice(nextLineIndex).trim();
2589
+ }
2590
+ else {
2591
+ break;
2592
+ }
2593
+ } while (true);
2594
+ return input;
2595
+ }
2596
+ function getFirstLine(input) {
2597
+ const nextLineMatch = input.match(fields_1.NEW_LINE_REGEX);
2598
+ if (nextLineMatch == null) {
2599
+ return undefined;
2600
+ }
2601
+ const nextLineIndex = nextLineMatch.index;
2602
+ const firstLine = input.slice(0, nextLineIndex);
2603
+ return firstLine;
2604
+ }
2605
+ function skyify(input) {
2606
+ return input.replaceAll(/[^\n\r ]/g, (_) => getRandomWeighedItem(fields_1.NIGHT_SKY_ITEMS, fields_1.NIGHT_SKY_ITEMS_TOTAL_WEIGHT)).slice(0, fields_1.DISCORD_MESSAGE_LENGTH_LIMIT);
2607
+ }
2608
+ function dateToFilename(date) {
2609
+ const year = date.getFullYear();
2610
+ const month = String(date.getMonth() + 1).padStart(2, '0');
2611
+ const day = String(date.getDate()).padStart(2, '0');
2612
+ return `${year}-${month}-${day}_${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`;
2613
+ }
2614
+ function makeMap(preparer) {
2615
+ return make(new Map, preparer);
2616
+ }
2617
+ function makeWeightedMap(input) {
2618
+ if (input instanceof Array) {
2619
+ return makeWeightedMap(map => {
2620
+ for (const item of input) {
2621
+ map.add(item, 1);
2622
+ }
2623
+ });
2624
+ }
2625
+ return make(new classes_1.WeightedMap, input);
2626
+ }
2627
+ function makeWeightedTextCompMap(input) {
2628
+ if (input instanceof Array) {
2629
+ return makeWeightedTextCompMap(map => {
2630
+ for (const item of input) {
2631
+ map.add(item, 1);
2632
+ }
2633
+ });
2634
+ }
2635
+ return make(new classes_1.WeightedMap, input);
2636
+ }
2637
+ function generateLinesUntilCharacterLimit(generator, amount = 1, limit = fields_1.DISCORD_MESSAGE_LENGTH_LIMIT) {
2638
+ let output = "";
2639
+ for (let i = 0; i < amount; ++i) {
2640
+ const nextLine = generator();
2641
+ if (limit < output.length + nextLine.length + 1) {
2642
+ break;
2643
+ }
2644
+ output += `${nextLine}\n`;
2645
+ }
2646
+ return output;
2647
+ }
2648
+ function lastIndexOfSeparator(path) {
2649
+ return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
2650
+ }
2651
+ function timestamp() {
2652
+ const now = new Date();
2653
+ return `[${padLeft(now.getHours().toString(), 2, "0")}:${padLeft(now.getMinutes().toString(), 2, "0")}:${padLeft(now.getSeconds().toString(), 2, "0")}]`;
2654
+ }
2655
+ function timestampWithMs() {
2656
+ const now = new Date();
2657
+ return `${timestamp().slice(0, -1)}.${padLeft(now.getMilliseconds().toString(), 3, "0")}]`;
2658
+ }
2659
+ function isSilent(buffer) {
2660
+ var speechSample;
2661
+ for (var i = 0; i < buffer.length; i = i + 2) {
2662
+ if (buffer[i + 1] > 128) {
2663
+ speechSample = (buffer[i + 1] - 256) * 256;
2664
+ }
2665
+ else {
2666
+ speechSample = buffer[i + 1] * 256;
2667
+ }
2668
+ speechSample += buffer[i];
2669
+ if (Math.abs(speechSample) > 2000) {
2670
+ return false;
2671
+ }
2672
+ }
2673
+ return true;
2674
+ }
2675
+ async function waitMs(ms) {
2676
+ return new Promise(resolve => setTimeout(resolve, ms));
2677
+ }
2678
+ async function waitS(s) {
2679
+ return new Promise(resolve => setTimeout(resolve, s * 1000));
2680
+ }
2681
+ async function whileFalseAsyncS(intervalS, stopIfTrue) {
2682
+ return whileFalseAsyncMs(intervalS * 1000, stopIfTrue);
2683
+ }
2684
+ async function whileFalseAsyncMs(intervalMs, stopIfTrue) {
2685
+ return new Promise(async (resolve, reject) => {
2686
+ let task = null;
2687
+ task = setInterval(() => {
2688
+ if (stopIfTrue()) {
2689
+ clearInterval(task);
2690
+ resolve(true);
2691
+ }
2692
+ }, intervalMs);
2693
+ });
2694
+ }
2695
+ async function repeatForAsyncS(durationS, intervalS, stopIfTrue) {
2696
+ return repeatForAsyncMs(durationS * 1000, intervalS * 1000, stopIfTrue);
2697
+ }
2698
+ async function repeatForAsyncMs(durationMs, intervalMs, stopIfTrue) {
2699
+ const endTime = Date.now() + durationMs;
2700
+ return whileFalseAsyncMs(intervalMs, () => {
2701
+ if (Date.now() <= endTime || stopIfTrue()) {
2702
+ return false;
2703
+ }
2704
+ return true;
2705
+ });
2706
+ }
2707
+ // let lastSetTerminalLine: string = ""
2708
+ // export function replaceLastTerminalLine(text: string)
2709
+ // {
2710
+ // process.stdout.clearLine(0)
2711
+ // process.stdout.cursorTo(0)
2712
+ // if (lastSetTerminalLine !== text)
2713
+ // {
2714
+ // process.stdout.write(text)
2715
+ // lastSetTerminalLine = text
2716
+ // }
2717
+ // }
2718
+ let lastSetTerminalLine = "";
2719
+ function replaceLastTerminalLine(text) {
2720
+ process.stdout.clearLine(0);
2721
+ process.stdout.cursorTo(0);
2722
+ if (lastSetTerminalLine !== text) {
2723
+ process.stdout.write(text);
2724
+ lastSetTerminalLine = text;
2725
+ }
2726
+ }
2727
+ let lastTerminalOutputLines = 0;
2728
+ function setTerminalOutput(text, newSession = false) {
2729
+ clearTerminalLines(lastTerminalOutputLines);
2730
+ if (newSession) {
2731
+ lastTerminalOutputLines = 0;
2732
+ }
2733
+ const lines = text.split(/[\n\r]/).length;
2734
+ process.stdout.write(`${text}\n`);
2735
+ lastTerminalOutputLines = lines;
2736
+ }
2737
+ function clearSetTerminalOutput() {
2738
+ clearTerminalLines(lastTerminalOutputLines);
2739
+ lastTerminalOutputLines = 0;
2740
+ }
2741
+ function clearTerminalLines(amount) {
2742
+ process.stdout.write('\x1b[0G'); // Move to start of line
2743
+ for (let i = 0; i < amount + 1; i++) {
2744
+ process.stdout.write('\x1b[2K'); // Clear line
2745
+ if (i < amount) {
2746
+ process.stdout.write('\x1b[1A'); // Move up
2747
+ }
2748
+ }
2749
+ }
2750
+ function sIfNot1(count) {
2751
+ return count == 1 ? "" : "s";
2752
+ }
2753
+ function if1Else(count, if1, or) {
2754
+ return count == 1 ? if1 : or;
2755
+ }
2756
+ function makePath(...paths) {
2757
+ return paths.join(path_1.default.sep).replaceAll(/[/\\]/g, path_1.default.sep);
2758
+ }
2759
+ function makeUnixPath(...paths) {
2760
+ return paths.join("/").replaceAll("\\", "/");
2761
+ }
2762
+ function makeWindowsPath(...paths) {
2763
+ return paths.join("\\").replaceAll("/", "\\");
2764
+ }
2765
+ function overflow(value, min, max) {
2766
+ if (value < min) {
2767
+ const gap = max - min + 1;
2768
+ const minGap = min - value - 1;
2769
+ return max - (minGap % gap);
2770
+ }
2771
+ if (max < value) {
2772
+ const gap = max - min + 1;
2773
+ const maxGap = value - max - 1;
2774
+ return min + (maxGap % gap);
2775
+ }
2776
+ return value;
2777
+ }
2778
+ function overflow0(value, max) {
2779
+ return overflow(value, 0, max);
2780
+ }
2781
+ function isWithin(value, min, max) {
2782
+ return min <= value && value <= max;
2783
+ }
2784
+ //region Menu
2785
+ async function startShiftItemsMenu(items, itemValueMap, values, selectedIndex = 0, rainbow = true, itemToString = objectToString, valueToString = objectToString) {
2786
+ if (values.length === 0) {
2787
+ throw new Error("startShiftItemsMenu: No values to select from!");
2788
+ }
2789
+ const valueMemory = [];
2790
+ for (const item of items) {
2791
+ const value = getOrCreate(itemValueMap, item, () => values[0]);
2792
+ const valueIndex = values.indexOf(value);
2793
+ if (valueIndex === -1) {
2794
+ itemValueMap.set(item, value);
2795
+ }
2796
+ valueMemory.push(valueIndex);
2797
+ }
2798
+ return startMenu(items, itemValueMap, selectedIndex, (selectedIndex, info, update, setSelectedIndex) => {
2799
+ const item = items[selectedIndex];
2800
+ let valueIndex = valueMemory[selectedIndex];
2801
+ const result = shiftMenuItemsFunction(valueIndex, values, values[selectedIndex], info);
2802
+ valueIndex = result.index;
2803
+ valueMemory[selectedIndex] = valueIndex;
2804
+ itemValueMap.set(item, result.value);
2805
+ update();
2806
+ }, rainbow, itemToString, valueToString);
2807
+ }
2808
+ function getRelativeOverflow(startIndex, values, moveBy) {
2809
+ return values[overflow0(startIndex + moveBy, values.length - 1)];
2810
+ }
2811
+ function shiftMenuItemsFunction(valueIndex, values, value, info) {
2812
+ if (valueIndex === -1) {
2813
+ valueIndex = clamp0(values.indexOf(value), values.length - 1);
2814
+ }
2815
+ const moveBy = navigationKeysToNumber(info);
2816
+ valueIndex = overflow0(valueIndex + moveBy, values.length - 1);
2817
+ return {
2818
+ value: values[valueIndex],
2819
+ index: valueIndex
2820
+ };
2821
+ }
2822
+ async function startNumbersEditMenu(items, itemValueMap, selectedIndex = 0, rainbow = true, itemToString = objectToString, valueToString = objectToString) {
2823
+ getOrCreateFromKeys(itemValueMap, items, () => 0);
2824
+ return startMenu(items, itemValueMap, selectedIndex, (selectedIndex, info, update, setSelectedIndex) => {
2825
+ switch (info.name) {
2826
+ // case 'w':
2827
+ // case 's':
2828
+ // {
2829
+ // const itemsRange = RangedNumber.arrayLimits(items)
2830
+ // setSelectedIndex(editNumberByInput(selectedIndex, info.name, itemsRange, info.ctrl, info.shift, info.meta))
2831
+ // update()
2832
+ // }
2833
+ // break
2834
+ case 'left':
2835
+ case 'right':
2836
+ case 'a':
2837
+ case 'd':
2838
+ {
2839
+ const item = items[selectedIndex];
2840
+ const value = itemValueMap.get(item);
2841
+ const newValue = value + navigationKeysToNumber(info);
2842
+ if (newValue !== value) {
2843
+ itemValueMap.set(item, newValue);
2844
+ update();
2845
+ }
2846
+ }
2847
+ }
2848
+ }, rainbow, itemToString, valueToString);
2849
+ }
2850
+ async function startMenu(items, itemValueMap, selectedIndex = 0, onKeyPress, rainbow = true, itemToString = objectToString, valueToString = objectToString) {
2851
+ selectedIndex = clamp0(selectedIndex, items.length - 1);
2852
+ return new Promise((resolve, reject) => {
2853
+ if (items.length === 0) {
2854
+ reject('startMenu: No items to select from!');
2855
+ return;
2856
+ }
2857
+ const itemsRange = structs_1.RangedNumber.range(0, items.length - 1);
2858
+ let item;
2859
+ const update = () => {
2860
+ item = items[selectedIndex];
2861
+ setTerminalOutput(toMenuString(items, itemValueMap, selectedIndex, rainbow, itemToString, valueToString));
2862
+ };
2863
+ update();
2864
+ readline.emitKeypressEvents(process.stdin);
2865
+ if (process.stdin.isTTY) {
2866
+ process.stdin.setRawMode(true);
2867
+ }
2868
+ process.stdin.on('keypress', (ignore, info) => {
2869
+ switch (info.name) {
2870
+ case 'up':
2871
+ case 'down':
2872
+ case 'w':
2873
+ case 's':
2874
+ {
2875
+ selectedIndex = editNumberByInput(selectedIndex, info.name, itemsRange, info.ctrl, info.shift, info.meta);
2876
+ update();
2877
+ }
2878
+ break;
2879
+ case 'return':
2880
+ case 'enter':
2881
+ case 'escape':
2882
+ {
2883
+ process.stdin.removeAllListeners('keypress');
2884
+ if (process.stdin.isTTY) {
2885
+ process.stdin.setRawMode(false);
2886
+ }
2887
+ resolve(true);
2888
+ return;
2889
+ }
2890
+ break;
2891
+ default:
2892
+ {
2893
+ onKeyPress(selectedIndex, info, update, (newIndex) => selectedIndex = newIndex);
2894
+ }
2895
+ break;
2896
+ }
2897
+ });
2898
+ });
2899
+ }
2900
+ function navigationKeysToNumber(info) {
2901
+ const key = info.name.toLowerCase();
2902
+ switch (key) {
2903
+ case 'up':
2904
+ case 'down':
2905
+ case 'w':
2906
+ case 's':
2907
+ {
2908
+ const up = key === 'up' || key === 'w';
2909
+ let moveBy = info.ctrl ? 25 : info.shift ? 5 : 1;
2910
+ return up ? -moveBy : moveBy;
2911
+ }
2912
+ case 'left':
2913
+ case 'right':
2914
+ case 'a':
2915
+ case 'd':
2916
+ {
2917
+ const left = key === 'left' || key === 'a';
2918
+ let changeBy = (info.ctrl && info.shift) ? 1000 : info.ctrl ? 100 : info.shift ? 10 : 1;
2919
+ return left ? -changeBy : changeBy;
2920
+ }
2921
+ }
2922
+ return 0;
2923
+ }
2924
+ function editNumberByInput(value, key, overflowLimits, control = false, shift = false, meta = false) {
2925
+ switch (key.toLowerCase()) {
2926
+ case 'up':
2927
+ case 'down':
2928
+ case 'w':
2929
+ case 's':
2930
+ {
2931
+ const up = key === 'up' || key === 'w';
2932
+ let moveBy = control ? 25 : shift ? 5 : 1;
2933
+ if (up) {
2934
+ moveBy = -moveBy;
2935
+ }
2936
+ value += moveBy;
2937
+ if (overflowLimits) {
2938
+ value = overflow(value, overflowLimits.minValue, overflowLimits.maxValue);
2939
+ }
2940
+ }
2941
+ break;
2942
+ case 'left':
2943
+ case 'right':
2944
+ case 'a':
2945
+ case 'd':
2946
+ {
2947
+ const left = key === 'left' || key === 'a';
2948
+ let changeBy = (control && shift) ? 1000 : control ? 100 : shift ? 10 : 1;
2949
+ if (left) {
2950
+ changeBy = -changeBy;
2951
+ }
2952
+ value += changeBy;
2953
+ }
2954
+ break;
2955
+ }
2956
+ return value;
2957
+ }
2958
+ const objectToString = (obj) => obj.toString();
2959
+ function toMenuString(items, itemValueMap, selectedIndex = 0, rainbow = true, itemToString = objectToString, valueToString = objectToString) {
2960
+ let output = '';
2961
+ let longest = 0;
2962
+ for (const [item, value] of itemValueMap) {
2963
+ const valueText = valueToString(value);
2964
+ if (longest < valueText.length) {
2965
+ longest = valueText.length;
2966
+ }
2967
+ }
2968
+ let itemIndex = 0;
2969
+ for (const [item, value] of itemValueMap) {
2970
+ const selected = itemIndex === selectedIndex;
2971
+ const prefix = selected ? '>' : fields_1.EMPTY;
2972
+ const valueText = valueToString(value);
2973
+ let itemText = `${prefix}${`[${padRight(valueText, longest, fields_1.EMPTY)}]`} | ${itemToString(item)}`;
2974
+ if (selected) {
2975
+ itemText = exports.chalk.bold(itemText);
2976
+ }
2977
+ if (rainbow) {
2978
+ itemText = chalkRainbowColor(itemText, itemIndex);
2979
+ }
2980
+ output += `${itemText}\n`;
2981
+ ++itemIndex;
2982
+ }
2983
+ return output.trim();
2984
+ }
2985
+ //endregion Menu
2986
+ function toPrintString(fileName, functionName, lineNumber) {
2987
+ return `${timestamp()} ${exports.chalk.cyanBright(sliceOffNonProject(fileName).replaceAll("\\", "/"))}${functionName ? ` | ${exports.chalk.magentaBright(functionName)}` : ""}#${exports.chalk.greenBright(lineNumber)}`;
2988
+ }
2989
+ function print(message) {
2990
+ message = message ? `: ${message}` : "";
2991
+ const stack = new Error().stack;
2992
+ if (stack) {
2993
+ const lines = stack.split('\n');
2994
+ if (lines.length > 2) {
2995
+ const callerLine = lines[2].trim();
2996
+ const match = callerLine.match(/at\s+(.*)\s+\((.*):(\d+):\d+\)/);
2997
+ if (match) {
2998
+ const [, functionName, fileName, lineNumber] = match;
2999
+ console.log(`${toPrintString(fileName, functionName, lineNumber)}${message}`);
3000
+ }
3001
+ else {
3002
+ const match2 = callerLine.match(/at\s+(.*):(\d+):\d+/);
3003
+ if (match2) {
3004
+ const [, fileName, lineNumber] = match2;
3005
+ console.log(`${toPrintString(fileName, undefined, lineNumber)}${message}`);
3006
+ }
3007
+ }
3008
+ }
3009
+ }
3010
+ }
3011
+ function softToFixed(num, maxDecimals = 2) {
3012
+ if (!isFinite(num)) {
3013
+ return String(num);
3014
+ }
3015
+ const factor = Math.pow(10, maxDecimals);
3016
+ const rounded = Math.round(num * factor) / factor;
3017
+ return rounded.toString();
3018
+ }
3019
+ function extractEpisodeNumber(filename) {
3020
+ const match = filename.match(/(?:e\s*)?(\d{1,3})(?!\d)/i);
3021
+ return match ? parseInt(match[1], 10) : -1;
3022
+ }
3023
+ function trashSoft(filePath) {
3024
+ if (!(0, fs_1.existsSync)(filePath)) {
3025
+ return false;
3026
+ }
3027
+ const plat = (0, os_1.platform)();
3028
+ try {
3029
+ switch (plat) {
3030
+ case "win32":
3031
+ {
3032
+ (0, child_process_1.execSync)(`powershell -Command "Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('${filePath.replace(/'/g, "''")}', 'OnlyErrorDialogs', 'SendToRecycleBin')"`);
3033
+ }
3034
+ break;
3035
+ case "darwin":
3036
+ {
3037
+ (0, child_process_1.execSync)(`osascript -e 'tell app "Finder" to delete POSIX file "${filePath.replace(/"/g, '\\"')}"'`);
3038
+ }
3039
+ break;
3040
+ default:
3041
+ {
3042
+ try {
3043
+ (0, child_process_1.execSync)(`gio trash "${filePath.replace(/"/g, '\\"')}"`);
3044
+ }
3045
+ catch (_a) {
3046
+ (0, child_process_1.execSync)(`trash "${filePath.replace(/"/g, '\\"')}"`);
3047
+ }
3048
+ }
3049
+ break;
3050
+ }
3051
+ }
3052
+ catch (e) {
3053
+ (0, fs_1.rmSync)(filePath);
3054
+ }
3055
+ return true;
3056
+ }
3057
+ //region extensions
3058
+ const pictureExtensions = new Set([
3059
+ 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif',
3060
+ 'heif', 'heic', 'avif', 'svg', 'ico', 'raw', 'cr2', 'nef', 'orf', 'raf'
3061
+ ]);
3062
+ const videoExtensions = new Set([
3063
+ 'mp4', 'mkv', 'mov', 'avi', 'wmv', 'flv', 'webm', 'm4v',
3064
+ 'mpeg', 'mpg', '3gp', 'ogv', 'ts', 'm2ts'
3065
+ ]);
3066
+ const audioExtensions = new Set([
3067
+ 'mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a', 'wma', 'opus',
3068
+ 'aiff', 'alac', 'mid', 'midi'
3069
+ ]);
3070
+ const subtitleExtensions = new Set([
3071
+ 'srt', 'ass', 'ssa', 'vtt', 'sub', 'idx', 'sup', 'ttml'
3072
+ ]);
3073
+ const fontExtensions = new Set([
3074
+ 'ttf', 'otf', 'woff', 'woff2', 'fon'
3075
+ ]);
3076
+ const archiveExtensions = new Set([
3077
+ 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz'
3078
+ ]);
3079
+ const documentExtensions = new Set([
3080
+ 'txt', 'rtf', 'pdf', 'doc', 'docx', 'odt', 'md', 'html', 'htm',
3081
+ 'epub', 'djvu'
3082
+ ]);
3083
+ const codeExtensions = new Set([
3084
+ 'ts', 'js', 'jsx', 'tsx', 'py', 'java', 'c', 'cpp', 'cs', 'php',
3085
+ 'rb', 'go', 'rs', 'swift', 'sh', 'bat', 'pl'
3086
+ ]);
3087
+ const modelExtensions = new Set([
3088
+ 'obj', 'fbx', 'glb', 'gltf', 'stl', 'ply', '3ds', 'blend'
3089
+ ]);
3090
+ const imageSequenceExtensions = new Set([
3091
+ 'dpx', 'exr', 'tga'
3092
+ ]);
3093
+ function isOfType(extension, extensions) {
3094
+ return extensions.has(extension);
3095
+ }
3096
+ // --- Exports ---
3097
+ const isPicture = (extension) => isOfType(extension, pictureExtensions);
3098
+ exports.isPicture = isPicture;
3099
+ const isVideo = (extension) => isOfType(extension, videoExtensions);
3100
+ exports.isVideo = isVideo;
3101
+ const isAudio = (extension) => isOfType(extension, audioExtensions);
3102
+ exports.isAudio = isAudio;
3103
+ const isSubtitle = (extension) => isOfType(extension, subtitleExtensions);
3104
+ exports.isSubtitle = isSubtitle;
3105
+ const isFont = (extension) => isOfType(extension, fontExtensions);
3106
+ exports.isFont = isFont;
3107
+ const isArchive = (extension) => isOfType(extension, archiveExtensions);
3108
+ exports.isArchive = isArchive;
3109
+ const isDocument = (extension) => isOfType(extension, documentExtensions);
3110
+ exports.isDocument = isDocument;
3111
+ const isCode = (extension) => isOfType(extension, codeExtensions);
3112
+ exports.isCode = isCode;
3113
+ const isModel = (extension) => isOfType(extension, modelExtensions);
3114
+ exports.isModel = isModel;
3115
+ const isImageSequence = (extension) => isOfType(extension, imageSequenceExtensions);
3116
+ exports.isImageSequence = isImageSequence;
3117
+ const classifyExt = (ext) => {
3118
+ ext = ext.toLowerCase();
3119
+ switch (true) {
3120
+ case pictureExtensions.has(ext): return 'picture';
3121
+ case videoExtensions.has(ext): return 'video';
3122
+ case audioExtensions.has(ext): return 'audio';
3123
+ case subtitleExtensions.has(ext): return 'subtitle';
3124
+ case fontExtensions.has(ext): return 'font';
3125
+ case archiveExtensions.has(ext): return 'archive';
3126
+ case documentExtensions.has(ext): return 'document';
3127
+ case codeExtensions.has(ext): return 'code';
3128
+ case modelExtensions.has(ext): return '3d-model';
3129
+ case imageSequenceExtensions.has(ext): return 'image-sequence';
3130
+ default: return 'unknown';
3131
+ }
3132
+ };
3133
+ exports.classifyExt = classifyExt;
3134
+ //endregion extensions
3135
+ function subtitlesStreamInfoToString(info) {
3136
+ return `${info.language}:${info.streamIndex}`;
3137
+ }
3138
+ async function extractsubtitlesStreamsInfo(videoWithSubtitlesPath) {
3139
+ const command = `ffmpeg -i "${sanitizeStringForFFMPEG(videoWithSubtitlesPath)}"`;
3140
+ const result = await runCommandRejectAsResolve(command);
3141
+ const subtitles = [];
3142
+ for (const match of result.matchAll(fields_1.SUBTITLE_METADATA_REGEX)) {
3143
+ let format = null;
3144
+ const formatGroup1 = match[3].toLowerCase();
3145
+ switch (formatGroup1) {
3146
+ case "subrip":
3147
+ {
3148
+ format = "srt";
3149
+ }
3150
+ break;
3151
+ case "ass":
3152
+ {
3153
+ format = "ass";
3154
+ }
3155
+ break;
3156
+ }
3157
+ if (format === null) {
3158
+ const formatGroup2 = match[4].toLowerCase();
3159
+ switch (formatGroup2) {
3160
+ case "srt":
3161
+ {
3162
+ format = "srt";
3163
+ }
3164
+ break;
3165
+ case "ssa":
3166
+ {
3167
+ format = "ass";
3168
+ }
3169
+ break;
3170
+ default:
3171
+ {
3172
+ format = "sub";
3173
+ }
3174
+ }
3175
+ }
3176
+ subtitles.push({
3177
+ streamIndex: parseInt(match[1]),
3178
+ language: match[2],
3179
+ format: format,
3180
+ });
3181
+ }
3182
+ return subtitles;
3183
+ }
3184
+ async function tryExtractSubtitles(videoWithSubtitlesPath, subtitlesOutputPath, streamId = 0) {
3185
+ const command = `ffmpeg -y -i "${sanitizeStringForFFMPEG(videoWithSubtitlesPath)}" -map 0:${streamId} -c copy "${sanitizeStringForFFMPEG(subtitlesOutputPath)}"`;
3186
+ try {
3187
+ trashSoft(subtitlesOutputPath);
3188
+ const result = await runCommand(command);
3189
+ return true;
3190
+ }
3191
+ catch (e) {
3192
+ trashSoft(subtitlesOutputPath);
3193
+ // print(chalk.redBright(command))
3194
+ return false;
3195
+ }
3196
+ }
3197
+ async function addSubtitles(videoToAddSubtitlesToFile, subtitlesFile, customSubtitlesName = "", clearExistingSubtitles = false) {
3198
+ const tempOutputFile = `${videoToAddSubtitlesToFile.directory}/temp_${videoToAddSubtitlesToFile.fullName}`;
3199
+ trashSoft(tempOutputFile);
3200
+ // let command = `ffmpeg -i "${sanitizeStringForFFMPEG(videoToAddSubtitlesToFile.path)}" -i "${sanitizeStringForFFMPEG(subtitlesFile.path)}" -c copy -map 0 -map 1`
3201
+ let command = `ffmpeg -i "${sanitizeStringForFFMPEG(videoToAddSubtitlesToFile.path)}" -i "${sanitizeStringForFFMPEG(subtitlesFile.path)}" -map 0 -map 1`;
3202
+ if (clearExistingSubtitles) {
3203
+ command += ` -map -0:s`;
3204
+ }
3205
+ command += ` -c copy`;
3206
+ if (customSubtitlesName.length > 0) {
3207
+ command += ` -metadata:s:s:0 title="${customSubtitlesName}"`;
3208
+ }
3209
+ command += ` "${sanitizeStringForFFMPEG(tempOutputFile)}"`;
3210
+ try {
3211
+ await runCommand(command);
3212
+ }
3213
+ catch (e) {
3214
+ trashSoft(tempOutputFile);
3215
+ return false;
3216
+ }
3217
+ trashSoft(videoToAddSubtitlesToFile.path);
3218
+ (0, fs_1.renameSync)(tempOutputFile, videoToAddSubtitlesToFile.path);
3219
+ return true;
3220
+ }
3221
+ //# sourceMappingURL=util.js.map