@putkoff/abstract-utilities 0.1.178 → 0.1.179

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.
package/dist/esm/index.js CHANGED
@@ -927,6 +927,28 @@ function eatEnd(obj, endings = ['/']) {
927
927
  }
928
928
  return result;
929
929
  }
930
+ function tryParse(obj) {
931
+ try {
932
+ obj = JSON.stringify(obj);
933
+ }
934
+ catch (err) {
935
+ try {
936
+ obj = JSON.parse(obj);
937
+ }
938
+ catch (err) {
939
+ }
940
+ }
941
+ return obj;
942
+ }
943
+ function create_list_string(array_obj) {
944
+ let string = '';
945
+ for (const obj in array_obj) {
946
+ const array_value = array_obj[obj];
947
+ const parsed_value = tryParse(array_value);
948
+ string += `${obj} == ${parsed_value}\n`;
949
+ }
950
+ return string;
951
+ }
930
952
 
931
953
  function ensure_list(obj) {
932
954
  const objArray = Array.isArray(obj) ? obj : [obj];
@@ -1175,22 +1197,43 @@ function getConfig(key) {
1175
1197
  });
1176
1198
  }
1177
1199
 
1178
- function ensureAbstractUrl(endpoint, slices = []) {
1179
- slices = slices || ['https//abstractendeavors.com', 'api'];
1180
- // 1) build a prefix string like "api/v1/"
1181
- const prefix = slices.map((s) => `${s}/`).join("");
1182
- const windowHost = getWindowHost();
1183
- const normalized = [
1184
- '/',
1185
- ...slices,
1186
- windowHost, // so "abstractendeavors.com" will be stripped
1187
- `${windowHost}/api` // etc, if you need it
1188
- ];
1189
- const stripped = stripPrefixes(endpoint, normalized);
1190
- console.log('BUILD PREFIX:', prefix);
1191
- console.log('RAW ENDPOINT:', endpoint);
1192
- console.log('STRIPPED ENDPT:', stripped);
1193
- return make_path(prefix, stripped);
1200
+ /**
1201
+ * Strip a leading host (http://host) from any URL-like string.
1202
+ */
1203
+ function stripHost(str) {
1204
+ // now also removes "abstractendeavors.com" even without protocol
1205
+ const hostPattern = `(?:https?:\\/\\/)?${getWindowHost()}`;
1206
+ return str.replace(new RegExp(`^${hostPattern}`), '');
1207
+ }
1208
+ /**
1209
+ * Given an “endpoint” slug like "api/list", build the full URL
1210
+ * from the BASE_API_URL entry in your JSON config.
1211
+ */
1212
+ function get_app_config_url(endpoint) {
1213
+ return __awaiter(this, void 0, void 0, function* () {
1214
+ // 1) normalize your input
1215
+ try {
1216
+ endpoint = endpoint || '';
1217
+ const clean = stripHost(endpoint.trim().toLowerCase());
1218
+ const cfg = yield loadConfig();
1219
+ // 2) pick the key you expect in your JSON
1220
+ const appKey = (`BASE_API_URL`);
1221
+ const base = yield fetchIt('https://abstractendeavors.com/api/secure_env', { "key": 'BASE_API_URL', 'path': '/var/www/abstractendeavors/secure-files/public/config.json' }, 'POST', null, false, true);
1222
+ endpoint = stripPrefixes(endpoint, ['/', 'https://', 'abstractendeavors.com', 'api']);
1223
+ if (base && endpoint) {
1224
+ return make_path(base, endpoint);
1225
+ }
1226
+ if (base) {
1227
+ return base;
1228
+ }
1229
+ if (endpoint) {
1230
+ return endpoint;
1231
+ }
1232
+ }
1233
+ catch (_a) {
1234
+ return endpoint;
1235
+ }
1236
+ });
1194
1237
  }
1195
1238
  /**
1196
1239
  * Unwraps nested { result } fields until you hit a non-object or no more "result" keys.
@@ -1204,42 +1247,6 @@ function getResult(obj) {
1204
1247
  }
1205
1248
  return current;
1206
1249
  }
1207
- // Constructs API URL from endpoint
1208
- function api(endpoint) {
1209
- return ensureAbstractUrl(endpoint);
1210
- }
1211
- /**
1212
- * Intercept 401/403 and force a clean redirect to login
1213
- * without ever showing an alert.
1214
- */
1215
- function checkResponse(res) {
1216
- if (res.status === 401 || res.status === 403) {
1217
- // 1) clear out the stale token
1218
- localStorage.removeItem("token");
1219
- // 2) replace history so "back" doesn’t re-trigger the protected route
1220
- window.history.replaceState({}, "", "/secure-files");
1221
- // 3) short-circuit all further fetch logic
1222
- throw new Error("SessionExpired");
1223
- }
1224
- return res;
1225
- }
1226
- /**
1227
- * parseResult no longer needs to worry about JSON vs HTML redirect errors;
1228
- * all 401/403 have already been handled above.
1229
- */
1230
- function parseResult(res) {
1231
- return __awaiter(this, void 0, void 0, function* () {
1232
- // runs checkResponse first, will throw if session is expired
1233
- res = checkResponse(res);
1234
- if (!res.ok) {
1235
- // for any other non-401 errors, you can still surface them
1236
- const errorText = yield res.text();
1237
- throw new Error(errorText || res.statusText);
1238
- }
1239
- // now safely parse JSON
1240
- return res.json();
1241
- });
1242
- }
1243
1250
  // Determines HTTP method, defaults to GET or POST based on body
1244
1251
  function getMethod(method = null, body = null) {
1245
1252
  const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'PULL'];
@@ -1294,88 +1301,46 @@ function getFetchVars(headers = null, method = null, body = null) {
1294
1301
  }
1295
1302
  return { method, headers, body };
1296
1303
  }
1297
- // Constructs HTML directory path
1298
- function getHtmlDirectory(directory, filename) {
1299
- return `${directory}/${filename}.html`;
1300
- }
1301
- // Fetches HTML content
1302
- function fetchIndexHtml(filename_1) {
1303
- return __awaiter(this, arguments, void 0, function* (filename, directory = 'sf_index', base = 'html') {
1304
- const url = `/${base}/${directory}/${filename}.html`;
1305
- const response = yield fetch(api(url));
1306
- return yield response.text();
1307
- });
1308
- }
1309
- // Fetches and injects HTML content into container
1310
- function fetchIndexHtmlContainer(filename_1) {
1311
- return __awaiter(this, arguments, void 0, function* (filename, doc = document, directory = 'html') {
1312
- const container = `${filename}-container`;
1313
- const html = yield fetchIndexHtml(filename, directory);
1314
- const el = doc.getElementById(container);
1315
- if (el) {
1316
- el.innerHTML = html;
1317
- }
1318
- else {
1319
- console.warn(`⚠️ No container found for: #${container}`);
1304
+ /*
1305
+ * parseResult no longer needs to worry about JSON vs HTML redirect errors;
1306
+ * all 401/403 have already been handled above.
1307
+ */
1308
+ function parseResult(res) {
1309
+ return __awaiter(this, void 0, void 0, function* () {
1310
+ // runs checkResponse first, will throw if session is expired
1311
+ res = checkResponse(res);
1312
+ if (!res.ok) {
1313
+ // for any other non-401 errors, you can still surface them
1314
+ const errorText = yield res.text();
1315
+ throw new Error(errorText || res.statusText);
1320
1316
  }
1317
+ // now safely parse JSON
1318
+ return res.json();
1321
1319
  });
1322
1320
  }
1323
-
1324
1321
  /**
1325
- * Strip a leading host (http://host) from any URL-like string.
1326
- */
1327
- function stripHost(str) {
1328
- // now also removes "abstractendeavors.com" even without protocol
1329
- const hostPattern = `(?:https?:\\/\\/)?${getWindowHost()}`;
1330
- return str.replace(new RegExp(`^${hostPattern}`), '');
1331
- }
1332
- /**
1333
- * Given an “endpoint” slug like "api/list", build the full URL
1334
- * from the BASE_API_URL entry in your JSON config.
1322
+ * Intercept 401/403 and force a clean redirect to login
1323
+ * without ever showing an alert.
1335
1324
  */
1336
- function get_app_config_url(endpoint) {
1337
- return __awaiter(this, void 0, void 0, function* () {
1338
- // 1) normalize your input
1339
- try {
1340
- endpoint = endpoint || '';
1341
- const clean = stripHost(endpoint.trim().toLowerCase());
1342
- const cfg = yield loadConfig();
1343
- // 2) pick the key you expect in your JSON
1344
- const appKey = (`BASE_API_URL`);
1345
- const base = yield fetchIt('https://abstractendeavors.com/api/secure_env', { "key": 'BASE_API_URL', 'path': '/var/www/abstractendeavors/secure-files/public/config.json' }, 'POST', null, false, true);
1346
- endpoint = stripPrefixes(endpoint, ['/', 'https://', 'abstractendeavors.com', 'api']);
1347
- if (base && endpoint) {
1348
- return make_path(base, endpoint);
1349
- }
1350
- if (base) {
1351
- return base;
1352
- }
1353
- if (endpoint) {
1354
- return endpoint;
1355
- }
1356
- }
1357
- catch (_a) {
1358
- return endpoint;
1359
- }
1360
- });
1325
+ function checkResponse(res) {
1326
+ if (res.status === 401 || res.status === 403) {
1327
+ // 1) clear out the stale token
1328
+ localStorage.removeItem("token");
1329
+ // 2) replace history so "back" doesn’t re-trigger the protected route
1330
+ window.history.replaceState({}, "", "/secure-files");
1331
+ // 3) short-circuit all further fetch logic
1332
+ throw new Error("SessionExpired");
1333
+ }
1334
+ return res;
1361
1335
  }
1362
1336
  function fetchIt(url, body, method, headers, blob, noApi, withCredentials, returnJson, returnReult) {
1363
1337
  return __awaiter(this, void 0, void 0, function* () {
1364
- const vars = getFetchVars(headers, method, body);
1365
- const res = yield fetch(url, vars);
1366
- return blob ? (checkResponse(res), res.blob()) : yield parseResult(res);
1367
- });
1368
- }
1369
- function secureFetchIt(endpoint_1) {
1370
- return __awaiter(this, arguments, void 0, function* (endpoint, body = null, method = null, customHeaders = null, blob = false, noApi = false, withCredentials = true, returnJson = true, returnReult = true) {
1371
- // strip leading slashes off the endpoint
1372
1338
  method = method || "GET";
1373
- let url = endpoint;
1374
1339
  if (!noApi) {
1375
- url = yield get_app_config_url(endpoint);
1340
+ url = yield get_app_config_url(url);
1376
1341
  }
1377
1342
  // headers: JSON by default, plus any auth + overrides
1378
- const headers = Object.assign(Object.assign(Object.assign({}, (body instanceof FormData ? {} : { "Content-Type": "application/json" })), getAuthorizationHeader()), customHeaders);
1343
+ headers = Object.assign(Object.assign(Object.assign({}, (body instanceof FormData ? {} : { "Content-Type": "application/json" })), getAuthorizationHeader()), headers);
1379
1344
  const opts = {
1380
1345
  method: method.toUpperCase(),
1381
1346
  credentials: withCredentials ? "include" : "same-origin",
@@ -1401,6 +1366,12 @@ function secureFetchIt(endpoint_1) {
1401
1366
  return res;
1402
1367
  });
1403
1368
  }
1369
+
1370
+ function secureFetchIt(endpoint_1) {
1371
+ return __awaiter(this, arguments, void 0, function* (endpoint, body = null, method = null, customHeaders = null, blob = false, configUrl = false, withCredentials = true, returnJson = true, returnReult = true) {
1372
+ return yield fetchIt(endpoint, body, method, customHeaders, blob, configUrl, withCredentials, returnJson, returnReult);
1373
+ });
1374
+ }
1404
1375
  // Performs PATCH request
1405
1376
  function requestPatch(url_1) {
1406
1377
  return __awaiter(this, arguments, void 0, function* (url, body = null) {
@@ -1436,6 +1407,54 @@ function fetchSharePatch(file_1) {
1436
1407
  });
1437
1408
  }
1438
1409
 
1410
+ function ensureAbstractUrl(endpoint, slices = []) {
1411
+ slices = slices || ['https//abstractendeavors.com', 'api'];
1412
+ // 1) build a prefix string like "api/v1/"
1413
+ const prefix = slices.map((s) => `${s}/`).join("");
1414
+ const windowHost = getWindowHost();
1415
+ const normalized = [
1416
+ '/',
1417
+ ...slices,
1418
+ windowHost, // so "abstractendeavors.com" will be stripped
1419
+ `${windowHost}/api` // etc, if you need it
1420
+ ];
1421
+ const stripped = stripPrefixes(endpoint, normalized);
1422
+ console.log('BUILD PREFIX:', prefix);
1423
+ console.log('RAW ENDPOINT:', endpoint);
1424
+ console.log('STRIPPED ENDPT:', stripped);
1425
+ return make_path(prefix, stripped);
1426
+ }
1427
+ // Constructs API URL from endpoint
1428
+ function api(endpoint) {
1429
+ return ensureAbstractUrl(endpoint);
1430
+ }
1431
+ // Constructs HTML directory path
1432
+ function getHtmlDirectory(directory, filename) {
1433
+ return `${directory}/${filename}.html`;
1434
+ }
1435
+ // Fetches HTML content
1436
+ function fetchIndexHtml(filename_1) {
1437
+ return __awaiter(this, arguments, void 0, function* (filename, directory = 'sf_index', base = 'html') {
1438
+ const url = `/${base}/${directory}/${filename}.html`;
1439
+ const response = yield fetch(api(url));
1440
+ return yield response.text();
1441
+ });
1442
+ }
1443
+ // Fetches and injects HTML content into container
1444
+ function fetchIndexHtmlContainer(filename_1) {
1445
+ return __awaiter(this, arguments, void 0, function* (filename, doc = document, directory = 'html') {
1446
+ const container = `${filename}-container`;
1447
+ const html = yield fetchIndexHtml(filename, directory);
1448
+ const el = doc.getElementById(container);
1449
+ if (el) {
1450
+ el.innerHTML = html;
1451
+ }
1452
+ else {
1453
+ console.warn(`⚠️ No container found for: #${container}`);
1454
+ }
1455
+ });
1456
+ }
1457
+
1439
1458
  function Button(_a) {
1440
1459
  var { children, color = 'gray', variant = 'default', className = '' } = _a, rest = __rest(_a, ["children", "color", "variant", "className"]);
1441
1460
  const base = 'rounded px-3 py-1 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors duration-150';
@@ -1518,5 +1537,5 @@ function readJsonFile(relativeOrAbsolutePath) {
1518
1537
  });
1519
1538
  }
1520
1539
 
1521
- export { API_PREFIX, BASE_URL, Button, Checkbox, DEV_PREFIX, DOMAIN_NAME, Input, PROD_PREFIX, PROTOCOL, SUB_DIR, Spinner, alertit, api, callStorage, callWindowMethod, checkResponse, currentUsername, currentUsernames, decodeJwt, eatAll, eatEnd, eatInner, eatOuter, ensureAbstractUrl, ensure_list, fetchIndexHtml, fetchIndexHtmlContainer, fetchIt, fetchSharePatch, geAuthsUtilsDirectory, geBackupsUtilsDirectory, geConstantsUtilsDirectory, geEnvUtilsDirectory, geFetchUtilsDirectory, geFileUtilsDirectory, gePathUtilsDirectory, geStaticDirectory, geStringUtilsDirectory, geTypeUtilsDirectory, getAbsDir, getAbsPath, getAuthorizationHeader, getBaseDir, getBody, getComponentsUtilsDirectory, getConfig, getDbConfigsPath, getDistDir, getDocumentProp, getEnvDir, getEnvPath, getFetchVars, getFunctionsDir, getFunctionsUtilsDirectory, getHeaders, getHooksUtilsDirectory, getHtmlDirectory, getLibUtilsDirectory, getMethod, getPublicDir, getResult, getSafeDocument, getSafeLocalStorage, getSafeWindow, getSchemasDirPath, getSchemasPath, getSrcDir, getSubstring, getToken, getWindowHost, getWindowProp, get_app_config_url, get_basename, get_dirname, get_extname, get_filename, get_splitext, get_window, get_window_location, get_window_parts, get_window_pathname, isLoggedIn, isTokenExpired, loadConfig, make_path, make_sanitized_path, normalizeUrl, parseResult, readFileContents, readJsonFile, requestPatch, requireToken, safeGlobalProp, safeStorage, sanitizeFilename, secureFetchIt, stripHost, stripPrefixes, truncateString };
1540
+ export { API_PREFIX, BASE_URL, Button, Checkbox, DEV_PREFIX, DOMAIN_NAME, Input, PROD_PREFIX, PROTOCOL, SUB_DIR, Spinner, alertit, api, callStorage, callWindowMethod, checkResponse, create_list_string, currentUsername, currentUsernames, decodeJwt, eatAll, eatEnd, eatInner, eatOuter, ensureAbstractUrl, ensure_list, fetchIndexHtml, fetchIndexHtmlContainer, fetchIt, fetchSharePatch, geAuthsUtilsDirectory, geBackupsUtilsDirectory, geConstantsUtilsDirectory, geEnvUtilsDirectory, geFetchUtilsDirectory, geFileUtilsDirectory, gePathUtilsDirectory, geStaticDirectory, geStringUtilsDirectory, geTypeUtilsDirectory, getAbsDir, getAbsPath, getAuthorizationHeader, getBaseDir, getBody, getComponentsUtilsDirectory, getConfig, getDbConfigsPath, getDistDir, getDocumentProp, getEnvDir, getEnvPath, getFetchVars, getFunctionsDir, getFunctionsUtilsDirectory, getHeaders, getHooksUtilsDirectory, getHtmlDirectory, getLibUtilsDirectory, getMethod, getPublicDir, getResult, getSafeDocument, getSafeLocalStorage, getSafeWindow, getSchemasDirPath, getSchemasPath, getSrcDir, getSubstring, getToken, getWindowHost, getWindowProp, get_app_config_url, get_basename, get_dirname, get_extname, get_filename, get_splitext, get_window, get_window_location, get_window_parts, get_window_pathname, isLoggedIn, isTokenExpired, loadConfig, make_path, make_sanitized_path, normalizeUrl, parseResult, readFileContents, readJsonFile, requestPatch, requireToken, safeGlobalProp, safeStorage, sanitizeFilename, secureFetchIt, stripHost, stripPrefixes, truncateString, tryParse };
1522
1541
  //# sourceMappingURL=index.js.map