-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathutils.ts
More file actions
39 lines (32 loc) · 1.36 KB
/
utils.ts
File metadata and controls
39 lines (32 loc) · 1.36 KB
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
import { decodeBase64Url, encodeBase64Url } from "@toruslabs/metadata-helpers";
import { klona } from "klona/json";
export function base64toJSON<T = Record<string, unknown>>(b64str: string): T {
return JSON.parse(decodeBase64Url(b64str));
}
export function jsonToBase64<T = Record<string, unknown>>(json: T): string {
return encodeBase64Url(JSON.stringify(json));
}
export const htmlToElement = <T extends Element>(html: string): T => {
const template = window.document.createElement("template");
const trimmedHtml = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = trimmedHtml;
return template.content.firstChild as T;
};
export function cloneDeep<T>(object: T): T {
try {
return klona(object);
} catch {
return JSON.parse(JSON.stringify(object));
}
}
export function isObject(value: unknown): value is Record<PropertyKey, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
export function hasProperty<Key extends PropertyKey>(value: unknown, key: Key): value is Record<Key, unknown> {
return isObject(value) && key in value;
}
export function generateRecordId(): string {
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
if (typeof cr?.randomUUID !== "function") throw new Error("crypto.randomUUID must be defined");
return cr.randomUUID();
}