@putkoff/abstract-utilities 0.1.183 → 0.1.185

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
@@ -1275,6 +1275,29 @@ function getConfig(key) {
1275
1275
  return key != null ? cfg[key] : cfg;
1276
1276
  });
1277
1277
  }
1278
+ function getConfigContent() {
1279
+ return __awaiter(this, void 0, void 0, function* () {
1280
+ try {
1281
+ // `readJsonFile` should throw if the file isn’t there or isn’t valid JSON
1282
+ const cfg = yield readJsonFile('./config.json');
1283
+ return cfg;
1284
+ }
1285
+ catch (_a) {
1286
+ // swallow errors & return null so callers can detect “no config”
1287
+ return null;
1288
+ }
1289
+ });
1290
+ }
1291
+ // 2) Pull a single key out of that object
1292
+ function getConfigVar() {
1293
+ return __awaiter(this, arguments, void 0, function* (key = null) {
1294
+ const cfg = yield getConfigContent();
1295
+ if (cfg && typeof cfg === 'object' && key in cfg) {
1296
+ return cfg[key];
1297
+ }
1298
+ return undefined;
1299
+ });
1300
+ }
1278
1301
 
1279
1302
  // Constructs API URL from endpoint
1280
1303
  function api(endpoint) {
@@ -1300,31 +1323,31 @@ function ensureAbstractUrl(endpoint, slices = []) {
1300
1323
  `${windowHost}/api` // etc, if you need it
1301
1324
  ];
1302
1325
  const stripped = stripPrefixes(endpoint, normalized);
1303
- console.log('BUILD PREFIX:', prefix);
1304
- console.log('RAW ENDPOINT:', endpoint);
1305
- console.log('STRIPPED ENDPT:', stripped);
1306
1326
  return make_path(prefix, stripped);
1307
1327
  }
1308
1328
  /**
1309
1329
  * Given an “endpoint” slug like "api/list", build the full URL
1310
1330
  * from the BASE_API_URL entry in your JSON config.
1331
+ * If anything goes wrong, just returns the raw endpoint.
1311
1332
  */
1312
1333
  function get_app_config_url(endpoint) {
1313
1334
  return __awaiter(this, void 0, void 0, function* () {
1314
- // 1) normalize + strip prefixes
1315
1335
  const clean = stripHost(endpoint);
1316
- // 2) fetch your BASE_API_URL
1317
- const vars = getFetchVars(null, 'POST', {
1318
- key: 'BASE_API_URL',
1319
- path: '/var/www/abstractendeavors/secure-files/public/config.json'
1320
- });
1321
- const resp = yield fetch(ensureAbstractUrl('/secure_env'), vars);
1322
- checkResponse(resp);
1323
- // 3) parse, then unwrap { result }
1324
- const json = yield resp.json();
1325
- const baseUrl = getResult(json);
1326
- // 4) now build your final URL
1327
- return make_path(baseUrl, clean);
1336
+ try {
1337
+ const vars = getFetchVars(null, 'POST', {
1338
+ key: 'BASE_API_URL',
1339
+ path: '/var/www/abstractendeavors/secure-files/public/config.json'
1340
+ });
1341
+ const resp = yield fetch(ensureAbstractUrl('/secure_env'), vars);
1342
+ checkResponse(resp);
1343
+ const json = yield resp.json();
1344
+ const baseUrl = getResult(json);
1345
+ return make_path(baseUrl, clean);
1346
+ }
1347
+ catch (err) {
1348
+ console.warn(`[get_app_config_url] failed, falling back to raw endpoint:`, endpoint, err);
1349
+ return endpoint;
1350
+ }
1328
1351
  });
1329
1352
  }
1330
1353
  /**
@@ -1427,38 +1450,49 @@ function checkResponse(res) {
1427
1450
  }
1428
1451
  function fetchIt(endpoint_1) {
1429
1452
  return __awaiter(this, arguments, void 0, function* (endpoint, body = null, method = null, headers = null, blob = false, noApi = false, withCredentials = true, returnJson = true, returnReult = true) {
1430
- method = (method || "GET").toUpperCase();
1431
- // 1) auto-detect absolute URLs
1432
- const isAbsolute = typeof endpoint === "string" && /^https?:\/\//i.test(endpoint);
1433
- // 2) choose the URL
1453
+ const verb = (method || 'GET').toUpperCase();
1454
+ // 1) auto-detect absolute URLs, or use API lookup, but never throw
1434
1455
  let url;
1435
- if (isAbsolute) {
1436
- url = endpoint;
1456
+ try {
1457
+ const isAbsolute = typeof endpoint === 'string' && /^https?:\/\//i.test(endpoint);
1458
+ if (isAbsolute || noApi) {
1459
+ url = endpoint;
1460
+ }
1461
+ else {
1462
+ url = yield get_app_config_url(endpoint);
1463
+ }
1437
1464
  }
1438
- else if (noApi) {
1465
+ catch (_a) {
1439
1466
  url = endpoint;
1440
1467
  }
1441
- else {
1442
- url = yield get_app_config_url(endpoint);
1443
- }
1444
- // 3) prepare headers & body
1445
- headers = Object.assign(Object.assign(Object.assign({}, (body instanceof FormData ? {} : { "Content-Type": "application/json" })), getAuthorizationHeader()), headers);
1468
+ // 2) prepare headers & body
1469
+ const authHeaders = Object.assign({}, (body instanceof FormData ? {} : { 'Content-Type': 'application/json' }));
1470
+ headers = Object.assign(Object.assign(Object.assign({}, authHeaders), getFetchVars(null, verb, body).headers), headers);
1446
1471
  const opts = {
1447
- method,
1448
- credentials: withCredentials ? "include" : "same-origin",
1472
+ method: verb,
1473
+ credentials: withCredentials ? 'include' : 'same-origin',
1449
1474
  headers,
1450
1475
  body: body instanceof FormData
1451
1476
  ? body
1452
- : body != null && method !== "GET"
1477
+ : body != null && verb !== 'GET'
1453
1478
  ? JSON.stringify(body)
1454
1479
  : undefined,
1455
1480
  };
1456
- console.debug("➡️ secureFetchIt", url, opts);
1457
- const res = yield fetch(url, opts);
1458
- if (!res.ok) {
1459
- const err = yield res.text();
1460
- throw new Error(`HTTP ${res.status}: ${err}`);
1481
+ console.debug('➡️ fetchIt', url, opts);
1482
+ // 3) perform fetch, swallow any errors and return raw URL on failure
1483
+ let res;
1484
+ try {
1485
+ res = yield fetch(url, opts);
1486
+ if (!res.ok) {
1487
+ const err = yield res.text();
1488
+ throw new Error(`HTTP ${res.status}: ${err}`);
1489
+ }
1461
1490
  }
1491
+ catch (err) {
1492
+ console.warn(`[fetchIt] failed for ${url}, returning raw endpoint:`, err);
1493
+ return url;
1494
+ }
1495
+ // 4) produce the expected result
1462
1496
  if (blob)
1463
1497
  return res.blob();
1464
1498
  if (returnReult)
@@ -1534,6 +1568,51 @@ function fetchIndexHtmlContainer(filename_1) {
1534
1568
  }
1535
1569
  });
1536
1570
  }
1571
+ // 2) Pull a single key out of that object
1572
+ function getBaseUrl() {
1573
+ return __awaiter(this, arguments, void 0, function* (key = null) {
1574
+ key = key || 'BASE_API_URL';
1575
+ const value = yield getConfigVar(key);
1576
+ return value;
1577
+ });
1578
+ }
1579
+ function getEndpoints() {
1580
+ return __awaiter(this, arguments, void 0, function* (base_url = null) {
1581
+ base_url = yield getUrl(base_url);
1582
+ const endpoints_url = `${base_url}/api/endpoints`;
1583
+ return yield fetchIt(endpoints_url, {}, "GET");
1584
+ });
1585
+ }
1586
+ function getUrl() {
1587
+ return __awaiter(this, arguments, void 0, function* (base_url = null) {
1588
+ return base_url || (yield getBaseUrl()) || 'https://abstractendeavors.com';
1589
+ });
1590
+ }
1591
+ /**
1592
+ * Find the most specific endpoint matching the given keyword.
1593
+ * @param keyword A fragment to search for, e.g. 'list'
1594
+ * @returns The full path string, or null if nothing matches
1595
+ */
1596
+ function getEndpoint(keyword_1) {
1597
+ return __awaiter(this, arguments, void 0, function* (keyword, base_url = null) {
1598
+ base_url = yield getUrl(base_url);
1599
+ const endpoints = yield getEndpoints(base_url);
1600
+ const lower = keyword.toLowerCase();
1601
+ let bestMatch = null;
1602
+ let bestLen = -1;
1603
+ for (const [path] of endpoints) {
1604
+ const lastSegment = path.split("/").pop().toLowerCase();
1605
+ // does either string contain the other?
1606
+ if (lastSegment.includes(lower)) {
1607
+ if (lastSegment.length > bestLen) {
1608
+ bestLen = lastSegment.length;
1609
+ bestMatch = path;
1610
+ }
1611
+ }
1612
+ }
1613
+ return `${base_url}${bestMatch}`;
1614
+ });
1615
+ }
1537
1616
 
1538
1617
  function Button(_a) {
1539
1618
  var { children, color = 'gray', variant = 'default', className = '' } = _a, rest = __rest(_a, ["children", "color", "variant", "className"]);
@@ -1570,5 +1649,5 @@ function Spinner() {
1570
1649
  return (jsx("p", { className: 'animate-pulse', children: "Loading\u2026" }));
1571
1650
  }
1572
1651
 
1573
- 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, readJsonFile, requestPatch, requireToken, safeGlobalProp, safeStorage, sanitizeFilename, secureFetchIt, stripHost, stripPrefixes, truncateString, tryParse };
1652
+ 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, getBaseUrl, getBody, getComponentsUtilsDirectory, getConfig, getConfigContent, getConfigVar, getDbConfigsPath, getDistDir, getDocumentProp, getEndpoint, getEndpoints, getEnvDir, getEnvPath, getFetchVars, getFunctionsDir, getFunctionsUtilsDirectory, getHeaders, getHooksUtilsDirectory, getHtmlDirectory, getLibUtilsDirectory, getMethod, getPublicDir, getResult, getSafeDocument, getSafeLocalStorage, getSafeWindow, getSchemasDirPath, getSchemasPath, getSrcDir, getSubstring, getToken, getUrl, 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, readJsonFile, requestPatch, requireToken, safeGlobalProp, safeStorage, sanitizeFilename, secureFetchIt, stripHost, stripPrefixes, truncateString, tryParse };
1574
1653
  //# sourceMappingURL=index.js.map