diff --git a/app/src/Api.ts b/app/src/Api.ts index 593979e2..1c26cbca 100644 --- a/app/src/Api.ts +++ b/app/src/Api.ts @@ -117,8 +117,6 @@ export class Api { this.updateToken(token); } } - - //console.warn("Couldn't extract token"); } updateToken(token?: string, rebuild?: boolean) { diff --git a/app/src/App.ts b/app/src/App.ts index 1e7b52a1..96836164 100644 --- a/app/src/App.ts +++ b/app/src/App.ts @@ -15,7 +15,7 @@ import * as SystemPermissions from "modules/permissions"; import { AdminController, type AdminControllerOptions } from "modules/server/AdminController"; import { SystemController } from "modules/server/SystemController"; -// biome-ignore format: must be there +// biome-ignore format: must be here import { Api, type ApiOptions } from "Api"; import type { ServerEnv } from "modules/Controller"; diff --git a/app/src/adapter/cloudflare/cloudflare-workers.adapter.ts b/app/src/adapter/cloudflare/cloudflare-workers.adapter.ts index 523372f1..8ff1d08d 100644 --- a/app/src/adapter/cloudflare/cloudflare-workers.adapter.ts +++ b/app/src/adapter/cloudflare/cloudflare-workers.adapter.ts @@ -7,6 +7,7 @@ import { getFresh } from "./modes/fresh"; import { getCached } from "./modes/cached"; import { getDurable } from "./modes/durable"; import type { App } from "bknd"; +import { $console } from "core"; export type CloudflareEnv = object; export type CloudflareBkndConfig = RuntimeBkndConfig & { @@ -37,7 +38,7 @@ export function serve( const url = new URL(request.url); if (config.manifest && config.static === "assets") { - console.warn("manifest is not useful with static 'assets'"); + $console.warn("manifest is not useful with static 'assets'"); } else if (!config.manifest && config.static === "kv") { throw new Error("manifest is required with static 'kv'"); } diff --git a/app/src/adapter/cloudflare/config.ts b/app/src/adapter/cloudflare/config.ts index 4b9f3d7f..0c972931 100644 --- a/app/src/adapter/cloudflare/config.ts +++ b/app/src/adapter/cloudflare/config.ts @@ -5,6 +5,7 @@ import type { CloudflareBkndConfig, CloudflareEnv } from "."; import { App } from "bknd"; import { makeConfig as makeAdapterConfig } from "bknd/adapter"; import type { ExecutionContext } from "hono"; +import { $console } from "core"; export const constants = { exec_async_event_id: "cf_register_waituntil", @@ -27,12 +28,12 @@ export function makeConfig( if (!appConfig.connection) { let db: D1Database | undefined; if (bindings?.db) { - console.log("Using database from bindings"); + $console.log("Using database from bindings"); db = bindings.db; } else if (Object.keys(args).length > 0) { const binding = getBinding(args, "D1Database"); if (binding) { - console.log(`Using database from env "${binding.key}"`); + $console.log(`Using database from env "${binding.key}"`); db = binding.value; } } diff --git a/app/src/adapter/cloudflare/modes/durable.ts b/app/src/adapter/cloudflare/modes/durable.ts index 414c1974..310fd244 100644 --- a/app/src/adapter/cloudflare/modes/durable.ts +++ b/app/src/adapter/cloudflare/modes/durable.ts @@ -3,6 +3,7 @@ import type { App, CreateAppConfig } from "bknd"; import { createRuntimeApp, makeConfig } from "bknd/adapter"; import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index"; import { constants, registerAsyncsExecutionContext } from "../config"; +import { $console } from "core"; export async function getDurable( config: CloudflareBkndConfig, @@ -13,7 +14,7 @@ export async function getDurable( const key = config.key ?? "app"; if ([config.onBuilt, config.beforeBuild].some((x) => x)) { - console.log("onBuilt and beforeBuild are not supported with DurableObject mode"); + $console.warn("onBuilt and beforeBuild are not supported with DurableObject mode"); } const start = performance.now(); diff --git a/app/src/adapter/cloudflare/storage/StorageR2Adapter.ts b/app/src/adapter/cloudflare/storage/StorageR2Adapter.ts index 465c665e..030855a5 100644 --- a/app/src/adapter/cloudflare/storage/StorageR2Adapter.ts +++ b/app/src/adapter/cloudflare/storage/StorageR2Adapter.ts @@ -124,12 +124,10 @@ export class StorageR2Adapter extends StorageAdapter { } } - //console.log("response headers:before", headersToObject(responseHeaders)); this.writeHttpMetadata(responseHeaders, object); responseHeaders.set("etag", object.httpEtag); responseHeaders.set("Content-Length", String(object.size)); responseHeaders.set("Last-Modified", object.uploaded.toUTCString()); - //console.log("response headers:after", headersToObject(responseHeaders)); return new Response(object.body, { status: object.range ? 206 : 200, diff --git a/app/src/adapter/node/node.adapter.ts b/app/src/adapter/node/node.adapter.ts index 816eb92c..ed078008 100644 --- a/app/src/adapter/node/node.adapter.ts +++ b/app/src/adapter/node/node.adapter.ts @@ -4,6 +4,7 @@ import { serveStatic } from "@hono/node-server/serve-static"; import { registerLocalMediaAdapter } from "adapter/node/index"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { config as $config } from "bknd/core"; +import { $console } from "core"; type NodeEnv = NodeJS.ProcessEnv; export type NodeBkndConfig = RuntimeBkndConfig & { @@ -62,7 +63,7 @@ export function serve( fetch: createHandler(config, args, opts), }, (connInfo) => { - console.log(`Server is running on http://localhost:${connInfo.port}`); + $console.log(`Server is running on http://localhost:${connInfo.port}`); listener?.(connInfo); }, ); diff --git a/app/src/auth/AppAuth.ts b/app/src/auth/AppAuth.ts index 97395666..95d87312 100644 --- a/app/src/auth/AppAuth.ts +++ b/app/src/auth/AppAuth.ts @@ -36,7 +36,7 @@ export class AppAuth extends Module { if (!from.enabled && to.enabled) { if (to.jwt.secret === defaultSecret) { - console.warn("No JWT secret provided, generating a random one"); + $console.warn("No JWT secret provided, generating a random one"); to.jwt.secret = secureRandomString(64); } } @@ -171,7 +171,6 @@ export class AppAuth extends Module { // compare strategy and identifier if (result.data.strategy !== strategy.getName()) { - //console.log("!!! User registered with different strategy"); throw new Exception("User registered with different strategy"); } diff --git a/app/src/auth/authenticate/Authenticator.ts b/app/src/auth/authenticate/Authenticator.ts index 50077121..c4f1100c 100644 --- a/app/src/auth/authenticate/Authenticator.ts +++ b/app/src/auth/authenticate/Authenticator.ts @@ -1,6 +1,12 @@ -import { type DB, Exception, type PrimaryFieldType } from "core"; +import { $console, type DB, Exception, type PrimaryFieldType } from "core"; import { addFlashMessage } from "core/server/flash"; -import { type Static, StringEnum, type TObject, parse, runtimeSupports } from "core/utils"; +import { + type Static, + StringEnum, + type TObject, + parse, + runtimeSupports, +} from "core/utils"; import type { Context, Hono } from "hono"; import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie"; import { sign, verify } from "hono/jwt"; @@ -123,7 +129,6 @@ export class Authenticator = Record< identifier: string, profile: ProfileExchange, ): Promise { - //console.log("resolve", { action, strategy: strategy.getName(), profile }); const user = await this.userResolver(action, strategy, identifier, profile); if (user) { @@ -219,7 +224,7 @@ export class Authenticator = Record< return token; } catch (e: any) { if (e instanceof Error) { - console.error("[Error:getAuthCookie]", e.message); + $console.error("[getAuthCookie]", e.message); } return undefined; @@ -256,7 +261,6 @@ export class Authenticator = Record< // @todo: move this to a server helper isJsonRequest(c: Context): boolean { - //return c.req.header("Content-Type") === "application/x-www-form-urlencoded"; return c.req.header("Content-Type") === "application/json"; } @@ -283,7 +287,6 @@ export class Authenticator = Record< async respond(c: Context, data: AuthResponse | Error | any, redirect?: string) { const successUrl = this.getSafeUrl(c, redirect ?? this.config.cookie.pathSuccess ?? "/"); const referer = redirect ?? c.req.header("Referer") ?? successUrl; - //console.log("auth respond", { redirect, successUrl, successPath }); if ("token" in data) { await this.setAuthCookie(c, data.token); @@ -293,7 +296,6 @@ export class Authenticator = Record< } // can't navigate to "/" – doesn't work on nextjs - //console.log("auth success, redirecting to", successUrl); return c.redirect(successUrl); } @@ -307,7 +309,6 @@ export class Authenticator = Record< } await addFlashMessage(c, message, "error"); - //console.log("auth failed, redirecting to", referer); return c.redirect(referer); } diff --git a/app/src/auth/authenticate/strategies/PasswordStrategy.ts b/app/src/auth/authenticate/strategies/PasswordStrategy.ts index a43c52ac..7166d26b 100644 --- a/app/src/auth/authenticate/strategies/PasswordStrategy.ts +++ b/app/src/auth/authenticate/strategies/PasswordStrategy.ts @@ -11,13 +11,10 @@ type LoginSchema = { username: string; password: string } | { email: string; pas type RegisterSchema = { email: string; password: string; [key: string]: any }; const schema = Type.Object({ - hashing: StringEnum(["plain", "sha256" /*, "bcrypt"*/] as const, { default: "sha256" }), + hashing: StringEnum(["plain", "sha256"] as const, { default: "sha256" }), }); export type PasswordStrategyOptions = Static; -/*export type PasswordStrategyOptions2 = { - hashing?: "plain" | "bcrypt" | "sha256"; -};*/ export class PasswordStrategy implements Strategy { private options: PasswordStrategyOptions; diff --git a/app/src/auth/authenticate/strategies/index.ts b/app/src/auth/authenticate/strategies/index.ts index 86c3ba2d..2ca487e0 100644 --- a/app/src/auth/authenticate/strategies/index.ts +++ b/app/src/auth/authenticate/strategies/index.ts @@ -5,8 +5,8 @@ import { OAuthCallbackException, OAuthStrategy } from "./oauth/OAuthStrategy"; export * as issuers from "./oauth/issuers"; export { - PasswordStrategy, type PasswordStrategyOptions, + PasswordStrategy, OAuthStrategy, OAuthCallbackException, CustomOAuthStrategy, diff --git a/app/src/auth/authenticate/strategies/oauth/OAuthStrategy.ts b/app/src/auth/authenticate/strategies/oauth/OAuthStrategy.ts index f6a2d564..481e747a 100644 --- a/app/src/auth/authenticate/strategies/oauth/OAuthStrategy.ts +++ b/app/src/auth/authenticate/strategies/oauth/OAuthStrategy.ts @@ -15,7 +15,6 @@ type RequireKeys = Required> & O const schemaProvided = Type.Object( { - //type: StringEnum(["oidc", "oauth2"] as const, { default: "oidc" }), name: StringEnum(Object.keys(issuers) as ConfiguredIssuers[]), client: Type.Object( { @@ -174,8 +173,7 @@ export class OAuthStrategy implements Strategy { ) { const config = await this.getConfig(); const { client, as, type } = config; - //console.log("config", config); - console.log("callbackParams", callbackParams, options); + const parameters = oauth.validateAuthResponse( as, client, // no client_secret required @@ -183,13 +181,9 @@ export class OAuthStrategy implements Strategy { oauth.expectNoState, ); if (oauth.isOAuth2Error(parameters)) { - //console.log("callback.error", parameters); throw new OAuthCallbackException(parameters, "validateAuthResponse"); } - /*console.log( - "callback.parameters", - JSON.stringify(Object.fromEntries(parameters.entries()), null, 2), - );*/ + const response = await oauth.authorizationCodeGrantRequest( as, client, @@ -197,13 +191,9 @@ export class OAuthStrategy implements Strategy { options.redirect_uri, options.state, ); - //console.log("callback.response", response); const challenges = oauth.parseWwwAuthenticateChallenges(response); if (challenges) { - for (const challenge of challenges) { - //console.log("callback.challenge", challenge); - } // @todo: Handle www-authenticate challenges as needed throw new OAuthCallbackException(challenges, "www-authenticate"); } @@ -218,20 +208,13 @@ export class OAuthStrategy implements Strategy { expectedNonce, ); if (oauth.isOAuth2Error(result)) { - console.log("callback.error", result); // @todo: Handle OAuth 2.0 response body error throw new OAuthCallbackException(result, "processAuthorizationCodeOpenIDResponse"); } - //console.log("callback.result", result); - const claims = oauth.getValidatedIdTokenClaims(result); - //console.log("callback.IDTokenClaims", claims); - const infoRequest = await oauth.userInfoRequest(as, client, result.access_token!); - const resultUser = await oauth.processUserInfoResponse(as, client, claims.sub, infoRequest); - //console.log("callback.resultUser", resultUser); return await config.profile(resultUser, config, claims); // @todo: check claims } @@ -242,8 +225,7 @@ export class OAuthStrategy implements Strategy { ) { const config = await this.getConfig(); const { client, type, as, profile } = config; - console.log("config", { client, as, type }); - console.log("callbackParams", callbackParams, options); + const parameters = oauth.validateAuthResponse( as, client, // no client_secret required @@ -251,13 +233,9 @@ export class OAuthStrategy implements Strategy { oauth.expectNoState, ); if (oauth.isOAuth2Error(parameters)) { - console.log("callback.error", parameters); throw new OAuthCallbackException(parameters, "validateAuthResponse"); } - console.log( - "callback.parameters", - JSON.stringify(Object.fromEntries(parameters.entries()), null, 2), - ); + const response = await oauth.authorizationCodeGrantRequest( as, client, @@ -268,9 +246,6 @@ export class OAuthStrategy implements Strategy { const challenges = oauth.parseWwwAuthenticateChallenges(response); if (challenges) { - for (const challenge of challenges) { - //console.log("callback.challenge", challenge); - } // @todo: Handle www-authenticate challenges as needed throw new OAuthCallbackException(challenges, "www-authenticate"); } @@ -281,19 +256,15 @@ export class OAuthStrategy implements Strategy { try { result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response); if (oauth.isOAuth2Error(result)) { - console.log("error", result); throw new Error(); // Handle OAuth 2.0 response body error } } catch (e) { result = (await copy.json()) as any; - console.log("failed", result); } const res2 = await oauth.userInfoRequest(as, client, result.access_token!); const user = await res2.json(); - console.log("res2", res2, user); - console.log("result", result); return await config.profile(user, config, result); } @@ -303,7 +274,6 @@ export class OAuthStrategy implements Strategy { ): Promise { const type = this.getIssuerConfig().type; - console.log("type", type); switch (type) { case "oidc": return await this.oidc(callbackParams, options); @@ -327,7 +297,6 @@ export class OAuthStrategy implements Strategy { }; const setState = async (c: Context, config: TState): Promise => { - console.log("--- setting state", config); await setSignedCookie(c, cookie_name, JSON.stringify(config), secret, { secure: true, httpOnly: true, @@ -358,7 +327,6 @@ export class OAuthStrategy implements Strategy { const params = new URLSearchParams(url.search); const state = await getState(c); - console.log("state", state); // @todo: add config option to determine if state.action is allowed const redirect_uri = @@ -373,7 +341,6 @@ export class OAuthStrategy implements Strategy { try { const data = await auth.resolve(state.action, this, profile.sub, profile); - console.log("******** RESOLVED ********", data); if (state.mode === "cookie") { return await auth.respond(c, data, state.redirect); @@ -414,10 +381,8 @@ export class OAuthStrategy implements Strategy { redirect_uri, state, }); - //console.log("_state", state); await setState(c, { state, action, redirect: referer.toString(), mode: "cookie" }); - console.log("--redirecting to", response.url); return c.redirect(response.url); }); diff --git a/app/src/auth/authenticate/strategies/oauth/issuers/github.ts b/app/src/auth/authenticate/strategies/oauth/issuers/github.ts index 4f98b9f9..2874761f 100644 --- a/app/src/auth/authenticate/strategies/oauth/issuers/github.ts +++ b/app/src/auth/authenticate/strategies/oauth/issuers/github.ts @@ -34,8 +34,6 @@ export const github: IssuerConfig = { config: Omit, tokenResponse: any, ) => { - console.log("github info", info, config, tokenResponse); - try { const res = await fetch("https://api.github.com/user/emails", { headers: { @@ -45,7 +43,6 @@ export const github: IssuerConfig = { }, }); const data = (await res.json()) as GithubUserEmailResponse; - console.log("data", data); const email = data.find((e: any) => e.primary)?.email; if (!email) { throw new Error("No primary email found"); diff --git a/app/src/auth/authorize/Guard.ts b/app/src/auth/authorize/Guard.ts index 8a1da25d..96e6e1ba 100644 --- a/app/src/auth/authorize/Guard.ts +++ b/app/src/auth/authorize/Guard.ts @@ -1,4 +1,4 @@ -import { Exception, Permission } from "core"; +import { $console, Exception, Permission } from "core"; import { objectTransform } from "core/utils"; import type { Context } from "hono"; import type { ServerEnv } from "modules/Controller"; @@ -14,8 +14,6 @@ export type GuardConfig = { }; export type GuardContext = Context | GuardUserContext; -const debug = false; - export class Guard { permissions: Permission[]; roles?: Role[]; @@ -95,16 +93,15 @@ export class Guard { if (user && typeof user.role === "string") { const role = this.roles?.find((role) => role.name === user?.role); if (role) { - debug && console.log("guard: role found", [user.role]); + $console.debug("guard: role found", [user.role]); return role; } } - debug && - console.log("guard: role not found", { - user: user, - role: user?.role, - }); + $console.debug("guard: role not found", { + user: user, + role: user?.role, + }); return this.getDefaultRole(); } @@ -120,7 +117,6 @@ export class Guard { hasPermission(name: string, user?: GuardUserContext): boolean; hasPermission(permissionOrName: Permission | string, user?: GuardUserContext): boolean { if (!this.isEnabled()) { - //console.log("guard not enabled, allowing"); return true; } @@ -133,10 +129,10 @@ export class Guard { const role = this.getUserRole(user); if (!role) { - debug && console.log("guard: role not found, denying"); + $console.debug("guard: role not found, denying"); return false; } else if (role.implicit_allow === true) { - debug && console.log("guard: role implicit allow, allowing"); + $console.debug("guard: role implicit allow, allowing"); return true; } @@ -144,12 +140,11 @@ export class Guard { (rolePermission) => rolePermission.permission.name === name, ); - debug && - console.log("guard: rolePermission, allowing?", { - permission: name, - role: role.name, - allowing: !!rolePermission, - }); + $console.debug("guard: rolePermission, allowing?", { + permission: name, + role: role.name, + allowing: !!rolePermission, + }); return !!rolePermission; } diff --git a/app/src/auth/index.ts b/app/src/auth/index.ts index b99de5ab..513eb9ac 100644 --- a/app/src/auth/index.ts +++ b/app/src/auth/index.ts @@ -1,5 +1,4 @@ export { UserExistsException, UserNotFoundException, InvalidCredentialsException } from "./errors"; -export { sha256 } from "./utils/hash"; export { type ProfileExchange, type Strategy, diff --git a/app/src/auth/utils/hash.ts b/app/src/auth/utils/hash.ts deleted file mode 100644 index 5056938e..00000000 --- a/app/src/auth/utils/hash.ts +++ /dev/null @@ -1,13 +0,0 @@ -// @deprecated: moved to @bknd/core -export async function sha256(password: string, salt?: string) { - // 1. Convert password to Uint8Array - const encoder = new TextEncoder(); - const data = encoder.encode((salt ?? "") + password); - - // 2. Hash the data using SHA-256 - const hashBuffer = await crypto.subtle.digest("SHA-256", data); - - // 3. Convert hash to hex string for easier display - const hashArray = Array.from(new Uint8Array(hashBuffer)); - return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join(""); -} diff --git a/app/src/cli/commands/config.ts b/app/src/cli/commands/config.ts index 3d853ab2..81e6cb7e 100644 --- a/app/src/cli/commands/config.ts +++ b/app/src/cli/commands/config.ts @@ -8,6 +8,8 @@ export const config: CliCommand = (program) => { .option("--pretty", "pretty print") .action((options) => { const config = getDefaultConfig(); + + // biome-ignore lint/suspicious/noConsoleLog: console.log(options.pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)); }); }; diff --git a/app/src/cli/commands/copy-assets.ts b/app/src/cli/commands/copy-assets.ts index 813288c4..d9d1d12c 100644 --- a/app/src/cli/commands/copy-assets.ts +++ b/app/src/cli/commands/copy-assets.ts @@ -32,5 +32,6 @@ async function action(options: { out?: string; clean?: boolean }) { // delete ".vite" directory in out await fs.rm(path.resolve(out, ".vite"), { recursive: true }); + // biome-ignore lint/suspicious/noConsoleLog: console.log(c.green(`Assets copied to: ${c.bold(out)}`)); } diff --git a/app/src/cli/commands/create/create.ts b/app/src/cli/commands/create/create.ts index 3c5233d6..e3d7fc48 100644 --- a/app/src/cli/commands/create/create.ts +++ b/app/src/cli/commands/create/create.ts @@ -43,10 +43,12 @@ export const create: CliCommand = (program) => { function errorOutro() { $p.outro(color.red("Failed to create project.")); + // biome-ignore lint/suspicious/noConsoleLog: console.log( color.yellow("Sorry that this happened. If you think this is a bug, please report it at: ") + color.cyan("https://github.com/bknd-io/bknd/issues"), ); + // biome-ignore lint/suspicious/noConsoleLog: console.log(""); process.exit(1); } @@ -55,7 +57,14 @@ async function onExit() { await flush(); } -async function action(options: { template?: string; dir?: string; integration?: string, yes?: boolean, clean?: boolean }) { +async function action(options: { + template?: string; + dir?: string; + integration?: string; + yes?: boolean; + clean?: boolean; +}) { + // biome-ignore lint/suspicious/noConsoleLog: console.log(""); const $t = createScoped("create"); $t.capture("start", { @@ -96,10 +105,12 @@ async function action(options: { template?: string; dir?: string; integration?: $t.properties.at = "dir"; if (fs.existsSync(downloadOpts.dir)) { - const clean = options.clean ?? await $p.confirm({ - message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`, - initialValue: false, - }); + const clean = + options.clean ?? + (await $p.confirm({ + message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`, + initialValue: false, + })); if ($p.isCancel(clean)) { await onExit(); process.exit(1); @@ -174,8 +185,6 @@ async function action(options: { template?: string; dir?: string; integration?: process.exit(1); } - //console.log("integration", { type, integration }); - const choices = templates.filter((t) => t.integration === integration); if (choices.length === 0) { await onExit(); @@ -261,9 +270,11 @@ async function action(options: { template?: string; dir?: string; integration?: $p.log.success(`Updated package name to ${color.cyan(ctx.name)}`); { - const install = options.yes ?? await $p.confirm({ - message: "Install dependencies?", - }); + const install = + options.yes ?? + (await $p.confirm({ + message: "Install dependencies?", + })); if ($p.isCancel(install)) { await onExit(); diff --git a/app/src/cli/commands/debug.ts b/app/src/cli/commands/debug.ts index 9f817c3e..a9a1e6f6 100644 --- a/app/src/cli/commands/debug.ts +++ b/app/src/cli/commands/debug.ts @@ -17,6 +17,7 @@ export const debug: CliCommand = (program) => { const subjects = { paths: async () => { + // biome-ignore lint/suspicious/noConsoleLog: console.log("[PATHS]", { rootpath: getRootPath(), distPath: getDistPath(), @@ -27,6 +28,7 @@ const subjects = { }); }, routes: async () => { + // biome-ignore lint/suspicious/noConsoleLog: console.log("[APP ROUTES]"); const credentials = getConnectionCredentialsFromEnv(); const app = createApp({ connection: credentials }); diff --git a/app/src/cli/commands/run/platform.ts b/app/src/cli/commands/run/platform.ts index 480a979a..fbafedbd 100644 --- a/app/src/cli/commands/run/platform.ts +++ b/app/src/cli/commands/run/platform.ts @@ -1,6 +1,6 @@ import path from "node:path"; import type { Config } from "@libsql/client/node"; -import { config } from "core"; +import { $console, config } from "core"; import type { MiddlewareHandler } from "hono"; import open from "open"; import { fileExists, getRelativeDistPath } from "../../utils/sys"; @@ -36,7 +36,7 @@ export async function startServer( options: { port: number; open?: boolean }, ) { const port = options.port; - console.log(`Using ${server} serve`); + $console.log(`Using ${server} serve`); switch (server) { case "node": { @@ -58,7 +58,8 @@ export async function startServer( } const url = `http://localhost:${port}`; - console.info("Server listening on", url); + $console.info("Server listening on", url); + if (options.open) { await open(url); } diff --git a/app/src/cli/commands/schema.ts b/app/src/cli/commands/schema.ts index 13c1c1ef..5dceee9d 100644 --- a/app/src/cli/commands/schema.ts +++ b/app/src/cli/commands/schema.ts @@ -8,6 +8,7 @@ export const schema: CliCommand = (program) => { .option("--pretty", "pretty print") .action((options) => { const schema = getDefaultSchema(); + // biome-ignore lint/suspicious/noConsoleLog: console.log(options.pretty ? JSON.stringify(schema, null, 2) : JSON.stringify(schema)); }); }; diff --git a/app/src/cli/commands/user.ts b/app/src/cli/commands/user.ts index a7260627..6c66acc4 100644 --- a/app/src/cli/commands/user.ts +++ b/app/src/cli/commands/user.ts @@ -169,6 +169,7 @@ async function token(app: App, options: any) { } $log.info(`User found: ${c.cyan(user.email)}`); + // biome-ignore lint/suspicious/noConsoleLog: console.log( `\n${c.dim("Token:")}\n${c.yellow(await app.module.auth.authenticator.jwt(user))}\n`, ); diff --git a/app/src/core/clients/aws/AwsClient.ts b/app/src/core/clients/aws/AwsClient.ts index 838367fe..b5c33cfd 100644 --- a/app/src/core/clients/aws/AwsClient.ts +++ b/app/src/core/clients/aws/AwsClient.ts @@ -29,7 +29,6 @@ export class AwsClient extends Aws4fetchClient { } getUrl(path: string = "/", searchParamsObj: Record = {}): string { - //console.log("super:getUrl", path, searchParamsObj); const url = new URL(path); const converted = this.convertParams(searchParamsObj); Object.entries(converted).forEach(([key, value]) => { @@ -76,8 +75,6 @@ export class AwsClient extends Aws4fetchClient { } const raw = await response.text(); - //console.log("raw", raw); - //console.log(JSON.stringify(xmlToObject(raw), null, 2)); return xmlToObject(raw) as T; } diff --git a/app/src/core/events/EventManager.ts b/app/src/core/events/EventManager.ts index 1c20e58b..59efc8f7 100644 --- a/app/src/core/events/EventManager.ts +++ b/app/src/core/events/EventManager.ts @@ -1,5 +1,6 @@ import { type Event, type EventClass, InvalidEventReturn } from "./Event"; import { EventListener, type ListenerHandler, type ListenerMode } from "./EventListener"; +import { $console } from "core"; export type RegisterListenerConfig = | ListenerMode @@ -83,10 +84,6 @@ export class EventManager< } else { // @ts-expect-error slug = eventOrSlug.constructor?.slug ?? eventOrSlug.slug; - /*eventOrSlug instanceof Event - ? // @ts-expect-error slug is static - eventOrSlug.constructor.slug - : eventOrSlug.slug;*/ } return !!this.events.find((e) => slug === e.slug); @@ -128,8 +125,7 @@ export class EventManager< if (listener.id) { const existing = this.listeners.find((l) => l.id === listener.id); if (existing) { - // @todo: add a verbose option? - //console.warn(`Listener with id "${listener.id}" already exists.`); + $console.debug(`Listener with id "${listener.id}" already exists.`); return this; } } @@ -191,7 +187,7 @@ export class EventManager< // @ts-expect-error slug is static const slug = event.constructor.slug; if (!this.enabled) { - console.log("EventManager disabled, not emitting", slug); + $console.debug("EventManager disabled, not emitting", slug); return event; } @@ -240,7 +236,7 @@ export class EventManager< } catch (e) { if (e instanceof InvalidEventReturn) { this.options?.onInvalidReturn?.(_event, e); - console.warn(`Invalid return of event listener for "${slug}": ${e.message}`); + $console.warn(`Invalid return of event listener for "${slug}": ${e.message}`); } else if (this.options?.onError) { this.options.onError(_event, e); } else { diff --git a/app/src/core/object/SchemaObject.ts b/app/src/core/object/SchemaObject.ts index 8151c8a9..21199781 100644 --- a/app/src/core/object/SchemaObject.ts +++ b/app/src/core/object/SchemaObject.ts @@ -73,6 +73,7 @@ export class SchemaObject { forceParse: true, skipMark: this.isForceParse(), }); + // regardless of "noEmit" – this should always be triggered const updatedConfig = await this.onBeforeUpdate(this._config, valid); @@ -122,19 +123,15 @@ export class SchemaObject { const partial = path.length > 0 ? (set({}, path, value) as Partial>) : value; this.throwIfRestricted(partial); - //console.log(getFullPathKeys(value).map((k) => path + "." + k)); // overwrite arrays and primitives, only deep merge objects // @ts-ignore - //console.log("---alt:new", _jsonp(mergeObject(current, partial))); const config = mergeObjectWith(current, partial, (objValue, srcValue) => { if (Array.isArray(objValue) && Array.isArray(srcValue)) { return srcValue; } }); - //console.log("---new", _jsonp(config)); - //console.log("overwritePaths", this.options?.overwritePaths); if (this.options?.overwritePaths) { const keys = getFullPathKeys(value).map((k) => { // only prepend path if given @@ -149,7 +146,6 @@ export class SchemaObject { } }); }); - //console.log("overwritePaths", keys, overwritePaths); if (overwritePaths.length > 0) { // filter out less specific paths (but only if more than 1) @@ -157,12 +153,10 @@ export class SchemaObject { overwritePaths.length > 1 ? overwritePaths.filter((k) => overwritePaths.some((k2) => { - //console.log("keep?", { k, k2 }, k2 !== k && k2.startsWith(k)); return k2 !== k && k2.startsWith(k); }), ) : overwritePaths; - //console.log("specific", specific); for (const p of specific) { set(config, p, get(partial, p)); @@ -170,8 +164,6 @@ export class SchemaObject { } } - //console.log("patch", _jsonp({ path, value, partial, config, current })); - const newConfig = await this.set(config); return [partial, newConfig]; } @@ -181,14 +173,11 @@ export class SchemaObject { const partial = path.length > 0 ? (set({}, path, value) as Partial>) : value; this.throwIfRestricted(partial); - //console.log(getFullPathKeys(value).map((k) => path + "." + k)); // overwrite arrays and primitives, only deep merge objects // @ts-ignore const config = set(current, path, value); - //console.log("overwrite", { path, value, partial, config, current }); - const newConfig = await this.set(config); return [partial, newConfig]; } @@ -198,7 +187,6 @@ export class SchemaObject { if (p.length > 1) { const parent = p.slice(0, -1).join("."); if (!has(this._config, parent)) { - //console.log("parent", parent, JSON.stringify(this._config, null, 2)); throw new Error(`Parent path "${parent}" does not exist`); } } diff --git a/app/src/core/template/SimpleRenderer.ts b/app/src/core/template/SimpleRenderer.ts index 1a16d1d0..361ebe4c 100644 --- a/app/src/core/template/SimpleRenderer.ts +++ b/app/src/core/template/SimpleRenderer.ts @@ -22,7 +22,6 @@ export class SimpleRenderer { } static hasMarkup(template: string | object): boolean { - //console.log("has markup?", template); let flat: string = ""; if (Array.isArray(template) || typeof template === "object") { @@ -34,12 +33,8 @@ export class SimpleRenderer { flat = String(template); } - //console.log("** flat", flat); - const checks = ["{{", "{%", "{#", "{:"]; - const hasMarkup = checks.some((check) => flat.includes(check)); - //console.log("--has markup?", hasMarkup); - return hasMarkup; + return checks.some((check) => flat.includes(check)); } async render(template: Given): Promise { @@ -75,7 +70,6 @@ export class SimpleRenderer { } async renderString(template: string): Promise { - //console.log("*** renderString", template, this.variables); return this.engine.parseAndRender(template, this.variables, this.options); } diff --git a/app/src/core/utils/DebugLogger.ts b/app/src/core/utils/DebugLogger.ts index 23a1b446..febab17b 100644 --- a/app/src/core/utils/DebugLogger.ts +++ b/app/src/core/utils/DebugLogger.ts @@ -9,13 +9,11 @@ export class DebugLogger { } context(context: string) { - //console.log("[ settings context ]", context, this._context); this._context.push(context); return this; } clear() { - //console.log("[ clear context ]", this._context.pop(), this._context); this._context.pop(); return this; } @@ -33,6 +31,8 @@ export class DebugLogger { const indents = " ".repeat(Math.max(this._context.length - 1, 0)); const context = this._context.length > 0 ? `[${this._context[this._context.length - 1]}]` : ""; + + // biome-ignore lint/suspicious/noConsoleLog: console.log(indents, context, time, ...args); this.last = now; diff --git a/app/src/core/utils/dates.ts b/app/src/core/utils/dates.ts index 46280040..1d37cb3a 100644 --- a/app/src/core/utils/dates.ts +++ b/app/src/core/utils/dates.ts @@ -4,7 +4,6 @@ import weekOfYear from "dayjs/plugin/weekOfYear.js"; declare module "dayjs" { interface Dayjs { week(): number; - week(value: number): dayjs.Dayjs; } } diff --git a/app/src/core/utils/file.ts b/app/src/core/utils/file.ts index 96970a7b..c3db78f0 100644 --- a/app/src/core/utils/file.ts +++ b/app/src/core/utils/file.ts @@ -2,6 +2,7 @@ import { extension, guess, isMimeType } from "media/storage/mime-types-tiny"; import { randomString } from "core/utils/strings"; import type { Context } from "hono"; import { invariant } from "core/utils/runtime"; +import { $console } from "../console"; export function getContentName(request: Request): string | undefined; export function getContentName(contentDisposition: string): string | undefined; @@ -130,7 +131,7 @@ export async function getFileFromContext(c: Context): Promise { return await blobToFile(v); } } catch (e) { - console.warn("Error parsing form data", e); + $console.warn("Error parsing form data", e); } } else { try { @@ -141,7 +142,7 @@ export async function getFileFromContext(c: Context): Promise { return await blobToFile(blob, { name: getContentName(c.req.raw), type: contentType }); } } catch (e) { - console.warn("Error parsing blob", e); + $console.warn("Error parsing blob", e); } } diff --git a/app/src/core/utils/reqres.ts b/app/src/core/utils/reqres.ts index 3e9ec122..7f6c0844 100644 --- a/app/src/core/utils/reqres.ts +++ b/app/src/core/utils/reqres.ts @@ -1,7 +1,3 @@ -import { randomString } from "core/utils/strings"; -import type { Context } from "hono"; -import { extension, guess, isMimeType } from "media/storage/mime-types-tiny"; - export function headersToObject(headers: Headers): Record { if (!headers) return {}; return { ...Object.fromEntries(headers.entries()) }; diff --git a/app/src/core/utils/typebox/index.ts b/app/src/core/utils/typebox/index.ts index 2da76668..036e3f7b 100644 --- a/app/src/core/utils/typebox/index.ts +++ b/app/src/core/utils/typebox/index.ts @@ -107,7 +107,6 @@ export function parse( } else if (options?.onError) { options.onError(Errors(schema, data)); } else { - //console.warn("errors", JSON.stringify([...Errors(schema, data)], null, 2)); throw new TypeInvalidError(schema, data); } @@ -119,13 +118,11 @@ export function parseDecode( schema: Schema, data: RecursivePartial>, ): tb.StaticDecode { - //console.log("parseDecode", schema, data); const parsed = Default(schema, data); if (Check(schema, parsed)) { return parsed as tb.StaticDecode; } - //console.log("errors", ...Errors(schema, data)); throw new TypeInvalidError(schema, data); } diff --git a/app/src/data/api/DataController.ts b/app/src/data/api/DataController.ts index 2013a805..333b9a38 100644 --- a/app/src/data/api/DataController.ts +++ b/app/src/data/api/DataController.ts @@ -1,4 +1,4 @@ -import { isDebug, tbValidator as tb } from "core"; +import { $console, isDebug, tbValidator as tb } from "core"; import { StringEnum } from "core/utils"; import * as tbbox from "@sinclair/typebox"; import { @@ -47,7 +47,6 @@ export class DataController extends Controller { const template = { data: res.data, meta }; // @todo: this works but it breaks in FE (need to improve DataTable) - //return objectCleanEmpty(template) as any; // filter empty return Object.fromEntries( Object.entries(template).filter(([_, v]) => typeof v !== "undefined" && v !== null), @@ -58,7 +57,6 @@ export class DataController extends Controller { const template = { data: res.data }; // filter empty - //return objectCleanEmpty(template); return Object.fromEntries(Object.entries(template).filter(([_, v]) => v !== undefined)); } @@ -74,11 +72,6 @@ export class DataController extends Controller { const { permission, auth } = this.middlewares; const hono = this.create().use(auth(), permission(SystemPermissions.accessApi)); - const definedEntities = this.em.entities.map((e) => e.name); - const tbNumber = Type.Transform(Type.String({ pattern: "^[1-9][0-9]{0,}$" })) - .Decode(Number.parseInt) - .Encode(String); - // @todo: sample implementation how to augment handler with additional info function handler(name: string, h: HH): any { const func = h; @@ -143,10 +136,8 @@ export class DataController extends Controller { }), ), async (c) => { - //console.log("request", c.req.raw); const { entity, context } = c.req.param(); if (!this.entityExists(entity)) { - console.warn("not found:", entity, definedEntities); return this.notFound(c); } const _entity = this.em.entity(entity); @@ -256,7 +247,6 @@ export class DataController extends Controller { async (c) => { const { entity } = c.req.param(); if (!this.entityExists(entity)) { - console.warn("not found:", entity, definedEntities); return this.notFound(c); } const options = c.req.valid("query") as RepoQuery; @@ -330,7 +320,6 @@ export class DataController extends Controller { return this.notFound(c); } const options = (await c.req.valid("json")) as RepoQuery; - //console.log("options", options); const result = await this.em.repository(entity).findMany(options); return c.json(this.repoResult(result), { status: result.data ? 200 : 404 }); diff --git a/app/src/data/connection/sqlite/LibsqlConnection.ts b/app/src/data/connection/sqlite/LibsqlConnection.ts index 75183571..c8b4441a 100644 --- a/app/src/data/connection/sqlite/LibsqlConnection.ts +++ b/app/src/data/connection/sqlite/LibsqlConnection.ts @@ -38,7 +38,7 @@ export class LibsqlConnection extends SqliteConnection { if (clientOrCredentials && "url" in clientOrCredentials) { let { url, authToken, protocol } = clientOrCredentials; if (protocol && LIBSQL_PROTOCOLS.includes(protocol)) { - console.log("changing protocol to", protocol); + $console.log("changing protocol to", protocol); const [, rest] = url.split("://"); url = `${protocol}://${rest}`; } diff --git a/app/src/data/data-schema.ts b/app/src/data/data-schema.ts index faac1ee1..38f272f5 100644 --- a/app/src/data/data-schema.ts +++ b/app/src/data/data-schema.ts @@ -35,7 +35,6 @@ export type TAppDataField = Static; export type TAppDataEntityFields = Static; export const entitiesSchema = tb.Type.Object({ - //name: Type.String(), type: tb.Type.Optional( tb.Type.String({ enum: entityTypes, default: "regular", readOnly: true }), ), @@ -63,7 +62,6 @@ export const indicesSchema = tb.Type.Object( { entity: tb.Type.String(), fields: tb.Type.Array(tb.Type.String(), { minItems: 1 }), - //name: Type.Optional(Type.String()), unique: tb.Type.Optional(tb.Type.Boolean({ default: false })), }, { diff --git a/app/src/data/entities/Entity.ts b/app/src/data/entities/Entity.ts index 5d1f2b24..a59672fa 100644 --- a/app/src/data/entities/Entity.ts +++ b/app/src/data/entities/Entity.ts @@ -1,4 +1,4 @@ -import { config } from "core"; +import { $console, config } from "core"; import { type Static, StringEnum, @@ -184,9 +184,9 @@ export class Entity< if (existing) { // @todo: for now adding a graceful method if (JSON.stringify(existing) === JSON.stringify(field)) { - /*console.warn( + $console.warn( `Field "${field.name}" already exists on entity "${this.name}", but it's the same, so skipping.`, - );*/ + ); return; } @@ -233,7 +233,13 @@ export class Entity< for (const field of fields) { if (!field.isValid(data[field.name], context)) { - console.log("Entity.isValidData:invalid", context, field.name, data[field.name]); + $console.warn( + "invalid data given for", + this.name, + context, + field.name, + data[field.name], + ); if (options?.explain) { throw new Error(`Field "${field.name}" has invalid data: "${data[field.name]}"`); } @@ -259,7 +265,6 @@ export class Entity< const _fields = Object.fromEntries(fields.map((field) => [field.name, field])); const schema = Type.Object( transformObject(_fields, (field) => { - //const hidden = field.isHidden(options?.context); const fillable = field.isFillable(options?.context); return { title: field.config.label, @@ -277,9 +282,7 @@ export class Entity< toJSON() { return { - //name: this.name, type: this.type, - //fields: transformObject(this.fields, (field) => field.toJSON()), fields: Object.fromEntries(this.fields.map((field) => [field.name, field.toJSON()])), config: this.config, }; diff --git a/app/src/data/entities/EntityManager.ts b/app/src/data/entities/EntityManager.ts index 8d36cf3f..e4e71c22 100644 --- a/app/src/data/entities/EntityManager.ts +++ b/app/src/data/entities/EntityManager.ts @@ -1,4 +1,4 @@ -import type { DB as DefaultDB } from "core"; +import { $console, type DB as DefaultDB } from "core"; import { EventManager } from "core/events"; import { sql } from "kysely"; import { Connection } from "../connection/Connection"; @@ -55,7 +55,6 @@ export class EntityManager { this.connection = connection; this.emgr = emgr ?? new EventManager(); - //console.log("registering events", EntityManager.Events); this.emgr.registerEvents(EntityManager.Events); } @@ -90,7 +89,9 @@ export class EntityManager { if (existing) { // @todo: for now adding a graceful method if (JSON.stringify(existing) === JSON.stringify(entity)) { - //console.warn(`Entity "${entity.name}" already exists, but it's the same, so skipping.`); + $console.warn( + `Entity "${entity.name}" already exists, but it's the same, skipping adding it.`, + ); return; } @@ -108,7 +109,6 @@ export class EntityManager { } this._entities[entityIndex] = entity; - // caused issues because this.entity() was using a reference (for when initial config was given) } @@ -295,7 +295,6 @@ export class EntityManager { return { entities: Object.fromEntries(this.entities.map((e) => [e.name, e.toJSON()])), relations: Object.fromEntries(this.relations.all.map((r) => [r.getName(), r.toJSON()])), - //relations: this.relations.all.map((r) => r.toJSON()), indices: Object.fromEntries(this.indices.map((i) => [i.name, i.toJSON()])), }; } diff --git a/app/src/data/entities/Mutator.ts b/app/src/data/entities/Mutator.ts index ce6330a0..0e4dae44 100644 --- a/app/src/data/entities/Mutator.ts +++ b/app/src/data/entities/Mutator.ts @@ -1,4 +1,4 @@ -import type { DB as DefaultDB, PrimaryFieldType } from "core"; +import { $console, type DB as DefaultDB, type PrimaryFieldType } from "core"; import { type EmitsEvents, EventManager } from "core/events"; import type { DeleteQueryBuilder, InsertQueryBuilder, UpdateQueryBuilder } from "kysely"; import { type TActionContext, WhereBuilder } from ".."; @@ -72,7 +72,6 @@ export class Mutator< // if relation field (include key and value in validatedData) if (Array.isArray(result)) { - //console.log("--- (instructions)", result); const [relation_key, relation_value] = result; validatedData[relation_key] = relation_value; } @@ -122,7 +121,7 @@ export class Mutator< }; } catch (e) { // @todo: redact - console.log("[Error in query]", sql); + $console.error("[Error in query]", sql); throw e; } } diff --git a/app/src/data/fields/BooleanField.ts b/app/src/data/fields/BooleanField.ts index d4239d93..5349b6e9 100644 --- a/app/src/data/fields/BooleanField.ts +++ b/app/src/data/fields/BooleanField.ts @@ -49,7 +49,6 @@ export class BooleanField extends Field< } override transformRetrieve(value: unknown): boolean | null { - //console.log("Boolean:transformRetrieve:value", value); if (typeof value === "undefined" || value === null) { if (this.isRequired()) return false; if (this.hasDefault()) return this.getDefault(); diff --git a/app/src/data/fields/DateField.ts b/app/src/data/fields/DateField.ts index 2fc21d97..b2055a08 100644 --- a/app/src/data/fields/DateField.ts +++ b/app/src/data/fields/DateField.ts @@ -1,13 +1,13 @@ import { type Static, StringEnum, dayjs } from "core/utils"; import type { EntityManager } from "../entities"; import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; +import { $console } from "core"; import * as tbbox from "@sinclair/typebox"; const { Type } = tbbox; export const dateFieldConfigSchema = Type.Composite( [ Type.Object({ - //default_value: Type.Optional(Type.Date()), type: StringEnum(["date", "datetime", "week"] as const, { default: "date" }), timezone: Type.Optional(Type.String()), min_date: Type.Optional(Type.String()), @@ -53,13 +53,11 @@ export class DateField extends Field< } private parseDateFromString(value: string): Date { - //console.log("parseDateFromString", value); if (this.config.type === "week" && value.includes("-W")) { const [year, week] = value.split("-W").map((n) => Number.parseInt(n, 10)) as [ number, number, ]; - //console.log({ year, week }); // @ts-ignore causes errors on build? return dayjs().year(year).week(week).toDate(); } @@ -69,15 +67,12 @@ export class DateField extends Field< override getValue(value: string, context?: TRenderContext): string | undefined { if (value === null || !value) return; - //console.log("getValue", { value, context }); const date = this.parseDateFromString(value); - //console.log("getValue.date", date); if (context === "submit") { try { return date.toISOString(); } catch (e) { - //console.warn("DateField.getValue:value/submit", value, e); return undefined; } } @@ -86,7 +81,7 @@ export class DateField extends Field< try { return `${date.getFullYear()}-W${dayjs(date).week()}`; } catch (e) { - console.warn("error - DateField.getValue:week", value, e); + $console.warn("DateField.getValue:week error", value, String(e)); return; } } @@ -99,8 +94,7 @@ export class DateField extends Field< return this.formatDate(local); } catch (e) { - console.warn("DateField.getValue:value", value); - console.warn("DateField.getValue:e", e); + $console.warn("DateField.getValue error", this.config.type, value, String(e)); return; } } @@ -119,7 +113,6 @@ export class DateField extends Field< } override transformRetrieve(_value: string): Date | null { - //console.log("transformRetrieve DateField", _value); const value = super.transformRetrieve(_value); if (value === null) return null; @@ -138,7 +131,6 @@ export class DateField extends Field< const value = await super.transformPersist(_value, em, context); if (this.nullish(value)) return value; - //console.log("transformPersist DateField", value); switch (this.config.type) { case "date": case "week": diff --git a/app/src/data/fields/EnumField.ts b/app/src/data/fields/EnumField.ts index 99339463..8bb65d63 100644 --- a/app/src/data/fields/EnumField.ts +++ b/app/src/data/fields/EnumField.ts @@ -1,7 +1,7 @@ import { Const, type Static, StringEnum } from "core/utils"; import type { EntityManager } from "data"; import { TransformPersistFailedException } from "../errors"; -import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field"; +import { baseFieldConfigSchema, Field, type TActionContext, type TRenderContext } from "./Field"; import * as tbbox from "@sinclair/typebox"; const { Type } = tbbox; @@ -55,10 +55,6 @@ export class EnumField) { super(name, config); - /*if (this.config.options.values.length === 0) { - throw new Error(`Enum field "${this.name}" requires at least one option`); - }*/ - if (this.config.default_value && !this.isValidValue(this.config.default_value)) { throw new Error(`Default value "${this.config.default_value}" is not a valid option`); } @@ -71,10 +67,6 @@ export class EnumField ({ label: option, value: option })); } diff --git a/app/src/data/fields/JsonField.ts b/app/src/data/fields/JsonField.ts index e4259c95..4dae1cf5 100644 --- a/app/src/data/fields/JsonField.ts +++ b/app/src/data/fields/JsonField.ts @@ -84,7 +84,6 @@ export class JsonField { const value = await super.transformPersist(_value, em, context); - //console.log("value", value); if (this.nullish(value)) return value; if (!this.isSerializable(value)) { diff --git a/app/src/data/fields/JsonSchemaField.ts b/app/src/data/fields/JsonSchemaField.ts index 7253d052..c1f3a2ec 100644 --- a/app/src/data/fields/JsonSchemaField.ts +++ b/app/src/data/fields/JsonSchemaField.ts @@ -48,22 +48,16 @@ export class JsonSchemaField< override isValid(value: any, context: TActionContext = "update"): boolean { const parentValid = super.isValid(value, context); - //console.log("jsonSchemaField:isValid", this.getJsonSchema(), this.name, value, parentValid); if (parentValid) { // already checked in parent if (!this.isRequired() && (!value || typeof value !== "object")) { - //console.log("jsonschema:valid: not checking", this.name, value, context); return true; } const result = this.validator.validate(value); - //console.log("jsonschema:errors", this.name, result.errors); return result.valid; - } else { - //console.log("jsonschema:invalid", this.name, value, context); } - //console.log("jsonschema:invalid:fromParent", this.name, value, context); return false; } @@ -91,7 +85,6 @@ export class JsonSchemaField< try { return Default(FromSchema(this.getJsonSchema()), {}); } catch (e) { - //console.error("jsonschema:transformRetrieve", e); return null; } } else if (this.hasDefault()) { @@ -109,13 +102,9 @@ export class JsonSchemaField< ): Promise { const value = await super.transformPersist(_value, em, context); if (this.nullish(value)) return value; - //console.log("jsonschema:transformPersist", this.name, _value, context); if (!this.isValid(value)) { - //console.error("jsonschema:transformPersist:invalid", this.name, value); throw new TransformPersistFailedException(this.name, value); - } else { - //console.log("jsonschema:transformPersist:valid", this.name, value); } if (!value || typeof value !== "object") return this.getDefault(); diff --git a/app/src/data/fields/field-test-suite.ts b/app/src/data/fields/field-test-suite.ts index 4a2394d2..f32e58cb 100644 --- a/app/src/data/fields/field-test-suite.ts +++ b/app/src/data/fields/field-test-suite.ts @@ -98,12 +98,9 @@ export function fieldTestSuite( test("toJSON", async () => { const _config = { ..._requiredConfig, - //order: 1, fillable: true, required: false, hidden: false, - //virtual: false, - //default_value: undefined }; function fieldJson(field: Field) { @@ -115,19 +112,16 @@ export function fieldTestSuite( } expect(fieldJson(noConfigField)).toEqual({ - //name: "no_config", type: noConfigField.type, config: _config, }); expect(fieldJson(fillable)).toEqual({ - //name: "fillable", type: noConfigField.type, config: _config, }); expect(fieldJson(required)).toEqual({ - //name: "required", type: required.type, config: { ..._config, @@ -136,7 +130,6 @@ export function fieldTestSuite( }); expect(fieldJson(hidden)).toEqual({ - //name: "hidden", type: required.type, config: { ..._config, @@ -145,7 +138,6 @@ export function fieldTestSuite( }); expect(fieldJson(dflt)).toEqual({ - //name: "dflt", type: dflt.type, config: { ..._config, @@ -154,7 +146,6 @@ export function fieldTestSuite( }); expect(fieldJson(requiredAndDefault)).toEqual({ - //name: "full", type: requiredAndDefault.type, config: { ..._config, diff --git a/app/src/data/fields/indices/EntityIndex.ts b/app/src/data/fields/indices/EntityIndex.ts index 239510b8..e8af2e65 100644 --- a/app/src/data/fields/indices/EntityIndex.ts +++ b/app/src/data/fields/indices/EntityIndex.ts @@ -39,7 +39,6 @@ export class EntityIndex { return { entity: this.entity.name, fields: this.fields.map((f) => f.name), - //name: this.name, unique: this.unique, }; } diff --git a/app/src/data/helper.ts b/app/src/data/helper.ts index 838b3b07..79dfeb0b 100644 --- a/app/src/data/helper.ts +++ b/app/src/data/helper.ts @@ -18,7 +18,6 @@ export function getChangeSet( data: EntityData, fields: Field[], ): EntityData { - //console.log("getChangeSet", formData, data); return transform( formData, (acc, _value, key) => { @@ -32,17 +31,6 @@ export function getChangeSet( // @todo: add typing for "action" if (action === "create" || newValue !== data[key]) { acc[key] = newValue; - /*console.log("changed", { - key, - value, - valueType: typeof value, - prev: data[key], - newValue, - new: value, - sent: acc[key] - });*/ - } else { - //console.log("no change", key, value, data[key]); } }, {} as typeof formData, diff --git a/app/src/data/relations/EntityRelation.ts b/app/src/data/relations/EntityRelation.ts index 4b8459a4..49277d1e 100644 --- a/app/src/data/relations/EntityRelation.ts +++ b/app/src/data/relations/EntityRelation.ts @@ -14,15 +14,6 @@ const { Type } = tbbox; export type KyselyJsonFrom = any; export type KyselyQueryBuilder = SelectQueryBuilder; -/*export type RelationConfig = { - mappedBy?: string; - inversedBy?: string; - sourceCardinality?: number; - connectionTable?: string; - connectionTableMappedName?: string; - required?: boolean; -};*/ - export type BaseRelationConfig = Static; // @todo: add generic type for relation config @@ -167,7 +158,6 @@ export abstract class EntityRelation< * @param entity */ isListableFor(entity: Entity): boolean { - //console.log("isListableFor", entity.name, this.source.entity.name, this.target.entity.name); return this.target.entity.name === entity.name; } diff --git a/app/src/data/relations/ManyToManyRelation.ts b/app/src/data/relations/ManyToManyRelation.ts index 49ffac3c..47674328 100644 --- a/app/src/data/relations/ManyToManyRelation.ts +++ b/app/src/data/relations/ManyToManyRelation.ts @@ -1,9 +1,9 @@ import type { Static } from "core/utils"; import type { ExpressionBuilder } from "kysely"; import { Entity, type EntityManager } from "../entities"; -import { type Field, PrimaryField, VirtualField } from "../fields"; +import { type Field, PrimaryField } from "../fields"; import type { RepoQuery } from "../server/data-query-impl"; -import { EntityRelation, type KyselyJsonFrom, type KyselyQueryBuilder } from "./EntityRelation"; +import { EntityRelation, type KyselyQueryBuilder } from "./EntityRelation"; import { EntityRelationAnchor } from "./EntityRelationAnchor"; import { RelationField } from "./RelationField"; import { type RelationType, RelationTypes } from "./relation-types"; @@ -48,7 +48,6 @@ export class ManyToManyRelation extends EntityRelation; export type RelationFieldBaseConfig = { label?: string }; @@ -33,16 +28,6 @@ export class RelationField extends Field { return relationFieldConfigSchema; } - /*constructor(name: string, config?: Partial) { - //relation_name = relation_name || target.name; - //const name = [relation_name, target.getPrimaryField().name].join("_"); - super(name, config); - - //console.log(this.config); - //this.relation.target = target; - //this.relation.name = relation_name; - }*/ - static create( relation: EntityRelation, target: EntityRelationAnchor, @@ -52,7 +37,7 @@ export class RelationField extends Field { target.reference ?? target.entity.name, target.entity.getPrimaryField().name, ].join("_"); - //console.log('name', name); + return new RelationField(name, { ...config, required: relation.required, diff --git a/app/src/data/relations/RelationMutator.ts b/app/src/data/relations/RelationMutator.ts index 60366e92..225885b6 100644 --- a/app/src/data/relations/RelationMutator.ts +++ b/app/src/data/relations/RelationMutator.ts @@ -63,7 +63,6 @@ export class RelationMutator { // make sure it's a primitive value // @todo: this is not a good way of checking primitives. Null is also an object if (typeof value === "object") { - console.log("value", value); throw new Error(`Invalid value for relation field "${key}" given, expected primitive.`); } diff --git a/app/src/data/test-types.ts b/app/src/data/test-types.ts deleted file mode 100644 index 1c23fb94..00000000 --- a/app/src/data/test-types.ts +++ /dev/null @@ -1,78 +0,0 @@ -type Field = { - _type: Type; - _required: Required; -}; -type TextField = Field & { - _type: string; - required: () => TextField; -}; -type NumberField = Field & { - _type: number; - required: () => NumberField; -}; - -type Entity> = {}> = { name: string; fields: Fields }; - -function entity>>( - name: string, - fields: Fields, -): Entity { - return { name, fields }; -} - -function text(): TextField { - return {} as any; -} -function number(): NumberField { - return {} as any; -} - -const field1 = text(); -const field1_req = text().required(); -const field2 = number(); -const user = entity("users", { - name: text().required(), - bio: text(), - age: number(), - some: number().required(), -}); - -type InferEntityFields = T extends Entity - ? { - [K in keyof Fields]: Fields[K] extends { _type: infer Type; _required: infer Required } - ? Required extends true - ? Type - : Type | undefined - : never; - } - : never; - -type Prettify = { - [K in keyof T]: T[K]; -}; -export type Simplify = { [KeyType in keyof T]: T[KeyType] } & {}; - -// from https://github.com/type-challenges/type-challenges/issues/28200 -type Merge = { - [K in keyof T]: T[K]; -}; -type OptionalUndefined< - T, - Props extends keyof T = keyof T, - OptionsProps extends keyof T = Props extends keyof T - ? undefined extends T[Props] - ? Props - : never - : never, -> = Merge< - { - [K in OptionsProps]?: T[K]; - } & { - [K in Exclude]: T[K]; - } ->; - -type UserFields = InferEntityFields; -type UserFields2 = Simplify>; - -const obj: UserFields2 = { name: "h", age: 1, some: 1 }; diff --git a/app/src/flows/AppFlows.ts b/app/src/flows/AppFlows.ts index a75defef..6e9ac364 100644 --- a/app/src/flows/AppFlows.ts +++ b/app/src/flows/AppFlows.ts @@ -25,7 +25,6 @@ export class AppFlows extends Module { } override async build() { - //console.log("building flows", this.config); const flows = transformObject(this.config.flows, (flowConfig, name) => { return Flow.fromObject(name, flowConfig as any, TASKS); }); diff --git a/app/src/flows/flows/Execution.ts b/app/src/flows/flows/Execution.ts index fc69f74b..61bf05e9 100644 --- a/app/src/flows/flows/Execution.ts +++ b/app/src/flows/flows/Execution.ts @@ -2,6 +2,7 @@ import { Event, EventManager, type ListenerHandler } from "core/events"; import type { EmitsEvents } from "core/events"; import type { Task, TaskResult } from "../tasks/Task"; import type { Flow } from "./Flow"; +import { $console } from "core"; export type TaskLog = TaskResult & { task: Task; @@ -185,10 +186,9 @@ export class Execution implements EmitsEvents { await Promise.all(promises); return this.run(); } catch (e) { - console.log("RuntimeExecutor: error", e); + $console.error("RuntimeExecutor: error", e); // for now just throw - // biome-ignore lint/complexity/noUselessCatch: @todo: add error task on flow throw e; } } diff --git a/app/src/flows/flows/Flow.ts b/app/src/flows/flows/Flow.ts index 287a46e0..c924756a 100644 --- a/app/src/flows/flows/Flow.ts +++ b/app/src/flows/flows/Flow.ts @@ -5,6 +5,7 @@ import { Condition, TaskConnection } from "../tasks/TaskConnection"; import { Execution } from "./Execution"; import { FlowTaskConnector } from "./FlowTaskConnector"; import { Trigger } from "./triggers/Trigger"; +import { $console } from "core"; type Jsoned object }> = ReturnType; @@ -53,8 +54,6 @@ export class Flow { } getSequence(sequence: Task[][] = []): Task[][] { - //console.log("queue", queue.map((step) => step.map((t) => t.name))); - // start task if (sequence.length === 0) { sequence.push([this.startTask]); @@ -69,7 +68,6 @@ export class Flow { // check if task already in one of queue steps // this is when we have a circle back if (sequence.some((step) => step.includes(outTask))) { - //console.log("Task already in queue", outTask.name); return; } nextStep.push(outTask); @@ -110,14 +108,6 @@ export class Flow { return this; } - /*getResponse() { - if (!this.respondingTask) { - return; - } - - return this.respondingTask.log.output; - }*/ - // @todo: check for existence addConnection(connection: TaskConnection) { // check if connection already exists @@ -179,7 +169,7 @@ export class Flow { // @ts-ignore return new cls(name, obj.params); } catch (e: any) { - console.log("Error creating task", name, obj.type, obj, taskClass); + $console.error("Error creating task", name, obj.type, obj, taskClass); throw new Error(`Error creating task ${obj.type}: ${e.message}`); } }); diff --git a/app/src/flows/flows/FlowTaskConnector.ts b/app/src/flows/flows/FlowTaskConnector.ts index cd11ff57..0622db18 100644 --- a/app/src/flows/flows/FlowTaskConnector.ts +++ b/app/src/flows/flows/FlowTaskConnector.ts @@ -31,37 +31,11 @@ export class FlowTaskConnector { } } - /*const targetDepth = this.task(target).getDepth(); - console.log("depth", ownDepth, targetDepth); - - // if target has a lower depth - if (targetDepth > 0 && ownDepth >= targetDepth) { - // check for unique out conditions - console.log( - "out conditions", - this.source.name, - this.getOutConnections().map((c) => [c.target.name, c.condition]) - ); - if ( - this.getOutConnections().some( - (c) => - c.condition[0] === condition[0] && - c.condition[1] === condition[1] - ) - ) { - throw new Error( - "Task cannot be connected to a deeper task with the same condition" - ); - } - }*/ - this.flow.addConnection(new TaskConnection(this.source, target, { condition, max_retries })); } asOutputFor(target: Task, condition?: Condition) { this.task(target).asInputFor(this.source, condition); - //new FlowTaskConnector(this.flow, target).asInputFor(this.source); - //this.flow.addConnection(new TaskConnection(target, this.source)); } getNext() { @@ -107,12 +81,4 @@ export class FlowTaskConnector { getOutTasks(result?: TaskResult): Task[] { return this.getOutConnections(result).map((c) => c.target); } - - /*getNextRunnableConnections() { - return this.getOutConnections().filter((c) => c.source.log.success); - } - - getNextRunnableTasks() { - return this.getNextRunnableConnections().map((c) => c.target); - }*/ } diff --git a/app/src/flows/flows/executors/RuntimeExecutor.ts b/app/src/flows/flows/executors/RuntimeExecutor.ts index 4f8ec314..46ea1054 100644 --- a/app/src/flows/flows/executors/RuntimeExecutor.ts +++ b/app/src/flows/flows/executors/RuntimeExecutor.ts @@ -1,4 +1,5 @@ import type { Task } from "../../tasks/Task"; +import { $console } from "core"; export class RuntimeExecutor { async run( @@ -10,7 +11,6 @@ export class RuntimeExecutor { return; } - //const promises = tasks.map((t) => t.run()); const promises = tasks.map(async (t) => { const result = await t.run(); onDone?.(t, result); @@ -20,7 +20,7 @@ export class RuntimeExecutor { try { await Promise.all(promises); } catch (e) { - console.log("RuntimeExecutor: error", e); + $console.error("RuntimeExecutor: error", e); } return this.run(nextTasks, onDone); diff --git a/app/src/flows/flows/triggers/EventTrigger.ts b/app/src/flows/flows/triggers/EventTrigger.ts index a595c5f3..3924840a 100644 --- a/app/src/flows/flows/triggers/EventTrigger.ts +++ b/app/src/flows/flows/triggers/EventTrigger.ts @@ -1,6 +1,7 @@ import type { EventManager } from "core/events"; import type { Flow } from "../Flow"; import { Trigger } from "./Trigger"; +import { $console } from "core"; import * as tbbox from "@sinclair/typebox"; const { Type } = tbbox; @@ -23,17 +24,13 @@ export class EventTrigger extends Trigger { emgr.on( this.config.event, async (event) => { - console.log("event", event); - /*if (!this.match(event)) { - return; - }*/ const execution = flow.createExecution(); this.executions.push(execution); try { await execution.start(event.params); } catch (e) { - console.error(e); + $console.error(e); } }, this.config.mode, diff --git a/app/src/flows/flows/triggers/HttpTrigger.ts b/app/src/flows/flows/triggers/HttpTrigger.ts index 00f5193e..6dc66d94 100644 --- a/app/src/flows/flows/triggers/HttpTrigger.ts +++ b/app/src/flows/flows/triggers/HttpTrigger.ts @@ -12,14 +12,11 @@ export class HttpTrigger extends Trigger { static override schema = Type.Composite([ Trigger.schema, - Type.Object( - { - path: Type.String({ pattern: "^/.*$" }), - method: StringEnum(httpMethods, { default: "GET" }), - response_type: StringEnum(["json", "text", "html"], { default: "json" }), - }, - //{ additionalProperties: false } - ), + Type.Object({ + path: Type.String({ pattern: "^/.*$" }), + method: StringEnum(httpMethods, { default: "GET" }), + response_type: StringEnum(["json", "text", "html"], { default: "json" }), + }), ]); override async register(flow: Flow, hono: Hono) { @@ -45,7 +42,5 @@ export class HttpTrigger extends Trigger { execution.start(params); return c.json({ success: true }); }); - - //console.log("--registered flow", flow.name, "on", method, this.config.path); } } diff --git a/app/src/flows/flows/triggers/Trigger.ts b/app/src/flows/flows/triggers/Trigger.ts index d9cbfdaa..a8e22157 100644 --- a/app/src/flows/flows/triggers/Trigger.ts +++ b/app/src/flows/flows/triggers/Trigger.ts @@ -10,12 +10,9 @@ export class Trigger; - static schema = Type.Object( - { - mode: StringEnum(["sync", "async"], { default: "async" }), - }, - //{ additionalProperties: false } - ); + static schema = Type.Object({ + mode: StringEnum(["sync", "async"], { default: "async" }), + }); constructor(config?: Partial>) { const schema = (this.constructor as typeof Trigger).schema; diff --git a/app/src/flows/flows/triggers/index.ts b/app/src/flows/flows/triggers/index.ts index bdd8f19b..6ae8ddc4 100644 --- a/app/src/flows/flows/triggers/index.ts +++ b/app/src/flows/flows/triggers/index.ts @@ -4,7 +4,6 @@ import { Trigger } from "./Trigger"; export { Trigger, EventTrigger, HttpTrigger }; -//export type TriggerMapType = { [key: string]: { cls: typeof Trigger } }; export const TriggerMap = { manual: { cls: Trigger }, event: { cls: EventTrigger }, diff --git a/app/src/flows/index.ts b/app/src/flows/index.ts index 4ca0de4f..9f7546b7 100644 --- a/app/src/flows/index.ts +++ b/app/src/flows/index.ts @@ -23,13 +23,9 @@ export { } from "./flows/triggers"; import { Task } from "./tasks/Task"; -export { type TaskResult, type TaskRenderProps } from "./tasks/Task"; +export type { TaskResult, TaskRenderProps } from "./tasks/Task"; export { TaskConnection, Condition } from "./tasks/TaskConnection"; -// test -//export { simpleFetch } from "./examples/simple-fetch"; - -//export type TaskMapType = { [key: string]: { cls: typeof Task } }; export const TaskMap = { fetch: { cls: FetchTask }, log: { cls: LogTask }, diff --git a/app/src/flows/tasks/Task.tsx b/app/src/flows/tasks/Task.tsx index e73c93a3..933bf15f 100644 --- a/app/src/flows/tasks/Task.tsx +++ b/app/src/flows/tasks/Task.tsx @@ -14,10 +14,6 @@ export type TaskResult = { params: any; }; -/*export type TaskRenderProps = NodeProps<{ - task: T; - state: { i: number; isStartTask: boolean; isRespondingTask; event: ExecutionEvent | undefined }; -}>;*/ export type TaskRenderProps = any; export function dynamic( @@ -94,21 +90,6 @@ export abstract class Task { // @todo: string enums fail to validate this._params = parse(schema, params || {}); - - /*const validator = new Validator(schema as any); - const _params = Default(schema, params || {}); - const result = validator.validate(_params); - if (!result.valid) { - //console.log("---errors", result, { params, _params }); - const error = result.errors[0]!; - throw new Error( - `Invalid params for task "${name}.${error.keyword}": "${ - error.error - }". Params given: ${JSON.stringify(params)}` - ); - } - - this._params = _params as Static;*/ } get params() { @@ -127,11 +108,8 @@ export abstract class Task { const newParams: any = {}; const renderer = new SimpleRenderer(inputs, { strictVariables: true, renderKeys: true }); - //console.log("--resolveParams", params); - for (const [key, value] of Object.entries(params)) { if (value && SimpleRenderer.hasMarkup(value)) { - //console.log("--- has markup", value); try { newParams[key] = await renderer.render(value as string); } catch (e: any) { @@ -151,29 +129,21 @@ export abstract class Task { throw e; } continue; - } else { - //console.log("-- no markup", key, value); } newParams[key] = value; } - //console.log("--beforeDecode", newParams); - const v = Value.Decode(schema, newParams); - //console.log("--afterDecode", v); - //process.exit(); - return v; + return Value.Decode(schema, newParams); } private async cloneWithResolvedParams(_inputs: Map) { const inputs = Object.fromEntries(_inputs.entries()); - //console.log("--clone:inputs", inputs, this.params); const newParams = await Task.resolveParams( (this.constructor as any).schema, this._params, inputs, ); - //console.log("--clone:newParams", this.name, newParams); return this.clone(this.name, newParams as any); } @@ -201,7 +171,6 @@ export abstract class Task { success = true; } catch (e: any) { success = false; - //status.output = undefined; if (e instanceof BkndError) { error = e.toJSON(); diff --git a/app/src/flows/tasks/TaskConnection.ts b/app/src/flows/tasks/TaskConnection.ts index 54efa3e1..186eb282 100644 --- a/app/src/flows/tasks/TaskConnection.ts +++ b/app/src/flows/tasks/TaskConnection.ts @@ -80,7 +80,6 @@ export class Condition { return result.success === false; case "matches": return get(result.output, this.path) === this.value; - //return this.value === output[this.path]; } } diff --git a/app/src/flows/tasks/presets/FetchTask.ts b/app/src/flows/tasks/presets/FetchTask.ts index 6f9c5a33..17b17a3e 100644 --- a/app/src/flows/tasks/presets/FetchTask.ts +++ b/app/src/flows/tasks/presets/FetchTask.ts @@ -15,8 +15,6 @@ export class FetchTask> extends Task< url: Type.String({ pattern: "^(http|https)://", }), - //method: Type.Optional(Type.Enum(FetchMethodsEnum)), - //method: Type.Optional(dynamic(Type.String({ enum: FetchMethods, default: "GET" }))), method: Type.Optional(dynamic(StringEnum(FetchMethods, { default: "GET" }))), headers: Type.Optional( dynamic( @@ -43,7 +41,6 @@ export class FetchTask> extends Task< } async execute() { - //console.log(`method: (${this.params.method})`); if (!FetchMethods.includes(this.params.method ?? "GET")) { throw this.error("Invalid method", { given: this.params.method, @@ -54,19 +51,12 @@ export class FetchTask> extends Task< const body = this.getBody(); const headers = new Headers(this.params.headers?.map((h) => [h.key, h.value])); - /*console.log("[FETCH]", { - url: this.params.url, - method: this.params.method ?? "GET", - headers, - body - });*/ const result = await fetch(this.params.url, { method: this.params.method ?? "GET", headers, body, }); - //console.log("fetch:response", result); if (!result.ok) { throw this.error("Failed to fetch", { status: result.status, @@ -75,8 +65,6 @@ export class FetchTask> extends Task< } const data = (await result.json()) as Output; - //console.log("fetch:response:data", data); - return data; } } diff --git a/app/src/flows/tasks/presets/LogTask.ts b/app/src/flows/tasks/presets/LogTask.ts index 2085e473..fda6d125 100644 --- a/app/src/flows/tasks/presets/LogTask.ts +++ b/app/src/flows/tasks/presets/LogTask.ts @@ -1,4 +1,5 @@ import { Task } from "../Task"; +import { $console } from "core"; import * as tbbox from "@sinclair/typebox"; const { Type } = tbbox; @@ -11,7 +12,7 @@ export class LogTask extends Task { async execute() { await new Promise((resolve) => setTimeout(resolve, this.params.delay)); - console.log(`[DONE] LogTask: ${this.name}`); + $console.log(`[DONE] LogTask: ${this.name}`); return true; } } diff --git a/app/src/media/AppMedia.ts b/app/src/media/AppMedia.ts index 4c73b9d4..aa53a89c 100644 --- a/app/src/media/AppMedia.ts +++ b/app/src/media/AppMedia.ts @@ -1,5 +1,5 @@ -import type { PrimaryFieldType } from "core"; -import { type Entity, EntityIndex, type EntityManager } from "data"; +import { $console, type PrimaryFieldType } from "core"; +import { type Entity, type EntityManager } from "data"; import { type FileUploadedEventData, Storage, type StorageAdapter } from "media"; import { Module } from "modules/Module"; import { @@ -145,11 +145,10 @@ export class AppMedia extends Module { // simple file deletion sync const { data } = await em.repo(media).findOne({ path: e.params.name }); if (data) { - console.log("item.data", data); await em.mutator(media).deleteOne(data.id); } - console.log("App:storage:file deleted", e); + $console.log("App:storage:file deleted", e.params); }, { mode: "sync", id: "delete-data-media" }, ); diff --git a/app/src/modules/ModuleApi.ts b/app/src/modules/ModuleApi.ts index 6c453af7..b4c3eec0 100644 --- a/app/src/modules/ModuleApi.ts +++ b/app/src/modules/ModuleApi.ts @@ -1,4 +1,4 @@ -import type { PrimaryFieldType } from "core"; +import { $console, type PrimaryFieldType } from "core"; import { isDebug } from "core/env"; import { encodeSearch } from "core/utils/reqres"; @@ -87,7 +87,6 @@ export abstract class ModuleApi> implements Promise { const fetcher = this.options?.fetcher ?? fetch; if (this.verbose) { - console.log("[FetchPromise] Request", { + $console.debug("[FetchPromise] Request", { method: this.request.method, url: this.request.url, }); @@ -253,7 +252,7 @@ export class FetchPromise> implements Promise { const res = await fetcher(this.request); if (this.verbose) { - console.log("[FetchPromise] Response", { + $console.debug("[FetchPromise] Response", { res: res, ok: res.ok, status: res.status, diff --git a/app/src/modules/ModuleManager.ts b/app/src/modules/ModuleManager.ts index bbbb180b..bc6a6871 100644 --- a/app/src/modules/ModuleManager.ts +++ b/app/src/modules/ModuleManager.ts @@ -561,7 +561,7 @@ export class ModuleManager { } return async (...args) => { - console.log("[Safe Mutate]", name); + $console.log("[Safe Mutate]", name); try { // overwrite listener to run build inside this try/catch module.setListener(async () => { @@ -583,12 +583,12 @@ export class ModuleManager { return result; } catch (e) { - console.error("[Safe Mutate] failed", e); + $console.error("[Safe Mutate] failed", e); // revert to previous config & rebuild using original listener this.setConfigs(copy); await this.onModuleConfigUpdated(name, module.config as any); - console.log("[Safe Mutate] reverted"); + $console.warn("[Safe Mutate] reverted"); // make sure to throw the error throw e; diff --git a/app/src/modules/middlewares.ts b/app/src/modules/middlewares.ts deleted file mode 100644 index be1ad591..00000000 --- a/app/src/modules/middlewares.ts +++ /dev/null @@ -1 +0,0 @@ -export { auth, permission } from "auth/middlewares"; diff --git a/app/src/modules/migrations.ts b/app/src/modules/migrations.ts index 59911b10..3ce4ffbf 100644 --- a/app/src/modules/migrations.ts +++ b/app/src/modules/migrations.ts @@ -1,7 +1,6 @@ -import { _jsonp, transformObject } from "core/utils"; -import { type Kysely, sql } from "kysely"; +import { transformObject } from "core/utils"; +import type { Kysely } from "kysely"; import { set } from "lodash-es"; -import type { InitialModuleConfigs } from "modules/ModuleManager"; export type MigrationContext = { db: Kysely; @@ -17,7 +16,6 @@ export type Migration = { export const migrations: Migration[] = [ { version: 1, - //schema: true, up: async (config) => config, }, { @@ -28,7 +26,6 @@ export const migrations: Migration[] = [ }, { version: 3, - //schema: true, up: async (config) => config, }, { @@ -46,7 +43,6 @@ export const migrations: Migration[] = [ { version: 5, up: async (config, { db }) => { - //console.log("config", _jsonp(config)); const cors = config.server.cors?.allow_methods ?? []; set(config.server, "cors.allow_methods", [...new Set([...cors, "PATCH"])]); return config; @@ -114,15 +110,12 @@ export async function migrateTo( config: GenericConfigObject, ctx: MigrationContext, ): Promise<[number, GenericConfigObject]> { - //console.log("migrating from", current, "to", CURRENT_VERSION, config); const todo = migrations.filter((m) => m.version > current && m.version <= to); - //console.log("todo", todo.length); let updated = Object.assign({}, config); let i = 0; let version = current; for (const migration of todo) { - //console.log("-- running migration", i + 1, "of", todo.length, { version: migration.version }); try { updated = await migration.up(updated, ctx); version = migration.version; diff --git a/app/src/modules/server/AdminController.tsx b/app/src/modules/server/AdminController.tsx index d1e5bcbf..f06c3aa2 100644 --- a/app/src/modules/server/AdminController.tsx +++ b/app/src/modules/server/AdminController.tsx @@ -1,7 +1,7 @@ /** @jsxImportSource hono/jsx */ import type { App } from "App"; -import { config, isDebug } from "core"; +import { $console, config, isDebug } from "core"; import { addFlashMessage } from "core/server/flash"; import { html } from "hono/html"; import { Fragment } from "hono/jsx"; @@ -99,7 +99,7 @@ export class AdminController extends Controller { onGranted: async (c) => { // @todo: add strict test to permissions middleware? if (c.get("auth")?.user) { - console.log("redirecting to success"); + $console.log("redirecting to success"); return c.redirect(authRoutes.success); } }, @@ -122,7 +122,7 @@ export class AdminController extends Controller { onDenied: async (c) => { addFlashMessage(c, "You are not authorized to access the Admin UI", "error"); - console.log("redirecting"); + $console.log("redirecting"); return c.redirect(authRoutes.login); }, }), @@ -150,7 +150,7 @@ export class AdminController extends Controller { ); } - console.warn( + $console.warn( `Custom HTML needs to include '${htmlBkndContextReplace}' to inject BKND context`, ); return this.options.html as string; diff --git a/app/src/modules/server/AppServer.ts b/app/src/modules/server/AppServer.ts index 7b6b1c12..9f9d1378 100644 --- a/app/src/modules/server/AppServer.ts +++ b/app/src/modules/server/AppServer.ts @@ -1,4 +1,4 @@ -import { Exception, isDebug } from "core"; +import { Exception, isDebug, $console } from "core"; import { type Static, StringEnum } from "core/utils"; import { cors } from "hono/cors"; import { Module } from "modules/Module"; @@ -31,8 +31,6 @@ export const serverConfigSchema = Type.Object( export type AppServerConfig = Static; export class AppServer extends Module { - //private admin_html?: string; - override getRestrictedPaths() { return []; } @@ -72,14 +70,13 @@ export class AppServer extends Module { this.client.onError((err, c) => { //throw err; - console.error(err); + $console.error(err); if (err instanceof Response) { return err; } if (err instanceof Exception) { - console.log("---is exception", err.code); return c.json(err.toJSON(), err.code as any); } diff --git a/app/src/modules/server/SystemController.ts b/app/src/modules/server/SystemController.ts index 8790c2c7..7ade0e81 100644 --- a/app/src/modules/server/SystemController.ts +++ b/app/src/modules/server/SystemController.ts @@ -100,7 +100,7 @@ export class SystemController extends Controller { try { return c.json(await cb(), { status: 202 }); } catch (e) { - console.error(e); + $console.error("config update error", e); if (e instanceof TypeInvalidError) { return c.json( @@ -161,7 +161,6 @@ export class SystemController extends Controller { if (this.app.modules.get(module).schema().has(path)) { return c.json({ success: false, path, error: "Path already exists" }, { status: 400 }); } - console.log("-- add", module, path, value); return await handleConfigUpdateResponse(c, async () => { await this.app.mutateConfig(module).patch(path, value); diff --git a/app/src/ui/components/canvas/panels/index.tsx b/app/src/ui/components/canvas/panels/index.tsx index 8d423ff5..7fedb118 100644 --- a/app/src/ui/components/canvas/panels/index.tsx +++ b/app/src/ui/components/canvas/panels/index.tsx @@ -35,16 +35,14 @@ export function Panels({ children, ...props }: PanelsProps) { )} {props.zoom && ( - <> - - - - {percent}% - - - - - + + + + {percent}% + + + + )} {props.minimap && ( <> diff --git a/app/src/ui/components/form/json-schema/templates/BaseInputTemplate.tsx b/app/src/ui/components/form/json-schema/templates/BaseInputTemplate.tsx index cc384dd3..1e5e80f7 100644 --- a/app/src/ui/components/form/json-schema/templates/BaseInputTemplate.tsx +++ b/app/src/ui/components/form/json-schema/templates/BaseInputTemplate.tsx @@ -55,7 +55,7 @@ export default function BaseInputTemplate< ...getInputProps(schema, type, options), }; - let inputValue; + let inputValue: any; if (inputProps.type === "number" || inputProps.type === "integer") { inputValue = value || value === 0 ? value : ""; } else { @@ -68,11 +68,11 @@ export default function BaseInputTemplate< [onChange, options], ); const _onBlur = useCallback( - ({ target }: FocusEvent) => onBlur(id, target && target.value), + ({ target }: FocusEvent) => onBlur(id, target?.value), [onBlur, id], ); const _onFocus = useCallback( - ({ target }: FocusEvent) => onFocus(id, target && target.value), + ({ target }: FocusEvent) => onFocus(id, target?.value), [onFocus, id], ); diff --git a/app/src/ui/modules/data/components/canvas/EntityTableNode.tsx b/app/src/ui/modules/data/components/canvas/EntityTableNode.tsx index 8c6a1bc5..96ba653b 100644 --- a/app/src/ui/modules/data/components/canvas/EntityTableNode.tsx +++ b/app/src/ui/modules/data/components/canvas/EntityTableNode.tsx @@ -1,4 +1,4 @@ -import { Handle, type Node, type NodeProps, Position, useReactFlow } from "@xyflow/react"; +import { Handle, type Node, type NodeProps, Position } from "@xyflow/react"; import type { TAppDataEntity } from "data/data-schema"; import { useState } from "react"; @@ -24,8 +24,6 @@ function NodeComponent(props: NodeProps const { data } = props; const fields = props.data.fields ?? {}; const field_count = Object.keys(fields).length; - //const flow = useReactFlow(); - //const flow = useTestContext(); return ( @@ -92,15 +90,13 @@ const TableRow = ({
{field.type}
{handles && ( - <> - - + )} ); diff --git a/app/src/ui/routes/test/tests/appshell-accordions-test.tsx b/app/src/ui/routes/test/tests/appshell-accordions-test.tsx index 549b8a61..c921040f 100644 --- a/app/src/ui/routes/test/tests/appshell-accordions-test.tsx +++ b/app/src/ui/routes/test/tests/appshell-accordions-test.tsx @@ -73,18 +73,16 @@ export default function AppShellAccordionsTest() {
- - - - + + + } className="pl-3" > diff --git a/biome.json b/biome.json index 41e7a19e..28818cb9 100644 --- a/biome.json +++ b/biome.json @@ -69,7 +69,8 @@ "noExplicitAny": "off", "noArrayIndexKey": "off", "noImplicitAnyLet": "warn", - "noConfusingVoidType": "off" + "noConfusingVoidType": "off", + "noConsoleLog": "warn" }, "security": { "noDangerouslySetInnerHtml": "off"