@putkoff/abstract-utilities 1.0.132 → 1.0.134

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,1624 @@
1
+ import path from 'path';
2
+ import { u as path$1, t as safeGlobalProp } from './safe_storage-BmC80yrG.js';
3
+ import { readFileSync } from 'node:fs';
4
+ import { isAbsolute, resolve } from 'node:path';
5
+ import { inspect } from 'util';
6
+
7
+ const PROTOCOL = 'https://';
8
+ const DOMAIN_NAME = 'abstractendeavors';
9
+ const BASE_URL = `${PROTOCOL}${DOMAIN_NAME}.com`;
10
+ const SUB_DIR = 'secure-files';
11
+ const PROD_PREFIX = `/${SUB_DIR}/`;
12
+ const API_PREFIX = `/${SUB_DIR}/api`;
13
+ const DEV_PREFIX = `/${SUB_DIR}-dev/`;
14
+
15
+ function get_window() {
16
+ try {
17
+ if (typeof window !== 'undefined') {
18
+ return window;
19
+ }
20
+ }
21
+ catch (err) {
22
+ alert(err);
23
+ }
24
+ return null;
25
+ }
26
+ function get_window_location() {
27
+ try {
28
+ const Window = get_window();
29
+ if (!Window) {
30
+ return BASE_URL;
31
+ }
32
+ return Window.location;
33
+ }
34
+ catch (err) {
35
+ alert(err);
36
+ }
37
+ return null;
38
+ }
39
+ function get_window_pathname() {
40
+ try {
41
+ const Window = get_window();
42
+ if (!Window) {
43
+ return DEV_PREFIX;
44
+ }
45
+ return Window.location.pathname;
46
+ }
47
+ catch (err) {
48
+ alert(err);
49
+ }
50
+ return null;
51
+ }
52
+ function get_window_parts() {
53
+ try {
54
+ return get_window_location();
55
+ }
56
+ catch (err) {
57
+ alert(err);
58
+ }
59
+ return null;
60
+ }
61
+
62
+ /**
63
+ * Unwraps nested { result } fields until you hit a non-object or no more "result" keys.
64
+ */
65
+ function getResult(obj) {
66
+ let current = obj;
67
+ while (current &&
68
+ typeof current === "object" &&
69
+ Object.prototype.hasOwnProperty.call(current, "result")) {
70
+ current = current.result;
71
+ }
72
+ return current;
73
+ }
74
+ // Determines HTTP method, defaults to GET or POST based on body
75
+ function getMethod(method = null, body = null) {
76
+ const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'PULL'];
77
+ method = (method || '').toUpperCase();
78
+ if (!validMethods.includes(method)) {
79
+ method = body ? 'POST' : 'GET';
80
+ }
81
+ return method;
82
+ }
83
+ // Gets headers, skips JSON headers when body is FormData
84
+ function getHeaders(headers = {}, method = null, body = null) {
85
+ const result = { ...headers };
86
+ // let browser set boundary
87
+ if (body instanceof FormData) {
88
+ return result;
89
+ }
90
+ const upper = method?.toUpperCase();
91
+ if (['POST', 'PUT', 'PATCH'].includes(upper ?? '') &&
92
+ !result['Content-Type']) {
93
+ result['Content-Type'] = 'application/json';
94
+ }
95
+ return result;
96
+ }
97
+ // Prepares request body, serializes to JSON for non-GET requests
98
+ function getBody(body = null, method = null) {
99
+ method = getMethod(method, body);
100
+ if (method === 'GET') {
101
+ return undefined;
102
+ }
103
+ if (body) {
104
+ try {
105
+ return JSON.stringify(body);
106
+ }
107
+ catch (err) {
108
+ return body;
109
+ }
110
+ }
111
+ return undefined;
112
+ }
113
+ // Prepares fetch variables, passes FormData intact
114
+ function getFetchVars(headers = null, method = null, body = null) {
115
+ method = getMethod(method, body);
116
+ headers = getHeaders(headers || {}, method, body);
117
+ // only JSON-stringify non-FormData bodies
118
+ if (!(body instanceof FormData)) {
119
+ body = getBody(body, method);
120
+ }
121
+ return { method, headers, body };
122
+ }
123
+ /*
124
+ * parseResult no longer needs to worry about JSON vs HTML redirect errors;
125
+ * all 401/403 have already been handled above.
126
+ */
127
+ async function parseResult(res) {
128
+ // runs checkResponse first, will throw if session is expired
129
+ res = checkResponse(res);
130
+ if (!res.ok) {
131
+ // for any other non-401 errors, you can still surface them
132
+ const errorText = await res.text();
133
+ throw new Error(errorText || res.statusText);
134
+ }
135
+ // now safely parse JSON
136
+ return res.json();
137
+ }
138
+ /**
139
+ * Intercept 401/403 and force a clean redirect to login
140
+ * without ever showing an alert.
141
+ */
142
+ function checkResponse(res) {
143
+ if (res.status === 401 || res.status === 403) {
144
+ // 1) clear out the stale token
145
+ localStorage.removeItem("token");
146
+ // 2) replace history so "back" doesn’t re-trigger the protected route
147
+ window.history.replaceState({}, "", "/secure-files");
148
+ // 3) short-circuit all further fetch logic
149
+ throw new Error("SessionExpired");
150
+ }
151
+ return res;
152
+ }
153
+
154
+ async function fetchIt(endpoint, body = null, method = null, headers = null, blob = false, configUrl = false, withCredentials = true, returnJson = true, returnReult = true) {
155
+ method = (method || "GET").toUpperCase();
156
+ // 2) choose the URL
157
+ const url = endpoint;
158
+ // 3) prepare headers & body
159
+ headers = {
160
+ ...(body instanceof FormData ? {} : { "Content-Type": "application/json" }),
161
+ ...headers,
162
+ };
163
+ const opts = {
164
+ method,
165
+ credentials: withCredentials ? "include" : "same-origin",
166
+ headers,
167
+ body: body instanceof FormData
168
+ ? body
169
+ : body != null && method !== "GET"
170
+ ? JSON.stringify(body)
171
+ : undefined,
172
+ };
173
+ console.debug("āž”ļø secureFetchIt →", url, opts);
174
+ const res = await fetch(url, opts);
175
+ if (!res.ok) {
176
+ const err = await res.text();
177
+ throw new Error(`HTTP ${res.status}: ${err}`);
178
+ }
179
+ if (blob)
180
+ return res.blob();
181
+ if (returnReult)
182
+ return getResult(res.json());
183
+ if (returnJson)
184
+ return res.json();
185
+ return res;
186
+ }
187
+ // Constructs HTML directory path
188
+ function getHtmlDirectory(directory, filename) {
189
+ return `${directory}/${filename}.html`;
190
+ }
191
+ // Fetches HTML content
192
+ async function fetchIndexHtml(filename, directory = 'sf_index', base = 'html') {
193
+ const url = `/${base}/${directory}/${filename}.html`;
194
+ const response = await fetch(url);
195
+ return await response.text();
196
+ }
197
+ // Fetches and injects HTML content into container
198
+ async function fetchIndexHtmlContainer(filename, doc = document, directory = 'html') {
199
+ const container = `${filename}-container`;
200
+ const html = await fetchIndexHtml(filename, directory);
201
+ const el = doc.getElementById(container);
202
+ if (el) {
203
+ el.innerHTML = html;
204
+ }
205
+ else {
206
+ console.warn(`āš ļø No container found for: #${container}`);
207
+ }
208
+ }
209
+
210
+ function urlJoin(...parts) {
211
+ const s = (parts.length === 1 && Array.isArray(parts[0]) ? parts[0] : parts);
212
+ let r = "";
213
+ for (let i = 0; i < s.length; i++) {
214
+ let d = (s[i] ?? "").toString();
215
+ if (!d)
216
+ continue;
217
+ if (i === 0)
218
+ r = d;
219
+ else {
220
+ d = d.replace(/^\/+/, "");
221
+ r = r.replace(/\/+$/, "");
222
+ r = `${r}/${d}`;
223
+ }
224
+ }
225
+ return r;
226
+ }
227
+ /**
228
+ * Returns a full URL.
229
+ * If partial_url is already absolute (starts with http), it is returned as is.
230
+ * Otherwise, it is combined with the base URL.
231
+ */
232
+ function get_full_url(partial_url, domain = null) {
233
+ if (typeof partial_url !== 'string') {
234
+ throw new Error('partial_url must be a string');
235
+ }
236
+ // If it already starts with http, assume it is absolute.
237
+ if (partial_url.startsWith('http')) {
238
+ return partial_url;
239
+ }
240
+ return urlJoin(domain, partial_url);
241
+ }
242
+ /**
243
+ * Returns a full file system path.
244
+ * If partial_path is already absolute, it is returned as is.
245
+ * Otherwise, it is joined with the base directory.
246
+ */
247
+ function get_full_path(partial_path, parent_dir = null) {
248
+ if (typeof partial_path !== 'string') {
249
+ throw new Error('partial_path must be a string');
250
+ }
251
+ if (path.isAbsolute(partial_path)) {
252
+ return partial_path;
253
+ }
254
+ return urlJoin(parent_dir, partial_path);
255
+ }
256
+ /**
257
+ * Converts a local file system path into its corresponding URL.
258
+ * It checks against the known directories in all_paths and replaces the matching base.
259
+ */
260
+ function path_to_url(filePath, all_paths) {
261
+ if (typeof filePath !== 'string') {
262
+ throw new Error('filePath must be a string');
263
+ }
264
+ for (const key in all_paths) {
265
+ const mapping = all_paths[key];
266
+ const normalizedBase = path.normalize(mapping.path);
267
+ if (filePath.startsWith(normalizedBase)) {
268
+ const relativePath = filePath.substring(normalizedBase.length);
269
+ return urlJoin(mapping.url, relativePath.replace(/\\/g, '/'));
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ /**
275
+ * Converts a URL into its corresponding local file system path.
276
+ * It checks against the known URL prefixes in all_paths and replaces the matching base.
277
+ */
278
+ function url_to_path(urlStr, all_paths) {
279
+ if (typeof urlStr !== 'string') {
280
+ throw new Error('urlStr must be a string');
281
+ }
282
+ for (const key in all_paths) {
283
+ const mapping = all_paths[key];
284
+ if (urlStr.startsWith(mapping.url)) {
285
+ const relativeUrl = urlStr.substring(mapping.url.length);
286
+ return urlJoin(mapping.path, relativeUrl);
287
+ }
288
+ }
289
+ return null;
290
+ }
291
+ function urljoin(...parts) {
292
+ return urlJoin(...parts);
293
+ }
294
+
295
+ function split_outside_brackets(s) {
296
+ let depth = 0;
297
+ let start = 0;
298
+ const out = [];
299
+ for (let i = 0; i < s.length; i++) {
300
+ const c = s[i];
301
+ if (c === "[")
302
+ depth++;
303
+ else if (c === "]")
304
+ depth--;
305
+ // split only when NOT inside brackets
306
+ if (c === "," && depth === 0) {
307
+ out.push(s.slice(start, i));
308
+ start = i + 1;
309
+ }
310
+ }
311
+ out.push(s.slice(start));
312
+ return out;
313
+ }
314
+ function parse_nested_list(s) {
315
+ // strip outer brackets
316
+ const inner = s.slice(1, -1).trim();
317
+ const parts = split_outside_brackets(inner);
318
+ const result = [];
319
+ for (let p of parts) {
320
+ p = p.trim();
321
+ if (p.startsWith("[") && p.endsWith("]")) {
322
+ // recursively parse nested list
323
+ result.push(parse_nested_list(p));
324
+ }
325
+ else {
326
+ result.push(p);
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+
332
+ function ensure_list(obj) {
333
+ if (obj == null)
334
+ return [];
335
+ if (Array.isArray(obj)) {
336
+ return obj.flatMap(item => ensure_list(item));
337
+ }
338
+ const s = String(obj).trim();
339
+ if (s.startsWith("[") && s.endsWith("]")) {
340
+ return parse_nested_list(s);
341
+ }
342
+ return split_outside_brackets(s).map(x => x.trim());
343
+ }
344
+ // coerce any single value into a number (0 if it can't)
345
+ function ensure_number(x) {
346
+ const n = Number(x);
347
+ return isNaN(n) ? 0 : n;
348
+ }
349
+ function ensure_string(obj) {
350
+ return String(obj);
351
+ }
352
+ function ensurelist(obj) {
353
+ return ensure_list(obj);
354
+ }
355
+ function assureList(obj) {
356
+ return ensure_list(obj);
357
+ }
358
+ function assure_list(obj) {
359
+ return ensure_list(obj);
360
+ }
361
+ function ensureList(obj) {
362
+ return ensure_list(obj);
363
+ }
364
+ function assurelist(obj) {
365
+ return ensure_list(obj);
366
+ }
367
+ function ensurenumber(x) {
368
+ return ensure_number(x);
369
+ }
370
+ function assureNumber(x) {
371
+ return ensure_number(x);
372
+ }
373
+ function ensureNumber(x) {
374
+ return ensure_number(x);
375
+ }
376
+ function assurenumber(x) {
377
+ return ensure_number(x);
378
+ }
379
+ function assure_number(x) {
380
+ return ensure_number(x);
381
+ }
382
+ function ensurestring(obj) {
383
+ return ensure_string(obj);
384
+ }
385
+ function ensureString(obj) {
386
+ return ensure_string(obj);
387
+ }
388
+ function assureString(obj) {
389
+ return ensure_string(obj);
390
+ }
391
+ function assurestring(obj) {
392
+ return ensure_string(obj);
393
+ }
394
+ function assure_string(obj) {
395
+ return ensure_string(obj);
396
+ }
397
+ function assurearray(obj) {
398
+ return ensure_list(obj);
399
+ }
400
+ function ensurearray(obj) {
401
+ return ensure_list(obj);
402
+ }
403
+ function ensure_array(obj) {
404
+ return ensure_list(obj);
405
+ }
406
+ function ensureArray(obj) {
407
+ return ensure_list(obj);
408
+ }
409
+ function assure_array(obj) {
410
+ return ensure_list(obj);
411
+ }
412
+ function assureArray(obj) {
413
+ return ensure_list(obj);
414
+ }
415
+
416
+ function cleanText(input) {
417
+ // Replace delimiters with spaces and split
418
+ const str = ensure_string(input);
419
+ const words = str.replace(/[_.-]/g, ' '); // Replace _, -, . with space
420
+ return words;
421
+ }
422
+ function cleanArray(obj) {
423
+ obj = ensure_array(obj);
424
+ return Array.from(new Set(obj));
425
+ }
426
+ function getCleanArray(obj) {
427
+ obj = obj.split(/\s+/) // Split on any whitespace
428
+ .filter((item) => typeof item === 'string' && item !== '');
429
+ // Get basename
430
+ // Remove duplicates using Set
431
+ const uniqueWords = cleanArray(obj);
432
+ return uniqueWords;
433
+ }
434
+ // Cache a formatter instance for slightly better performance
435
+ const US_DECIMAL_FORMATTER = new Intl.NumberFormat('en-US', {
436
+ minimumFractionDigits: 2,
437
+ maximumFractionDigits: 2,
438
+ });
439
+ function formatNumber(value) {
440
+ try {
441
+ // coerce to number
442
+ const num = Number(value);
443
+ // if it's NaN or infinite, bail out
444
+ if (!isFinite(num))
445
+ return value;
446
+ return US_DECIMAL_FORMATTER.format(num);
447
+ }
448
+ catch {
449
+ // if anything goes wrong, return the original
450
+ return value;
451
+ }
452
+ }
453
+
454
+ // Constrain T so 'in obj' is allowed
455
+ function get_key_value(obj, key) {
456
+ // we cast to any for the indexing, since TS can’t infer arbitrary string keys
457
+ if (key in obj && obj[key] != null) {
458
+ return obj[key];
459
+ }
460
+ return null;
461
+ }
462
+ function get(obj, keys, defaultValue = null) {
463
+ const keyArray = ensure_array(keys);
464
+ if (!obj || keyArray.length === 0) {
465
+ return defaultValue;
466
+ }
467
+ for (const key of keyArray) {
468
+ const val = get_key_value(obj, key);
469
+ if (val != null) {
470
+ return val;
471
+ }
472
+ }
473
+ return defaultValue;
474
+ }
475
+ // Create the accountInfo table if it doesn't already exist
476
+ function findKeyValue(obj, keyToFind) {
477
+ if (keyToFind in obj)
478
+ return obj[keyToFind];
479
+ for (const key in obj) {
480
+ if (typeof obj[key] === 'object' && obj[key] !== null) {
481
+ const result = findKeyValue(obj[key], keyToFind);
482
+ if (result !== undefined)
483
+ return result;
484
+ }
485
+ }
486
+ return undefined;
487
+ }
488
+ function omitKeys(obj, ...keys) {
489
+ const newObj = { ...obj };
490
+ keys.forEach(key => {
491
+ delete newObj[key];
492
+ });
493
+ return newObj;
494
+ }
495
+ /**
496
+ * Extracts necessary properties from the insertValue to prevent circular references.
497
+ *
498
+ * @param insertValue - The original RPC result.
499
+ * @returns A new object with only the required properties.
500
+ */
501
+ function extractInsertData(insertValue) {
502
+ // Example: Suppose you only need certain fields from the transaction
503
+ // Modify this function based on your actual data structure
504
+ if (insertValue && typeof insertValue === 'object') {
505
+ const { transaction, ...rest } = insertValue; // Exclude 'transaction' property
506
+ return rest;
507
+ }
508
+ return insertValue;
509
+ }
510
+ // Recursive function to load nested JSON
511
+ function loadInnerJson(data) {
512
+ if (typeof data === 'string') {
513
+ try {
514
+ const parsed = JSON.parse(data);
515
+ return loadInnerJson(parsed);
516
+ }
517
+ catch (e) {
518
+ return data;
519
+ }
520
+ }
521
+ else if (Array.isArray(data)) {
522
+ return data.map(item => loadInnerJson(item));
523
+ }
524
+ else if (typeof data === 'object' && data !== null) {
525
+ const result = {};
526
+ for (const key in data) {
527
+ if (data.hasOwnProperty(key)) {
528
+ result[key] = loadInnerJson(data[key]);
529
+ }
530
+ }
531
+ return result;
532
+ }
533
+ return data;
534
+ }
535
+
536
+ function isType(obj, type) {
537
+ if (typeof obj === type) {
538
+ return true;
539
+ }
540
+ return false;
541
+ }
542
+ function isStrInString(obj, string) {
543
+ const obj_str = ensure_string(obj).toLowerCase;
544
+ string = ensure_string(string).toLowerCase;
545
+ if (string.includes(obj_str)) {
546
+ return true;
547
+ }
548
+ return false;
549
+ }
550
+ function getChar(i, string) {
551
+ if (string.length >= i) {
552
+ return ensure_string(string)[i];
553
+ }
554
+ }
555
+ function getAlphaNum(obj) {
556
+ const is_num = isNum(obj);
557
+ const alphas = getAlphas();
558
+ if (is_num) {
559
+ return getChar(obj, alphas);
560
+ }
561
+ if (isStrInString(obj, alphas)) {
562
+ return getChar(obj, alphas);
563
+ }
564
+ }
565
+ function getNums() {
566
+ return '0123456789';
567
+ }
568
+ function isNum(obj) {
569
+ return !Number.isNaN(Number(obj));
570
+ }
571
+ function getAlphas() {
572
+ return 'abcdefghijklmnopqrstuvwxyz';
573
+ }
574
+
575
+ // Function to handle undefined or null values
576
+ function getIfNone(obj, fallback) {
577
+ return obj !== undefined && obj !== null && obj !== '' ? obj : fallback;
578
+ }
579
+ /**
580
+ * Merges non-null values from multiple dictionaries.
581
+ */
582
+ function mergeNotNullValues(dictA, dictB, dictC, dictD, dictE) {
583
+ const result = {};
584
+ for (const key of Object.keys(dictA)) {
585
+ result[key] = dictA[key] ?? dictB?.[key] ?? dictC?.[key] ?? dictD?.[key] ?? dictE?.[key];
586
+ }
587
+ return result;
588
+ }
589
+ /**
590
+ * Converts an empty object to null.
591
+ */
592
+ function emptyObjectToNull(value) {
593
+ return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0 ? null : value;
594
+ }
595
+
596
+ function getSubstring(obj, maxLength = null, minLength = null) {
597
+ const objLength = obj.length;
598
+ const effectiveMaxLength = maxLength ?? objLength; // Use nullish coalescing for clarity
599
+ const effectiveMinLength = minLength ?? 0;
600
+ // Ensure bounds are valid
601
+ const clampedMaxLength = Math.min(Math.max(effectiveMaxLength, 0), objLength);
602
+ const clampedMinLength = Math.min(Math.max(effectiveMinLength, 0), objLength);
603
+ // If minLength exceeds maxLength, return empty string or adjust logic as needed
604
+ if (clampedMinLength >= clampedMaxLength) {
605
+ return '';
606
+ }
607
+ return obj.substring(clampedMinLength, clampedMaxLength);
608
+ }
609
+ /**
610
+ * Sanitize a string by removing null bytes and trimming whitespace.
611
+ */
612
+ function sanitizeString(input) {
613
+ if (!input)
614
+ return input;
615
+ return input.replace(/\u0000/g, "").trim(); // Remove null bytes and whitespace
616
+ }
617
+ function truncateString(obj, maxLength = 20) {
618
+ const objLength = obj.length;
619
+ if (objLength > maxLength && maxLength) {
620
+ obj = getSubstring(obj, maxLength) + '...';
621
+ }
622
+ return obj;
623
+ }
624
+ function capitalize_str(string) {
625
+ string = assureString(string);
626
+ const string_len = string.length;
627
+ let init_char = string.toUpperCase();
628
+ if (string_len > 0) {
629
+ init_char = string[0].toUpperCase();
630
+ }
631
+ let rest_chars = '';
632
+ if (string_len > 1) {
633
+ rest_chars = string.slice(1).toLowerCase();
634
+ }
635
+ const fin_chars = `${init_char}${rest_chars}`;
636
+ return fin_chars;
637
+ }
638
+ function capitalize(string) {
639
+ let nu_string = '';
640
+ string = assureString(string);
641
+ const objs = string.replace('-', '_').split('_');
642
+ for (const obj of objs) {
643
+ const str_obj = capitalize_str(obj);
644
+ nu_string = `${nu_string} ${str_obj}`;
645
+ }
646
+ return eatAll(nu_string, [' ']);
647
+ }
648
+ // string_utils/src/string_utils.ts
649
+ function stripPrefixes(str, bases = []) {
650
+ /* NEW: coerce whatever arrives into a string */
651
+ str = String(str);
652
+ const prefixes = (Array.isArray(bases) ? bases : [bases])
653
+ .filter(Boolean)
654
+ .sort((a, b) => b.length - a.length); // longest first
655
+ let changed = true;
656
+ while (changed) {
657
+ changed = false;
658
+ for (const prefix of prefixes) {
659
+ if (str.startsWith(prefix)) {
660
+ str = str.slice(prefix.length);
661
+ changed = true;
662
+ break; // restart from longest prefix
663
+ }
664
+ }
665
+ }
666
+ return str;
667
+ }
668
+ function tryEatPrefix(str, length, ...objs) {
669
+ str = String(str);
670
+ objs = ensure_list(objs);
671
+ const prefix = str.slice(0, length);
672
+ if (length < 0) {
673
+ const start = str.length + length;
674
+ const actualPrefix = str.slice(start);
675
+ return objs.includes(actualPrefix) ? [str.slice(0, start), true] : [str, false];
676
+ }
677
+ if (objs.includes(prefix)) {
678
+ return [str.slice(length), true];
679
+ }
680
+ return [str, false];
681
+ }
682
+ /** Python-equivalent eatInner */
683
+ function eatInner(str, listObjects) {
684
+ str = String(str);
685
+ const chars = Array.isArray(listObjects) ? listObjects : [listObjects];
686
+ // Keep removing from left while leftmost char is in the set
687
+ while (str.length > 0 && chars.includes(str[0])) {
688
+ str = str.slice(1);
689
+ }
690
+ return str;
691
+ }
692
+ /** Python-equivalent eatOuter */
693
+ function eatOuter(str, listObjects) {
694
+ str = String(str);
695
+ const chars = Array.isArray(listObjects) ? listObjects : [listObjects];
696
+ if (!str || chars.length === 0)
697
+ return str;
698
+ for (let i = 0; i < str.length; i++) {
699
+ if (!str)
700
+ return str;
701
+ const last = str[str.length - 1];
702
+ if (!chars.includes(last)) {
703
+ return str;
704
+ }
705
+ str = str.slice(0, -1);
706
+ }
707
+ return str;
708
+ }
709
+ /** Python-equivalent eatAll */
710
+ function eatAll(str, listObjects) {
711
+ str = String(str);
712
+ const chars = Array.isArray(listObjects) ? listObjects : [listObjects];
713
+ str = eatInner(str, chars);
714
+ str = eatOuter(str, chars);
715
+ return str;
716
+ }
717
+ // Plug in the actual version from your project
718
+ function get_alpha_ints(opts) {
719
+ // REPLACE WITH YOUR REAL IMPLEMENTATION
720
+ return [];
721
+ }
722
+ /** Python-equivalent eatElse */
723
+ function eatElse(stringObj, chars, ints = true, alpha = true, lower = true, capitalize = true, string = true, listObj = true) {
724
+ stringObj = String(stringObj);
725
+ const alphaInts = get_alpha_ints();
726
+ const ls = ensure_list(chars || []).concat(alphaInts);
727
+ while (true) {
728
+ if (!stringObj)
729
+ return stringObj;
730
+ const startOk = !ls.includes(stringObj[0]);
731
+ const endOk = !ls.includes(stringObj[stringObj.length - 1]);
732
+ const shouldEat = startOk || endOk;
733
+ if (!shouldEat)
734
+ return stringObj;
735
+ if (stringObj && startOk) {
736
+ stringObj = stringObj.length === 1 ? "" : stringObj.slice(1);
737
+ }
738
+ if (stringObj && endOk) {
739
+ stringObj = stringObj.length === 1 ? "" : stringObj.slice(0, -1);
740
+ }
741
+ }
742
+ }
743
+ function tryParse(obj) {
744
+ try {
745
+ obj = JSON.stringify(obj);
746
+ }
747
+ catch (err) {
748
+ try {
749
+ obj = JSON.parse(obj);
750
+ }
751
+ catch (err) {
752
+ }
753
+ }
754
+ return obj;
755
+ }
756
+ function create_list_string(array_obj) {
757
+ let string = '';
758
+ for (const obj in array_obj) {
759
+ const array_value = array_obj[obj];
760
+ const parsed_value = tryParse(array_value);
761
+ string += `${obj} == ${parsed_value}\n`;
762
+ }
763
+ return string;
764
+ }
765
+ function eatall(str, listObjects) {
766
+ return eatAll(str, listObjects);
767
+ }
768
+ function eatinner(str, listObjects) {
769
+ return eatInner(str, listObjects);
770
+ }
771
+ function eatouter(str, listObjects) {
772
+ return eatOuter(str, listObjects);
773
+ }
774
+
775
+ /**
776
+ * Checks if a value is enclosed in quotes.
777
+ */
778
+ function ends_in_quotes(value) {
779
+ if (typeof value === 'string') {
780
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
781
+ return true;
782
+ }
783
+ }
784
+ return false;
785
+ }
786
+ function stripQuotes(value) {
787
+ if (ends_in_quotes(value)) {
788
+ return value.slice(1, -1); // Remove the first and last characters
789
+ }
790
+ return value; // Return the input unchanged for all other cases
791
+ }
792
+
793
+ /**
794
+ * In the browser we already have a WHATWG URL constructor on window.
795
+ * Here we re-export it as ā€œurlā€ so other modules can import it.
796
+ */
797
+ /**
798
+ * Minimal fileURLToPath implementation for browser-side code.
799
+ * If you only ever need to strip off ā€œfile://ā€ in development, this is enough.
800
+ */
801
+ function fileURLToPath(fileUrl) {
802
+ // e.g. fileUrl = "file:///Users/foo/bar.txt"
803
+ try {
804
+ const u = new URL(fileUrl);
805
+ return u.pathname;
806
+ }
807
+ catch {
808
+ // fallback: just strip file://
809
+ return fileUrl.replace(/^file:\/\//, '');
810
+ }
811
+ }
812
+ function getAbsolutePath() {
813
+ return fileURLToPath(import.meta.url);
814
+ }
815
+
816
+ function get_dirname(filePath) {
817
+ if (!filePath)
818
+ return '';
819
+ return path$1.dirname(filePath);
820
+ }
821
+ function get_basename(filePath) {
822
+ if (!filePath)
823
+ return '';
824
+ return path$1.basename(filePath);
825
+ }
826
+ function get_filename(filePath) {
827
+ if (!filePath)
828
+ return '';
829
+ const ext = path$1.extname(filePath);
830
+ return path$1.basename(filePath, ext);
831
+ }
832
+ function get_extname(filePath) {
833
+ if (!filePath)
834
+ return '';
835
+ return path$1.extname(filePath);
836
+ }
837
+ function get_splitext(filePath) {
838
+ if (!filePath)
839
+ return { filename: '', extname: '' };
840
+ const ext = path$1.extname(filePath);
841
+ // Get the basename without the extension
842
+ const filename = path$1.basename(filePath, ext);
843
+ return { filename, ext };
844
+ }
845
+ /**
846
+ * Returns the path of `targetPath` relative to `basePath`.
847
+ * Normalizes separators for consistent web and server environments.
848
+ *
849
+ * @param basePath - The base directory you want to compare from.
850
+ * @param targetPath - The full path of the file/directory.
851
+ * @returns A normalized relative path (e.g., "subdir/file.txt").
852
+ */
853
+ function get_relative_path(basePath, targetPath) {
854
+ try {
855
+ // Compute the relative path using Node's native path.relative
856
+ let rel = path$1.relative(basePath, targetPath);
857
+ // Normalize to POSIX-style slashes for consistency (especially on Windows)
858
+ rel = rel.split(path$1.sep).join('/');
859
+ // Avoid empty string (happens if both paths are identical)
860
+ return rel || '.';
861
+ }
862
+ catch (err) {
863
+ console.error(`[get_relative_path] Error computing relative path`, err);
864
+ return targetPath;
865
+ }
866
+ }
867
+ /**
868
+ * Join multiple path segments — clean, predictable, bulletproof.
869
+ *
870
+ * Accepts ANYTHING that ensure_list can handle:
871
+ * • 'a,b,c'
872
+ * • ['a', 'b,c']
873
+ * • 'a/b/c'
874
+ * • '/a/', 'b//c'
875
+ * • mixed arrays, comma strings, whatever
876
+ *
877
+ * Always returns a clean POSIX path string. Never a list.
878
+ */
879
+ function make_path(...parts) {
880
+ // Normalize incoming segments into a flat list
881
+ const segments = ensure_list(parts).map(x => String(x));
882
+ let out = "";
883
+ for (let i = 0; i < segments.length; i++) {
884
+ const seg = segments[i];
885
+ // Normalize a segment:
886
+ let cleaned = eatOuter(seg, "/"); // trim trailing slashes
887
+ if (!cleaned)
888
+ continue;
889
+ if (out === "") {
890
+ out = cleaned;
891
+ }
892
+ else {
893
+ cleaned = eatInner(cleaned, "/"); // trim leading slashes
894
+ out = `${out}/${cleaned}`;
895
+ }
896
+ }
897
+ return out;
898
+ }
899
+ function sanitizeFilename(filename) {
900
+ return filename
901
+ .toLowerCase()
902
+ .replace(/\s+|-/g, '-') // Replace spaces and hyphens with single hyphen
903
+ .replace(/_/g, '-') // Replace underscores with hyphens
904
+ .replace(/[^a-z0-9-.]/g, '') // Remove all non-alphanumeric chars except hyphen and dot
905
+ .replace(/-+/g, '-') // Collapse multiple hyphens into one
906
+ .replace(/^-|-$/, ''); // Remove leading/trailing hyphens
907
+ }
908
+ function make_sanitized_path(...paths) {
909
+ let real_path = '';
910
+ for (let i = 0; i < paths.length; i++) {
911
+ const sanitized = sanitizeFilename(eatOuter(paths[i], '/'));
912
+ if (i === 0) {
913
+ real_path = sanitized;
914
+ }
915
+ else if (sanitized) { // Only append if there's a non-empty segment
916
+ real_path = `${real_path}/${sanitized}`;
917
+ }
918
+ }
919
+ return real_path || '';
920
+ }
921
+ function normalizeUrl(base, p) {
922
+ if (!p)
923
+ return base;
924
+ const cleanBase = base.replace(/\/+$/, ''); // regex literal
925
+ const cleanPath = p.replace(/^\/+/, '');
926
+ // collapse multiple ā€œ//ā€ into one, but keep the ā€œ://ā€ after protocol
927
+ return `${cleanBase}/${cleanPath}`.replace(/([^:])\/{2,}/g, '$1/');
928
+ }
929
+ function pathjoin(...parts) {
930
+ return make_path(...parts);
931
+ }
932
+ function pathJoin(...parts) {
933
+ return make_path(...parts);
934
+ }
935
+ function makepath(...parts) {
936
+ return make_path(...parts);
937
+ }
938
+ function makePath(...parts) {
939
+ return make_path(...parts);
940
+ }
941
+ function path_join(...parts) {
942
+ return make_path(...parts);
943
+ }
944
+ function getSplitext(filePath) {
945
+ return get_splitext(filePath);
946
+ }
947
+ function getsplitext(filePath) {
948
+ return get_splitext(filePath);
949
+ }
950
+ function getextname(filePath) {
951
+ return get_extname(filePath);
952
+ }
953
+ function getExtname(filePath) {
954
+ return get_extname(filePath);
955
+ }
956
+ function getfilename(filePath) {
957
+ return get_filename(filePath);
958
+ }
959
+ function getFilename(filePath) {
960
+ return get_filename(filePath);
961
+ }
962
+ function getbasename(filePath) {
963
+ return get_basename(filePath);
964
+ }
965
+ function getBasename(filePath) {
966
+ return get_basename(filePath);
967
+ }
968
+ function getdirname(filePath) {
969
+ return get_dirname(filePath);
970
+ }
971
+ function getDirname(filePath) {
972
+ return get_dirname(filePath);
973
+ }
974
+
975
+ /**
976
+ * Returns the absolute path of the current file.
977
+ */
978
+ function getAbsDir() {
979
+ return get_dirname(getAbsolutePath());
980
+ }
981
+ function getAbsPath(subPath) {
982
+ return make_path(getAbsDir(), subPath);
983
+ }
984
+
985
+ function getFunctionsDir() {
986
+ return get_dirname(getAbsDir());
987
+ }
988
+ function geAuthsUtilsDirectory() {
989
+ return make_path(getFunctionsDir(), 'auths');
990
+ }
991
+ function geBackupsUtilsDirectory() {
992
+ return make_path(getFunctionsDir(), 'backups');
993
+ }
994
+ function geConstantsUtilsDirectory() {
995
+ return make_path(getFunctionsDir(), 'constants');
996
+ }
997
+ function geEnvUtilsDirectory() {
998
+ return make_path(getFunctionsDir(), 'env_utils');
999
+ }
1000
+ function geFetchUtilsDirectory() {
1001
+ return make_path(getFunctionsDir(), 'fetch_utils');
1002
+ }
1003
+ function geFileUtilsDirectory() {
1004
+ return make_path(getFunctionsDir(), 'file_utils');
1005
+ }
1006
+ function gePathUtilsDirectory() {
1007
+ return make_path(getFunctionsDir(), 'path_utils');
1008
+ }
1009
+ function geStringUtilsDirectory() {
1010
+ return make_path(getFunctionsDir(), 'string_utils');
1011
+ }
1012
+ function geTypeUtilsDirectory() {
1013
+ return make_path(getFunctionsDir(), 'type_utils');
1014
+ }
1015
+
1016
+ function getSrcDir() {
1017
+ return get_dirname(getFunctionsDir());
1018
+ }
1019
+ function geStaticDirectory() {
1020
+ return make_path(getSrcDir(), 'static');
1021
+ }
1022
+ function getLibUtilsDirectory() {
1023
+ return make_path(getSrcDir(), 'lib');
1024
+ }
1025
+ function getHooksUtilsDirectory() {
1026
+ return make_path(getSrcDir(), 'hooks');
1027
+ }
1028
+ function getFunctionsUtilsDirectory() {
1029
+ return make_path(getSrcDir(), 'functions');
1030
+ }
1031
+ function getComponentsUtilsDirectory() {
1032
+ return make_path(getSrcDir(), 'components');
1033
+ }
1034
+
1035
+ function getBaseDir() {
1036
+ return get_dirname(getSrcDir());
1037
+ }
1038
+ function getPublicDir() {
1039
+ return make_path(getBaseDir(), 'public');
1040
+ }
1041
+ function getDistDir() {
1042
+ return make_path(getBaseDir(), 'dist');
1043
+ }
1044
+ function getEnvDir() {
1045
+ return make_path(getBaseDir(), '.env');
1046
+ }
1047
+
1048
+ function getEnvPath(string = '.env') {
1049
+ return make_path(getEnvDir(), string);
1050
+ }
1051
+ function getDbConfigsPath() {
1052
+ return make_path(getBaseDir(), 'dbConfigs');
1053
+ }
1054
+ function getSchemasPath() {
1055
+ return make_path(getDbConfigsPath(), 'schemas');
1056
+ }
1057
+ function getSchemasDirPath(subPath) {
1058
+ return make_path(getSchemasPath(), subPath);
1059
+ }
1060
+
1061
+ // src/functions/rndm_utils/utils.ts
1062
+ function alertit(obj = null) {
1063
+ let msg;
1064
+ try {
1065
+ msg = JSON.stringify(obj);
1066
+ }
1067
+ catch {
1068
+ // If JSON.stringify fails (circular refs, etc.), fall back to a simple string
1069
+ msg = String(obj);
1070
+ }
1071
+ alert(msg);
1072
+ }
1073
+
1074
+ // take N args and coerce them all to numbers
1075
+ function safeNums(...args) {
1076
+ return args.map(ensure_number);
1077
+ }
1078
+ // divide the first value by each of the following
1079
+ function safeAdd(...args) {
1080
+ const [head, ...rest] = safeNums(...args);
1081
+ // if we don’t have a head or any divisor is zero, bail
1082
+ return rest.reduce((acc, d) => acc + d, head);
1083
+ }
1084
+ // divide the first value by each of the following
1085
+ function safeSubtract(...args) {
1086
+ const [head, ...rest] = safeNums(...args);
1087
+ // if we don’t have a head or any divisor is zero, bail
1088
+ return rest.reduce((acc, d) => acc - d, head);
1089
+ }
1090
+ // divide the first value by each of the following
1091
+ function safeDivide(...args) {
1092
+ const [head, ...rest] = safeNums(...args);
1093
+ // if we don’t have a head or any divisor is zero, bail
1094
+ if (head === 0 || rest.some((d) => d === 0))
1095
+ return 0;
1096
+ return rest.reduce((acc, d) => acc / d, head);
1097
+ }
1098
+ // multiply all the values together
1099
+ function safeMultiply(...args) {
1100
+ const nums = safeNums(...args);
1101
+ // if any number is zero, result is zero
1102
+ if (nums.includes(0))
1103
+ return 0;
1104
+ return nums.reduce((acc, n) => acc * n, 1);
1105
+ }
1106
+ // round a value to two decimals by percent
1107
+ function roundPercentage(x) {
1108
+ const pct = safeMultiply(ensure_number(x), 100);
1109
+ return safeDivide(Math.round(pct), 100);
1110
+ }
1111
+ function exponential(i, k) {
1112
+ return i * (10 ** (k));
1113
+ }
1114
+ function isZero(obj) {
1115
+ if (obj == 0) {
1116
+ return true;
1117
+ }
1118
+ return false;
1119
+ }
1120
+
1121
+ const SECOND = 1;
1122
+ const ZEPTOSECOND = exponential(SECOND, -21);
1123
+ const ATTOSECOND = exponential(SECOND, -18);
1124
+ const FEMTOSECOND = exponential(SECOND, -15);
1125
+ const PICOSECOND = exponential(SECOND, -12);
1126
+ const NANOSECOND = exponential(SECOND, -9);
1127
+ const MICROSECOND = exponential(SECOND, -6);
1128
+ const MILISECOND = exponential(SECOND, -3);
1129
+ const CENTISECOND = exponential(SECOND, -2);
1130
+ const DECISECOND = exponential(SECOND, -1);
1131
+ const MINUTE = 60 * SECOND;
1132
+ const HOUR = 60 * MINUTE;
1133
+ const DAY = 24 * HOUR;
1134
+ const YEAR = 365 * DAY;
1135
+ const MONTH = YEAR / 12;
1136
+ // Derived: explicit names
1137
+ const SECONDS_PER_MINUTE = MINUTE;
1138
+ const SECONDS_PER_HOUR = HOUR;
1139
+ const SECONDS_PER_DAY = DAY;
1140
+ //math
1141
+ const PI = Math.PI;
1142
+ const PI2 = 2 * PI;
1143
+ // Distance
1144
+ const METERS_PER_KM = 1000;
1145
+ const METERS_PER_MILE = 1609.34;
1146
+ const METERS_PER_FOOT = 0.3048;
1147
+ const KMS_PER_METER = 1 / METERS_PER_KM;
1148
+ const MILES_PER_METER = 1 / METERS_PER_MILE;
1149
+ const FEET_PER_METER = 1 / METERS_PER_FOOT;
1150
+ const MIN_IN_S = 1 / MINUTE;
1151
+ const HOUR_IN_S = 1 / HOUR;
1152
+ const DAY_IN_S = 1 / DAY;
1153
+ const YEAR_IN_S = 1 / YEAR;
1154
+ const MONTH_IN_S = 1 / MONTH;
1155
+ const MiPerH_TO_MPerS = METERS_PER_MILE * HOUR_IN_S;
1156
+ const MPerS_TO_MiPerH = 1 / MiPerH_TO_MPerS;
1157
+
1158
+ // conversions.ts
1159
+ /*───────────────────────────────────────────────────────────────
1160
+ 🧭 CANONICAL MAPPINGS
1161
+ ───────────────────────────────────────────────────────────────*/
1162
+ const DIST_ALIASES = {
1163
+ m: "m", meter: "m", meters: "m",
1164
+ km: "km", kms: "km", kilometer: "km", kilometers: "km",
1165
+ mi: "mi", mile: "mi", miles: "mi",
1166
+ ft: "ft", f: "ft", foot: "ft", feet: "ft",
1167
+ };
1168
+ const TIME_ALIASES = {
1169
+ s: "s", sec: "s", second: "s", seconds: "s",
1170
+ min: "min", m: "min", minute: "min", minutes: "min",
1171
+ h: "h", hr: "h", hour: "h", hours: "h",
1172
+ day: "day", d: "day", days: "day",
1173
+ };
1174
+ const DIST_FACTORS = {
1175
+ m: 1,
1176
+ km: METERS_PER_KM,
1177
+ mi: METERS_PER_MILE,
1178
+ ft: METERS_PER_FOOT,
1179
+ };
1180
+ const TIME_FACTORS = {
1181
+ s: 1,
1182
+ min: MINUTE,
1183
+ h: HOUR,
1184
+ day: DAY,
1185
+ };
1186
+ /*───────────────────────────────────────────────────────────────
1187
+ šŸ” CANONICALIZATION HELPERS
1188
+ ───────────────────────────────────────────────────────────────*/
1189
+ function canonDist(u) {
1190
+ const key = (u ?? "m").toString().toLowerCase();
1191
+ const canon = DIST_ALIASES[key];
1192
+ if (!canon)
1193
+ throw new Error(`Unknown distance unit: ${u}`);
1194
+ return canon;
1195
+ }
1196
+ function canonTime(u) {
1197
+ const key = (u ?? "s").toString().toLowerCase();
1198
+ const canon = TIME_ALIASES[key];
1199
+ if (!canon)
1200
+ throw new Error(`Unknown time unit: ${u}`);
1201
+ return canon;
1202
+ }
1203
+ /*───────────────────────────────────────────────────────────────
1204
+ āš–ļø NORMALIZATION HELPERS
1205
+ ───────────────────────────────────────────────────────────────*/
1206
+ function distanceToMeters(d, unit) {
1207
+ const u = canonDist(unit);
1208
+ return safeMultiply(d, DIST_FACTORS[u]);
1209
+ }
1210
+ function metersToDistance(v, unit) {
1211
+ const u = canonDist(unit);
1212
+ return safeDivide(v, DIST_FACTORS[u]);
1213
+ }
1214
+ function timeToSeconds(t, unit) {
1215
+ const u = canonTime(unit);
1216
+ return safeMultiply(t, TIME_FACTORS[u]);
1217
+ }
1218
+ function secondsToTime(v, unit) {
1219
+ const u = canonTime(unit);
1220
+ return safeDivide(v, TIME_FACTORS[u]);
1221
+ }
1222
+ /*───────────────────────────────────────────────────────────────
1223
+ šŸš€ SPEED CONVERSIONS (normalize / unnormalize)
1224
+ ───────────────────────────────────────────────────────────────*/
1225
+ function speedToMps(v, distUnit, timeUnit) {
1226
+ const du = canonDist(distUnit);
1227
+ const tu = canonTime(timeUnit);
1228
+ return v * (DIST_FACTORS[du] / TIME_FACTORS[tu]);
1229
+ }
1230
+ function mpsToSpeed(vMps, distUnit, timeUnit) {
1231
+ const du = canonDist(distUnit);
1232
+ const tu = canonTime(timeUnit);
1233
+ return vMps * (TIME_FACTORS[tu] / DIST_FACTORS[du]);
1234
+ }
1235
+ /*───────────────────────────────────────────────────────────────
1236
+ šŸŽÆ UNIVERSAL CONVERTERS
1237
+ ───────────────────────────────────────────────────────────────*/
1238
+ function convertDistance({ d, fromDist, toDist, vOnly = true, }) {
1239
+ const m = distanceToMeters(d, fromDist);
1240
+ const D = canonDist(toDist ?? "m");
1241
+ const out = metersToDistance(m, D);
1242
+ return vOnly ? out : { d: out, D };
1243
+ }
1244
+ function convertTime({ t, fromTime, toTime, vOnly = true, }) {
1245
+ const sec = timeToSeconds(t, fromTime);
1246
+ const T = canonTime(toTime ?? "s");
1247
+ const out = secondsToTime(sec, T);
1248
+ return vOnly ? out : { t: out, T };
1249
+ }
1250
+ function convertSpeed({ v, fromDist, fromTime, toDist, toTime, vOnly = true, }) {
1251
+ const mps = speedToMps(v, fromDist, fromTime);
1252
+ const d = canonDist(toDist ?? "m");
1253
+ const t = canonTime(toTime ?? "s");
1254
+ const out = mpsToSpeed(mps, d, t);
1255
+ return vOnly ? out : { v: out, d, t };
1256
+ }
1257
+ const DistanceConverter = {
1258
+ normalize: distanceToMeters,
1259
+ unnormalize: metersToDistance,
1260
+ };
1261
+ const TimeConverter = {
1262
+ normalize: timeToSeconds,
1263
+ unnormalize: secondsToTime,
1264
+ };
1265
+ const SpeedConverter = {
1266
+ normalize: (v, [du, tu]) => speedToMps(v, du, tu),
1267
+ unnormalize: (v, [du, tu]) => mpsToSpeed(v, du, tu),
1268
+ };
1269
+ /*───────────────────────────────────────────────────────────────
1270
+ 🧩 COMPATIBILITY WRAPPERS (legacy aliases)
1271
+ ───────────────────────────────────────────────────────────────*/
1272
+ const toMeters = distanceToMeters;
1273
+ const fromMeters = metersToDistance;
1274
+ const toSeconds = timeToSeconds;
1275
+ const fromSeconds = secondsToTime;
1276
+ const velocityToMs = (value, unit) => speedToMps(value, unit, "s");
1277
+ const velocityFromMs = (value, unit) => mpsToSpeed(value, unit, "s");
1278
+ /** Non-canonical helper for arbitrary rate conversion, e.g. ft/day → m/s */
1279
+ const fromMps = (v, dist_unit, time_unit) => mpsToSpeed(v, dist_unit, time_unit);
1280
+ /*───────────────────────────────────────────────────────────────
1281
+ šŸ“Š UTILITIES
1282
+ ───────────────────────────────────────────────────────────────*/
1283
+ const isFiniteNum = (x) => Number.isFinite(x);
1284
+ const fmt = (n, digits = 2) => isFiniteNum(n) ? n.toFixed(digits) : "N/A";
1285
+
1286
+ // Function to check time interval
1287
+ function isTimeInterval(timeObj, interval) {
1288
+ return (Date.now() / 1000 - timeObj) < (interval - 1);
1289
+ }
1290
+
1291
+ /**
1292
+ * Recursively traverse the object and convert BigInts to numbers or strings.
1293
+ *
1294
+ * @param {object|array} obj - The object to traverse
1295
+ * @param {boolean} convertToNumber - Whether to convert BigInt to Number (default is true)
1296
+ * @returns {object|array} - The transformed object
1297
+ */
1298
+ function convertBigInts(obj, convertToNumber = true) {
1299
+ if (obj === null || obj === undefined)
1300
+ return obj;
1301
+ try {
1302
+ if (typeof obj === 'bigint') {
1303
+ return convertToNumber ? Number(obj) : obj.toString();
1304
+ }
1305
+ if (typeof obj === 'object') {
1306
+ if (Array.isArray(obj)) {
1307
+ return obj.map((item) => convertBigInts(item, convertToNumber));
1308
+ }
1309
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, convertBigInts(value, convertToNumber)]));
1310
+ }
1311
+ }
1312
+ catch (error) {
1313
+ }
1314
+ return obj;
1315
+ }
1316
+
1317
+ function getSafeDocument() {
1318
+ return typeof document !== 'undefined' ? document : undefined;
1319
+ }
1320
+ function getDocumentProp(...keys) {
1321
+ let obj = getSafeDocument();
1322
+ for (const k of keys) {
1323
+ if (obj == null || typeof obj !== 'object')
1324
+ return undefined;
1325
+ obj = obj[k];
1326
+ }
1327
+ return obj;
1328
+ }
1329
+
1330
+ /**
1331
+ * Returns the global window object if it exists, otherwise undefined.
1332
+ */
1333
+ function getSafeWindow() {
1334
+ return typeof window !== 'undefined' ? window : undefined;
1335
+ }
1336
+ /**
1337
+ * Safely call a method on window by name.
1338
+ *
1339
+ * @param method The Window method to call (e.g. "alert", "open", etc.).
1340
+ * @param args Arguments to pass to that method.
1341
+ * @returns The method’s return value, or undefined if
1342
+ * window/method isn’t available or throws.
1343
+ */
1344
+ function callWindowMethod(method, ...args) {
1345
+ const w = getSafeWindow();
1346
+ if (!w)
1347
+ return undefined;
1348
+ const fn = w[method];
1349
+ if (typeof fn !== 'function')
1350
+ return undefined;
1351
+ try {
1352
+ // cast to any so TS doesn’t complain about apply/invoke
1353
+ return fn(...args);
1354
+ }
1355
+ catch {
1356
+ return undefined;
1357
+ }
1358
+ }
1359
+ /** implementation */
1360
+ function getWindowProp(...keys) {
1361
+ let obj = getSafeWindow();
1362
+ for (const k of keys) {
1363
+ if (obj == null || typeof obj !== 'object')
1364
+ return undefined;
1365
+ obj = obj[k];
1366
+ }
1367
+ return obj;
1368
+ }
1369
+ function getWindowHost() {
1370
+ return getWindowProp('location', 'host');
1371
+ }
1372
+
1373
+ async function readJsonFileBrowser(url) {
1374
+ const fetchFn = safeGlobalProp("fetch");
1375
+ if (typeof fetchFn !== "function")
1376
+ return null;
1377
+ try {
1378
+ const res = await fetchFn(url);
1379
+ if (!res.ok)
1380
+ return null;
1381
+ return (await res.json());
1382
+ }
1383
+ catch {
1384
+ return null;
1385
+ }
1386
+ }
1387
+
1388
+ var readJsonFile_browser = /*#__PURE__*/Object.freeze({
1389
+ __proto__: null,
1390
+ readJsonFileBrowser: readJsonFileBrowser
1391
+ });
1392
+
1393
+ function readJsonFileNode(relativeOrAbsolutePath) {
1394
+ try {
1395
+ const filePath = isAbsolute(relativeOrAbsolutePath)
1396
+ ? relativeOrAbsolutePath
1397
+ : resolve(process.cwd(), relativeOrAbsolutePath);
1398
+ return JSON.parse(readFileSync(filePath, "utf8"));
1399
+ }
1400
+ catch {
1401
+ return null;
1402
+ }
1403
+ }
1404
+
1405
+ var readJsonFile_node = /*#__PURE__*/Object.freeze({
1406
+ __proto__: null,
1407
+ readJsonFileNode: readJsonFileNode
1408
+ });
1409
+
1410
+ async function readJsonFile(relativeOrAbsolutePath) {
1411
+ if (typeof process !== "undefined" && process.versions?.node) {
1412
+ const mod = await Promise.resolve().then(function () { return readJsonFile_node; });
1413
+ return mod.readJsonFileNode(relativeOrAbsolutePath);
1414
+ }
1415
+ else {
1416
+ const mod = await Promise.resolve().then(function () { return readJsonFile_browser; });
1417
+ return mod.readJsonFileBrowser(relativeOrAbsolutePath);
1418
+ }
1419
+ }
1420
+ async function getConfigContent() {
1421
+ try {
1422
+ // `readJsonFile` should throw if the file isn’t there or isn’t valid JSON
1423
+ const cfg = await readJsonFile('./config.json');
1424
+ return cfg;
1425
+ }
1426
+ catch {
1427
+ // swallow errors & return null so callers can detect ā€œno configā€
1428
+ return null;
1429
+ }
1430
+ }
1431
+
1432
+ // src/functions/config_utils/src/config_utils.ts
1433
+ let _cachedConfig = null;
1434
+ async function loadConfig(filePath = null) {
1435
+ if (_cachedConfig) {
1436
+ return _cachedConfig;
1437
+ }
1438
+ // 1) figure out where config.json lives
1439
+ let configUrl;
1440
+ if (filePath) {
1441
+ configUrl = filePath;
1442
+ }
1443
+ else if (typeof import.meta !== 'undefined' && typeof import.meta.url === 'string') {
1444
+ // ES module: resolve relative to this file
1445
+ try {
1446
+ const mod = await (new Function("return import('./config.json').catch(() => ({}))"))();
1447
+ _cachedConfig = mod.default ?? {};
1448
+ return _cachedConfig;
1449
+ }
1450
+ catch {
1451
+ configUrl = 'config.json';
1452
+ }
1453
+ }
1454
+ else {
1455
+ // browser fallback
1456
+ const baseURI = safeGlobalProp('document', 'baseURI');
1457
+ try {
1458
+ configUrl =
1459
+ typeof baseURI === 'string'
1460
+ ? new URL('config.json', baseURI).href
1461
+ : 'config.json';
1462
+ }
1463
+ catch {
1464
+ configUrl = 'config.json';
1465
+ }
1466
+ }
1467
+ // 2) if we have a fetch, try HTTP(S)
1468
+ const fetchFn = safeGlobalProp('fetch');
1469
+ if (typeof fetchFn === 'function') {
1470
+ try {
1471
+ const res = await fetchFn(configUrl);
1472
+ if (res.ok) {
1473
+ const json = await res.json();
1474
+ // cache & return
1475
+ _cachedConfig = json ?? {};
1476
+ return _cachedConfig;
1477
+ }
1478
+ }
1479
+ catch {
1480
+ /* swallow */
1481
+ }
1482
+ }
1483
+ // 3) Node fallback: try reading from disk (requires your readJsonFile util)
1484
+ try {
1485
+ const disk = await readJsonFile(configUrl);
1486
+ _cachedConfig = disk ?? {};
1487
+ return _cachedConfig;
1488
+ }
1489
+ catch {
1490
+ /* swallow */
1491
+ }
1492
+ // 4) if all else fails, return an empty config
1493
+ _cachedConfig = {};
1494
+ return _cachedConfig;
1495
+ }
1496
+ async function getConfig(key) {
1497
+ const cfg = await loadConfig();
1498
+ return key != null ? cfg[key] : cfg;
1499
+ }
1500
+
1501
+ /**
1502
+ * Processes keywords by checking if keywords is a string and splitting it.
1503
+ * Then cleans each keyword using `eatAll` with a set of characters to remove.
1504
+ *
1505
+ * @param keywords - The keywords as a comma-separated string or as an array.
1506
+ * @returns An array of cleaned keywords.
1507
+ */
1508
+ function processKeywords(keywords) {
1509
+ let keywordArray;
1510
+ // If keywords is a string, split it on commas
1511
+ if (typeof keywords === "string") {
1512
+ keywordArray = keywords.split(",");
1513
+ }
1514
+ else {
1515
+ keywordArray = keywords;
1516
+ }
1517
+ // Clean each keyword by removing unwanted characters
1518
+ return keywordArray.map(keyword => eatAll(keyword, [",", "\n", "\t", " ", "#"]));
1519
+ }
1520
+ /**
1521
+ * Constructs a keyword string where each keyword is prefixed with a hash (#).
1522
+ *
1523
+ * @param keywords - An array of keywords.
1524
+ * @returns A string with each keyword prefixed by '#'.
1525
+ */
1526
+ function get_keyword_string(keywords) {
1527
+ keywords = processKeywords(keywords);
1528
+ let allString = "";
1529
+ for (const keyword of keywords) {
1530
+ allString += ` #${keyword}`;
1531
+ }
1532
+ return allString;
1533
+ }
1534
+
1535
+ // Function to compare MB
1536
+ function exceedsMbLimit(limitMb, payloadMb) {
1537
+ return payloadMb > limitMb;
1538
+ }
1539
+ function safeJsonSizeInMb(value) {
1540
+ const seen = new WeakSet();
1541
+ const json = JSON.stringify(value, (_, v) => {
1542
+ if (typeof v === "bigint")
1543
+ return v.toString();
1544
+ if (typeof v === "object" && v !== null) {
1545
+ if (seen.has(v))
1546
+ return "[Circular]";
1547
+ seen.add(v);
1548
+ }
1549
+ return v;
1550
+ });
1551
+ return Buffer.byteLength(json, "utf8") / (1024 * 1024);
1552
+ }
1553
+ function dataSizeInMb(data) {
1554
+ const size = typeof data === "string"
1555
+ ? Buffer.byteLength(data, "utf8")
1556
+ : Buffer.byteLength(JSON.stringify(data), "utf8");
1557
+ return size / (1024 * 1024);
1558
+ }
1559
+ function getJsonSizeInMb(json) {
1560
+ return Buffer.byteLength(JSON.stringify(json), "utf8") / (1024 * 1024);
1561
+ }
1562
+ // Function to calculate data size in KB
1563
+ function dataSize(data) {
1564
+ let size = 0;
1565
+ if (typeof data === 'string') {
1566
+ size = Buffer.byteLength(data, 'utf8');
1567
+ }
1568
+ else if (Buffer.isBuffer(data)) {
1569
+ size = data.length;
1570
+ }
1571
+ else if (typeof data === 'object') {
1572
+ size = Buffer.byteLength(JSON.stringify(data), 'utf8');
1573
+ }
1574
+ else {
1575
+ size = Buffer.byteLength(String(data), 'utf8');
1576
+ }
1577
+ return size / 1000; // Convert to kilobytes
1578
+ }
1579
+
1580
+ function getLastCaller(skip = ["debugPrint"]) {
1581
+ const stack = new Error().stack;
1582
+ if (!stack)
1583
+ return null;
1584
+ const lines = stack
1585
+ .split("\n")
1586
+ .map(l => l.trim())
1587
+ .slice(1); // drop "Error"
1588
+ for (const line of lines) {
1589
+ // Example:
1590
+ // at processSingleAddress (/path/file.ts:142:7)
1591
+ const match = line.match(/at (.+?) \((.+?):(\d+):(\d+)\)/) ||
1592
+ line.match(/at (.+?):(\d+):(\d+)/);
1593
+ if (!match)
1594
+ continue;
1595
+ const functionName = match[1] ?? "anonymous";
1596
+ if (skip.includes(functionName))
1597
+ continue;
1598
+ return {
1599
+ functionName,
1600
+ file: match[2],
1601
+ line: Number(match[3]),
1602
+ column: Number(match[4]),
1603
+ };
1604
+ }
1605
+ return null;
1606
+ }
1607
+
1608
+ function debugPrint(value, label = null) {
1609
+ const caller = getLastCaller();
1610
+ const header = label ??
1611
+ (caller
1612
+ ? `${caller.functionName} @ ${caller.file}:${caller.line}`
1613
+ : "object");
1614
+ console.log(`\nšŸ” ${header}`);
1615
+ console.log(inspect(value, {
1616
+ depth: null,
1617
+ colors: true,
1618
+ compact: false,
1619
+ maxArrayLength: null,
1620
+ }));
1621
+ }
1622
+
1623
+ export { getAbsDir as $, API_PREFIX as A, BASE_URL as B, get_extname as C, DOMAIN_NAME as D, get_splitext as E, get_relative_path as F, make_path as G, sanitizeFilename as H, make_sanitized_path as I, normalizeUrl as J, pathjoin as K, pathJoin as L, makepath as M, makePath as N, path_join as O, PROTOCOL as P, getSplitext as Q, getsplitext as R, SUB_DIR as S, getextname as T, getExtname as U, getfilename as V, getFilename as W, getbasename as X, getBasename as Y, getdirname as Z, getDirname as _, PROD_PREFIX as a, mpsToSpeed as a$, getAbsPath as a0, getFunctionsDir as a1, geAuthsUtilsDirectory as a2, geBackupsUtilsDirectory as a3, geConstantsUtilsDirectory as a4, geEnvUtilsDirectory as a5, geFetchUtilsDirectory as a6, geFileUtilsDirectory as a7, gePathUtilsDirectory as a8, geStringUtilsDirectory as a9, eatElse as aA, tryParse as aB, create_list_string as aC, eatall as aD, eatinner as aE, eatouter as aF, ends_in_quotes as aG, stripQuotes as aH, safeNums as aI, safeAdd as aJ, safeSubtract as aK, safeDivide as aL, safeMultiply as aM, roundPercentage as aN, exponential as aO, isZero as aP, DIST_ALIASES as aQ, TIME_ALIASES as aR, DIST_FACTORS as aS, TIME_FACTORS as aT, canonDist as aU, canonTime as aV, distanceToMeters as aW, metersToDistance as aX, timeToSeconds as aY, secondsToTime as aZ, speedToMps as a_, geTypeUtilsDirectory as aa, getSrcDir as ab, geStaticDirectory as ac, getLibUtilsDirectory as ad, getHooksUtilsDirectory as ae, getFunctionsUtilsDirectory as af, getComponentsUtilsDirectory as ag, getBaseDir as ah, getPublicDir as ai, getDistDir as aj, getEnvDir as ak, getEnvPath as al, getDbConfigsPath as am, getSchemasPath as an, getSchemasDirPath as ao, alertit as ap, getSubstring as aq, sanitizeString as ar, truncateString as as, capitalize_str as at, capitalize as au, stripPrefixes as av, tryEatPrefix as aw, eatInner as ax, eatOuter as ay, eatAll as az, DEV_PREFIX as b, assureNumber as b$, convertDistance as b0, convertTime as b1, convertSpeed as b2, DistanceConverter as b3, TimeConverter as b4, SpeedConverter as b5, toMeters as b6, fromMeters as b7, toSeconds as b8, fromSeconds as b9, METERS_PER_MILE as bA, METERS_PER_FOOT as bB, KMS_PER_METER as bC, MILES_PER_METER as bD, FEET_PER_METER as bE, MIN_IN_S as bF, HOUR_IN_S as bG, DAY_IN_S as bH, YEAR_IN_S as bI, MONTH_IN_S as bJ, MiPerH_TO_MPerS as bK, MPerS_TO_MiPerH as bL, isTimeInterval as bM, convertBigInts as bN, cleanText as bO, cleanArray as bP, getCleanArray as bQ, formatNumber as bR, ensure_list as bS, ensure_number as bT, ensure_string as bU, ensurelist as bV, assureList as bW, assure_list as bX, ensureList as bY, assurelist as bZ, ensurenumber as b_, velocityToMs as ba, velocityFromMs as bb, fromMps as bc, isFiniteNum as bd, fmt as be, SECOND as bf, ZEPTOSECOND as bg, ATTOSECOND as bh, FEMTOSECOND as bi, PICOSECOND as bj, NANOSECOND as bk, MICROSECOND as bl, MILISECOND as bm, CENTISECOND as bn, DECISECOND as bo, MINUTE as bp, HOUR as bq, DAY as br, YEAR as bs, MONTH as bt, SECONDS_PER_MINUTE as bu, SECONDS_PER_HOUR as bv, SECONDS_PER_DAY as bw, PI as bx, PI2 as by, METERS_PER_KM as bz, get_window_location as c, ensureNumber as c0, assurenumber as c1, assure_number as c2, ensurestring as c3, ensureString as c4, assureString as c5, assurestring as c6, assure_string as c7, assurearray as c8, ensurearray as c9, getSafeDocument as cA, getDocumentProp as cB, getSafeWindow as cC, callWindowMethod as cD, getWindowProp as cE, getWindowHost as cF, processKeywords as cG, get_keyword_string as cH, exceedsMbLimit as cI, safeJsonSizeInMb as cJ, dataSizeInMb as cK, getJsonSizeInMb as cL, dataSize as cM, debugPrint as cN, getLastCaller as cO, ensure_array as ca, ensureArray as cb, assure_array as cc, assureArray as cd, get_key_value as ce, get as cf, findKeyValue as cg, omitKeys as ch, extractInsertData as ci, loadInnerJson as cj, isType as ck, isStrInString as cl, getChar as cm, getAlphaNum as cn, getNums as co, isNum as cp, getAlphas as cq, getIfNone as cr, mergeNotNullValues as cs, emptyObjectToNull as ct, loadConfig as cu, getConfig as cv, readJsonFileBrowser as cw, readJsonFileNode as cx, readJsonFile as cy, getConfigContent as cz, get_window_pathname as d, get_window_parts as e, fetchIt as f, get_window as g, getHtmlDirectory as h, fetchIndexHtml as i, fetchIndexHtmlContainer as j, getResult as k, getMethod as l, getHeaders as m, getBody as n, getFetchVars as o, parseResult as p, checkResponse as q, get_full_url as r, get_full_path as s, path_to_url as t, urlJoin as u, url_to_path as v, urljoin as w, get_dirname as x, get_basename as y, get_filename as z };
1624
+ //# sourceMappingURL=print_utils-p0I6-E-k.js.map