Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -1,7 +1,7 @@
|
||||
# @toolctrl/cli
|
||||
# @hivegrid/cli
|
||||
|
||||
Operator CLI for the ToolCTRL boilerplate. Currently ships the `backup` family
|
||||
of subcommands. The entrypoint is `bin/toolctrl-cli.mjs`, wired up via
|
||||
Operator CLI for HiveGrid. Currently ships the `backup` family
|
||||
of subcommands. The entrypoint is `bin/hivegrid-cli.mjs`, wired up via
|
||||
[citty](https://github.com/unjs/citty) for consistent subcommand handling.
|
||||
|
||||
## Subcommands
|
||||
@@ -36,6 +36,6 @@ isolated from the application bucket:
|
||||
## Development
|
||||
|
||||
```sh
|
||||
pnpm --filter @toolctrl/cli test
|
||||
pnpm --filter @toolctrl/cli typecheck
|
||||
pnpm --filter @hivegrid/cli test
|
||||
pnpm --filter @hivegrid/cli typecheck
|
||||
```
|
||||
Regular → Executable
+1
-1
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
// Thin shim so the CLI is callable as `toolctrl-cli`.
|
||||
// Thin shim so the CLI is callable as `hivegrid-cli`.
|
||||
// The actual command tree lives in ../src/index.ts and is loaded via tsx in dev,
|
||||
// or via the compiled output once the build pipeline produces dist/index.js.
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "@toolctrl/cli",
|
||||
"name": "@hivegrid/cli",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -9,7 +9,7 @@
|
||||
"./backup": "./src/commands/backup/index.ts"
|
||||
},
|
||||
"bin": {
|
||||
"toolctrl-cli": "./bin/toolctrl-cli.mjs"
|
||||
"hivegrid-cli": "./bin/hivegrid-cli.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "pnpm run typecheck",
|
||||
@@ -19,13 +19,13 @@
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1048.0",
|
||||
"@aws-sdk/lib-storage": "^3.1048.0",
|
||||
"@toolctrl/db": "workspace:*",
|
||||
"@toolctrl/entitlements": "workspace:*",
|
||||
"@toolctrl/exports": "workspace:*",
|
||||
"@toolctrl/feature-flags": "workspace:*",
|
||||
"@toolctrl/form-widget": "workspace:*",
|
||||
"@toolctrl/plugin-runtime": "workspace:*",
|
||||
"@toolctrl/search": "workspace:*",
|
||||
"@hivegrid/db": "workspace:*",
|
||||
"@hivegrid/entitlements": "workspace:*",
|
||||
"@hivegrid/exports": "workspace:*",
|
||||
"@hivegrid/feature-flags": "workspace:*",
|
||||
"@hivegrid/form-widget": "workspace:*",
|
||||
"@hivegrid/plugin-runtime": "workspace:*",
|
||||
"@hivegrid/search": "workspace:*",
|
||||
"citty": "^0.1.6",
|
||||
"consola": "^3.4.0",
|
||||
"tar": "^7.4.3",
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ describe("scaffold helpers / writeScaffoldFile", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-scaffold-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-scaffold-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Shared helpers for the `toolctrl create …` / `toolctrl add …` scaffolding
|
||||
* Shared helpers for the `hivegrid create …` / `hivegrid add …` scaffolding
|
||||
* generators (Phase 08 / task #60).
|
||||
*
|
||||
* Design goals:
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ describe("add event-type generator", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-event-type-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-event-type-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl add event-type <name>` — scaffold a new EntityWebhook
|
||||
* `hivegrid add event-type <name>` — scaffold a new EntityWebhook
|
||||
* event-type definition (zod schema + example payload + handler stub).
|
||||
*
|
||||
* The workflow engine does not yet expose a single canonical event-type
|
||||
@@ -70,7 +70,7 @@ export async function generateEventType(options: GenerateEventTypeOptions): Prom
|
||||
function renderEventTypeFile({ eventName, typeName }: { eventName: string; typeName: string }): string {
|
||||
return `/**
|
||||
* EntityWebhook event-type: ${eventName}
|
||||
* Generated by toolctrl-cli.
|
||||
* Generated by hivegrid-cli.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ describe("add hook generator", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-hook-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-hook-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -31,7 +31,7 @@ describe("add hook generator", () => {
|
||||
|
||||
it("notes mention the plugin SDK migration path", async () => {
|
||||
const result = await generateHook({ name: "on-foo", repoRoot: tempRoot, dryRun: true });
|
||||
expect(result.notes.join("\n")).toMatch(/@toolctrl\/plugin-sdk/);
|
||||
expect(result.notes.join("\n")).toMatch(/@hivegrid\/plugin-sdk/);
|
||||
});
|
||||
|
||||
it("refuses to overwrite an existing hook", async () => {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* `toolctrl add hook <name>` — scaffold a plugin-hook registration file.
|
||||
* `hivegrid add hook <name>` — scaffold a plugin-hook registration file.
|
||||
*
|
||||
* NOTE: the plugin-system itself (Phase 06) is not yet built. This
|
||||
* generator therefore produces a *stub* with a clear "scaffolding for
|
||||
* future plugin system" header so downstream readers know the API
|
||||
* surface is provisional. Once Phase 06 lands the template will be
|
||||
* upgraded to import the real `@toolctrl/plugin-sdk`.
|
||||
* upgraded to import the real `@hivegrid/plugin-sdk`.
|
||||
*
|
||||
* Refs: docs/improvement-plan/08-mobile-cli-storybook-sdk/cli-scaffolding.md
|
||||
* Refs: docs/improvement-plan/06-plugin-system/audit-docs.md
|
||||
@@ -48,7 +48,7 @@ export async function generateHook(options: GenerateHookOptions): Promise<Scaffo
|
||||
|
||||
result.notes.push(
|
||||
"Phase 06 plugin system is not implemented yet — this hook is a forward-compatible stub.",
|
||||
"Update the import path to @toolctrl/plugin-sdk once Phase 06 ships.",
|
||||
"Update the import path to @hivegrid/plugin-sdk once Phase 06 ships.",
|
||||
);
|
||||
|
||||
return result;
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ describe("add permission generator", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-permission-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-permission-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl add permission <name>` — scaffold a new permission key plus
|
||||
* `hivegrid add permission <name>` — scaffold a new permission key plus
|
||||
* a frontend-mapper stub.
|
||||
*
|
||||
* The canonical permission list lives in
|
||||
@@ -87,7 +87,7 @@ function renderSeedFragment({
|
||||
}): string {
|
||||
return `/**
|
||||
* Permission seed fragment for "${permission}".
|
||||
* Generated by toolctrl-cli.
|
||||
* Generated by hivegrid-cli.
|
||||
*
|
||||
* Paste the constant into the \`defaultPermissionSeeds\` array in
|
||||
* \`packages/db/src/permissions-seed.server.ts\` and add a matching
|
||||
@@ -106,7 +106,7 @@ ${isAdmin ? ' "SuperAdmin",' : ' "SuperUser",\n "Admin",'}
|
||||
function renderMapperFragment({ permission, constName }: { permission: string; constName: string }): string {
|
||||
return `/**
|
||||
* Frontend permission-mapper stub for "${permission}".
|
||||
* Generated by toolctrl-cli.
|
||||
* Generated by hivegrid-cli.
|
||||
*
|
||||
* Wire this into your route loaders via the project's permission
|
||||
* helper (typically apps/web/app/utils/helpers/PermissionsHelper).
|
||||
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
// @vitest-environment node
|
||||
//
|
||||
// Pin to the node environment. When the coverage gate runs this suite from the
|
||||
// repo root, the root vitest.config.ts (environment: "jsdom") is loaded instead
|
||||
// of packages/cli/vitest.config.ts (environment: "node"). Under jsdom, vitest's
|
||||
// module interop for the mocked `node:fs/promises` builtin demands a `default`
|
||||
// export the mock does not provide, so the whole suite fails to load. These are
|
||||
// node CLI commands, so this pragma keeps the environment identical regardless
|
||||
// of the working directory the runner is invoked from.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { AuditPdfEvent } from "@hivegrid/exports/audit-pdf";
|
||||
|
||||
/**
|
||||
* Exercises the citty `run` wrappers of the audit commands — the inline
|
||||
* Prisma wiring (where-building, cursor pagination, chain-event mapping)
|
||||
* that the pure-function tests in verify-chain.test.ts / export-pdf.test.ts
|
||||
* deliberately bypass via injected dependencies.
|
||||
*/
|
||||
|
||||
const findMany = vi.fn<() => Promise<unknown[]>>();
|
||||
const verifyAuditChain = vi.fn();
|
||||
const serializeAuditEventsToPdf = vi.fn<() => Promise<Uint8Array>>();
|
||||
const writeFile = vi.fn<() => Promise<void>>();
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getReadDbClient: () => ({ auditEvent: { findMany } }),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-hash", () => ({
|
||||
verifyAuditChain: (...args: unknown[]) => verifyAuditChain(...(args as [])),
|
||||
}));
|
||||
vi.mock("@hivegrid/exports/audit-pdf", () => ({
|
||||
serializeAuditEventsToPdf: (...args: unknown[]) => serializeAuditEventsToPdf(...(args as [])),
|
||||
}));
|
||||
vi.mock("node:fs/promises", () => ({
|
||||
writeFile: (...args: unknown[]) => writeFile(...(args as [])),
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
log: vi.fn(),
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { auditExportPdfCommand } from "./export-pdf.js";
|
||||
import { auditVerifyChainCommand } from "./verify-chain.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
|
||||
return {
|
||||
id: "audit_1",
|
||||
createdAt: new Date("2026-05-17T00:00:00.000Z"),
|
||||
tenantId: "tenant_1",
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
actorEmail: null,
|
||||
actorIp: null,
|
||||
actorUserAgent: null,
|
||||
action: "widget.created",
|
||||
targetType: "widget",
|
||||
targetId: "widget_1",
|
||||
requestId: null,
|
||||
sourceModule: "crm",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: null,
|
||||
previousHash: null,
|
||||
eventHash: "h1",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("audit verify-chain command wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
findMany.mockResolvedValue([]);
|
||||
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = undefined;
|
||||
});
|
||||
|
||||
it("maps a concrete tenant + date range into the Prisma where clause", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({
|
||||
args: { tenant: "tenant_1", from: "2026-05-01T00:00:00Z", to: "2026-06-01T00:00:00Z" },
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
|
||||
},
|
||||
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
||||
take: 5_000,
|
||||
}),
|
||||
);
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("audit-chain OK — tenant=tenant_1 inspected=1");
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("translates --tenant=__platform__ into a null tenant filter", async () => {
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "__platform__" } } as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
|
||||
});
|
||||
|
||||
it("follows the cursor across pages until a short final page", async () => {
|
||||
const fullPage = Array.from({ length: 5_000 }, (_v, i) => makeEvent({ id: `evt_${i}` }));
|
||||
findMany.mockResolvedValueOnce(fullPage).mockResolvedValueOnce([makeEvent({ id: "evt_last" })]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 5_001, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledTimes(2);
|
||||
// Second page is requested with a skip+cursor anchored on the last id of page one.
|
||||
expect(findMany).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ skip: 1, cursor: { id: "evt_4999" } }),
|
||||
);
|
||||
expect(verifyAuditChain).toHaveBeenCalledWith(
|
||||
expect.arrayContaining([expect.objectContaining({ id: "evt_last" })]),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a broken chain on stderr with a non-zero exit code", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({
|
||||
ok: false,
|
||||
inspected: 1,
|
||||
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
|
||||
});
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
"audit-chain BROKEN — tenant=tenant_1 inspected=1 firstBreakId=audit_1 reason=hash-mismatch",
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it("emits a single JSON object in --json mode", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", json: true } } as never);
|
||||
|
||||
const printed = JSON.parse(String(consoleMock.log.mock.calls[0]?.[0]));
|
||||
expect(printed).toMatchObject({ tenantId: "tenant_1", from: null, to: null, inspected: 1, ok: true });
|
||||
// An intact chain has no firstBreak, so JSON.stringify drops the key entirely.
|
||||
expect(printed).not.toHaveProperty("firstBreak");
|
||||
});
|
||||
|
||||
it("catches an invalid --from value and exits non-zero", async () => {
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", from: "not-a-date" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Invalid --from value "not-a-date"'),
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("catches a database failure and exits non-zero", async () => {
|
||||
findMany.mockRejectedValueOnce(new Error("connection reset"));
|
||||
|
||||
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("connection reset");
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("audit export-pdf command wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
findMany.mockResolvedValue([]);
|
||||
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
|
||||
serializeAuditEventsToPdf.mockResolvedValue(new Uint8Array([1, 2, 3, 4]));
|
||||
writeFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = undefined;
|
||||
});
|
||||
|
||||
it("builds the where filter, renders, and writes the PDF on an intact chain", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
|
||||
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: {
|
||||
tenant: "tenant_1",
|
||||
from: "2026-05-01T00:00:00Z",
|
||||
to: "2026-06-01T00:00:00Z",
|
||||
"regulatory-scope": "gdpr",
|
||||
out: "/tmp/audit.pdf",
|
||||
"generated-by": "Ops",
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
|
||||
regulatoryScope: { hasSome: ["gdpr"] },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: 5_000,
|
||||
}),
|
||||
);
|
||||
expect(serializeAuditEventsToPdf).toHaveBeenCalledTimes(1);
|
||||
expect(writeFile).toHaveBeenCalledWith("/tmp/audit.pdf", new Uint8Array([1, 2, 3, 4]));
|
||||
expect(consoleMock.success).toHaveBeenCalledWith(
|
||||
"audit-pdf written — out=/tmp/audit.pdf rows=1 bytes=4 integrity=ok",
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("maps __platform__ to a null tenant and omits the date range when unset", async () => {
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: { tenant: "__platform__", out: "/tmp/p.pdf" },
|
||||
} as never);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
|
||||
});
|
||||
|
||||
it("flags a broken chain in the log line and exits non-zero", async () => {
|
||||
findMany.mockResolvedValueOnce([makeEvent()]);
|
||||
verifyAuditChain.mockReturnValueOnce({
|
||||
ok: false,
|
||||
inspected: 1,
|
||||
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
|
||||
});
|
||||
|
||||
await auditExportPdfCommand.run?.({
|
||||
args: { tenant: "tenant_1", out: "/tmp/audit.pdf" },
|
||||
} as never);
|
||||
|
||||
expect(writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(consoleMock.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining("audit-pdf written WITH BROKEN CHAIN"),
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects an empty --out before touching the database", async () => {
|
||||
await auditExportPdfCommand.run?.({ args: { tenant: "tenant_1", out: " " } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("Missing --out.");
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
|
||||
import { runAuditExportPdf, type AuditExportPdfDependencies } from "./export-pdf.js";
|
||||
|
||||
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
|
||||
@@ -50,7 +50,7 @@ function makeDeps(opts: {
|
||||
render: async (input) => {
|
||||
state.renderInput = input;
|
||||
// Fake PDF bytes — the renderer is unit-tested separately in
|
||||
// @toolctrl/exports.
|
||||
// @hivegrid/exports.
|
||||
return new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]); // "%PDF-1.7"
|
||||
},
|
||||
writeOutput: async (path, bytes) => {
|
||||
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
|
||||
* `hivegrid audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
|
||||
* --out <path>`
|
||||
*
|
||||
* Renders a tamper-evident PDF compliance report from AuditEvent rows for
|
||||
@@ -7,7 +7,7 @@
|
||||
* `verifyAuditChain` integrity check; the body lists each event in
|
||||
* chronological order with hash + actor + outcome + scope.
|
||||
*
|
||||
* Renders via @react-pdf/renderer through `@toolctrl/exports/audit-pdf`.
|
||||
* Renders via @react-pdf/renderer through `@hivegrid/exports/audit-pdf`.
|
||||
*
|
||||
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
|
||||
*/
|
||||
@@ -15,7 +15,7 @@ import { writeFile } from "node:fs/promises";
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
|
||||
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
|
||||
|
||||
const AUDIT_PDF_QUERY_LIMIT = 5_000;
|
||||
|
||||
@@ -138,9 +138,9 @@ export const auditExportPdfCommand = defineCommand({
|
||||
},
|
||||
async run({ args }) {
|
||||
const [{ getReadDbClient }, { verifyAuditChain }, { serializeAuditEventsToPdf }] = await Promise.all([
|
||||
import("@toolctrl/db/client.server"),
|
||||
import("@toolctrl/db/audit-hash"),
|
||||
import("@toolctrl/exports/audit-pdf"),
|
||||
import("@hivegrid/db/client.server"),
|
||||
import("@hivegrid/db/audit-hash"),
|
||||
import("@hivegrid/exports/audit-pdf"),
|
||||
]);
|
||||
|
||||
const db = getReadDbClient();
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { computeAuditHash, verifyAuditChain } from "@toolctrl/db/audit-hash";
|
||||
import { computeAuditHash, verifyAuditChain } from "@hivegrid/db/audit-hash";
|
||||
import {
|
||||
runAuditVerifyChain,
|
||||
type AuditVerifyChainDependencies,
|
||||
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* `toolctrl audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
|
||||
* `hivegrid audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
|
||||
*
|
||||
* Thin CLI wrapper around `verifyAuditChain` from @toolctrl/db/audit-hash.
|
||||
* Thin CLI wrapper around `verifyAuditChain` from @hivegrid/db/audit-hash.
|
||||
* Loads the per-tenant AuditEvent chain in chronological order, recomputes
|
||||
* each event's eventHash and compares it against the stored value. Exits
|
||||
* 0 on intact chain, non-zero with first-break diagnostics otherwise.
|
||||
@@ -21,7 +21,7 @@
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import type { AuditChainEvent, VerifyAuditChainResult } from "@toolctrl/db/audit-hash";
|
||||
import type { AuditChainEvent, VerifyAuditChainResult } from "@hivegrid/db/audit-hash";
|
||||
|
||||
const AUDIT_VERIFY_BATCH_SIZE = 5_000;
|
||||
|
||||
@@ -37,7 +37,7 @@ export type AuditVerifyChainRow = AuditChainEvent;
|
||||
export type AuditVerifyChainDependencies = {
|
||||
/** Cursor-iterable read of events ordered by createdAt ascending. */
|
||||
readRows: (args: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }) => AsyncIterable<AuditVerifyChainRow>;
|
||||
/** Chain verifier — usually `verifyAuditChain` from @toolctrl/db/audit-hash. */
|
||||
/** Chain verifier — usually `verifyAuditChain` from @hivegrid/db/audit-hash. */
|
||||
verify: (events: ReadonlyArray<AuditVerifyChainRow>, options?: { secret?: string | null }) => VerifyAuditChainResult;
|
||||
/** Output sink. Tests pass an array collector; production wires consola. */
|
||||
output: { info: (msg: string) => void; json: (obj: unknown) => void; error: (msg: string) => void };
|
||||
@@ -111,8 +111,8 @@ export const auditVerifyChainCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, default: false, description: "Emit a single JSON object instead of human-readable text." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { verifyAuditChain } = await import("@toolctrl/db/audit-hash");
|
||||
const { getReadDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { verifyAuditChain } = await import("@hivegrid/db/audit-hash");
|
||||
const { getReadDbClient } = await import("@hivegrid/db/client.server");
|
||||
const db = getReadDbClient();
|
||||
const tenantId = String(args.tenant);
|
||||
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ describe("create entity generator", () => {
|
||||
const fakeTimestamp = "20260101000000";
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-entity-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-entity-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl create entity <name>` — emit a Prisma model snippet plus a
|
||||
* `hivegrid create entity <name>` — emit a Prisma model snippet plus a
|
||||
* timestamped migration directory.
|
||||
*
|
||||
* The generator does NOT modify `prisma/schema.prisma` automatically —
|
||||
@@ -92,7 +92,7 @@ function defaultTimestamp(): string {
|
||||
}
|
||||
|
||||
function renderPrismaModel({ pascal, snake }: { pascal: string; snake: string }): string {
|
||||
return `// Generated by toolctrl-cli — paste this block into prisma/schema.prisma.
|
||||
return `// Generated by hivegrid-cli — paste this block into prisma/schema.prisma.
|
||||
model ${pascal} {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
@@ -107,7 +107,7 @@ model ${pascal} {
|
||||
}
|
||||
|
||||
function renderMigrationSql({ pascal, snake }: { pascal: string; snake: string }): string {
|
||||
return `-- Generated by toolctrl-cli for entity ${pascal}.
|
||||
return `-- Generated by hivegrid-cli for entity ${pascal}.
|
||||
-- Replace columns with actual schema before running \`prisma migrate dev\`.
|
||||
CREATE TABLE "${snake}" (
|
||||
"id" TEXT NOT NULL,
|
||||
@@ -133,7 +133,7 @@ function renderMigrationReadme({
|
||||
}): string {
|
||||
return `# Migration: create entity ${pascal}
|
||||
|
||||
Generated by \`toolctrl create entity ${kebab}\`.
|
||||
Generated by \`hivegrid create entity ${kebab}\`.
|
||||
|
||||
## How to apply
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ describe("create module generator", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-module-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-module-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl create module <name>` — generate a new feature-module skeleton
|
||||
* `hivegrid create module <name>` — generate a new feature-module skeleton
|
||||
* under `apps/web/app/modules/<name>/`.
|
||||
*
|
||||
* The generator emits the minimum set of files needed for a tenant-scoped
|
||||
@@ -107,7 +107,7 @@ export async function generateModule(options: GenerateModuleOptions): Promise<Sc
|
||||
function renderDbFile({ camel, pascal }: { camel: string; pascal: string }): string {
|
||||
return `/**
|
||||
* Tenant-scoped CRUD helpers for the ${pascal} module.
|
||||
* Generated by toolctrl-cli — fill in the model field references after
|
||||
* Generated by hivegrid-cli — fill in the model field references after
|
||||
* adding the Prisma model and running \`prisma migrate dev\`.
|
||||
*/
|
||||
import { db } from "~/utils/db.server";
|
||||
@@ -134,7 +134,7 @@ function renderServiceFile({ camel, pascal }: { camel: string; pascal: string })
|
||||
return `/**
|
||||
* Service-layer for the ${pascal} module — wraps the db helpers with
|
||||
* tenant-access guards so route handlers don't have to repeat the
|
||||
* permission boilerplate.
|
||||
* permission scaffold.
|
||||
*/
|
||||
import { list${pascal}, get${pascal}ById } from "../db/${camel}.db.server";
|
||||
|
||||
@@ -193,7 +193,7 @@ import { ${pascal}List } from "~/modules/${camel}/components/${pascal}List";
|
||||
|
||||
/**
|
||||
* Tenant route for the ${pascal} module.
|
||||
* Generated by toolctrl-cli. Wire in \`requireAuth\` and the
|
||||
* Generated by hivegrid-cli. Wire in \`requireAuth\` and the
|
||||
* "${permissionPrefix}.view" permission guard once you connect the module
|
||||
* to your auth helpers.
|
||||
*/
|
||||
@@ -241,7 +241,7 @@ function renderReadme({
|
||||
}): string {
|
||||
return `# ${pascal} module
|
||||
|
||||
Generated by \`toolctrl create module ${kebab}\`.
|
||||
Generated by \`hivegrid create module ${kebab}\`.
|
||||
|
||||
## Layout
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ describe("create route generator", () => {
|
||||
let tempRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-route-"));
|
||||
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-route-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl create route <path>` — generate a single React-Router-v7
|
||||
* `hivegrid create route <path>` — generate a single React-Router-v7
|
||||
* route file with a sensible auth/CSRF default plus a co-located
|
||||
* vitest stub.
|
||||
*
|
||||
@@ -97,7 +97,7 @@ function renderRoute({
|
||||
import { isRouteErrorResponse } from "react-router";
|
||||
|
||||
/**
|
||||
* Generated by \`toolctrl create route ${filename}\`.
|
||||
* Generated by \`hivegrid create route ${filename}\`.
|
||||
* TODO: wire \`requireAuth(request)\` and \`validateCSRFToken(request)\`
|
||||
* from your project's auth utility module.
|
||||
*/
|
||||
|
||||
+2
-2
@@ -24,10 +24,10 @@ function getDsgvoCliMocks(): DsgvoCliMocks {
|
||||
return global.__dsgvoCliMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => getDsgvoCliMocks().db,
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: getDsgvoCliMocks().createAuditEvent,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
@@ -47,8 +47,8 @@ export const dsgvoDeleteCommand = defineCommand({
|
||||
const requestId = randomUUID();
|
||||
|
||||
const [{ getDbClient }, { createAuditEvent }] = await Promise.all([
|
||||
import("@toolctrl/db/client.server"),
|
||||
import("@toolctrl/db/audit-events.server"),
|
||||
import("@hivegrid/db/client.server"),
|
||||
import("@hivegrid/db/audit-events.server"),
|
||||
]);
|
||||
const prisma = getDbClient();
|
||||
await prisma.user.update({
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type AuditEventInput = {
|
||||
tenantId: string | null;
|
||||
actorId: string;
|
||||
actorType: string;
|
||||
action: string;
|
||||
targetType: string;
|
||||
targetId: string;
|
||||
regulatoryScope: string[];
|
||||
dataSensitivity: string;
|
||||
outcome: string;
|
||||
metadata: { requestId: string; intent: string; source: string };
|
||||
};
|
||||
|
||||
const createAuditEvent = vi.fn<(input: AuditEventInput) => Promise<{ id: string }>>();
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: (...args: unknown[]) => createAuditEvent(...(args as [AuditEventInput])),
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { dsgvoExportCommand } from "./export.js";
|
||||
import { dsgvoVerifyCommand } from "./verify.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
||||
|
||||
describe("dsgvo export command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
createAuditEvent.mockResolvedValue({ id: "audit_1" });
|
||||
});
|
||||
|
||||
it("writes a REQUEST_PERSONAL_DATA_EXPORT audit row with explicit tenant and actor", async () => {
|
||||
await dsgvoExportCommand.run?.({
|
||||
args: { user: "user_1", tenant: "tenant_1", actor: "admin_1" },
|
||||
} as never);
|
||||
|
||||
expect(createAuditEvent).toHaveBeenCalledTimes(1);
|
||||
const payload = createAuditEvent.mock.calls[0]![0];
|
||||
expect(payload).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
actorId: "admin_1",
|
||||
action: "REQUEST_PERSONAL_DATA_EXPORT",
|
||||
targetType: "User",
|
||||
targetId: "user_1",
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
});
|
||||
expect(payload.metadata.intent).toBe("export");
|
||||
expect(payload.metadata.source).toBe("cli");
|
||||
expect(payload.metadata.requestId).toMatch(UUID_RE);
|
||||
expect(consoleMock.success).toHaveBeenCalledWith(
|
||||
`Personal-data export queued for user=user_1 requestId=${payload.metadata.requestId}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults the actor to cli-operator and tenant to null when omitted", async () => {
|
||||
await dsgvoExportCommand.run?.({ args: { user: "user_2" } } as never);
|
||||
|
||||
expect(createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantId: null, actorId: "cli-operator" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dsgvo verify command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
createAuditEvent.mockResolvedValue({ id: "audit_1" });
|
||||
});
|
||||
|
||||
it("writes a VERIFY_USER_DELETION audit row with verify intent", async () => {
|
||||
await dsgvoVerifyCommand.run?.({
|
||||
args: { user: "user_1", tenant: "tenant_1", actor: "admin_1" },
|
||||
} as never);
|
||||
|
||||
const payload = createAuditEvent.mock.calls[0]![0];
|
||||
expect(payload).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
actorId: "admin_1",
|
||||
action: "VERIFY_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: "user_1",
|
||||
});
|
||||
expect(payload.metadata.intent).toBe("verify");
|
||||
expect(payload.metadata.requestId).toMatch(UUID_RE);
|
||||
expect(consoleMock.success).toHaveBeenCalledWith(
|
||||
`Verifier-pass queued for user=user_1 requestId=${payload.metadata.requestId}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults the actor and tenant when only the user id is given", async () => {
|
||||
await dsgvoVerifyCommand.run?.({ args: { user: "user_9" } } as never);
|
||||
|
||||
expect(createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantId: null, actorId: "cli-operator" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,7 @@ export const dsgvoExportCommand = defineCommand({
|
||||
const actorId = args.actor ? String(args.actor) : "cli-operator";
|
||||
const requestId = randomUUID();
|
||||
|
||||
const { createAuditEvent } = await import("@toolctrl/db/audit-events.server");
|
||||
const { createAuditEvent } = await import("@hivegrid/db/audit-events.server");
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId,
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@ export const dsgvoReactivateCommand = defineCommand({
|
||||
const requestId = randomUUID();
|
||||
|
||||
const [{ getDbClient }, { createAuditEvent }] = await Promise.all([
|
||||
import("@toolctrl/db/client.server"),
|
||||
import("@toolctrl/db/audit-events.server"),
|
||||
import("@hivegrid/db/client.server"),
|
||||
import("@hivegrid/db/audit-events.server"),
|
||||
]);
|
||||
const prisma = getDbClient();
|
||||
const existing = await prisma.user.findUnique({
|
||||
|
||||
@@ -25,7 +25,7 @@ export const dsgvoVerifyCommand = defineCommand({
|
||||
const tenantId = args.tenant ? String(args.tenant) : null;
|
||||
const actorId = args.actor ? String(args.actor) : "cli-operator";
|
||||
const requestId = randomUUID();
|
||||
const { createAuditEvent } = await import("@toolctrl/db/audit-events.server");
|
||||
const { createAuditEvent } = await import("@hivegrid/db/audit-events.server");
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId,
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const publishMock = vi.fn();
|
||||
vi.mock("@toolctrl/feature-flags", () => ({
|
||||
vi.mock("@hivegrid/feature-flags", () => ({
|
||||
publishFeatureFlagInvalidationOnce: (...args: unknown[]) => publishMock(...args),
|
||||
}));
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
* web side (60s default) is the safety net.
|
||||
*/
|
||||
import consola from "consola";
|
||||
import { publishFeatureFlagInvalidationOnce } from "@toolctrl/feature-flags";
|
||||
import { publishFeatureFlagInvalidationOnce } from "@hivegrid/feature-flags";
|
||||
|
||||
const DEFAULT_PUBLISH_NAMESPACE = "web";
|
||||
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ const dbMock = {
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ export const featureFlagsListCommand = defineCommand({
|
||||
},
|
||||
async run({ args }) {
|
||||
const filter = args.enabled === undefined ? undefined : String(args.enabled) === "true";
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const where = filter === undefined ? {} : { enabled: filter };
|
||||
const flags = await prisma.featureFlag.findMany({
|
||||
|
||||
+3
-3
@@ -22,10 +22,10 @@ const dbMock = {
|
||||
const broadcastFlagInvalidationMock = vi.fn();
|
||||
const evaluateRuleMock = vi.fn();
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("@toolctrl/feature-flags", () => ({
|
||||
vi.mock("@hivegrid/feature-flags", () => ({
|
||||
evaluateRule: (...args: unknown[]) => evaluateRuleMock(...args),
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
@@ -52,7 +52,7 @@ function writeRulesFile(contents: string): string {
|
||||
|
||||
describe("feature flag set-rules command", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "toolctrl-cli-flags-"));
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hivegrid-cli-flags-"));
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
dbMock.$transaction.mockResolvedValue([]);
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { evaluateRule, type TargetingRule } from "@toolctrl/feature-flags";
|
||||
import { evaluateRule, type TargetingRule } from "@hivegrid/feature-flags";
|
||||
import { broadcastFlagInvalidation } from "./invalidate.js";
|
||||
|
||||
async function applyRules(name: string, rulesJson: string): Promise<void> {
|
||||
@@ -29,7 +29,7 @@ async function applyRules(name: string, rulesJson: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const existing = await prisma.featureFlag.findFirst({ where: { name } });
|
||||
if (!existing) {
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ const dbMock = {
|
||||
};
|
||||
const broadcastFlagInvalidationMock = vi.fn();
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import consola from "consola";
|
||||
import { broadcastFlagInvalidation } from "./invalidate.js";
|
||||
|
||||
async function toggleFlag(name: string, target: boolean): Promise<void> {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const existing = await prisma.featureFlag.findFirst({ where: { name } });
|
||||
if (!existing) {
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type FormRow = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
isEnabled: boolean;
|
||||
_count: { submissions: number };
|
||||
};
|
||||
|
||||
type FormCreateArgs = {
|
||||
data: {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
definition: { fields: Array<{ key: string; type: string }> };
|
||||
allowedOrigins: string[];
|
||||
config: { honeypotEnabled: boolean };
|
||||
};
|
||||
};
|
||||
|
||||
const dbMock = {
|
||||
form: {
|
||||
create: vi.fn<(args: FormCreateArgs) => Promise<{ id: string; key: string }>>(),
|
||||
findMany: vi.fn<() => Promise<FormRow[]>>(),
|
||||
findUnique: vi.fn<() => Promise<{ id: string; name: string } | null>>(),
|
||||
delete: vi.fn<() => Promise<{ id: string }>>(),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
info: vi.fn(),
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { formsCreateCommand } from "./create.js";
|
||||
import { formsDeleteCommand } from "./delete.js";
|
||||
import { formsListCommand } from "./list.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
describe("forms create command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
dbMock.form.create.mockResolvedValue({ id: "form_1", key: "pub_key_1" });
|
||||
});
|
||||
|
||||
it("seeds the default text/email/textarea/honeypot definition with no origins", async () => {
|
||||
await formsCreateCommand.run?.({ args: { tenant: "tenant_1", name: "Contact" } } as never);
|
||||
|
||||
expect(dbMock.form.create).toHaveBeenCalledTimes(1);
|
||||
const payload = dbMock.form.create.mock.calls[0]![0];
|
||||
expect(payload.data.tenantId).toBe("tenant_1");
|
||||
expect(payload.data.name).toBe("Contact");
|
||||
expect(payload.data.allowedOrigins).toEqual([]);
|
||||
expect(payload.data.config).toEqual({ honeypotEnabled: true });
|
||||
const fieldTypes = payload.data.definition.fields.map((f) => f.type);
|
||||
expect(fieldTypes).toEqual(["text", "email", "textarea", "honeypot"]);
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("Form created: id=form_1 key=pub_key_1");
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining('data-form-key="pub_key_1"'));
|
||||
});
|
||||
|
||||
it("records the allowed embedding origin when --origin is supplied", async () => {
|
||||
await formsCreateCommand.run?.({
|
||||
args: { tenant: "tenant_1", name: "Newsletter", origin: "https://acme.example" },
|
||||
} as never);
|
||||
|
||||
const payload = dbMock.form.create.mock.calls[0]![0];
|
||||
expect(payload.data.allowedOrigins).toEqual(["https://acme.example"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("forms list command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.form.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("prints ON/OFF state, submission counts, and a closing summary", async () => {
|
||||
dbMock.form.findMany.mockResolvedValueOnce([
|
||||
{ id: "form_1", key: "pub_a", name: "Contact", isEnabled: true, _count: { submissions: 12 } },
|
||||
{ id: "form_2", key: "pub_b", name: "Survey", isEnabled: false, _count: { submissions: 0 } },
|
||||
]);
|
||||
|
||||
await formsListCommand.run?.({ args: { tenant: "tenant_1" } } as never);
|
||||
|
||||
expect(dbMock.form.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
name: true,
|
||||
isEnabled: true,
|
||||
_count: { select: { submissions: true } },
|
||||
},
|
||||
});
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^ON .*form_1.*subs=12 Contact/u));
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^OFF.*form_2.*subs=0 Survey/u));
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("2 forms listed.");
|
||||
});
|
||||
|
||||
it("reports an empty tenant without a summary line", async () => {
|
||||
await formsListCommand.run?.({ args: { tenant: "tenant_empty" } } as never);
|
||||
|
||||
expect(consoleMock.info).toHaveBeenCalledWith("No forms for tenant tenant_empty.");
|
||||
expect(consoleMock.success).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("forms delete command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
dbMock.form.findUnique.mockResolvedValue(null);
|
||||
dbMock.form.delete.mockResolvedValue({ id: "form_1" });
|
||||
});
|
||||
|
||||
it("hard-deletes an existing form and confirms with its name", async () => {
|
||||
dbMock.form.findUnique.mockResolvedValueOnce({ id: "form_1", name: "Contact" });
|
||||
|
||||
await formsDeleteCommand.run?.({ args: { id: "form_1" } } as never);
|
||||
|
||||
expect(dbMock.form.delete).toHaveBeenCalledWith({ where: { id: "form_1" } });
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("Form deleted: form_1 (Contact).");
|
||||
expect(process.exitCode).toBeUndefined();
|
||||
});
|
||||
|
||||
it("sets a non-zero exit code and skips the delete when the form is missing", async () => {
|
||||
await formsDeleteCommand.run?.({ args: { id: "ghost" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("Form ghost not found.");
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(dbMock.form.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@toolctrl/form-widget";
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
|
||||
|
||||
export const formsCreateCommand = defineCommand({
|
||||
meta: { name: "create", description: "Seed a minimal form for a tenant." },
|
||||
@@ -29,7 +29,7 @@ export const formsCreateCommand = defineCommand({
|
||||
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", label: "Leave empty" },
|
||||
],
|
||||
});
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const created = await prisma.form.create({
|
||||
data: {
|
||||
|
||||
@@ -11,7 +11,7 @@ export const formsDeleteCommand = defineCommand({
|
||||
id: { type: "string", required: true, description: "Form ID." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const id = String(args.id);
|
||||
const existing = await prisma.form.findUnique({ where: { id }, select: { id: true, name: true } });
|
||||
|
||||
@@ -10,7 +10,7 @@ export const formsListCommand = defineCommand({
|
||||
tenant: { type: "string", required: true, description: "Tenant ID." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const tenantId = String(args.tenant);
|
||||
const forms = await prisma.form.findMany({
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ const dbMock = {
|
||||
};
|
||||
const writeFileMock = vi.fn();
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("node:fs/promises", () => ({
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMock = {
|
||||
lead: {
|
||||
findUnique: vi.fn<() => Promise<{ email: string } | null>>(),
|
||||
delete: vi.fn<() => Promise<{ id: string }>>(),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
warn: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { leadsDeleteCommand } from "./delete.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
describe("leads delete command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.lead.findUnique.mockResolvedValue(null);
|
||||
dbMock.lead.delete.mockResolvedValue({ id: "lead_1" });
|
||||
});
|
||||
|
||||
it("hard-deletes an existing lead and echoes its email for the audit trail", async () => {
|
||||
dbMock.lead.findUnique.mockResolvedValueOnce({ email: "ada@example.com" });
|
||||
|
||||
await leadsDeleteCommand.run?.({ args: { id: "lead_1" } } as never);
|
||||
|
||||
expect(dbMock.lead.findUnique).toHaveBeenCalledWith({
|
||||
where: { id: "lead_1" },
|
||||
select: { email: true },
|
||||
});
|
||||
expect(dbMock.lead.delete).toHaveBeenCalledWith({ where: { id: "lead_1" } });
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("Deleted lead lead_1 (ada@example.com).");
|
||||
});
|
||||
|
||||
it("warns and skips the delete when the lead does not exist", async () => {
|
||||
await leadsDeleteCommand.run?.({ args: { id: "ghost" } } as never);
|
||||
|
||||
expect(consoleMock.warn).toHaveBeenCalledWith("Lead ghost not found.");
|
||||
expect(dbMock.lead.delete).not.toHaveBeenCalled();
|
||||
expect(consoleMock.success).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ export const leadsDeleteCommand = defineCommand({
|
||||
id: { type: "string", required: true, description: "Lead id." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const id = String(args.id);
|
||||
const existing = await prisma.lead.findUnique({ where: { id }, select: { email: true } });
|
||||
|
||||
@@ -44,7 +44,7 @@ export const leadsExportCommand = defineCommand({
|
||||
status: { type: "string", required: false, description: "Filter by status." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const where = args.status ? { status: String(args.status) as never } : {};
|
||||
const leads = await prisma.lead.findMany({ where, orderBy: { createdAt: "desc" } });
|
||||
|
||||
@@ -11,7 +11,7 @@ export const leadsListCommand = defineCommand({
|
||||
limit: { type: "string", required: false, description: "Max rows (default 50)." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const limit = Math.min(500, Math.max(1, Number(args.limit ?? "50")));
|
||||
const where = args.status ? { status: String(args.status) as never } : {};
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ export const marketingAttributionCommand = defineCommand({
|
||||
limit: { type: "string", required: false, description: "Top N rows (default 25)." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getReadDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getReadDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getReadDbClient();
|
||||
const days = Math.min(365, Math.max(1, Number(args.days ?? "30")));
|
||||
const dim = (DIMENSIONS as readonly string[]).includes(String(args.dimension ?? ""))
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type GroupByRow = {
|
||||
_count: { _all: number };
|
||||
utmCampaign?: string | null;
|
||||
utmSource?: string | null;
|
||||
source?: string | null;
|
||||
conversionPath?: string | null;
|
||||
};
|
||||
|
||||
const dbMock = {
|
||||
tenantAcquisition: {
|
||||
groupBy: vi.fn<() => Promise<GroupByRow[]>>(),
|
||||
count: vi.fn<() => Promise<number>>(),
|
||||
},
|
||||
lead: {
|
||||
count: vi.fn<() => Promise<number>>(),
|
||||
groupBy: vi.fn<() => Promise<Array<{ status: string; _count: { _all: number } }>>>(),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getReadDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
info: vi.fn(),
|
||||
log: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { marketingAttributionCommand } from "./attribution.js";
|
||||
import { marketingFunnelCommand } from "./funnel.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
const now = new Date("2026-06-25T00:00:00.000Z");
|
||||
|
||||
describe("marketing attribution command", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
vi.clearAllMocks();
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("defaults to the campaign dimension, 30 days, and limit 25", async () => {
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([
|
||||
{ utmCampaign: "spring", _count: { _all: 7 } },
|
||||
{ utmCampaign: null, _count: { _all: 3 } },
|
||||
]);
|
||||
|
||||
await marketingAttributionCommand.run?.({ args: {} } as never);
|
||||
|
||||
const since = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith({
|
||||
by: ["utmCampaign"],
|
||||
_count: { _all: true },
|
||||
where: { convertedAt: { gte: since } },
|
||||
orderBy: { _count: { tenantId: "desc" } },
|
||||
take: 25,
|
||||
});
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`Attribution by campaign — last 30 days (since ${since.toISOString().slice(0, 10)})`),
|
||||
);
|
||||
// Null keys fall back to "(none)" and counts are padded.
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("spring"));
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("(none)"));
|
||||
});
|
||||
|
||||
it("groups by utmSource when that dimension is requested", async () => {
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ utmSource: "newsletter", _count: { _all: 2 } }]);
|
||||
|
||||
await marketingAttributionCommand.run?.({ args: { dimension: "utmSource" } } as never);
|
||||
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ by: ["utmSource"] }),
|
||||
);
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("Attribution by utmSource"));
|
||||
});
|
||||
|
||||
it("groups by source when that dimension is requested", async () => {
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ source: "organic", _count: { _all: 9 } }]);
|
||||
|
||||
await marketingAttributionCommand.run?.({ args: { dimension: "source" } } as never);
|
||||
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ by: ["source"] }),
|
||||
);
|
||||
});
|
||||
|
||||
it("groups by conversionPath for the path dimension", async () => {
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ conversionPath: "/pricing", _count: { _all: 4 } }]);
|
||||
|
||||
await marketingAttributionCommand.run?.({ args: { dimension: "path" } } as never);
|
||||
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ by: ["conversionPath"] }),
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to campaign for an unknown dimension value", async () => {
|
||||
await marketingAttributionCommand.run?.({ args: { dimension: "garbage" } } as never);
|
||||
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ by: ["utmCampaign"] }),
|
||||
);
|
||||
});
|
||||
|
||||
it("clamps days to the [1, 365] window and limit to [1, 200]", async () => {
|
||||
await marketingAttributionCommand.run?.({ args: { days: "9999", limit: "5000" } } as never);
|
||||
const since365 = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { convertedAt: { gte: since365 } }, take: 200 }),
|
||||
);
|
||||
|
||||
vi.clearAllMocks();
|
||||
dbMock.tenantAcquisition.groupBy.mockResolvedValue([]);
|
||||
await marketingAttributionCommand.run?.({ args: { days: "0", limit: "0" } } as never);
|
||||
const since1 = new Date(now.getTime() - 1 * 24 * 60 * 60 * 1000);
|
||||
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { convertedAt: { gte: since1 } }, take: 1 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an empty period via consola.info without a table", async () => {
|
||||
await marketingAttributionCommand.run?.({ args: { days: "14" } } as never);
|
||||
|
||||
expect(consoleMock.info).toHaveBeenCalledWith("No conversions in last 14 days.");
|
||||
expect(consoleMock.log).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("marketing funnel command", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
vi.clearAllMocks();
|
||||
dbMock.lead.count.mockResolvedValue(0);
|
||||
dbMock.tenantAcquisition.count.mockResolvedValue(0);
|
||||
dbMock.lead.groupBy.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("computes the conversion rate and renders the full stage ladder", async () => {
|
||||
dbMock.lead.count.mockResolvedValueOnce(200);
|
||||
dbMock.tenantAcquisition.count.mockResolvedValueOnce(50);
|
||||
dbMock.lead.groupBy.mockResolvedValueOnce([
|
||||
{ status: "new", _count: { _all: 120 } },
|
||||
{ status: "customer", _count: { _all: 50 } },
|
||||
]);
|
||||
|
||||
await marketingFunnelCommand.run?.({ args: {} } as never);
|
||||
|
||||
expect(consoleMock.log).toHaveBeenCalledWith("Leads captured: 200");
|
||||
expect(consoleMock.log).toHaveBeenCalledWith("Conversions: 50");
|
||||
expect(consoleMock.log).toHaveBeenCalledWith("Conversion rate: 25.00%");
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("new"));
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("120"));
|
||||
// Stages without data render a zero count rather than being skipped.
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/churned\s+0/u));
|
||||
});
|
||||
|
||||
it("guards division by zero when no leads were captured", async () => {
|
||||
await marketingFunnelCommand.run?.({ args: { days: "7" } } as never);
|
||||
|
||||
const since = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
expect(dbMock.lead.count).toHaveBeenCalledWith({ where: { createdAt: { gte: since } } });
|
||||
expect(consoleMock.log).toHaveBeenCalledWith("Conversion rate: 0.00%");
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -12,7 +12,7 @@ export const marketingFunnelCommand = defineCommand({
|
||||
days: { type: "string", required: false, description: "Period in days (default 30)." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getReadDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getReadDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getReadDbClient();
|
||||
const days = Math.min(365, Math.max(1, Number(args.days ?? "30")));
|
||||
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
|
||||
@@ -8,7 +8,7 @@ describe("ops env resolver", () => {
|
||||
let home: string;
|
||||
|
||||
beforeEach(() => {
|
||||
home = mkdtempSync(path.join(tmpdir(), "toolctrl-cli-ops-env-"));
|
||||
home = mkdtempSync(path.join(tmpdir(), "hivegrid-cli-ops-env-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -23,8 +23,8 @@ describe("ops env resolver", () => {
|
||||
expect(resolved.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it("reads ~/.toolctrl/envs/<name>.env when --env is supplied", () => {
|
||||
const envDir = path.join(home, ".toolctrl", "envs");
|
||||
it("reads ~/.hivegrid/envs/<name>.env when --env is supplied", () => {
|
||||
const envDir = path.join(home, ".hivegrid", "envs");
|
||||
mkdirSync(envDir, { recursive: true });
|
||||
const file = path.join(envDir, "staging.env");
|
||||
writeFileSync(file, "# header\nDATABASE_URL=postgres://u:p@host:5432/db\nREDIS_URL=\"redis://r\"\n");
|
||||
@@ -38,7 +38,7 @@ describe("ops env resolver", () => {
|
||||
});
|
||||
|
||||
it("warns when the env-file is world-readable", () => {
|
||||
const envDir = path.join(home, ".toolctrl", "envs");
|
||||
const envDir = path.join(home, ".hivegrid", "envs");
|
||||
mkdirSync(envDir, { recursive: true });
|
||||
const file = path.join(envDir, "loose.env");
|
||||
writeFileSync(file, "FOO=bar\n");
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* `toolctrl ops` env resolver.
|
||||
* `hivegrid ops` env resolver.
|
||||
*
|
||||
* Two layers:
|
||||
* - **local (default):** the operator's working-dir `.env` (already loaded
|
||||
* by the runtime via dotenv or shell-export). We just read from
|
||||
* `process.env`.
|
||||
* - **named (`--env=<name>`):** parsed from `~/.toolctrl/envs/<name>.env`.
|
||||
* - **named (`--env=<name>`):** parsed from `~/.hivegrid/envs/<name>.env`.
|
||||
* File format is a simple `KEY=VALUE` `.env` syntax — no shell
|
||||
* interpolation. Lines starting with `#` and blank lines are skipped.
|
||||
*
|
||||
@@ -63,7 +63,7 @@ export function resolveOpsEnv(options: ResolveEnvOptions = {}): ResolvedOpsEnv {
|
||||
}
|
||||
validateEnvName(options.name);
|
||||
const home = options.homeDirOverride ?? homedir();
|
||||
const filePath = path.join(home, ".toolctrl", "envs", `${options.name}.env`);
|
||||
const filePath = path.join(home, ".hivegrid", "envs", `${options.name}.env`);
|
||||
if (!existsSync(filePath)) {
|
||||
throw new OpsEnvError(
|
||||
`Env file not found: ${filePath}. Create it (chmod 600) before invoking --env=${options.name}.`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl ops doctor` — local-stack health check.
|
||||
* `hivegrid ops doctor` — local-stack health check.
|
||||
*
|
||||
* Runs a list of probes, each returning `{ name, status, message? }`.
|
||||
* `status` is `ok | warn | fail`. Exit code is 1 when any probe is `fail`.
|
||||
@@ -310,7 +310,7 @@ export const opsDoctorCommand = defineCommand({
|
||||
env: {
|
||||
type: "string",
|
||||
required: false,
|
||||
description: "Named env file under ~/.toolctrl/envs/<name>.env (default: local .env).",
|
||||
description: "Named env file under ~/.hivegrid/envs/<name>.env (default: local .env).",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl ops impersonate <tenant> <user>`
|
||||
* `hivegrid ops impersonate <tenant> <user>`
|
||||
*
|
||||
* Generates a 15-minute, HMAC-signed magic-link the engineer can paste
|
||||
* into a non-production browser to debug a tenant's user account.
|
||||
@@ -8,7 +8,7 @@
|
||||
* outcome=success) so the action is reviewable.
|
||||
*
|
||||
* The Prisma client + URL base are dependency-injected — the production
|
||||
* `bin/toolctrl-cli.mjs` wires `@toolctrl/db` + the resolved web origin.
|
||||
* `bin/hivegrid-cli.mjs` wires `@hivegrid/db` + the resolved web origin.
|
||||
*
|
||||
* Refs: docs/improvement-plan/08-mobile-cli-storybook-sdk/cli-ops.md
|
||||
*/
|
||||
@@ -170,7 +170,7 @@ export async function runImpersonate(opts: RunImpersonateOptions): Promise<RunIm
|
||||
action: "ops.impersonate.issued",
|
||||
targetType: "user",
|
||||
targetId: opts.userId,
|
||||
sourceModule: "toolctrl-cli/ops",
|
||||
sourceModule: "hivegrid-cli/ops",
|
||||
outcome: "success",
|
||||
dataSensitivity: "pii",
|
||||
regulatoryScope: ["soc2"],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl ops` — operator subcommand group.
|
||||
* `hivegrid ops` — operator subcommand group.
|
||||
*
|
||||
* Children:
|
||||
* - `doctor` — local environment health-check
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ describe("runMigration", () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(path.join(tmpdir(), "toolctrl-cli-migrate-"));
|
||||
dir = mkdtempSync(path.join(tmpdir(), "hivegrid-cli-migrate-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
+4
-4
@@ -1,15 +1,15 @@
|
||||
/**
|
||||
* `toolctrl ops migrate-tenant <id> --from=<src> --to=<tgt>`
|
||||
* `hivegrid ops migrate-tenant <id> --from=<src> --to=<tgt>`
|
||||
*
|
||||
* Resumable orchestrator that drives tenant-snapshot (#44) export against
|
||||
* the source env and a corresponding restore into the target env. State
|
||||
* is persisted to `~/.toolctrl/migrations/<id>-<timestamp>.state.json` so
|
||||
* is persisted to `~/.hivegrid/migrations/<id>-<timestamp>.state.json` so
|
||||
* a crash mid-flight can be resumed via `--resume <state-file>`.
|
||||
*
|
||||
* This command intentionally does not import the heavy tenant-snapshot
|
||||
* implementation directly — the snapshot/restore steps are
|
||||
* dependency-injected so unit tests stay hermetic. The production
|
||||
* entrypoint (`bin/toolctrl-cli.mjs`) wires up the real Prisma runner
|
||||
* entrypoint (`bin/hivegrid-cli.mjs`) wires up the real Prisma runner
|
||||
* and S3 client.
|
||||
*
|
||||
* Refs: docs/improvement-plan/08-mobile-cli-storybook-sdk/cli-ops.md
|
||||
@@ -77,7 +77,7 @@ export interface MigrationOutcome {
|
||||
}
|
||||
|
||||
export function defaultStateDir(): string {
|
||||
return path.join(homedir(), ".toolctrl", "migrations");
|
||||
return path.join(homedir(), ".hivegrid", "migrations");
|
||||
}
|
||||
|
||||
export function newMigrationState(opts: {
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface OutboxRequeueEventRow {
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow interface against `@toolctrl/db` — just the methods the
|
||||
* Narrow interface against `@hivegrid/db` — just the methods the
|
||||
* runner uses. Tests inject an in-memory fake.
|
||||
*/
|
||||
export interface OutboxRequeueClient {
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { OutboxRequeueOutput } from "./_lib.js";
|
||||
|
||||
const runById = vi.fn();
|
||||
const runBulk = vi.fn();
|
||||
|
||||
vi.mock("./_lib.js", () => ({
|
||||
runOutboxRequeueById: (...args: unknown[]) => runById(...args),
|
||||
runOutboxRequeueBulk: (...args: unknown[]) => runBulk(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => ({ outboxEvent: {} }),
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
log: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { outboxRequeueCommand } from "./requeue.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
describe("outbox requeue command wrapper", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.exitCode = undefined;
|
||||
runById.mockResolvedValue({ exitCode: 0 });
|
||||
runBulk.mockResolvedValue({ exitCode: 0 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = undefined;
|
||||
});
|
||||
|
||||
it("rejects passing both --event-id and --type", async () => {
|
||||
await outboxRequeueCommand.run?.({ args: { "event-id": "evt-1", type: "a.b.c" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("Pass --event-id OR (--type + --since), not both.");
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(runById).not.toHaveBeenCalled();
|
||||
expect(runBulk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects when neither mode is fully specified", async () => {
|
||||
await outboxRequeueCommand.run?.({ args: { type: "a.b.c" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("Either --event-id or (--type + --since) is required.");
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(runById).not.toHaveBeenCalled();
|
||||
expect(runBulk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("delegates single-event mode and adopts the lib outcome exit code", async () => {
|
||||
runById.mockResolvedValueOnce({ exitCode: 0 });
|
||||
|
||||
await outboxRequeueCommand.run?.({ args: { "event-id": "evt-1" } } as never);
|
||||
|
||||
expect(runById).toHaveBeenCalledWith(
|
||||
{ eventId: "evt-1", json: false },
|
||||
expect.objectContaining({ client: expect.anything(), output: expect.anything() }),
|
||||
);
|
||||
expect(runBulk).not.toHaveBeenCalled();
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("delegates bulk mode with a parsed limit and apply flags", async () => {
|
||||
runBulk.mockResolvedValueOnce({ exitCode: 0 });
|
||||
|
||||
await outboxRequeueCommand.run?.({
|
||||
args: {
|
||||
type: "billing.subscription.ended",
|
||||
since: "2026-05-01T00:00:00Z",
|
||||
apply: true,
|
||||
"include-done": true,
|
||||
limit: "42",
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(runBulk).toHaveBeenCalledWith(
|
||||
{
|
||||
type: "billing.subscription.ended",
|
||||
since: "2026-05-01T00:00:00Z",
|
||||
apply: true,
|
||||
includeDone: true,
|
||||
limit: 42,
|
||||
json: false,
|
||||
},
|
||||
expect.objectContaining({ client: expect.anything(), output: expect.anything() }),
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("omits limit from the bulk payload when not parseable", async () => {
|
||||
await outboxRequeueCommand.run?.({
|
||||
args: { type: "a.b.c", since: "2026-05-01T00:00:00Z", limit: "not-a-number" },
|
||||
} as never);
|
||||
|
||||
const payload = runBulk.mock.calls[0]?.[0] as Record<string, unknown>;
|
||||
expect(payload).not.toHaveProperty("limit");
|
||||
expect(payload).toMatchObject({ apply: false, includeDone: false, json: false });
|
||||
});
|
||||
|
||||
it("routes the lib output sink through consola (text mode)", async () => {
|
||||
runById.mockImplementationOnce(async (_input: unknown, ctx: { output: OutboxRequeueOutput }) => {
|
||||
ctx.output.log("done");
|
||||
ctx.output.warn("careful");
|
||||
ctx.output.error("nope");
|
||||
ctx.output.json({ a: 1 });
|
||||
return { exitCode: 0 };
|
||||
});
|
||||
|
||||
await outboxRequeueCommand.run?.({ args: { "event-id": "evt-1" } } as never);
|
||||
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("done");
|
||||
expect(consoleMock.warn).toHaveBeenCalledWith("careful");
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("nope");
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(JSON.stringify({ a: 1 }));
|
||||
});
|
||||
|
||||
it("suppresses log/error decorations in JSON mode but keeps warnings", async () => {
|
||||
runById.mockImplementationOnce(async (_input: unknown, ctx: { output: OutboxRequeueOutput }) => {
|
||||
ctx.output.log("done");
|
||||
ctx.output.warn("careful");
|
||||
ctx.output.error("nope");
|
||||
return { exitCode: 0 };
|
||||
});
|
||||
|
||||
await outboxRequeueCommand.run?.({ args: { "event-id": "evt-1", json: true } } as never);
|
||||
|
||||
expect(consoleMock.success).not.toHaveBeenCalled();
|
||||
expect(consoleMock.error).not.toHaveBeenCalled();
|
||||
expect(consoleMock.warn).toHaveBeenCalledWith("careful");
|
||||
});
|
||||
|
||||
it("catches lib exceptions and reports a human error in text mode", async () => {
|
||||
runById.mockRejectedValueOnce(new Error("db down"));
|
||||
|
||||
await outboxRequeueCommand.run?.({ args: { "event-id": "evt-1" } } as never);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("outbox requeue failed: db down");
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it("catches lib exceptions and emits a JSON failure envelope in JSON mode", async () => {
|
||||
runBulk.mockRejectedValueOnce("boom");
|
||||
|
||||
await outboxRequeueCommand.run?.({
|
||||
args: { type: "a.b.c", since: "2026-05-01T00:00:00Z", json: true },
|
||||
} as never);
|
||||
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(
|
||||
JSON.stringify({ ok: false, reason: "exception", message: "boom" }),
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `toolctrl-cli outbox requeue` — re-queue failed (or dead-letter) outbox
|
||||
* `hivegrid-cli outbox requeue` — re-queue failed (or dead-letter) outbox
|
||||
* events back into the dispatcher's pending pool.
|
||||
*
|
||||
* Two modes:
|
||||
@@ -11,7 +11,7 @@
|
||||
* to perform the writes.
|
||||
*
|
||||
* Output: human summary by default, JSON when `--json` is set. The CLI
|
||||
* uses `@toolctrl/db` directly so the worker process does not need to
|
||||
* uses `@hivegrid/db` directly so the worker process does not need to
|
||||
* be reachable.
|
||||
*/
|
||||
import { defineCommand } from "citty";
|
||||
@@ -95,7 +95,7 @@ export const outboxRequeueCommand = defineCommand({
|
||||
return;
|
||||
}
|
||||
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient() as unknown as OutboxRequeueClient;
|
||||
const output = makeOutput(json);
|
||||
|
||||
|
||||
+3
-3
@@ -36,10 +36,10 @@ function getPluginCliMocks(): PluginCliMocks {
|
||||
return global.__pluginCliMocks__;
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => getPluginCliMocks().db,
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
publishAuditEventViaOutbox: getPluginCliMocks().publishAuditEventViaOutbox,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
@@ -52,7 +52,7 @@ vi.mock("consola", () => ({
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { stampPluginCapabilityUseChain, verifyPluginCapabilityUseChain, type PluginCapabilityUseChainRow } from "@toolctrl/plugin-runtime";
|
||||
import { stampPluginCapabilityUseChain, verifyPluginCapabilityUseChain, type PluginCapabilityUseChainRow } from "@hivegrid/plugin-runtime";
|
||||
import { pluginsCommand } from "./index.js";
|
||||
import { pluginsEnableCommand } from "./toggle.js";
|
||||
import { pluginsUninstallCommand } from "./uninstall.js";
|
||||
|
||||
+4
-4
@@ -3,8 +3,8 @@ import {
|
||||
getUnavailablePluginCapabilityNames,
|
||||
isCapabilityGrantScopeSatisfied,
|
||||
type PluginManifest,
|
||||
} from "@toolctrl/plugin-runtime";
|
||||
import { resolvePluginLifecycleRuntimeEnv, type EnvRecord } from "@toolctrl/config";
|
||||
} from "@hivegrid/plugin-runtime";
|
||||
import { resolvePluginLifecycleRuntimeEnv, type EnvRecord } from "@hivegrid/config";
|
||||
|
||||
export class CliPluginLifecycleError extends Error {
|
||||
public override readonly name = "CliPluginLifecycleError";
|
||||
@@ -159,7 +159,7 @@ export async function setPluginEnabledViaLifecycle(args: {
|
||||
assertCliProductionCapabilitiesAvailable(args.env, manifestCapabilities(row));
|
||||
await assertEnableConsentSatisfied(args.db, row, args.env);
|
||||
}
|
||||
const { publishAuditEventViaOutbox } = await import("@toolctrl/db/audit-events.server");
|
||||
const { publishAuditEventViaOutbox } = await import("@hivegrid/db/audit-events.server");
|
||||
return await args.db.$transaction(async (tx) => {
|
||||
const updated = await tx.plugin.update({
|
||||
where: { id: row.id },
|
||||
@@ -185,7 +185,7 @@ export async function setPluginEnabledViaLifecycle(args: {
|
||||
|
||||
export async function uninstallPluginViaLifecycle(args: { db: PluginLifecycleDb; tenantId: string; pluginId: string }): Promise<PluginRow> {
|
||||
const row = await findInstalledPlugin(args.db, args);
|
||||
const { publishAuditEventViaOutbox } = await import("@toolctrl/db/audit-events.server");
|
||||
const { publishAuditEventViaOutbox } = await import("@hivegrid/db/audit-events.server");
|
||||
return await args.db.$transaction(async (tx) => {
|
||||
const deleted = await tx.plugin.delete({ where: { id: row.id } });
|
||||
await publishAuditEventViaOutbox(tx as never, {
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
PLUGIN_CAPABILITY_NAMES,
|
||||
type PluginCapabilityName,
|
||||
parsePluginManifest,
|
||||
} from "@toolctrl/plugin-runtime";
|
||||
} from "@hivegrid/plugin-runtime";
|
||||
|
||||
export interface LintFinding {
|
||||
readonly severity: "error" | "warn";
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type PluginRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pluginId: string;
|
||||
version: string;
|
||||
enabled: boolean;
|
||||
installedAt: Date;
|
||||
};
|
||||
|
||||
const dbMock = {
|
||||
plugin: {
|
||||
findMany: vi.fn<() => Promise<PluginRow[]>>(),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
info: vi.fn(),
|
||||
log: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { pluginsListCommand } from "./list.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
describe("plugins list command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.plugin.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("lists all rows with ON/OFF state when no filters are supplied", async () => {
|
||||
dbMock.plugin.findMany.mockResolvedValueOnce([
|
||||
{
|
||||
id: "row_1",
|
||||
tenantId: "tenant_a",
|
||||
pluginId: "com.acme.crm",
|
||||
version: "1.2.3",
|
||||
enabled: true,
|
||||
installedAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "row_2",
|
||||
tenantId: "tenant_b",
|
||||
pluginId: "com.acme.forms",
|
||||
version: "0.9.0",
|
||||
enabled: false,
|
||||
installedAt: new Date("2026-05-02T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await pluginsListCommand.run?.({ args: {} } as never);
|
||||
|
||||
expect(dbMock.plugin.findMany).toHaveBeenCalledWith({
|
||||
where: {},
|
||||
orderBy: [{ tenantId: "asc" }, { pluginId: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
pluginId: true,
|
||||
version: true,
|
||||
enabled: true,
|
||||
installedAt: true,
|
||||
},
|
||||
});
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^ON .*tenant_a.*com\.acme\.crm.*v1\.2\.3/u));
|
||||
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^OFF.*tenant_b.*com\.acme\.forms.*v0\.9\.0/u));
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("2 plugin row(s) listed.");
|
||||
});
|
||||
|
||||
it("narrows the query to a single tenant and only-enabled rows", async () => {
|
||||
dbMock.plugin.findMany.mockResolvedValueOnce([
|
||||
{
|
||||
id: "row_1",
|
||||
tenantId: "tenant_a",
|
||||
pluginId: "com.acme.crm",
|
||||
version: "1.0.0",
|
||||
enabled: true,
|
||||
installedAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await pluginsListCommand.run?.({ args: { tenantId: "tenant_a", enabled: "true" } } as never);
|
||||
|
||||
expect(dbMock.plugin.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { tenantId: "tenant_a", enabled: true } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("filters to disabled rows when enabled=false", async () => {
|
||||
await pluginsListCommand.run?.({ args: { enabled: "false" } } as never);
|
||||
|
||||
expect(dbMock.plugin.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { enabled: false } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores a blank tenantId and an unrecognised enabled value", async () => {
|
||||
await pluginsListCommand.run?.({ args: { tenantId: "", enabled: "maybe" } } as never);
|
||||
|
||||
expect(dbMock.plugin.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: {} }));
|
||||
});
|
||||
|
||||
it("prints an info message and no summary when nothing matches", async () => {
|
||||
await pluginsListCommand.run?.({ args: { tenantId: "tenant_x" } } as never);
|
||||
|
||||
expect(consoleMock.info).toHaveBeenCalledWith("No installed plugins matched the filter.");
|
||||
expect(consoleMock.success).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ export const pluginsListCommand = defineCommand({
|
||||
},
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const where: Record<string, unknown> = {};
|
||||
if (typeof args.tenantId === "string" && args.tenantId.length > 0) {
|
||||
|
||||
+2
-2
@@ -32,10 +32,10 @@ describe("renderPluginScaffold", () => {
|
||||
expect(() => renderPluginScaffold({ name: "x", targetDir: "/tmp", publisher: "TOP" })).toThrow(/reverse-DNS/u);
|
||||
});
|
||||
|
||||
test("source file imports from @toolctrl/plugin-sdk", () => {
|
||||
test("source file imports from @hivegrid/plugin-sdk", () => {
|
||||
const files = renderPluginScaffold({ name: "x", targetDir: "/tmp" });
|
||||
const src = files.find((f) => f.path === "src/index.ts");
|
||||
expect(src?.contents).toContain('from "@toolctrl/plugin-sdk"');
|
||||
expect(src?.contents).toContain('from "@hivegrid/plugin-sdk"');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+12
-12
@@ -4,7 +4,7 @@
|
||||
* Materialises a plugin starter under `<targetDir>/<name>/` containing:
|
||||
* - plugin.toml (manifest seed with placeholder hashes)
|
||||
* - src/index.ts (HookHandler example)
|
||||
* - package.json (depends on @toolctrl/plugin-sdk)
|
||||
* - package.json (depends on @hivegrid/plugin-sdk)
|
||||
* - tsconfig.json (strict mode, ES2022)
|
||||
* - README.md (next-step instructions for the plugin author)
|
||||
*
|
||||
@@ -35,7 +35,7 @@ const PLUGIN_ID_PATTERN = /^[a-z]+(\.[a-z0-9-]+){1,}$/u;
|
||||
|
||||
export function renderPluginScaffold(options: ScaffoldOptions): ReadonlyArray<ScaffoldFile> {
|
||||
const name = options.name;
|
||||
const description = options.description ?? `Toolctrl plugin: ${name}`;
|
||||
const description = options.description ?? `HiveGrid plugin: ${name}`;
|
||||
const publisher = options.publisher ?? "example.author";
|
||||
const pluginId = `${publisher}.${name}`;
|
||||
if (!PLUGIN_NAME_PATTERN.test(name)) {
|
||||
@@ -66,7 +66,7 @@ name = "onHello"
|
||||
export = "handleHello"
|
||||
`;
|
||||
|
||||
const source = `import { defineHook, type HookHandler } from "@toolctrl/plugin-sdk";
|
||||
const source = `import { defineHook, type HookHandler } from "@hivegrid/plugin-sdk";
|
||||
|
||||
/**
|
||||
* Hook handler — invoked when the host emits the "onHello" event for
|
||||
@@ -90,12 +90,12 @@ export const handleHello: HookHandler<{ name: string }, { greeting: string }> =
|
||||
},
|
||||
"scripts": {
|
||||
"build": "echo 'wire your wasm toolchain here (asc / cargo / etc) — see docs/plugins/cli-reference.md#build'",
|
||||
"lint": "toolctrl-cli plugins lint",
|
||||
"sign": "toolctrl-cli plugins sign --manifest plugin.toml",
|
||||
"pack": "toolctrl-cli plugins publish --manifest plugin.toml"
|
||||
"lint": "hivegrid-cli plugins lint",
|
||||
"sign": "hivegrid-cli plugins sign --manifest plugin.toml",
|
||||
"pack": "hivegrid-cli plugins publish --manifest plugin.toml"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@toolctrl/plugin-sdk": "workspace:*",
|
||||
"@hivegrid/plugin-sdk": "workspace:*",
|
||||
"typescript": "^5.3.2"
|
||||
}
|
||||
}
|
||||
@@ -117,16 +117,16 @@ export const handleHello: HookHandler<{ name: string }, { greeting: string }> =
|
||||
|
||||
const readme = `# ${name}
|
||||
|
||||
Scaffolded with \`toolctrl-cli plugins scaffold\`.
|
||||
Scaffolded with \`hivegrid-cli plugins scaffold\`.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. Implement \`src/index.ts\` against \`@toolctrl/plugin-sdk\`.
|
||||
1. Implement \`src/index.ts\` against \`@hivegrid/plugin-sdk\`.
|
||||
2. Build to wasm with your chosen toolchain (AssemblyScript / TinyGo / Rust).
|
||||
3. Generate an ed25519 keypair (out-of-band — see docs/plugins/security-best-practices.md).
|
||||
4. \`toolctrl-cli plugins lint\` — validate the manifest.
|
||||
5. \`toolctrl-cli plugins sign --key <path> --key-id <id> --manifest plugin.toml\`.
|
||||
6. \`toolctrl-cli plugins publish --manifest plugin.toml\` — emit deployable tarball.
|
||||
4. \`hivegrid-cli plugins lint\` — validate the manifest.
|
||||
5. \`hivegrid-cli plugins sign --key <path> --key-id <id> --manifest plugin.toml\`.
|
||||
6. \`hivegrid-cli plugins publish --manifest plugin.toml\` — emit deployable tarball.
|
||||
|
||||
See \`docs/plugins/\` in the host repo for the full author guide.
|
||||
`;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { generateKeyPairSync, createPrivateKey, verify as cryptoVerify } from "node:crypto";
|
||||
import { verifyPluginSignature } from "@toolctrl/plugin-runtime";
|
||||
import { verifyPluginSignature } from "@hivegrid/plugin-runtime";
|
||||
import { canonicalManifestBytes, signPluginArtifact } from "./sign.js";
|
||||
|
||||
function ed25519PemPair(): { privatePem: string; publicSpkiDer: Buffer } {
|
||||
|
||||
@@ -20,7 +20,7 @@ import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
import { createHash, sign as cryptoSign, createPrivateKey, createPublicKey } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { canonicalPluginSignaturePayload } from "@toolctrl/plugin-runtime";
|
||||
import { canonicalPluginSignaturePayload } from "@hivegrid/plugin-runtime";
|
||||
|
||||
export interface SignPluginInput {
|
||||
/** Raw wasm bytes. */
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import consola from "consola";
|
||||
import { CliPluginLifecycleError, setPluginEnabledViaLifecycle } from "./lifecycle.js";
|
||||
|
||||
async function setEnabled(opts: { tenantId: string; pluginId: string; enabled: boolean }): Promise<void> {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
try {
|
||||
await setPluginEnabledViaLifecycle({
|
||||
db: getDbClient() as never,
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ export const pluginsUninstallCommand = defineCommand({
|
||||
return;
|
||||
}
|
||||
}
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
try {
|
||||
await uninstallPluginViaLifecycle({ db: getDbClient() as never, tenantId, pluginId });
|
||||
consola.success(`Plugin ${pluginId} uninstalled from tenant ${tenantId}.`);
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import type { PluginCapabilityUseChainRow, VerifyChainResult } from "@toolctrl/plugin-runtime";
|
||||
import type { PluginCapabilityUseChainRow, VerifyChainResult } from "@hivegrid/plugin-runtime";
|
||||
|
||||
const PLUGIN_AUDIT_VERIFY_BATCH_SIZE = 5_000;
|
||||
|
||||
@@ -107,8 +107,8 @@ export const pluginsVerifyAuditChainCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, default: false, description: "Emit one JSON object instead of human-readable text." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getReadDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { verifyPluginCapabilityUseChain } = await import("@toolctrl/plugin-runtime");
|
||||
const { getReadDbClient } = await import("@hivegrid/db/client.server");
|
||||
const { verifyPluginCapabilityUseChain } = await import("@hivegrid/plugin-runtime");
|
||||
const db = getReadDbClient();
|
||||
|
||||
async function* readRows(opts: {
|
||||
|
||||
+7
-4
@@ -5,9 +5,8 @@ import {
|
||||
BULK_REINDEX_SUPPORTED_INDEX_NAMES,
|
||||
crmContactsIndex,
|
||||
kbArticlesIndex,
|
||||
rowsIndex,
|
||||
usersIndex,
|
||||
} from "@toolctrl/search";
|
||||
} from "@hivegrid/search";
|
||||
import { enqueueReindexEvents, selectIndexes, selectTenants } from "./reindex.js";
|
||||
|
||||
describe("selectIndexes", () => {
|
||||
@@ -20,7 +19,6 @@ describe("selectIndexes", () => {
|
||||
it("returns the matching schema when a known name is passed", () => {
|
||||
expect(selectIndexes("kb-articles")).toEqual([kbArticlesIndex]);
|
||||
expect(selectIndexes("crm-contacts")).toEqual([crmContactsIndex]);
|
||||
expect(selectIndexes("rows")).toEqual([rowsIndex]);
|
||||
expect(selectIndexes("users")).toEqual([usersIndex]);
|
||||
});
|
||||
|
||||
@@ -29,7 +27,12 @@ describe("selectIndexes", () => {
|
||||
(name) => !(BULK_REINDEX_SUPPORTED_INDEX_NAMES as readonly string[]).includes(name)
|
||||
);
|
||||
|
||||
expect(unsupportedCatalogNames).toEqual(["entities"]);
|
||||
// `files`, `tasks`, `hr-directory` and `hr-locations` are cataloged in
|
||||
// ALL_SEARCH_INDEXES but intentionally have no bulk-reindex pager (not in
|
||||
// BULK_REINDEX_SUPPORTED_INDEX_NAMES), so they must reject in selectIndexes.
|
||||
// HR (P17 — AK-P17a) follows the same per-event-only pattern as `tasks`; a
|
||||
// bulk-reindex pager for HR would be follow-up work.
|
||||
expect(unsupportedCatalogNames).toEqual(["files", "tasks", "hr-directory", "hr-locations"]);
|
||||
for (const name of unsupportedCatalogNames) {
|
||||
expect(() => selectIndexes(name)).toThrow(/Unsupported search reindex target/);
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@
|
||||
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
import { BULK_REINDEX_SUPPORTED_INDEXES, BULK_REINDEX_SUPPORTED_INDEX_NAMES, searchEventType, type SearchIndexSchema } from "@toolctrl/search";
|
||||
import { BULK_REINDEX_SUPPORTED_INDEXES, BULK_REINDEX_SUPPORTED_INDEX_NAMES, searchEventType, type SearchIndexSchema } from "@hivegrid/search";
|
||||
|
||||
export interface ReindexEnqueueResult {
|
||||
readonly indexName: string;
|
||||
@@ -85,7 +85,7 @@ export const searchReindexCommand = defineCommand({
|
||||
// Lazy-load the Prisma-backed publish so the CLI binary does not pull
|
||||
// in @prisma/client at import time. Imports happen here, inside the
|
||||
// run handler, after argument parsing.
|
||||
const [{ getDbClient }, dbOutbox] = await Promise.all([import("@toolctrl/db/client.server"), import("@toolctrl/db/outbox")]);
|
||||
const [{ getDbClient }, dbOutbox] = await Promise.all([import("@hivegrid/db/client.server"), import("@hivegrid/db/outbox")]);
|
||||
const prisma = getDbClient();
|
||||
const tenantIds = await resolveTenantIds(prisma, tenantArg);
|
||||
if (tenantIds.length === 0) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Marketing-Funnel Phase 3 (Phase 05 #80) — shared helpers for the
|
||||
* `toolctrl-cli sequences` subcommands. Kept here so each command file
|
||||
* `hivegrid-cli sequences` subcommands. Kept here so each command file
|
||||
* is a thin defineCommand wrapper over the testable pure functions.
|
||||
*/
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ export const sequencesDisableCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, description: "Emit JSON result." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const id = String(args.id);
|
||||
const existing = await prisma.emailSequence.findFirst({ where: { id }, select: { id: true, isEnabled: true } });
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ export const sequencesEnableCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, description: "Emit JSON result." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const id = String(args.id);
|
||||
const existing = await prisma.emailSequence.findFirst({ where: { id }, select: { id: true, isEnabled: true } });
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ const dbMock = {
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ export const sequencesListCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, description: "Emit JSON instead of human-readable rows." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const sequences = await prisma.emailSequence.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ const dbMock = {
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ export const sequencesStartRunCommand = defineCommand({
|
||||
else consola.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const sequence = await prisma.emailSequence.findFirst({ where: { id: sequenceId } });
|
||||
if (!sequence) {
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ const dbMock = {
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ export const sequencesStatsCommand = defineCommand({
|
||||
json: { type: "boolean", required: false, description: "Emit JSON instead of human-readable rows." },
|
||||
},
|
||||
async run({ args }) {
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const prisma = getDbClient();
|
||||
const sequences = await prisma.emailSequence.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type SequenceRecord = { id: string; isEnabled: boolean };
|
||||
|
||||
const dbMock = {
|
||||
emailSequence: {
|
||||
findFirst: vi.fn<() => Promise<SequenceRecord | null>>(),
|
||||
update: vi.fn<() => Promise<SequenceRecord>>(),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: () => dbMock,
|
||||
}));
|
||||
vi.mock("consola", () => ({
|
||||
default: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import consola from "consola";
|
||||
import { sequencesDisableCommand } from "./disable.js";
|
||||
import { sequencesEnableCommand } from "./enable.js";
|
||||
|
||||
const consoleMock = vi.mocked(consola);
|
||||
|
||||
function mockProcessExit() {
|
||||
return vi.spyOn(process, "exit").mockImplementation((code?: string | number | null) => {
|
||||
throw new Error(`process.exit(${String(code)})`);
|
||||
});
|
||||
}
|
||||
|
||||
describe("sequences enable command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.emailSequence.findFirst.mockResolvedValue(null);
|
||||
dbMock.emailSequence.update.mockResolvedValue({ id: "seq_1", isEnabled: true });
|
||||
});
|
||||
|
||||
it("flips a disabled sequence to enabled and confirms", async () => {
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: false });
|
||||
|
||||
await sequencesEnableCommand.run?.({ args: { id: "seq_1" } } as never);
|
||||
|
||||
expect(dbMock.emailSequence.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "seq_1" },
|
||||
select: { id: true, isEnabled: true },
|
||||
});
|
||||
expect(dbMock.emailSequence.update).toHaveBeenCalledWith({
|
||||
where: { id: "seq_1" },
|
||||
data: { isEnabled: true },
|
||||
});
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("Sequence seq_1 enabled.");
|
||||
});
|
||||
|
||||
it("is a no-op for an already enabled sequence", async () => {
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: true });
|
||||
|
||||
await sequencesEnableCommand.run?.({ args: { id: "seq_1" } } as never);
|
||||
|
||||
expect(consoleMock.info).toHaveBeenCalledWith("Sequence seq_1 already enabled.");
|
||||
expect(dbMock.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits a no-op JSON result for an already enabled sequence", async () => {
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: true });
|
||||
|
||||
await sequencesEnableCommand.run?.({ args: { id: "seq_1", json: true } } as never);
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ ok: true, updated: false, id: "seq_1" });
|
||||
expect(dbMock.emailSequence.update).not.toHaveBeenCalled();
|
||||
stdoutSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("emits an updated JSON result after enabling", async () => {
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: false });
|
||||
|
||||
await sequencesEnableCommand.run?.({ args: { id: "seq_1", json: true } } as never);
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ ok: true, updated: true, id: "seq_1" });
|
||||
stdoutSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("exits non-zero with an error when the sequence is missing", async () => {
|
||||
const exitSpy = mockProcessExit();
|
||||
|
||||
await expect(sequencesEnableCommand.run?.({ args: { id: "ghost" } } as never)).rejects.toThrow(
|
||||
"process.exit(1)",
|
||||
);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("No sequence with id ghost");
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("exits non-zero with a JSON not_found payload when missing", async () => {
|
||||
const exitSpy = mockProcessExit();
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
|
||||
await expect(
|
||||
sequencesEnableCommand.run?.({ args: { id: "ghost", json: true } } as never),
|
||||
).rejects.toThrow("process.exit(1)");
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({
|
||||
ok: false,
|
||||
reason: "not_found",
|
||||
id: "ghost",
|
||||
});
|
||||
expect(consoleMock.error).not.toHaveBeenCalled();
|
||||
stdoutSpy.mockRestore();
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sequences disable command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.emailSequence.findFirst.mockResolvedValue(null);
|
||||
dbMock.emailSequence.update.mockResolvedValue({ id: "seq_1", isEnabled: false });
|
||||
});
|
||||
|
||||
it("flips an enabled sequence to disabled and confirms", async () => {
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: true });
|
||||
|
||||
await sequencesDisableCommand.run?.({ args: { id: "seq_1" } } as never);
|
||||
|
||||
expect(dbMock.emailSequence.update).toHaveBeenCalledWith({
|
||||
where: { id: "seq_1" },
|
||||
data: { isEnabled: false },
|
||||
});
|
||||
expect(consoleMock.success).toHaveBeenCalledWith("Sequence seq_1 disabled.");
|
||||
});
|
||||
|
||||
it("is a no-op for an already disabled sequence", async () => {
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: false });
|
||||
|
||||
await sequencesDisableCommand.run?.({ args: { id: "seq_1" } } as never);
|
||||
|
||||
expect(consoleMock.info).toHaveBeenCalledWith("Sequence seq_1 already disabled.");
|
||||
expect(dbMock.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits an updated JSON result after disabling", async () => {
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: true });
|
||||
|
||||
await sequencesDisableCommand.run?.({ args: { id: "seq_1", json: true } } as never);
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ ok: true, updated: true, id: "seq_1" });
|
||||
stdoutSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("emits a no-op JSON result for an already disabled sequence", async () => {
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
dbMock.emailSequence.findFirst.mockResolvedValueOnce({ id: "seq_1", isEnabled: false });
|
||||
|
||||
await sequencesDisableCommand.run?.({ args: { id: "seq_1", json: true } } as never);
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ ok: true, updated: false, id: "seq_1" });
|
||||
expect(dbMock.emailSequence.update).not.toHaveBeenCalled();
|
||||
stdoutSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("exits non-zero with an error when the sequence is missing", async () => {
|
||||
const exitSpy = mockProcessExit();
|
||||
|
||||
await expect(sequencesDisableCommand.run?.({ args: { id: "ghost" } } as never)).rejects.toThrow(
|
||||
"process.exit(1)",
|
||||
);
|
||||
|
||||
expect(consoleMock.error).toHaveBeenCalledWith("No sequence with id ghost");
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("exits non-zero with a JSON not_found payload when missing", async () => {
|
||||
const exitSpy = mockProcessExit();
|
||||
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
|
||||
await expect(
|
||||
sequencesDisableCommand.run?.({ args: { id: "ghost", json: true } } as never),
|
||||
).rejects.toThrow("process.exit(1)");
|
||||
|
||||
expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({
|
||||
ok: false,
|
||||
reason: "not_found",
|
||||
id: "ghost",
|
||||
});
|
||||
expect(consoleMock.error).not.toHaveBeenCalled();
|
||||
stdoutSpy.mockRestore();
|
||||
exitSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
+6
-6
@@ -76,15 +76,15 @@ describe("anonymize", () => {
|
||||
expect(row.fromUrl).toMatch(/^https:\/\/anonymized\.test\//u);
|
||||
});
|
||||
|
||||
it("rewrites Stripe customer/subscription ids with anon prefix", () => {
|
||||
it("rewrites billing customer/subscription ids with anon prefix", () => {
|
||||
const row = anonymizeRow(
|
||||
FULL_ANONYMIZED_PROFILE,
|
||||
"TenantSubscription",
|
||||
{ stripeCustomerId: "cus_real", stripeSubscriptionId: "sub_real" },
|
||||
{ billingProviderCustomerId: "cus_real", billingProviderSubscriptionId: "sub_real" },
|
||||
ctx,
|
||||
);
|
||||
expect(row.stripeCustomerId).toMatch(/^cus_anon[0-9a-f]{8}$/u);
|
||||
expect(row.stripeSubscriptionId).toMatch(/^sub_anon[0-9a-f]{8}$/u);
|
||||
expect(row.billingProviderCustomerId).toMatch(/^cus_anon[0-9a-f]{8}$/u);
|
||||
expect(row.billingProviderSubscriptionId).toMatch(/^sub_anon[0-9a-f]{8}$/u);
|
||||
});
|
||||
|
||||
it("redacts secrets to [REDACTED]", () => {
|
||||
@@ -102,7 +102,7 @@ describe("anonymize", () => {
|
||||
const row = anonymizeRow(
|
||||
FULL_ANONYMIZED_PROFILE,
|
||||
"TenantSubscription",
|
||||
{ stripeCustomerId: "cus_real", planTier: "pro", active: true },
|
||||
{ billingProviderCustomerId: "cus_real", planTier: "pro", active: true },
|
||||
ctx,
|
||||
);
|
||||
expect(row.planTier).toBe("pro");
|
||||
@@ -156,7 +156,7 @@ describe("anonymize", () => {
|
||||
|
||||
describe("none profile", () => {
|
||||
it("passes everything through unchanged", () => {
|
||||
const original = { email: "alice@example.com", stripeCustomerId: "cus_real" };
|
||||
const original = { email: "alice@example.com", billingProviderCustomerId: "cus_real" };
|
||||
const row = anonymizeRow(NONE_PROFILE, "TenantSubscription", original, {
|
||||
...ctx,
|
||||
profileName: "none",
|
||||
|
||||
+12
-12
@@ -30,10 +30,10 @@ export type FieldStrategy =
|
||||
| "address-country"
|
||||
| "zip-code"
|
||||
| "ip-address"
|
||||
| "stripe-customer-id"
|
||||
| "stripe-subscription-id"
|
||||
| "stripe-payment-method-id"
|
||||
| "stripe-id-generic"
|
||||
| "billing-customer-id"
|
||||
| "billing-subscription-id"
|
||||
| "payment-method-id"
|
||||
| "payment-id-generic"
|
||||
| "url-rewrite"
|
||||
| "avatar-url"
|
||||
| "redact"
|
||||
@@ -122,14 +122,14 @@ export const FULL_ANONYMIZED_PROFILE: AnonymizationProfile = {
|
||||
textBody: "redact",
|
||||
},
|
||||
TenantSubscription: {
|
||||
stripeCustomerId: "stripe-customer-id",
|
||||
stripeSubscriptionId: "stripe-subscription-id",
|
||||
billingProviderCustomerId: "billing-customer-id",
|
||||
billingProviderSubscriptionId: "billing-subscription-id",
|
||||
},
|
||||
TenantProductConfiguration: {
|
||||
stripeAccountId: "stripe-id-generic",
|
||||
paymentProviderAccountId: "payment-id-generic",
|
||||
},
|
||||
Credit: {
|
||||
stripeInvoiceId: "stripe-id-generic",
|
||||
providerInvoiceId: "payment-id-generic",
|
||||
},
|
||||
WorkflowCredential: {
|
||||
secret: "redact",
|
||||
@@ -345,13 +345,13 @@ export function applyStrategy(
|
||||
return anonZip(value, ctx);
|
||||
case "ip-address":
|
||||
return anonIp(value, ctx);
|
||||
case "stripe-customer-id":
|
||||
case "billing-customer-id":
|
||||
return `cus_anon${seededHex(value, ctx, 8)}`;
|
||||
case "stripe-subscription-id":
|
||||
case "billing-subscription-id":
|
||||
return `sub_anon${seededHex(value, ctx, 8)}`;
|
||||
case "stripe-payment-method-id":
|
||||
case "payment-method-id":
|
||||
return `pm_anon${seededHex(value, ctx, 8)}`;
|
||||
case "stripe-id-generic":
|
||||
case "payment-id-generic":
|
||||
return `anon_${seededHex(value, ctx, 12)}`;
|
||||
case "url-rewrite":
|
||||
return `https://anonymized.test/${seededHex(value, ctx, 10)}`;
|
||||
|
||||
+2
-2
@@ -35,10 +35,10 @@ describe("resolveTenantSnapshotConfig", () => {
|
||||
|
||||
it("threads STORAGE_BUCKET and optional prefix through", () => {
|
||||
const cfg = resolveTenantSnapshotConfig({
|
||||
STORAGE_BUCKET: "boilerplate-files",
|
||||
STORAGE_BUCKET: "hivegrid-files",
|
||||
TENANT_SNAPSHOT_STORAGE_PREFIX: "tenants/abc/",
|
||||
});
|
||||
expect(cfg.appStorageBucket).toBe("boilerplate-files");
|
||||
expect(cfg.appStorageBucket).toBe("hivegrid-files");
|
||||
expect(cfg.storagePrefix).toBe("tenants/abc/");
|
||||
});
|
||||
|
||||
|
||||
+4
-1
@@ -48,11 +48,14 @@ describe("collectAndWriteGlobals", () => {
|
||||
ctx: { salt: "deadbeef", profileName: "full-anonymized" },
|
||||
});
|
||||
|
||||
expect(result.entries).toHaveLength(1); // just User today
|
||||
expect(result.entries).toHaveLength(2); // User + McpOAuthClient today
|
||||
const userEntry = result.entries.find((e) => e.model === "User");
|
||||
expect(userEntry).toBeDefined();
|
||||
expect(userEntry?.rowCount).toBe(0);
|
||||
expect(userEntry?.path).toBe("globals/User.jsonl");
|
||||
const clientEntry = result.entries.find((e) => e.model === "McpOAuthClient");
|
||||
expect(clientEntry).toBeDefined();
|
||||
expect(clientEntry?.rowCount).toBe(0);
|
||||
expect(calls).toHaveLength(0);
|
||||
const userFile = await readFile(join(globalsDir, "User.jsonl"), "utf8");
|
||||
expect(userFile).toBe("");
|
||||
|
||||
+3
-3
@@ -65,13 +65,13 @@ describe("parseSchemaScalarTypes", () => {
|
||||
expect(collab?.fields.get("ydocState")).toBe("Bytes");
|
||||
});
|
||||
|
||||
it("captures RowValue.numberValue as Decimal (nullable + non-tenant-scoped)", () => {
|
||||
it("captures IpAddress.latitude as Decimal (nullable + non-tenant-scoped)", () => {
|
||||
// Use a Decimal field that actually exists in the schema. Decimal
|
||||
// columns are rare in tenant-scoped models today — the codec must
|
||||
// still parse them so non-tenant-scoped models referenced indirectly
|
||||
// (or future schema growth) decode correctly.
|
||||
const rowValue = map.get("RowValue");
|
||||
expect(rowValue?.fields.get("numberValue")).toBe("Decimal");
|
||||
const ipAddress = map.get("IpAddress");
|
||||
expect(ipAddress?.fields.get("latitude")).toBe("Decimal");
|
||||
});
|
||||
|
||||
it("captures TenantUser.createdAt as DateTime", () => {
|
||||
|
||||
+234
-24
@@ -43,18 +43,16 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
{ model: "MetricLog", tenantField: "tenantId", schema: "core.prisma" },
|
||||
{ model: "Widget", tenantField: "tenantId", schema: "core.prisma" },
|
||||
|
||||
// entityBuilder.prisma
|
||||
{ model: "Property", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "EntityTemplate", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "EntityView", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "EntityGroupConfiguration", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "Row", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "RowPermission", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "TenantSettingsRow", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
{ model: "FormulaLog", tenantField: "tenantId", schema: "entityBuilder.prisma" },
|
||||
// publicApi.prisma (VR-P22b) — incoming endpoint before ingestion logs,
|
||||
// outgoing subscription before delivery logs (FK subscriptionId, Cascade).
|
||||
{ model: "PublicIncomingWebhookEndpoint", tenantField: "tenantId", schema: "publicApi.prisma" },
|
||||
{ model: "PublicWebhookIngestionLog", tenantField: "tenantId", schema: "publicApi.prisma" },
|
||||
{ model: "PublicWebhookSubscription", tenantField: "tenantId", schema: "publicApi.prisma" },
|
||||
{ model: "PublicWebhookDeliveryLog", tenantField: "tenantId", schema: "publicApi.prisma" },
|
||||
|
||||
// subscriptions.prisma
|
||||
{ model: "TenantSubscription", tenantField: "tenantId", schema: "subscriptions.prisma" },
|
||||
{ model: "TenantSubscriptionUsageRecord", tenantField: "tenantId", schema: "subscriptions.prisma" },
|
||||
{ model: "TenantFeatureOverride", tenantField: "tenantId", schema: "subscriptions.prisma" },
|
||||
{ model: "TenantProductConfiguration", tenantField: "tenantId", schema: "subscriptions.prisma" },
|
||||
{ model: "Credit", tenantField: "tenantId", schema: "subscriptions.prisma" },
|
||||
@@ -64,6 +62,20 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
{ model: "TenantInboundAddress", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "Campaign", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "OutboundEmail", tenantField: "tenantId", schema: "email.prisma" },
|
||||
// AK-P14a — email foundation (sending domain, suppression, templates).
|
||||
{ model: "TenantSendingDomain", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "EmailSuppressionList", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "EmailTemplate", tenantField: "tenantId", schema: "email.prisma" },
|
||||
// AK-P14b — email marketing (segments, A/B variants, consent, unsubscribe).
|
||||
// Ordering: RecipientSegment before SegmentSnapshotMember (FK segmentId,
|
||||
// Cascade); CampaignVariant references Campaign (listed above). kontaktId /
|
||||
// campaignId on Consent/Unsubscribe are BARE scalars (no @relation), so they
|
||||
// are NOT collected as globals.
|
||||
{ model: "RecipientSegment", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "SegmentSnapshotMember", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "CampaignVariant", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "KontaktMarketingConsent", tenantField: "tenantId", schema: "email.prisma" },
|
||||
{ model: "Unsubscribe", tenantField: "tenantId", schema: "email.prisma" },
|
||||
|
||||
// workflows.prisma
|
||||
{ model: "Workflow", tenantField: "tenantId", schema: "workflows.prisma" },
|
||||
@@ -71,10 +83,23 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
{ model: "WorkflowVariable", tenantField: "tenantId", schema: "workflows.prisma" },
|
||||
{ model: "WorkflowCredential", tenantField: "tenantId", schema: "workflows.prisma" },
|
||||
|
||||
// appsEngine.prisma
|
||||
{ model: "App", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
{ model: "AppSyncRun", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
// automation.prisma (R-P12a: typed automation engine foundation)
|
||||
{ model: "AutomationRule", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationRuleStep", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationExecution", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationStepExecution", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationCredential", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationTemplate", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
{ model: "AutomationTriggerMeter", tenantField: "tenantId", schema: "automation.prisma" },
|
||||
|
||||
// appsEngine.prisma (R-P5: App is GLOBAL/no-tenant; tenant-scoped rows below)
|
||||
{ model: "DataConnection", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
{ model: "AppSyncRun", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
{ model: "AppSyncRunLog", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
{ model: "AppSyncItem", tenantField: "tenantId", schema: "appsEngine.prisma" },
|
||||
|
||||
// crypto.prisma (R-P5 Phase 1)
|
||||
{ model: "TenantEncryptionKey", tenantField: "tenantId", schema: "crypto.prisma" },
|
||||
|
||||
// featureFlags.prisma
|
||||
{ model: "FeatureFlag", tenantField: "tenantId", schema: "featureFlags.prisma" },
|
||||
@@ -89,6 +114,12 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
// queue.prisma
|
||||
{ model: "ExportJob", tenantField: "tenantId", schema: "queue.prisma" },
|
||||
|
||||
// gdpr.prisma (AK-P21) — privacy exports, tenant deletion requests and AVV
|
||||
// acceptance history. Subprocessor is a global catalog, not tenant-scoped.
|
||||
{ model: "GdprExportJob", tenantField: "tenantId", schema: "gdpr.prisma" },
|
||||
{ model: "TenantDeletionRequest", tenantField: "tenantId", schema: "gdpr.prisma" },
|
||||
{ model: "AvvAcceptance", tenantField: "tenantId", schema: "gdpr.prisma" },
|
||||
|
||||
// knowledgeBase.prisma
|
||||
{ model: "KnowledgeBase", tenantField: "tenantId", schema: "knowledgeBase.prisma" },
|
||||
|
||||
@@ -98,6 +129,7 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
|
||||
// onboarding.prisma
|
||||
{ model: "OnboardingSession", tenantField: "tenantId", schema: "onboarding.prisma" },
|
||||
{ model: "OnboardingDemoProvisioning", tenantField: "tenantId", schema: "onboarding.prisma" },
|
||||
|
||||
// portals.prisma
|
||||
{ model: "Portal", tenantField: "tenantId", schema: "portals.prisma" },
|
||||
@@ -108,7 +140,11 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
|
||||
// formWidget.prisma (Phase 05 #58 — embeddable form widget)
|
||||
{ model: "Form", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
{ model: "FormField", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
{ model: "FormSubmission", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
{ model: "FormFile", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
{ model: "FormAction", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
{ model: "FormActionLog", tenantField: "tenantId", schema: "formWidget.prisma" },
|
||||
|
||||
// outbox.prisma (tenantId is nullable — system-wide events use NULL)
|
||||
{ model: "OutboxEvent", tenantField: "tenantId", schema: "outbox.prisma" },
|
||||
@@ -134,6 +170,177 @@ export const TENANT_SCOPED_MODELS: readonly TenantScopedModel[] = [
|
||||
|
||||
// notifications.prisma — push tokens
|
||||
{ model: "DeviceToken", tenantField: "tenantId", schema: "notifications.prisma" },
|
||||
|
||||
// admin.prisma — operator note on a tenant (authorUserId → User global,
|
||||
// onDelete:SetNull; tenant Tenant relation = snapshot root).
|
||||
{ model: "AdminTenantNote", tenantField: "tenantId", schema: "admin.prisma" },
|
||||
|
||||
// files.prisma (P4 — AK-P4a). Direct `tenantId String` scalar. Ordering:
|
||||
// File before FileEntityLink (FK fileId, Cascade), FileUpload before
|
||||
// FileUploadChunk (FK uploadId, Cascade). createdByUserId/assignedToUserId
|
||||
// are intentionally BARE scalars (no DB-level FK), so they are NOT collected
|
||||
// as globals.
|
||||
{ model: "File", tenantField: "tenantId", schema: "files.prisma" },
|
||||
{ model: "FileEntityLink", tenantField: "tenantId", schema: "files.prisma" },
|
||||
{ model: "FileUpload", tenantField: "tenantId", schema: "files.prisma" },
|
||||
{ model: "FileUploadChunk", tenantField: "tenantId", schema: "files.prisma" },
|
||||
|
||||
// tasks.prisma (P4 — AK-P4b). Direct `tenantId String` scalar. Ordering:
|
||||
// Task before TaskWatcher (FK taskId, Cascade). createdByUserId/
|
||||
// assignedToUserId/assignedToGroupId are BARE scalars (no DB-level FK).
|
||||
{ model: "Task", tenantField: "tenantId", schema: "tasks.prisma" },
|
||||
{ model: "TaskWatcher", tenantField: "tenantId", schema: "tasks.prisma" },
|
||||
|
||||
// entityLinks.prisma (P4 — AK-P4b). Generic polymorphic link; all
|
||||
// references are bare scalars (no @relation), so no globals to collect.
|
||||
{ model: "EntityLink", tenantField: "tenantId", schema: "entityLinks.prisma" },
|
||||
|
||||
// hr.prisma (P17 — AK-P17a). Direct `tenantId String` scalar. AD-21: all
|
||||
// cross-model references (location_id, employee_user_id, manager_user_id,
|
||||
// file_id) are BARE scalars (no @relation), so they are NOT collected as
|
||||
// globals. Ordering: EmployeePasswordSafeVault before its Entry/Access (FK
|
||||
// vaultId, Cascade); the rest are independent.
|
||||
{ model: "HrEmployeeProfile", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrLocation", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrEmployeeDocument", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrResource", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrQuickLink", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeePasswordSafeVault", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeePasswordSafeEntry", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeePasswordSafeAccess", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
// P17 HR-Hub workflows (AK-P17b). Ordering: a parent before its Cascade
|
||||
// children (HrAnnouncement before Read/Reaction/Comment; EmployeeUploadReminder
|
||||
// before Dispatch; HrSurvey before Item/Submission; HrRequestTemplate before
|
||||
// HrRequest [SetNull]). The rest are independent.
|
||||
{ model: "EmployeeVacationRequest", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeeSickLeaveReport", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeePayslip", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrAnnouncement", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrAnnouncementRead", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrAnnouncementReaction", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrAnnouncementComment", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeeUploadReminder", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "EmployeeUploadReminderDispatch", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrRequestTemplate", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrRequest", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrSurvey", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrSurveyItem", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
{ model: "HrSurveySubmission", tenantField: "tenantId", schema: "hr.prisma" },
|
||||
|
||||
// crm.prisma (P6 — R-P6). Direct `tenantId String` scalar. AD-21: all
|
||||
// cross-model references (createdByUserId, zustaendigerUserId) are BARE scalars
|
||||
// (no @relation), so they are NOT collected as globals. Ordering: a referenced
|
||||
// model before its Cascade children — Adresse before Kontakt (FK adresseId),
|
||||
// Kontakt before KontaktEmail/Telefon/Relation (FK kontaktId/von-/zuKontaktId),
|
||||
// CustomFieldDefinition before CustomFieldValue (FK definitionId),
|
||||
// Tag before TagAssignment (FK tagId).
|
||||
{ model: "Adresse", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "Kontakt", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "KontaktEmail", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "KontaktTelefon", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "KontaktRelation", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "CustomFieldDefinition", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "CustomFieldValue", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "Tag", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
{ model: "TagAssignment", tenantField: "tenantId", schema: "crm.prisma" },
|
||||
|
||||
// calendar.prisma (AK-P16a) — Connection before its Cascade children
|
||||
// (Event/Mapping/SyncCursor/WebhookEvent/Conflict via FK connectionId),
|
||||
// CalendarEvent before CalendarEventMapping (FK internalEventId).
|
||||
{ model: "CalendarConnection", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
{ model: "CalendarEvent", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
{ model: "CalendarEventMapping", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
{ model: "CalendarSyncCursor", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
{ model: "CalendarWebhookEvent", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
{ model: "CalendarConflict", tenantField: "tenantId", schema: "calendar.prisma" },
|
||||
|
||||
// email-inbox.prisma (VA-P23) — Mailbox before its Cascade children
|
||||
// (Message/SyncCursor/WebhookEvent via FK mailboxId).
|
||||
{ model: "EmailIntegrationMailbox", tenantField: "tenantId", schema: "email-inbox.prisma" },
|
||||
{ model: "EmailIntegrationMessage", tenantField: "tenantId", schema: "email-inbox.prisma" },
|
||||
{ model: "EmailIntegrationSyncCursor", tenantField: "tenantId", schema: "email-inbox.prisma" },
|
||||
{ model: "EmailIntegrationWebhookEvent", tenantField: "tenantId", schema: "email-inbox.prisma" },
|
||||
|
||||
// booking.prisma (AK-P16b) — BookingPage before its Cascade children
|
||||
// (BookingPageProvider/Appointment via FK bookingPageId). AvailabilityRule/
|
||||
// Exception are standalone (provider linked by bare scalar, no FK).
|
||||
{ model: "BookingPage", tenantField: "tenantId", schema: "booking.prisma" },
|
||||
{ model: "BookingPageProvider", tenantField: "tenantId", schema: "booking.prisma" },
|
||||
{ model: "AvailabilityRule", tenantField: "tenantId", schema: "booking.prisma" },
|
||||
{ model: "AvailabilityException", tenantField: "tenantId", schema: "booking.prisma" },
|
||||
{ model: "Appointment", tenantField: "tenantId", schema: "booking.prisma" },
|
||||
|
||||
// signature.prisma (AK-P16d) — provider connection before documents; document
|
||||
// before signers/events (Cascade by documentId). Cross-module references
|
||||
// (Projekt/DataConnection/File/Kontakt/User) are BARE scalars.
|
||||
{ model: "SignatureProviderConnection", tenantField: "tenantId", schema: "signature.prisma" },
|
||||
{ model: "ProjektSignatureDocument", tenantField: "tenantId", schema: "signature.prisma" },
|
||||
{ model: "ProjektSignatureSigner", tenantField: "tenantId", schema: "signature.prisma" },
|
||||
{ model: "SignatureEvent", tenantField: "tenantId", schema: "signature.prisma" },
|
||||
|
||||
// leads.prisma (P7 — R-P7). Direct `tenantId String` scalar. Cross-module
|
||||
// references (createdByUserId, zustaendigerUserId, konvertiertProjektId,
|
||||
// verknuepfterKontaktId) are BARE scalars. Ordering: LeadSource before InboxLead
|
||||
// (FK sourceId SetNull), config independent.
|
||||
{ model: "LeadSource", tenantField: "tenantId", schema: "leads.prisma" },
|
||||
{ model: "InboxLead", tenantField: "tenantId", schema: "leads.prisma" },
|
||||
{ model: "LeadAntiSpamConfig", tenantField: "tenantId", schema: "leads.prisma" },
|
||||
|
||||
// projekt.prisma (P8 — R-P8a). Direct `tenantId String` scalar. Ordering:
|
||||
// HiveNumberSeq independent; Pipeline before Cascade children; PipelineStage
|
||||
// and LostReason before Projekt; Projekt before history/contact children.
|
||||
// User/Kontakt/Lead/Adresse references are BARE scalars and not collected as globals.
|
||||
{ model: "HiveNumberSeq", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "Pipeline", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "PipelineStage", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "PipelineAccess", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "PipelineFieldConfig", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "PipelineFieldVisibility", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "LostReason", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "Projekt", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "ProjektStageChange", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "PipelineAggregateSnapshot", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
{ model: "ProjektKontakt", tenantField: "tenantId", schema: "projekt.prisma" },
|
||||
|
||||
// auftrag.prisma (P9 — R-P9a/R-P9b). Order-specific sub-areas on the same
|
||||
// Projekt core. Projekt/User/Group/File/Form/Calendar references are BARE
|
||||
// scalars and not collected as globals; restore Projekt first via
|
||||
// projekt.prisma rows. Ordering keeps parents before Cascade/Restrict
|
||||
// children (ProjektChecklist before Item, ScheduleEntry before Conflict,
|
||||
// AbnahmeProtokoll before Signatur).
|
||||
{ model: "ProjektMitglied", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ProjektTermin", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "Rechnung", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ProjektChecklist", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ProjektChecklistItem", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "AuftragPipelineStageConfig", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "AcceptanceFormTemplate", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ProjectTemplate", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ScheduleEntry", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "ScheduleConflict", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "AbnahmeProtokoll", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "AbnahmeSignatur", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
{ model: "OfflineSyncMutation", tenantField: "tenantId", schema: "auftrag.prisma" },
|
||||
|
||||
// search.prisma (P11 — R-P11a). Polymorphic entity references are bare
|
||||
// scalars; RecentSearch references User by bare userId for per-user recents.
|
||||
{ model: "SearchIndexEntry", tenantField: "tenantId", schema: "search.prisma" },
|
||||
{ model: "RecentSearch", tenantField: "tenantId", schema: "search.prisma" },
|
||||
|
||||
// dashboard.prisma (P11 — R-P11b). Dashboard before layout and widget
|
||||
// instances (Cascade by dashboardId); userId is a bare scalar.
|
||||
{ model: "Dashboard", tenantField: "tenantId", schema: "dashboard.prisma" },
|
||||
{ model: "DashboardLayout", tenantField: "tenantId", schema: "dashboard.prisma" },
|
||||
{ model: "WidgetInstance", tenantField: "tenantId", schema: "dashboard.prisma" },
|
||||
|
||||
// mcpOAuth.prisma (VR-MCP). OAuth grants carry bare tenantId/tenantSlug
|
||||
// scalars (userId is a bare scalar too); McpOAuthClient is a global
|
||||
// (dynamic client registration, no tenantId) and lives under
|
||||
// GLOBAL_REFERENCED_MODELS. RefreshToken before AccessToken
|
||||
// (AccessToken.refreshTokenId is a nullable SetNull FK).
|
||||
{ model: "McpOAuthAuthorizationCode", tenantField: "tenantId", schema: "mcpOAuth.prisma" },
|
||||
{ model: "McpOAuthRefreshToken", tenantField: "tenantId", schema: "mcpOAuth.prisma" },
|
||||
{ model: "McpOAuthAccessToken", tenantField: "tenantId", schema: "mcpOAuth.prisma" },
|
||||
];
|
||||
|
||||
/** Constant-time check that a model name is known to be tenant-scoped. */
|
||||
@@ -162,8 +369,7 @@ export function tenantScopedModelNames(): readonly string[] {
|
||||
* staging verification flagged as broken (`TenantUser`, `TenantIpAddress`,
|
||||
* `UserRole`, `Event`, `Log`, `SupportTicket`). All other globals reached
|
||||
* from tenant-scoped models in the current schema are platform-level
|
||||
* catalogs (`Entity`, `Formula`, `EntityGroup`, `Onboarding`,
|
||||
* `RowComment`, `WorkflowBlock`) — these are expected to
|
||||
* catalogs (`Onboarding`, `WorkflowBlock`) — these are expected to
|
||||
* already exist on the target deployment because they are seeded by
|
||||
* migrations/setup scripts, NOT by tenant onboarding. Their absence on
|
||||
* an "empty" target is therefore an operator-environment issue, not a
|
||||
@@ -193,16 +399,16 @@ export const GLOBAL_REFERENCED_MODELS: readonly GlobalReferencedModel[] = [
|
||||
schema: "accounts.prisma",
|
||||
referencedBy: [
|
||||
// (kept in alphabetical order by source model for review-friendliness)
|
||||
{ model: "AdminTenantNote", fkColumn: "authorUserId" },
|
||||
{ model: "ApiKey", fkColumn: "createdByUserId" },
|
||||
{ model: "App", fkColumn: "installedByUserId" },
|
||||
{ model: "AppSyncRun", fkColumn: "createdByUserId" },
|
||||
{ model: "DataConnection", fkColumn: "createdByUserId" },
|
||||
{ model: "ProjektSignatureDocument", fkColumn: "createdByUserId" },
|
||||
{ model: "SignatureEvent", fkColumn: "actorUserId" },
|
||||
{ model: "Credit", fkColumn: "userId" },
|
||||
{ model: "DeviceToken", fkColumn: "userId" },
|
||||
{ model: "EntityView", fkColumn: "createdByUserId" },
|
||||
{ model: "EntityView", fkColumn: "userId" },
|
||||
{ model: "Event", fkColumn: "userId" },
|
||||
{ model: "Feedback", fkColumn: "userId" },
|
||||
{ model: "FormulaLog", fkColumn: "userId" },
|
||||
{ model: "Group", fkColumn: "createdByUserId" },
|
||||
{ model: "ImpersonationAudit", fkColumn: "actorUserId" },
|
||||
{ model: "ImpersonationAudit", fkColumn: "targetUserId" },
|
||||
@@ -211,8 +417,6 @@ export const GLOBAL_REFERENCED_MODELS: readonly GlobalReferencedModel[] = [
|
||||
{ model: "NotificationDelivery", fkColumn: "userId" },
|
||||
{ model: "OnboardingSession", fkColumn: "userId" },
|
||||
{ model: "Portal", fkColumn: "createdByUserId" },
|
||||
{ model: "Row", fkColumn: "createdByUserId" },
|
||||
{ model: "RowPermission", fkColumn: "userId" },
|
||||
{ model: "Site", fkColumn: "createdByUserId" },
|
||||
{ model: "SupportTicket", fkColumn: "userId" },
|
||||
{ model: "TenantIpAddress", fkColumn: "userId" },
|
||||
@@ -229,6 +433,15 @@ export const GLOBAL_REFERENCED_MODELS: readonly GlobalReferencedModel[] = [
|
||||
{ model: "WorkflowVariable", fkColumn: "userId" },
|
||||
],
|
||||
},
|
||||
{
|
||||
model: "McpOAuthClient",
|
||||
schema: "mcpOAuth.prisma",
|
||||
referencedBy: [
|
||||
{ model: "McpOAuthAccessToken", fkColumn: "clientId" },
|
||||
{ model: "McpOAuthAuthorizationCode", fkColumn: "clientId" },
|
||||
{ model: "McpOAuthRefreshToken", fkColumn: "clientId" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -238,11 +451,8 @@ export const GLOBAL_REFERENCED_MODELS: readonly GlobalReferencedModel[] = [
|
||||
* test can prove every global reference is consciously categorized.
|
||||
*/
|
||||
export const PLATFORM_CATALOG_GLOBALS: readonly string[] = [
|
||||
"Entity",
|
||||
"EntityGroup",
|
||||
"Formula",
|
||||
"App", // R-P5: global integrations catalog (seeded at deployment), referenced by DataConnection.appId
|
||||
"Onboarding",
|
||||
"RowComment",
|
||||
"WorkflowBlock",
|
||||
];
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Bridge between the generic, dependency-injected `PrismaRunner` /
|
||||
* `PrismaRestoreRunner` interfaces and a real `@toolctrl/db` PrismaClient.
|
||||
* `PrismaRestoreRunner` interfaces and a real `@hivegrid/db` PrismaClient.
|
||||
*
|
||||
* Kept separate from `snapshot.ts` / `restore.ts` so those modules stay
|
||||
* Prisma-free (and trivially unit-testable with plain fakes). The CLI bin
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* The Prisma layer is dependency-injected via the `PrismaRestoreRunner`
|
||||
* interface so the CLI package stays free of `@prisma/client`. Production
|
||||
* callers wire up a real client in `bin/toolctrl-cli.mjs`; tests pass a fake.
|
||||
* callers wire up a real client in `bin/hivegrid-cli.mjs`; tests pass a fake.
|
||||
*
|
||||
* Foreign-key remapping: only the `tenantId` column is rewritten. Row primary
|
||||
* keys are preserved (the snapshot is intended to land in a separate
|
||||
@@ -435,7 +435,7 @@ export const tenantRestoreCommand = defineCommand({
|
||||
const { resolveTenantSnapshotConfig } = await import("./env.js");
|
||||
const cfg = resolveTenantSnapshotConfig(process.env as Record<string, string | undefined>);
|
||||
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const { createPrismaRestoreRunner } = await import("./prisma-runner.js");
|
||||
const { parseSchemaScalarTypes } = await import("./json-codec.js");
|
||||
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ import { mkdtemp } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createDbClient } from "@toolctrl/db/client.server";
|
||||
import { createDbClient } from "@hivegrid/db/client.server";
|
||||
import { runTenantSnapshot } from "./snapshot.js";
|
||||
import { runTenantRestore } from "./restore.js";
|
||||
import { createPrismaSnapshotRunner, createPrismaRestoreRunner } from "./prisma-runner.js";
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
*
|
||||
* The Prisma layer is dependency-injected via the `PrismaRunner` interface so
|
||||
* the CLI package stays free of `@prisma/client`. The production entrypoint
|
||||
* (`bin/toolctrl-cli.mjs` of the consumer) wires up the real `PrismaClient`;
|
||||
* (`bin/hivegrid-cli.mjs` of the consumer) wires up the real `PrismaClient`;
|
||||
* tests pass a fake.
|
||||
*/
|
||||
import { defineCommand } from "citty";
|
||||
@@ -511,7 +511,7 @@ export const tenantSnapshotCommand = defineCommand({
|
||||
const { resolveTenantSnapshotConfig } = await import("./env.js");
|
||||
const cfg = resolveTenantSnapshotConfig(process.env as Record<string, string | undefined>);
|
||||
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const { getDbClient } = await import("@hivegrid/db/client.server");
|
||||
const { createPrismaSnapshotRunner } = await import("./prisma-runner.js");
|
||||
const prisma = getDbClient();
|
||||
const runner = createPrismaSnapshotRunner(prisma as unknown as Record<string, unknown>);
|
||||
|
||||
@@ -11,7 +11,7 @@ async function resolveValue<T>(value: T | (() => T) | (() => Promise<T>)): Promi
|
||||
describe("cli main command", () => {
|
||||
it("exposes the backup subcommand tree", async () => {
|
||||
const mainMeta = await resolveValue(mainCommand.meta);
|
||||
expect(mainMeta).toMatchObject({ name: "toolctrl-cli" });
|
||||
expect(mainMeta).toMatchObject({ name: "hivegrid-cli" });
|
||||
|
||||
const backupMeta = await resolveValue(backupCommand.meta);
|
||||
expect(backupMeta).toMatchObject({ name: "backup" });
|
||||
|
||||
@@ -17,9 +17,9 @@ import { tenantCommand } from "./commands/tenant/index.js";
|
||||
|
||||
export const mainCommand = defineCommand({
|
||||
meta: {
|
||||
name: "toolctrl-cli",
|
||||
name: "hivegrid-cli",
|
||||
version: "0.0.0",
|
||||
description: "ToolCTRL operator CLI (audit, backup, restore, verify, tenant snapshots, search reindex, feature-flags, forms, leads, marketing, create, add, ops).",
|
||||
description: "HiveGrid operator CLI (audit, backup, restore, verify, tenant snapshots, search reindex, feature-flags, forms, leads, marketing, create, add, ops).",
|
||||
},
|
||||
subCommands: {
|
||||
add: addCommand,
|
||||
|
||||
Reference in new issue
Block a user