Skip to content

Fix spillover from digest preview#809

Merged
elie222 merged 6 commits intomainfrom
fix/digest-styling-spillover
Sep 21, 2025
Merged

Fix spillover from digest preview#809
elie222 merged 6 commits intomainfrom
fix/digest-styling-spillover

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 21, 2025

Summary by CodeRabbit

  • New Features

    • Added a TimePicker and unified single time field for scheduling; "Save" label updated.
    • Live HTML preview of digest emails in Settings, shown in an iframe.
    • Clearer display labels for selected digests (e.g., “Cold Emails” and rule names).
    • New reusable input component for consistent form controls.
  • Chores

    • Added backend preview endpoint with request validation to power live previews.
    • Added HTML email rendering dependency.
    • Bumped version to v2.10.8.

@vercel
Copy link

vercel bot commented Sep 21, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 21, 2025 3:53pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 21, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Replaces separate hour/minute/AM/PM scheduling with a single time string and TimePicker UI, adds a live HTML digest preview powered by a new /api/digest-preview GET route (validated with Zod) that renders DigestEmail via @react-email/render, and introduces reusable TimePicker and Input components.

Changes

Cohort / File(s) Summary of changes
UI: Digest settings & preview
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
Replaced hour/minute/ampm fields with time: "HH:MM" and a TimePicker; compute schedule/timeOfDay from time; derive selectedDigestNames: string[]; swap local mock preview for SWR-driven fetch and render HTML in an iframe; updated EmailPreview signature to accept selectedDigestNames.
New API: digest preview
apps/web/app/api/digest-preview/route.ts
Added GET handler that validates categories with Zod, builds mock digest payloads by category, renders DigestEmail to HTML via @react-email/render, and returns text/html with 400/500 error handling.
Validation schema
apps/web/app/api/digest-preview/validation.ts
Added exported Zod schema digestPreviewBody and type DigestPreviewBody ({ categories: string[] }) for request validation.
Components: Time & Input
apps/web/components/TimePicker.tsx
apps/web/components/ui/input.tsx
Added client TimePicker component (labeled time input) and a reusable Input component (forwardRef) with styled classes for consistent inputs.
Dependencies & metadata
apps/web/package.json
version.txt
Added dependency @react-email/render@1.2.1; bumped version from v2.10.7 to v2.10.8.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant UI as DigestSettingsForm
  participant SWR as SWR Hook
  participant API as /api/digest-preview
  participant Z as Zod Validation
  participant M as Mock Data Builder
  participant R as @react-email/render

  U->>UI: choose digests & set time (TimePicker)
  UI->>SWR: fetch /api/digest-preview?categories=[names]
  SWR->>API: GET with categories
  API->>Z: validate categories
  alt valid
    API->>M: build mock digest payload
    API->>R: render DigestEmail -> HTML
    R-->>API: HTML string
    API-->>SWR: 200 text/html
    SWR-->>UI: HTML content
    UI->>UI: embed HTML in iframe
  else invalid
    API-->>SWR: 400 error
    SWR-->>UI: show error state
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A nibble, a hop, a rendered sight,
I pick your time and fetch the night,
From rules to HTML, I hum and play,
A little rabbit previewing your day! 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Fix spillover from digest preview" is a concise, single-sentence summary that directly targets the primary user-facing change in this PR: switching the digest preview to a live HTML preview fetched from /api/digest-preview and rendered in an iframe to prevent styling spillover. The branch also includes related refactors (TimePicker and scheduling changes, EmailPreview signature updates, new API validation and dependency), but those are secondary to the visual spillover fix. Overall, the title accurately highlights the main change a reviewer or teammate would care about.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/digest-styling-spillover

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (1)

78-429: Add 'use client' directive

apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx uses client-side hooks (useState, useEffect, useForm, useAction); add "use client" as the first line of the file.

🧹 Nitpick comments (4)
apps/web/app/api/digest-preview/validation.ts (1)

4-17: Make query param nullable and enforce array-of-strings output

If categories is absent, z.string() will fail before transform. Also tighten the output type and cap length.

Apply:

-export const digestPreviewBody = z.object({
-  categories: z.string().transform((val) => {
+export const digestPreviewBody = z.object({
+  categories: z
+    .string()
+    .nullish()
+    .transform((val) => {
       if (!val) return [];
       try {
         // Try to parse as JSON array first
         const parsed = JSON.parse(val);
-        return Array.isArray(parsed) ? parsed : [];
+        return Array.isArray(parsed)
+          ? parsed.map(String).map((s) => s.trim()).filter(Boolean)
+          : [];
       } catch {
         // Fall back to comma-separated string
-        return val
+        return (val ?? "")
           .split(",")
           .map((s) => s.trim())
           .filter(Boolean);
-    }
-  }),
+    })
+    .pipe(z.array(z.string()).max(50)),
 });
apps/web/app/api/digest-preview/route.ts (2)

56-64: Deduplicate categories before building mock data

Prevents repeated sections and unnecessary work.

 function createMockDigestData(categories: string[]): DigestEmailProps {
-  const digestData: DigestEmailProps = {
+  const digestData: DigestEmailProps = {
     baseUrl: "https://www.getinboxzero.com",
     unsubscribeToken: "preview-token",
     emailAccountId: "preview-account",
     date: new Date(),
   };
@@
-  for (const category of categories) {
+  const uniqueCategories = Array.from(new Set(categories));
+  for (const category of uniqueCategories) {

Also applies to: 139-165


51-54: Log render failures with scoped logger

Helps triage unexpected errors while keeping user-facing messages generic.

-} catch {
-  return new Response("Error rendering preview", { status: 500 });
+} catch (err) {
+  // logger.with({ err }).error("digest preview render failure");
+  return new Response("Error rendering preview", { status: 500 });
 }
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (1)

431-446: Build URL with JSON-encoded categories to avoid parsing issues

Encodes safely and matches the server’s JSON-first parsing.

-const { data: htmlContent } = useSWR<string>(
-  selectedDigestNames.length > 0
-    ? `/api/digest-preview?categories=${selectedDigestNames.join(",")}`
-    : null,
-  async (url: string) => {
-    const response = await fetch(url);
+const { data: htmlContent } = useSWR<string>(
+  selectedDigestNames.length > 0
+    ? `/api/digest-preview?categories=${encodeURIComponent(
+        JSON.stringify(selectedDigestNames),
+      )}`
+    : null,
+  async (url: string) => {
+    const response = await fetch(url, { headers: { Accept: "text/html" } });
     if (!response.ok) throw new Error("Failed to fetch preview");
     return response.text();
   },
   { keepPreviousData: true },
 );
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74e704b and be9d30c.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (3 hunks)
  • apps/web/app/api/digest-preview/route.ts (1 hunks)
  • apps/web/app/api/digest-preview/validation.ts (1 hunks)
  • apps/web/package.json (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (18)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/package.json
  • version.txt
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/package.json
  • version.txt
  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/digest-preview/route.ts
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/digest-preview/route.ts
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧠 Learnings (15)
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Request bodies in API routes should use Zod schemas for validation.

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Always define a Zod schema for response validation

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define input validation schemas using Zod in the corresponding `.validation.ts` file. These schemas are used by `next-safe-action` (`.schema()`) and can also be reused on the client for form validation.

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Request bodies in API routes MUST be validated using Zod schemas before use.

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Applied to files:

  • apps/web/app/api/digest-preview/validation.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Export response types from GET API routes for type-safe client usage.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Export response types from GET routes

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/components/**/*Form.tsx : Use React Hook Form with Zod resolver for form handling and validation.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.tsx : Use React Hook Form with Zod for validation

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : For fetching data from API endpoints in custom hooks, prefer using `useSWR`.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/hooks/**/*.ts : Use SWR for efficient data fetching and caching

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-09-20T18:24:34.271Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.271Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧬 Code graph analysis (2)
apps/web/app/api/digest-preview/route.ts (2)
apps/web/app/api/digest-preview/validation.ts (1)
  • digestPreviewBody (3-18)
packages/resend/emails/digest.tsx (2)
  • DigestEmail (87-303)
  • DigestEmailProps (72-86)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (1)
apps/web/components/Input.tsx (1)
  • Label (116-132)
🪛 ast-grep (0.39.5)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx

[warning] 458-458: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Software Component Analysis Js
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Jit Security
  • GitHub Check: Vercel Agent Review
🔇 Additional comments (3)
version.txt (1)

1-1: Version bump looks good

No functional impact. Make sure release notes mention the digest preview change.

apps/web/app/api/digest-preview/route.ts (1)

23-44: Inline <style> in returned HTML will leak into the host page — sandbox or strip styles

Returning a full HTML document here that includes a <style> with a body selector will leak CSS into the host when that HTML is injected client-side (e.g., via dangerouslySetInnerHTML). Sandbox the preview in an iframe or remove/transform/namespace the style tags (alternatives: Shadow DOM or scoped selectors).

Location: apps/web/app/api/digest-preview/route.ts (lines 23–44). I proposed an iframe fix in DigestSettingsForm — verify after applying that spillover is eliminated.

apps/web/package.json (1)

67-67: Confirmed: @react-email/render is only imported in server-side code

Found imports in:

  • apps/web/app/api/digest-preview/route.ts (Next API route)
  • packages/resend/src/send.tsx

No other occurrences detected; client bundles should not include this dependency.

Comment on lines 9 to 16
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const categoriesParam = searchParams.get("categories");

const { success, data } = digestPreviewBody.safeParse({
categories: categoriesParam,
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add auth middleware and export response type

Per guidelines, wrap GET with withAuth/withError and export the response type for client usage.

Example (adjust import paths to your project):

+export type GetDigestPreviewResponse = string;
+
-import type { NextRequest } from "next/server";
+import type { NextRequest } from "next/server";
+// import { withAuth } from "@/app/api/_lib/withAuth"; // adjust path
+// import { createScopedLogger } from "@/utils/logger"; // adjust path
+// const logger = createScopedLogger("api:digest-preview");
 
-export async function GET(request: NextRequest) {
-  try {
+export async function GET(request: NextRequest) {
+  try {
     const { searchParams } = new URL(request.url);
     const categoriesParam = searchParams.get("categories");
 
     const { success, data } = digestPreviewBody.safeParse({
       categories: categoriesParam,
     });

If this route is intentionally public, use withError and keep auth rationale documented.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/app/api/digest-preview/route.ts around lines 9 to 16, the GET
handler needs to be wrapped with the project's auth/error middleware and the
response type exported for client usage; update imports (withAuth, withError,
and the response type utility) as needed, wrap the exported GET handler with
withAuth(withError(...)) (or withError(...) only if this route is intentionally
public and document that rationale in a comment), and export a named
type/interface describing the JSON response shape so clients can import it.

Comment on lines 436 to 446
const { data: htmlContent } = useSWR<string>(
selectedDigestNames.length > 0
? `/api/digest-preview?categories=${selectedDigestNames.join(",")}`
: null,
async (url: string) => {
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to fetch preview");
return response.text();
},
{ keepPreviousData: true },
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The EmailPreview component is missing error handling for the digest preview API call. When the API fails, users see "Select digest items to see a preview" instead of an error message.

View Details
📝 Patch Details
diff --git a/apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx b/apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
index a435c4755..93332bfaa 100644
--- a/apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
+++ b/apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
@@ -433,7 +433,7 @@ function EmailPreview({
 }: {
   selectedDigestNames: string[];
 }) {
-  const { data: htmlContent } = useSWR<string>(
+  const { data: htmlContent, isLoading, error } = useSWR<string>(
     selectedDigestNames.length > 0
       ? `/api/digest-preview?categories=${selectedDigestNames.join(",")}`
       : null,
@@ -449,20 +449,22 @@ function EmailPreview({
     <div>
       <Label>Preview</Label>
       <div className="mt-3 border rounded-lg overflow-hidden bg-slate-50">
-        {selectedDigestNames.length > 0 && htmlContent ? (
-          <div
-            className="w-full min-h-[700px] max-h-[700px] bg-white overflow-auto p-6"
-            style={{
-              contain: "layout",
-            }}
-            // biome-ignore lint/security/noDangerouslySetInnerHtml: we control the html content
-            dangerouslySetInnerHTML={{ __html: htmlContent }}
-          />
-        ) : (
-          <div className="text-center text-slate-500 py-8">
-            <p>Select digest items to see a preview</p>
-          </div>
-        )}
+        <LoadingContent loading={isLoading} error={error}>
+          {selectedDigestNames.length > 0 && htmlContent ? (
+            <div
+              className="w-full min-h-[700px] max-h-[700px] bg-white overflow-auto p-6"
+              style={{
+                contain: "layout",
+              }}
+              // biome-ignore lint/security/noDangerouslySetInnerHtml: we control the html content
+              dangerouslySetInnerHTML={{ __html: htmlContent }}
+            />
+          ) : (
+            <div className="text-center text-slate-500 py-8">
+              <p>Select digest items to see a preview</p>
+            </div>
+          )}
+        </LoadingContent>
       </div>
     </div>
   );

Analysis

EmailPreview component missing error handling causes API failures to appear as empty state

What fails: EmailPreview component in DigestSettingsForm.tsx only destructures data from useSWR, ignoring error when /api/digest-preview API fails

How to reproduce:

# Trigger 400 error:
curl "http://localhost:3000/api/digest-preview?categories="
# Returns: "Invalid categories parameter" with 400 status

# EmailPreview component shows "Select digest items to see a preview" instead of error message

Result: When API returns 400/500 errors, users see the fallback "Select digest items to see a preview" message instead of the actual error, making it impossible to distinguish between "no items selected" vs "server error"

Expected: Should follow established codebase pattern where useSWR destructures both data and error, then uses LoadingContent component to display API errors - consistent with History.tsx, Pending.tsx, and main DigestSettingsForm usage

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 issues found across 6 files

Prompt for AI agents (all 7 issues)

Understand the root cause of the following 7 issues and fix them.


<file name="apps/web/package.json">

<violation number="1" location="apps/web/package.json:67">
Added dependency appears unused; consider removing it or adding usage to justify it.</violation>
</file>

<file name="apps/web/app/api/digest-preview/validation.ts">

<violation number="1" location="apps/web/app/api/digest-preview/validation.ts:9">
Returning parsed directly allows non-string elements and infers categories as any[], risking runtime errors downstream. Ensure output is string[] by filtering with a type guard.</violation>
</file>

<file name="apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx">

<violation number="1" location="apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx:279">
Cold Emails is mapped to a display name, but the API expects the key &#39;cold-emails&#39;; the preview will not render cold email content correctly.</violation>

<violation number="2" location="apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx:438">
Building the categories query with join(&#39;,&#39;) can break when names include commas or special characters; URL-encode a JSON array instead.</violation>

<violation number="3" location="apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx:459">
Injecting a full HTML document with a global &lt;style&gt; (targeting body) can leak styles across the app; consider rendering the preview in a sandboxed iframe (srcDoc) or stripping global styles before injection.</violation>
</file>

<file name="apps/web/app/api/digest-preview/route.ts">

<violation number="1" location="apps/web/app/api/digest-preview/route.ts:21">
categories may include non-strings from JSON input, leading to runtime errors (toLowerCase on non-string); ensure elements are strings before use.</violation>

<violation number="2" location="apps/web/app/api/digest-preview/route.ts:46">
Embedding a full HTML document from render() inside another document creates invalid nested &lt;html&gt;/&lt;head&gt; structure; return the rendered HTML directly.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

"@radix-ui/react-toggle": "1.1.10",
"@radix-ui/react-tooltip": "1.2.8",
"@radix-ui/react-use-controllable-state": "1.2.2",
"@react-email/render": "1.2.1",
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added dependency appears unused; consider removing it or adding usage to justify it.

Prompt for AI agents
Address the following comment on apps/web/package.json at line 67:

<comment>Added dependency appears unused; consider removing it or adding usage to justify it.</comment>

<file context>
@@ -64,6 +64,7 @@
     &quot;@radix-ui/react-toggle&quot;: &quot;1.1.10&quot;,
     &quot;@radix-ui/react-tooltip&quot;: &quot;1.2.8&quot;,
     &quot;@radix-ui/react-use-controllable-state&quot;: &quot;1.2.2&quot;,
+    &quot;@react-email/render&quot;: &quot;1.2.1&quot;,
     &quot;@sentry/nextjs&quot;: &quot;10.8.0&quot;,
     &quot;@serwist/next&quot;: &quot;9.2.0&quot;,
</file context>
Fix with Cubic

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Building the categories query with join(',') can break when names include commas or special characters; URL-encode a JSON array instead.

Prompt for AI agents
Address the following comment on apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx at line 438:

<comment>Building the categories query with join(&#39;,&#39;) can break when names include commas or special characters; URL-encode a JSON array instead.</comment>

<file context>
@@ -421,31 +423,41 @@ export function DigestSettingsForm() {
 }) {
+  const { data: htmlContent } = useSWR&lt;string&gt;(
+    selectedDigestNames.length &gt; 0
+      ? `/api/digest-preview?categories=${selectedDigestNames.join(&quot;,&quot;)}`
+      : null,
+    async (url: string) =&gt; {
</file context>

✅ Addressed in e21f585

];

const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) => {
if (itemId === "cold-emails") return "Cold Emails";
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cold Emails is mapped to a display name, but the API expects the key 'cold-emails'; the preview will not render cold email content correctly.

Prompt for AI agents
Address the following comment on apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx at line 279:

<comment>Cold Emails is mapped to a display name, but the API expects the key &#39;cold-emails&#39;; the preview will not render cold email content correctly.</comment>

<file context>
@@ -278,6 +275,11 @@ export function DigestSettingsForm() {
   ];
 
+  const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) =&gt; {
+    if (itemId === &quot;cold-emails&quot;) return &quot;Cold Emails&quot;;
+    return rules?.find((rule) =&gt; rule.id === itemId)?.name || itemId;
+  });
</file context>
Suggested change
if (itemId === "cold-emails") return "Cold Emails";
if (itemId === "cold-emails") return "cold-emails";
Fix with Cubic

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Embedding a full HTML document from render() inside another document creates invalid nested / structure; return the rendered HTML directly.

Prompt for AI agents
Address the following comment on apps/web/app/api/digest-preview/route.ts at line 46:

<comment>Embedding a full HTML document from render() inside another document creates invalid nested &lt;html&gt;/&lt;head&gt; structure; return the rendered HTML directly.</comment>

<file context>
@@ -0,0 +1,209 @@
+&lt;/body&gt;
+&lt;/html&gt;`;
+
+    return new Response(fullHtml, {
+      headers: {
+        &quot;Content-Type&quot;: &quot;text/html&quot;,
</file context>

✅ Addressed in 08c1bab

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
apps/web/app/api/digest-preview/route.ts (4)

1-6: Export a typed response for client imports

Expose a named response type for SWR callers.

Apply:

 import type { NextRequest } from "next/server";
 import { render } from "@react-email/render";
 import DigestEmail, {
   type DigestEmailProps,
 } from "@inboxzero/resend/emails/digest";
 import { digestPreviewBody } from "@/app/api/digest-preview/validation";
 
+export type GetDigestPreviewResponse = string;

8-9: Update the usage comment to match the JSON array input

The frontend now sends JSON, not CSV.

Apply:

-// http://localhost:3000/api/digest-preview?categories=newsletter,receipt,marketing
+// Example:
+// /api/digest-preview?categories=%5B%22newsletter%22%2C%22receipt%22%2C%22marketing%22%5D

51-54: Prefer centralized error handling middleware

Per guidelines, wrap GET with withError (or withAuth if needed) and drop the try/catch; keep messages generic.

Would you like a patch using your project’s withError import path?


139-165: Minor: preserve human-friendly rule names

When mapping unknown rule names to a category type, capture the display name so the email can render the friendly label via DigestEmail’s ruleNames prop.

Apply:

-  const digestData: DigestEmailProps = {
+  const digestData: DigestEmailProps = {
     baseUrl: "https://www.getinboxzero.com",
     unsubscribeToken: "preview-token",
     emailAccountId: "preview-account",
     date: new Date(),
+    ruleNames: {},
   };
@@
-    } else {
+    } else {
       // Fallback for rule names - map to a category type for proper coloring
       const categoryType = getCategoryTypeFromRuleName(category);
+      (digestData.ruleNames as Record<string, string>)[categoryType] ??= category;
       digestData[categoryType] = mockDataTemplates[
         categoryType as keyof typeof mockDataTemplates
       ] || [
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be9d30c and e21f585.

📒 Files selected for processing (3)
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (3 hunks)
  • apps/web/app/api/digest-preview/route.ts (1 hunks)
  • apps/web/app/api/digest-preview/validation.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/api/digest-preview/validation.ts
🧰 Additional context used
📓 Path-based instructions (18)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/digest-preview/route.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/digest-preview/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/digest-preview/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/digest-preview/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧠 Learnings (16)
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Export response types from GET API routes for type-safe client usage.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Wrap all GET API route handlers with `withAuth` or `withEmailAccount` middleware for authentication and authorization.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Always wrap the handler with `withAuth` or `withEmailAccount` for consistent error handling and authentication in GET API routes.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Export response types from GET routes

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withError` middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Applied to files:

  • apps/web/app/api/digest-preview/route.ts
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/components/**/*Form.tsx : Use React Hook Form with Zod resolver for form handling and validation.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.tsx : Use React Hook Form with Zod for validation

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : For fetching data from API endpoints in custom hooks, prefer using `useSWR`.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/hooks/**/*.ts : Use SWR for efficient data fetching and caching

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-09-20T18:24:34.271Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.271Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧬 Code graph analysis (2)
apps/web/app/api/digest-preview/route.ts (2)
apps/web/app/api/digest-preview/validation.ts (1)
  • digestPreviewBody (3-5)
packages/resend/emails/digest.tsx (2)
  • DigestEmail (87-303)
  • DigestEmailProps (72-86)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (1)
apps/web/components/Input.tsx (1)
  • Label (116-132)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Software Component Analysis Js
  • GitHub Check: Vercel Agent Review
  • GitHub Check: Jit Security
🔇 Additional comments (7)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (5)

3-3: Good: safe-actions hook imported

Aligns with action usage elsewhere.


426-427: LGTM: iframe-based preview usage

Switching to an isolated preview component fixes the spillover.


436-446: Handle loading/error state and keep UI consistent

EmailPreview should follow our LoadingContent pattern; otherwise API errors look like “empty state.” Also consider disabling focus revalidation to avoid flicker.

Apply:

-  const { data: htmlContent } = useSWR<string>(
+  const { data: htmlContent, isLoading, error } = useSWR<string>(
     selectedDigestNames.length > 0
       ? `/api/digest-preview?categories=${encodeURIComponent(JSON.stringify(selectedDigestNames))}`
       : null,
     async (url: string) => {
       const response = await fetch(url);
       if (!response.ok) throw new Error("Failed to fetch preview");
       return response.text();
     },
-    { keepPreviousData: true },
+    { revalidateOnFocus: false },
   );

If you're relying on SWR’s keepPreviousData option, confirm it’s supported in your installed SWR version:

Does the latest SWR (v2.x) support a `keepPreviousData` configuration option similar to React Query?

451-458: Good: sandboxed iframe eliminates CSS spillover

Title set and srcDoc used; this is the right containment approach.


278-281: Cold Emails key mismatch breaks preview mapping

The API expects "cold-emails" (key), not "Cold Emails" (label). Passing the label prevents the server from recognizing/including cold email items.

Apply:

-  const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) => {
-    if (itemId === "cold-emails") return "Cold Emails";
-    return rules?.find((rule) => rule.id === itemId)?.name || itemId;
-  });
+  const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) => {
+    if (itemId === "cold-emails") return "cold-emails";
+    return rules?.find((rule) => rule.id === itemId)?.name || itemId;
+  });
apps/web/app/api/digest-preview/route.ts (2)

56-63: LGTM: base props and preview token are scoped to preview

No user data exposure here.


25-50: Avoid nesting a full HTML document inside another HTML document

render() already returns a complete HTML document. Wrapping it produces invalid nested / and can render as literal text. Return the rendered HTML directly and set proper headers.

Apply:

-    const fullHtml = `
-<!DOCTYPE html>
-<html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>Digest Preview</title>
-    <style>
-        body {
-            margin: 0;
-            padding: 20px;
-            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
-            background-color: #f8fafc;
-        }
-    </style>
-</head>
-<body>
-    ${html}
-</body>
-</html>`;
-
-    return new Response(fullHtml, {
+    return new Response(html, {
       headers: {
-        "Content-Type": "text/html",
+        "Content-Type": "text/html; charset=UTF-8",
+        "Cache-Control": "no-store",
       },
     });

Comment on lines +10 to +16
try {
const { searchParams } = new URL(request.url);
const categoriesParam = searchParams.get("categories");

const { success, data } = digestPreviewBody.safeParse({
categories: categoriesParam?.split(","),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Parse JSON categories (with CSV fallback) to match client

Client encodes a JSON array; splitting on commas breaks names with commas and special chars.

Apply:

 export async function GET(request: NextRequest) {
   try {
     const { searchParams } = new URL(request.url);
     const categoriesParam = searchParams.get("categories");
 
-    const { success, data } = digestPreviewBody.safeParse({
-      categories: categoriesParam?.split(","),
-    });
+    // Accept JSON array (preferred) or CSV as a fallback.
+    let parsedCategories: unknown = [];
+    if (categoriesParam) {
+      if (categoriesParam.trim().startsWith("[")) {
+        try {
+          parsedCategories = JSON.parse(categoriesParam);
+        } catch {
+          return new Response("Invalid categories parameter", { status: 400 });
+        }
+      } else {
+        parsedCategories = categoriesParam
+          .split(",")
+          .map((s) => s.trim())
+          .filter(Boolean);
+      }
+    }
+
+    const { success, data } = digestPreviewBody.safeParse({
+      categories: parsedCategories,
+    });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const { searchParams } = new URL(request.url);
const categoriesParam = searchParams.get("categories");
const { success, data } = digestPreviewBody.safeParse({
categories: categoriesParam?.split(","),
});
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const categoriesParam = searchParams.get("categories");
// Accept JSON array (preferred) or CSV as a fallback.
let parsedCategories: unknown = [];
if (categoriesParam) {
if (categoriesParam.trim().startsWith("[")) {
try {
parsedCategories = JSON.parse(categoriesParam);
} catch {
return new Response("Invalid categories parameter", { status: 400 });
}
} else {
parsedCategories = categoriesParam
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
}
const { success, data } = digestPreviewBody.safeParse({
categories: parsedCategories,
});
🤖 Prompt for AI Agents
In apps/web/app/api/digest-preview/route.ts around lines 10 to 16, the code
currently splits the categories query param on commas which breaks JSON-encoded
arrays and values that contain commas; instead, attempt to parse categoriesParam
as JSON first (JSON.parse) and if that succeeds use the resulting array,
otherwise fall back to treating it as CSV by splitting on commas, and if
categoriesParam is null/empty pass undefined or an empty array as appropriate;
ensure the final value passed into digestPreviewBody.safeParse is an array (or
undefined) and handle JSON.parse errors without throwing.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (1)

47-50: Don’t downgrade existing schedules; support biweekly/monthly consistently

Users with 14/30‑day schedules will see “Select…” and saving will silently change them to daily. Add options and map them.

Apply:

 const frequencies = [
   { value: "daily", label: "Day" },
   { value: "weekly", label: "Week" },
+  { value: "biweekly", label: "2 weeks" },
+  { value: "monthly", label: "Month" },
 ];
@@
   let intervalDays: number;
   switch (schedule) {
     case "daily":
       intervalDays = 1;
       break;
     case "weekly":
       intervalDays = 7;
       break;
+    case "biweekly":
+      intervalDays = 14;
+      break;
+    case "monthly":
+      intervalDays = 30;
+      break;
     default:
       intervalDays = 1;
   }

Also applies to: 201-211

🧹 Nitpick comments (4)
apps/web/components/ui/input.tsx (1)

5-5: Avoid duplicate Input components / confusing note

This comment conflicts with our convention “shadcn components are in components/ui”. Either remove the note or make this the canonical Input and re-export from components/Input.tsx to avoid drift.

Apply:

-// Note we usually use /components/Input.tsx instead of this one
apps/web/components/TimePicker.tsx (1)

7-15: Forward extra input props for flexibility

TimePicker currently blocks native input props (e.g., name, step, min, max). Extend from input props and spread the rest to Input.

Apply:

-interface TimePickerProps {
-  id?: string;
-  label?: string;
-  value: string;
-  onChange: (value: string) => void;
-  className?: string;
-  disabled?: boolean;
-  required?: boolean;
-}
+interface TimePickerProps
+  extends Omit<React.ComponentProps<"input">, "type" | "value" | "onChange" | "id"> {
+  id?: string;
+  label?: string;
+  value: string;
+  onChange: (value: string) => void;
+  className?: string;
+}
@@
-export function TimePicker({
+export function TimePicker({
   id = "time-picker",
   label = "Time",
   value,
   onChange,
-  className,
-  disabled = false,
-  required = false,
+  className,
+  disabled = false,
+  required = false,
+  ...rest
 }: TimePickerProps) {
@@
       <Input
         type="time"
         id={id}
         value={value}
         onChange={(e) => onChange(e.target.value)}
         disabled={disabled}
         required={required}
+        {...rest}
         className={cn(
           "bg-background w-32 appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none",
           className,
         )}
       />

Also applies to: 26-41

apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (2)

311-334: Show day-of-week only where it applies

Day selector appears for monthly; confirm backend semantics. If monthly ignores dayOfWeek, gate this to weekly/biweekly only.

Apply:

-{watchedValues.schedule !== "daily" && (
+{["weekly", "biweekly"].includes(watchedValues.schedule) && (

If monthly does require it, ignore this change.


257-261: Stabilize SWR key (optional)

Order of Set iteration can vary across sessions; sort names before stringify to improve cache reuse.

Apply:

-  const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) => {
+  const selectedDigestNames = Array.from(selectedDigestItems).map((itemId) => {
     if (itemId === "cold-emails") return "Cold Emails";
     return rules?.find((rule) => rule.id === itemId)?.name || itemId;
-  });
+  }).sort((a, b) => a.localeCompare(b));

Also applies to: 364-365

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08c1bab and a0ec18c.

📒 Files selected for processing (3)
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (9 hunks)
  • apps/web/components/TimePicker.tsx (1 hunks)
  • apps/web/components/ui/input.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/components/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Use React Hook Form with Zod validation for form handling

Use the LoadingContent component to handle loading and error states consistently in data-fetching components.

Use PascalCase for components (e.g. components/Button.tsx)

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/components/ui/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Shadcn components are in components/ui

Files:

  • apps/web/components/ui/input.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/components/ui/input.tsx
  • apps/web/components/TimePicker.tsx
  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧠 Learnings (7)
📚 Learning: 2025-07-19T17:50:22.078Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-07-19T17:50:22.078Z
Learning: Applies to components/**/*.tsx : Use the `Input` component for text inputs, passing `registerProps` and `error` props for form handling

Applied to files:

  • apps/web/components/ui/input.tsx
📚 Learning: 2025-07-19T17:50:22.078Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-07-19T17:50:22.078Z
Learning: Applies to components/**/*.tsx : Use the `Input` component with `autosizeTextarea` and appropriate props for text areas

Applied to files:

  • apps/web/components/ui/input.tsx
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/components/**/*Form.tsx : Use React Hook Form with Zod resolver for form handling and validation.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.tsx : Use React Hook Form with Zod for validation

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
📚 Learning: 2025-09-20T18:24:34.271Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.271Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx
🧬 Code graph analysis (3)
apps/web/components/ui/input.tsx (1)
apps/web/utils/index.ts (1)
  • cn (4-6)
apps/web/components/TimePicker.tsx (2)
apps/web/components/Input.tsx (1)
  • Label (116-132)
apps/web/utils/index.ts (1)
  • cn (4-6)
apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (3)
apps/web/utils/schedule.ts (1)
  • createCanonicalTimeOfDay (12-14)
apps/web/components/TimePicker.tsx (1)
  • TimePicker (17-43)
apps/web/components/Input.tsx (1)
  • Label (116-132)
🔇 Additional comments (5)
apps/web/components/ui/input.tsx (1)

6-20: LGTM: solid shadcn-style Input

ForwardRef typing, cn usage, and base classes look good.

apps/web/components/TimePicker.tsx (1)

17-43: LGTM

Client component, label association, and Input usage are correct.

apps/web/app/(app)/[emailAccountId]/settings/DigestSettingsForm.tsx (3)

257-261: Confirm API expects display names vs keys

You send JSON of display names (e.g., "Cold Emails"). If the API expects canonical keys (e.g., "cold-emails" or rule ids), preview content will be wrong.

Run:

#!/bin/bash
# Inspect digest-preview schema and usage
rg -nP "digest-preview/validation\.ts|digest-preview/route\.ts"
rg -nP "(categories|Category|categoriesJson)" apps/web/app/api/digest-preview
rg -nP "z\.\s*array\(\s*z\.string\(\)\s*\)" apps/web/app/api/digest-preview -C3
rg -nP "cold-?emails|Cold Emails" apps/web/app/api/digest-preview -n -C2

If keys are expected, build a parallel array of keys for the API and keep display names for UI.

Also applies to: 362-372


362-372: keepPreviousData supported — no action required.

apps/web/package.json shows swr@2.3.6 (v2), so the keepPreviousData option is valid.


362-372: Add LoadingContent and error handling in EmailPreview

Follow repository pattern; otherwise API failures look like empty state.

Apply:

-  const { data: htmlContent } = useSWR<string>(
+  const { data: htmlContent, isLoading, error } = useSWR<string>(
     selectedDigestNames.length > 0
       ? `/api/digest-preview?categories=${encodeURIComponent(JSON.stringify(selectedDigestNames))}`
       : null,
     async (url: string) => {
       const response = await fetch(url);
       if (!response.ok) throw new Error("Failed to fetch preview");
       return response.text();
     },
-    { keepPreviousData: true },
+    { keepPreviousData: true },
   );
@@
-      <div className="mt-3 border rounded-lg overflow-hidden bg-slate-50">
-        {selectedDigestNames.length > 0 && htmlContent ? (
-          <iframe
-            title="Digest preview"
-            sandbox=""
-            className="w-full min-h-[700px] max-h-[700px] bg-white"
-            srcDoc={htmlContent}
-          />
-        ) : (
-          <div className="text-center text-slate-500 py-8">
-            <p>Select digest items to see a preview</p>
-          </div>
-        )}
-      </div>
+      <div className="mt-3 border rounded-lg overflow-hidden bg-slate-50">
+        <LoadingContent loading={isLoading} error={error}>
+          {selectedDigestNames.length > 0 && htmlContent ? (
+            <iframe
+              title="Digest preview"
+              sandbox=""
+              className="w-full min-h-[700px] max-h-[700px] bg-white"
+              srcDoc={htmlContent}
+            />
+          ) : (
+            <div className="text-center text-slate-500 py-8">
+              <p>Select digest items to see a preview</p>
+            </div>
+          )}
+        </LoadingContent>
+      </div>

Also applies to: 377-385

Comment on lines +42 to 43
time: z.string().min(1, "Please select a time"),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate and parse time safely

Current min(1) + split(":") can produce NaN and invalid Date. Enforce HH:MM and guard parsing.

Apply:

-  time: z.string().min(1, "Please select a time"),
+  time: z
+    .string()
+    .regex(/^\d{2}:\d{2}$/, "Please select a valid time (HH:MM)"),
@@
-  const [hourStr, minuteStr] = time.split(":");
-  const hour24 = Number.parseInt(hourStr, 10);
-  const minute = Number.parseInt(minuteStr, 10);
-
-  const timeOfDay = createCanonicalTimeOfDay(hour24, minute);
+  const [hourStr, minuteStr] = time.split(":");
+  const hour24 = Number.parseInt(hourStr, 10);
+  const minute = Number.parseInt(minuteStr, 10);
+  if (
+    Number.isNaN(hour24) ||
+    Number.isNaN(minute) ||
+    hour24 < 0 ||
+    hour24 > 23 ||
+    minute < 0 ||
+    minute > 59
+  ) {
+    throw new Error("Invalid time");
+  }
+  const timeOfDay = createCanonicalTimeOfDay(hour24, minute);

Also applies to: 213-218

@elie222 elie222 merged commit 1f530ca into main Sep 21, 2025
17 checks passed
@elie222 elie222 deleted the fix/digest-styling-spillover branch September 21, 2025 19:49
@coderabbitai coderabbitai bot mentioned this pull request Sep 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments