From 225588d8d5f065e6254c1484cf02b0e6e687536a Mon Sep 17 00:00:00 2001 From: Serg Dort Date: Wed, 4 Mar 2026 20:47:43 +0000 Subject: [PATCH 1/3] refactor: adopt core service DI across API and CLI --- .agents/notes.md | 1 + AGENTS.md | 1 + apps/api/src/app/create-api-app.ts | 22 +- apps/api/src/features/extract/routes.ts | 15 +- apps/api/src/features/inbox/routes.ts | 17 +- apps/api/src/features/item/routes.ts | 17 +- apps/api/src/features/save/routes.ts | 17 +- apps/api/src/features/status/routes.ts | 25 +- apps/api/src/features/tags/routes.ts | 39 +- apps/api/src/features/tts/routes.ts | 57 +-- apps/api/test/integration.test.ts | 328 +++++++++++++++++ apps/cli/src/cli.ts | 335 ++++++------------ apps/cli/test/integration.test.ts | 31 ++ packages/core/src/index.ts | 1 + packages/core/src/services/contracts.ts | 92 +++++ .../core/src/services/create-core-services.ts | 51 +++ packages/core/src/services/index.ts | 2 + packages/core/test/core-services.test.ts | 184 ++++++++++ 18 files changed, 877 insertions(+), 358 deletions(-) create mode 100644 apps/api/test/integration.test.ts create mode 100644 packages/core/src/services/contracts.ts create mode 100644 packages/core/src/services/create-core-services.ts create mode 100644 packages/core/src/services/index.ts create mode 100644 packages/core/test/core-services.test.ts diff --git a/.agents/notes.md b/.agents/notes.md index f4114ce..37b49e7 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -50,3 +50,4 @@ [0] In SQLite table-rebuild migrations (`__new_*` + rename), `CHECK` constraints must reference unqualified column names; qualifiers like `__new_table.column` can break after rename. [0] Drizzle SQLite migrator runs migrations in a transaction; `PRAGMA foreign_keys=OFF` inside migration SQL may not disable FK checks. Table-copy migrations should filter/clean orphan rows explicitly (e.g., `INNER JOIN` parents) instead of relying on that pragma. [0] CI `validate` workflow currently runs `format:check`, `lint`, `test`, and `apps/web` build. Before pushing, run all four locally to avoid fast-follow CI fix commits. +[0] `stash db doctor` does not create parent directories for a missing DB path; if `STASH_DB_PATH` points to a non-existent directory, command can fail with `unable to open database file`. diff --git a/AGENTS.md b/AGENTS.md index 6c4ae52..be992d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,3 +370,4 @@ Updates should include: - Prefer Drizzle ORM for database access in application/runtime code. - Use raw SQL string queries only when Drizzle does not support the required functionality clearly or safely (for example, specialized migration-runner behavior). - Prefer explicit return types on functions and methods (especially exported/public APIs and non-trivial helpers). +- Dependency injection pattern: prefer `createXService`/`createCoreServices` factory objects over classes, and inject least-privilege service slices into API route plugins and command handlers. diff --git a/apps/api/src/app/create-api-app.ts b/apps/api/src/app/create-api-app.ts index 4e6aa88..2589a70 100644 --- a/apps/api/src/app/create-api-app.ts +++ b/apps/api/src/app/create-api-app.ts @@ -2,6 +2,7 @@ import Fastify, { type FastifyInstance } from "fastify" import { extractRoutes } from "../features/extract/routes.js" import { inboxRoutes } from "../features/inbox/routes.js" import { itemRoutes } from "../features/item/routes.js" +import { createCoreServices } from "../../../../packages/core/src/services/index.js" import type { ApiRouteOptions } from "../features/options.js" import { saveRoutes } from "../features/save/routes.js" import { statusRoutes } from "../features/status/routes.js" @@ -15,6 +16,10 @@ export function createApiApp(options: CreateApiAppOptions): FastifyInstance { const server = Fastify({ logger: false, }) + const services = createCoreServices({ + dbPath: options.dbPath, + migrationsDir: options.migrationsDir, + }) // Fastify's default JSON parser rejects empty bodies (e.g. DELETE with Content-Type: application/json). // Override it to treat empty bodies as undefined instead of an error. @@ -36,13 +41,16 @@ export function createApiApp(options: CreateApiAppOptions): FastifyInstance { async (api) => { api.get("/health", async () => ({ ok: true })) - api.register(inboxRoutes, options) - api.register(itemRoutes, options) - api.register(saveRoutes, options) - api.register(tagsRoutes, options) - api.register(statusRoutes, options) - api.register(extractRoutes, options) - api.register(ttsRoutes, options) + api.register(inboxRoutes, { itemsService: services.items }) + api.register(itemRoutes, { itemsService: services.items }) + api.register(saveRoutes, { itemsService: services.items }) + api.register(tagsRoutes, { tagsService: services.tags }) + api.register(statusRoutes, { statusService: services.status }) + api.register(extractRoutes, { extractService: services.extract }) + api.register(ttsRoutes, { + ttsJobsService: services.ttsJobs, + audioDir: options.audioDir, + }) }, { prefix: "/api" }, ) diff --git a/apps/api/src/features/extract/routes.ts b/apps/api/src/features/extract/routes.ts index 9f5cfab..00fb94c 100644 --- a/apps/api/src/features/extract/routes.ts +++ b/apps/api/src/features/extract/routes.ts @@ -1,7 +1,6 @@ import type { FastifyPluginAsync } from "fastify" -import { extractItem } from "../../../../../packages/core/src/features/extract/service.js" -import type { ApiRouteOptions } from "../options.js" +import type { ExtractService } from "../../../../../packages/core/src/services/contracts.js" import { parseAutoTags, parseForce, parseItemId } from "./dto.js" const extractParamsSchema = { @@ -20,7 +19,7 @@ const extractBodySchema = { }, } as const -export const extractRoutes: FastifyPluginAsync = async (fastify, options) => { +export const extractRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.post( "/items/:id/extract", { @@ -31,11 +30,7 @@ export const extractRoutes: FastifyPluginAsync = async (fastify }, async (request) => { const autoTags = parseAutoTags(request.body) - const result = await extractItem( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, + const result = await options.extractService.extractItem( parseItemId(request.params as Record), { force: parseForce(request.body), @@ -50,3 +45,7 @@ export const extractRoutes: FastifyPluginAsync = async (fastify }, ) } + +export type ExtractRoutesOptions = { + extractService: Pick +} diff --git a/apps/api/src/features/inbox/routes.ts b/apps/api/src/features/inbox/routes.ts index 70cc7db..5486bec 100644 --- a/apps/api/src/features/inbox/routes.ts +++ b/apps/api/src/features/inbox/routes.ts @@ -1,7 +1,6 @@ import type { FastifyPluginAsync } from "fastify" -import { listItems } from "../../../../../packages/core/src/features/items/service.js" -import type { ApiRouteOptions } from "../options.js" +import type { ItemsService } from "../../../../../packages/core/src/services/contracts.js" import { getSearchParams } from "../../shared/request/search-params.js" import { parseInboxQuery } from "./dto.js" @@ -24,7 +23,7 @@ const inboxQuerySchema = { }, } as const -export const inboxRoutes: FastifyPluginAsync = async (fastify, options) => { +export const inboxRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.get( "/items", { @@ -33,13 +32,7 @@ export const inboxRoutes: FastifyPluginAsync = async (fastify, }, }, async (request) => { - const result = listItems( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - parseInboxQuery(getSearchParams(request)), - ) + const result = options.itemsService.listItems(parseInboxQuery(getSearchParams(request))) return { ok: true, @@ -48,3 +41,7 @@ export const inboxRoutes: FastifyPluginAsync = async (fastify, }, ) } + +export type InboxRoutesOptions = { + itemsService: Pick +} diff --git a/apps/api/src/features/item/routes.ts b/apps/api/src/features/item/routes.ts index d69de9d..6406d07 100644 --- a/apps/api/src/features/item/routes.ts +++ b/apps/api/src/features/item/routes.ts @@ -1,8 +1,7 @@ import type { FastifyPluginAsync } from "fastify" -import { getItem } from "../../../../../packages/core/src/features/items/service.js" import { StashError } from "../../../../../packages/core/src/errors.js" -import type { ApiRouteOptions } from "../options.js" +import type { ItemsService } from "../../../../../packages/core/src/services/contracts.js" import { parseItemId } from "./dto.js" const itemParamsSchema = { @@ -13,7 +12,7 @@ const itemParamsSchema = { required: ["id"], } as const -export const itemRoutes: FastifyPluginAsync = async (fastify, options) => { +export const itemRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.get( "/items/:id", { @@ -23,13 +22,7 @@ export const itemRoutes: FastifyPluginAsync = async (fastify, o }, async (request) => { const itemId = parseItemId(request.params as Record) - const item = getItem( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - itemId, - ) + const item = options.itemsService.getItem(itemId) if (!item) { throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) @@ -42,3 +35,7 @@ export const itemRoutes: FastifyPluginAsync = async (fastify, o }, ) } + +export type ItemRoutesOptions = { + itemsService: Pick +} diff --git a/apps/api/src/features/save/routes.ts b/apps/api/src/features/save/routes.ts index e98e11e..8ae183f 100644 --- a/apps/api/src/features/save/routes.ts +++ b/apps/api/src/features/save/routes.ts @@ -1,7 +1,6 @@ import type { FastifyPluginAsync } from "fastify" -import { saveItem } from "../../../../../packages/core/src/features/items/service.js" -import type { ApiRouteOptions } from "../options.js" +import type { ItemsService } from "../../../../../packages/core/src/services/contracts.js" import { parseSaveBody } from "./dto.js" const saveBodySchema = { @@ -19,7 +18,7 @@ const saveBodySchema = { required: ["url"], } as const -export const saveRoutes: FastifyPluginAsync = async (fastify, options) => { +export const saveRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.post( "/items", { @@ -28,13 +27,7 @@ export const saveRoutes: FastifyPluginAsync = async (fastify, o }, }, async (request) => { - const result = await saveItem( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - parseSaveBody(request.body), - ) + const result = await options.itemsService.saveItem(parseSaveBody(request.body)) return { ok: true, @@ -43,3 +36,7 @@ export const saveRoutes: FastifyPluginAsync = async (fastify, o }, ) } + +export type SaveRoutesOptions = { + itemsService: Pick +} diff --git a/apps/api/src/features/status/routes.ts b/apps/api/src/features/status/routes.ts index 20fe7be..b581cfe 100644 --- a/apps/api/src/features/status/routes.ts +++ b/apps/api/src/features/status/routes.ts @@ -1,7 +1,6 @@ import type { FastifyPluginAsync } from "fastify" -import { markRead, markUnread } from "../../../../../packages/core/src/features/status/service.js" -import type { ApiRouteOptions } from "../options.js" +import type { StatusService } from "../../../../../packages/core/src/services/contracts.js" import { parseItemId, parseStatusBody } from "./dto.js" const statusParamsSchema = { @@ -23,7 +22,7 @@ const statusBodySchema = { required: ["status"], } as const -export const statusRoutes: FastifyPluginAsync = async (fastify, options) => { +export const statusRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.patch( "/items/:id/status", { @@ -39,20 +38,8 @@ export const statusRoutes: FastifyPluginAsync = async (fastify, const result = status === "read" - ? markRead( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - itemId, - ) - : markUnread( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - itemId, - ) + ? options.statusService.markRead(itemId) + : options.statusService.markUnread(itemId) return { ok: true, @@ -61,3 +48,7 @@ export const statusRoutes: FastifyPluginAsync = async (fastify, }, ) } + +export type StatusRoutesOptions = { + statusService: Pick +} diff --git a/apps/api/src/features/tags/routes.ts b/apps/api/src/features/tags/routes.ts index 5ed98aa..7b09016 100644 --- a/apps/api/src/features/tags/routes.ts +++ b/apps/api/src/features/tags/routes.ts @@ -1,11 +1,6 @@ import type { FastifyPluginAsync } from "fastify" -import { - addTag, - listTags, - removeTag, -} from "../../../../../packages/core/src/features/tags/service.js" -import type { ApiRouteOptions } from "../options.js" +import type { TagsService } from "../../../../../packages/core/src/services/contracts.js" import { getSearchParams } from "../../shared/request/search-params.js" import { parseItemId, parseTagBody, parseTagParam, parseTagsListQuery } from "./dto.js" @@ -42,7 +37,7 @@ const addTagBodySchema = { required: ["tag"], } as const -export const tagsRoutes: FastifyPluginAsync = async (fastify, options) => { +export const tagsRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.get( "/tags", { @@ -51,13 +46,7 @@ export const tagsRoutes: FastifyPluginAsync = async (fastify, o }, }, async (request) => { - const result = listTags( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - parseTagsListQuery(getSearchParams(request)), - ) + const result = options.tagsService.listTags(parseTagsListQuery(getSearchParams(request))) return { ok: true, @@ -76,14 +65,7 @@ export const tagsRoutes: FastifyPluginAsync = async (fastify, o }, async (request) => { const params = request.params as Record - const result = addTag( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - parseItemId(params), - parseTagBody(request.body), - ) + const result = options.tagsService.addTag(parseItemId(params), parseTagBody(request.body)) return { ok: true, @@ -101,14 +83,7 @@ export const tagsRoutes: FastifyPluginAsync = async (fastify, o }, async (request) => { const params = request.params as Record - const result = removeTag( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - parseItemId(params), - parseTagParam(params), - ) + const result = options.tagsService.removeTag(parseItemId(params), parseTagParam(params)) return { ok: true, @@ -117,3 +92,7 @@ export const tagsRoutes: FastifyPluginAsync = async (fastify, o }, ) } + +export type TagsRoutesOptions = { + tagsService: Pick +} diff --git a/apps/api/src/features/tts/routes.ts b/apps/api/src/features/tts/routes.ts index 4ba829b..89f5611 100644 --- a/apps/api/src/features/tts/routes.ts +++ b/apps/api/src/features/tts/routes.ts @@ -3,14 +3,8 @@ import path from "node:path" import type { FastifyPluginAsync } from "fastify" -import { - enqueueTtsJob, - getTtsJob, - listTtsJobsForItem, - waitForTtsJob, -} from "../../../../../packages/core/src/features/tts/jobs.js" import { StashError } from "../../../../../packages/core/src/errors.js" -import type { ApiRouteOptions } from "../options.js" +import type { TtsJobsService } from "../../../../../packages/core/src/services/contracts.js" import { getSearchParams } from "../../shared/request/search-params.js" import { parseFileName, parseItemId, parseJobListQuery, parseTtsBody } from "./dto.js" @@ -60,7 +54,7 @@ function mapJobFailureToHttp(errorCode: string | null): number { } } -export const ttsRoutes: FastifyPluginAsync = async (fastify, options) => { +export const ttsRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.post( "/items/:id/tts", { @@ -84,25 +78,12 @@ export const ttsRoutes: FastifyPluginAsync = async (fastify, op enqueueInput.format = body.format } - const enqueue = enqueueTtsJob( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - enqueueInput, - ) + const enqueue = options.ttsJobsService.enqueueTtsJob(enqueueInput) if (body.wait) { - const job = await waitForTtsJob( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - enqueue.job.id, - { - pollMs: enqueue.poll_interval_ms, - }, - ) + const job = await options.ttsJobsService.waitForTtsJob(enqueue.job.id, { + pollMs: enqueue.poll_interval_ms, + }) if (job.status === "failed") { throw new StashError( @@ -203,13 +184,7 @@ export const ttsRoutes: FastifyPluginAsync = async (fastify, op }, async (request) => { const jobId = parseItemId(request.params as Record) - const job = getTtsJob( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - jobId, - ) + const job = options.ttsJobsService.getTtsJob(jobId) return { ok: true, @@ -229,15 +204,7 @@ export const ttsRoutes: FastifyPluginAsync = async (fastify, op async (request) => { const itemId = parseItemId(request.params as Record) const { limit, offset } = parseJobListQuery(getSearchParams(request)) - const jobs = listTtsJobsForItem( - { - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }, - itemId, - limit, - offset, - ) + const jobs = options.ttsJobsService.listTtsJobsForItem(itemId, limit, offset) return { ok: true, @@ -251,3 +218,11 @@ export const ttsRoutes: FastifyPluginAsync = async (fastify, op }, ) } + +export type TtsRoutesOptions = { + ttsJobsService: Pick< + TtsJobsService, + "enqueueTtsJob" | "waitForTtsJob" | "getTtsJob" | "listTtsJobsForItem" + > + audioDir: string +} diff --git a/apps/api/test/integration.test.ts b/apps/api/test/integration.test.ts new file mode 100644 index 0000000..be45490 --- /dev/null +++ b/apps/api/test/integration.test.ts @@ -0,0 +1,328 @@ +import { spawnSync } from "node:child_process" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" + +import { describe, expect, it } from "vitest" + +import { createApiApp } from "../src/app/create-api-app.js" + +type SaveResponse = { + ok: boolean + created: boolean + item: { + id: number + url: string + tags: string[] + status: "unread" | "read" | "archived" + } +} + +type ListResponse = { + ok: boolean + items: Array<{ + id: number + url: string + tags: string[] + status: "unread" | "read" | "archived" + }> + paging: { + limit: number + offset: number + returned: number + } +} + +type ItemResponse = { + ok: boolean + item: { + id: number + url: string + tags: string[] + status: "unread" | "read" | "archived" + } +} + +type StatusResponse = { + ok: boolean + item_id: number + action: "mark_read" | "mark_unread" + status: "read" | "unread" +} + +type ExtractResponse = { + ok: boolean + item_id: number + title_extracted: string | null + title_updated: boolean + content_length: number + updated_at: string +} + +type TagsListResponse = { + ok: boolean + tags: Array<{ name: string; item_count: number }> + paging: { + limit: number + offset: number + returned: number + } +} + +type TagMutationResponse = { + ok: boolean + item_id: number + tag: string + added?: boolean + removed?: boolean +} + +type TtsEnqueueResponse = { + ok: boolean + created: boolean + job: { + id: number + item_id: number + status: "queued" | "running" + } + poll_interval_ms: number + poll_url: string +} + +type TtsJobResponse = { + ok: boolean + job: { + id: number + item_id: number + status: "queued" | "running" | "succeeded" | "failed" + output_file_name: string | null + } +} + +type TtsJobsListResponse = { + ok: boolean + jobs: Array<{ + id: number + item_id: number + status: "queued" | "running" | "succeeded" | "failed" + }> + paging: { + limit: number + offset: number + returned: number + } +} + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) +const repoRoot = path.resolve(__dirname, "../../..") +const migrationsDir = path.join(repoRoot, "drizzle") + +function probeSqliteBinding(): ReturnType { + return spawnSync( + process.execPath, + [ + "-e", + "import('better-sqlite3').then((mod) => { const Database = mod.default; const db = new Database(':memory:'); db.close(); process.exit(0); }).catch((error) => { console.error(error?.message ?? String(error)); process.exit(1); })", + ], + { + cwd: repoRoot, + encoding: "utf8", + env: process.env, + }, + ) +} + +function createTempPaths(): { dbPath: string; audioDir: string; cleanup: () => void } { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-api-integration-")) + const dbPath = path.join(tempDir, "stash.db") + const audioDir = path.join(tempDir, "audio") + const cleanup = (): void => { + fs.rmSync(tempDir, { recursive: true, force: true }) + } + return { dbPath, audioDir, cleanup } +} + +function buildDataHtmlUrl(html: string): string { + return `data:text/html;charset=utf-8,${encodeURIComponent(html)}` +} + +function parseJson(payload: string): T { + return JSON.parse(payload) as T +} + +const sqliteProbe = probeSqliteBinding() +const sqliteProbeOutput = `${sqliteProbe.stdout}\n${sqliteProbe.stderr}` +const sqliteBindingsMissing = + sqliteProbe.status !== 0 && sqliteProbeOutput.includes("Could not locate the bindings file") + +if (sqliteProbe.status !== 0 && !sqliteBindingsMissing) { + throw new Error(`Failed to load better-sqlite3 before tests:\n${sqliteProbeOutput}`) +} + +const integrationSuite = sqliteBindingsMissing ? describe.skip : describe +const integrationTitle = sqliteBindingsMissing + ? "integration: stash API (skipped: better-sqlite3 native bindings unavailable)" + : "integration: stash API" + +integrationSuite(integrationTitle, () => { + it("keeps endpoint response contracts stable across save/list/item/status/extract/tags/tts flows", async () => { + const { dbPath, audioDir, cleanup } = createTempPaths() + const app = createApiApp({ + dbPath, + migrationsDir, + audioDir, + }) + + try { + const articleUrl = buildDataHtmlUrl( + "

API integration article

Testing extraction and route contracts for API.

", + ) + + const saveRes = await app.inject({ + method: "POST", + url: "/api/items", + payload: { + url: articleUrl, + title: "API item", + tags: ["API", "test"], + extract: false, + }, + }) + expect(saveRes.statusCode).toBe(200) + const saveBody = parseJson(saveRes.payload) + expect(Object.keys(saveBody).sort()).toEqual(["created", "item", "ok"]) + expect(saveBody.ok).toBe(true) + expect(saveBody.created).toBe(true) + expect(saveBody.item.tags).toEqual(["api", "test"]) + + const itemId = saveBody.item.id + + const listRes = await app.inject({ + method: "GET", + url: "/api/items", + }) + expect(listRes.statusCode).toBe(200) + const listBody = parseJson(listRes.payload) + expect(Object.keys(listBody).sort()).toEqual(["items", "ok", "paging"]) + expect(listBody.ok).toBe(true) + expect(listBody.items[0]?.id).toBe(itemId) + + const getItemRes = await app.inject({ + method: "GET", + url: `/api/items/${itemId}`, + }) + expect(getItemRes.statusCode).toBe(200) + const getItemBody = parseJson(getItemRes.payload) + expect(Object.keys(getItemBody).sort()).toEqual(["item", "ok"]) + expect(getItemBody.ok).toBe(true) + expect(getItemBody.item.id).toBe(itemId) + + const patchStatusRes = await app.inject({ + method: "PATCH", + url: `/api/items/${itemId}/status`, + payload: { status: "read" }, + }) + expect(patchStatusRes.statusCode).toBe(200) + const patchStatusBody = parseJson(patchStatusRes.payload) + expect(Object.keys(patchStatusBody).sort()).toEqual(["action", "item_id", "ok", "status"]) + expect(patchStatusBody.ok).toBe(true) + expect(patchStatusBody.action).toBe("mark_read") + expect(patchStatusBody.status).toBe("read") + + const extractRes = await app.inject({ + method: "POST", + url: `/api/items/${itemId}/extract`, + payload: {}, + }) + expect(extractRes.statusCode).toBe(200) + const extractBody = parseJson(extractRes.payload) + expect(Object.keys(extractBody).sort()).toEqual([ + "content_length", + "item_id", + "ok", + "title_extracted", + "title_updated", + "updated_at", + ]) + expect(extractBody.ok).toBe(true) + expect(extractBody.item_id).toBe(itemId) + expect(extractBody.content_length).toBeGreaterThan(0) + + const tagsListRes = await app.inject({ + method: "GET", + url: "/api/tags", + }) + expect(tagsListRes.statusCode).toBe(200) + const tagsListBody = parseJson(tagsListRes.payload) + expect(Object.keys(tagsListBody).sort()).toEqual(["ok", "paging", "tags"]) + expect(tagsListBody.ok).toBe(true) + expect(tagsListBody.tags.map((entry) => entry.name)).toContain("api") + + const addTagRes = await app.inject({ + method: "POST", + url: `/api/items/${itemId}/tags`, + payload: { tag: "backend" }, + }) + expect(addTagRes.statusCode).toBe(200) + const addTagBody = parseJson(addTagRes.payload) + expect(Object.keys(addTagBody).sort()).toEqual(["added", "item_id", "ok", "tag"]) + expect(addTagBody.ok).toBe(true) + expect(addTagBody.added).toBe(true) + expect(addTagBody.tag).toBe("backend") + + const removeTagRes = await app.inject({ + method: "DELETE", + url: `/api/items/${itemId}/tags/backend`, + }) + expect(removeTagRes.statusCode).toBe(200) + const removeTagBody = parseJson(removeTagRes.payload) + expect(Object.keys(removeTagBody).sort()).toEqual(["item_id", "ok", "removed", "tag"]) + expect(removeTagBody.ok).toBe(true) + expect(removeTagBody.removed).toBe(true) + + const enqueueTtsRes = await app.inject({ + method: "POST", + url: `/api/items/${itemId}/tts`, + payload: {}, + }) + expect(enqueueTtsRes.statusCode).toBe(202) + const enqueueTtsBody = parseJson(enqueueTtsRes.payload) + expect(Object.keys(enqueueTtsBody).sort()).toEqual([ + "created", + "job", + "ok", + "poll_interval_ms", + "poll_url", + ]) + expect(enqueueTtsBody.ok).toBe(true) + expect(enqueueTtsBody.created).toBe(true) + expect(enqueueTtsBody.job.item_id).toBe(itemId) + expect(enqueueTtsBody.poll_url).toBe(`/api/tts-jobs/${enqueueTtsBody.job.id}`) + + const getJobRes = await app.inject({ + method: "GET", + url: `/api/tts-jobs/${enqueueTtsBody.job.id}`, + }) + expect(getJobRes.statusCode).toBe(200) + const getJobBody = parseJson(getJobRes.payload) + expect(Object.keys(getJobBody).sort()).toEqual(["job", "ok"]) + expect(getJobBody.ok).toBe(true) + expect(getJobBody.job.id).toBe(enqueueTtsBody.job.id) + + const itemJobsRes = await app.inject({ + method: "GET", + url: `/api/items/${itemId}/tts-jobs`, + }) + expect(itemJobsRes.statusCode).toBe(200) + const itemJobsBody = parseJson(itemJobsRes.payload) + expect(Object.keys(itemJobsBody).sort()).toEqual(["jobs", "ok", "paging"]) + expect(itemJobsBody.ok).toBe(true) + expect(itemJobsBody.jobs[0]?.id).toBe(enqueueTtsBody.job.id) + } finally { + await app.close() + cleanup() + } + }) +}) diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 25440f8..3d01bd9 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -4,30 +4,17 @@ import path from "node:path" import { fileURLToPath } from "node:url" import { Command, InvalidArgumentError } from "commander" -import { and, asc, desc, eq, exists, inArray, type SQL, sql } from "drizzle-orm" -import { openDb, type StashDb } from "../../../packages/core/src/db/client.js" import { getMigrationStatus, runMigrations } from "../../../packages/core/src/db/migrate.js" -import * as schema from "../../../packages/core/src/db/schema.js" import { StashError } from "../../../packages/core/src/errors.js" -import { inspectAutoTagsHealth } from "../../../packages/core/src/features/auto-tags/doctor.js" -import { extractItem } from "../../../packages/core/src/features/extract/service.js" -import { saveItem } from "../../../packages/core/src/features/items/service.js" -import { addTag, listTags, removeTag } from "../../../packages/core/src/features/tags/service.js" -import { inspectCoquiTtsHealth } from "../../../packages/core/src/features/tts/doctor.js" -import { - enqueueTtsJob, - getTtsJob, - runTtsWorkerOnce, - startTtsWorker, - waitForTtsJob, -} from "../../../packages/core/src/features/tts/jobs.js" import { DEFAULT_AUDIO_DIR, DEFAULT_DB_PATH, resolveAudioDir, resolveDbPath, } from "../../../packages/core/src/lib/paths.js" +import { createCoreServices } from "../../../packages/core/src/services/index.js" +import type { StashItem as CoreStashItem } from "../../../packages/core/src/types.js" import { startWebStack } from "../../api/src/index.js" const CLI_DIR = path.dirname(fileURLToPath(import.meta.url)) @@ -49,9 +36,6 @@ const DEFAULT_TTS_VOICE = "tts_models/en/vctk/vits|p241" // Coqui male voice type ItemStatus = "unread" | "read" | "archived" type TagMode = "any" | "all" -type ItemRow = typeof schema.items.$inferSelect & { status: ItemStatus } -type Db = StashDb - type StashItem = { id: number url: string @@ -130,17 +114,6 @@ function ensureDbDirectory(dbPath: string): void { fs.mkdirSync(dir, { recursive: true }) } -function nowMs(): number { - return Date.now() -} - -function toIso(value: Date | number | null): string | null { - if (value === null) { - return null - } - return (value instanceof Date ? value : new Date(value)).toISOString() -} - function normalizeTag(tag: string): string { const normalized = tag.trim().toLowerCase() if (normalized.length === 0) { @@ -170,19 +143,19 @@ function parsePort(value: string): number { return port } -function serializeItem(row: ItemRow, tags: string[]): StashItem { +function toCliListItem(item: CoreStashItem): StashItem { return { - id: row.id, - url: row.url, - title: row.title, - domain: row.domain, - status: row.status, - is_starred: row.isStarred, - tags, - created_at: toIso(row.createdAt) as string, - updated_at: toIso(row.updatedAt) as string, - read_at: toIso(row.readAt), - archived_at: toIso(row.archivedAt), + id: item.id, + url: item.url, + title: item.title, + domain: item.domain, + status: item.status, + is_starred: item.is_starred, + tags: item.tags, + created_at: item.created_at, + updated_at: item.updated_at, + read_at: item.read_at, + archived_at: item.archived_at, } } @@ -230,16 +203,6 @@ function handleActionError(error: unknown, jsonMode: boolean): never { printError(message, jsonMode, "INTERNAL_ERROR", 1) } -function withDb(dbPath: string, action: (db: Db) => T): T { - ensureDbDirectory(dbPath) - const { db, sqlite } = openDb(dbPath) - try { - return action(db) - } finally { - sqlite.close() - } -} - function resolveMigrationsDir(value?: string): string { if (!value || value.trim().length === 0) { return DEFAULT_MIGRATIONS_DIR @@ -264,37 +227,6 @@ function ensureDbReady(dbPath: string): void { runMigrations(dbPath, migrationsDir) } -function withReadyDb(dbPath: string, action: (db: Db) => T): T { - ensureDbReady(dbPath) - return withDb(dbPath, action) -} - -function getTagsMap(db: Db, itemIds: number[]): Map { - const map = new Map() - if (itemIds.length === 0) { - return map - } - - const rows = db - .select({ - itemId: schema.itemTags.itemId, - name: schema.tags.name, - }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where(inArray(schema.itemTags.itemId, itemIds)) - .orderBy(asc(schema.tags.name)) - .all() - - for (const row of rows) { - const values = map.get(row.itemId) ?? [] - values.push(row.name) - map.set(row.itemId, values) - } - - return map -} - function runDbAction(jsonMode: boolean, action: () => T | Promise): T | Promise { try { const result = action() @@ -468,6 +400,7 @@ program dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) return runDbAction(jsonMode, async () => { const saveInput = { @@ -477,7 +410,7 @@ program ...(options.extract !== undefined ? { extract: options.extract } : {}), ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), } - const result = await saveItem(context, saveInput) + const result = await services.items.saveItem(saveInput) if (jsonMode) { printJson({ @@ -528,6 +461,7 @@ program dbPath, migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) return runDbAction(jsonMode, async () => { if (id === "doctor") { @@ -539,7 +473,7 @@ program ) } - const report = inspectCoquiTtsHealth() + const report = services.doctor.inspectCoquiTtsHealth() if (jsonMode) { printJson({ ok: true, @@ -579,7 +513,7 @@ program ) } const parsedJobId = parseItemId(jobId) - const job = getTtsJob(context, parsedJobId) + const job = services.ttsJobs.getTtsJob(parsedJobId) if (jsonMode) { printJson({ @@ -603,7 +537,7 @@ program } const itemId = parseItemId(id) - const enqueue = enqueueTtsJob(context, { + const enqueue = services.ttsJobs.enqueueTtsJob({ itemId, voice: options.voice, format: options.format, @@ -628,13 +562,13 @@ program } const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) - const worker = startTtsWorker(context, { + const worker = services.ttsJobs.startTtsWorker({ pollMs: options.pollMs, audioDir, }) try { - const completed = await waitForTtsJob(context, enqueue.job.id, { + const completed = await services.ttsJobs.waitForTtsJob(enqueue.job.id, { pollMs: options.pollMs, }) @@ -687,6 +621,7 @@ program dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) const itemId = parseItemId(id) return runDbAction(jsonMode, async () => { @@ -694,7 +629,7 @@ program ...(options.force !== undefined ? { force: options.force } : {}), ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), } - const result = await extractItem(context, itemId, extractOptions) + const result = await services.extract.extractItem(itemId, extractOptions) if (jsonMode) { printJson({ @@ -748,80 +683,48 @@ program printError("Invalid tag mode. Use any or all.", jsonMode, "VALIDATION_ERROR", 2) } - runDbAction(jsonMode, () => - withReadyDb(resolveDbPath(program.opts().dbPath as string), (db) => { - const tags = normalizeTags(options.tag ?? []) - const conditions: SQL[] = [] - - if (status) { - conditions.push(eq(schema.items.status, status)) - } - - if (tags.length > 0) { - if (tagMode === "any") { - const subquery = db - .select({ one: sql`1` }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where( - and(eq(schema.itemTags.itemId, schema.items.id), inArray(schema.tags.name, tags)), - ) - conditions.push(exists(subquery)) - } else { - for (const tag of tags) { - const subquery = db - .select({ one: sql`1` }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where( - and(eq(schema.itemTags.itemId, schema.items.id), eq(schema.tags.name, tag)), - ) - conditions.push(exists(subquery)) - } - } - } - - const whereClause = conditions.length > 0 ? and(...conditions) : undefined - const rows = db - .select() - .from(schema.items) - .where(whereClause) - .orderBy(desc(schema.items.createdAt), desc(schema.items.id)) - .limit(options.limit) - .offset(options.offset) - .all() as ItemRow[] - - const tagsMap = getTagsMap( - db, - rows.map((row) => row.id), - ) - const items = rows.map((row) => serializeItem(row, tagsMap.get(row.id) ?? [])) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) + + runDbAction(jsonMode, () => { + const tags = normalizeTags(options.tag ?? []) + const listInput = { + tags, + tagMode, + limit: options.limit, + offset: options.offset, + ...(status ? { status } : {}), + } + const result = services.items.listItems(listInput) + const items = result.items.map(toCliListItem) - if (jsonMode) { - printJson({ - ok: true, - items, - paging: { - limit: options.limit, - offset: options.offset, - returned: items.length, - }, - }) - return - } + if (jsonMode) { + printJson({ + ok: true, + items, + paging: { + limit: options.limit, + offset: options.offset, + returned: items.length, + }, + }) + return + } - if (items.length === 0) { - process.stdout.write("No items found.\n") - return - } + if (items.length === 0) { + process.stdout.write("No items found.\n") + return + } - for (const item of items) { - const displayTitle = item.title ?? item.url - const displayTags = item.tags.length > 0 ? ` [${item.tags.join(", ")}]` : "" - process.stdout.write(`#${item.id} ${item.status} ${displayTitle}${displayTags}\n`) - } - }), - ) + for (const item of items) { + const displayTitle = item.title ?? item.url + const displayTags = item.tags.length > 0 ? ` [${item.tags.join(", ")}]` : "" + process.stdout.write(`#${item.id} ${item.status} ${displayTitle}${displayTags}\n`) + } + }) }, ) @@ -849,9 +752,10 @@ tagsCommand dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) runDbAction(jsonMode, () => { - const result = listTags(context, { + const result = services.tags.listTags({ limit: options.limit, offset: options.offset, }) @@ -881,9 +785,14 @@ tagsCommand .option("--json", "Print machine-readable JSON output") .action((options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) runDbAction(jsonMode, () => { - const report = inspectAutoTagsHealth() + const report = services.doctor.inspectAutoTagsHealth() if (jsonMode) { printJson({ @@ -933,9 +842,10 @@ tagCommand dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) runDbAction(jsonMode, () => { - const result = addTag(context, parseItemId(id), tag) + const result = services.tags.addTag(parseItemId(id), tag) if (jsonMode) { printJson({ ok: true, @@ -960,9 +870,10 @@ tagCommand dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) runDbAction(jsonMode, () => { - const result = removeTag(context, parseItemId(id), tag) + const result = services.tags.removeTag(parseItemId(id), tag) if (jsonMode) { printJson({ ok: true, @@ -977,45 +888,6 @@ tagCommand }) }) -function markItemStatus( - status: Exclude, - itemId: number, -): { itemId: number; status: ItemStatus } { - const dbPath = resolveDbPath(program.opts().dbPath as string) - - return withReadyDb(dbPath, (db) => { - const timestamp = new Date(nowMs()) - const update = - status === "read" - ? db - .update(schema.items) - .set({ - status: "read", - readAt: timestamp, - archivedAt: null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - : db - .update(schema.items) - .set({ - status: "unread", - readAt: null, - archivedAt: null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - - if (Number(update.changes) === 0) { - throw new CliError(`Item ${itemId} not found.`, "NOT_FOUND", 3) - } - - return { itemId, status } - }) -} - const markCommand = program.command("mark").description("Mark item states") markCommand.addHelpText( @@ -1033,20 +905,23 @@ markCommand .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) runDbAction(jsonMode, () => { const itemId = parseItemId(id) - const result = markItemStatus("read", itemId) + const result = services.status.markRead(itemId) if (jsonMode) { printJson({ ok: true, - item_id: result.itemId, - action: "mark_read", - status: result.status, + ...result, }) return } - process.stdout.write(`marked #${result.itemId} as read\n`) + process.stdout.write(`marked #${result.item_id} as read\n`) }) }) @@ -1056,20 +931,23 @@ markCommand .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) runDbAction(jsonMode, () => { const itemId = parseItemId(id) - const result = markItemStatus("unread", itemId) + const result = services.status.markUnread(itemId) if (jsonMode) { printJson({ ok: true, - item_id: result.itemId, - action: "mark_unread", - status: result.status, + ...result, }) return } - process.stdout.write(`marked #${result.itemId} as unread\n`) + process.stdout.write(`marked #${result.item_id} as unread\n`) }) }) @@ -1089,10 +967,11 @@ jobsCommand dbPath: resolveDbPath(program.opts().dbPath as string), migrationsDir: resolveMigrationsDir(), } + const services = createCoreServices(context) const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) if (options.once) { - const processed = await runTtsWorkerOnce(context, { audioDir }) + const processed = await services.ttsJobs.runTtsWorkerOnce({ audioDir }) if (jsonMode) { printJson({ ok: true, @@ -1111,7 +990,7 @@ jobsCommand return } - const worker = startTtsWorker(context, { + const worker = services.ttsJobs.startTtsWorker({ pollMs: options.pollMs, audioDir, }) @@ -1194,19 +1073,22 @@ program .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) runDbAction(jsonMode, () => { const itemId = parseItemId(id) - const result = markItemStatus("read", itemId) + const result = services.status.markRead(itemId) if (jsonMode) { printJson({ ok: true, - item_id: result.itemId, - action: "mark_read", - status: result.status, + ...result, }) return } - process.stdout.write(`marked #${result.itemId} as read\n`) + process.stdout.write(`marked #${result.item_id} as read\n`) }) }) @@ -1216,19 +1098,22 @@ program .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const services = createCoreServices(context) runDbAction(jsonMode, () => { const itemId = parseItemId(id) - const result = markItemStatus("unread", itemId) + const result = services.status.markUnread(itemId) if (jsonMode) { printJson({ ok: true, - item_id: result.itemId, - action: "mark_unread", - status: result.status, + ...result, }) return } - process.stdout.write(`marked #${result.itemId} as unread\n`) + process.stdout.write(`marked #${result.item_id} as unread\n`) }) }) diff --git a/apps/cli/test/integration.test.ts b/apps/cli/test/integration.test.ts index a3614b0..bc47424 100644 --- a/apps/cli/test/integration.test.ts +++ b/apps/cli/test/integration.test.ts @@ -626,6 +626,37 @@ integrationSuite(integrationTitle, () => { } }) + it("keeps `stash list --json` item shape stable", () => { + const { dbPath, cleanup } = createTempDb() + try { + seedSavedItem(dbPath) + + const list = runJson(["list"], { dbPath }) + expect(list.ok).toBe(true) + expect(list.items.length).toBe(1) + + const first = list.items[0] as unknown as Record + expect(Object.keys(first).sort()).toEqual([ + "archived_at", + "created_at", + "domain", + "id", + "is_starred", + "read_at", + "status", + "tags", + "title", + "updated_at", + "url", + ]) + expect(first.thumbnail_url).toBeUndefined() + expect(first.has_extracted_content).toBeUndefined() + expect(first.tts_audio).toBeUndefined() + } finally { + cleanup() + } + }) + it("lists tags and keeps add/rm idempotent", () => { const { dbPath, cleanup } = createTempDb() try { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7e1b51b..d3b5af8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -11,4 +11,5 @@ export * from "./features/tts/doctor.js" export * from "./features/tts/jobs.js" export * from "./features/tts/service.js" export * as paths from "./lib/paths.js" +export * from "./services/index.js" export * from "./types.js" diff --git a/packages/core/src/services/contracts.ts b/packages/core/src/services/contracts.ts new file mode 100644 index 0000000..1aa4f9d --- /dev/null +++ b/packages/core/src/services/contracts.ts @@ -0,0 +1,92 @@ +import type { AutoTagsDoctorReport } from "../features/auto-tags/types.js" +import type { + EnqueueTtsJobInput, + EnqueueTtsJobResult, + TtsWorkerHandle, + TtsWorkerOptions, +} from "../features/tts/jobs.js" +import type { TtsDoctorReport } from "../features/tts/doctor.js" +import type { + ExtractItemOptions, + ExtractItemResult, + ListItemsInput, + ListItemsResult, + SaveItemInput, + SaveItemResult, + TagsListInput, + TagsListResult, + TtsJob, +} from "../types.js" + +export type TagAddResult = { + item_id: number + tag: string + added: boolean +} + +export type TagRemoveResult = { + item_id: number + tag: string + removed: boolean +} + +export type MarkReadResult = { + item_id: number + action: "mark_read" + status: "read" +} + +export type MarkUnreadResult = { + item_id: number + action: "mark_unread" + status: "unread" +} + +export interface ItemsService { + saveItem(input: SaveItemInput): Promise + listItems(input: ListItemsInput): ListItemsResult + getItem(itemId: number): SaveItemResult["item"] | undefined +} + +export interface ExtractService { + extractItem(itemId: number, options?: ExtractItemOptions): Promise +} + +export interface TagsService { + listTags(input: TagsListInput): TagsListResult + addTag(itemId: number, tag: string): TagAddResult + removeTag(itemId: number, tag: string): TagRemoveResult +} + +export interface StatusService { + markRead(itemId: number): MarkReadResult + markUnread(itemId: number): MarkUnreadResult +} + +export interface TtsJobsService { + enqueueTtsJob(input: EnqueueTtsJobInput): EnqueueTtsJobResult + getTtsJob(jobId: number): TtsJob + listTtsJobsForItem(itemId: number, limit?: number, offset?: number): TtsJob[] + waitForTtsJob(jobId: number, options?: { pollMs?: number; timeoutMs?: number }): Promise + startTtsWorker(options?: TtsWorkerOptions): TtsWorkerHandle + runTtsWorkerOnce(options?: { audioDir?: string }): Promise +} + +export interface TtsDoctorService { + inspectCoquiTtsHealth(): TtsDoctorReport +} + +export interface AutoTagsDoctorService { + inspectAutoTagsHealth(): AutoTagsDoctorReport +} + +export interface DoctorService extends TtsDoctorService, AutoTagsDoctorService {} + +export interface CoreServices { + items: ItemsService + extract: ExtractService + tags: TagsService + status: StatusService + ttsJobs: TtsJobsService + doctor: DoctorService +} diff --git a/packages/core/src/services/create-core-services.ts b/packages/core/src/services/create-core-services.ts new file mode 100644 index 0000000..ab6c792 --- /dev/null +++ b/packages/core/src/services/create-core-services.ts @@ -0,0 +1,51 @@ +import { inspectAutoTagsHealth } from "../features/auto-tags/doctor.js" +import { extractItem } from "../features/extract/service.js" +import { getItem, listItems, saveItem } from "../features/items/service.js" +import { markRead, markUnread } from "../features/status/service.js" +import { addTag, listTags, removeTag } from "../features/tags/service.js" +import { inspectCoquiTtsHealth } from "../features/tts/doctor.js" +import { + enqueueTtsJob, + getTtsJob, + listTtsJobsForItem, + runTtsWorkerOnce, + startTtsWorker, + waitForTtsJob, +} from "../features/tts/jobs.js" +import type { OperationContext } from "../types.js" +import type { CoreServices } from "./contracts.js" + +export function createCoreServices(context: OperationContext): CoreServices { + return { + items: { + saveItem: async (input) => await saveItem(context, input), + listItems: (input) => listItems(context, input), + getItem: (itemId) => getItem(context, itemId), + }, + extract: { + extractItem: async (itemId, options = {}) => await extractItem(context, itemId, options), + }, + tags: { + listTags: (input) => listTags(context, input), + addTag: (itemId, tag) => addTag(context, itemId, tag), + removeTag: (itemId, tag) => removeTag(context, itemId, tag), + }, + status: { + markRead: (itemId) => markRead(context, itemId), + markUnread: (itemId) => markUnread(context, itemId), + }, + ttsJobs: { + enqueueTtsJob: (input) => enqueueTtsJob(context, input), + getTtsJob: (jobId) => getTtsJob(context, jobId), + listTtsJobsForItem: (itemId, limit, offset) => + listTtsJobsForItem(context, itemId, limit, offset), + waitForTtsJob: async (jobId, options) => await waitForTtsJob(context, jobId, options), + startTtsWorker: (options) => startTtsWorker(context, options), + runTtsWorkerOnce: async (options = {}) => await runTtsWorkerOnce(context, options), + }, + doctor: { + inspectCoquiTtsHealth: () => inspectCoquiTtsHealth(), + inspectAutoTagsHealth: () => inspectAutoTagsHealth(), + }, + } +} diff --git a/packages/core/src/services/index.ts b/packages/core/src/services/index.ts new file mode 100644 index 0000000..f361ec9 --- /dev/null +++ b/packages/core/src/services/index.ts @@ -0,0 +1,2 @@ +export * from "./contracts.js" +export * from "./create-core-services.js" diff --git a/packages/core/test/core-services.test.ts b/packages/core/test/core-services.test.ts new file mode 100644 index 0000000..fbbaac4 --- /dev/null +++ b/packages/core/test/core-services.test.ts @@ -0,0 +1,184 @@ +import { afterEach, describe, expect, it, vi } from "vitest" + +import * as autoTagsDoctorModule from "../src/features/auto-tags/doctor.js" +import * as extractModule from "../src/features/extract/service.js" +import * as itemsModule from "../src/features/items/service.js" +import * as statusModule from "../src/features/status/service.js" +import * as tagsModule from "../src/features/tags/service.js" +import * as ttsDoctorModule from "../src/features/tts/doctor.js" +import * as ttsJobsModule from "../src/features/tts/jobs.js" +import { createCoreServices } from "../src/services/create-core-services.js" +import type { TtsJob } from "../src/types.js" + +afterEach(() => { + vi.restoreAllMocks() +}) + +const context = { + dbPath: "/tmp/stash-test.db", + migrationsDir: "/tmp/stash-migrations", +} + +function buildTtsJob(id: number): TtsJob { + return { + id, + item_id: 1, + status: "queued", + voice: "voice", + format: "mp3", + error_code: null, + error_message: null, + output_file_name: null, + created_at: new Date(0).toISOString(), + started_at: null, + finished_at: null, + updated_at: new Date(0).toISOString(), + } +} + +describe("createCoreServices", () => { + it("delegates all service methods to existing feature functions with bound context", async () => { + const saveSpy = vi.spyOn(itemsModule, "saveItem").mockResolvedValue({ + created: true, + item: {} as never, + }) + const listSpy = vi.spyOn(itemsModule, "listItems").mockReturnValue({ + items: [], + paging: { limit: 20, offset: 0, returned: 0 }, + }) + const getItemSpy = vi.spyOn(itemsModule, "getItem").mockReturnValue(undefined) + + const extractSpy = vi.spyOn(extractModule, "extractItem").mockResolvedValue({ + item_id: 1, + title_extracted: null, + title_updated: false, + content_length: 0, + updated_at: new Date(0).toISOString(), + }) + + const listTagsSpy = vi.spyOn(tagsModule, "listTags").mockReturnValue({ + tags: [], + paging: { limit: 50, offset: 0, returned: 0 }, + }) + const addTagSpy = vi.spyOn(tagsModule, "addTag").mockReturnValue({ + item_id: 1, + tag: "ai", + added: true, + }) + const removeTagSpy = vi.spyOn(tagsModule, "removeTag").mockReturnValue({ + item_id: 1, + tag: "ai", + removed: true, + }) + + const markReadSpy = vi.spyOn(statusModule, "markRead").mockReturnValue({ + item_id: 1, + action: "mark_read", + status: "read", + }) + const markUnreadSpy = vi.spyOn(statusModule, "markUnread").mockReturnValue({ + item_id: 1, + action: "mark_unread", + status: "unread", + }) + + const enqueueSpy = vi.spyOn(ttsJobsModule, "enqueueTtsJob").mockReturnValue({ + created: true, + poll_interval_ms: 1500, + job: buildTtsJob(10), + }) + const getJobSpy = vi.spyOn(ttsJobsModule, "getTtsJob").mockReturnValue(buildTtsJob(10)) + const listJobsSpy = vi.spyOn(ttsJobsModule, "listTtsJobsForItem").mockReturnValue([]) + const waitSpy = vi.spyOn(ttsJobsModule, "waitForTtsJob").mockResolvedValue({ + ...buildTtsJob(10), + status: "succeeded", + }) + const workerHandle = { + stop: async (): Promise => {}, + } + const startWorkerSpy = vi + .spyOn(ttsJobsModule, "startTtsWorker") + .mockReturnValue(workerHandle) + const runOnceSpy = vi.spyOn(ttsJobsModule, "runTtsWorkerOnce").mockResolvedValue(null) + + const ttsDoctorSpy = vi + .spyOn(ttsDoctorModule, "inspectCoquiTtsHealth") + .mockReturnValue({ + provider: "coqui", + healthy: true, + checks: [], + coqui_cli_features: { + supports_text_file: true, + supports_progress_bar: true, + }, + invocation_strategy: "text_file_then_fallback_text", + }) + const autoTagsDoctorSpy = vi + .spyOn(autoTagsDoctorModule, "inspectAutoTagsHealth") + .mockReturnValue({ + backend: "rule", + healthy: true, + model: "rule", + helper_path: "/tmp/helper.py", + python_path: null, + checks: [], + }) + + const services = createCoreServices(context) + + const saveInput = { url: "https://example.com" } + const listInput = { limit: 5, offset: 0 } + const extractOptions = { force: true } + const listTagsInput = { limit: 10, offset: 1 } + const enqueueInput = { itemId: 1, format: "mp3" as const } + const waitOptions = { pollMs: 500 } + const startWorkerOptions = { pollMs: 1500 } + const runOnceOptions = { audioDir: "/tmp/audio" } + + await services.items.saveItem(saveInput) + services.items.listItems(listInput) + services.items.getItem(1) + + await services.extract.extractItem(1, extractOptions) + + services.tags.listTags(listTagsInput) + services.tags.addTag(1, "ai") + services.tags.removeTag(1, "ai") + + services.status.markRead(1) + services.status.markUnread(1) + + services.ttsJobs.enqueueTtsJob(enqueueInput) + services.ttsJobs.getTtsJob(10) + services.ttsJobs.listTtsJobsForItem(1, 10, 0) + await services.ttsJobs.waitForTtsJob(10, waitOptions) + services.ttsJobs.startTtsWorker(startWorkerOptions) + await services.ttsJobs.runTtsWorkerOnce(runOnceOptions) + + services.doctor.inspectCoquiTtsHealth() + services.doctor.inspectAutoTagsHealth() + + expect(saveSpy).toHaveBeenCalledWith(context, saveInput) + expect(listSpy).toHaveBeenCalledWith(context, listInput) + expect(getItemSpy).toHaveBeenCalledWith(context, 1) + + expect(extractSpy).toHaveBeenCalledWith(context, 1, extractOptions) + + expect(listTagsSpy).toHaveBeenCalledWith(context, listTagsInput) + expect(addTagSpy).toHaveBeenCalledWith(context, 1, "ai") + expect(removeTagSpy).toHaveBeenCalledWith(context, 1, "ai") + + expect(markReadSpy).toHaveBeenCalledWith(context, 1) + expect(markUnreadSpy).toHaveBeenCalledWith(context, 1) + + expect(enqueueSpy).toHaveBeenCalledWith(context, enqueueInput) + expect(getJobSpy).toHaveBeenCalledWith(context, 10) + expect(listJobsSpy).toHaveBeenCalledWith(context, 1, 10, 0) + expect(waitSpy).toHaveBeenCalledWith(context, 10, waitOptions) + expect(startWorkerSpy).toHaveBeenCalledWith(context, startWorkerOptions) + expect(runOnceSpy).toHaveBeenCalledWith(context, runOnceOptions) + + expect(ttsDoctorSpy).toHaveBeenCalled() + expect(autoTagsDoctorSpy).toHaveBeenCalled() + }) +}) From 6655162d45b0845e1fe63bf363bb42478131e0d5 Mon Sep 17 00:00:00 2001 From: Serg Dort Date: Wed, 4 Mar 2026 22:16:12 +0000 Subject: [PATCH 2/3] refactor: migrate to @stash/core package imports --- .agents/notes.md | 6 +-- AGENTS.md | 5 +- apps/api/package.json | 8 ++- apps/api/src/app/create-api-app.ts | 2 +- apps/api/src/app/error-handler.ts | 2 +- apps/api/src/app/server.ts | 3 +- apps/api/src/features/extract/routes.ts | 2 +- apps/api/src/features/inbox/dto.ts | 6 +-- apps/api/src/features/inbox/routes.ts | 2 +- apps/api/src/features/item/routes.ts | 3 +- apps/api/src/features/save/dto.ts | 3 +- apps/api/src/features/save/routes.ts | 2 +- apps/api/src/features/status/dto.ts | 2 +- apps/api/src/features/status/routes.ts | 2 +- apps/api/src/features/tags/dto.ts | 2 +- apps/api/src/features/tags/routes.ts | 2 +- apps/api/src/features/tts/dto.ts | 2 +- apps/api/src/features/tts/routes.ts | 3 +- apps/api/src/shared/validation/parse.ts | 2 +- apps/api/tsconfig.build.json | 9 ++++ apps/cli/package.json | 6 +++ apps/cli/src/cli.ts | 65 ++++++++++++++++++++++--- apps/cli/test/integration.test.ts | 4 +- apps/cli/tsconfig.build.json | 9 ++++ apps/web/vite.config.ts | 4 ++ docs/CLI_REFERENCE.md | 4 +- package.json | 14 +++--- packages/core/package.json | 13 ++++- packages/core/src/index.ts | 2 + packages/core/tsconfig.build.json | 9 ++++ pnpm-lock.yaml | 12 ++++- 31 files changed, 159 insertions(+), 51 deletions(-) create mode 100644 apps/api/tsconfig.build.json create mode 100644 apps/cli/tsconfig.build.json create mode 100644 packages/core/tsconfig.build.json diff --git a/.agents/notes.md b/.agents/notes.md index 37b49e7..249d058 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -1,6 +1,6 @@ -[1] In this sandbox, dependency installs can fail for two environment reasons: `pnpm install` may require `CI=true` in non-TTY mode, and external registry resolution (`registry.npmjs.org`) may be unavailable, which blocks lockfile/dependency updates. +[2] In this sandbox, dependency installs can fail for two environment reasons: `pnpm install` may require `CI=true` in non-TTY mode (and sometimes `--no-frozen-lockfile` when package.json changed), and external registry resolution (`registry.npmjs.org`) may be unavailable, which blocks lockfile/dependency updates. -[2] In this sandbox, integration tests that bind a local HTTP listener (e.g., `startWebServer` on `127.0.0.1`) can fail with `listen EPERM`; validate those tests in a less restricted environment. +[3] In this sandbox, integration tests or dev servers that bind a local HTTP listener (e.g., `startWebServer`/Vite on `127.0.0.1`) can fail with `listen EPERM`; validate those flows in a less restricted environment. [0] If `pnpm add` fails with `ERR_PNPM_UNEXPECTED_STORE`, rerun with `--store-dir` pointing to the store path used by current `node_modules` (for this repo: `/Users/sergiishulga/Library/pnpm/store/v10`). @@ -36,7 +36,7 @@ [0] When adding a new DB migration, update CLI integration assertions that hard-code `db doctor` migration counts (e.g., expected `applied_count`) to prevent false negatives. [0] In sandboxed tests, default `~/.stash/audio` can be unwritable; set `STASH_AUDIO_DIR` to a temp path for worker-based TTS tests/commands. [0] Coqui CLI variants differ: some support `--text_file`, others only `--text`. Keep provider invocation backward compatible by retrying with inline `--text` when `--text_file`/`--progress_bar` is rejected. -[0] CLI integration tests execute `dist/apps/cli/src/cli.js`; always run `pnpm run build` after source edits and before targeted integration runs, otherwise tests can fail against stale command behavior. +[0] CLI integration tests execute `apps/cli/dist/cli.js`; always run `pnpm run build` after source edits and before targeted integration runs, otherwise tests can fail against stale command behavior. [0] With VS Code `node-terminal` launch running `pnpm run dev -- web`, the debugger UI can show wrapper-process disconnect messages (`Debugger attached` / `Waiting for the debugger to disconnect...`) even while the actual `stash web` child process is still running; verify via `/api/health` and use an attach config for breakpoints in the real process. [0] `scripts/with-env.mjs` should forward `SIGINT`/`SIGTERM`/`SIGHUP` to its spawned child; otherwise VS Code stop/terminate can kill the wrapper and orphan long-running child processes (e.g., `stash web`) on their ports. [0] For X/Twitter pages, `page.content()` can include the `