From 900bb5e845c3ad44defbd427cae3d44a4a43321f Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Sat, 25 Feb 2023 13:15:44 +0100 Subject: feat: Initial commit --- code/app/src/utilities/_fetch.ts | 94 +++++++++++++++++++++++ code/app/src/utilities/cache.ts | 38 ++++++++++ code/app/src/utilities/colors.ts | 47 ++++++++++++ code/app/src/utilities/crypto-helpers.ts | 48 ++++++++++++ code/app/src/utilities/dom-helpers.ts | 105 +++++++++++++++++++++++++ code/app/src/utilities/global-state.ts | 22 ++++++ code/app/src/utilities/logger.ts | 118 +++++++++++++++++++++++++++++ code/app/src/utilities/misc-helpers.ts | 77 +++++++++++++++++++ code/app/src/utilities/persistent-store.ts | 111 +++++++++++++++++++++++++++ code/app/src/utilities/storage-helpers.ts | 26 +++++++ code/app/src/utilities/testing-helpers.ts | 7 ++ code/app/src/utilities/validators.ts | 34 +++++++++ 12 files changed, 727 insertions(+) create mode 100644 code/app/src/utilities/_fetch.ts create mode 100644 code/app/src/utilities/cache.ts create mode 100644 code/app/src/utilities/colors.ts create mode 100644 code/app/src/utilities/crypto-helpers.ts create mode 100644 code/app/src/utilities/dom-helpers.ts create mode 100644 code/app/src/utilities/global-state.ts create mode 100644 code/app/src/utilities/logger.ts create mode 100644 code/app/src/utilities/misc-helpers.ts create mode 100644 code/app/src/utilities/persistent-store.ts create mode 100644 code/app/src/utilities/storage-helpers.ts create mode 100644 code/app/src/utilities/testing-helpers.ts create mode 100644 code/app/src/utilities/validators.ts (limited to 'code/app/src/utilities') diff --git a/code/app/src/utilities/_fetch.ts b/code/app/src/utilities/_fetch.ts new file mode 100644 index 0000000..992c7f5 --- /dev/null +++ b/code/app/src/utilities/_fetch.ts @@ -0,0 +1,94 @@ +import { Temporal } from "temporal-polyfill"; +import { redirect } from "@sveltejs/kit"; +import { browser } from "$app/environment"; +import { goto } from "$app/navigation"; +import { SignInPageMessage, signInPageMessageQueryKey } from "$routes/(main)/(public)/sign-in"; +import { log_error } from "$utilities/logger"; +import { AccountService } from "$services/account-service"; + +export async function http_post_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { + const init = make_request_init("post", body, abort_signal); + const response = await internal_fetch_async({ url, init, timeout }); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; +} + +export async function http_get_async(url: string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { + const init = make_request_init("get", undefined, abort_signal); + const response = await internal_fetch_async({ url, init, timeout }); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; +} + +export async function http_delete_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { + const init = make_request_init("delete", body, abort_signal); + const response = await internal_fetch_async({ url, init, timeout }); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; +} + +async function internal_fetch_async(request: InternalFetchRequest): Promise { + if (!request.init) throw new Error("request.init is required"); + const fetch_request = new Request(request.url, request.init); + let response: any; + + try { + if (request.timeout && request.timeout > 500) { + response = await Promise.race([ + fetch(fetch_request), + new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), request.timeout)), + ]); + } else { + response = await fetch(fetch_request); + } + } catch (error: any) { + log_error(error); + if (error.message === "Timeout") { + console.error("Request timed out"); + } else if (error.message === "Network request failed") { + console.error("No internet connection"); + } else { + throw error; + } + } + + return response; +} + +async function redirect_if_401_async(response: Response): Promise { + if (response.status === 401) { + const redirectUrl = `/sign-in?${signInPageMessageQueryKey}=${SignInPageMessage.LOGGED_OUT}`; + await AccountService.resolve().end_session_async(); + if (browser) { + await goto(redirectUrl); + } else { + throw redirect(307, redirectUrl); + } + } + return false; +} + +function make_request_init(method: string, body?: any, signal?: AbortSignal): RequestInit { + const init = { + method, + credentials: "include", + signal, + headers: { + "X-TimeZone": Temporal.Now.timeZone().id, + }, + } as RequestInit; + + if (body) { + init.body = JSON.stringify(body); + init.headers["Content-Type"] = "application/json;charset=UTF-8"; + } + + return init; +} + +export type InternalFetchRequest = { + url: string, + init: RequestInit, + timeout?: number + retry_count?: number, +} \ No newline at end of file diff --git a/code/app/src/utilities/cache.ts b/code/app/src/utilities/cache.ts new file mode 100644 index 0000000..db9be9a --- /dev/null +++ b/code/app/src/utilities/cache.ts @@ -0,0 +1,38 @@ +import { Temporal } from "temporal-polyfill"; +import { log_debug } from "$utilities/logger"; + +let cache = {}; + +export const CacheKeys = { + isAuthenticated: "isAuthenticated" +} + +export async function cached_result_async(key: string, staleAfterSeconds: number, get_result: any, forceRefresh: boolean = false) { + if (!cache[key]) { + cache[key] = { + l: 0, + c: undefined as T, + }; + } + const staleEpoch = ((cache[key]?.l ?? 0) + staleAfterSeconds); + const isStale = forceRefresh || (staleEpoch < Temporal.Now.instant().epochSeconds); + if (isStale || !cache[key]?.c) { + cache[key].c = typeof get_result === "function" ? await get_result() : get_result; + cache[key].l = Temporal.Now.instant().epochSeconds; + } + + log_debug("Ran cached_result_async", { + cacheKey: key, + isStale, + cache: cache[key], + staleEpoch, + }); + + return cache[key].c as T; +} + +export function clear_cache_key(key: string) { + if (!key) throw new Error("No key was specified"); + cache[key].c = undefined; + log_debug("Cleared cache with key: " + key); +} \ No newline at end of file diff --git a/code/app/src/utilities/colors.ts b/code/app/src/utilities/colors.ts new file mode 100644 index 0000000..34c7992 --- /dev/null +++ b/code/app/src/utilities/colors.ts @@ -0,0 +1,47 @@ +export function generate_random_hex_color(skip_contrast_check = false) { + let hex = __generate_random_hex_color(); + if (skip_contrast_check) return hex; + while ((__calculate_contrast_ratio("#ffffff", hex) < 4.5) || (__calculate_contrast_ratio("#000000", hex) < 4.5)) { + hex = __generate_random_hex_color(); + } + + return hex; +} + +// Largely copied from chroma js api +function __generate_random_hex_color(): string { + let code = "#"; + for (let i = 0; i < 6; i++) { + code += "0123456789abcdef".charAt(Math.floor(Math.random() * 16)); + } + return code; +} + +function __calculate_contrast_ratio(hex1: string, hex2: string): number { + const rgb1 = __hex_to_rgb(hex1); + const rgb2 = __hex_to_rgb(hex2); + const l1 = __get_luminance(rgb1[0], rgb1[1], rgb1[2]); + const l2 = __get_luminance(rgb2[0], rgb2[1], rgb2[2]); + const result = l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05); + return result; +} + +function __hex_to_rgb(hex: string): number[] { + if (!hex.match(/^#([A-Fa-f0-9]{6})$/)) return []; + if (hex[0] === "#") hex = hex.substring(1, hex.length); + return [parseInt(hex.substring(0, 2), 16), parseInt(hex.substring(2, 4), 16), parseInt(hex.substring(4, 6), 16)]; +} + +function __get_luminance(r: any, g: any, b: any) { + // relative luminance + // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + r = __luminance_x(r); + g = __luminance_x(g); + b = __luminance_x(b); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +function __luminance_x(x: any) { + x /= 255; + return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} diff --git a/code/app/src/utilities/crypto-helpers.ts b/code/app/src/utilities/crypto-helpers.ts new file mode 100644 index 0000000..49af7d3 --- /dev/null +++ b/code/app/src/utilities/crypto-helpers.ts @@ -0,0 +1,48 @@ +// A formatted version of a popular md5 implementation. +// Original copyright (c) Paul Johnston & Greg Holt. +// The function itself is now 42 lines long. +// https://stackoverflow.com/a/60467595 "Don't deny." + +export function get_md5_hash(inputString: string): string { + const hc = "0123456789abcdef"; + function rh(n) { var j, s = ""; for (j = 0; j <= 3; j++) s += hc.charAt((n >> (j * 8 + 4)) & 0x0F) + hc.charAt((n >> (j * 8)) & 0x0F); return s; } + function ad(x, y) { var l = (x & 0xFFFF) + (y & 0xFFFF); var m = (x >> 16) + (y >> 16) + (l >> 16); return (m << 16) | (l & 0xFFFF); } + function rl(n, c) { return (n << c) | (n >>> (32 - c)); } + function cm(q, a, b, x, s, t) { return ad(rl(ad(ad(a, q), ad(x, t)), s), b); } + function ff(a, b, c, d, x, s, t) { return cm((b & c) | ((~b) & d), a, b, x, s, t); } + function gg(a, b, c, d, x, s, t) { return cm((b & d) | (c & (~d)), a, b, x, s, t); } + function hh(a, b, c, d, x, s, t) { return cm(b ^ c ^ d, a, b, x, s, t); } + function ii(a, b, c, d, x, s, t) { return cm(c ^ (b | (~d)), a, b, x, s, t); } + function sb(x) { + var i; var nblk = ((x.length + 8) >> 6) + 1; var blks = new Array(nblk * 16); for (i = 0; i < nblk * 16; i++) blks[i] = 0; + for (i = 0; i < x.length; i++) blks[i >> 2] |= x.charCodeAt(i) << ((i % 4) * 8); + blks[i >> 2] |= 0x80 << ((i % 4) * 8); blks[nblk * 16 - 2] = x.length * 8; return blks; + } + var i, x = sb(inputString), a = 1732584193, b = -271733879, c = -1732584194, d = 271733878, olda, oldb, oldc, oldd; + for (i = 0; i < x.length; i += 16) { + olda = a; oldb = b; oldc = c; oldd = d; + a = ff(a, b, c, d, x[i + 0], 7, -680876936); d = ff(d, a, b, c, x[i + 1], 12, -389564586); c = ff(c, d, a, b, x[i + 2], 17, 606105819); + b = ff(b, c, d, a, x[i + 3], 22, -1044525330); a = ff(a, b, c, d, x[i + 4], 7, -176418897); d = ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = ff(c, d, a, b, x[i + 6], 17, -1473231341); b = ff(b, c, d, a, x[i + 7], 22, -45705983); a = ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = ff(d, a, b, c, x[i + 9], 12, -1958414417); c = ff(c, d, a, b, x[i + 10], 17, -42063); b = ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = ff(a, b, c, d, x[i + 12], 7, 1804603682); d = ff(d, a, b, c, x[i + 13], 12, -40341101); c = ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = ff(b, c, d, a, x[i + 15], 22, 1236535329); a = gg(a, b, c, d, x[i + 1], 5, -165796510); d = gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = gg(c, d, a, b, x[i + 11], 14, 643717713); b = gg(b, c, d, a, x[i + 0], 20, -373897302); a = gg(a, b, c, d, x[i + 5], 5, -701558691); + d = gg(d, a, b, c, x[i + 10], 9, 38016083); c = gg(c, d, a, b, x[i + 15], 14, -660478335); b = gg(b, c, d, a, x[i + 4], 20, -405537848); + a = gg(a, b, c, d, x[i + 9], 5, 568446438); d = gg(d, a, b, c, x[i + 14], 9, -1019803690); c = gg(c, d, a, b, x[i + 3], 14, -187363961); + b = gg(b, c, d, a, x[i + 8], 20, 1163531501); a = gg(a, b, c, d, x[i + 13], 5, -1444681467); d = gg(d, a, b, c, x[i + 2], 9, -51403784); + c = gg(c, d, a, b, x[i + 7], 14, 1735328473); b = gg(b, c, d, a, x[i + 12], 20, -1926607734); a = hh(a, b, c, d, x[i + 5], 4, -378558); + d = hh(d, a, b, c, x[i + 8], 11, -2022574463); c = hh(c, d, a, b, x[i + 11], 16, 1839030562); b = hh(b, c, d, a, x[i + 14], 23, -35309556); + a = hh(a, b, c, d, x[i + 1], 4, -1530992060); d = hh(d, a, b, c, x[i + 4], 11, 1272893353); c = hh(c, d, a, b, x[i + 7], 16, -155497632); + b = hh(b, c, d, a, x[i + 10], 23, -1094730640); a = hh(a, b, c, d, x[i + 13], 4, 681279174); d = hh(d, a, b, c, x[i + 0], 11, -358537222); + c = hh(c, d, a, b, x[i + 3], 16, -722521979); b = hh(b, c, d, a, x[i + 6], 23, 76029189); a = hh(a, b, c, d, x[i + 9], 4, -640364487); + d = hh(d, a, b, c, x[i + 12], 11, -421815835); c = hh(c, d, a, b, x[i + 15], 16, 530742520); b = hh(b, c, d, a, x[i + 2], 23, -995338651); + a = ii(a, b, c, d, x[i + 0], 6, -198630844); d = ii(d, a, b, c, x[i + 7], 10, 1126891415); c = ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = ii(b, c, d, a, x[i + 5], 21, -57434055); a = ii(a, b, c, d, x[i + 12], 6, 1700485571); d = ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = ii(c, d, a, b, x[i + 10], 15, -1051523); b = ii(b, c, d, a, x[i + 1], 21, -2054922799); a = ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = ii(d, a, b, c, x[i + 15], 10, -30611744); c = ii(c, d, a, b, x[i + 6], 15, -1560198380); b = ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = ii(a, b, c, d, x[i + 4], 6, -145523070); d = ii(d, a, b, c, x[i + 11], 10, -1120210379); c = ii(c, d, a, b, x[i + 2], 15, 718787259); + b = ii(b, c, d, a, x[i + 9], 21, -343485551); a = ad(a, olda); b = ad(b, oldb); c = ad(c, oldc); d = ad(d, oldd); + } + return rh(a) + rh(b) + rh(c) + rh(d); +} \ No newline at end of file diff --git a/code/app/src/utilities/dom-helpers.ts b/code/app/src/utilities/dom-helpers.ts new file mode 100644 index 0000000..94a74c1 --- /dev/null +++ b/code/app/src/utilities/dom-helpers.ts @@ -0,0 +1,105 @@ +interface CreateElementOptions { + name: string, + properties?: object, + children?: Array +} + +export function create_element_from_object(elementOptions: CreateElementOptions): HTMLElement { + return create_element(elementOptions.name, elementOptions.properties, elementOptions.children); +} + +export function create_element(name: string, properties?: object, children?: Array): HTMLElement { + if (!name || name.length < 1) { + throw new Error("name is required"); + } + const node = document.createElement(name); + if (properties) { + for (const [key, value] of Object.entries(properties)) { + // @ts-ignore + node[key] = value; + } + } + + if (children && children.length > 0) { + let actualChildren = children; + if (typeof children === "function") { + // @ts-ignore + actualChildren = children(); + } + for (const child of actualChildren) { + node.appendChild(child as Node); + } + } + return node; +} + +// https://stackoverflow.com/a/45215694/11961742 +export function get_selected_options(domElement: HTMLSelectElement): Array { + const ret = []; + + // fast but not universally supported + if (domElement.selectedOptions !== undefined) { + for (let i = 0; i < domElement.selectedOptions.length; i++) { + ret.push(domElement.selectedOptions[i].value); + } + + // compatible, but can be painfully slow + } else { + for (let i = 0; i < domElement.options.length; i++) { + if (domElement.options[i].selected) { + ret.push(domElement.options[i].value); + } + } + } + return ret; +} + + +export function get_element_position(element: HTMLElement | any) { + if (!element) return {x: 0, y: 0}; + let x = 0; + let y = 0; + while (true) { + x += element.offsetLeft; + y += element.offsetTop; + if (element.offsetParent === null) { + break; + } + element = element.offsetParent; + } + return {x, y}; +} + +export function restrict_input_to_numbers(element: HTMLElement, specials: Array = [], mergeSpecialsWithDefaults: boolean = false): void { + if (!element) return; + element.addEventListener("keydown", (e) => { + const defaultSpecials = ["Backspace", "ArrowLeft", "ArrowRight", "Tab"]; + let keys = specials.length > 0 ? specials : defaultSpecials; + if (mergeSpecialsWithDefaults && specials) { + keys = [...specials, ...defaultSpecials]; + } + if (keys.indexOf(e.key) !== -1) { + return; + } + if (isNaN(parseInt(e.key))) { + e.preventDefault(); + } + }); +} + +export function element_has_focus(element: HTMLElement): boolean { + return element === document.activeElement; +} + +export function move_focus(element: HTMLElement): void { + if (!element) { + element = document.getElementsByTagName("body")[0]; + } + element.focus(); + // @ts-ignore + if (!element_has_focus(element)) { + element.setAttribute("tabindex", "-1"); + element.focus(); + } +} + diff --git a/code/app/src/utilities/global-state.ts b/code/app/src/utilities/global-state.ts new file mode 100644 index 0000000..b585ced --- /dev/null +++ b/code/app/src/utilities/global-state.ts @@ -0,0 +1,22 @@ +import { get } from "svelte/store"; +import { create_writable_persistent } from "./persistent-store"; + +const state = create_writable_persistent({ + initialState: {}, + name: "global-state" +}); + +export type GlobalStateKeys = "isLoggedIn" | "showEmailValidatedAlertWhenLoggedIn" | "all"; + +export function fgs(key: GlobalStateKeys): any { + const value = get(state); + if (key === "all") return value; + return value[key]; +} + +export function sgs(key: GlobalStateKeys, value: any) { + if (key === "all") throw new Error("Not allowed to set global state key: all"); + const stateValue = get(state); + stateValue[key] = JSON.stringify(value) + state.set(stateValue); +} \ No newline at end of file diff --git a/code/app/src/utilities/logger.ts b/code/app/src/utilities/logger.ts new file mode 100644 index 0000000..c21bd76 --- /dev/null +++ b/code/app/src/utilities/logger.ts @@ -0,0 +1,118 @@ +import { browser, dev } from "$app/environment"; +import { env } from '$env/dynamic/private'; +import { StorageKeys } from "$configuration"; +import pino, { type Logger, type LoggerOptions } from "pino"; +import { createStream } from "pino-seq"; +import type { SeqConfig } from "pino-seq"; + +function get_pino_logger(): Logger { + const config = { + name: "greatoffice-app", + level: LogLevel.current().as_string(), + customLevels: { + "INFO": LogLevel.INFO, + "WARNING": LogLevel.WARNING, + "ERROR": LogLevel.ERROR, + "DEBUG": LogLevel.DEBUG, + "SILENT": LogLevel.SILENT, + } + } as LoggerOptions; + + const seq = { + config: { + apiKey: browser ? env.SEQ_API_KEY : "", + serverUrl: browser ? env.SEQ_SERVER_URL : "" + } as SeqConfig, + streams: [{ + level: LogLevel.to_string(LogLevel.DEBUG), + }], + enabled: () => ( + !browser + && !dev + && seq.config.apiKey.length > 0 + && seq.config.serverUrl.length > 0 + ) + }; + + return seq.enabled() ? pino(config, createStream(seq.config)) : pino(config); +} + +type LogLevelString = "DEBUG" | "INFO" | "WARNING" | "ERROR" | "SILENT"; + +export const LogLevel = { + DEBUG: 0, + INFO: 1, + WARNING: 2, + ERROR: 3, + SILENT: 4, + current(): { as_string: Function, as_number: Function } { + const logLevelString = (browser ? window.sessionStorage.getItem(StorageKeys.logLevel) : env.LOG_LEVEL) as LogLevelString; + return { + as_number(): number { + return LogLevel.to_number_or_default(logLevelString, LogLevel.INFO) + }, + as_string(): LogLevelString { + return logLevelString.length > 3 ? logLevelString : LogLevel.to_string(LogLevel.INFO); + } + } + }, + to_string(levelInt: number): LogLevelString { + switch (levelInt) { + case 0: + return "DEBUG"; + case 1: + return "INFO"; + case 2: + return "WARNING"; + case 3: + return "ERROR"; + case 4: + return "SILENT"; + default: + throw new Error("Unknown LogLevel number " + levelInt); + } + }, + to_number_or_default(levelString?: string | null, defaultValue?: number): number { + if (!levelString && defaultValue) return defaultValue; + else if (!levelString && !defaultValue) throw new Error("levelString was empty, and no default value was specified"); + switch (levelString?.toUpperCase()) { + case "DEBUG": + return 0; + case "INFO": + return 1; + case "WARNING": + return 2; + case "ERROR": + return 3; + case "SILENT": + return 4; + default: + if (!defaultValue) throw new Error("Unknown LogLevel string " + levelString + ", and no defaultValue"); + else return defaultValue; + } + }, +}; + +export function log_warning(message: string, ...additional: any[]): void { + if (LogLevel.current().as_number() <= LogLevel.WARNING) { + get_pino_logger().warn(message, additional); + } +} + +export function log_debug(message: string, ...additional: any[]): void { + if (LogLevel.current().as_number() <= LogLevel.DEBUG) { + get_pino_logger().debug(message, additional); + } +} + +export function log_info(message: string, ...additional: any[]): void { + if (LogLevel.current().as_number() <= LogLevel.INFO) { + get_pino_logger().info(message, additional); + } +} + +export function log_error(message: any, ...additional: any[]): void { + if (LogLevel.current().as_number() <= LogLevel.ERROR) { + get_pino_logger().error(message, additional); + } +} \ No newline at end of file diff --git a/code/app/src/utilities/misc-helpers.ts b/code/app/src/utilities/misc-helpers.ts new file mode 100644 index 0000000..afb20e7 --- /dev/null +++ b/code/app/src/utilities/misc-helpers.ts @@ -0,0 +1,77 @@ +export function merge_obj_arr(a: Array, b: Array, props: Array): Array { + let start = 0; + let merge = []; + + while (start < a.length) { + + if (a[start] === b[start]) { + //pushing the merged objects into array + merge.push({ ...a[start], ...b[start] }); + } + //incrementing start value + start = start + 1; + } + return merge; +} + +export function no_type_check(x: any) { + return x; +} + +export function capitalise(value: string): string { + return value.charAt(0).toUpperCase() + value.slice(1); +} + +export function get_query_string(params: any = {}): string { + const map = Object.keys(params).reduce((arr: Array, key: string) => { + if (params[key] !== undefined) { + return arr.concat(`${key}=${encodeURIComponent(params[key])}`); + } + return arr; + }, [] as any); + + if (map.length) { + return `?${map.join("&")}`; + } + + return ""; +} + +export function make_url(url: string, params: object): string { + return `${url}${get_query_string(params)}`; +} + +export function noop() { +} + +export function random_string(length: number): string { + if (!length) { + throw new Error("length is undefined"); + } + let result = ""; + const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + const charactersLength = characters.length; + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +export function get_random_int(min: number, max: number): number { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +export function get_hash_code(value: string): number | undefined { + let hash = 0; + if (value.length === 0) { + return; + } + for (let i = 0; i < value.length; i++) { + const char = value.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash |= 0; + } + return hash; +} diff --git a/code/app/src/utilities/persistent-store.ts b/code/app/src/utilities/persistent-store.ts new file mode 100644 index 0000000..3f56312 --- /dev/null +++ b/code/app/src/utilities/persistent-store.ts @@ -0,0 +1,111 @@ +import { browser } from "$app/environment"; +import { writable as _writable, readable as _readable } from "svelte/store"; +import type { Writable, Readable, StartStopNotifier } from "svelte/store"; +import { log_debug, log_info } from "./logger"; + +enum StoreType { + SESSION = 0, + LOCAL = 1 +} + +interface StoreOptions { + store?: StoreType; +} + +interface WritableStoreInit { + name: string, + initialState: T, + options?: StoreOptions +} + +interface ReadableStoreInit { + name: string, + initialState: T, + callback: StartStopNotifier, + options?: StoreOptions +} + +function get_store(type: StoreType): Storage { + if (!browser) return undefined; + switch (type) { + case StoreType.SESSION: + return window.sessionStorage; + case StoreType.LOCAL: + return window.localStorage; + } +} + +function prepared_store_value(value: any): string { + try { + return JSON.stringify(value); + } catch (e) { + console.error(e); + return "__INVALID__"; + } +} + +function get_store_value(init: WritableStoreInit | ReadableStoreInit): any { + try { + const storage = get_store(init.options.store); + if (!storage) return; + const value = storage.getItem(init.name); + if (!value) return false; + return JSON.parse(value); + } catch (e) { + console.error(e); + return { __INVALID__: true }; + } +} + +function hydrate(store: Writable, init: WritableStoreInit | ReadableStoreInit): void { + const value = get_store_value(init); + if (value && store.set) store.set(value); +} + +function subscribe(store: Writable | Readable, init: WritableStoreInit | ReadableStoreInit): void { + const storage = get_store(init.options.store); + if (!storage) return; + if (!store.subscribe) return; + store.subscribe((state: any) => { + storage.setItem(init.name, prepared_store_value(state)); + }); +} + +function create_writable_persistent(init: WritableStoreInit): Writable { + if (!browser) { + log_info("WARN: Persistent store is only available in the browser"); + return; + } + if (init.options === undefined) throw new Error("init is a required parameter"); + log_debug("creating writable store with options: ", init); + const store = _writable(init.initialState); + hydrate(store, init); + subscribe(store, init); + return store; +} + +function create_readable_persistent(init: ReadableStoreInit): Readable { + if (!browser) { + log_info("WARN: Persistent store is only available in the browser"); + return; + } + if (init.options === undefined) throw new Error("init is a required parameter"); + log_debug("Creating readable store with options: ", init); + const store = _readable(init.initialState, init.callback); + // hydrate(store, options); + subscribe(store, init); + return store; +} + +export { + create_writable_persistent, + create_readable_persistent, + StoreType, +}; + +export type { + WritableStoreInit as WritableStore, + ReadableStoreInit as ReadableStore, + StoreOptions, +}; + diff --git a/code/app/src/utilities/storage-helpers.ts b/code/app/src/utilities/storage-helpers.ts new file mode 100644 index 0000000..cce655c --- /dev/null +++ b/code/app/src/utilities/storage-helpers.ts @@ -0,0 +1,26 @@ +import { browser } from "$app/environment"; +import { is_empty_object } from "./validators"; + +export type StorageType = "local" | "session"; +export const browserStorage = { + remove_with_regex(type: StorageType, regex: RegExp): void { + if (!browser) return; + const storage = (type === "local" ? window.localStorage : window.sessionStorage); + let n = storage.length; + while (n--) { + const key = storage.key(n); + if (key && regex.test(key)) { + storage.removeItem(key); + } + } + }, + set_stringified(type: StorageType, key: string, value: object): void { + if (!browser) return; + if (is_empty_object(value)) return; + (type === "local" ? window.localStorage : window.sessionStorage).setItem(key, JSON.stringify(value)); + }, + get_stringified(type: StorageType, key: string): T | any { + if (!browser) return; + return JSON.parse((type === "local" ? window.localStorage : window.sessionStorage).getItem(key) ?? "{}"); + } +} \ No newline at end of file diff --git a/code/app/src/utilities/testing-helpers.ts b/code/app/src/utilities/testing-helpers.ts new file mode 100644 index 0000000..f21412e --- /dev/null +++ b/code/app/src/utilities/testing-helpers.ts @@ -0,0 +1,7 @@ +export function get_element_by_pw_key(key: string): HTMLElement | null { + return document.querySelector("[pw-key='" + key + "']"); +} + +export function get_pw_key_selector(key: string): string { + return "[pw-key='" + key + "']"; +} \ No newline at end of file diff --git a/code/app/src/utilities/validators.ts b/code/app/src/utilities/validators.ts new file mode 100644 index 0000000..b69470e --- /dev/null +++ b/code/app/src/utilities/validators.ts @@ -0,0 +1,34 @@ +export const EMAIL_REGEX = new RegExp(/^([a-z0-9]+(?:([._\-])[a-z0-9]+)*@(?:[a-z0-9]+(?:(-)[a-z0-9]+)?\.)+[a-z0-9](?:[a-z0-9]*[a-z0-9])?)$/i); +export const URL_REGEX = new RegExp(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-.][a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm); +export const GUID_REGEX = new RegExp(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i); +export const NORWEGIAN_PHONE_NUMBER_REGEX = new RegExp(/(0047|\+47|47)?\d{8,12}/); + +export function is_email(value: string): boolean { + return EMAIL_REGEX.test(String(value).toLowerCase()); +} + +export function is_url(value: string): boolean { + return URL_REGEX.test(String(value).toLowerCase()); +} + +export function is_norwegian_phone_number(value: string): boolean { + if (value.length < 8 || value.length > 12) { + return false; + } + return NORWEGIAN_PHONE_NUMBER_REGEX.test(String(value)); +} + +export function is_guid(value: string): boolean { + if (!value) { + return false; + } + if (value[0] === "{") { + value = value.substring(1, value.length - 1); + } + return GUID_REGEX.test(value); +} + +export function is_empty_object(obj: object): boolean { + if (!obj) return true; + return obj !== void 0 && Object.keys(obj).length > 0; +} \ No newline at end of file -- cgit v1.3