diff --git a/src/cli/commands/functions/deploy.ts b/src/cli/commands/functions/deploy.ts index 1c5fa79..abd438e 100644 --- a/src/cli/commands/functions/deploy.ts +++ b/src/cli/commands/functions/deploy.ts @@ -54,17 +54,9 @@ async function deployFunctionsAction(): Promise { } export function getFunctionsDeployCommand(context: CLIContext): Command { - return new Command("functions") - .description("Manage project functions") - .addCommand( - new Command("deploy") - .description("Deploy local functions to Base44") - .action(async () => { - await runCommand( - deployFunctionsAction, - { requireAuth: true }, - context - ); - }) - ); + return new Command("deploy") + .description("Deploy local functions to Base44") + .action(async () => { + await runCommand(deployFunctionsAction, { requireAuth: true }, context); + }); } diff --git a/src/cli/commands/functions/index.ts b/src/cli/commands/functions/index.ts new file mode 100644 index 0000000..ed509d2 --- /dev/null +++ b/src/cli/commands/functions/index.ts @@ -0,0 +1,9 @@ +import { Command } from "commander"; +import type { CLIContext } from "@/cli/types.js"; +import { getFunctionsDeployCommand } from "./deploy.js"; + +export function getFunctionsCommand(context: CLIContext): Command { + return new Command("functions") + .description("Manage project functions") + .addCommand(getFunctionsDeployCommand(context)); +} diff --git a/src/cli/commands/logs/index.ts b/src/cli/commands/logs/index.ts new file mode 100644 index 0000000..49d5f9e --- /dev/null +++ b/src/cli/commands/logs/index.ts @@ -0,0 +1,569 @@ +import { log } from "@clack/prompts"; +import { Command } from "commander"; +import type { CLIContext } from "@/cli/types.js"; +import { runCommand, runTask, theme } from "@/cli/utils/index.js"; +import type { RunCommandResult } from "@/cli/utils/runCommand.js"; +import { InvalidInputError } from "@/core/errors.js"; +import { readProjectConfig } from "@/core/index.js"; +import type { + AuditLogEvent, + AuditLogFilters, + AuditLogsResponse, +} from "@/core/logs/index.js"; +import { fetchAuditLogs } from "@/core/logs/index.js"; +import type { + FunctionLogFilters, + LogLevel, +} from "@/core/resources/function/index.js"; +import { fetchFunctionLogs } from "@/core/resources/function/index.js"; + +// ─── TYPES ────────────────────────────────────────────────── + +interface LogsOptions { + function?: string; + since?: string; + until?: string; + level?: string; + limit?: string; + order?: string; + json?: boolean; +} + +/** + * Unified log entry for display (normalized from both sources). + */ +interface UnifiedLogEntry { + time: string; + level: string; + message: string; + source: string; // "App" for audit logs, function name for function logs +} + +// ─── CONSTANTS ────────────────────────────────────────────── + +const VALID_LEVELS = ["log", "info", "warn", "error", "debug"]; + +// ─── AUDIT LOG MESSAGE FORMATTING ─────────────────────────── + +/** + * Format an audit log event into a human-readable message. + */ +function formatAuditMessage(event: AuditLogEvent): string { + const m = (event.metadata ?? {}) as Record; + const isFailure = event.status === "failure"; + + switch (event.event_type) { + // Function calls + case "api.function.call": { + const fnName = m.function_name ?? "unknown"; + const statusCode = m.status_code ?? ""; + return isFailure + ? `function ${fnName} failed (status ${statusCode})` + : `function ${fnName} called (status ${statusCode})`; + } + + // Entity operations + case "app.entity.created": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to create entity ${entity}` + : `entity ${entity} created (id: ${id})`; + } + case "app.entity.updated": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to update entity ${entity}` + : `entity ${entity} updated (id: ${id})`; + } + case "app.entity.deleted": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to delete entity ${entity}` + : `entity ${entity} deleted (id: ${id})`; + } + case "app.entity.bulk_created": { + const entity = m.entity_name ?? "unknown"; + const count = m.count ?? 0; + const method = m.method ?? ""; + return isFailure + ? `bulk create failed for ${entity}` + : `${count} ${entity} entities created via ${method}`; + } + case "app.entity.bulk_deleted": { + const entity = m.entity_name ?? "unknown"; + const count = m.count ?? 0; + const method = m.method ?? ""; + return isFailure + ? `bulk delete failed for ${entity}` + : `${count} ${entity} entities deleted via ${method}`; + } + case "app.entity.query": { + const entity = m.entity_name ?? "unknown"; + return isFailure ? `query failed for ${entity}` : `queried ${entity}`; + } + + // User operations (always success) + case "app.user.registered": { + const email = m.target_email ?? "unknown"; + const role = m.role ?? ""; + return `user ${email} registered as ${role}`; + } + case "app.user.updated": { + const email = m.target_email ?? "unknown"; + return `user ${email} updated`; + } + case "app.user.deleted": { + const email = m.target_email ?? "unknown"; + return `user ${email} deleted`; + } + case "app.user.role_changed": { + const email = m.target_email ?? "unknown"; + const oldRole = m.old_role ?? ""; + const newRole = m.new_role ?? ""; + return `user ${email} role changed: ${oldRole} → ${newRole}`; + } + case "app.user.invited": { + const email = m.invitee_email ?? "unknown"; + const role = m.role ?? ""; + return `invited ${email} as ${role}`; + } + case "app.user.page_visit": { + const page = m.page_name ?? "unknown"; + return `page visit: ${page}`; + } + + // Auth operations (always success) + case "app.auth.login": { + const method = m.auth_method ?? "unknown"; + return `login via ${method}`; + } + + // Access operations (always success) + case "app.access.requested": { + const email = m.requester_email ?? "unknown"; + return `access requested by ${email}`; + } + case "app.access.approved": { + const email = m.target_email ?? "unknown"; + return `access approved for ${email}`; + } + case "app.access.denied": { + const email = m.target_email ?? "unknown"; + return `access denied for ${email}`; + } + + // Automation & Integration (can fail) + case "app.automation.executed": { + const name = m.automation_name ?? "unknown"; + return isFailure + ? `automation ${name} failed` + : `automation ${name} executed`; + } + case "app.integration.executed": { + const name = m.integration_name ?? "unknown"; + const action = m.action ?? ""; + const duration = m.duration_ms ?? ""; + return isFailure + ? `integration ${name} failed: ${action}` + : `integration ${name}: ${action} (${duration}ms)`; + } + + // Agent conversation (always success) + case "app.agent.conversation": { + const name = m.agent_name ?? "unknown"; + const model = m.model ?? ""; + return `agent ${name} conversation (${model})`; + } + + // Fallback for unknown event types + default: + return isFailure ? `${event.event_type} failed` : event.event_type; + } +} + +/** + * Normalize an audit log event to unified format. + */ +function normalizeAuditLog(event: AuditLogEvent): UnifiedLogEntry { + const level = event.status === "failure" ? "error" : "info"; + const message = formatAuditMessage(event); + return { time: event.timestamp, level, message, source: "App" }; +} + +/** + * Normalize a function log entry to unified format. + */ +function normalizeFunctionLog( + entry: { time: string; level: string; message: string }, + functionName: string +): UnifiedLogEntry { + return { + time: entry.time, + level: entry.level, + message: `[${functionName}] ${entry.message}`, + source: functionName, + }; +} + +// ─── OPTION PARSING ───────────────────────────────────────── + +/** + * Map --level to audit log status filter. + * - log/info → success + * - error → failure + * - debug → skip audit logs (returns null) + * - warn → no filter (show all) + */ +function mapLevelToStatus( + level: string | undefined +): "success" | "failure" | null | undefined { + if (!level) return undefined; // No filter + if (level === "debug") return null; // Skip audit logs + if (level === "log" || level === "info") return "success"; + if (level === "error") return "failure"; + return undefined; // warn - show all +} + +/** + * Parse CLI options into AuditLogFilters. + */ +function parseAuditFilters(options: LogsOptions): AuditLogFilters { + const filters: AuditLogFilters = {}; + + // Map level to status + const status = mapLevelToStatus(options.level); + if (status) { + filters.status = status; + } + + if (options.since) { + filters.since = options.since; + } + + if (options.until) { + filters.until = options.until; + } + + if (options.limit) { + const limit = Number.parseInt(options.limit, 10); + if (Number.isNaN(limit) || limit < 1 || limit > 1000) { + throw new InvalidInputError( + `Invalid limit: "${options.limit}". Must be a number between 1 and 1000.` + ); + } + filters.limit = limit; + } + + if (options.order) { + const order = options.order.toUpperCase(); + if (order !== "ASC" && order !== "DESC") { + throw new InvalidInputError( + `Invalid order: "${options.order}". Must be "ASC" or "DESC".` + ); + } + filters.order = order as "ASC" | "DESC"; + } + + return filters; +} + +/** + * Check if audit logs should be fetched based on level filter. + */ +function shouldFetchAuditLogs(level: string | undefined): boolean { + return mapLevelToStatus(level) !== null; +} + +/** + * Parse CLI options into FunctionLogFilters. + */ +function parseFunctionFilters(options: LogsOptions): FunctionLogFilters { + const filters: FunctionLogFilters = {}; + + if (options.since) { + filters.since = options.since; + } + + if (options.until) { + filters.until = options.until; + } + + if (options.level) { + if (!VALID_LEVELS.includes(options.level)) { + throw new InvalidInputError( + `Invalid level: "${options.level}". Must be one of: ${VALID_LEVELS.join(", ")}.` + ); + } + filters.level = options.level as LogLevel; + } + + return filters; +} + +/** + * Parse --function option into array of function names. + */ +function parseFunctionNames(option: string | undefined): string[] { + if (!option) return []; + return option + .split(",") + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +// ─── DISPLAY ──────────────────────────────────────────────── + +/** + * Get color/style for a log level. + */ +function formatLevel(level: string): string { + switch (level) { + case "error": + return theme.colors.base44Orange(level.padEnd(5)); + case "warn": + return theme.colors.shinyOrange(level.padEnd(5)); + case "info": + return theme.colors.links(level.padEnd(5)); + case "debug": + return theme.styles.dim(level.padEnd(5)); + default: + return level.padEnd(5); + } +} + +/** + * Wrap text at specified width, returning array of lines. + */ +function wrapText(text: string, width: number): string[] { + if (text.length <= width) return [text]; + + const lines: string[] = []; + let remaining = text; + + while (remaining.length > width) { + // Find last space within width, or break at width if no space + let breakPoint = remaining.lastIndexOf(" ", width); + if (breakPoint <= 0) breakPoint = width; + + lines.push(remaining.substring(0, breakPoint)); + remaining = remaining.substring(breakPoint).trimStart(); + } + + if (remaining.length > 0) { + lines.push(remaining); + } + + return lines; +} + +// Column widths: TIME(19) + 2 spaces + LEVEL(5) + 2 spaces = 28 chars before message +const MESSAGE_INDENT = " ".repeat(28); +const MESSAGE_WIDTH = 80; + +/** + * Format a unified log entry for display. + */ +function formatEntry(entry: UnifiedLogEntry): string { + const time = entry.time.substring(0, 19).replace("T", " "); + const level = formatLevel(entry.level); + + // Wrap message at 80 characters + const messageLines = wrapText(entry.message, MESSAGE_WIDTH); + const firstLine = `${theme.styles.dim(time)} ${level} ${messageLines[0]}`; + + if (messageLines.length === 1) { + return firstLine; + } + + // Join continuation lines with proper indentation + const continuationLines = messageLines + .slice(1) + .map((line) => `${MESSAGE_INDENT}${line}`) + .join("\n"); + + return `${firstLine}\n${continuationLines}`; +} + +/** + * Display unified logs. + */ +function displayLogs( + entries: UnifiedLogEntry[], + pagination?: AuditLogsResponse["pagination"] +): void { + if (entries.length === 0) { + log.info("No logs found matching the filters."); + return; + } + + // Header + const countInfo = pagination + ? `Showing ${entries.length} of ${pagination.total} events` + : `Showing ${entries.length} log entries`; + log.info(theme.styles.dim(`${countInfo}\n`)); + + const header = `${"TIME".padEnd(19)} ${"LEVEL".padEnd(5)} MESSAGE`; + log.message(theme.styles.header(header)); + + // Entries + for (const entry of entries) { + log.message(formatEntry(entry)); + } + + // Pagination hint (only for audit logs) + if (pagination?.has_more) { + log.info( + theme.styles.dim("\nMore results available. Use --limit to fetch more.") + ); + } +} + +// ─── ACTIONS ──────────────────────────────────────────────── + +/** + * Fetch and display audit logs. + */ +async function fetchAuditLogsAction(options: LogsOptions): Promise<{ + entries: UnifiedLogEntry[]; + pagination: AuditLogsResponse["pagination"]; +}> { + const filters = parseAuditFilters(options); + + const response = await runTask( + "Fetching app logs...", + async () => { + return await fetchAuditLogs(filters); + }, + { + successMessage: "Logs fetched successfully", + errorMessage: "Failed to fetch app logs", + } + ); + + const entries = response.events.map(normalizeAuditLog); + return { entries, pagination: response.pagination }; +} + +/** + * Fetch and display function logs. + */ +async function fetchFunctionLogsAction( + functionNames: string[], + options: LogsOptions +): Promise { + const filters = parseFunctionFilters(options); + const allEntries: UnifiedLogEntry[] = []; + + for (const functionName of functionNames) { + const logs = await runTask( + `Fetching logs for "${functionName}"...`, + async () => { + return await fetchFunctionLogs(functionName, filters); + }, + { + successMessage: `Logs for "${functionName}" fetched`, + errorMessage: `Failed to fetch logs for "${functionName}"`, + } + ); + + // Filter by level if specified (API doesn't support level filtering) + const filteredLogs = filters.level + ? logs.filter((entry) => entry.level === filters.level) + : logs; + + const entries = filteredLogs.map((entry) => + normalizeFunctionLog(entry, functionName) + ); + allEntries.push(...entries); + } + + // Sort by time (respecting order option) + const order = options.order?.toUpperCase() === "ASC" ? 1 : -1; + allEntries.sort((a, b) => order * a.time.localeCompare(b.time)); + + return allEntries; +} + +/** + * Get all function names from project config. + */ +async function getAllFunctionNames(): Promise { + const { functions } = await readProjectConfig(); + return functions.map((fn) => fn.name); +} + +/** + * Main logs action. + */ +async function logsAction(options: LogsOptions): Promise { + const specifiedFunctions = parseFunctionNames(options.function); + const allEntries: UnifiedLogEntry[] = []; + let pagination: AuditLogsResponse["pagination"] | undefined; + + if (specifiedFunctions.length > 0) { + // --function specified: fetch only those function logs (no audit logs) + const entries = await fetchFunctionLogsAction(specifiedFunctions, options); + allEntries.push(...entries); + } else { + // No --function: fetch both audit logs and all project function logs + + // Fetch audit logs (unless --level=debug) + if (shouldFetchAuditLogs(options.level)) { + const result = await fetchAuditLogsAction(options); + allEntries.push(...result.entries); + pagination = result.pagination; + } + + // Fetch all project function logs + const functionNames = await getAllFunctionNames(); + if (functionNames.length > 0) { + const functionEntries = await fetchFunctionLogsAction( + functionNames, + options + ); + allEntries.push(...functionEntries); + } + + // Sort combined entries by time + const order = options.order?.toUpperCase() === "ASC" ? 1 : -1; + allEntries.sort((a, b) => order * a.time.localeCompare(b.time)); + } + + if (options.json) { + process.stdout.write(`${JSON.stringify(allEntries, null, 2)}\n`); + } else { + displayLogs(allEntries, pagination); + } + + return {}; +} + +// ─── COMMAND ──────────────────────────────────────────────── + +export function getLogsCommand(context: CLIContext): Command { + return new Command("logs") + .description("Fetch logs for this app (app logs + all function logs)") + .option( + "--function ", + "Filter by function name(s), comma-separated. If provided, fetches only those function logs" + ) + .option("--since ", "Show logs from this time (ISO format)") + .option("--until ", "Show logs until this time (ISO format)") + .option( + "--level ", + "Filter by log level: log, info, warn, error, debug" + ) + .option("-n, --limit ", "Results per page (1-1000, default: 50)") + .option("--order ", "Sort order: ASC|DESC (default: DESC)") + .option("--json", "Output raw JSON") + .action(async (options: LogsOptions) => { + await runCommand( + () => logsAction(options), + { requireAuth: true }, + context + ); + }); +} diff --git a/src/cli/program.ts b/src/cli/program.ts index 8d01d27..2e73afc 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -5,7 +5,8 @@ import { getLogoutCommand } from "@/cli/commands/auth/logout.js"; import { getWhoamiCommand } from "@/cli/commands/auth/whoami.js"; import { getDashboardCommand } from "@/cli/commands/dashboard/index.js"; import { getEntitiesPushCommand } from "@/cli/commands/entities/push.js"; -import { getFunctionsDeployCommand } from "@/cli/commands/functions/deploy.js"; +import { getFunctionsCommand } from "@/cli/commands/functions/index.js"; +import { getLogsCommand } from "@/cli/commands/logs/index.js"; import { getCreateCommand } from "@/cli/commands/project/create.js"; import { getDeployCommand } from "@/cli/commands/project/deploy.js"; import { getLinkCommand } from "@/cli/commands/project/link.js"; @@ -45,10 +46,13 @@ export function createProgram(context: CLIContext): Command { program.addCommand(getAgentsCommand(context)); // Register functions commands - program.addCommand(getFunctionsDeployCommand(context)); + program.addCommand(getFunctionsCommand(context)); // Register site commands program.addCommand(getSiteCommand(context)); + // Register logs command + program.addCommand(getLogsCommand(context)); + return program; } diff --git a/src/core/index.ts b/src/core/index.ts index 723c3e7..78381b2 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,6 +3,7 @@ export * from "./clients/index.js"; export * from "./config.js"; export * from "./consts.js"; export * from "./errors.js"; +export * from "./logs/index.js"; export * from "./project/index.js"; export * from "./resources/index.js"; export * from "./site/index.js"; diff --git a/src/core/logs/api.ts b/src/core/logs/api.ts new file mode 100644 index 0000000..b81f25e --- /dev/null +++ b/src/core/logs/api.ts @@ -0,0 +1,109 @@ +/** + * Audit logs API functions. + */ + +import type { KyResponse } from "ky"; +import { base44Client } from "@/core/clients/index.js"; +import { ApiError, SchemaValidationError } from "@/core/errors.js"; +import { getAppConfig } from "@/core/project/index.js"; +import type { AuditLogFilters, AuditLogsResponse } from "./schema.js"; +import { AppInfoResponseSchema, AuditLogsResponseSchema } from "./schema.js"; + +/** + * Fetch the workspace (organization) ID for the current app. + * Required because audit logs are fetched at the workspace level. + */ +export async function getWorkspaceId(): Promise { + const { id: appId } = getAppConfig(); + + let response: KyResponse; + try { + // GET /api/apps/{app_id} returns app info including organization_id + response = await base44Client.get(`api/apps/${appId}`); + } catch (error) { + throw await ApiError.fromHttpError(error, "fetching app info"); + } + + const result = AppInfoResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid app info response from server", + result.error + ); + } + + return result.data.organization_id; +} + +/** + * Build the API request body from CLI filter options. + * Transforms camelCase options to snake_case for the API. + */ +function buildRequestBody( + appId: string, + filters: AuditLogFilters +): Record { + const body: Record = { + app_id: appId, + order: filters.order ?? "DESC", + limit: filters.limit ?? 50, + }; + + if (filters.status) { + body.status = filters.status; + } + if (filters.eventTypes && filters.eventTypes.length > 0) { + body.event_types = filters.eventTypes; + } + if (filters.userEmail) { + body.user_email = filters.userEmail; + } + if (filters.since) { + body.start_date = filters.since; + } + if (filters.until) { + body.end_date = filters.until; + } + if (filters.cursorTimestamp) { + body.cursor_timestamp = filters.cursorTimestamp; + } + if (filters.cursorUserEmail) { + body.cursor_user_email = filters.cursorUserEmail; + } + + return body; +} + +/** + * Fetch audit logs for the current app. + */ +export async function fetchAuditLogs( + filters: AuditLogFilters = {} +): Promise { + const { id: appId } = getAppConfig(); + const workspaceId = await getWorkspaceId(); + + let response: KyResponse; + try { + response = await base44Client.post( + `api/workspace/audit-logs/list?workspaceId=${workspaceId}`, + { + json: buildRequestBody(appId, filters), + } + ); + } catch (error) { + throw await ApiError.fromHttpError(error, "fetching audit logs"); + } + + const result = AuditLogsResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid audit logs response from server", + result.error + ); + } + + return result.data; +} diff --git a/src/core/logs/index.ts b/src/core/logs/index.ts new file mode 100644 index 0000000..4b137f0 --- /dev/null +++ b/src/core/logs/index.ts @@ -0,0 +1,9 @@ +export { fetchAuditLogs, getWorkspaceId } from "./api.js"; +export type { + AuditLogEvent, + AuditLogFilters, + AuditLogRequest, + AuditLogsResponse, + Pagination, + PaginationCursor, +} from "./schema.js"; diff --git a/src/core/logs/schema.ts b/src/core/logs/schema.ts new file mode 100644 index 0000000..4b836da --- /dev/null +++ b/src/core/logs/schema.ts @@ -0,0 +1,95 @@ +import { z } from "zod"; + +/** + * Request body schema for the audit logs API. + * Uses snake_case to match API expectations. + */ +export const AuditLogRequestSchema = z.object({ + app_id: z.string(), + event_types: z.array(z.string()).optional(), + user_email: z.string().optional(), + status: z.enum(["success", "failure"]).optional(), + start_date: z.string().optional(), + end_date: z.string().optional(), + limit: z.number().min(1).max(1000).default(50), + order: z.enum(["ASC", "DESC"]).default("DESC"), + cursor_timestamp: z.string().optional(), + cursor_user_email: z.string().optional(), +}); + +export type AuditLogRequest = z.infer; + +/** + * Single audit log event from the API response. + */ +export const AuditLogEventSchema = z.looseObject({ + timestamp: z.string(), + user_email: z.string().nullable(), + workspace_id: z.string(), + app_id: z.string(), + ip: z.string().nullable(), + user_agent: z.string().nullable(), + event_type: z.string(), + status: z.enum(["success", "failure"]), + error_code: z.string().nullable(), + metadata: z.record(z.string(), z.unknown()).nullable(), +}); + +export type AuditLogEvent = z.infer; + +/** + * Pagination cursor for fetching the next page. + */ +export const PaginationCursorSchema = z.object({ + timestamp: z.string(), + user_email: z.string(), +}); + +export type PaginationCursor = z.infer; + +/** + * Pagination info from the API response. + */ +export const PaginationSchema = z.object({ + total: z.number(), + limit: z.number(), + has_more: z.boolean(), + next_cursor: PaginationCursorSchema.nullable(), +}); + +export type Pagination = z.infer; + +/** + * Full audit logs API response. + */ +export const AuditLogsResponseSchema = z.object({ + events: z.array(AuditLogEventSchema), + pagination: PaginationSchema, +}); + +export type AuditLogsResponse = z.infer; + +/** + * App info response schema (for extracting workspace/organization ID). + */ +export const AppInfoResponseSchema = z.looseObject({ + organization_id: z.string(), +}); + +export type AppInfoResponse = z.infer; + +/** + * CLI filter options (camelCase for TypeScript). + * These are transformed to snake_case when building the API request. + */ +export interface AuditLogFilters { + status?: "success" | "failure"; + eventTypes?: string[]; + userEmail?: string; + since?: string; + until?: string; + limit?: number; + order?: "ASC" | "DESC"; + cursorTimestamp?: string; + cursorUserEmail?: string; +} diff --git a/src/core/resources/function/api.ts b/src/core/resources/function/api.ts index bf4edca..4b47c93 100644 --- a/src/core/resources/function/api.ts +++ b/src/core/resources/function/api.ts @@ -3,9 +3,14 @@ import { getAppClient } from "@/core/clients/index.js"; import { ApiError, SchemaValidationError } from "@/core/errors.js"; import type { DeployFunctionsResponse, + FunctionLogFilters, + FunctionLogsResponse, FunctionWithCode, } from "@/core/resources/function/schema.js"; -import { DeployFunctionsResponseSchema } from "@/core/resources/function/schema.js"; +import { + DeployFunctionsResponseSchema, + FunctionLogsResponseSchema, +} from "@/core/resources/function/schema.js"; function toDeployPayloadItem(fn: FunctionWithCode) { return { @@ -44,3 +49,53 @@ export async function deployFunctions( return result.data; } + +// ─── FUNCTION LOGS API ────────────────────────────────────── + +/** + * Build query string from filter options. + */ +function buildLogsQueryString(filters: FunctionLogFilters): string { + const params = new URLSearchParams(); + + if (filters.since) { + params.set("since", filters.since); + } + if (filters.until) { + params.set("until", filters.until); + } + + const queryString = params.toString(); + return queryString ? `?${queryString}` : ""; +} + +/** + * Fetch runtime logs for a specific function from Deno Deploy. + */ +export async function fetchFunctionLogs( + functionName: string, + filters: FunctionLogFilters = {} +): Promise { + const appClient = getAppClient(); + const queryString = buildLogsQueryString(filters); + + let response: KyResponse; + try { + response = await appClient.get( + `functions-mgmt/${functionName}/logs${queryString}` + ); + } catch (error) { + throw await ApiError.fromHttpError(error, "fetching function logs"); + } + + const result = FunctionLogsResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid function logs response from server", + result.error + ); + } + + return result.data; +} diff --git a/src/core/resources/function/schema.ts b/src/core/resources/function/schema.ts index e3021d6..a7dc283 100644 --- a/src/core/resources/function/schema.ts +++ b/src/core/resources/function/schema.ts @@ -48,3 +48,39 @@ export type DeployFunctionsResponse = z.infer< export type FunctionWithCode = Omit & { files: FunctionFile[]; }; + +// ─── FUNCTION LOGS SCHEMAS ────────────────────────────────── + +/** + * Log level from Deno Deploy runtime. + */ +export const LogLevelSchema = z.enum(["log", "info", "warn", "error", "debug"]); + +export type LogLevel = z.infer; + +/** + * Single log entry from the function runtime (Deno Deploy). + */ +export const FunctionLogEntrySchema = z.object({ + time: z.string(), + level: LogLevelSchema, + message: z.string(), +}); + +export type FunctionLogEntry = z.infer; + +/** + * Response from the function logs API - array of log entries. + */ +export const FunctionLogsResponseSchema = z.array(FunctionLogEntrySchema); + +export type FunctionLogsResponse = z.infer; + +/** + * CLI filter options for function logs. + */ +export interface FunctionLogFilters { + since?: string; + until?: string; + level?: LogLevel; +} diff --git a/tests/cli/functions_logs.spec.ts b/tests/cli/functions_logs.spec.ts new file mode 100644 index 0000000..b58d8f0 --- /dev/null +++ b/tests/cli/functions_logs.spec.ts @@ -0,0 +1,130 @@ +import { describe, it } from "vitest"; +import { fixture, setupCLITests } from "./testkit/index.js"; + +describe("functions logs command", () => { + const t = setupCLITests(); + + it("fetches and displays logs successfully", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "info", + message: "Processing request", + }, + { + time: "2024-01-15T10:30:00.050Z", + level: "error", + message: "Something went wrong", + }, + ]); + + const result = await t.run("functions", "logs", "my-function"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Logs fetched successfully"); + t.expectResult(result).toContain('Showing 2 log entries for "my-function"'); + t.expectResult(result).toContain("Processing request"); + }); + + it("shows no logs message when empty", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", []); + + const result = await t.run("functions", "logs", "my-function"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("No logs found"); + }); + + it("filters by log level", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "info", + message: "Info message", + }, + { + time: "2024-01-15T10:30:00.050Z", + level: "error", + message: "Error message", + }, + ]); + + const result = await t.run( + "functions", + "logs", + "my-function", + "--level", + "error" + ); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Showing 1 log entries"); + t.expectResult(result).toContain("Error message"); + }); + + it("outputs raw JSON with --json flag", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "log", + message: "Test message", + }, + ]); + + const result = await t.run("functions", "logs", "my-function", "--json"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain('"time"'); + t.expectResult(result).toContain('"level"'); + t.expectResult(result).toContain('"message"'); + }); + + it("fails when not in a project directory", async () => { + await t.givenLoggedIn({ email: "test@example.com", name: "Test User" }); + + const result = await t.run("functions", "logs", "my-function"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("No Base44 project found"); + }); + + it("fails when API returns error", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogsError("my-function", { + status: 404, + body: { error: "Function not found" }, + }); + + const result = await t.run("functions", "logs", "my-function"); + + t.expectResult(result).toFail(); + }); + + it("fails with invalid level option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run( + "functions", + "logs", + "my-function", + "--level", + "invalid" + ); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid level"); + }); + + it("requires function name argument", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("functions", "logs"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("missing required argument"); + }); +}); diff --git a/tests/cli/logs.spec.ts b/tests/cli/logs.spec.ts new file mode 100644 index 0000000..33e028b --- /dev/null +++ b/tests/cli/logs.spec.ts @@ -0,0 +1,227 @@ +import { describe, it } from "vitest"; +import { fixture, setupCLITests } from "./testkit/index.js"; + +const TEST_WORKSPACE_ID = "test-workspace-id"; + +describe("logs command", () => { + const t = setupCLITests(); + + it("fetches and displays logs successfully", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + { + timestamp: "2024-01-15T10:29:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "app.entity.created", + status: "failure", + ip: null, + user_agent: null, + error_code: "VALIDATION_ERROR", + metadata: { entity_name: "Task" }, + }, + ], + pagination: { + total: 2, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Logs fetched successfully"); + t.expectResult(result).toContain("Showing 2 of 2 events"); + t.expectResult(result).toContain("api.function.call"); + t.expectResult(result).toContain("app.entity.created"); + }); + + it("shows no events message when empty", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [], + pagination: { + total: 0, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("No events found"); + }); + + it("outputs raw JSON with --json flag", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + ], + pagination: { + total: 1, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs", "--json"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain('"events"'); + t.expectResult(result).toContain('"pagination"'); + }); + + it("shows pagination hint when more results available", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + ], + pagination: { + total: 100, + limit: 50, + has_more: true, + next_cursor: { + timestamp: "2024-01-15T10:29:00Z", + user_email: "user@example.com", + }, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("More results available"); + t.expectResult(result).toContain("--cursor-timestamp"); + }); + + it("fails when not in a project directory", async () => { + await t.givenLoggedIn({ email: "test@example.com", name: "Test User" }); + + const result = await t.run("logs"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("No Base44 project found"); + }); + + it("fails when API returns error", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogsError({ + status: 500, + body: { error: "Server error" }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toFail(); + }); + + it("fails with invalid status option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--status", "invalid"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid status"); + }); + + it("fails with invalid event-types option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--event-types", "not-json"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid event-types"); + }); + + it("fails with invalid limit option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--limit", "9999"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid limit"); + }); + + it("fails with invalid order option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--order", "RANDOM"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid order"); + }); + + it("passes filter options to API", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [], + pagination: { + total: 0, + limit: 10, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run( + "logs", + "--status", + "failure", + "--limit", + "10", + "--order", + "ASC" + ); + + t.expectResult(result).toSucceed(); + }); +}); diff --git a/tests/cli/testkit/Base44APIMock.ts b/tests/cli/testkit/Base44APIMock.ts index c1e1d4e..edefb0c 100644 --- a/tests/cli/testkit/Base44APIMock.ts +++ b/tests/cli/testkit/Base44APIMock.ts @@ -57,6 +57,37 @@ export interface AgentsFetchResponse { total: number; } +export interface AppInfoResponse { + organization_id: string; + [key: string]: unknown; +} + +export interface AuditLogsResponse { + events: Array<{ + timestamp: string; + user_email: string | null; + workspace_id: string; + app_id: string; + event_type: string; + status: "success" | "failure"; + [key: string]: unknown; + }>; + pagination: { + total: number; + limit: number; + has_more: boolean; + next_cursor: { timestamp: string; user_email: string } | null; + }; +} + +export interface FunctionLogEntry { + time: string; + level: "log" | "info" | "warn" | "error" | "debug"; + message: string; +} + +export type FunctionLogsResponse = FunctionLogEntry[]; + export interface CreateAppResponse { id: string; name: string; @@ -182,6 +213,44 @@ export class Base44APIMock { return this; } + /** Mock GET /api/apps/{appId} - Get app info (for workspace ID) */ + mockAppInfo(response: AppInfoResponse): this { + this.handlers.push( + http.get(`${BASE_URL}/api/apps/${this.appId}`, () => + HttpResponse.json(response) + ) + ); + return this; + } + + /** Mock POST /api/workspace/audit-logs/list - Fetch audit logs */ + mockAuditLogs(workspaceId: string, response: AuditLogsResponse): this { + this.handlers.push( + http.post(`${BASE_URL}/api/workspace/audit-logs/list`, ({ request }) => { + const url = new URL(request.url); + if (url.searchParams.get("workspaceId") === workspaceId) { + return HttpResponse.json(response); + } + return HttpResponse.json( + { error: "Workspace not found" }, + { status: 404 } + ); + }) + ); + return this; + } + + /** Mock GET /api/apps/{appId}/functions-mgmt/{functionName}/logs - Fetch function logs */ + mockFunctionLogs(functionName: string, response: FunctionLogsResponse): this { + this.handlers.push( + http.get( + `${BASE_URL}/api/apps/${this.appId}/functions-mgmt/${functionName}/logs`, + () => HttpResponse.json(response) + ) + ); + return this; + } + // ─── GENERAL ENDPOINTS ───────────────────────────────────── /** Mock POST /api/apps - Create new app */ @@ -263,6 +332,25 @@ export class Base44APIMock { ); } + /** Mock app info to return an error */ + mockAppInfoError(error: ErrorResponse): this { + return this.mockError("get", `/api/apps/${this.appId}`, error); + } + + /** Mock audit logs to return an error */ + mockAuditLogsError(error: ErrorResponse): this { + return this.mockError("post", "/api/workspace/audit-logs/list", error); + } + + /** Mock function logs to return an error */ + mockFunctionLogsError(functionName: string, error: ErrorResponse): this { + return this.mockError( + "get", + `/api/apps/${this.appId}/functions-mgmt/${functionName}/logs`, + error + ); + } + /** Mock token endpoint to return an error (for auth failure testing) */ mockTokenError(error: ErrorResponse): this { return this.mockError("post", "/oauth/token", error);