import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; type FeatureFlagRecord = { id: string; name: string; rules: unknown; }; const dbMock = { featureFlag: { findFirst: vi.fn<() => Promise>(), update: vi.fn(), }, featureFlagAudit: { create: vi.fn(), }, $transaction: vi.fn(), }; const broadcastFlagInvalidationMock = vi.fn(); const evaluateRuleMock = vi.fn(); vi.mock("@hivegrid/db/client.server", () => ({ getDbClient: () => dbMock, })); vi.mock("@hivegrid/feature-flags", () => ({ evaluateRule: (...args: unknown[]) => evaluateRuleMock(...args), })); vi.mock("consola", () => ({ default: { error: vi.fn(), success: vi.fn(), }, })); vi.mock("./invalidate.js", () => ({ broadcastFlagInvalidation: (...args: unknown[]) => broadcastFlagInvalidationMock(...args), })); import consola from "consola"; import { featureFlagsSetRulesCommand } from "./set-rules.js"; const consoleMock = vi.mocked(consola); let tempDir: string; function writeRulesFile(contents: string): string { const path = join(tempDir, `rules-${crypto.randomUUID()}.json`); writeFileSync(path, contents, "utf-8"); return path; } describe("feature flag set-rules command", () => { beforeEach(() => { tempDir = mkdtempSync(join(tmpdir(), "hivegrid-cli-flags-")); vi.clearAllMocks(); process.exitCode = undefined; dbMock.$transaction.mockImplementation(async (callback: (transaction: typeof dbMock) => Promise) => callback(dbMock)); broadcastFlagInvalidationMock.mockResolvedValue(undefined); }); afterEach(() => { rmSync(tempDir, { force: true, recursive: true }); }); it("rejects invalid JSON before opening a DB client", async () => { const file = writeRulesFile("{"); await featureFlagsSetRulesCommand.run?.({ args: { name: "billing.beta", file } } as never); expect(consoleMock.error).toHaveBeenCalledWith("Failed to parse rules JSON:", expect.any(SyntaxError)); expect(process.exitCode).toBe(1); expect(evaluateRuleMock).not.toHaveBeenCalled(); expect(dbMock.featureFlag.findFirst).not.toHaveBeenCalled(); }); it("rejects rule trees that do not evaluate cleanly", async () => { const file = writeRulesFile('{"all":[{"attribute":"plan","operator":"eq","value":"pro"}]}'); const error = new Error("bad operator"); evaluateRuleMock.mockImplementationOnce(() => { throw error; }); await featureFlagsSetRulesCommand.run?.({ args: { name: "billing.beta", file } } as never); expect(evaluateRuleMock).toHaveBeenCalledWith( { all: [{ attribute: "plan", operator: "eq", value: "pro" }] }, { flagName: "billing.beta", tenantId: "probe", userId: "probe" } ); expect(consoleMock.error).toHaveBeenCalledWith("Rule tree did not evaluate cleanly:", error); expect(process.exitCode).toBe(1); expect(dbMock.featureFlag.findFirst).not.toHaveBeenCalled(); }); it("reports missing flags after validating the replacement rules", async () => { const file = writeRulesFile('{"all":[]}'); dbMock.featureFlag.findFirst.mockResolvedValueOnce(null); await featureFlagsSetRulesCommand.run?.({ args: { name: "billing.beta", file } } as never); expect(dbMock.featureFlag.findFirst).toHaveBeenCalledWith({ where: { name: "billing.beta" } }); expect(consoleMock.error).toHaveBeenCalledWith('Flag "billing.beta" not found.'); expect(process.exitCode).toBe(1); expect(dbMock.$transaction).not.toHaveBeenCalled(); expect(broadcastFlagInvalidationMock).not.toHaveBeenCalled(); }); it("treats blank rule files as clearing rules and skips rule evaluation", async () => { const file = writeRulesFile(" \n"); dbMock.featureFlag.findFirst.mockResolvedValueOnce({ id: "flag_1", name: "billing.beta", rules: { all: [] }, }); await featureFlagsSetRulesCommand.run?.({ args: { name: "billing.beta", file } } as never); expect(evaluateRuleMock).not.toHaveBeenCalled(); expect(dbMock.featureFlag.update).toHaveBeenCalledWith({ where: { id: "flag_1" }, data: { rules: null }, }); expect(dbMock.featureFlagAudit.create).toHaveBeenCalledWith({ data: { flagId: "flag_1", actorUserId: null, action: "update", oldValue: { rules: { all: [] } }, newValue: { rules: null }, }, }); expect(dbMock.$transaction).toHaveBeenCalledWith(expect.any(Function)); expect(broadcastFlagInvalidationMock).toHaveBeenCalledWith("billing.beta"); expect(consoleMock.success).toHaveBeenCalledWith('Rules for "billing.beta" updated.'); }); });