@putkoff/abstract-utilities 1.0.126 → 1.0.128

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,1612 @@
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 safeDivide(...args) {
1080
+ const [head, ...rest] = safeNums(...args);
1081
+ // if we don’t have a head or any divisor is zero, bail
1082
+ if (head === 0 || rest.some((d) => d === 0))
1083
+ return 0;
1084
+ return rest.reduce((acc, d) => acc / d, head);
1085
+ }
1086
+ // multiply all the values together
1087
+ function safeMultiply(...args) {
1088
+ const nums = safeNums(...args);
1089
+ // if any number is zero, result is zero
1090
+ if (nums.includes(0))
1091
+ return 0;
1092
+ return nums.reduce((acc, n) => acc * n, 1);
1093
+ }
1094
+ // round a value to two decimals by percent
1095
+ function roundPercentage(x) {
1096
+ const pct = safeMultiply(ensure_number(x), 100);
1097
+ return safeDivide(Math.round(pct), 100);
1098
+ }
1099
+ function exponential(i, k) {
1100
+ return i * (10 ** (k));
1101
+ }
1102
+ function isZero(obj) {
1103
+ if (obj == 0) {
1104
+ return true;
1105
+ }
1106
+ return false;
1107
+ }
1108
+
1109
+ const SECOND = 1;
1110
+ const ZEPTOSECOND = exponential(SECOND, -21);
1111
+ const ATTOSECOND = exponential(SECOND, -18);
1112
+ const FEMTOSECOND = exponential(SECOND, -15);
1113
+ const PICOSECOND = exponential(SECOND, -12);
1114
+ const NANOSECOND = exponential(SECOND, -9);
1115
+ const MICROSECOND = exponential(SECOND, -6);
1116
+ const MILISECOND = exponential(SECOND, -3);
1117
+ const CENTISECOND = exponential(SECOND, -2);
1118
+ const DECISECOND = exponential(SECOND, -1);
1119
+ const MINUTE = 60 * SECOND;
1120
+ const HOUR = 60 * MINUTE;
1121
+ const DAY = 24 * HOUR;
1122
+ const YEAR = 365 * DAY;
1123
+ const MONTH = YEAR / 12;
1124
+ // Derived: explicit names
1125
+ const SECONDS_PER_MINUTE = MINUTE;
1126
+ const SECONDS_PER_HOUR = HOUR;
1127
+ const SECONDS_PER_DAY = DAY;
1128
+ //math
1129
+ const PI = Math.PI;
1130
+ const PI2 = 2 * PI;
1131
+ // Distance
1132
+ const METERS_PER_KM = 1000;
1133
+ const METERS_PER_MILE = 1609.34;
1134
+ const METERS_PER_FOOT = 0.3048;
1135
+ const KMS_PER_METER = 1 / METERS_PER_KM;
1136
+ const MILES_PER_METER = 1 / METERS_PER_MILE;
1137
+ const FEET_PER_METER = 1 / METERS_PER_FOOT;
1138
+ const MIN_IN_S = 1 / MINUTE;
1139
+ const HOUR_IN_S = 1 / HOUR;
1140
+ const DAY_IN_S = 1 / DAY;
1141
+ const YEAR_IN_S = 1 / YEAR;
1142
+ const MONTH_IN_S = 1 / MONTH;
1143
+ const MiPerH_TO_MPerS = METERS_PER_MILE * HOUR_IN_S;
1144
+ const MPerS_TO_MiPerH = 1 / MiPerH_TO_MPerS;
1145
+
1146
+ // conversions.ts
1147
+ /*───────────────────────────────────────────────────────────────
1148
+ 🧭 CANONICAL MAPPINGS
1149
+ ───────────────────────────────────────────────────────────────*/
1150
+ const DIST_ALIASES = {
1151
+ m: "m", meter: "m", meters: "m",
1152
+ km: "km", kms: "km", kilometer: "km", kilometers: "km",
1153
+ mi: "mi", mile: "mi", miles: "mi",
1154
+ ft: "ft", f: "ft", foot: "ft", feet: "ft",
1155
+ };
1156
+ const TIME_ALIASES = {
1157
+ s: "s", sec: "s", second: "s", seconds: "s",
1158
+ min: "min", m: "min", minute: "min", minutes: "min",
1159
+ h: "h", hr: "h", hour: "h", hours: "h",
1160
+ day: "day", d: "day", days: "day",
1161
+ };
1162
+ const DIST_FACTORS = {
1163
+ m: 1,
1164
+ km: METERS_PER_KM,
1165
+ mi: METERS_PER_MILE,
1166
+ ft: METERS_PER_FOOT,
1167
+ };
1168
+ const TIME_FACTORS = {
1169
+ s: 1,
1170
+ min: MINUTE,
1171
+ h: HOUR,
1172
+ day: DAY,
1173
+ };
1174
+ /*───────────────────────────────────────────────────────────────
1175
+ šŸ” CANONICALIZATION HELPERS
1176
+ ───────────────────────────────────────────────────────────────*/
1177
+ function canonDist(u) {
1178
+ const key = (u ?? "m").toString().toLowerCase();
1179
+ const canon = DIST_ALIASES[key];
1180
+ if (!canon)
1181
+ throw new Error(`Unknown distance unit: ${u}`);
1182
+ return canon;
1183
+ }
1184
+ function canonTime(u) {
1185
+ const key = (u ?? "s").toString().toLowerCase();
1186
+ const canon = TIME_ALIASES[key];
1187
+ if (!canon)
1188
+ throw new Error(`Unknown time unit: ${u}`);
1189
+ return canon;
1190
+ }
1191
+ /*───────────────────────────────────────────────────────────────
1192
+ āš–ļø NORMALIZATION HELPERS
1193
+ ───────────────────────────────────────────────────────────────*/
1194
+ function distanceToMeters(d, unit) {
1195
+ const u = canonDist(unit);
1196
+ return safeMultiply(d, DIST_FACTORS[u]);
1197
+ }
1198
+ function metersToDistance(v, unit) {
1199
+ const u = canonDist(unit);
1200
+ return safeDivide(v, DIST_FACTORS[u]);
1201
+ }
1202
+ function timeToSeconds(t, unit) {
1203
+ const u = canonTime(unit);
1204
+ return safeMultiply(t, TIME_FACTORS[u]);
1205
+ }
1206
+ function secondsToTime(v, unit) {
1207
+ const u = canonTime(unit);
1208
+ return safeDivide(v, TIME_FACTORS[u]);
1209
+ }
1210
+ /*───────────────────────────────────────────────────────────────
1211
+ šŸš€ SPEED CONVERSIONS (normalize / unnormalize)
1212
+ ───────────────────────────────────────────────────────────────*/
1213
+ function speedToMps(v, distUnit, timeUnit) {
1214
+ const du = canonDist(distUnit);
1215
+ const tu = canonTime(timeUnit);
1216
+ return v * (DIST_FACTORS[du] / TIME_FACTORS[tu]);
1217
+ }
1218
+ function mpsToSpeed(vMps, distUnit, timeUnit) {
1219
+ const du = canonDist(distUnit);
1220
+ const tu = canonTime(timeUnit);
1221
+ return vMps * (TIME_FACTORS[tu] / DIST_FACTORS[du]);
1222
+ }
1223
+ /*───────────────────────────────────────────────────────────────
1224
+ šŸŽÆ UNIVERSAL CONVERTERS
1225
+ ───────────────────────────────────────────────────────────────*/
1226
+ function convertDistance({ d, fromDist, toDist, vOnly = true, }) {
1227
+ const m = distanceToMeters(d, fromDist);
1228
+ const D = canonDist(toDist ?? "m");
1229
+ const out = metersToDistance(m, D);
1230
+ return vOnly ? out : { d: out, D };
1231
+ }
1232
+ function convertTime({ t, fromTime, toTime, vOnly = true, }) {
1233
+ const sec = timeToSeconds(t, fromTime);
1234
+ const T = canonTime(toTime ?? "s");
1235
+ const out = secondsToTime(sec, T);
1236
+ return vOnly ? out : { t: out, T };
1237
+ }
1238
+ function convertSpeed({ v, fromDist, fromTime, toDist, toTime, vOnly = true, }) {
1239
+ const mps = speedToMps(v, fromDist, fromTime);
1240
+ const d = canonDist(toDist ?? "m");
1241
+ const t = canonTime(toTime ?? "s");
1242
+ const out = mpsToSpeed(mps, d, t);
1243
+ return vOnly ? out : { v: out, d, t };
1244
+ }
1245
+ const DistanceConverter = {
1246
+ normalize: distanceToMeters,
1247
+ unnormalize: metersToDistance,
1248
+ };
1249
+ const TimeConverter = {
1250
+ normalize: timeToSeconds,
1251
+ unnormalize: secondsToTime,
1252
+ };
1253
+ const SpeedConverter = {
1254
+ normalize: (v, [du, tu]) => speedToMps(v, du, tu),
1255
+ unnormalize: (v, [du, tu]) => mpsToSpeed(v, du, tu),
1256
+ };
1257
+ /*───────────────────────────────────────────────────────────────
1258
+ 🧩 COMPATIBILITY WRAPPERS (legacy aliases)
1259
+ ───────────────────────────────────────────────────────────────*/
1260
+ const toMeters = distanceToMeters;
1261
+ const fromMeters = metersToDistance;
1262
+ const toSeconds = timeToSeconds;
1263
+ const fromSeconds = secondsToTime;
1264
+ const velocityToMs = (value, unit) => speedToMps(value, unit, "s");
1265
+ const velocityFromMs = (value, unit) => mpsToSpeed(value, unit, "s");
1266
+ /** Non-canonical helper for arbitrary rate conversion, e.g. ft/day → m/s */
1267
+ const fromMps = (v, dist_unit, time_unit) => mpsToSpeed(v, dist_unit, time_unit);
1268
+ /*───────────────────────────────────────────────────────────────
1269
+ šŸ“Š UTILITIES
1270
+ ───────────────────────────────────────────────────────────────*/
1271
+ const isFiniteNum = (x) => Number.isFinite(x);
1272
+ const fmt = (n, digits = 2) => isFiniteNum(n) ? n.toFixed(digits) : "N/A";
1273
+
1274
+ // Function to check time interval
1275
+ function isTimeInterval(timeObj, interval) {
1276
+ return (Date.now() / 1000 - timeObj) < (interval - 1);
1277
+ }
1278
+
1279
+ /**
1280
+ * Recursively traverse the object and convert BigInts to numbers or strings.
1281
+ *
1282
+ * @param {object|array} obj - The object to traverse
1283
+ * @param {boolean} convertToNumber - Whether to convert BigInt to Number (default is true)
1284
+ * @returns {object|array} - The transformed object
1285
+ */
1286
+ function convertBigInts(obj, convertToNumber = true) {
1287
+ if (obj === null || obj === undefined)
1288
+ return obj;
1289
+ try {
1290
+ if (typeof obj === 'bigint') {
1291
+ return convertToNumber ? Number(obj) : obj.toString();
1292
+ }
1293
+ if (typeof obj === 'object') {
1294
+ if (Array.isArray(obj)) {
1295
+ return obj.map((item) => convertBigInts(item, convertToNumber));
1296
+ }
1297
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, convertBigInts(value, convertToNumber)]));
1298
+ }
1299
+ }
1300
+ catch (error) {
1301
+ }
1302
+ return obj;
1303
+ }
1304
+
1305
+ function getSafeDocument() {
1306
+ return typeof document !== 'undefined' ? document : undefined;
1307
+ }
1308
+ function getDocumentProp(...keys) {
1309
+ let obj = getSafeDocument();
1310
+ for (const k of keys) {
1311
+ if (obj == null || typeof obj !== 'object')
1312
+ return undefined;
1313
+ obj = obj[k];
1314
+ }
1315
+ return obj;
1316
+ }
1317
+
1318
+ /**
1319
+ * Returns the global window object if it exists, otherwise undefined.
1320
+ */
1321
+ function getSafeWindow() {
1322
+ return typeof window !== 'undefined' ? window : undefined;
1323
+ }
1324
+ /**
1325
+ * Safely call a method on window by name.
1326
+ *
1327
+ * @param method The Window method to call (e.g. "alert", "open", etc.).
1328
+ * @param args Arguments to pass to that method.
1329
+ * @returns The method’s return value, or undefined if
1330
+ * window/method isn’t available or throws.
1331
+ */
1332
+ function callWindowMethod(method, ...args) {
1333
+ const w = getSafeWindow();
1334
+ if (!w)
1335
+ return undefined;
1336
+ const fn = w[method];
1337
+ if (typeof fn !== 'function')
1338
+ return undefined;
1339
+ try {
1340
+ // cast to any so TS doesn’t complain about apply/invoke
1341
+ return fn(...args);
1342
+ }
1343
+ catch {
1344
+ return undefined;
1345
+ }
1346
+ }
1347
+ /** implementation */
1348
+ function getWindowProp(...keys) {
1349
+ let obj = getSafeWindow();
1350
+ for (const k of keys) {
1351
+ if (obj == null || typeof obj !== 'object')
1352
+ return undefined;
1353
+ obj = obj[k];
1354
+ }
1355
+ return obj;
1356
+ }
1357
+ function getWindowHost() {
1358
+ return getWindowProp('location', 'host');
1359
+ }
1360
+
1361
+ async function readJsonFileBrowser(url) {
1362
+ const fetchFn = safeGlobalProp("fetch");
1363
+ if (typeof fetchFn !== "function")
1364
+ return null;
1365
+ try {
1366
+ const res = await fetchFn(url);
1367
+ if (!res.ok)
1368
+ return null;
1369
+ return (await res.json());
1370
+ }
1371
+ catch {
1372
+ return null;
1373
+ }
1374
+ }
1375
+
1376
+ var readJsonFile_browser = /*#__PURE__*/Object.freeze({
1377
+ __proto__: null,
1378
+ readJsonFileBrowser: readJsonFileBrowser
1379
+ });
1380
+
1381
+ function readJsonFileNode(relativeOrAbsolutePath) {
1382
+ try {
1383
+ const filePath = isAbsolute(relativeOrAbsolutePath)
1384
+ ? relativeOrAbsolutePath
1385
+ : resolve(process.cwd(), relativeOrAbsolutePath);
1386
+ return JSON.parse(readFileSync(filePath, "utf8"));
1387
+ }
1388
+ catch {
1389
+ return null;
1390
+ }
1391
+ }
1392
+
1393
+ var readJsonFile_node = /*#__PURE__*/Object.freeze({
1394
+ __proto__: null,
1395
+ readJsonFileNode: readJsonFileNode
1396
+ });
1397
+
1398
+ async function readJsonFile(relativeOrAbsolutePath) {
1399
+ if (typeof process !== "undefined" && process.versions?.node) {
1400
+ const mod = await Promise.resolve().then(function () { return readJsonFile_node; });
1401
+ return mod.readJsonFileNode(relativeOrAbsolutePath);
1402
+ }
1403
+ else {
1404
+ const mod = await Promise.resolve().then(function () { return readJsonFile_browser; });
1405
+ return mod.readJsonFileBrowser(relativeOrAbsolutePath);
1406
+ }
1407
+ }
1408
+ async function getConfigContent() {
1409
+ try {
1410
+ // `readJsonFile` should throw if the file isn’t there or isn’t valid JSON
1411
+ const cfg = await readJsonFile('./config.json');
1412
+ return cfg;
1413
+ }
1414
+ catch {
1415
+ // swallow errors & return null so callers can detect ā€œno configā€
1416
+ return null;
1417
+ }
1418
+ }
1419
+
1420
+ // src/functions/config_utils/src/config_utils.ts
1421
+ let _cachedConfig = null;
1422
+ async function loadConfig(filePath = null) {
1423
+ if (_cachedConfig) {
1424
+ return _cachedConfig;
1425
+ }
1426
+ // 1) figure out where config.json lives
1427
+ let configUrl;
1428
+ if (filePath) {
1429
+ configUrl = filePath;
1430
+ }
1431
+ else if (typeof import.meta !== 'undefined' && typeof import.meta.url === 'string') {
1432
+ // ES module: resolve relative to this file
1433
+ try {
1434
+ const mod = await (new Function("return import('./config.json').catch(() => ({}))"))();
1435
+ _cachedConfig = mod.default ?? {};
1436
+ return _cachedConfig;
1437
+ }
1438
+ catch {
1439
+ configUrl = 'config.json';
1440
+ }
1441
+ }
1442
+ else {
1443
+ // browser fallback
1444
+ const baseURI = safeGlobalProp('document', 'baseURI');
1445
+ try {
1446
+ configUrl =
1447
+ typeof baseURI === 'string'
1448
+ ? new URL('config.json', baseURI).href
1449
+ : 'config.json';
1450
+ }
1451
+ catch {
1452
+ configUrl = 'config.json';
1453
+ }
1454
+ }
1455
+ // 2) if we have a fetch, try HTTP(S)
1456
+ const fetchFn = safeGlobalProp('fetch');
1457
+ if (typeof fetchFn === 'function') {
1458
+ try {
1459
+ const res = await fetchFn(configUrl);
1460
+ if (res.ok) {
1461
+ const json = await res.json();
1462
+ // cache & return
1463
+ _cachedConfig = json ?? {};
1464
+ return _cachedConfig;
1465
+ }
1466
+ }
1467
+ catch {
1468
+ /* swallow */
1469
+ }
1470
+ }
1471
+ // 3) Node fallback: try reading from disk (requires your readJsonFile util)
1472
+ try {
1473
+ const disk = await readJsonFile(configUrl);
1474
+ _cachedConfig = disk ?? {};
1475
+ return _cachedConfig;
1476
+ }
1477
+ catch {
1478
+ /* swallow */
1479
+ }
1480
+ // 4) if all else fails, return an empty config
1481
+ _cachedConfig = {};
1482
+ return _cachedConfig;
1483
+ }
1484
+ async function getConfig(key) {
1485
+ const cfg = await loadConfig();
1486
+ return key != null ? cfg[key] : cfg;
1487
+ }
1488
+
1489
+ /**
1490
+ * Processes keywords by checking if keywords is a string and splitting it.
1491
+ * Then cleans each keyword using `eatAll` with a set of characters to remove.
1492
+ *
1493
+ * @param keywords - The keywords as a comma-separated string or as an array.
1494
+ * @returns An array of cleaned keywords.
1495
+ */
1496
+ function processKeywords(keywords) {
1497
+ let keywordArray;
1498
+ // If keywords is a string, split it on commas
1499
+ if (typeof keywords === "string") {
1500
+ keywordArray = keywords.split(",");
1501
+ }
1502
+ else {
1503
+ keywordArray = keywords;
1504
+ }
1505
+ // Clean each keyword by removing unwanted characters
1506
+ return keywordArray.map(keyword => eatAll(keyword, [",", "\n", "\t", " ", "#"]));
1507
+ }
1508
+ /**
1509
+ * Constructs a keyword string where each keyword is prefixed with a hash (#).
1510
+ *
1511
+ * @param keywords - An array of keywords.
1512
+ * @returns A string with each keyword prefixed by '#'.
1513
+ */
1514
+ function get_keyword_string(keywords) {
1515
+ keywords = processKeywords(keywords);
1516
+ let allString = "";
1517
+ for (const keyword of keywords) {
1518
+ allString += ` #${keyword}`;
1519
+ }
1520
+ return allString;
1521
+ }
1522
+
1523
+ // Function to compare MB
1524
+ function exceedsMbLimit(limitMb, payloadMb) {
1525
+ return payloadMb > limitMb;
1526
+ }
1527
+ function safeJsonSizeInMb(value) {
1528
+ const seen = new WeakSet();
1529
+ const json = JSON.stringify(value, (_, v) => {
1530
+ if (typeof v === "bigint")
1531
+ return v.toString();
1532
+ if (typeof v === "object" && v !== null) {
1533
+ if (seen.has(v))
1534
+ return "[Circular]";
1535
+ seen.add(v);
1536
+ }
1537
+ return v;
1538
+ });
1539
+ return Buffer.byteLength(json, "utf8") / (1024 * 1024);
1540
+ }
1541
+ function dataSizeInMb(data) {
1542
+ const size = typeof data === "string"
1543
+ ? Buffer.byteLength(data, "utf8")
1544
+ : Buffer.byteLength(JSON.stringify(data), "utf8");
1545
+ return size / (1024 * 1024);
1546
+ }
1547
+ function getJsonSizeInMb(json) {
1548
+ return Buffer.byteLength(JSON.stringify(json), "utf8") / (1024 * 1024);
1549
+ }
1550
+ // Function to calculate data size in KB
1551
+ function dataSize(data) {
1552
+ let size = 0;
1553
+ if (typeof data === 'string') {
1554
+ size = Buffer.byteLength(data, 'utf8');
1555
+ }
1556
+ else if (Buffer.isBuffer(data)) {
1557
+ size = data.length;
1558
+ }
1559
+ else if (typeof data === 'object') {
1560
+ size = Buffer.byteLength(JSON.stringify(data), 'utf8');
1561
+ }
1562
+ else {
1563
+ size = Buffer.byteLength(String(data), 'utf8');
1564
+ }
1565
+ return size / 1000; // Convert to kilobytes
1566
+ }
1567
+
1568
+ function getLastCaller(skip = ["debugPrint"]) {
1569
+ const stack = new Error().stack;
1570
+ if (!stack)
1571
+ return null;
1572
+ const lines = stack
1573
+ .split("\n")
1574
+ .map(l => l.trim())
1575
+ .slice(1); // drop "Error"
1576
+ for (const line of lines) {
1577
+ // Example:
1578
+ // at processSingleAddress (/path/file.ts:142:7)
1579
+ const match = line.match(/at (.+?) \((.+?):(\d+):(\d+)\)/) ||
1580
+ line.match(/at (.+?):(\d+):(\d+)/);
1581
+ if (!match)
1582
+ continue;
1583
+ const functionName = match[1] ?? "anonymous";
1584
+ if (skip.includes(functionName))
1585
+ continue;
1586
+ return {
1587
+ functionName,
1588
+ file: match[2],
1589
+ line: Number(match[3]),
1590
+ column: Number(match[4]),
1591
+ };
1592
+ }
1593
+ return null;
1594
+ }
1595
+
1596
+ function debugPrint(value, label = null) {
1597
+ const caller = getLastCaller();
1598
+ const header = label ??
1599
+ (caller
1600
+ ? `${caller.functionName} @ ${caller.file}:${caller.line}`
1601
+ : "object");
1602
+ console.log(`\nšŸ” ${header}`);
1603
+ console.log(inspect(value, {
1604
+ depth: null,
1605
+ colors: true,
1606
+ compact: false,
1607
+ maxArrayLength: null,
1608
+ }));
1609
+ }
1610
+
1611
+ 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, convertTime 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, safeDivide as aJ, safeMultiply as aK, roundPercentage as aL, exponential as aM, isZero as aN, DIST_ALIASES as aO, TIME_ALIASES as aP, DIST_FACTORS as aQ, TIME_FACTORS as aR, canonDist as aS, canonTime as aT, distanceToMeters as aU, metersToDistance as aV, timeToSeconds as aW, secondsToTime as aX, speedToMps as aY, mpsToSpeed as aZ, convertDistance 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$, convertSpeed as b0, DistanceConverter as b1, TimeConverter as b2, SpeedConverter as b3, toMeters as b4, fromMeters as b5, toSeconds as b6, fromSeconds as b7, velocityToMs as b8, velocityFromMs as b9, KMS_PER_METER as bA, MILES_PER_METER as bB, FEET_PER_METER as bC, MIN_IN_S as bD, HOUR_IN_S as bE, DAY_IN_S as bF, YEAR_IN_S as bG, MONTH_IN_S as bH, MiPerH_TO_MPerS as bI, MPerS_TO_MiPerH as bJ, isTimeInterval as bK, convertBigInts as bL, cleanText as bM, cleanArray as bN, getCleanArray as bO, formatNumber as bP, ensure_list as bQ, ensure_number as bR, ensure_string as bS, ensurelist as bT, assureList as bU, assure_list as bV, ensureList as bW, assurelist as bX, ensurenumber as bY, assureNumber as bZ, ensureNumber as b_, fromMps as ba, isFiniteNum as bb, fmt as bc, SECOND as bd, ZEPTOSECOND as be, ATTOSECOND as bf, FEMTOSECOND as bg, PICOSECOND as bh, NANOSECOND as bi, MICROSECOND as bj, MILISECOND as bk, CENTISECOND as bl, DECISECOND as bm, MINUTE as bn, HOUR as bo, DAY as bp, YEAR as bq, MONTH as br, SECONDS_PER_MINUTE as bs, SECONDS_PER_HOUR as bt, SECONDS_PER_DAY as bu, PI as bv, PI2 as bw, METERS_PER_KM as bx, METERS_PER_MILE as by, METERS_PER_FOOT as bz, get_window_location as c, assure_number as c0, ensurestring as c1, ensureString as c2, assureString as c3, assurestring as c4, assure_string as c5, assurearray as c6, ensurearray as c7, ensure_array as c8, ensureArray as c9, getSafeWindow as cA, callWindowMethod as cB, getWindowProp as cC, getWindowHost as cD, processKeywords as cE, get_keyword_string as cF, exceedsMbLimit as cG, safeJsonSizeInMb as cH, dataSizeInMb as cI, getJsonSizeInMb as cJ, dataSize as cK, debugPrint as cL, getLastCaller as cM, assure_array as ca, assureArray as cb, get_key_value as cc, get as cd, findKeyValue as ce, omitKeys as cf, extractInsertData as cg, loadInnerJson as ch, isType as ci, isStrInString as cj, getChar as ck, getAlphaNum as cl, getNums as cm, isNum as cn, getAlphas as co, getIfNone as cp, mergeNotNullValues as cq, emptyObjectToNull as cr, loadConfig as cs, getConfig as ct, readJsonFileBrowser as cu, readJsonFileNode as cv, readJsonFile as cw, getConfigContent as cx, getSafeDocument as cy, getDocumentProp 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 };
1612
+ //# sourceMappingURL=print_utils-Bg-2k-Zo.js.map