Files
CatoandClaude Fable 5.1 634ea86168 refactor: quality sweep — lint at zero warnings, one logger, shared ingestion kit, no generated client in git (#271)
* chore(repo): drop ralph.sh residue, ignore the generated Prisma client at the root

ralph.sh was byte-identical to reparaturbonus-zh/ralph.sh ("Ralph Loop for
Revamp-Hirn") and PROMPT.md was its blank task template; nothing in CI, docs
or scripts referenced either.

backend/generated/ is produced by `prisma generate` (typecheck, build and
Dockerfile.backend all run it) and was already ignored by backend/.gitignore,
so it was never committed — but tools that only read the root ignore file
(the fleet jscpd sweep) counted its ~1,300 generated lines as duplicated
source and reported the repo at 4.4%. Listing it at the root too makes those
sweeps see what git sees.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(backend): log through one pino instance, lint console.log out

The backend had pino-http for requests and bare console.log everywhere else
(index.js, jobs/, services/websocket.js — 26 lines). lib/logger.js now owns
the pino-http middleware and exposes its logger, so application logs and
request logs share level, destination and redaction. pino stays an indirect
dependency: pnpm does not hoist pino-http's copy, and a second pino would be
a second place to configure.

The backend had no linter at all. eslint.config.mjs enables exactly one rule,
no-console (warn/error allowed), so this cannot drift back; the root `lint`
now runs both halves, which is what `verify` and CI call.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(ingest): one shared kit for the image/video/audio/database ingestion components and the /ingest pages

The four data-ingestion components each carried their own copy of the
upload state machine (idle → uploading → processing → complete/error), the
file picker + drag-drop + object-URL preview, the auth header, the response
reader, the drop zone, progress bar, error banner, result card and submit
button. The five /ingest/<kind> pages likewise repeated the page frame, the
"Recent …" panel with its loading/error/empty states, the status badge and
the detail panel, plus a private copy of formatFileSize/formatDate.

Now there is one of each:
- components/data-ingestion/shared.tsx — useIngestionUpload, useFilePreview,
  authHeaders, readIngestionResponse and the shared markup pieces
- components/data-ingestion/icons.tsx — the inline SVG paths as data, one
  OutlineIcon/SpinnerIcon component
- ingest/shared.tsx — IngestPage, RecentPanel, StatusBadge, DetailPanel and
  the useRecentSources fetch
- lib/format.ts — formatFileSize/formatDuration/formatDate, with a test

Markup and copy are unchanged; the components render exactly what they did.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(forms): type the stored form structure once, drop the dead quick-field builder

`/api/v1/forms` returned `schema as any` and every consumer re-derived its
shape. `StoredFormStructure` / `FormListRow` in types/saved-form.ts are now
the one description of what the builder writes into the Json column, used by
the route, SavedFormsLibrary, ModernFormBuilderLayout and the builder page.

DynamicForm loses its unused `addQuickField` duplicate of FormFieldBuilder's
own field factory and an unused `handleCreateGroup` argument; the autosave
draft effect reads the current form through a ref instead of listing the
form as a dependency (which is what the exhaustive-deps warning was pointing
at — re-running it per keystroke would clobber the user's input).
SavedFormsLibrary wraps fetchForms in useCallback so the token effect is
honest about what it depends on; its `handleLoginSuccess` was never wired to
anything. Rendered output is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(frontend): fix every ESLint warning, gate lint at --max-warnings 0, ban console.log

The frontend lint config had downgraded no-unused-vars, no-explicit-any,
ban-ts-comment, exhaustive-deps, no-unescaped-entities and no-img-element to
"warn" ("temporarily, for build success") and `eslint .` ran with no
warning cap, so 152 warnings sat there unread. Every one is fixed at the
source rather than silenced:

- no-explicit-any: real types — jose's private `email` claim, the next-auth
  Session/User augmentation (`session.user.id` is set by the session
  callback), OpenAI.APIError for the vision route's status checks, typed
  event/data shapes elsewhere. The ambient `declare module '@dnd-kit/*'`
  stub is gone: `@dnd-kit/utilities` is now a declared dependency so its own
  types load.
- no-unused-vars: unused imports/params/state dropped. Seven components and
  one hook turned out to be rendered nowhere (BuilderToolbar,
  FormBuilderQuickStart, FormCreationHub, ModernSidebarStore, MultiStepForm,
  MultiStepFormBuilderStore, QuickActions, useApiRequest) — deleted, and the
  README paragraph that described the *Store wrappers updated.
- exhaustive-deps: callbacks memoised so the dependency arrays are truthful.
- ban-ts-comment / no-unescaped-entities: the comments were covering typed
  code; the entities are escaped.
- The 5 console.log calls in frontend/src (debug leftovers in components
  and services) are removed; console.warn/error stay. `no-console` (allow
  warn/error) is now an error so they cannot come back, with scripts/**
  exempt because printing is their job. (Of the 82 console.log in the repo,
  26 were the backend — routed through pino in the previous commit — and
  the rest are operator scripts, which print by design.)

The downgrade block is gone, so upstream next/core-web-vitals defaults
apply, and `lint` runs with `--max-warnings 0`: a warning fails the gate.
152 → 0.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:22:22 -07:00

113 lines
3.5 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const { createServer } = require('http');
require('dotenv').config();
const app = express();
const server = createServer(app);
const { trpcMiddleware } = require('./middleware/trpc');
const cookieParser = require('cookie-parser');
const { httpLogger, logger } = require('./lib/logger');
const webSocketService = require('./services/websocket');
const { getAIHealth } = require('./lib/aiChain');
// Middleware
app.use(
cors({
origin: process.env.FRONTEND_URL || 'http://localhost:3000',
credentials: true,
}),
);
app.use(express.json());
app.use(cookieParser());
app.use(httpLogger);
// Health check
app.get('/', (req, res) => {
res.json({
message: 'DataCat Backend API',
version: '2.0.0',
status: 'running',
endpoints: {
trpc: '/api/trpc',
rest: '/api/v1',
},
});
});
// Dedicated health endpoint for deployment monitoring
app.get('/health', async (req, res) => {
// AI health is informational only — it never flips this endpoint's overall
// `status`. A dead AI vendor chain is a real, user-visible degradation, but
// this app has non-AI features too; gating deploy health on it would take
// the whole box "down" for an outage in one dependency. See
// backend/lib/aiChain.js and ai-kit's health.ts for why this is tracked at
// all: a chain that silently swallows every failure looks identical to a
// healthy one from the outside.
const ai = await getAIHealth().catch(() => null);
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
version: '2.0.0',
environment: process.env.NODE_ENV || 'development',
ai,
});
});
// tRPC API (primary)
app.use('/api/trpc', trpcMiddleware);
// Legacy REST API routes (for backward compatibility)
app.use('/api/v1/auth', require('./routes/auth'));
app.use('/api/v1/user', require('./routes/user'));
app.use('/api/v1/forms', require('./routes/forms'));
app.use('/api/v1/submissions', require('./routes/submissions'));
app.use('/api/v1/databases', require('./routes/database'));
// Data Ingestion API routes
app.use('/api/v1/audio', require('./routes/audio'));
app.use('/api/v1/images', require('./routes/images'));
app.use('/api/v1/videos', require('./routes/videos'));
app.use('/api/v1/websites', require('./routes/websites'));
app.use('/api/v1/db-ingestion', require('./routes/dbIngestion'));
// Deprecated REST routes (redirect to v1)
app.use('/api/auth', (req, res) => {
res.status(301).json({
message: 'This endpoint has moved to /api/v1/auth',
deprecated: true,
});
});
app.use('/api/user', (req, res) => {
res.status(301).json({
message: 'This endpoint has moved to /api/v1/user',
deprecated: true,
});
});
app.use('/api/forms', (req, res) => {
res.status(301).json({
message: 'This endpoint has moved to /api/v1/forms',
deprecated: true,
});
});
app.use('/api/submissions', (req, res) => {
res.status(301).json({
message: 'This endpoint has moved to /api/v1/submissions',
deprecated: true,
});
});
const PORT = process.env.PORT || 5001;
// Initialize WebSocket service
webSocketService.initialize(server);
server.listen(PORT, '0.0.0.0', () => {
logger.info(`🚀 DataCat Backend Server running on port ${PORT}`);
logger.info(`📊 API endpoints available at http://localhost:${PORT}/api/trpc`);
logger.info(`🔌 WebSocket server ready for real-time connections`);
logger.info(`📚 Architecture documentation: /backend/ARCHITECTURE.md`);
});