refactor(marketing-pages)!: delete marketing-pages demo feature
Veect retrofit (ADR-027): fourth slice of the demo-content removal. Deletes packages/marketing-pages whole and prunes every composition edge in one commit: core-api router mount + dep, core-cms collection/global composition + dep + regenerated Payload types, web-next bindAll (prod + dev-seed) + tests + about page + Tailwind source + transpilePackages + dep, cms/core-cms payload config test assertions, marketing-page e2e spec, tsconfig paths, fallow ignore entry, anchor-guard + generator e2e feature lists, compliance data-map + retention-policy regeneration, lockfile prune, and feature-list doc entries (CLAUDE.md, AGENTS.md, glossary, app/feature AGENTS.md). Event teardown: marketing-pages was the sole consumer of auth.user.signed-up (welcome-email handler + job). The handler, its Payload tasks, and the bus subscription all lived inside the package's own binders, so they die with it — no other package wires the subscription. Auth's manifest `publishes` stays untouched: a publisher with zero consumers is legal (pnpm conformance only fails on orphan consumers, verified green). The app-level sign-up-welcome-email test asserted the marketing-pages mailer stays empty without a bus; it is deleted with the feature, and the now-unused test-only bind-state helpers in web-next bind-production.ts go with it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016j8z4VHjedXDTjEDNg7qHK
This commit is contained in:
@@ -29,7 +29,6 @@
|
||||
"@trpc/server",
|
||||
"superjson",
|
||||
"@repo/core-api",
|
||||
"@repo/marketing-pages",
|
||||
"@repo/navigation",
|
||||
"@repo/core-testing",
|
||||
"http-server",
|
||||
|
||||
10
AGENTS.md
10
AGENTS.md
@@ -37,7 +37,6 @@ See `docs/guides/runbook.md` for the full workflow.
|
||||
| `@repo/core-cms` | core-composition | Payload config aggregator — imports `@repo/<feature>/cms` only |
|
||||
| `@repo/core-trpc` | core-composition | Frontend tRPC client + framework-specific providers (Next.js, TanStack) |
|
||||
| `@repo/auth` | feature | Users collection + sign-in/up/out |
|
||||
| `@repo/marketing-pages` | feature | Pages collection + SiteSettings global |
|
||||
| `@repo/navigation` | feature | Header global |
|
||||
| `@repo/core-eslint` | tooling | Shared ESLint 9 flat configs (base, next, react-internal, boundaries) |
|
||||
| `@repo/core-typescript` | tooling | Shared TypeScript base configs + Vitest base |
|
||||
@@ -52,7 +51,7 @@ See `docs/guides/runbook.md` for the full workflow.
|
||||
- **app** (3 packages) — `apps/web-next`, `apps/cms`, `apps/storybook`
|
||||
- **core-composition** (3 packages) — `packages/core-api`, `core-cms`, `core-trpc`
|
||||
- **core** (1–2 packages) — `packages/core-shared`; `core-ui` is optional (scaffold with `pnpm turbo gen core-package ui`)
|
||||
- **feature** (3 packages) — `packages/auth`, `marketing-pages`, `navigation`
|
||||
- **feature** (2 packages) — `packages/auth`, `navigation`
|
||||
- **tooling** (3 packages) — `packages/core-eslint`, `core-typescript`, `core-testing`
|
||||
|
||||
### Allowed dependency directions
|
||||
@@ -383,7 +382,6 @@ export async function bindAllProduction(): Promise<void> {
|
||||
};
|
||||
|
||||
bindProductionAuth(ctx);
|
||||
bindProductionMarketingPages(ctx);
|
||||
bindProductionNavigation(ctx);
|
||||
}
|
||||
|
||||
@@ -404,11 +402,11 @@ export async function bindAllDevSeed(): Promise<void> {
|
||||
};
|
||||
|
||||
await bindDevSeedAuth(ctx);
|
||||
// ... (same for marketing-pages, navigation)
|
||||
// ... (same for navigation)
|
||||
}
|
||||
```
|
||||
|
||||
Actual function names: `bindProductionAuth`, `bindProductionMarketingPages`, `bindProductionNavigation`.
|
||||
Actual function names: `bindProductionAuth`, `bindProductionNavigation`.
|
||||
|
||||
Each feature binder signature is `(ctx: BindProductionContext): void` for production and `(ctx: BindContext): Promise<void>` for dev-seed. Required ctx fields: `tracer`, `logger`. Production-only: `config`. Optional: `bus`, `queue`, `realtime`, `realtimeRegistry`.
|
||||
|
||||
@@ -574,6 +572,6 @@ Per-package documentation lives in each `AGENTS.md`:
|
||||
- `packages/core-shared/AGENTS.md`
|
||||
- `packages/core-api/AGENTS.md`, `core-cms/AGENTS.md`, `core-trpc/AGENTS.md`
|
||||
- `packages/core-ui/AGENTS.md` (optional — generated by `pnpm turbo gen core-package ui`; see `turbo/generators/templates/core-package/ui/AGENTS.md.hbs`)
|
||||
- `packages/auth/AGENTS.md`, `marketing-pages/AGENTS.md`, `navigation/AGENTS.md`
|
||||
- `packages/auth/AGENTS.md`, `navigation/AGENTS.md`
|
||||
- `packages/core-eslint/AGENTS.md`, `core-typescript/AGENTS.md`, `core-testing/AGENTS.md`
|
||||
- `apps/cms/AGENTS.md`, `web-next/AGENTS.md`, `storybook/AGENTS.md`
|
||||
|
||||
@@ -44,7 +44,7 @@ See `docs/guides/tdd-workflow.md` for the full cycle.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Turborepo + pnpm monorepo organized by vertical features. Each feature (`auth`, `marketing-pages`, `navigation`) owns its Clean Architecture layers. Must-have core packages (`core-shared`, `core-cms`, `core-api`) provide foundation; five optional core packages (`core-realtime`, `core-events`, `core-trpc`, `core-ui`, `core-audit`) scaffold on demand via `pnpm turbo gen core-package <name>` (see `docs/architecture/template-tiers.md`). Two tooling packages (`core-eslint`, `core-typescript`) provide shared configs. Workspace boundaries are enforced by ESLint (lint-time) and Turborepo (build-graph time). Supports Next.js and TanStack Start as frontend frameworks, Payload CMS for content management, and comprehensive agent-optimized documentation.
|
||||
Turborepo + pnpm monorepo organized by vertical features. Each feature (`auth`, `navigation`) owns its Clean Architecture layers. Must-have core packages (`core-shared`, `core-cms`, `core-api`) provide foundation; five optional core packages (`core-realtime`, `core-events`, `core-trpc`, `core-ui`, `core-audit`) scaffold on demand via `pnpm turbo gen core-package <name>` (see `docs/architecture/template-tiers.md`). Two tooling packages (`core-eslint`, `core-typescript`) provide shared configs. Workspace boundaries are enforced by ESLint (lint-time) and Turborepo (build-graph time). Supports Next.js and TanStack Start as frontend frameworks, Payload CMS for content management, and comprehensive agent-optimized documentation.
|
||||
|
||||
## Read First
|
||||
|
||||
@@ -95,7 +95,7 @@ See `docs/guides/coverage.md` for the cookbook and ADR-020 for the full rational
|
||||
## Key Conventions
|
||||
|
||||
- **Conventional Commits (non-negotiable)** — Every commit message MUST follow the [Conventional Commits](https://www.conventionalcommits.org/) spec: `<type>(<scope>): <imperative subject>` (≤72 chars). Types: `feat | fix | docs | style | refactor | test | chore | perf | ci | build | revert`. Use `!` after type/scope for breaking changes. Body explains WHY if non-obvious. Examples: `feat(auth): hash password before persisting`, `test(blog): assert article not found error`, `refactor(docs)!: consolidate scaffolding into guides`. The sandcastle implementer + reviewer prompts both enforce this; agents authoring commits autonomously MUST honor it. Commits become versions + changelog entries automatically via release-please (ADR-021 / `docs/guides/releasing.md`).
|
||||
- **Versioning is hybrid (ADR-021)** — Root template (`template-vertical`) + 3 feature packages (`@repo/{auth,marketing-pages,navigation}`) each version independently from `0.1.0`. release-please reads Conventional Commits since the last tag and opens a rolling release PR on every merge to main; merging it cuts per-package tags (`template-v0.2.0`, `auth-v0.1.1`, etc.) + GitHub releases. **Bump targeting is by commit path** — files under `packages/<feature>/**` bump that feature; cross-cutting paths (`docs/`, `scripts/`, `.github/`, root configs) bump the root. Pre-1.0 policy: `feat:` → patch, `feat!:` → minor.
|
||||
- **Versioning is hybrid (ADR-021)** — Root template (`template-vertical`) + 2 feature packages (`@repo/{auth,navigation}`) each version independently from `0.1.0`. release-please reads Conventional Commits since the last tag and opens a rolling release PR on every merge to main; merging it cuts per-package tags (`template-v0.2.0`, `auth-v0.1.1`, etc.) + GitHub releases. **Bump targeting is by commit path** — files under `packages/<feature>/**` bump that feature; cross-cutting paths (`docs/`, `scripts/`, `.github/`, root configs) bump the root. Pre-1.0 policy: `feat:` → patch, `feat!:` → minor.
|
||||
- **Relative imports in `src/`** — Source files use relative paths (`../repositories/...`), not `@/` alias
|
||||
- **`@/` alias in tests** — Test files (`*.test.ts`) use `@/` to import from `src/`
|
||||
- **`vitest.config.ts`** — Every package must define `resolve.alias: { "@": path.resolve(__dirname, "./src") }`
|
||||
@@ -119,7 +119,7 @@ See `docs/guides/coverage.md` for the cookbook and ADR-020 for the full rational
|
||||
- **PII handling is non-negotiable** — `sendDefaultPii: false` everywhere (CI grep gate); replay default-masks all text/inputs/media (allowlist starts empty); `setUser({ id })` only — no email/username; server-side PII scrubbing happens at the OTel processor layer (`PiiScrubSpanProcessor` + `PiiScrubLogRecordProcessor`) before any exporter sees the data (ADR-017 §7)
|
||||
- **Two apps, two Sentry projects** — `WEB_NEXT_SENTRY_DSN`, `CMS_SENTRY_DSN`. The browser DSN uses the `NEXT_PUBLIC_` prefix (web-next)
|
||||
- **Instrumentation binding is orthogonal to repo binding** — `bindAll()`'s Rule 0 (DSN → OTel+Sentry vs Noop) is independent of `USE_DEV_SEED` / `NODE_ENV`. Run `pnpm dev` with `WEB_NEXT_SENTRY_DSN` set to test the integration locally
|
||||
- **Cross-feature events go through `IEventBus` (E0)** — In-feature reactions are direct use-case calls, not bus publishes. The bus is for _crossing_ feature boundaries (e.g. `auth` → `marketing-pages` welcome email)
|
||||
- **Cross-feature events go through `IEventBus` (E0)** — In-feature reactions are direct use-case calls, not bus publishes. The bus is for _crossing_ feature boundaries (e.g. an `auth` signed-up event consumed by another feature)
|
||||
- **Event contracts are public; handlers are private (E1)** — Publisher's `events/<x>.event.ts` is exported from the feature root barrel. Consumer's `events/handlers/on-<publisher>-<event>.handler.ts` is never re-exported (ESLint-enforced via `core-eslint/rules/no-handler-reexport`)
|
||||
- **Jobs are for _deferred_ work, not abstraction (J0)** — Synchronous code stays synchronous. A job exists only when something must run off the request path (latency, retries, cron). Feature packages enqueue via `IJobQueue` only — direct `payload.jobs.queue()` is ESLint-blocked outside `core-shared/jobs/`
|
||||
- **Realtime is for state delivery, not for replacing tRPC (R0)** — Persistent request/response operations belong on tRPC procedures. Use realtime when the server needs to push without a request or the data is too high-frequency for HTTP
|
||||
|
||||
@@ -5,12 +5,12 @@ describe("CMS app payload.config", () => {
|
||||
it("registers all feature collections", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.collections?.map((c) => c.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users"]));
|
||||
});
|
||||
|
||||
it("registers all feature globals", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.globals?.map((g) => g.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["site-settings", "header"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["header"]));
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -26,7 +26,7 @@ pnpm dev --filter @repo/web-next # Next.js on port 3000
|
||||
| ----------------------- | ---------------------------------------------------------------------------------------- |
|
||||
| `src/app/layout.tsx` | Root layout — wraps app with `<Providers>` |
|
||||
| `src/app/providers.tsx` | Client component wrapper (add tRPC/React Query here after scaffolding `@repo/core-trpc`) |
|
||||
| `src/app/page.tsx` | Home page — navigation + marketing content |
|
||||
| `src/app/page.tsx` | Home page |
|
||||
| `e2e/` | Playwright end-to-end tests |
|
||||
|
||||
## tRPC Setup (optional)
|
||||
@@ -104,7 +104,7 @@ Run: `pnpm test:e2e` starts the dev server and runs all `.spec.ts` files.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- **Feature packages:** `packages/{auth,marketing-pages,navigation}/`
|
||||
- **Feature packages:** `packages/{auth,navigation}/`
|
||||
- **tRPC composition:** `packages/core-api/AGENTS.md`
|
||||
- **tRPC client + provider (optional):** scaffold `@repo/core-trpc` first, then see `turbo/generators/templates/core-package/trpc/AGENTS.md.hbs`
|
||||
- **UI components (optional):** scaffold with `pnpm turbo gen core-package ui`, then see `turbo/generators/templates/core-package/ui/AGENTS.md.hbs`
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
test("home page renders site name + nav + article list", async ({ page }) => {
|
||||
test("home page renders heading + nav", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
// Page renders and shows site name
|
||||
// Page renders and shows the heading
|
||||
await expect(page.locator("h1").first()).toBeVisible();
|
||||
// Site name from siteSettings (mock seed: "My App")
|
||||
await expect(page.locator("body")).toContainText(/My App/i);
|
||||
// Nav element is present on the page
|
||||
const nav = page.locator("nav");
|
||||
await expect(nav).toHaveCount(1);
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
test("/about renders the about marketing page", async ({ page }) => {
|
||||
await page.goto("/about");
|
||||
// Either renders the seeded page (h1 = "About us") or "not yet published" message
|
||||
// — both are HTTP 200, so the test only checks it doesn't 500.
|
||||
const status = (await page.context().request.get("/about")).status();
|
||||
expect(status).toBe(200);
|
||||
await expect(page.locator("body")).toBeVisible();
|
||||
});
|
||||
@@ -12,7 +12,6 @@ const nextConfig = {
|
||||
"@repo/core-dsr",
|
||||
"@repo/core-shared",
|
||||
"@repo/core-ui",
|
||||
"@repo/marketing-pages",
|
||||
"@repo/navigation",
|
||||
"@repo/core-trpc",
|
||||
],
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"@repo/core-cms": "workspace:*",
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@repo/core-trpc": "workspace:^",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"@sentry/nextjs": "^10.51.0",
|
||||
"@tailwindcss/postcss": "^4.3.0",
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// Cross-feature event bus proof-of-life (DISABLED — @repo/core-events removed).
|
||||
//
|
||||
// @repo/core-events is now optional. When absent, ctx.bus is undefined, and
|
||||
// bus?.subscribe(...) / bus?.publish(...) calls are no-ops. Cross-feature event
|
||||
// fanout does not occur until core-events is scaffolded via:
|
||||
//
|
||||
// pnpm turbo gen core-package events
|
||||
//
|
||||
// After scaffolding, restore this test and re-wire the bus in bind-production.ts
|
||||
// (see the comment in bindAll()). Until then, signing up does NOT trigger a
|
||||
// welcome email — the mailer queue stays empty.
|
||||
//
|
||||
// Replaced with a reduced test that asserts the no-bus behavior.
|
||||
|
||||
import "reflect-metadata";
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { bindAllDevSeed, __resetBindStateForTests } from "@/server/bind-production";
|
||||
import { authContainer } from "@repo/auth/di/container";
|
||||
import { AUTH_SYMBOLS } from "@repo/auth/di/symbols";
|
||||
import type { ISignUpController } from "@repo/auth";
|
||||
import { marketingPagesContainer } from "@repo/marketing-pages/di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "@repo/marketing-pages/di/symbols";
|
||||
import { RecordingMailerService } from "@repo/marketing-pages/services/recording-mailer";
|
||||
|
||||
describe("e2e: sign-up with no event bus (core-events not scaffolded)", () => {
|
||||
beforeEach(() => {
|
||||
__resetBindStateForTests();
|
||||
});
|
||||
|
||||
it("sign-up succeeds and mailer stays empty (no cross-feature fanout without bus)", async () => {
|
||||
await bindAllDevSeed();
|
||||
|
||||
const mailer = marketingPagesContainer.get<RecordingMailerService>(
|
||||
MARKETING_PAGES_SYMBOLS.IMailerService,
|
||||
);
|
||||
const signUp = authContainer.get<ISignUpController>(AUTH_SYMBOLS.ISignUpController);
|
||||
|
||||
await signUp({
|
||||
username: "testuser",
|
||||
password: "secret_password",
|
||||
confirmPassword: "secret_password",
|
||||
});
|
||||
|
||||
// Without a bus, bus?.subscribe() is a no-op so the event handler never
|
||||
// fires and the mailer receives nothing.
|
||||
await new Promise((r) => setImmediate(r));
|
||||
|
||||
expect(mailer.sent).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { PageContent } from "@repo/marketing-pages/ui";
|
||||
import { bindAll } from "../../server/bind-production";
|
||||
|
||||
export default async function AboutPage() {
|
||||
await bindAll();
|
||||
|
||||
return (
|
||||
<main className="px-6 py-8">
|
||||
<PageContent slug="about" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -7,16 +7,10 @@ vi.mock("payload", () => ({
|
||||
vi.mock("@repo/auth/di/bind-production", () => ({
|
||||
bindProductionAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/marketing-pages/di/bind-production", () => ({
|
||||
bindProductionMarketingPages: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/navigation/di/bind-production", () => ({
|
||||
bindProductionNavigation: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/auth/di/bind-dev-seed", () => ({ bindDevSeedAuth: vi.fn() }));
|
||||
vi.mock("@repo/marketing-pages/di/bind-dev-seed", () => ({
|
||||
bindDevSeedMarketingPages: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/navigation/di/bind-dev-seed", () => ({
|
||||
bindDevSeedNavigation: vi.fn(),
|
||||
}));
|
||||
@@ -39,19 +33,16 @@ describe("bindAllProduction", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("binds all three feature production repos", async () => {
|
||||
it("binds both feature production repos", async () => {
|
||||
const { bindAllProduction } = await import("./bind-production");
|
||||
const { bindProductionAuth } =
|
||||
await import("@repo/auth/di/bind-production");
|
||||
const { bindProductionMarketingPages } =
|
||||
await import("@repo/marketing-pages/di/bind-production");
|
||||
const { bindProductionNavigation } =
|
||||
await import("@repo/navigation/di/bind-production");
|
||||
|
||||
await bindAllProduction();
|
||||
|
||||
expect(bindProductionAuth).toHaveBeenCalledOnce();
|
||||
expect(bindProductionMarketingPages).toHaveBeenCalledOnce();
|
||||
expect(bindProductionNavigation).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
|
||||
@@ -18,10 +18,8 @@ import {
|
||||
} from "@repo/core-shared/jobs";
|
||||
import { NoopRateLimit } from "@repo/core-shared/rate-limit";
|
||||
import { bindProductionAuth } from "@repo/auth/di/bind-production";
|
||||
import { bindProductionMarketingPages } from "@repo/marketing-pages/di/bind-production";
|
||||
import { bindProductionNavigation } from "@repo/navigation/di/bind-production";
|
||||
import { bindDevSeedAuth } from "@repo/auth/di/bind-dev-seed";
|
||||
import { bindDevSeedMarketingPages } from "@repo/marketing-pages/di/bind-dev-seed";
|
||||
import { bindDevSeedNavigation } from "@repo/navigation/di/bind-dev-seed";
|
||||
|
||||
let bindPromise: Promise<void> | null = null;
|
||||
@@ -96,7 +94,6 @@ export async function bindAllProduction(): Promise<void> {
|
||||
};
|
||||
|
||||
bindProductionAuth(ctx);
|
||||
bindProductionMarketingPages(ctx);
|
||||
bindProductionNavigation(ctx);
|
||||
}
|
||||
|
||||
@@ -117,7 +114,6 @@ export async function bindAllDevSeed(): Promise<void> {
|
||||
};
|
||||
|
||||
await bindDevSeedAuth(ctx);
|
||||
await bindDevSeedMarketingPages(ctx);
|
||||
await bindDevSeedNavigation(ctx);
|
||||
}
|
||||
|
||||
@@ -153,19 +149,3 @@ export function bindAll(): Promise<void> {
|
||||
|
||||
return bindPromise;
|
||||
}
|
||||
|
||||
/** Test-only resets — not exported via package. Used by bind-production.test.ts. */
|
||||
export function __resetBindStateForTests(): void {
|
||||
bindPromise = null;
|
||||
resolvedTracer = null;
|
||||
resolvedLogger = null;
|
||||
resolvedQueue = null;
|
||||
}
|
||||
|
||||
/** Test-only accessor for resolved instrumentation. */
|
||||
export function __getInstrumentationForTests(): {
|
||||
tracer: ITracer | null;
|
||||
logger: ILogger | null;
|
||||
} {
|
||||
return { tracer: resolvedTracer, logger: resolvedLogger };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
@import "tailwindcss";
|
||||
@source "../../../../packages/core-ui/src";
|
||||
@source "../../../../packages/navigation/src";
|
||||
@source "../../../../packages/marketing-pages/src";
|
||||
@source "../../../../packages/auth/src";
|
||||
@source "../";
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,10 +2,6 @@
|
||||
# Generated by scripts/compliance/emit-data-map.mjs — do not edit manually.
|
||||
# Run `pnpm compliance:data-map` to regenerate.
|
||||
collections:
|
||||
pages:
|
||||
auth: false
|
||||
piiFields: []
|
||||
slug: pages
|
||||
users:
|
||||
auth: true
|
||||
piiFields:
|
||||
|
||||
@@ -2,13 +2,6 @@
|
||||
# Generated by scripts/compliance/emit-retention-policy.mjs — do not edit manually.
|
||||
# Run `pnpm compliance:retention-policy` to regenerate.
|
||||
collections:
|
||||
pages:
|
||||
postDeletion:
|
||||
action: hard-delete
|
||||
duration: P90D
|
||||
trigger: after-deletion
|
||||
purgeSchedule: monthly
|
||||
slug: pages
|
||||
users:
|
||||
postDeletion:
|
||||
action: hard-delete
|
||||
|
||||
@@ -22,7 +22,7 @@ _Avoid:_ module, library, app (unless specifically `apps/`).
|
||||
The boundary classification on a package (`app`, `core`, `core-composition`, `feature`, `tooling`). Enforced by ESLint (`eslint-plugin-boundaries`) and Turborepo `boundaries`. See `AGENTS.md` → Boundary Rules.
|
||||
|
||||
**Feature** (a.k.a. **feature package**):
|
||||
A vertical slice owning its Clean Architecture layers + integrations under `packages/<name>/`. Currently: `auth`, `marketing-pages`, `navigation`. **In architecture-refactor conversations (the `improve-codebase-architecture` skill), "module" defaults to "feature" — they're the same unit at the highest level of granularity.**
|
||||
A vertical slice owning its Clean Architecture layers + integrations under `packages/<name>/`. Currently: `auth`, `navigation`. **In architecture-refactor conversations (the `improve-codebase-architecture` skill), "module" defaults to "feature" — they're the same unit at the highest level of granularity.**
|
||||
_Avoid:_ domain, vertical (use "feature" or "vertical feature"). "Module" is acceptable inside the refactor skill specifically, where it abstractly covers "anything with interface + implementation" at any scale (use case, controller, repository port, or full feature).
|
||||
|
||||
**Must-have core**:
|
||||
@@ -190,7 +190,7 @@ The commit-message spec mandated by this template — `<type>(<scope>): <imperat
|
||||
The Google-maintained automation that reads Conventional Commits, derives semver bumps, and opens a rolling release PR with version bumps + per-package CHANGELOG entries on every push to main. Configured in `release-please-config.json` + `.release-please-manifest.json`. ADR-021.
|
||||
|
||||
**Hybrid versioning**:
|
||||
The template's versioning strategy (ADR-021) — root template (`template-vertical`) + 3 feature packages (`@repo/{auth,marketing-pages,navigation}`) version independently from `0.1.0`. Core packages, tooling, and apps are NOT versioned (cascade-effect would invalidate the signal).
|
||||
The template's versioning strategy (ADR-021) — root template (`template-vertical`) + 2 feature packages (`@repo/{auth,navigation}`) version independently from `0.1.0`. Core packages, tooling, and apps are NOT versioned (cascade-effect would invalidate the signal).
|
||||
|
||||
**Tag prefix**:
|
||||
The per-package prefix release-please uses to avoid tag collisions in a monorepo — `template-v0.1.0` for the root, `auth-v0.1.0` / etc. for features.
|
||||
|
||||
@@ -151,7 +151,7 @@ tests/
|
||||
|
||||
## What it must NOT import
|
||||
|
||||
- Any other feature package (`@repo/marketing-pages`, `@repo/navigation`, etc.)
|
||||
- Any other feature package (`@repo/navigation`, etc.)
|
||||
- Any app package
|
||||
- `@repo/core-api`, `@repo/core-cms`, `@repo/core-trpc`, `@repo/core-ui` directly; only `@repo/core-shared`
|
||||
> Note: `@repo/core-trpc` and `@repo/core-ui` are optional packages scaffolded via `pnpm turbo gen core-package trpc` / `ui`. If not present, these constraints still apply to any future installation.
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"@repo/core-consent": "workspace:*",
|
||||
"@repo/core-dsr": "workspace:*",
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"@trpc/server": "^11.0.0"
|
||||
},
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { router } from "@repo/core-shared/trpc/init";
|
||||
import { authRouter } from "@repo/auth/api";
|
||||
import { marketingPagesRouter } from "@repo/marketing-pages/api";
|
||||
import { navigationRouter } from "@repo/navigation/api";
|
||||
import { dsrRouter } from "@repo/core-dsr";
|
||||
import { consentRouter } from "@repo/core-consent";
|
||||
|
||||
export const appRouter = router({
|
||||
auth: authRouter,
|
||||
marketingPages: marketingPagesRouter,
|
||||
navigation: navigationRouter,
|
||||
// gen:routers — optional-core routers composed below
|
||||
dsr: dsrRouter,
|
||||
|
||||
@@ -65,11 +65,10 @@ function makeUnauthCaller(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("appRouter composition", () => {
|
||||
it("exposes auth, marketingPages, navigation routers", () => {
|
||||
it("exposes auth, navigation routers", () => {
|
||||
const procedures = appRouter._def.procedures;
|
||||
const keys = Object.keys(procedures);
|
||||
expect(keys.some((k) => k.startsWith("auth."))).toBe(true);
|
||||
expect(keys.some((k) => k.startsWith("marketingPages."))).toBe(true);
|
||||
expect(keys.some((k) => k.startsWith("navigation."))).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
- **`@repo/<feature>/cms`** subpath exports only (to get collections/globals)
|
||||
- e.g., `import { articles } from "@repo/blog/cms"`
|
||||
- e.g., `import { users } from "@repo/auth/cms"`
|
||||
- e.g., `import { pages, siteSettings } from "@repo/marketing-pages/cms"`
|
||||
- e.g., `import { header } from "@repo/navigation/cms"`
|
||||
|
||||
## Must NOT import
|
||||
|
||||
@@ -29,10 +29,12 @@
|
||||
## Public exports
|
||||
|
||||
From `package.json`:
|
||||
|
||||
- `.` — the Payload config (default export) + buildConfig re-export
|
||||
- `./generated-types` — Payload-generated TypeScript types
|
||||
|
||||
Example usage:
|
||||
|
||||
```typescript
|
||||
import { buildConfig } from "@repo/core-cms";
|
||||
// or
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"@payloadcms/db-postgres": "^3.14.0",
|
||||
"@payloadcms/richtext-lexical": "^3.14.0",
|
||||
"@repo/auth": "workspace:*",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"payload": "^3.14.0"
|
||||
},
|
||||
|
||||
@@ -68,7 +68,6 @@ export interface Config {
|
||||
blocks: {};
|
||||
collections: {
|
||||
users: User;
|
||||
pages: Page;
|
||||
"payload-kv": PayloadKv;
|
||||
"payload-locked-documents": PayloadLockedDocument;
|
||||
"payload-preferences": PayloadPreference;
|
||||
@@ -77,7 +76,6 @@ export interface Config {
|
||||
collectionsJoins: {};
|
||||
collectionsSelect: {
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
pages: PagesSelect<false> | PagesSelect<true>;
|
||||
"payload-kv": PayloadKvSelect<false> | PayloadKvSelect<true>;
|
||||
"payload-locked-documents":
|
||||
| PayloadLockedDocumentsSelect<false>
|
||||
@@ -94,11 +92,9 @@ export interface Config {
|
||||
};
|
||||
fallbackLocale: null;
|
||||
globals: {
|
||||
"site-settings": SiteSetting;
|
||||
header: Header;
|
||||
};
|
||||
globalsSelect: {
|
||||
"site-settings": SiteSettingsSelect<false> | SiteSettingsSelect<true>;
|
||||
header: HeaderSelect<false> | HeaderSelect<true>;
|
||||
};
|
||||
locale: null;
|
||||
@@ -165,41 +161,6 @@ export interface User {
|
||||
password?: string | null;
|
||||
collection: "users";
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "pages".
|
||||
*/
|
||||
export interface Page {
|
||||
id: number;
|
||||
title: string;
|
||||
/**
|
||||
* Auto-generated from title if left empty
|
||||
*/
|
||||
slug?: string | null;
|
||||
hero: {
|
||||
heading: string;
|
||||
subheading?: string | null;
|
||||
};
|
||||
layout?:
|
||||
| {
|
||||
title: string;
|
||||
buttonLabel: string;
|
||||
href: string;
|
||||
id?: string | null;
|
||||
blockName?: string | null;
|
||||
blockType: "cta";
|
||||
}[]
|
||||
| null;
|
||||
status: "draft" | "published";
|
||||
publishedAt?: string | null;
|
||||
seo: {
|
||||
title: string;
|
||||
description?: string | null;
|
||||
};
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
_status?: ("draft" | "published") | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "payload-kv".
|
||||
@@ -223,15 +184,10 @@ export interface PayloadKv {
|
||||
*/
|
||||
export interface PayloadLockedDocument {
|
||||
id: number;
|
||||
document?:
|
||||
| ({
|
||||
document?: {
|
||||
relationTo: "users";
|
||||
value: number | User;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: "pages";
|
||||
value: number | Page;
|
||||
} | null);
|
||||
} | null;
|
||||
globalSlug?: string | null;
|
||||
user: {
|
||||
relationTo: "users";
|
||||
@@ -299,44 +255,6 @@ export interface UsersSelect<T extends boolean = true> {
|
||||
expiresAt?: T;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "pages_select".
|
||||
*/
|
||||
export interface PagesSelect<T extends boolean = true> {
|
||||
title?: T;
|
||||
slug?: T;
|
||||
hero?:
|
||||
| T
|
||||
| {
|
||||
heading?: T;
|
||||
subheading?: T;
|
||||
};
|
||||
layout?:
|
||||
| T
|
||||
| {
|
||||
cta?:
|
||||
| T
|
||||
| {
|
||||
title?: T;
|
||||
buttonLabel?: T;
|
||||
href?: T;
|
||||
id?: T;
|
||||
blockName?: T;
|
||||
};
|
||||
};
|
||||
status?: T;
|
||||
publishedAt?: T;
|
||||
seo?:
|
||||
| T
|
||||
| {
|
||||
title?: T;
|
||||
description?: T;
|
||||
};
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
_status?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "payload-kv_select".
|
||||
@@ -377,17 +295,6 @@ export interface PayloadMigrationsSelect<T extends boolean = true> {
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "site-settings".
|
||||
*/
|
||||
export interface SiteSetting {
|
||||
id: number;
|
||||
siteName: string;
|
||||
siteDescription?: string | null;
|
||||
updatedAt?: string | null;
|
||||
createdAt?: string | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "header".
|
||||
@@ -405,17 +312,6 @@ export interface Header {
|
||||
updatedAt?: string | null;
|
||||
createdAt?: string | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "site-settings_select".
|
||||
*/
|
||||
export interface SiteSettingsSelect<T extends boolean = true> {
|
||||
siteName?: T;
|
||||
siteDescription?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
globalType?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "header_select".
|
||||
|
||||
@@ -5,12 +5,12 @@ describe("payloadConfig composition", () => {
|
||||
it("registers all feature collections", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.collections?.map((c) => c.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users"]));
|
||||
});
|
||||
|
||||
it("registers all feature globals", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.globals?.map((g) => g.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["site-settings", "header"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["header"]));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,6 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { users } from "@repo/auth/cms";
|
||||
import { pages, siteSettings } from "@repo/marketing-pages/cms";
|
||||
import { header } from "@repo/navigation/cms";
|
||||
|
||||
const filename = fileURLToPath(import.meta.url);
|
||||
@@ -13,8 +12,8 @@ const dirname = path.dirname(filename);
|
||||
|
||||
export default buildConfig({
|
||||
editor: lexicalEditor(),
|
||||
collections: [users, pages],
|
||||
globals: [siteSettings, header],
|
||||
collections: [users],
|
||||
globals: [header],
|
||||
secret: process.env.PAYLOAD_SECRET || "default-secret-change-me",
|
||||
db: postgresAdapter({
|
||||
pool: {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = join(__dirname, "..", "..");
|
||||
const FEATURES = ["auth", "marketing-pages", "navigation"];
|
||||
const FEATURES = ["auth", "navigation"];
|
||||
const ANCHORS = {
|
||||
"src/index.ts": ["// <gen:events>", "// <gen:realtime-channels>"],
|
||||
"src/di/symbols.ts": [
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
# AGENTS.md — marketing-pages
|
||||
|
||||
Pages collection + SiteSettings global for site-wide metadata. Provides marketing/landing page content, SEO settings, and site configuration via Payload.
|
||||
|
||||
## Overview
|
||||
|
||||
`@repo/marketing-pages` owns: Page and SiteSettings domain models, marketing-pages-scoped errors, `IPagesRepository` + `ISiteSettingsRepository` interfaces, two use cases, two controllers, real Payload-backed repositories, and the tRPC `marketingPagesRouter`. Query builders live in `./ui`.
|
||||
|
||||
## Layer responsibilities
|
||||
|
||||
| Layer | Key files |
|
||||
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **entities/models** | `page.ts` (`Page`, `PageStatus`, `Hero`), `site-settings.ts` (`SiteSettings`) — Zod schemas + types |
|
||||
| **entities/errors** | `page.ts` (PageNotFoundError), `common.ts` (InputParseError) |
|
||||
| **application/use-cases** | `get-page-by-slug.use-case.ts`, `get-site-settings.use-case.ts` — factory functions + exported schemas |
|
||||
| **application/repositories** | `pages.repository.interface.ts`, `site-settings.repository.interface.ts` |
|
||||
| **infrastructure/repositories** | `pages.repository.ts`, `site-settings.repository.ts` (real Payload-backed); `pages.repository.mock.ts`, `site-settings.repository.mock.ts` |
|
||||
| **interface-adapters/controllers** | `get-page-by-slug.controller.ts`, `get-site-settings.controller.ts` — one file per use case |
|
||||
| **di** | `symbols.ts` (MARKETING_PAGES_SYMBOLS), `module.ts`, `container.ts`, `bind-production.ts` |
|
||||
| **integrations/api** | `procedures.ts` (marketingPagesProcedure), `router.ts` (marketingPagesRouter) |
|
||||
| **integrations/cms** | `collections/pages.ts`, `globals/site-settings.ts` — Payload definitions |
|
||||
| **ui** | `src/ui/index.ts` — re-exports `pageBySlugQuery` and `siteSettingsQuery` |
|
||||
|
||||
## Public exports
|
||||
|
||||
| Subpath | Contents |
|
||||
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `.` | `Page`, `PageStatus`, `Hero`, `SiteSettings` types; `PageNotFoundError`, `InputParseError`; all use-case schemas + input/output types + `IXUseCase` aliases; `IXController` type aliases; `MarketingPagesRouter` type |
|
||||
| `./ui` | `pageBySlugQuery`, `siteSettingsQuery` — React Query option builders |
|
||||
| `./api` | `marketingPagesRouter` (tRPC router) |
|
||||
| `./cms` | Payload Pages collection + SiteSettings global |
|
||||
| `./di/bind-production` | `bindProductionMarketingPages(ctx: BindProductionContext)` — swaps mock impls for real Payload-backed ones at app boot |
|
||||
| `./di/bind-dev-seed` | `bindDevSeedMarketingPages(ctx: BindContext)` — replaces the default empty mocks with populated ones for dev / Storybook |
|
||||
| `./di/container` | `marketingPagesContainer` — the per-feature inversify container (consumed by e2e tests + production Payload event-tasks) |
|
||||
| `./di/symbols` | `MARKETING_PAGES_SYMBOLS` — DI symbol registry (consumed by e2e tests + production Payload event-tasks) |
|
||||
| `./services/mailer` | `IMailerService` — interface for the welcome-email seam (ADR-015 proof-of-life) |
|
||||
| `./services/recording-mailer` | `RecordingMailerService` — test / dev-seed mailer that records calls instead of sending |
|
||||
|
||||
## Use-case + controller patterns
|
||||
|
||||
See `CLAUDE.md` Key Conventions and `docs/architecture/overview.md` for the canonical factory templates.
|
||||
|
||||
### Use cases
|
||||
|
||||
| Use case | Input schema | Output schema | Notes |
|
||||
| ------------------------ | ------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `getPageBySlugUseCase` | `getPageBySlugInputSchema` — `{ slug }` | `getPageBySlugOutputSchema` — `pageSchema \| undefined` | Returns `undefined` for missing pages (preserves existing semantics); `PageNotFoundError` mapping is forward-compatible for if/when the use case changes to throw |
|
||||
| `getSiteSettingsUseCase` | `getSiteSettingsInputSchema` — `z.object({}).strict()` (void input) | `getSiteSettingsOutputSchema` — `siteSettingsSchema` | Takes `_input: GetSiteSettingsInput` parameter; always returns settings or throws |
|
||||
|
||||
### Controllers
|
||||
|
||||
Both controllers use identity presenters — `function presenter(value: XOutput) { return value; }`. `getPageBySlugController` return type is `ReturnType<typeof presenter> | undefined` (preserves the missing-page semantics). Both accept `unknown` input and `safeParse` with the use-case's `xInputSchema`, throwing `InputParseError` on failure.
|
||||
|
||||
## Errors → tRPC codes
|
||||
|
||||
| Error class | tRPC code | Thrown by |
|
||||
| ------------------- | ------------- | -------------------------------------------------------------------------------------- |
|
||||
| `InputParseError` | `BAD_REQUEST` | controllers (safeParse failure) |
|
||||
| `PageNotFoundError` | `NOT_FOUND` | forward-compat; current `getPageBySlugUseCase` returns `undefined` instead of throwing |
|
||||
|
||||
Defined in `src/integrations/api/procedures.ts` via `marketingPagesProcedure = t.procedure.use(defineErrorMiddleware([...]))`.
|
||||
|
||||
## Tests
|
||||
|
||||
- **Factories:** `src/__factories__/page.factory.ts`, `src/__factories__/site-settings.factory.ts`
|
||||
- **Contract suites:** `src/__contracts__/pages-repository.contract.ts`, `src/__contracts__/site-settings-repository.contract.ts`
|
||||
- **Unit tests:** colocated `*.test.ts` next to each source file
|
||||
- **Feature integration:** `tests/page-by-slug.feature.test.ts` — full slice: tRPC caller → controller → use case → mock repo
|
||||
- **R25** (output validation): `get-page-by-slug.use-case.test.ts` has a test injecting a malformed page repository mock asserting `.rejects.toBeInstanceOf(ZodError)`. `get-site-settings.use-case.test.ts` uses an inline malformed repository mock (e.g., `{ siteName: "" }` failing `min(1)`) to assert ZodError.
|
||||
- **R26** (router error mapping): `router.test.ts` asserts `BAD_REQUEST` on empty input for `pageBySlug`; confirms `undefined` return for missing slug (use case does not throw `PageNotFoundError` today).
|
||||
- **R27/R28** (presenter shape): both controllers use identity presenters — no reshape test obligation.
|
||||
|
||||
```bash
|
||||
pnpm test --filter @repo/marketing-pages
|
||||
pnpm test --filter @repo/marketing-pages -- --watch
|
||||
```
|
||||
|
||||
See `docs/guides/tdd-workflow.md` for the full cycle.
|
||||
|
||||
## Directory structure
|
||||
|
||||
```
|
||||
src/
|
||||
entities/
|
||||
models/
|
||||
page.ts
|
||||
site-settings.ts
|
||||
errors/
|
||||
page.ts # PageNotFoundError
|
||||
common.ts # InputParseError
|
||||
application/
|
||||
repositories/
|
||||
pages.repository.interface.ts
|
||||
site-settings.repository.interface.ts
|
||||
use-cases/
|
||||
get-page-by-slug.use-case.ts
|
||||
get-site-settings.use-case.ts
|
||||
infrastructure/
|
||||
repositories/
|
||||
pages.repository.ts # real Payload-backed
|
||||
pages.repository.mock.ts
|
||||
site-settings.repository.ts # real Payload-backed
|
||||
site-settings.repository.mock.ts
|
||||
interface-adapters/
|
||||
controllers/
|
||||
get-page-by-slug.controller.ts
|
||||
get-site-settings.controller.ts
|
||||
integrations/
|
||||
api/
|
||||
procedures.ts # marketingPagesProcedure
|
||||
router.ts # marketingPagesRouter
|
||||
cms/
|
||||
collections/
|
||||
pages.ts
|
||||
globals/
|
||||
site-settings.ts
|
||||
index.ts
|
||||
di/
|
||||
symbols.ts
|
||||
module.ts
|
||||
container.ts
|
||||
bind-production.ts
|
||||
ui/
|
||||
index.ts # pageBySlugQuery, siteSettingsQuery
|
||||
query.ts
|
||||
index.ts
|
||||
__factories__/
|
||||
page.factory.ts
|
||||
site-settings.factory.ts
|
||||
__contracts__/
|
||||
pages-repository.contract.ts
|
||||
site-settings-repository.contract.ts
|
||||
tests/
|
||||
page-by-slug.feature.test.ts
|
||||
```
|
||||
|
||||
## What it must NOT import
|
||||
|
||||
- Any other feature package (`@repo/auth`, `@repo/blog`, etc.)
|
||||
- Any app package
|
||||
- `@repo/core-api`, `@repo/core-cms`, `@repo/core-trpc`, `@repo/core-ui` directly; only `@repo/core-shared`
|
||||
> Note: `@repo/core-trpc` and `@repo/core-ui` are optional packages scaffolded via `pnpm turbo gen core-package trpc` / `ui`. If not present, these constraints still apply to any future installation.
|
||||
|
||||
## Cross-links
|
||||
|
||||
- ADR-012 (`docs/decisions/adr-012-feature-conventions.md`) — factory-style use cases, per-use-case controllers, file-naming conventions
|
||||
- ADR-013 (`docs/decisions/adr-013-input-output-unification.md`) — schemas-in-use-case, presenter, `./ui` subpath, error middleware
|
||||
@@ -1,11 +0,0 @@
|
||||
# Changelog — @repo/marketing-pages
|
||||
|
||||
All notable changes to the `marketing-pages` feature package. Maintained by [release-please](https://github.com/googleapis/release-please) on merges to `main`. See [ADR-021](../../docs/decisions/adr-021-versioning-and-changelog.md) and [`docs/guides/releasing.md`](../../docs/guides/releasing.md).
|
||||
|
||||
## 0.1.0 (2026-05-13)
|
||||
|
||||
### Initial baseline
|
||||
|
||||
The `marketing-pages` feature established at v0.1.0 alongside the hybrid versioning rollout (ADR-021). The feature has been stable since the template-reset cleanup; this is the first formally versioned baseline.
|
||||
|
||||
Future entries appear above this section as release-please assembles them from conventional commits scoped to `packages/marketing-pages/**` since the last release.
|
||||
@@ -1,3 +0,0 @@
|
||||
import baseConfig from "@repo/core-eslint/base";
|
||||
|
||||
export default baseConfig;
|
||||
@@ -1,46 +0,0 @@
|
||||
{
|
||||
"name": "@repo/marketing-pages",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./ui": "./src/ui/index.ts",
|
||||
"./cms": "./src/integrations/cms/index.ts",
|
||||
"./api": "./src/integrations/api/router.ts",
|
||||
"./di/bind-production": "./src/di/bind-production.ts",
|
||||
"./di/bind-dev-seed": "./src/di/bind-dev-seed.ts",
|
||||
"./di/container": "./src/di/container.ts",
|
||||
"./di/symbols": "./src/di/symbols.ts",
|
||||
"./services/mailer": "./src/application/services/mailer.service.interface.ts",
|
||||
"./services/recording-mailer": "./src/infrastructure/services/recording-mailer.service.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@repo/auth": "workspace:*",
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@repo/core-trpc": "workspace:^",
|
||||
"@tanstack/react-query": "^5.66.0",
|
||||
"@trpc/client": "^11.17.0",
|
||||
"@trpc/server": "^11.0.0",
|
||||
"inversify": "^6.2.0",
|
||||
"payload": "^3.14.0",
|
||||
"react": "^19.0.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"zod": "^3.24.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@repo/core-eslint": "workspace:*",
|
||||
"@repo/core-testing": "workspace:*",
|
||||
"@repo/core-typescript": "workspace:*",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"vitest": "^3.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { it, expect, beforeEach, describe } from "vitest";
|
||||
import { defineContractSuite } from "@repo/core-testing/contract";
|
||||
import type { IPagesRepository } from "../application/repositories/pages.repository.interface";
|
||||
import type { Page } from "../entities/models/page";
|
||||
|
||||
const SEED_DATE = new Date("2026-01-01T00:00:00.000Z");
|
||||
|
||||
/**
|
||||
* Known fixtures that every implementation's `buildSubject` must pre-seed.
|
||||
* Exported so that test files can pass them to `MockPagesRepository` or the
|
||||
* Payload stub without duplicating definitions.
|
||||
*/
|
||||
export const CONTRACT_PAGES_SEED: Page[] = [
|
||||
{
|
||||
id: "cp-1",
|
||||
title: "About",
|
||||
slug: "about",
|
||||
hero: { heading: "About us" },
|
||||
layout: [],
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "About — Site" },
|
||||
createdAt: SEED_DATE,
|
||||
updatedAt: SEED_DATE,
|
||||
},
|
||||
{
|
||||
id: "cp-2",
|
||||
title: "Draft Page",
|
||||
slug: "draft-page",
|
||||
hero: { heading: "Draft" },
|
||||
layout: [],
|
||||
status: "draft",
|
||||
publishedAt: null,
|
||||
seo: { title: "Draft — Site" },
|
||||
createdAt: SEED_DATE,
|
||||
updatedAt: SEED_DATE,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Contract for IPagesRepository.
|
||||
*
|
||||
* IPagesRepository is read-only (no createPage). Each `buildSubject`
|
||||
* must return a repo pre-loaded with CONTRACT_PAGES_SEED (two pages:
|
||||
* one published with slug "about", one draft with slug "draft-page").
|
||||
*/
|
||||
export const pagesRepositoryContract = defineContractSuite<IPagesRepository>(
|
||||
"IPagesRepository",
|
||||
({ buildSubject, getTracer }) => {
|
||||
let repo: IPagesRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repo = await buildSubject();
|
||||
});
|
||||
|
||||
// --- getPageBySlug ---
|
||||
|
||||
it("getPageBySlug returns the published page by slug", async () => {
|
||||
const result = await repo.getPageBySlug("about");
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.slug).toBe("about");
|
||||
expect(result?.status).toBe("published");
|
||||
expect(result?.id).toBeDefined();
|
||||
});
|
||||
|
||||
it("getPageBySlug returns undefined for an unknown slug", async () => {
|
||||
expect(await repo.getPageBySlug("no-such-page")).toBeUndefined();
|
||||
});
|
||||
|
||||
// --- getPages ---
|
||||
|
||||
it("getPages with no filter returns all seeded pages", async () => {
|
||||
const list = await repo.getPages();
|
||||
expect(list).toHaveLength(2);
|
||||
for (const page of list) {
|
||||
expect(page.id).toBeDefined();
|
||||
expect(page.slug).toBeDefined();
|
||||
expect(["draft", "published"]).toContain(page.status);
|
||||
}
|
||||
});
|
||||
|
||||
it("getPages({ status: 'published' }) returns only published pages", async () => {
|
||||
const published = await repo.getPages({ status: "published" });
|
||||
expect(published).toHaveLength(1);
|
||||
for (const page of published) {
|
||||
expect(page.status).toBe("published");
|
||||
}
|
||||
});
|
||||
|
||||
it("getPages({ status: 'draft' }) returns only draft pages", async () => {
|
||||
const drafts = await repo.getPages({ status: "draft" });
|
||||
expect(drafts).toHaveLength(1);
|
||||
for (const page of drafts) {
|
||||
expect(page.status).toBe("draft");
|
||||
}
|
||||
});
|
||||
|
||||
describe("span emission", () => {
|
||||
it("getPageBySlug emits pages.getPageBySlug span with slug attribute", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.getPageBySlug("about");
|
||||
const span = tracer.findSpan("pages.getPageBySlug");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
expect(span!.attributes.slug).toBe("about");
|
||||
});
|
||||
|
||||
it("getPages emits pages.getPages span with op=repository", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.getPages({ status: "published" });
|
||||
const span = tracer.findSpan("pages.getPages");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
expect(span!.attributes.status).toBe("published");
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,50 +0,0 @@
|
||||
import { it, expect, beforeEach, describe } from "vitest";
|
||||
import { defineContractSuite } from "@repo/core-testing/contract";
|
||||
import type { ISiteSettingsRepository } from "../application/repositories/site-settings.repository.interface";
|
||||
|
||||
/**
|
||||
* Contract for ISiteSettingsRepository.
|
||||
*
|
||||
* SiteSettings is a singleton (Payload Global). The interface exposes
|
||||
* only getSiteSettings(). The contract verifies the shape of the return value.
|
||||
*/
|
||||
export const siteSettingsRepositoryContract =
|
||||
defineContractSuite<ISiteSettingsRepository>(
|
||||
"ISiteSettingsRepository",
|
||||
({ buildSubject, getTracer }) => {
|
||||
let repo: ISiteSettingsRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repo = await buildSubject();
|
||||
});
|
||||
|
||||
// --- getSiteSettings ---
|
||||
|
||||
it("getSiteSettings returns an object with a non-empty siteName", async () => {
|
||||
const settings = await repo.getSiteSettings();
|
||||
expect(settings).toBeDefined();
|
||||
expect(typeof settings.siteName).toBe("string");
|
||||
expect(settings.siteName.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("getSiteSettings siteDescription is string or undefined", async () => {
|
||||
const settings = await repo.getSiteSettings();
|
||||
expect(
|
||||
settings.siteDescription === undefined ||
|
||||
typeof settings.siteDescription === "string",
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
describe("span emission", () => {
|
||||
it("getSiteSettings emits site-settings.getSiteSettings span with op=repository", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.getSiteSettings();
|
||||
const span = tracer.findSpan("site-settings.getSiteSettings");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,2 +0,0 @@
|
||||
export { pageFactory } from "./page.factory";
|
||||
export { siteSettingsFactory } from "./site-settings.factory";
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { pageFactory } from "@/__factories__/page.factory";
|
||||
|
||||
describe("pageFactory", () => {
|
||||
beforeEach(() => pageFactory.reset());
|
||||
|
||||
it("returns a Page with stable defaults", () => {
|
||||
const p = pageFactory.build();
|
||||
expect(p.id).toBe("page-1");
|
||||
expect(p.title).toBe("Page 1");
|
||||
expect(p.slug).toBe("page-1");
|
||||
expect(p.status).toBe("draft");
|
||||
expect(p.createdAt).toEqual(new Date("2026-01-01T00:00:00Z"));
|
||||
});
|
||||
|
||||
it("applies overrides", () => {
|
||||
const p = pageFactory.build({ status: "published", title: "About" });
|
||||
expect(p.status).toBe("published");
|
||||
expect(p.title).toBe("About");
|
||||
expect(p.id).toBe("page-1");
|
||||
});
|
||||
|
||||
it("increments sequence per build", () => {
|
||||
const a = pageFactory.build();
|
||||
const b = pageFactory.build();
|
||||
expect(a.id).toBe("page-1");
|
||||
expect(b.id).toBe("page-2");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import { defineFactory } from "@repo/core-testing/factory";
|
||||
import type { Page } from "../entities/models/page";
|
||||
|
||||
export const pageFactory = defineFactory<Page>(({ sequence }) => ({
|
||||
id: `page-${sequence}`,
|
||||
title: `Page ${sequence}`,
|
||||
slug: `page-${sequence}`,
|
||||
hero: {
|
||||
heading: `Hero ${sequence}`,
|
||||
},
|
||||
layout: [],
|
||||
status: "draft",
|
||||
publishedAt: null,
|
||||
seo: {
|
||||
title: `Page ${sequence} | Site`,
|
||||
},
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||
}));
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { siteSettingsFactory } from "@/__factories__/site-settings.factory";
|
||||
|
||||
describe("siteSettingsFactory", () => {
|
||||
beforeEach(() => siteSettingsFactory.reset());
|
||||
|
||||
it("returns SiteSettings with stable defaults", () => {
|
||||
const s = siteSettingsFactory.build();
|
||||
expect(s.siteName).toBe("Site 1");
|
||||
});
|
||||
|
||||
it("applies overrides", () => {
|
||||
const s = siteSettingsFactory.build({ siteName: "My Brand" });
|
||||
expect(s.siteName).toBe("My Brand");
|
||||
});
|
||||
|
||||
it("increments sequence per build (siteName reflects it)", () => {
|
||||
const a = siteSettingsFactory.build();
|
||||
const b = siteSettingsFactory.build();
|
||||
expect(a.siteName).toBe("Site 1");
|
||||
expect(b.siteName).toBe("Site 2");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { defineFactory } from "@repo/core-testing/factory";
|
||||
import type { SiteSettings } from "../entities/models/site-settings";
|
||||
|
||||
export const siteSettingsFactory = defineFactory<SiteSettings>(
|
||||
({ sequence }) => ({
|
||||
siteName: `Site ${sequence}`,
|
||||
}),
|
||||
);
|
||||
@@ -1,55 +0,0 @@
|
||||
import { pageFactory } from "../__factories__/page.factory";
|
||||
import { siteSettingsFactory } from "../__factories__/site-settings.factory";
|
||||
import type { Page } from "../entities/models/page";
|
||||
import type { SiteSettings } from "../entities/models/site-settings";
|
||||
|
||||
/**
|
||||
* Realistic marketing-pages seed for dev mode + storybook stories.
|
||||
*
|
||||
* Built from `pageFactory` / `siteSettingsFactory` so factory defaults take
|
||||
* care of boring fields and we only override what makes the data look like a
|
||||
* real site.
|
||||
*
|
||||
* Lazily produced so importing this module is side-effect-free — the
|
||||
* factory's sequence counter only advances when a binder calls
|
||||
* `buildDevPages()` / `buildDevSiteSettings()`.
|
||||
*/
|
||||
export function buildDevPages(): Page[] {
|
||||
const SEED_DATE = new Date("2026-01-01T00:00:00.000Z");
|
||||
return [
|
||||
pageFactory.build({
|
||||
id: "home",
|
||||
slug: "home",
|
||||
title: "Home",
|
||||
hero: { heading: "Welcome to our site" },
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "Home | My App" },
|
||||
}),
|
||||
pageFactory.build({
|
||||
id: "about",
|
||||
slug: "about",
|
||||
title: "About Us",
|
||||
hero: { heading: "Our story" },
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "About | My App" },
|
||||
}),
|
||||
pageFactory.build({
|
||||
id: "pricing",
|
||||
slug: "pricing",
|
||||
title: "Pricing",
|
||||
hero: { heading: "Simple, transparent pricing" },
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "Pricing | My App" },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
export function buildDevSiteSettings(): SiteSettings {
|
||||
return siteSettingsFactory.build({
|
||||
siteName: "My App",
|
||||
siteDescription: "A vertical-feature monorepo template",
|
||||
});
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
export interface IPagesRepository {
|
||||
getPageBySlug(slug: string): Promise<Page | undefined>;
|
||||
getPages(options?: {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Page[]>;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
export interface ISiteSettingsRepository {
|
||||
getSiteSettings(): Promise<SiteSettings>;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export interface IMailerService {
|
||||
sendWelcome(userId: string, email: string): Promise<void>;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ZodError } from "zod";
|
||||
import { getPageBySlugUseCase } from "@/application/use-cases/get-page-by-slug.use-case";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
|
||||
describe("getPageBySlugUseCase", () => {
|
||||
it("returns the page when found", async () => {
|
||||
const repo = new MockPagesRepository();
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
const result = await useCase({ slug: "about" });
|
||||
expect(result?.slug).toBe("about");
|
||||
});
|
||||
|
||||
it("returns undefined when not found", async () => {
|
||||
const repo = new MockPagesRepository();
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
const result = await useCase({ slug: "missing-page" });
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws ZodError when repository returns malformed page data", async () => {
|
||||
const repo = new MockPagesRepository([
|
||||
{
|
||||
id: "p-bad",
|
||||
title: "",
|
||||
slug: "bad-page",
|
||||
hero: { heading: "" },
|
||||
layout: [],
|
||||
status: "published",
|
||||
publishedAt: null,
|
||||
seo: { title: "" },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
} as never,
|
||||
]);
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
await expect(useCase({ slug: "bad-page" })).rejects.toBeInstanceOf(
|
||||
ZodError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { pageSchema } from "../../entities/models/page";
|
||||
import type { IPagesRepository } from "../repositories/pages.repository.interface";
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────────
|
||||
export const getPageBySlugInputSchema = z.object({ slug: z.string().min(1) }).strict();
|
||||
export type GetPageBySlugInput = z.infer<typeof getPageBySlugInputSchema>;
|
||||
|
||||
// ── Output ───────────────────────────────────────────────────────────────
|
||||
export const getPageBySlugOutputSchema = pageSchema;
|
||||
export type GetPageBySlugOutput = z.infer<typeof getPageBySlugOutputSchema>;
|
||||
|
||||
// ── Use case ─────────────────────────────────────────────────────────────
|
||||
export type IGetPageBySlugUseCase = ReturnType<typeof getPageBySlugUseCase>;
|
||||
|
||||
export const getPageBySlugUseCase =
|
||||
(pagesRepository: IPagesRepository) =>
|
||||
async (input: GetPageBySlugInput): Promise<GetPageBySlugOutput | undefined> => {
|
||||
const page = await pagesRepository.getPageBySlug(input.slug);
|
||||
if (!page) return undefined;
|
||||
return getPageBySlugOutputSchema.parse(page);
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ZodError } from "zod";
|
||||
import { getSiteSettingsUseCase } from "@/application/use-cases/get-site-settings.use-case";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
|
||||
describe("getSiteSettingsUseCase", () => {
|
||||
it("returns the seeded site settings", async () => {
|
||||
const repo = new MockSiteSettingsRepository();
|
||||
const useCase = getSiteSettingsUseCase(repo);
|
||||
const result = await useCase({});
|
||||
expect(result.siteName).toBe("My App");
|
||||
});
|
||||
|
||||
it("throws ZodError when repository returns malformed site settings", async () => {
|
||||
const malformedRepo = {
|
||||
getSiteSettings: async () => ({ siteName: "" }),
|
||||
};
|
||||
const useCase = getSiteSettingsUseCase(malformedRepo);
|
||||
await expect(useCase({})).rejects.toBeInstanceOf(ZodError);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { siteSettingsSchema } from "../../entities/models/site-settings";
|
||||
import type { ISiteSettingsRepository } from "../repositories/site-settings.repository.interface";
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────────
|
||||
export const getSiteSettingsInputSchema = z.object({}).strict();
|
||||
export type GetSiteSettingsInput = z.infer<typeof getSiteSettingsInputSchema>;
|
||||
|
||||
// ── Output ───────────────────────────────────────────────────────────────
|
||||
export const getSiteSettingsOutputSchema = siteSettingsSchema;
|
||||
export type GetSiteSettingsOutput = z.infer<typeof getSiteSettingsOutputSchema>;
|
||||
|
||||
// ── Use case ─────────────────────────────────────────────────────────────
|
||||
export type IGetSiteSettingsUseCase = ReturnType<typeof getSiteSettingsUseCase>;
|
||||
|
||||
export const getSiteSettingsUseCase =
|
||||
(siteSettingsRepository: ISiteSettingsRepository) =>
|
||||
async (_input: GetSiteSettingsInput): Promise<GetSiteSettingsOutput> => {
|
||||
const result = await siteSettingsRepository.getSiteSettings();
|
||||
return getSiteSettingsOutputSchema.parse(result);
|
||||
};
|
||||
@@ -1,102 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { NoopTracer, NoopLogger } from "@repo/core-shared/instrumentation";
|
||||
import { RecordingEventBus, RecordingJobQueue } from "@repo/core-testing/instrumentation";
|
||||
import { bindDevSeedMarketingPages } from "@/di/bind-dev-seed";
|
||||
import { marketingPagesContainer } from "@/di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "@/di/symbols";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
import type { IPagesRepository } from "@/application/repositories/pages.repository.interface";
|
||||
import type { ISiteSettingsRepository } from "@/application/repositories/site-settings.repository.interface";
|
||||
|
||||
const noop = { tracer: new NoopTracer(), logger: new NoopLogger() };
|
||||
|
||||
describe("bindDevSeedMarketingPages", () => {
|
||||
// Each test starts from default mock bindings and tears down afterwards so
|
||||
// the global marketingPagesContainer state stays clean for siblings.
|
||||
beforeEach(() => {
|
||||
if (marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IPagesRepository)) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IPagesRepository);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<IPagesRepository>(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
.to(MockPagesRepository);
|
||||
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<ISiteSettingsRepository>(MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository)
|
||||
.to(MockSiteSettingsRepository);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IPagesRepository)) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IPagesRepository);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<IPagesRepository>(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
.to(MockPagesRepository);
|
||||
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<ISiteSettingsRepository>(MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository)
|
||||
.to(MockSiteSettingsRepository);
|
||||
});
|
||||
|
||||
it("populates the pages repository with the dev pages", async () => {
|
||||
await bindDevSeedMarketingPages({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
|
||||
const repo = marketingPagesContainer.get<IPagesRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.IPagesRepository,
|
||||
);
|
||||
const pages = await repo.getPages();
|
||||
|
||||
expect(pages.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("seeds site settings with a non-default site name", async () => {
|
||||
await bindDevSeedMarketingPages({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
|
||||
const settingsRepo = marketingPagesContainer.get<ISiteSettingsRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
const settings = await settingsRepo.getSiteSettings();
|
||||
|
||||
expect(settings.siteName).toBe("My App");
|
||||
expect(settings.siteDescription).toBeDefined();
|
||||
});
|
||||
|
||||
it("is idempotent — calling twice rebuilds fresh populated repos", async () => {
|
||||
await bindDevSeedMarketingPages({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
const before = marketingPagesContainer.get<IPagesRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.IPagesRepository,
|
||||
);
|
||||
const beforeCount = (await before.getPages()).length;
|
||||
|
||||
await bindDevSeedMarketingPages({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
const after = marketingPagesContainer.get<IPagesRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.IPagesRepository,
|
||||
);
|
||||
const afterCount = (await after.getPages()).length;
|
||||
|
||||
expect(afterCount).toBe(beforeCount);
|
||||
// It's a fresh instance — not the previous one.
|
||||
expect(after).not.toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -1,268 +0,0 @@
|
||||
import {
|
||||
withSpan,
|
||||
withCapture,
|
||||
INSTRUMENTATION_SYMBOLS,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
import type { BindContext } from "@repo/core-shared/di";
|
||||
import {
|
||||
assertFeatureConformance,
|
||||
wireUseCase,
|
||||
} from "@repo/core-shared/conformance";
|
||||
import { marketingPagesManifest } from "../feature.manifest";
|
||||
import { marketingPagesContainer } from "./container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "./symbols";
|
||||
import { MockPagesRepository } from "../infrastructure/repositories/pages.repository.mock";
|
||||
import { buildDevPages, buildDevSiteSettings } from "../__seeds__/dev";
|
||||
import { getSiteSettingsUseCase } from "../application/use-cases/get-site-settings.use-case";
|
||||
import { getPageBySlugUseCase } from "../application/use-cases/get-page-by-slug.use-case";
|
||||
import { getSiteSettingsController } from "../interface-adapters/controllers/get-site-settings.controller";
|
||||
import { getPageBySlugController } from "../interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import type { IPagesRepository } from "../application/repositories/pages.repository.interface";
|
||||
import type { ISiteSettingsRepository } from "../application/repositories/site-settings.repository.interface";
|
||||
import { userSignedUpEvent } from "@repo/auth";
|
||||
import { onAuthUserSignedUpHandler } from "../events/handlers/on-auth-user-signed-up.handler";
|
||||
import {
|
||||
sendWelcomeEmailJob,
|
||||
type ISendWelcomeEmailJob,
|
||||
type SendWelcomeEmailInput,
|
||||
} from "../jobs/send-welcome-email.job";
|
||||
import { RecordingMailerService } from "../infrastructure/services/recording-mailer.service";
|
||||
import type { IMailerService } from "../application/services/mailer.service.interface";
|
||||
|
||||
/**
|
||||
* Replace the default empty mocks with populated ones for dev mode + storybook.
|
||||
*
|
||||
* Call this from app boot when `USE_DEV_SEED=true`, mutually exclusive with
|
||||
* `bindProductionMarketingPages(config)`. Tests must NOT call this — they
|
||||
* construct mocks directly and seed via factories per-test.
|
||||
*
|
||||
* Idempotent: safe to call multiple times; each call rebuilds fresh populated
|
||||
* repos and rebinds both symbols.
|
||||
*/
|
||||
export async function bindDevSeedMarketingPages(
|
||||
ctx: BindContext,
|
||||
): Promise<void> {
|
||||
const { tracer, logger, bus, queue, realtime, realtimeRegistry } = ctx;
|
||||
|
||||
// Bind shared instrumentation into feature container
|
||||
if (marketingPagesContainer.isBound(INSTRUMENTATION_SYMBOLS.TRACER)) {
|
||||
marketingPagesContainer.unbind(INSTRUMENTATION_SYMBOLS.TRACER);
|
||||
}
|
||||
if (marketingPagesContainer.isBound(INSTRUMENTATION_SYMBOLS.LOGGER)) {
|
||||
marketingPagesContainer.unbind(INSTRUMENTATION_SYMBOLS.LOGGER);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<ITracer>(INSTRUMENTATION_SYMBOLS.TRACER)
|
||||
.toConstantValue(tracer);
|
||||
marketingPagesContainer
|
||||
.bind<ILogger>(INSTRUMENTATION_SYMBOLS.LOGGER)
|
||||
.toConstantValue(logger);
|
||||
|
||||
// Pages repository — MockPagesRepository accepts an initial array.
|
||||
if (
|
||||
marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IPagesRepository);
|
||||
}
|
||||
const pagesRepo = new MockPagesRepository(buildDevPages(), tracer, logger);
|
||||
marketingPagesContainer
|
||||
.bind<IPagesRepository>(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
.toConstantValue(pagesRepo);
|
||||
|
||||
// Site settings repository
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
}
|
||||
const settings = buildDevSiteSettings();
|
||||
// Inline constant so dev seed returns exactly the seeded value (not the mock's default)
|
||||
const siteSettingsRepo: ISiteSettingsRepository = {
|
||||
getSiteSettings: async () => settings,
|
||||
};
|
||||
marketingPagesContainer
|
||||
.bind<ISiteSettingsRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
)
|
||||
.toConstantValue(siteSettingsRepo);
|
||||
|
||||
// Use cases
|
||||
const wrappedGetSiteSettings = wireUseCase({
|
||||
container: marketingPagesContainer,
|
||||
symbol: MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase,
|
||||
factory: getSiteSettingsUseCase,
|
||||
deps: [siteSettingsRepo],
|
||||
feature: "marketing-pages",
|
||||
layer: "use-case",
|
||||
name: "getSiteSettings",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedGetPageBySlug = wireUseCase({
|
||||
container: marketingPagesContainer,
|
||||
symbol: MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase,
|
||||
factory: getPageBySlugUseCase,
|
||||
deps: [pagesRepo],
|
||||
feature: "marketing-pages",
|
||||
layer: "use-case",
|
||||
name: "getPageBySlug",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
|
||||
for (const sym of [
|
||||
MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController,
|
||||
MARKETING_PAGES_SYMBOLS.IGetPageBySlugController,
|
||||
]) {
|
||||
if (marketingPagesContainer.isBound(sym))
|
||||
marketingPagesContainer.unbind(sym);
|
||||
}
|
||||
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.getSiteSettings", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "controller",
|
||||
name: "marketing-pages.getSiteSettings",
|
||||
},
|
||||
getSiteSettingsController(wrappedGetSiteSettings),
|
||||
),
|
||||
),
|
||||
);
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IGetPageBySlugController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.getPageBySlug", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "controller",
|
||||
name: "marketing-pages.getPageBySlug",
|
||||
},
|
||||
getPageBySlugController(wrappedGetPageBySlug),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Bind the dev-seed mailer (recording so e2e tests can inspect calls).
|
||||
if (marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IMailerService)) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IMailerService);
|
||||
}
|
||||
const mailer = new RecordingMailerService();
|
||||
marketingPagesContainer
|
||||
.bind<IMailerService>(MARKETING_PAGES_SYMBOLS.IMailerService)
|
||||
.toConstantValue(mailer);
|
||||
|
||||
// <gen:event-handlers>
|
||||
// onAuthUserSignedUpHandler subscription — generated, edit the handler file (not this block) for behavior.
|
||||
// bus is optional: when @repo/core-events is not scaffolded, ctx.bus is undefined and the handler is not bound.
|
||||
// queue (IJobQueue) is in core-shared and always provided; the inner if (queue) below is belt-and-suspenders.
|
||||
if (queue) {
|
||||
const wrappedAuthUserSignedUp = withSpan(
|
||||
tracer,
|
||||
{
|
||||
name: "marketing-pages.onAuthUserSignedUpHandler",
|
||||
op: "event-handler",
|
||||
},
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "event-handler",
|
||||
name: "marketing-pages.onAuthUserSignedUpHandler",
|
||||
},
|
||||
onAuthUserSignedUpHandler(queue),
|
||||
),
|
||||
);
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler)
|
||||
.toConstantValue(wrappedAuthUserSignedUp);
|
||||
bus?.subscribe(
|
||||
userSignedUpEvent,
|
||||
"marketing-pages",
|
||||
wrappedAuthUserSignedUp,
|
||||
);
|
||||
}
|
||||
// <gen:jobs>
|
||||
const wrappedSendWelcomeEmail = withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.sendWelcomeEmail", op: "job" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "job",
|
||||
name: "marketing-pages.sendWelcomeEmail",
|
||||
},
|
||||
sendWelcomeEmailJob(mailer),
|
||||
),
|
||||
);
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob)
|
||||
.toConstantValue(wrappedSendWelcomeEmail);
|
||||
|
||||
// Register the dev-seed in-memory queue handler so enqueue() actually fires
|
||||
// the wrapped job. Production binding skips this — the Payload task does it.
|
||||
if (
|
||||
queue &&
|
||||
"register" in queue &&
|
||||
typeof (queue as { register?: unknown }).register === "function"
|
||||
) {
|
||||
(
|
||||
queue as {
|
||||
register: (slug: string, h: (input: unknown) => Promise<void>) => void;
|
||||
}
|
||||
).register("marketing-pages.send-welcome-email", async (input) => {
|
||||
const wrapped = marketingPagesContainer.get<ISendWelcomeEmailJob>(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
);
|
||||
await wrapped(input as SendWelcomeEmailInput);
|
||||
});
|
||||
}
|
||||
void realtime;
|
||||
void realtimeRegistry;
|
||||
// <gen:realtime-handlers>
|
||||
|
||||
// Boot-time conformance check (dev-seed mode).
|
||||
assertFeatureConformance(
|
||||
marketingPagesContainer,
|
||||
marketingPagesManifest,
|
||||
{
|
||||
getPageBySlug: MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase,
|
||||
getSiteSettings: MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase,
|
||||
},
|
||||
ctx,
|
||||
);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import { NoopTracer, NoopLogger } from "@repo/core-shared/instrumentation";
|
||||
import { bindProductionMarketingPages } from "@/di/bind-production";
|
||||
|
||||
describe("bindProductionMarketingPages — boot-time conformance", () => {
|
||||
it("binds every manifest use case through withSpan + withCapture", () => {
|
||||
expect(() =>
|
||||
bindProductionMarketingPages({
|
||||
config: {} as SanitizedConfig,
|
||||
tracer: new NoopTracer(),
|
||||
logger: new NoopLogger(),
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,227 +0,0 @@
|
||||
import {
|
||||
withSpan,
|
||||
withCapture,
|
||||
INSTRUMENTATION_SYMBOLS,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
import type { BindProductionContext } from "@repo/core-shared/di";
|
||||
import {
|
||||
assertFeatureConformance,
|
||||
wireUseCase,
|
||||
} from "@repo/core-shared/conformance";
|
||||
import { marketingPagesContainer } from "./container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "./symbols";
|
||||
import { marketingPagesManifest } from "../feature.manifest";
|
||||
import { PagesRepository } from "../infrastructure/repositories/pages.repository";
|
||||
import { SiteSettingsRepository } from "../infrastructure/repositories/site-settings.repository";
|
||||
import { getSiteSettingsUseCase } from "../application/use-cases/get-site-settings.use-case";
|
||||
import { getPageBySlugUseCase } from "../application/use-cases/get-page-by-slug.use-case";
|
||||
import { getSiteSettingsController } from "../interface-adapters/controllers/get-site-settings.controller";
|
||||
import { getPageBySlugController } from "../interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import { userSignedUpEvent } from "@repo/auth";
|
||||
import { onAuthUserSignedUpHandler } from "../events/handlers/on-auth-user-signed-up.handler";
|
||||
import { sendWelcomeEmailJob } from "../jobs/send-welcome-email.job";
|
||||
import { RecordingMailerService } from "../infrastructure/services/recording-mailer.service";
|
||||
import type { IMailerService } from "../application/services/mailer.service.interface";
|
||||
|
||||
export function bindProductionMarketingPages(ctx: BindProductionContext): void {
|
||||
const { config, tracer, logger, bus, queue, realtime, realtimeRegistry } =
|
||||
ctx;
|
||||
|
||||
// Bind shared instrumentation into feature container
|
||||
if (marketingPagesContainer.isBound(INSTRUMENTATION_SYMBOLS.TRACER)) {
|
||||
marketingPagesContainer.unbind(INSTRUMENTATION_SYMBOLS.TRACER);
|
||||
}
|
||||
if (marketingPagesContainer.isBound(INSTRUMENTATION_SYMBOLS.LOGGER)) {
|
||||
marketingPagesContainer.unbind(INSTRUMENTATION_SYMBOLS.LOGGER);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind<ITracer>(INSTRUMENTATION_SYMBOLS.TRACER)
|
||||
.toConstantValue(tracer);
|
||||
marketingPagesContainer
|
||||
.bind<ILogger>(INSTRUMENTATION_SYMBOLS.LOGGER)
|
||||
.toConstantValue(logger);
|
||||
|
||||
// Real repositories
|
||||
if (
|
||||
marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IPagesRepository);
|
||||
}
|
||||
const pagesRepo = new PagesRepository(config, tracer, logger);
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IPagesRepository)
|
||||
.toConstantValue(pagesRepo);
|
||||
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
}
|
||||
const siteSettingsRepo = new SiteSettingsRepository(config, tracer, logger);
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository)
|
||||
.toConstantValue(siteSettingsRepo);
|
||||
|
||||
// Use cases
|
||||
const wrappedGetSiteSettings = wireUseCase({
|
||||
container: marketingPagesContainer,
|
||||
symbol: MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase,
|
||||
factory: getSiteSettingsUseCase,
|
||||
deps: [siteSettingsRepo],
|
||||
feature: "marketing-pages",
|
||||
layer: "use-case",
|
||||
name: "getSiteSettings",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedGetPageBySlug = wireUseCase({
|
||||
container: marketingPagesContainer,
|
||||
symbol: MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase,
|
||||
factory: getPageBySlugUseCase,
|
||||
deps: [pagesRepo],
|
||||
feature: "marketing-pages",
|
||||
layer: "use-case",
|
||||
name: "getPageBySlug",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
|
||||
// Controllers — wrapped with span at bind time
|
||||
for (const sym of [
|
||||
MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController,
|
||||
MARKETING_PAGES_SYMBOLS.IGetPageBySlugController,
|
||||
]) {
|
||||
if (marketingPagesContainer.isBound(sym))
|
||||
marketingPagesContainer.unbind(sym);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.getSiteSettings", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "controller",
|
||||
name: "marketing-pages.getSiteSettings",
|
||||
},
|
||||
getSiteSettingsController(wrappedGetSiteSettings),
|
||||
),
|
||||
),
|
||||
);
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IGetPageBySlugController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.getPageBySlug", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "controller",
|
||||
name: "marketing-pages.getPageBySlug",
|
||||
},
|
||||
getPageBySlugController(wrappedGetPageBySlug),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Bind the production mailer. Until a real SMTP/SES adapter ships, this is
|
||||
// a placeholder RecordingMailerService — production wiring is structurally
|
||||
// identical to dev-seed but the impl is the seam where a real mailer plugs in.
|
||||
if (marketingPagesContainer.isBound(MARKETING_PAGES_SYMBOLS.IMailerService)) {
|
||||
marketingPagesContainer.unbind(MARKETING_PAGES_SYMBOLS.IMailerService);
|
||||
}
|
||||
const mailer = new RecordingMailerService();
|
||||
marketingPagesContainer
|
||||
.bind<IMailerService>(MARKETING_PAGES_SYMBOLS.IMailerService)
|
||||
.toConstantValue(mailer);
|
||||
|
||||
// <gen:event-handlers>
|
||||
// onAuthUserSignedUpHandler subscription — generated, edit the handler file (not this block) for behavior.
|
||||
// bus is optional: when @repo/core-events is not scaffolded, ctx.bus is undefined and the handler is not bound.
|
||||
// queue (IJobQueue) is in core-shared and always provided; the inner if (queue) below is belt-and-suspenders.
|
||||
if (queue) {
|
||||
const wrappedAuthUserSignedUp = withSpan(
|
||||
tracer,
|
||||
{
|
||||
name: "marketing-pages.onAuthUserSignedUpHandler",
|
||||
op: "event-handler",
|
||||
},
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "event-handler",
|
||||
name: "marketing-pages.onAuthUserSignedUpHandler",
|
||||
},
|
||||
onAuthUserSignedUpHandler(queue),
|
||||
),
|
||||
);
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler)
|
||||
.toConstantValue(wrappedAuthUserSignedUp);
|
||||
bus?.subscribe(
|
||||
userSignedUpEvent,
|
||||
"marketing-pages",
|
||||
wrappedAuthUserSignedUp,
|
||||
);
|
||||
}
|
||||
// <gen:jobs>
|
||||
const wrappedSendWelcomeEmail = withSpan(
|
||||
tracer,
|
||||
{ name: "marketing-pages.sendWelcomeEmail", op: "job" },
|
||||
withCapture(
|
||||
logger,
|
||||
{
|
||||
feature: "marketing-pages",
|
||||
layer: "job",
|
||||
name: "marketing-pages.sendWelcomeEmail",
|
||||
},
|
||||
sendWelcomeEmailJob(mailer),
|
||||
),
|
||||
);
|
||||
if (
|
||||
marketingPagesContainer.isBound(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
)
|
||||
) {
|
||||
marketingPagesContainer.unbind(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
);
|
||||
}
|
||||
marketingPagesContainer
|
||||
.bind(MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob)
|
||||
.toConstantValue(wrappedSendWelcomeEmail);
|
||||
void realtime;
|
||||
void realtimeRegistry;
|
||||
// <gen:realtime-handlers>
|
||||
|
||||
// Boot-time conformance check.
|
||||
assertFeatureConformance(
|
||||
marketingPagesContainer,
|
||||
marketingPagesManifest,
|
||||
{
|
||||
getPageBySlug: MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase,
|
||||
getSiteSettings: MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase,
|
||||
},
|
||||
ctx,
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { marketingPagesContainer } from "./container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "./symbols";
|
||||
import { MarketingPagesModule } from "./module";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
import type { IPagesRepository } from "@/application/repositories/pages.repository.interface";
|
||||
import type { ISiteSettingsRepository } from "@/application/repositories/site-settings.repository.interface";
|
||||
|
||||
describe("marketingPagesContainer", () => {
|
||||
beforeEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
marketingPagesContainer.load(MarketingPagesModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("resolves IPagesRepository to MockPagesRepository", () => {
|
||||
const repo = marketingPagesContainer.get<IPagesRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.IPagesRepository,
|
||||
);
|
||||
expect(repo).toBeInstanceOf(MockPagesRepository);
|
||||
});
|
||||
|
||||
it("resolves ISiteSettingsRepository to MockSiteSettingsRepository", () => {
|
||||
const repo = marketingPagesContainer.get<ISiteSettingsRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
);
|
||||
expect(repo).toBeInstanceOf(MockSiteSettingsRepository);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { Container } from "inversify";
|
||||
import { MarketingPagesModule } from "./module";
|
||||
|
||||
export const marketingPagesContainer = new Container({
|
||||
defaultScope: "Singleton",
|
||||
});
|
||||
marketingPagesContainer.load(MarketingPagesModule);
|
||||
@@ -1,68 +0,0 @@
|
||||
import { ContainerModule, type interfaces } from "inversify";
|
||||
|
||||
import type { IPagesRepository } from "../application/repositories/pages.repository.interface";
|
||||
import type { ISiteSettingsRepository } from "../application/repositories/site-settings.repository.interface";
|
||||
import { MockPagesRepository } from "../infrastructure/repositories/pages.repository.mock";
|
||||
import { MockSiteSettingsRepository } from "../infrastructure/repositories/site-settings.repository.mock";
|
||||
import {
|
||||
getPageBySlugUseCase,
|
||||
type IGetPageBySlugUseCase,
|
||||
} from "../application/use-cases/get-page-by-slug.use-case";
|
||||
import {
|
||||
getSiteSettingsUseCase,
|
||||
type IGetSiteSettingsUseCase,
|
||||
} from "../application/use-cases/get-site-settings.use-case";
|
||||
import {
|
||||
getPageBySlugController,
|
||||
type IGetPageBySlugController,
|
||||
} from "../interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import {
|
||||
getSiteSettingsController,
|
||||
type IGetSiteSettingsController,
|
||||
} from "../interface-adapters/controllers/get-site-settings.controller";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "./symbols";
|
||||
|
||||
export const MarketingPagesModule = new ContainerModule(
|
||||
(bind: interfaces.Bind) => {
|
||||
bind<IPagesRepository>(MARKETING_PAGES_SYMBOLS.IPagesRepository).to(
|
||||
MockPagesRepository,
|
||||
);
|
||||
bind<ISiteSettingsRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
).to(MockSiteSettingsRepository);
|
||||
|
||||
bind<IGetPageBySlugUseCase>(MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase).toDynamicValue(
|
||||
(ctx) =>
|
||||
getPageBySlugUseCase(
|
||||
ctx.container.get<IPagesRepository>(MARKETING_PAGES_SYMBOLS.IPagesRepository),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IGetSiteSettingsUseCase>(MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase).toDynamicValue(
|
||||
(ctx) =>
|
||||
getSiteSettingsUseCase(
|
||||
ctx.container.get<ISiteSettingsRepository>(
|
||||
MARKETING_PAGES_SYMBOLS.ISiteSettingsRepository,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IGetPageBySlugController>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetPageBySlugController,
|
||||
).toDynamicValue((ctx) =>
|
||||
getPageBySlugController(
|
||||
ctx.container.get<IGetPageBySlugUseCase>(MARKETING_PAGES_SYMBOLS.IGetPageBySlugUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IGetSiteSettingsController>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController,
|
||||
).toDynamicValue((ctx) =>
|
||||
getSiteSettingsController(
|
||||
ctx.container.get<IGetSiteSettingsUseCase>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetSiteSettingsUseCase,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,16 +0,0 @@
|
||||
export const MARKETING_PAGES_SYMBOLS = {
|
||||
IPagesRepository: Symbol.for("marketing-pages:IPagesRepository"),
|
||||
ISiteSettingsRepository: Symbol.for("marketing-pages:ISiteSettingsRepository"),
|
||||
IMailerService: Symbol.for("@repo/marketing-pages/IMailerService"),
|
||||
// Use cases
|
||||
IGetPageBySlugUseCase: Symbol.for("marketing-pages:IGetPageBySlugUseCase"),
|
||||
IGetSiteSettingsUseCase: Symbol.for("marketing-pages:IGetSiteSettingsUseCase"),
|
||||
// Controllers
|
||||
IGetPageBySlugController: Symbol.for("marketing-pages:IGetPageBySlugController"),
|
||||
IGetSiteSettingsController: Symbol.for("marketing-pages:IGetSiteSettingsController"),
|
||||
// <gen:event-handler-symbols>
|
||||
IOnAuthUserSignedUpHandler: Symbol.for("@repo/marketing-pages/onAuthUserSignedUp"),
|
||||
// <gen:job-symbols>
|
||||
ISendWelcomeEmailJob: Symbol.for("@repo/marketing-pages/sendWelcomeEmailJob"),
|
||||
// <gen:realtime-handler-symbols>
|
||||
} as const;
|
||||
@@ -1,6 +0,0 @@
|
||||
export class InputParseError extends Error {
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
super(message, options);
|
||||
this.name = "InputParseError";
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PageNotFoundError } from "./page";
|
||||
import { InputParseError } from "./common";
|
||||
|
||||
describe("PageNotFoundError", () => {
|
||||
it("uses the default message when none is given", () => {
|
||||
const err = new PageNotFoundError();
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe("Page not found");
|
||||
});
|
||||
|
||||
it("uses a custom message when provided", () => {
|
||||
const err = new PageNotFoundError("could not find page /about");
|
||||
expect(err.message).toBe("could not find page /about");
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputParseError", () => {
|
||||
it("is an instance of Error with the given message", () => {
|
||||
const err = new InputParseError("invalid input");
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe("invalid input");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
export class PageNotFoundError extends Error {
|
||||
constructor(message = "Page not found", options?: ErrorOptions) {
|
||||
super(message, options);
|
||||
this.name = "PageNotFoundError";
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pageSchema, pageStatusSchema } from "./page";
|
||||
|
||||
describe("pageSchema", () => {
|
||||
it("accepts a minimal valid page", () => {
|
||||
const result = pageSchema.parse({
|
||||
id: "p1",
|
||||
title: "About",
|
||||
slug: "about",
|
||||
hero: { heading: "About us" },
|
||||
layout: [],
|
||||
seo: { title: "About — My App" },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
expect(result.status).toBe("draft");
|
||||
expect(result.publishedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts a published page with publishedAt", () => {
|
||||
const result = pageSchema.parse({
|
||||
id: "p1",
|
||||
title: "About",
|
||||
slug: "about",
|
||||
hero: { heading: "About us" },
|
||||
layout: [],
|
||||
status: "published",
|
||||
publishedAt: new Date(),
|
||||
seo: { title: "About" },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
expect(result.status).toBe("published");
|
||||
expect(result.publishedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("rejects empty title", () => {
|
||||
expect(() =>
|
||||
pageSchema.parse({
|
||||
id: "p1",
|
||||
title: "",
|
||||
slug: "about",
|
||||
hero: { heading: "h" },
|
||||
layout: [],
|
||||
seo: { title: "x" },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pageStatusSchema", () => {
|
||||
it("accepts draft and published", () => {
|
||||
expect(pageStatusSchema.parse("draft")).toBe("draft");
|
||||
expect(pageStatusSchema.parse("published")).toBe("published");
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const pageStatusSchema = z.enum(["draft", "published"]);
|
||||
|
||||
export const heroSchema = z.object({
|
||||
heading: z.string().min(1).max(255),
|
||||
subheading: z.string().optional(),
|
||||
imageId: z.string().optional(),
|
||||
});
|
||||
|
||||
export const pageSchema = z.object({
|
||||
id: z.string(),
|
||||
title: z.string().min(1).max(255),
|
||||
slug: z.string().min(1).max(255),
|
||||
hero: heroSchema,
|
||||
layout: z.array(z.unknown()),
|
||||
status: pageStatusSchema.default("draft"),
|
||||
publishedAt: z.date().nullable().default(null),
|
||||
seo: z.object({
|
||||
title: z.string().min(1),
|
||||
description: z.string().optional(),
|
||||
}),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
});
|
||||
|
||||
export type Page = z.infer<typeof pageSchema>;
|
||||
export type PageStatus = z.infer<typeof pageStatusSchema>;
|
||||
export type Hero = z.infer<typeof heroSchema>;
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { siteSettingsSchema } from "./site-settings";
|
||||
|
||||
describe("siteSettingsSchema", () => {
|
||||
it("accepts a valid site settings object", () => {
|
||||
const result = siteSettingsSchema.parse({
|
||||
siteName: "My Site",
|
||||
siteDescription: "A great site",
|
||||
});
|
||||
expect(result.siteName).toBe("My Site");
|
||||
expect(result.siteDescription).toBe("A great site");
|
||||
});
|
||||
|
||||
it("accepts site settings without a description", () => {
|
||||
const result = siteSettingsSchema.parse({ siteName: "My Site" });
|
||||
expect(result.siteName).toBe("My Site");
|
||||
expect(result.siteDescription).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects an empty siteName", () => {
|
||||
expect(() => siteSettingsSchema.parse({ siteName: "" })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const siteSettingsSchema = z.object({
|
||||
siteName: z.string().min(1),
|
||||
siteDescription: z.string().optional(),
|
||||
});
|
||||
|
||||
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
|
||||
@@ -1,25 +0,0 @@
|
||||
// packages/marketing-pages/src/events/handlers/on-auth-user-signed-up.handler.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { RecordingJobQueue } from "@repo/core-testing/instrumentation";
|
||||
import { onAuthUserSignedUpHandler } from "@/events/handlers/on-auth-user-signed-up.handler";
|
||||
|
||||
describe("onAuthUserSignedUpHandler", () => {
|
||||
it("enqueues marketing-pages.send-welcome-email with userId + email", async () => {
|
||||
const queue = new RecordingJobQueue();
|
||||
const handler = onAuthUserSignedUpHandler(queue);
|
||||
|
||||
await handler({
|
||||
userId: "u-42",
|
||||
email: "alice@example.com",
|
||||
signedUpAt: "2026-05-08T12:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(queue.enqueued).toHaveLength(1);
|
||||
expect(queue.enqueued[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
taskSlug: "marketing-pages.send-welcome-email",
|
||||
input: { userId: "u-42", email: "alice@example.com" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
// packages/marketing-pages/src/events/handlers/on-auth-user-signed-up.handler.ts
|
||||
import type { UserSignedUpEvent } from "@repo/auth";
|
||||
import type { IJobQueue } from "@repo/core-shared/jobs";
|
||||
|
||||
export type IOnAuthUserSignedUpHandler = ReturnType<
|
||||
typeof onAuthUserSignedUpHandler
|
||||
>;
|
||||
|
||||
export const onAuthUserSignedUpHandler =
|
||||
(queue: IJobQueue) =>
|
||||
async (event: UserSignedUpEvent): Promise<void> => {
|
||||
await queue.enqueue("marketing-pages.send-welcome-email", {
|
||||
userId: event.userId,
|
||||
email: event.email,
|
||||
});
|
||||
};
|
||||
@@ -1,41 +0,0 @@
|
||||
import { defineFeature } from "@repo/core-shared/conformance";
|
||||
|
||||
/**
|
||||
* The marketing-pages feature's conformance manifest.
|
||||
*/
|
||||
export const marketingPagesManifest = defineFeature({
|
||||
name: "marketing-pages",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
getPageBySlug: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
getSiteSettings: {
|
||||
mutates: false,
|
||||
audits: [],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
},
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
coverage: {
|
||||
bands: {
|
||||
baseline: { statements: 80, branches: 75, functions: 80, lines: 80 },
|
||||
entities: { statements: 100, branches: 100, functions: 100, lines: 100 },
|
||||
"use-cases": {
|
||||
statements: 100,
|
||||
branches: 95,
|
||||
functions: 100,
|
||||
lines: 100,
|
||||
},
|
||||
controllers: {
|
||||
statements: 100,
|
||||
branches: 95,
|
||||
functions: 100,
|
||||
lines: 100,
|
||||
},
|
||||
},
|
||||
mutationTargets: ["entities", "use-cases"],
|
||||
},
|
||||
} as const);
|
||||
|
||||
export type MarketingPagesManifest = typeof marketingPagesManifest;
|
||||
@@ -1,32 +0,0 @@
|
||||
export type { Page, PageStatus, Hero } from "./entities/models/page";
|
||||
export type { SiteSettings } from "./entities/models/site-settings";
|
||||
export type { MarketingPagesRouter } from "./integrations/api/router";
|
||||
export { PageNotFoundError } from "./entities/errors/page";
|
||||
export { InputParseError } from "./entities/errors/common";
|
||||
|
||||
// Use case schemas + types
|
||||
export {
|
||||
getPageBySlugInputSchema,
|
||||
getPageBySlugOutputSchema,
|
||||
type GetPageBySlugInput,
|
||||
type GetPageBySlugOutput,
|
||||
type IGetPageBySlugUseCase,
|
||||
} from "./application/use-cases/get-page-by-slug.use-case";
|
||||
export {
|
||||
getSiteSettingsInputSchema,
|
||||
getSiteSettingsOutputSchema,
|
||||
type GetSiteSettingsInput,
|
||||
type GetSiteSettingsOutput,
|
||||
type IGetSiteSettingsUseCase,
|
||||
} from "./application/use-cases/get-site-settings.use-case";
|
||||
|
||||
// Controller type aliases
|
||||
export type { IGetPageBySlugController } from "./interface-adapters/controllers/get-page-by-slug.controller";
|
||||
export type { IGetSiteSettingsController } from "./interface-adapters/controllers/get-site-settings.controller";
|
||||
|
||||
// <gen:events>
|
||||
// <gen:realtime-channels>
|
||||
export {
|
||||
marketingPagesManifest,
|
||||
type MarketingPagesManifest,
|
||||
} from "./feature.manifest";
|
||||
@@ -1,17 +0,0 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
import {
|
||||
pagesRepositoryContract,
|
||||
CONTRACT_PAGES_SEED,
|
||||
} from "@/__contracts__/pages-repository.contract";
|
||||
|
||||
describe("MockPagesRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
// Pre-seed with the contract fixtures so the contract assertions find what
|
||||
// they expect (an "about" published page and a "draft-page" draft page).
|
||||
pagesRepositoryContract.run(
|
||||
() => new MockPagesRepository(CONTRACT_PAGES_SEED, tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IPagesRepository } from "../../application/repositories/pages.repository.interface";
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
const SEED_DATE = new Date("2026-01-01T00:00:00.000Z");
|
||||
|
||||
const DEFAULT_SEED: Page[] = [
|
||||
{
|
||||
id: "p1",
|
||||
title: "About",
|
||||
slug: "about",
|
||||
hero: { heading: "About us" },
|
||||
layout: [],
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "About — My App" },
|
||||
createdAt: SEED_DATE,
|
||||
updatedAt: SEED_DATE,
|
||||
},
|
||||
];
|
||||
|
||||
@injectable()
|
||||
export class MockPagesRepository implements IPagesRepository {
|
||||
private _pages: Page[];
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
initialPages: Page[] = DEFAULT_SEED,
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this._pages = [...initialPages];
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
void this.logger; // currently unused; reserved for future mock-thrown captures
|
||||
}
|
||||
|
||||
async getPageBySlug(slug: string): Promise<Page | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "pages.getPageBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
const found = this._pages.find((p) => p.slug === slug);
|
||||
span.setAttribute("found", Boolean(found));
|
||||
return found;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getPages(options?: {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Page[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "pages.getPages",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
limit: options?.limit ?? null,
|
||||
offset: options?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
let result = [...this._pages];
|
||||
if (options?.status) {
|
||||
result = result.filter((p) => p.status === options.status);
|
||||
}
|
||||
const offset = options?.offset ?? 0;
|
||||
const limit = options?.limit ?? 50;
|
||||
const page = result.slice(offset, offset + limit);
|
||||
span.setAttribute("count", page.length);
|
||||
return page;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
|
||||
// Mock repo also wraps in spans.
|
||||
describe("MockPagesRepository emits spans", () => {
|
||||
it("getPageBySlug emits one span with op='repository'", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockPagesRepository([], tracer, logger);
|
||||
await repo.getPageBySlug("about");
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
expect(tracer.spans[0]).toMatchObject({
|
||||
name: "pages.getPageBySlug",
|
||||
op: "repository",
|
||||
});
|
||||
expect(tracer.spans[0]!.attributes.slug).toBe("about");
|
||||
expect(tracer.spans[0]!.attributes.found).toBe(false);
|
||||
});
|
||||
|
||||
it("getPages emits a span with count attribute", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockPagesRepository(undefined, tracer);
|
||||
await repo.getPages({ limit: 10 });
|
||||
expect(tracer.findSpan("pages.getPages")).toBeDefined();
|
||||
expect(tracer.findSpan("pages.getPages")!.attributes.limit).toBe(10);
|
||||
expect(
|
||||
tracer.findSpan("pages.getPages")!.attributes.count,
|
||||
).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
import { describe, vi } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { PagesRepository } from "@/infrastructure/repositories/pages.repository";
|
||||
import {
|
||||
pagesRepositoryContract,
|
||||
CONTRACT_PAGES_SEED,
|
||||
} from "@/__contracts__/pages-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
import type { Page } from "@/entities/models/page";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub for pages (read-only collection)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildPayloadPagesStub(seed: Page[]) {
|
||||
const store = new Map<string, Record<string, unknown>>(
|
||||
seed.map((p) => [
|
||||
p.id,
|
||||
{
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
slug: p.slug,
|
||||
hero: p.hero
|
||||
? {
|
||||
heading: p.hero.heading,
|
||||
subheading: p.hero.subheading,
|
||||
}
|
||||
: null,
|
||||
layout: p.layout,
|
||||
status: p.status,
|
||||
publishedAt: p.publishedAt ? p.publishedAt.toISOString() : null,
|
||||
seo: p.seo ? { title: p.seo.title, description: p.seo.description } : null,
|
||||
createdAt: p.createdAt.toISOString(),
|
||||
updatedAt: p.updatedAt.toISOString(),
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
return {
|
||||
find: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
limit,
|
||||
}: {
|
||||
collection: string;
|
||||
where?: { slug?: { equals: string }; status?: { equals: string } };
|
||||
limit?: number;
|
||||
page?: number;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
let docs = Array.from(store.values());
|
||||
if (where?.slug) {
|
||||
docs = docs.filter((d) => d.slug === where.slug?.equals);
|
||||
}
|
||||
if (where?.status) {
|
||||
docs = docs.filter((d) => d.status === where.status?.equals);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
docs = docs.slice(0, limit);
|
||||
}
|
||||
return { docs };
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PagesRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
pagesRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildPayloadPagesStub(CONTRACT_PAGES_SEED);
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new PagesRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import { getPayload } from "payload";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IPagesRepository } from "../../application/repositories/pages.repository.interface";
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
type PayloadPageDoc = {
|
||||
id: string | number;
|
||||
title?: string | null;
|
||||
slug?: string | null;
|
||||
hero?:
|
||||
| {
|
||||
heading?: string | null;
|
||||
subheading?: string | null;
|
||||
image?: string | number | { id: string | number } | null;
|
||||
}
|
||||
| null;
|
||||
layout?: unknown[] | null;
|
||||
status?: string | null;
|
||||
publishedAt?: string | null;
|
||||
seo?: { title?: string | null; description?: string | null } | null;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
};
|
||||
|
||||
function mapDoc(doc: PayloadPageDoc): Page {
|
||||
const imageId =
|
||||
doc.hero && typeof doc.hero.image === "object" && doc.hero.image !== null
|
||||
? String(doc.hero.image.id)
|
||||
: doc.hero?.image != null
|
||||
? String(doc.hero.image)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: String(doc.id),
|
||||
title: doc.title ?? "",
|
||||
slug: doc.slug ?? "",
|
||||
hero: {
|
||||
heading: doc.hero?.heading ?? "",
|
||||
subheading: doc.hero?.subheading ?? undefined,
|
||||
imageId,
|
||||
},
|
||||
layout: doc.layout ?? [],
|
||||
status: doc.status === "published" ? "published" : "draft",
|
||||
publishedAt: doc.publishedAt ? new Date(doc.publishedAt) : null,
|
||||
seo: {
|
||||
title: doc.seo?.title ?? "",
|
||||
description: doc.seo?.description ?? undefined,
|
||||
},
|
||||
createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(0),
|
||||
updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
const FEATURE = "marketing-pages" as const;
|
||||
const REPO = "pages" as const;
|
||||
|
||||
@injectable()
|
||||
export class PagesRepository implements IPagesRepository {
|
||||
private config: SanitizedConfig;
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
config: SanitizedConfig,
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this.config = config;
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async getPageBySlug(slug: string): Promise<Page | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "pages.getPageBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const result = await payload.find({
|
||||
collection: "pages",
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const doc = result.docs[0] as PayloadPageDoc | undefined;
|
||||
span.setAttribute("found", Boolean(doc));
|
||||
return doc ? mapDoc(doc) : undefined;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getPageBySlug" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getPages(options?: {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Page[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "pages.getPages",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
limit: options?.limit ?? null,
|
||||
offset: options?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const where: Record<string, { equals: string }> = {};
|
||||
if (options?.status) where.status = { equals: options.status };
|
||||
const result = await payload.find({
|
||||
collection: "pages",
|
||||
where: where as never,
|
||||
limit: options?.limit ?? 50,
|
||||
page: options?.offset
|
||||
? Math.floor(options.offset / (options.limit ?? 50)) + 1
|
||||
: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const pages = result.docs.map((d) => mapDoc(d as PayloadPageDoc));
|
||||
span.setAttribute("count", pages.length);
|
||||
return pages;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getPages" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
import { siteSettingsRepositoryContract } from "@/__contracts__/site-settings-repository.contract";
|
||||
|
||||
describe("MockSiteSettingsRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
siteSettingsRepositoryContract.run(
|
||||
() => new MockSiteSettingsRepository(tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { ISiteSettingsRepository } from "../../application/repositories/site-settings.repository.interface";
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
@injectable()
|
||||
export class MockSiteSettingsRepository implements ISiteSettingsRepository {
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
void this.logger; // currently unused; reserved for future mock-thrown captures
|
||||
}
|
||||
|
||||
async getSiteSettings(): Promise<SiteSettings> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "site-settings.getSiteSettings", op: "repository", attributes: {} },
|
||||
async (span) => {
|
||||
span.setAttribute("found", true);
|
||||
return {
|
||||
siteName: "My App",
|
||||
siteDescription: "A vertical-feature monorepo template",
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
|
||||
// Mock repo also wraps in spans.
|
||||
describe("MockSiteSettingsRepository emits spans", () => {
|
||||
it("getSiteSettings emits one span with op='repository'", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockSiteSettingsRepository(tracer, logger);
|
||||
await repo.getSiteSettings();
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
expect(tracer.spans[0]).toMatchObject({
|
||||
name: "site-settings.getSiteSettings",
|
||||
op: "repository",
|
||||
});
|
||||
expect(tracer.spans[0]!.attributes.found).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, vi } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { SiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository";
|
||||
import { siteSettingsRepositoryContract } from "@/__contracts__/site-settings-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub for site-settings (Global)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildSiteSettingsStub() {
|
||||
const globalData: Record<string, unknown> = {
|
||||
siteName: "Contract Site",
|
||||
siteDescription: "A site for contract testing",
|
||||
};
|
||||
|
||||
return {
|
||||
findGlobal: vi.fn(async () => {
|
||||
return { ...globalData };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SiteSettingsRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
siteSettingsRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildSiteSettingsStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new SiteSettingsRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import { getPayload } from "payload";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { ISiteSettingsRepository } from "../../application/repositories/site-settings.repository.interface";
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
type PayloadSiteSettings = {
|
||||
siteName?: string | null;
|
||||
siteDescription?: string | null;
|
||||
};
|
||||
|
||||
const FEATURE = "marketing-pages" as const;
|
||||
const REPO = "site-settings" as const;
|
||||
|
||||
@injectable()
|
||||
export class SiteSettingsRepository implements ISiteSettingsRepository {
|
||||
private config: SanitizedConfig;
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
config: SanitizedConfig,
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this.config = config;
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async getSiteSettings(): Promise<SiteSettings> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "site-settings.getSiteSettings", op: "repository", attributes: {} },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const doc = (await payload.findGlobal({
|
||||
slug: "site-settings",
|
||||
overrideAccess: true,
|
||||
})) as PayloadSiteSettings;
|
||||
span.setAttribute("found", true);
|
||||
return {
|
||||
siteName: doc.siteName ?? "My App",
|
||||
siteDescription: doc.siteDescription ?? undefined,
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getSiteSettings" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { RecordingMailerService } from "@/infrastructure/services/recording-mailer.service";
|
||||
|
||||
describe("RecordingMailerService", () => {
|
||||
it("records welcome calls", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
await mailer.sendWelcome("u1", "u1@example.com");
|
||||
expect(mailer.sent).toEqual([{ userId: "u1", email: "u1@example.com" }]);
|
||||
});
|
||||
|
||||
it("preserves call order across multiple sends", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
await mailer.sendWelcome("u1", "a@x");
|
||||
await mailer.sendWelcome("u2", "b@x");
|
||||
expect(mailer.sent).toEqual([
|
||||
{ userId: "u1", email: "a@x" },
|
||||
{ userId: "u2", email: "b@x" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { IMailerService } from "../../application/services/mailer.service.interface";
|
||||
|
||||
export class RecordingMailerService implements IMailerService {
|
||||
readonly sent: { userId: string; email: string }[] = [];
|
||||
|
||||
async sendWelcome(userId: string, email: string): Promise<void> {
|
||||
this.sent.push({ userId, email });
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { t } from "@repo/core-shared/trpc/init";
|
||||
import { defineErrorMiddleware } from "@repo/core-shared/trpc/define-error-middleware";
|
||||
|
||||
import { PageNotFoundError } from "../../entities/errors/page";
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
|
||||
export const marketingPagesProcedure = t.procedure.use(
|
||||
defineErrorMiddleware([
|
||||
[InputParseError, "BAD_REQUEST"],
|
||||
[PageNotFoundError, "NOT_FOUND"],
|
||||
]),
|
||||
);
|
||||
@@ -1,62 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { marketingPagesContainer } from "@/di/container";
|
||||
import { MarketingPagesModule } from "@/di/module";
|
||||
import { marketingPagesRouter } from "@/integrations/api/router";
|
||||
|
||||
describe("marketingPagesRouter", () => {
|
||||
beforeEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
marketingPagesContainer.load(MarketingPagesModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("exposes pageBySlug + siteSettings procedures", () => {
|
||||
const names = Object.keys(marketingPagesRouter._def.procedures);
|
||||
expect(names).toContain("pageBySlug");
|
||||
expect(names).toContain("siteSettings");
|
||||
});
|
||||
|
||||
it("pageBySlug returns the seeded About page", async () => {
|
||||
const caller = marketingPagesRouter.createCaller({});
|
||||
const result = await caller.pageBySlug({ slug: "about" });
|
||||
expect(result?.title).toBe("About");
|
||||
});
|
||||
|
||||
it("siteSettings returns site name", async () => {
|
||||
const caller = marketingPagesRouter.createCaller({});
|
||||
const result = await caller.siteSettings({});
|
||||
expect(result.siteName).toBe("My App");
|
||||
});
|
||||
});
|
||||
|
||||
describe("marketingPagesRouter error mapping", () => {
|
||||
beforeEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
marketingPagesContainer.load(MarketingPagesModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
marketingPagesContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("translates zod parse failure → BAD_REQUEST on pageBySlug", async () => {
|
||||
const caller = marketingPagesRouter.createCaller({});
|
||||
try {
|
||||
await caller.pageBySlug({} as unknown as { slug: string });
|
||||
throw new Error("expected throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(TRPCError);
|
||||
expect((e as TRPCError).code).toBe("BAD_REQUEST");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns undefined (not NOT_FOUND) for missing slug since use case returns undefined", async () => {
|
||||
const caller = marketingPagesRouter.createCaller({});
|
||||
const result = await caller.pageBySlug({ slug: "does-not-exist" });
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import { router } from "@repo/core-shared/trpc/init";
|
||||
|
||||
import { marketingPagesContainer } from "../../di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "../../di/symbols";
|
||||
|
||||
import { getPageBySlugInputSchema } from "../../application/use-cases/get-page-by-slug.use-case";
|
||||
import { getSiteSettingsInputSchema } from "../../application/use-cases/get-site-settings.use-case";
|
||||
|
||||
import type { IGetPageBySlugController } from "../../interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import type { IGetSiteSettingsController } from "../../interface-adapters/controllers/get-site-settings.controller";
|
||||
|
||||
import { marketingPagesProcedure } from "./procedures";
|
||||
|
||||
export const marketingPagesRouter = router({
|
||||
pageBySlug: marketingPagesProcedure
|
||||
.input(getPageBySlugInputSchema)
|
||||
.query(({ input }) => {
|
||||
const ctrl = marketingPagesContainer.get<IGetPageBySlugController>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetPageBySlugController,
|
||||
);
|
||||
return ctrl(input);
|
||||
}),
|
||||
|
||||
siteSettings: marketingPagesProcedure
|
||||
.input(getSiteSettingsInputSchema)
|
||||
.query(({ input }) => {
|
||||
const ctrl = marketingPagesContainer.get<IGetSiteSettingsController>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetSiteSettingsController,
|
||||
);
|
||||
return ctrl(input);
|
||||
}),
|
||||
});
|
||||
|
||||
export type MarketingPagesRouter = typeof marketingPagesRouter;
|
||||
@@ -1,76 +0,0 @@
|
||||
import type { CollectionConfig } from "payload";
|
||||
import { cta, seoFields, slugifyIfMissing } from "@repo/core-shared/payload";
|
||||
|
||||
export const pages: CollectionConfig = {
|
||||
slug: "pages",
|
||||
custom: {
|
||||
retention: {
|
||||
purgeSchedule: "monthly",
|
||||
postDeletion: {
|
||||
duration: "P90D",
|
||||
trigger: "after-deletion",
|
||||
action: "hard-delete",
|
||||
},
|
||||
},
|
||||
},
|
||||
admin: {
|
||||
useAsTitle: "title",
|
||||
defaultColumns: ["title", "status", "updatedAt"],
|
||||
},
|
||||
hooks: {
|
||||
beforeChange: [slugifyIfMissing],
|
||||
},
|
||||
versions: {
|
||||
drafts: true,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "title",
|
||||
type: "text",
|
||||
required: true,
|
||||
maxLength: 255,
|
||||
},
|
||||
{
|
||||
name: "slug",
|
||||
type: "text",
|
||||
unique: true,
|
||||
admin: {
|
||||
position: "sidebar",
|
||||
description: "Auto-generated from title if left empty",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "hero",
|
||||
type: "group",
|
||||
fields: [
|
||||
{ name: "heading", type: "text", required: true },
|
||||
{ name: "subheading", type: "textarea" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "layout",
|
||||
type: "blocks",
|
||||
blocks: [cta],
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ label: "Draft", value: "draft" },
|
||||
{ label: "Published", value: "published" },
|
||||
],
|
||||
defaultValue: "draft",
|
||||
required: true,
|
||||
admin: { position: "sidebar" },
|
||||
},
|
||||
{
|
||||
name: "publishedAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
position: "sidebar",
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
},
|
||||
},
|
||||
seoFields,
|
||||
],
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { GlobalConfig } from "payload";
|
||||
|
||||
export const siteSettings: GlobalConfig = {
|
||||
slug: "site-settings",
|
||||
custom: {
|
||||
retention: {
|
||||
purgeSchedule: "monthly",
|
||||
postDeletion: {
|
||||
duration: "P90D",
|
||||
trigger: "after-deletion",
|
||||
action: "hard-delete",
|
||||
},
|
||||
},
|
||||
},
|
||||
admin: {
|
||||
group: "Settings",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "siteName",
|
||||
type: "text",
|
||||
required: true,
|
||||
defaultValue: "My App",
|
||||
},
|
||||
{
|
||||
name: "siteDescription",
|
||||
type: "textarea",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
export { pages } from "./collections/pages";
|
||||
export { siteSettings } from "./globals/site-settings";
|
||||
// <gen:job-tasks>
|
||||
export { sendWelcomeEmailTask } from "./jobs/send-welcome-email.task";
|
||||
export { onAuthUserSignedUpEventTask } from "./jobs/__events-auth-user-signed-up.task";
|
||||
@@ -1,26 +0,0 @@
|
||||
// packages/marketing-pages/src/integrations/cms/jobs/__events-auth-user-signed-up.task.ts
|
||||
// Generated by `gen event consume`. The PayloadJobsEventBus enqueues this task
|
||||
// when auth publishes `auth.user.signed-up`. The handler
|
||||
// resolves the consumer's wrapped event handler from the per-feature container
|
||||
// and invokes it with the typed payload.
|
||||
import type { TaskConfig } from "payload";
|
||||
import { marketingPagesContainer } from "../../../di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "../../../di/symbols";
|
||||
import type { IOnAuthUserSignedUpHandler } from "../../../events/handlers/on-auth-user-signed-up.handler";
|
||||
import type { UserSignedUpEvent } from "@repo/auth";
|
||||
|
||||
export const onAuthUserSignedUpEventTask: TaskConfig<{
|
||||
input: UserSignedUpEvent;
|
||||
output: object;
|
||||
}> = {
|
||||
slug: "__events.auth.user.signed-up.marketing-pages",
|
||||
inputSchema: [],
|
||||
retries: { attempts: 3, backoff: { type: "exponential", delay: 1000 } },
|
||||
handler: async ({ input }) => {
|
||||
const handler = marketingPagesContainer.get<IOnAuthUserSignedUpHandler>(
|
||||
MARKETING_PAGES_SYMBOLS.IOnAuthUserSignedUpHandler,
|
||||
);
|
||||
await handler(input);
|
||||
return { output: {} };
|
||||
},
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
// packages/marketing-pages/src/integrations/cms/jobs/send-welcome-email.task.ts
|
||||
import type { TaskConfig } from "payload";
|
||||
import { marketingPagesContainer } from "../../../di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "../../../di/symbols";
|
||||
import type { ISendWelcomeEmailJob } from "../../../jobs/send-welcome-email.job";
|
||||
import type { SendWelcomeEmailInput } from "../../../jobs/send-welcome-email.job";
|
||||
|
||||
export const sendWelcomeEmailTask: TaskConfig<{
|
||||
input: SendWelcomeEmailInput;
|
||||
output: object;
|
||||
}> = {
|
||||
slug: "marketing-pages.send-welcome-email",
|
||||
inputSchema: [],
|
||||
retries: { attempts: 3, backoff: { type: "exponential", delay: 1000 } },
|
||||
handler: async ({ input }) => {
|
||||
const job = marketingPagesContainer.get<ISendWelcomeEmailJob>(
|
||||
MARKETING_PAGES_SYMBOLS.ISendWelcomeEmailJob,
|
||||
);
|
||||
await job(input);
|
||||
return { output: {} };
|
||||
},
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getPageBySlugController } from "@/interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import { getPageBySlugUseCase } from "@/application/use-cases/get-page-by-slug.use-case";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
|
||||
describe("getPageBySlugController", () => {
|
||||
it("returns the page when found", async () => {
|
||||
const repo = new MockPagesRepository();
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
const controller = getPageBySlugController(useCase);
|
||||
|
||||
const result = await controller({ slug: "about" });
|
||||
expect(result?.slug).toBe("about");
|
||||
});
|
||||
|
||||
it("throws InputParseError on missing slug", async () => {
|
||||
const repo = new MockPagesRepository();
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
const controller = getPageBySlugController(useCase);
|
||||
|
||||
await expect(
|
||||
controller({}),
|
||||
).rejects.toBeInstanceOf(InputParseError);
|
||||
});
|
||||
|
||||
it("returns undefined when slug not found", async () => {
|
||||
const repo = new MockPagesRepository();
|
||||
const useCase = getPageBySlugUseCase(repo);
|
||||
const controller = getPageBySlugController(useCase);
|
||||
|
||||
const result = await controller({ slug: "nonexistent" });
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import {
|
||||
getPageBySlugInputSchema,
|
||||
type GetPageBySlugOutput,
|
||||
type IGetPageBySlugUseCase,
|
||||
} from "../../application/use-cases/get-page-by-slug.use-case";
|
||||
|
||||
function presenter(value: GetPageBySlugOutput) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export type IGetPageBySlugController = ReturnType<typeof getPageBySlugController>;
|
||||
|
||||
export const getPageBySlugController =
|
||||
(getPageBySlugUseCase: IGetPageBySlugUseCase) =>
|
||||
async (input: unknown): Promise<ReturnType<typeof presenter> | undefined> => {
|
||||
const parsed = getPageBySlugInputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid get-page-by-slug input", { cause: parsed.error });
|
||||
}
|
||||
const result = await getPageBySlugUseCase(parsed.data);
|
||||
if (result === undefined) return undefined;
|
||||
return presenter(result);
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getSiteSettingsController } from "@/interface-adapters/controllers/get-site-settings.controller";
|
||||
import { getSiteSettingsUseCase } from "@/application/use-cases/get-site-settings.use-case";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
|
||||
describe("getSiteSettingsController", () => {
|
||||
it("returns site settings", async () => {
|
||||
const repo = new MockSiteSettingsRepository();
|
||||
const useCase = getSiteSettingsUseCase(repo);
|
||||
const controller = getSiteSettingsController(useCase);
|
||||
|
||||
const result = await controller({});
|
||||
expect(result.siteName).toBe("My App");
|
||||
});
|
||||
|
||||
it("throws InputParseError on unknown fields (strict schema)", async () => {
|
||||
const repo = new MockSiteSettingsRepository();
|
||||
const useCase = getSiteSettingsUseCase(repo);
|
||||
const controller = getSiteSettingsController(useCase);
|
||||
|
||||
await expect(controller({ unknownField: 1 })).rejects.toThrow(
|
||||
InputParseError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import {
|
||||
getSiteSettingsInputSchema,
|
||||
type GetSiteSettingsOutput,
|
||||
type IGetSiteSettingsUseCase,
|
||||
} from "../../application/use-cases/get-site-settings.use-case";
|
||||
|
||||
function presenter(value: GetSiteSettingsOutput) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export type IGetSiteSettingsController = ReturnType<typeof getSiteSettingsController>;
|
||||
|
||||
export const getSiteSettingsController =
|
||||
(getSiteSettingsUseCase: IGetSiteSettingsUseCase) =>
|
||||
async (input: unknown): Promise<ReturnType<typeof presenter>> => {
|
||||
const parsed = getSiteSettingsInputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid get-site-settings input", { cause: parsed.error });
|
||||
}
|
||||
const result = await getSiteSettingsUseCase(parsed.data);
|
||||
return presenter(result);
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
// packages/marketing-pages/src/jobs/send-welcome-email.job.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sendWelcomeEmailJob, sendWelcomeEmailInputSchema } from "@/jobs/send-welcome-email.job";
|
||||
import { RecordingMailerService } from "@/infrastructure/services/recording-mailer.service";
|
||||
|
||||
describe("sendWelcomeEmailJob", () => {
|
||||
it("rejects unknown input fields", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
const job = sendWelcomeEmailJob(mailer);
|
||||
await expect(job({ unexpectedField: 1 } as never)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects input missing required fields", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
const job = sendWelcomeEmailJob(mailer);
|
||||
await expect(job({ userId: "u1" } as never)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects invalid email", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
const job = sendWelcomeEmailJob(mailer);
|
||||
await expect(
|
||||
job({ userId: "u1", email: "not-an-email" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("sends a welcome email via the mailer on valid input", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
const job = sendWelcomeEmailJob(mailer);
|
||||
await job({ userId: "u1", email: "u1@example.com" });
|
||||
expect(mailer.sent).toEqual([{ userId: "u1", email: "u1@example.com" }]);
|
||||
});
|
||||
|
||||
it("references its input schema", () => {
|
||||
expect(sendWelcomeEmailInputSchema).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
// packages/marketing-pages/src/jobs/send-welcome-email.job.ts
|
||||
import { z } from "zod";
|
||||
import type { IMailerService } from "../application/services/mailer.service.interface";
|
||||
|
||||
export const sendWelcomeEmailInputSchema = z
|
||||
.object({
|
||||
userId: z.string(),
|
||||
email: z.string().email(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type SendWelcomeEmailInput = z.infer<typeof sendWelcomeEmailInputSchema>;
|
||||
export type ISendWelcomeEmailJob = ReturnType<typeof sendWelcomeEmailJob>;
|
||||
|
||||
export const sendWelcomeEmailJob =
|
||||
(mailer: IMailerService) =>
|
||||
async (input: SendWelcomeEmailInput): Promise<void> => {
|
||||
sendWelcomeEmailInputSchema.parse(input);
|
||||
await mailer.sendWelcome(input.userId, input.email);
|
||||
};
|
||||
@@ -1,25 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { usePageBySlug } from "../hooks/use-page-by-slug";
|
||||
import { PageHero } from "./page-hero";
|
||||
|
||||
export type PageContentProps = {
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export function PageContent({ slug }: PageContentProps) {
|
||||
const { data: page } = usePageBySlug(slug);
|
||||
|
||||
if (!page) return null;
|
||||
|
||||
return (
|
||||
<article className="mx-auto max-w-3xl">
|
||||
<PageHero hero={page.hero} />
|
||||
<div className="prose text-foreground">
|
||||
<pre className="whitespace-pre-wrap text-sm">
|
||||
{JSON.stringify(page.layout, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
|
||||
import { getQueryClient } from "@repo/core-trpc";
|
||||
import { marketingPagesContainer } from "../../di/container";
|
||||
import { MARKETING_PAGES_SYMBOLS } from "../../di/symbols";
|
||||
import type { IGetPageBySlugController } from "../../interface-adapters/controllers/get-page-by-slug.controller";
|
||||
import { PageContent as PageContentClient } from "./page-content.client";
|
||||
|
||||
export async function PageContent({ slug }: { slug: string }) {
|
||||
const controller = marketingPagesContainer.get<IGetPageBySlugController>(
|
||||
MARKETING_PAGES_SYMBOLS.IGetPageBySlugController,
|
||||
);
|
||||
const page = await controller({ slug });
|
||||
const queryClient = getQueryClient();
|
||||
queryClient.setQueryData(
|
||||
["marketingPages", "pageBySlug", { input: { slug } }],
|
||||
page,
|
||||
);
|
||||
|
||||
if (!page) {
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-6 py-8">
|
||||
<h1 className="text-3xl font-bold text-foreground">Not found</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
This page hasn't been published yet.
|
||||
</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||
<PageContentClient slug={slug} />
|
||||
</HydrationBoundary>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { Hero } from "../../entities/models/page";
|
||||
|
||||
export type PageHeroProps = {
|
||||
hero: Hero;
|
||||
};
|
||||
|
||||
export function PageHero({ hero }: PageHeroProps) {
|
||||
return (
|
||||
<header className="mb-8">
|
||||
<h1 className="text-3xl font-bold text-foreground">{hero.heading}</h1>
|
||||
{hero.subheading ? (
|
||||
<p className="mt-2 text-lg text-muted-foreground">{hero.subheading}</p>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSuspenseQuery } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@repo/core-trpc";
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
export function usePageBySlug(slug: string) {
|
||||
const trpc = useTRPC();
|
||||
return useSuspenseQuery(
|
||||
trpc.marketingPages.pageBySlug.queryOptions({ slug }),
|
||||
) as { data: Page | null };
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useSuspenseQuery } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@repo/core-trpc";
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
export function useSiteSettings() {
|
||||
const trpc = useTRPC();
|
||||
return useSuspenseQuery(
|
||||
trpc.marketingPages.siteSettings.queryOptions({}),
|
||||
) as { data: SiteSettings };
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export { pageBySlugQuery, siteSettingsQuery } from "./query";
|
||||
export { usePageBySlug } from "./hooks/use-page-by-slug";
|
||||
export { useSiteSettings } from "./hooks/use-site-settings";
|
||||
export { PageHero, type PageHeroProps } from "./components/page-hero";
|
||||
export { PageContent } from "./components/page-content.server";
|
||||
@@ -1,14 +0,0 @@
|
||||
type TrpcClient = {
|
||||
marketingPages: {
|
||||
pageBySlug: { queryOptions: (input: { slug: string }) => unknown };
|
||||
siteSettings: { queryOptions: () => unknown };
|
||||
};
|
||||
};
|
||||
|
||||
export function pageBySlugQuery(client: TrpcClient, slug: string) {
|
||||
return client.marketingPages.pageBySlug.queryOptions({ slug });
|
||||
}
|
||||
|
||||
export function siteSettingsQuery(client: TrpcClient) {
|
||||
return client.marketingPages.siteSettings.queryOptions();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user