@putkoff/abstract-utilities 0.1.115 → 0.1.117

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.
@@ -1,17 +1,9 @@
1
1
  /**
2
2
  * Reads a file at `relativeOrAbsolutePath` and returns its contents as a string.
3
+ * In a browser this will reject immediately.
3
4
  */
4
5
  export declare function readFileContents(relativeOrAbsolutePath: string): Promise<string>;
5
6
  /**
6
7
  * Reads a JSON file and returns the parsed object.
7
8
  */
8
9
  export declare function readJsonFile<T = any>(relativeOrAbsolutePath: string): Promise<T>;
9
- /**
10
- * Read a file and optionally parse it as JSON (and even pluck a field).
11
- *
12
- * @param filePath Path to your file (relative to cwd or absolute)
13
- * @param asJson If true, JSON.parse the file.
14
- * If a string, JSON.parse then return parsed[string].
15
- * @returns The raw string, whole parsed object, or a specific field.
16
- */
17
- export declare function reader(filePath: string, asJson?: boolean | string): Promise<any>;
@@ -1,2 +1,3 @@
1
1
  export * from './functions';
2
2
  export * from './types';
3
+ export { loadConfig } from './utils';
package/dist/esm/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  export { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { jsx, jsxs } from 'react/jsx-runtime';
3
- import { promises } from 'fs';
4
- import path from 'path';
5
3
 
6
4
  /**
7
5
  ***Changes**:
@@ -1015,21 +1013,29 @@ function alertit(obj = null) {
1015
1013
  alert(msg);
1016
1014
  }
1017
1015
 
1018
- /** Will be filled in by loadConfig() */
1019
- function getAppConfig(endpoint) {
1020
- const base = apiBase(); // '' until load() finishes
1021
- const clean = endpoint.replace(/^\/+/, '');
1022
- return base ? `${base}/${clean}` : `/api/${clean}`;
1023
- }
1024
- /** Accessor for the loaded config. Throws if you forgot to loadConfig(). */
1025
- function getConfig$1() {
1026
- {
1027
- throw new Error('Config not loaded! Call loadConfig() first.');
1028
- }
1016
+ let _cachedConfig = null;
1017
+ function loadConfig$1() {
1018
+ return __awaiter(this, arguments, void 0, function* (filePath = null) {
1019
+ // 1. If nobody passed a custom path, we default to "config.json" (relative)
1020
+ const relativePath = filePath || 'config.json';
1021
+ // 2. Resolve it against the running page’s URL (document.baseURI)
1022
+ const configUrl = new URL(relativePath, document.baseURI).href;
1023
+ // 3. Fetch + cache
1024
+ if (_cachedConfig)
1025
+ return _cachedConfig;
1026
+ const res = yield fetch(configUrl);
1027
+ if (!res.ok) {
1028
+ throw new Error(`Could not fetch ${configUrl}: ${res.status}`);
1029
+ }
1030
+ _cachedConfig = (yield res.json());
1031
+ return _cachedConfig;
1032
+ });
1029
1033
  }
1030
- /** Convenience to grab the base URL once loaded. */
1031
- function apiBase() {
1032
- return getConfig$1().API_BASE_URL.replace(/\/+$/, '');
1034
+ function getConfig(key) {
1035
+ return __awaiter(this, void 0, void 0, function* () {
1036
+ const cfg = yield loadConfig$1();
1037
+ return key ? cfg[key] : cfg;
1038
+ });
1033
1039
  }
1034
1040
 
1035
1041
  function ensureAbstractUrl(endpoint, slices = []) {
@@ -1157,9 +1163,11 @@ function getFetchVars(headers = null, method = null, body = null) {
1157
1163
  /** Pulls base-URL from AppConfig.API_BASE_URL, strips trailing slashes */
1158
1164
  // src/functions/fetch/secureFetchIt.ts
1159
1165
  // --- fetch_utils/src/fetch_utils.ts ----------------------------
1160
- function get_app_config_url(endpoint) {
1166
+ function get_app_config_url(endpoint, appKey = null) {
1161
1167
  const cleanEndpoint = endpoint.replace(/^\/+/, "");
1162
- const baseUrl = getAppConfig(cleanEndpoint);
1168
+ const baseUrl = getConfig();
1169
+ appKey = appKey || 'BASE_API_URL';
1170
+ baseUrl[appKey];
1163
1171
  const baseSlices = baseUrl.split("/").filter(Boolean);
1164
1172
  const url = ensureAbstractUrl(cleanEndpoint, baseSlices);
1165
1173
  return url;
@@ -1178,7 +1186,7 @@ function secureFetchIt(endpoint_1) {
1178
1186
  method = method || "GET";
1179
1187
  let url = endpoint;
1180
1188
  if (!noApi) {
1181
- url = get_app_config_url(url);
1189
+ url = get_app_config_url(endpoint);
1182
1190
  }
1183
1191
  // headers: JSON by default, plus any auth + overrides
1184
1192
  const headers = Object.assign(Object.assign(Object.assign({}, (body instanceof FormData ? {} : { "Content-Type": "application/json" })), getAuthorizationHeader()), customHeaders);
@@ -1215,13 +1223,11 @@ function requestPatch(url_1) {
1215
1223
  });
1216
1224
  }
1217
1225
  // Performs PATCH request for file sharing
1218
- function fetchSharePatch(file) {
1219
- return __awaiter(this, void 0, void 0, function* () {
1226
+ function fetchSharePatch(file_1) {
1227
+ return __awaiter(this, arguments, void 0, function* (file, appKey = null) {
1220
1228
  const cleanEndpoint = '/files/share';
1221
- const baseUrl = getAppConfig(cleanEndpoint);
1222
- const baseSlices = baseUrl.split("/").filter(Boolean);
1223
- const url = ensureAbstractUrl(cleanEndpoint, baseSlices);
1224
1229
  // build final URL
1230
+ const url = get_app_config_url(cleanEndpoint);
1225
1231
  const token = localStorage.getItem('token');
1226
1232
  const body = JSON.stringify(file);
1227
1233
  const method = 'PATCH';
@@ -1279,42 +1285,41 @@ function Spinner() {
1279
1285
  return (jsx("p", { className: 'animate-pulse', children: "Loading\u2026" }));
1280
1286
  }
1281
1287
 
1282
- let _cachedConfig = null;
1283
- function loadConfig() {
1284
- return __awaiter(this, arguments, void 0, function* (filePath = null) {
1285
- // 1. If nobody passed a custom path, we default to "config.json" (relative)
1286
- const relativePath = filePath || 'config.json';
1287
- // 2. Resolve it against the running page’s URL (document.baseURI)
1288
- const configUrl = new URL(relativePath, document.baseURI).href;
1289
- // 3. Fetch + cache
1290
- if (_cachedConfig)
1291
- return _cachedConfig;
1292
- const res = yield fetch(configUrl);
1293
- if (!res.ok) {
1294
- throw new Error(`Could not fetch ${configUrl}: ${res.status}`);
1295
- }
1296
- _cachedConfig = (yield res.json());
1297
- return _cachedConfig;
1298
- });
1299
- }
1300
- function getConfig(key) {
1288
+ // src/read_utils.ts
1289
+ /**
1290
+ * Attempt to load the Node-only modules.
1291
+ * Returns { fs: null, path: null } in the browser.
1292
+ */
1293
+ function tryNodeModules() {
1301
1294
  return __awaiter(this, void 0, void 0, function* () {
1302
- const cfg = yield loadConfig();
1303
- return key ? cfg[key] : cfg;
1295
+ try {
1296
+ const fsMod = yield import('fs');
1297
+ const pathMod = yield import('path');
1298
+ return {
1299
+ fs: fsMod.promises, // keep the `promises` API
1300
+ path: pathMod
1301
+ };
1302
+ }
1303
+ catch (_a) {
1304
+ return { fs: null, path: null };
1305
+ }
1304
1306
  });
1305
1307
  }
1306
-
1307
1308
  /**
1308
1309
  * Reads a file at `relativeOrAbsolutePath` and returns its contents as a string.
1310
+ * In a browser this will reject immediately.
1309
1311
  */
1310
1312
  function readFileContents(relativeOrAbsolutePath) {
1311
1313
  return __awaiter(this, void 0, void 0, function* () {
1312
- // Resolve to an absolute path (so you’re always sure where it’s looking)
1314
+ const { fs, path } = yield tryNodeModules();
1315
+ if (!fs || !path) {
1316
+ throw new Error('readFileContents can only be used in Node.js');
1317
+ }
1318
+ // resolve absolute
1313
1319
  const filePath = path.isAbsolute(relativeOrAbsolutePath)
1314
1320
  ? relativeOrAbsolutePath
1315
1321
  : path.resolve(__dirname, relativeOrAbsolutePath);
1316
- // Read and return as UTF-8 text
1317
- return promises.readFile(filePath, 'utf8');
1322
+ return fs.readFile(filePath, 'utf8');
1318
1323
  });
1319
1324
  }
1320
1325
  /**
@@ -1322,42 +1327,21 @@ function readFileContents(relativeOrAbsolutePath) {
1322
1327
  */
1323
1328
  function readJsonFile(relativeOrAbsolutePath) {
1324
1329
  return __awaiter(this, void 0, void 0, function* () {
1325
- const filePath = path.isAbsolute(relativeOrAbsolutePath)
1326
- ? relativeOrAbsolutePath
1327
- : path.resolve(__dirname, relativeOrAbsolutePath);
1328
- const text = yield promises.readFile(filePath, 'utf8');
1330
+ const text = yield readFileContents(relativeOrAbsolutePath);
1329
1331
  return JSON.parse(text);
1330
1332
  });
1331
1333
  }
1332
- /**
1333
- * Read a file and optionally parse it as JSON (and even pluck a field).
1334
- *
1335
- * @param filePath Path to your file (relative to cwd or absolute)
1336
- * @param asJson If true, JSON.parse the file.
1337
- * If a string, JSON.parse then return parsed[string].
1338
- * @returns The raw string, whole parsed object, or a specific field.
1339
- */
1340
- function reader(filePath_1) {
1341
- return __awaiter(this, arguments, void 0, function* (filePath, asJson = false) {
1342
- // resolve to absolute so you know exactly where you’re reading from
1343
- const abs = path.isAbsolute(filePath)
1344
- ? filePath
1345
- : path.resolve(process.cwd(), filePath);
1346
- // 1) read file as text
1347
- const text = yield promises.readFile(abs, 'utf8');
1348
- // 2) if they want JSON, parse it
1349
- if (asJson) {
1350
- const obj = JSON.parse(text);
1351
- // 3) if they passed a string, return that property
1352
- if (typeof asJson === 'string') {
1353
- return obj[asJson];
1354
- }
1355
- return obj;
1356
- }
1357
- // 4) otherwise, just return the raw text
1358
- return text;
1334
+
1335
+ function loadConfig() {
1336
+ return __awaiter(this, void 0, void 0, function* () {
1337
+ const base = (process.env.BASE_API_URL || "").replace(/\/+$/, "");
1338
+ const url = `${base}/config.json`;
1339
+ const res = yield fetch(url);
1340
+ if (!res.ok)
1341
+ throw new Error(`Failed to load ${url}: ${res.status}`);
1342
+ yield res.json();
1359
1343
  });
1360
1344
  }
1361
1345
 
1362
- export { API_PREFIX, BASE_URL, Button, Checkbox, DEV_PREFIX, DOMAIN_NAME, Input, PROD_PREFIX, PROTOCOL, SUB_DIR, Spinner, alertit, currentUsername, currentUsernames, decodeJwt, eatAll, eatEnd, eatInner, eatOuter, ensure_list, fetchIt, fetchSharePatch, geAuthsUtilsDirectory, geBackupsUtilsDirectory, geConstantsUtilsDirectory, geEnvUtilsDirectory, geFetchUtilsDirectory, geFileUtilsDirectory, gePathUtilsDirectory, geStaticDirectory, geStringUtilsDirectory, geTypeUtilsDirectory, getAbsDir, getAbsPath, getAuthorizationHeader, getBaseDir, getComponentsUtilsDirectory, getConfig, getDbConfigsPath, getDistDir, getEnvDir, getEnvPath, getFunctionsDir, getFunctionsUtilsDirectory, getHooksUtilsDirectory, getLibUtilsDirectory, getPublicDir, getSchemasDirPath, getSchemasPath, getSrcDir, getSubstring, getToken, 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, make_path, make_sanitized_path, normalizeUrl, readFileContents, readJsonFile, reader, requestPatch, requireToken, sanitizeFilename, secureFetchIt, stripPrefixes, truncateString };
1346
+ export { API_PREFIX, BASE_URL, Button, Checkbox, DEV_PREFIX, DOMAIN_NAME, Input, PROD_PREFIX, PROTOCOL, SUB_DIR, Spinner, alertit, currentUsername, currentUsernames, decodeJwt, eatAll, eatEnd, eatInner, eatOuter, ensure_list, fetchIt, fetchSharePatch, geAuthsUtilsDirectory, geBackupsUtilsDirectory, geConstantsUtilsDirectory, geEnvUtilsDirectory, geFetchUtilsDirectory, geFileUtilsDirectory, gePathUtilsDirectory, geStaticDirectory, geStringUtilsDirectory, geTypeUtilsDirectory, getAbsDir, getAbsPath, getAuthorizationHeader, getBaseDir, getComponentsUtilsDirectory, getConfig, getDbConfigsPath, getDistDir, getEnvDir, getEnvPath, getFunctionsDir, getFunctionsUtilsDirectory, getHooksUtilsDirectory, getLibUtilsDirectory, getPublicDir, getSchemasDirPath, getSchemasPath, getSrcDir, getSubstring, getToken, 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, readFileContents, readJsonFile, requestPatch, requireToken, sanitizeFilename, secureFetchIt, stripPrefixes, truncateString };
1363
1347
  //# sourceMappingURL=index.js.map