refactor console verbosity and internal env handling

This commit is contained in:
dswbx
2025-03-04 11:18:14 +01:00
parent 36fba4588f
commit ab73b02138
13 changed files with 256 additions and 142 deletions

View File

@@ -1,5 +1,6 @@
import { datetimeStringLocal } from "core/utils";
import colors from "picocolors";
import { env } from "core";
function hasColors() {
try {
@@ -21,85 +22,74 @@ function hasColors() {
}
}
const originalConsoles = {
error: console.error,
warn: console.warn,
info: console.info,
log: console.log,
debug: console.debug,
} as typeof console;
const __consoles = {
error: {
prefix: "ERR",
color: colors.red,
args_color: colors.red,
original: console.error,
},
warn: {
prefix: "WRN",
color: colors.yellow,
args_color: colors.yellow,
original: console.warn,
},
info: {
prefix: "INF",
color: colors.cyan,
original: console.info,
},
log: {
prefix: "LOG",
color: colors.dim,
args_color: colors.dim,
original: console.log,
},
debug: {
prefix: "DBG",
color: colors.yellow,
args_color: colors.dim,
original: console.debug,
},
} as const;
function __tty(type: any, args: any[]) {
function __tty(_type: any, args: any[]) {
const has = hasColors();
const styles = {
error: {
prefix: colors.red,
args: colors.red,
},
warn: {
prefix: colors.yellow,
args: colors.yellow,
},
info: {
prefix: colors.cyan,
},
log: {
prefix: colors.dim,
},
debug: {
prefix: colors.yellow,
args: colors.dim,
},
} as const;
const prefix = styles[type].prefix(`[${type.toUpperCase()}]`);
const cons = __consoles[_type];
const prefix = cons.color(`[${cons.prefix}]`);
const _args = args.map((a) =>
"args" in styles[type] && has && typeof a === "string" ? styles[type].args(a) : a,
"args_color" in cons && has && typeof a === "string" ? cons.args_color(a) : a,
);
return originalConsoles[type](prefix, colors.gray(datetimeStringLocal()), ..._args);
return cons.original(prefix, colors.gray(datetimeStringLocal()), ..._args);
}
export type TConsoleSeverity = keyof typeof originalConsoles;
const severities = Object.keys(originalConsoles) as TConsoleSeverity[];
let enabled = [...severities];
export function disableConsole(severities: TConsoleSeverity[] = enabled) {
enabled = enabled.filter((s) => !severities.includes(s));
}
export function enableConsole() {
enabled = [...severities];
}
export type TConsoleSeverity = keyof typeof __consoles;
const level = env("cli_log_level", "log");
const keys = Object.keys(__consoles);
export const $console = new Proxy(
{},
{
get: (_, prop) => {
if (prop in originalConsoles && enabled.includes(prop as TConsoleSeverity)) {
if (prop === "original") {
return console;
}
const current = keys.indexOf(level as string);
const requested = keys.indexOf(prop as string);
if (prop in __consoles && requested <= current) {
return (...args: any[]) => __tty(prop, args);
}
return () => null;
},
},
) as typeof console;
export async function withDisabledConsole<R>(
fn: () => Promise<R>,
sev?: TConsoleSeverity[],
): Promise<R> {
disableConsole(sev);
try {
const result = await fn();
enableConsole();
return result;
} catch (e) {
enableConsole();
throw e;
}
}
) as typeof console & {
original: typeof console;
};
export function colorizeConsole(con: typeof console) {
for (const [key] of Object.entries(originalConsoles)) {
for (const [key] of Object.entries(__consoles)) {
con[key] = $console[key];
}
}

View File

@@ -1,27 +1,72 @@
type TURSO_DB = {
url: string;
authToken: string;
};
export type Env = {};
export type Env = {
__STATIC_CONTENT: Fetcher;
ENVIRONMENT: string;
CACHE: KVNamespace;
// db
DB_DATA: TURSO_DB;
DB_SCHEMA: TURSO_DB;
// storage
STORAGE: { access_key: string; secret_access_key: string; url: string };
BUCKET: R2Bucket;
export const is_toggled = (given: unknown): boolean => {
return typeof given === "string" ? [1, "1", "true"].includes(given) : Boolean(given);
};
export function isDebug(): boolean {
try {
// @ts-expect-error - this is a global variable in dev
return __isDev === "1" || __isDev === 1;
return is_toggled(__isDev);
} catch (e) {
return false;
}
}
const envs = {
// used in $console to determine the log level
cli_log_level: {
key: "BKND_CLI_LOG_LEVEL",
validate: (v: unknown) => {
if (
typeof v === "string" &&
["log", "info", "warn", "error", "debug"].includes(v.toLowerCase())
) {
return v.toLowerCase() as keyof typeof console;
}
return undefined;
},
},
// cli create, determine ref to download template
cli_create_ref: {
key: "BKND_CLI_CREATE_REF",
validate: (v: unknown) => {
return typeof v === "string" ? v : undefined;
},
},
// module manager debug: {
modules_debug: {
key: "BKND_MODULES_DEBUG",
validate: is_toggled,
},
} as const;
export const env = <
Key extends keyof typeof envs,
Fallback = any,
R = ReturnType<(typeof envs)[Key]["validate"]>,
>(
key: Key,
fallback?: Fallback,
opts?: {
source?: any;
onFallback?: (given: unknown) => void;
onValid?: (valid: R) => void;
},
): R extends undefined ? Fallback : R => {
try {
const source = opts?.source ?? process.env;
const c = envs[key];
const g = source[c.key];
const v = c.validate(g) as any;
if (typeof v !== "undefined") {
opts?.onValid?.(v);
return v;
}
opts?.onFallback?.(g);
} catch (e) {
opts?.onFallback?.(undefined);
}
return fallback as any;
};

View File

@@ -2,7 +2,7 @@ import type { Hono, MiddlewareHandler } from "hono";
export { tbValidator } from "./server/lib/tbValidator";
export { Exception, BkndError } from "./errors";
export { isDebug } from "./env";
export { isDebug, env } from "./env";
export { type PrimaryFieldType, config, type DB } from "./config";
export { AwsClient } from "./clients/aws/AwsClient";
export {