Fix eslint (#46)

* Fix mobile image upload and paste with improved file type handling

* Replace older sessions header with separator line

* Add ESLint no-console rules and fix lint errors

- Add eslint configuration for backend with no-console rule
- Add reusable error type guard utility
- Replace all error: any with error: unknown and type guards across backend
- Update logger to use console.warn/console.error only
- Remove unused variables and dead code functions
- Fix regex escape characters
- Update AGENTS.md with lint commands and requirements
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-03 15:19:28 -05:00
1 parent c9bf962ac0
commit 8166044d6e
23 files changed
+642 -334

No files matched your search

+16 -4
View File
@@ -1,11 +1,20 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
interface ColumnInfo {
cid: number
name: string
type: string
notnull: number
dflt_value: unknown
pk: number
}
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as any[]
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find((col: any) => col.name === 'repo_url')
const repoUrlColumn = tableInfo.find((col: ColumnInfo) => col.name === 'repo_url')
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
logger.info('Migrating repos table to allow nullable repo_url for local repos')
db.run('BEGIN TRANSACTION')
@@ -26,7 +35,7 @@ export function runMigrations(db: Database): void {
)
`)
const existingColumns = tableInfo.map((col: any) => col.name)
const existingColumns = tableInfo.map((col: ColumnInfo) => col.name)
const columnsToCopy = ['id', 'repo_url', 'local_path', 'branch', 'default_branch', 'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name', 'is_worktree', 'is_local']
.filter(col => existingColumns.includes(col))
@@ -107,7 +116,10 @@ export function runMigrations(db: Database): void {
}
try {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as any[]
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length > 0) {
logger.info(`Migrating ${repos.length} repos to remove 'repos/' prefix from local_path`)
const updateStmt = db.prepare("UPDATE repos SET local_path = ? WHERE id = ?")
+5 -3
View File
@@ -1,6 +1,7 @@
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { getErrorMessage } from '../utils/error-utils'
import path from 'path'
export interface RepoRow {
@@ -67,8 +68,9 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
}
return newRepo
} catch (error: any) {
if (error.message?.includes('UNIQUE constraint failed') || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
} catch (error: unknown) {
const errorMessage = getErrorMessage(error)
if (errorMessage.includes('UNIQUE constraint failed') || (error && typeof error === 'object' && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE')) {
const conflictRepo = repo.isLocal
? getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
@@ -81,7 +83,7 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo {
throw new Error(`Repository with ${identifier} already exists but could not be retrieved. This may indicate database corruption.`)
}
throw new Error(`Failed to create repository: ${error.message}`)
throw new Error(`Failed to create repository: ${errorMessage}`)
}
}
+1 -1
View File
@@ -225,7 +225,7 @@ try {
app.route('/api/repos', createRepoRoutes(db))
app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/files', createFileRoutes(db))
app.route('/api/files', createFileRoutes())
app.route('/api/providers', createProvidersRoutes())
app.route('/api/oauth', createOAuthRoutes())
app.route('/api/tts', createTTSRoutes(db))
+13 -12
View File
@@ -1,9 +1,10 @@
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import * as fileService from '../services/files'
import type { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
export function createFileRoutes(_database: Database) {
export function createFileRoutes() {
const app = new Hono()
app.get('/*', async (c) => {
@@ -50,9 +51,9 @@ export function createFileRoutes(_database: Database) {
}
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get file:', error)
return c.json({ error: error.message || 'Failed to get file' }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) || 'Failed to get file' }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -69,9 +70,9 @@ export function createFileRoutes(_database: Database) {
const relativePath = body.relativePath as string | undefined
const result = await fileService.uploadFile(path, file, relativePath)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to upload file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -82,9 +83,9 @@ export function createFileRoutes(_database: Database) {
const result = await fileService.createFileOrFolder(path, body)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -94,9 +95,9 @@ export function createFileRoutes(_database: Database) {
await fileService.deleteFileOrFolder(path)
return c.json({ success: true })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to delete file/folder:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -112,9 +113,9 @@ export function createFileRoutes(_database: Database) {
const result = await fileService.renameOrMoveFile(path, body)
return c.json(result)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to patch file:', error)
return c.json({ error: error.message }, error.statusCode || 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
+26 -24
View File
@@ -1,4 +1,5 @@
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Database } from 'bun:sqlite'
import * as db from '../db/queries'
import * as repoService from '../services/repo'
@@ -9,6 +10,7 @@ import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { opencodeServerManager } from '../services/opencode-single-server'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-manager/shared/config/env'
import path from 'path'
@@ -55,9 +57,9 @@ export function createRepoRoutes(database: Database) {
}
return c.json(repo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
@@ -71,9 +73,9 @@ export function createRepoRoutes(database: Database) {
})
)
return c.json(reposWithCurrentBranch)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to list repos:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -89,9 +91,9 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(repo)
return c.json({ ...repo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -107,9 +109,9 @@ export function createRepoRoutes(database: Database) {
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to delete repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -120,9 +122,9 @@ export function createRepoRoutes(database: Database) {
const repo = db.getRepoById(database, id)
return c.json(repo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to pull repo:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -164,9 +166,9 @@ export function createRepoRoutes(database: Database) {
const updatedRepo = db.getRepoById(database, id)
return c.json(updatedRepo)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to switch repo config:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -192,12 +194,12 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
return c.json({ ...updatedRepo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to switch branch:', error)
if (error instanceof GitAuthenticationError) {
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
}
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -223,12 +225,12 @@ export function createRepoRoutes(database: Database) {
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
return c.json({ ...updatedRepo, currentBranch })
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create branch:', error)
if (error instanceof GitAuthenticationError) {
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
}
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -245,9 +247,9 @@ export function createRepoRoutes(database: Database) {
return c.json(branches)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to list branches:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -265,9 +267,9 @@ export function createRepoRoutes(database: Database) {
return c.json(status)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get git status:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -291,9 +293,9 @@ export function createRepoRoutes(database: Database) {
return c.json(diff)
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to get file diff:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
@@ -329,9 +331,9 @@ export function createRepoRoutes(database: Database) {
'Content-Length': archiveSize.toString(),
}
})
} catch (error: any) {
} catch (error: unknown) {
logger.error('Failed to create repo archive:', error)
return c.json({ error: error.message }, 500)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
+6 -6
View File
@@ -106,11 +106,11 @@ export async function getFile(userPath: string): Promise<FileInfo> {
} else {
// It's a file - get content
let content = ''
let mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
if (stats.size < FILE_LIMITS.MAX_SIZE_BYTES) {
try {
const mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
if (mimeType.startsWith('image/') || !mimeType.startsWith('text/')) {
content = await readFileAsBase64(validatedPath)
@@ -144,8 +144,8 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st
throw new Error('File too large')
}
const mimeType = file.type || getMimeType(file.name, new Uint8Array())
if (!ALLOWED_MIME_TYPES.includes(mimeType as any) && !mimeType.startsWith('text/')) {
const mimeType = file.type || getMimeType(file.name)
if (!ALLOWED_MIME_TYPES.includes(mimeType) && !mimeType.startsWith('text/')) {
throw new Error('File type not allowed')
}
@@ -246,7 +246,7 @@ function validatePath(userPath: string): string {
return resolved
}
function getMimeType(filePath: string, _content: Uint8Array): string {
function getMimeType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, string> = {
@@ -323,7 +323,7 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
const totalLines = await countFileLines(validatedPath)
const clampedEnd = Math.min(endLine, totalLines)
const lines = await readFileLines(validatedPath, startLine, clampedEnd)
const mimeType = getMimeType(validatedPath, new Uint8Array())
const mimeType = getMimeType(validatedPath)
return {
name: path.basename(validatedPath),
+11 -9
View File
@@ -1,5 +1,6 @@
import { executeCommand } from '../utils/process'
import { logger } from '../utils/logger'
import { getErrorMessage } from '../utils/error-utils'
import { SettingsService } from './settings'
import type { Database } from 'bun:sqlite'
import path from 'path'
@@ -153,9 +154,9 @@ export async function getGitStatus(repoPath: string, database?: Database): Promi
files,
hasChanges: files.length > 0
}
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to get git status for ${repoPath}:`, error)
throw new Error(`Failed to get git status: ${error.message}`)
throw new Error(`Failed to get git status: ${getErrorMessage(error)}`)
}
}
@@ -187,9 +188,10 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
try {
const content = await executeCommand(['git', '-C', fullRepoPath, 'diff', '--no-index', '--', '/dev/null', filePath], { env })
diff = content
} catch (error: any) {
if (error.message?.includes('exit code 1') || error.message?.includes('Command failed with code 1')) {
const output = error.message || ''
} catch (error: unknown) {
const errorMessage = getErrorMessage(error)
if (errorMessage?.includes('exit code 1') || errorMessage?.includes('Command failed with code 1')) {
const output = errorMessage || ''
const diffMatch = output.match(/diff --git[\s\S]*/)
diff = diffMatch ? diffMatch[0] : `New file: ${filePath}`
} else {
@@ -204,8 +206,8 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
} else {
diff = `New file (no commits yet): ${filePath}`
}
} catch (error: any) {
logger.warn(`Failed to get diff for ${filePath}:`, error.message)
} catch (error: unknown) {
logger.warn(`Failed to get diff for ${filePath}:`, getErrorMessage(error))
diff = null
}
}
@@ -233,8 +235,8 @@ export async function getFileDiff(repoPath: string, filePath: string, database?:
deletions,
isBinary
}
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to get file diff for ${filePath}:`, error)
throw new Error(`Failed to get file diff: ${error.message}`)
throw new Error(`Failed to get file diff: ${getErrorMessage(error)}`)
}
}
@@ -190,10 +190,9 @@ class OpenCodeServerManager {
await new Promise(r => setTimeout(r, 2000))
try {
process.kill(this.serverPid, 0)
process.kill(this.serverPid, 'SIGKILL')
} catch {
} catch (error) {
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
}
this.serverPid = null
-48
View File
@@ -693,26 +693,7 @@ export async function cleanupOrphanedDirectories(database: Database): Promise<vo
}
}
async function checkWorktreeExists(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
const worktreeList = await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'list', '--porcelain'])
return worktreeList.includes(worktreePath)
} catch {
return false
}
}
async function removeStaleWorktree(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
logger.info(`Attempting to remove stale worktree: ${worktreePath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath])
logger.info(`Successfully removed stale worktree: ${worktreePath}`)
return true
} catch (error: any) {
logger.warn(`Failed to remove stale worktree ${worktreePath}:`, error.message)
return false
}
}
async function pruneWorktreeReferences(baseRepoPath: string): Promise<void> {
try {
@@ -749,36 +730,7 @@ async function cleanupStaleWorktree(baseRepoPath: string, worktreePath: string):
}
}
async function isBranchCheckedOutInMainWorktree(baseRepoPath: string, branch: string): Promise<boolean> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
return currentBranch === branch
}
async function getAvailableBranchForWorktree(baseRepoPath: string, targetBranch: string): Promise<string> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
if (!currentBranch) {
return targetBranch
}
if (currentBranch === targetBranch) {
logger.info(`Branch '${targetBranch}' is currently checked out in main worktree`)
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD']).then(ref => ref.trim()).catch(() => 'main')
const cleanDefaultBranch = defaultBranch.replace('origin/', '')
if (cleanDefaultBranch !== currentBranch) {
logger.info(`Switching to '${cleanDefaultBranch}' to free up '${targetBranch}' for worktree`)
await executeCommand(['git', '-C', baseRepoPath, 'checkout', cleanDefaultBranch])
return targetBranch
} else {
logger.warn(`Cannot free up branch '${targetBranch}' - it's the default branch`)
return `${targetBranch}-worktree-${Date.now()}`
}
}
return targetBranch
}
async function createWorktreeSafely(baseRepoPath: string, worktreePath: string, branch: string): Promise<void> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
+34
View File
@@ -0,0 +1,34 @@
export function isError(error: unknown): error is Error {
return error instanceof Error
}
export function getErrorMessage(error: unknown): string {
if (isError(error)) {
return error.message
}
return String(error)
}
export function getErrorStack(error: unknown): string | undefined {
if (isError(error)) {
return error.stack
}
return undefined
}
interface ErrorWithStatusCode {
statusCode?: number
status?: number
}
const VALID_STATUS_CODES = new Set([200, 201, 204, 301, 302, 304, 400, 401, 403, 404, 405, 409, 413, 422, 500, 501, 502, 503])
export function getStatusCode(error: unknown): number {
let code = 500
if (error && typeof error === 'object' && 'statusCode' in error) {
code = (error as ErrorWithStatusCode).statusCode || 500
} else if (error && typeof error === 'object' && 'status' in error) {
code = (error as ErrorWithStatusCode).status || 500
}
return VALID_STATUS_CODES.has(code) ? code : 500
}