181 lines
9.1 KiB
TypeScript
181 lines
9.1 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { runCli } from "../runner.js"
|
|
|
|
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
|
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
|
const oldFetch = globalThis.fetch
|
|
let dir: string
|
|
let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] }
|
|
let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }>
|
|
let failReadback: boolean
|
|
let failReadbackStatus: number
|
|
const original = structuredClone(document)
|
|
|
|
beforeEach(() => {
|
|
dir = mkdtempSync(join(tmpdir(), "seal-documents-cli-"))
|
|
const enterprises = join(dir, "enterprises")
|
|
mkdirSync(enterprises)
|
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
|
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
|
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
|
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
|
writeFileSync(join(enterprises, "document-cli-test.json"), JSON.stringify({
|
|
id: "document-cli-test", name: "Document Test", environment: "test",
|
|
seal: { url: "https://documents.example.test" },
|
|
source: { type: "seal", token: "test-token", sealUrl: "https://documents.example.test", staffId: "fixture" }
|
|
}))
|
|
document = structuredClone(original)
|
|
requests = []
|
|
failReadback = false
|
|
failReadbackStatus = 400
|
|
let writeCount = 0
|
|
let readbackWrites = 0
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const request = new Request(input, init)
|
|
const url = new URL(request.url)
|
|
const method = request.method
|
|
const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined
|
|
requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body })
|
|
if (failReadback && method === "GET" && writeCount > readbackWrites) {
|
|
readbackWrites = writeCount
|
|
return Response.json({ error: "offline" }, { status: failReadbackStatus })
|
|
}
|
|
if (method === "PATCH") {
|
|
writeCount++
|
|
document = { ...document, ...(body?.attributes as object) }
|
|
}
|
|
if (method === "POST") document = { ...document, ...body }
|
|
return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document })
|
|
}) as typeof fetch
|
|
})
|
|
|
|
afterEach(() => {
|
|
for (const key of envKeys) {
|
|
if (oldEnv[key] === undefined) delete process.env[key]
|
|
else process.env[key] = oldEnv[key]
|
|
}
|
|
globalThis.fetch = oldFetch
|
|
rmSync(dir, { recursive: true, force: true })
|
|
})
|
|
|
|
function cli(...argv: string[]) { return runCli(["documents", ...argv, "--corp", "document-cli-test"]) }
|
|
const writes = () => requests.filter(request => request.method !== "GET")
|
|
|
|
describe("documents CLI", () => {
|
|
test("exports body plus baseline, previews edits, and updates only body with JSON receipts", async () => {
|
|
const out = join(dir, "body.txt")
|
|
const exported = await cli("get", "doc-1", "--out", out)
|
|
expect(exported.exitCode).toBe(0)
|
|
expect(JSON.parse(exported.stdout)).toMatchObject({ contentFile: out, contentFormat: "raw" })
|
|
expect(readFileSync(out, "utf8")).toBe(original.content)
|
|
writeFileSync(out, "edited content")
|
|
const preview = await cli("update", "doc-1", "--content-file", out, "--dry-run", "--yes")
|
|
expect(preview.exitCode).toBe(0)
|
|
expect(JSON.parse(preview.stdout)).toMatchObject({ preview: true, executed: false, baselineAvailable: true, changedFields: ["content"] })
|
|
expect(writes()).toHaveLength(0)
|
|
const result = await cli("update", "doc-1", "--content-file", out, "--yes")
|
|
expect(result.exitCode).toBe(0)
|
|
const payload = JSON.parse(result.stdout)
|
|
expect(payload).toMatchObject({ verified: true, executed: true, baselineAvailable: true })
|
|
expect(JSON.parse(readFileSync(payload.snapshotFile, "utf8")).document.content).toBe(original.content)
|
|
expect(writes()).toHaveLength(1)
|
|
expect(writes()[0]?.body).toEqual({ attributes: { content: "edited content" } })
|
|
expect(document.title).toBe(original.title)
|
|
expect(document.status).toBe("published")
|
|
})
|
|
|
|
test("plain get and output-file still produce whole document JSON", async () => {
|
|
expect(JSON.parse((await cli("get", "doc-1")).stdout)).toMatchObject(original)
|
|
const path = join(dir, "document.json")
|
|
const result = await cli("get", "doc-1", "--output-file", path)
|
|
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
|
|
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject(original)
|
|
})
|
|
|
|
test("lightweight list and explicit fields do not request per-document details", async () => {
|
|
const summary = await cli("list", "--summary", "--limit", "2", "--offset", "1")
|
|
expect(summary.exitCode).toBe(0)
|
|
expect(JSON.parse(summary.stdout).articles[0]).not.toHaveProperty("content")
|
|
expect(new URLSearchParams(requests[0]?.query).get("limit")).toBe("2")
|
|
expect(new URLSearchParams(requests[0]?.query).get("offset")).toBe("1")
|
|
const fields = await cli("list", "--summary", "--fields", "id,title")
|
|
expect(JSON.parse(fields.stdout)).toEqual({ total: 115, articles: [{ id: "doc-1", title: original.title }] })
|
|
expect(requests.every(request => request.path === "/api/v1/knowledge/articles")).toBe(true)
|
|
expect((await cli("list", "--fields", "typo")).exitCode).toBe(2)
|
|
})
|
|
|
|
test("all write commands require confirmation and all previews remain read-only", async () => {
|
|
const variants = [
|
|
["create", "--title", "new", "--purpose", "test", "--content", "new"],
|
|
["update", "doc-1", "--content", "new"],
|
|
["delete", "doc-1"]
|
|
]
|
|
for (const argv of variants) {
|
|
expect((await cli(...argv)).exitCode).toBe(10)
|
|
for (const flag of ["--dry-run", "--dryRun"]) {
|
|
const result = await cli(...argv, flag, "--confirm")
|
|
expect(result.exitCode).toBe(0)
|
|
expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, executed: false })
|
|
}
|
|
}
|
|
expect(writes()).toHaveLength(0)
|
|
expect(existsSync(join(dir, "document-history"))).toBe(false)
|
|
})
|
|
|
|
test("conflicts and failed readback return JSON state with nonzero exit codes", async () => {
|
|
const path = join(dir, "body")
|
|
await cli("get", "doc-1", "--out", path)
|
|
writeFileSync(path, "my edit")
|
|
document.content = "remote edit"
|
|
const conflict = await cli("update", "doc-1", "--content-file", path, "--yes")
|
|
expect(conflict.exitCode).toBe(1)
|
|
expect(JSON.parse(conflict.stdout)).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false })
|
|
expect(writes()).toHaveLength(0)
|
|
failReadback = true
|
|
const uncertain = await cli("update", "doc-1", "--content", "new", "--yes")
|
|
expect(uncertain.exitCode).toBe(1)
|
|
expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
|
|
expect(uncertain.stderr).toContain("Next action:")
|
|
|
|
failReadbackStatus = 401
|
|
const authFailed = await cli("update", "doc-1", "--content", "newer", "--yes")
|
|
expect(authFailed.exitCode).toBe(11)
|
|
expect(JSON.parse(authFailed.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
|
|
})
|
|
|
|
test("unsupported format and path/input conflicts fail before requests or file changes", async () => {
|
|
const path = join(dir, "body")
|
|
writeFileSync(path, "keep")
|
|
for (const argv of [
|
|
["get", "doc-1", "--out", path, "--content-format", "markdown"],
|
|
["get", "doc-1", "--out", path, "--output-file", path],
|
|
["update", "doc-1", "--content-file", path, "--content", "other", "--yes"],
|
|
["update", "doc-1", "--content-file", path, "--output-file", path, "--yes"],
|
|
["update", "doc-1", "--content-file", path, "--output-file", `${path}.seal-use.json`, "--yes"]
|
|
]) expect((await cli(...argv)).exitCode).toBe(2)
|
|
expect(readFileSync(path, "utf8")).toBe("keep")
|
|
expect(requests).toHaveLength(0)
|
|
})
|
|
|
|
test("invalid UTF-8, missing file and damaged baseline fail with exit 13 and zero writes", async () => {
|
|
const path = join(dir, "body")
|
|
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
|
writeFileSync(path, Buffer.from([0xff]))
|
|
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
|
writeFileSync(path, "new")
|
|
writeFileSync(`${path}.seal-use.json`, "{}")
|
|
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
|
|
expect(writes()).toHaveLength(0)
|
|
})
|
|
|
|
test("legacy raw input is supported and discloses absence of an editing baseline", async () => {
|
|
const result = await cli("update", "doc-1", "--content", "new", "--confirm")
|
|
expect(result.exitCode).toBe(0)
|
|
expect(JSON.parse(result.stdout)).toMatchObject({ verified: true, baselineAvailable: false })
|
|
expect(result.stderr).toContain("baselineAvailable:false")
|
|
})
|
|
})
|