File size: 2,333 Bytes
0f454b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6e79c3
 
 
 
 
 
 
 
 
 
 
 
 
 
427e3d4
 
 
 
c9ff965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f454b6
 
 
b6e79c3
427e3d4
c9ff965
 
 
 
0f454b6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
};