Spaces:
Sleeping
Sleeping
| import axios from "axios"; | |
| import { NS_promise } from "./promise"; | |
| import createError from "http-errors"; | |
| function isUrlEncoded(str: string) { | |
| try { | |
| return decodeURIComponent(str) !== str; | |
| } catch (e) { | |
| return false; | |
| } | |
| } | |
| function isValidUrlFormat(url: string) { | |
| try { | |
| new URL(url); | |
| return true; | |
| } catch (e) { | |
| return false; | |
| } | |
| } | |
| async function F_test_connection(arg0: { | |
| url: URL; | |
| headers?: Record<string, any> | null; | |
| }) { | |
| const { url, headers } = arg0; | |
| const controller = new AbortController(); | |
| const t = setTimeout(() => { | |
| controller.abort(); | |
| }, 5_000); | |
| try { | |
| const response = await fetch(url.href, { | |
| method: "GET", | |
| headers: headers || {}, | |
| signal: controller.signal | |
| }); | |
| clearTimeout(t); | |
| if (!response.ok) { | |
| console.error("✗ Network test failed:", response.statusText); | |
| throw createError( | |
| response.status, | |
| `Ping failed: ${response.statusText} ${response.status}` | |
| ); | |
| } | |
| console.log("✓ Network connection OK:", response.status); | |
| return true; | |
| } catch (error: any) { | |
| clearTimeout(t); | |
| console.error(error); | |
| // throw createError(`Cannot reach URL: ${error.message}`); | |
| throw error; | |
| } | |
| } | |
| function F_get_obj_kv(arg0: { | |
| name: string; | |
| obj?: Record<string, any> | null; | |
| }) { | |
| const { name, obj } = arg0; | |
| if (!obj || typeof obj !== "object") return; | |
| const key = Object.keys(obj).find( | |
| (k) => k.toLowerCase() === name.toLowerCase() | |
| ); | |
| return key ? obj[key] : null; | |
| } | |
| function is_plain_object(obj: any): obj is Record<string, any> { | |
| return !!obj && obj.constructor === Object; | |
| } | |
| function cleanName(name: string): string { | |
| // Replace any character that is not a letter, number, bracket, -, or _ with an underscore | |
| return name.replace(/[^\w\-()[\]{}]/g, "_"); | |
| } | |
| function cleanNameV2(name: string): string { | |
| // Keep only letters, numbers, -, _, (, ), [, ], {, }, and . | |
| // Replace everything else with _ | |
| return name.replace(/[^\w\-()[\]{}.]/g, "_"); | |
| } | |
| function isValidUnixTimestamp(timestamp: number): boolean { | |
| const date = new Date(timestamp); | |
| return !isNaN(date.getTime()); | |
| } | |
| export const NS_misc = { | |
| isUrlEncoded, | |
| isValidUrlFormat, | |
| F_test_connection, | |
| F_get_obj_kv, | |
| is_plain_object, | |
| cleanName, | |
| cleanNameV2, | |
| isValidUnixTimestamp | |
| }; | |