Skip to content

Conversation

N2D4
Copy link
Contributor

@N2D4 N2D4 commented Jul 29, 2025

Important

This PR enhances project config with advanced TypeScript utilities, improved validation, and support for currency conversions, while fixing bugs and refactoring for better schema enforcement.

  • New Features:
    • Added advanced TypeScript utilities for config schemas, normalization, and type safety, including helpers for currencies, intervals, and string joining.
    • Introduced granular control for config validation, migration, and sanitization across project, branch, environment, and organization levels.
    • Added support for currency conversions and date interval arithmetic.
    • Added a command-line flag to skip Neon projects in data integrity checks.
  • Bug Fixes:
    • Improved config normalization and validation to handle nested and union types more robustly.
    • Fixed trusted domains config structure to use unique IDs.
  • Refactor:
    • Refactored config override logic for stricter schema enforcement and migration support.
    • Updated permission management to use new config override helpers.
    • Simplified environment theme handling by removing automatic active theme updates.
    • Reordered and cleaned import statements for better code clarity.
  • Documentation:
    • Expanded config system documentation with clearer explanations and new concepts.
    • Updated template overview links for improved navigation.
  • Chores:
    • Enhanced schema introspection and error handling for nested config fields.
    • Updated internal scripts and settings for improved developer experience.
    • Removed extraneous logging for cleaner output.

This description was created by Ellipsis for 68ea382. You can customize this summary. It will automatically update as commits are pushed.


Summary by CodeRabbit

New Features

  • Added advanced TypeScript utilities for config schemas, normalization, and type safety, including new helpers for currencies, intervals, and string joining.
  • Introduced granular control for config validation, migration, and sanitization across project, branch, environment, and organization levels.
  • Added support for currency conversions and date interval arithmetic.
  • Added a command-line flag to skip Neon projects in data integrity checks.

Bug Fixes

  • Improved config normalization and validation to handle nested and union types more robustly.
  • Fixed trusted domains config structure to use unique IDs.

Refactor

  • Refactored config override logic for stricter schema enforcement and migration support.
  • Updated permission management to use new config override helpers.
  • Simplified environment theme handling by removing automatic active theme updates.
  • Reordered and cleaned import statements for better code clarity.

Documentation

  • Expanded config system documentation with clearer explanations and new concepts.
  • Updated template overview links for improved navigation.

Chores

  • Enhanced schema introspection and error handling for nested config fields.
  • Updated internal scripts and settings for improved developer experience.
  • Removed extraneous logging for cleaner output.

@N2D4 N2D4 requested a review from Copilot July 29, 2025 08:45
Copy link

vercel bot commented Jul 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
stack-backend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 11:14am
stack-dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 11:14am
stack-demo ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 11:14am
stack-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 11:14am

Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

Walkthrough

This set of changes introduces a comprehensive refactor and extension of the configuration schema, validation, and normalization logic across the backend and shared packages. It includes stricter schema enforcement, improved type safety, new migration and sanitization utilities, expanded TypeScript type helpers, and enhanced schema introspection. Several new utility modules and functions are added for currency and date handling, and documentation is updated to clarify the config system. Minor adjustments and cleanups are made in various backend scripts and handlers to align with the new config logic.

Changes

Cohort / File(s) Change Summary
VSCode Spellcheck Settings
.vscode/settings.json
Added custom words to the cSpell dictionary.
Backend Codegen Script
apps/backend/package.json
Appended generate-migration-imports:watch to the codegen:watch script for concurrent execution.
Backend Seed Script
apps/backend/prisma/seed.ts
Removed an extraneous console log statement after creating a GitHub account for the admin user.
Backend Data Integrity Script
apps/backend/scripts/verify-data-integrity.ts
Added --skip-neon flag to skip projects with "Neon" in the description; updated Prisma query to select description.
Backend Email Render Route
apps/backend/src/app/api/latest/emails/render-email/route.tsx
Expanded import statement to include StackAssertionError and captureError.
Backend Email Template Internal Route
apps/backend/src/app/api/latest/internal/email-templates/[templateId]/route.tsx
Reordered imports; changed config override update to set only tsxSource and conditionally themeId, removing displayName.
Backend Email Templates Route
apps/backend/src/app/api/latest/internal/email-templates/route.tsx
Reordered imports; used typedEntries and filterUndefined for template mapping in GET handler.
Backend Email Themes Route
apps/backend/src/app/api/latest/internal/email-themes/route.tsx
Reordered imports; removed logic for setting a new active theme if missing; used typedEntries and filterUndefined.
Backend Config Library
apps/backend/src/lib/config.tsx
Major refactor: replaced previous defaults/validation with schema-aware sanitization, migration, and validation; updated all config-related functions and validation logic; added/changed function signatures; improved error reporting and type safety.
Backend Permissions Library
apps/backend/src/lib/permissions.tsx
Refactored to use new overrideEnvironmentConfigOverride helper for config updates in permission definition CRUD functions.
Backend Projects Library
apps/backend/src/lib/projects.tsx
Changed trusted domains config from an array to a UUID-keyed object using typedFromEntries.
Backend Smart Request Handler
apps/backend/src/route-handlers/smart-request.tsx
Inverted logic for dev key override in production; now throws unless explicitly allowed.
Config System Documentation
packages/stack-shared/src/config/README.md
Expanded and clarified documentation on config levels, rendered configs, and introduced the concept of config override overrides.
Config Format Utilities
packages/stack-shared/src/config/format.ts
Improved type safety for normalized configs; added options for handling dot notation on null/non-object; added normalization check/assertion utilities; updated normalization logic and tests.
Config Schema and Defaults
packages/stack-shared/src/config/schema.ts
Major refactor: stricter schemas, added migration and sanitization utilities, detailed defaults, improved validation, and expanded type definitions for all config levels.
Email Template Helpers
packages/stack-shared/src/helpers/emails.ts
Added themeId: undefined to each default email template object.
Yup Schema Field Utilities
packages/stack-shared/src/schema-fields.ts
Added nested schema introspection (hasNested, improved getNested), richer schema metadata, new domain-specific schemas, and improved error handling.
Currency Utilities
packages/stack-shared/src/utils/currencies.tsx
New module: defined currency types, supported currencies, MoneyAmount, and conversion utility for Stripe units.
Date Interval Utilities
packages/stack-shared/src/utils/dates.tsx
Added Interval and DayInterval types; new functions for adding/subtracting intervals from dates.
Object Utilities
packages/stack-shared/src/utils/objects.tsx
Enhanced deep partial/required types, added new type utilities, improved typings for typedEntries/typedKeys, and updated deepFilterUndefined for nested objects.
String Utilities
packages/stack-shared/src/utils/strings.tsx
Added Join type for type-safe string joining and typedJoin function.
Type Utilities
packages/stack-shared/src/utils/types.tsx
Added advanced TypeScript type utilities: union detection, expansion, intersection, key extraction, stringification, and compile-time type assertions.
Docs Template Links Update
docs/templates/overview.mdx
Updated hyperlink references in Cards for "Components" and "SDK Reference" to shorter paths.
Backend Email Rendering
apps/backend/src/lib/email-rendering.tsx
Reordered imports; removed a debug console log for matched <Subject /> in development/test environments.
Turbo Global Env Config
turbo.json
Added new global environment variables for Google AI API key and Discord webhook/token/channel.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Route
    participant Config_Lib
    participant Schema_Utils

    Client->>API_Route: PATCH /internal/email-templates/[templateId]
    API_Route->>Config_Lib: overrideEnvironmentConfigOverride({ tsxSource, themeId? })
    Config_Lib->>Schema_Utils: sanitizeEnvironmentConfig
    Schema_Utils-->>Config_Lib: Sanitized config
    Config_Lib-->>API_Route: Save override if valid
    API_Route-->>Client: Response
Loading
sequenceDiagram
    participant Backend
    participant Config_Lib
    participant Schema_Utils

    Backend->>Config_Lib: validateEnvironmentConfigOverride(override)
    Config_Lib->>Schema_Utils: getConfigOverrideErrors
    Schema_Utils-->>Config_Lib: Result<null, string>
    Config_Lib-->>Backend: Validation result
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Poem

A bunny with specs on its nose
Hopped through the configs and prose.
With schemas refactored,
And types neatly mastered,
Now all of the settings compose!

🐇✨

"From deep in the burrow,
I type-safe tomorrow—
Review with a wiggle of toes!"

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 51f8eb6 and 68ea382.

📒 Files selected for processing (1)
  • packages/stack-shared/src/utils/objects.tsx (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/stack-shared/src/utils/objects.tsx
⏰ 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). (9)
  • GitHub Check: build (22.x)
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: setup-tests
  • GitHub Check: restart-dev-and-test
  • GitHub Check: docker
  • GitHub Check: build (22.x)
  • GitHub Check: all-good
  • GitHub Check: docker
  • GitHub Check: Security Check
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improved-config

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR implements a comprehensive refactor of Stack Auth's configuration management system. The changes introduce several key improvements:

Configuration System Overhaul: The core configuration system has been completely refactored with enhanced validation, migration support, and sanitization. The new system provides better error categorization (FORMAT ERROR, ERROR, WARNING) and includes comprehensive test coverage. Configuration rendering now includes normalization and sanitization steps, with migration support for backwards compatibility.

Type Safety Improvements: Significant enhancements to TypeScript utility types have been added, including better handling of union/intersection types, object manipulation utilities, and more precise type assertions. The configuration schemas now use more sophisticated typing with OptionalKeys and RequiredKeys to distinguish between required and optional fields.

Domain Storage Refactor: The trusted domains configuration has been changed from an array structure to a Map-like object structure where each domain gets a unique UUID as a key. This improves indexing, lookup performance, and follows the codebase pattern for dynamic key configurations.

Enhanced Schema Infrastructure: New schema introspection capabilities have been added through hasNested and enhanced getNested methods, along with a metadata system (stackSchemaInfo) that tracks schema types for better validation and error reporting.

Payment System Foundation: New currency handling utilities and money amount schemas have been introduced, suggesting preparation for billing/subscription features with Stripe integration.

Bug Fixes: Several critical issues were addressed, including a security vulnerability in the development key override logic and proper indentation fixes in the database seed script for GitHub OAuth account creation.

Developer Experience: Various improvements including file watching for migration imports, better error messages with deindent formatting, and more consistent import organization across the codebase.

These changes represent a significant architectural improvement that maintains the same public API while substantially enhancing the internal implementation for better reliability, type safety, and maintainability.

Confidence score: 3/5

• This PR introduces substantial architectural changes that require careful testing, particularly around the configuration validation and migration systems.
• The score reflects concerns about the complexity of the new configuration system, potential runtime issues with the date interval mutations, and incomplete currency handling implementation.
• Files needing attention: packages/stack-shared/src/utils/dates.tsx (mutation issues), packages/stack-shared/src/utils/currencies.tsx (incomplete implementation), and apps/backend/src/lib/config.tsx (complex validation logic).

21 files reviewed, 9 comments

Edit Code Review Bot Settings | Greptile

Copilot

This comment was marked as outdated.

N2D4 and others added 3 commits July 29, 2025 02:48
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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

♻️ Duplicate comments (1)
packages/stack-shared/src/config/schema.ts (1)

26-31: Avoid as any cast in canNoLongerBeOverridden function.

The function uses as any cast which violates coding guidelines. Consider improving type inference to avoid this cast.

🧹 Nitpick comments (1)
packages/stack-shared/src/config/schema.ts (1)

1-1: Consider removing or addressing the TODO comment.

The TODO comment suggests code quality concerns. If the code truly needs refactoring, create a proper issue to track this work rather than leaving a TODO comment.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 34f739e and f356df1.

📒 Files selected for processing (6)
  • apps/backend/package.json (1 hunks)
  • apps/backend/src/lib/config.tsx (15 hunks)
  • apps/backend/src/lib/email-rendering.tsx (1 hunks)
  • packages/stack-shared/src/config/format.ts (7 hunks)
  • packages/stack-shared/src/config/schema.ts (4 hunks)
  • packages/stack-shared/src/utils/strings.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/backend/src/lib/email-rendering.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/stack-shared/src/utils/strings.tsx
  • apps/backend/src/lib/config.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: TypeScript with strict types, prefer type over interface
Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Files:

  • packages/stack-shared/src/config/format.ts
  • packages/stack-shared/src/config/schema.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: 2-space indentation, spaces in braces, semicolons required
Return promises with return await, no floating promises
Proper error handling for async code with try/catch
Use helper functions: yupXyz() for validation, getPublicEnvVar() for env
Switch cases must use blocks

Files:

  • packages/stack-shared/src/config/format.ts
  • packages/stack-shared/src/config/schema.ts
🧠 Learnings (3)
packages/stack-shared/src/config/format.ts (3)

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Switch cases must use blocks

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: yupXyz() for validation, getPublicEnvVar() for env

packages/stack-shared/src/config/schema.ts (3)

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: yupXyz() for validation, getPublicEnvVar() for env

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : TypeScript with strict types, prefer type over interface

apps/backend/package.json (1)

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: yupXyz() for validation, getPublicEnvVar() for env

🧬 Code Graph Analysis (1)
packages/stack-shared/src/config/format.ts (3)
packages/stack-shared/src/utils/types.tsx (2)
  • OptionalKeys (44-46)
  • RequiredKeys (47-49)
packages/stack-shared/src/utils/errors.tsx (1)
  • StackAssertionError (67-83)
packages/stack-shared/src/utils/objects.tsx (4)
  • set (533-535)
  • get (537-541)
  • hasAndNotUndefined (560-562)
  • deleteKey (564-570)
🪛 Biome (2.1.2)
apps/backend/package.json

[error] 21-21: Missing closing quote

The closing quote must be on the same line.

(parse)

🪛 GitHub Actions: Ensure Prisma migrations are in sync with the schema
apps/backend/package.json

[error] 21-21: pnpm install failed: Bad control character in string literal in JSON at position 1545 (line 21 column 229) in package.json.

🪛 GitHub Actions: Runs E2E API Tests
apps/backend/package.json

[error] 21-21: pnpm install failed: Bad control character in string literal in JSON at position 1545 (line 21 column 229). JSON parsing error in package.json.

🪛 GitHub Actions: Dev Environment Test
apps/backend/package.json

[error] 21-21: pnpm install failed due to JSON parse error: Bad control character in string literal at position 1545 in package.json.

🪛 GitHub Actions: Runs E2E API Tests with external source of truth
apps/backend/package.json

[error] 21-21: pnpm install failed due to JSON parse error: Bad control character in string literal at position 1545.

🪛 GitHub Actions: Run setup tests
apps/backend/package.json

[error] 1-1: pnpm install failed due to JSON parse error: Bad control character in string literal in JSON at position 1545.

🪛 GitHub Actions: Lint & build
apps/backend/package.json

[error] 21-21: pnpm install failed: Bad control character in string literal in JSON at position 1545 (line 21 column 229) while parsing package.json.

⏰ 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: docker
  • GitHub Check: all-good
  • GitHub Check: Security Check
🔇 Additional comments (7)
packages/stack-shared/src/config/format.ts (7)

5-5: LGTM!

The import of OptionalKeys and RequiredKeys utility types aligns with their usage in the _NormalizesTo type definition and follows the project's pattern of importing specific utility types.


20-21: Improved type precision with utility types.

The use of OptionalKeys and RequiredKeys provides better type safety by correctly distinguishing between optional and required properties in the normalized config type. The conditional handling for required keys that can be undefined is also correct.


169-183: Well-implemented utility functions for normalization checking.

The isNormalized and assertNormalized functions correctly identify normalized configs by checking for the absence of dot notation keys and null values. The assertion function follows TypeScript best practices with proper type narrowing.


145-160: Well-designed normalization options with clear documentation.

The expanded NormalizeOptions provides granular control over dot notation handling. The separation of onDotIntoNonObject and onDotIntoNull options allows for flexible configuration normalization strategies. The documentation clearly explains each option's behavior.


202-225: Correct implementation of dot notation handling logic.

The normalization logic properly handles the different options for dot notation behavior:

  • The "like-non-object" fallback correctly delegates to onDotIntoNonObject behavior
  • The "empty-object" case properly sets an empty object with a break statement
  • All switch cases use blocks as required by coding guidelines
  • Error messages are descriptive and include relevant context

228-228: Correct propagation of normalization options.

The options parameter is properly threaded through all helper functions (normalizeValue, setNormalizedValue) to ensure consistent normalization behavior throughout the process.

Also applies to: 233-233, 236-236, 240-240, 246-246


266-266: Comprehensive test coverage for new normalization options.

The test updates properly validate:

  • The onDotIntoNonObject: "ignore" behavior in the main test case
  • Error scenarios with updated parameter names
  • The new test case specifically covering dot notation into non-objects with "ignore" option

The expected results correctly match the documented behavior.

Also applies to: 280-280, 284-284, 287-287, 294-298

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

♻️ Duplicate comments (1)
packages/stack-shared/src/config/schema.ts (1)

490-517: Avoid multiple as any casts.

The functions use multiple as any casts which violate coding guidelines. This issue was previously identified and should be addressed by improving type inference.

🧹 Nitpick comments (1)
packages/stack-shared/src/config/schema.ts (1)

1-1: Consider addressing the TODO comment.

The comment suggests code quality concerns. If this file has become complex due to accumulated changes, consider refactoring it into smaller, more focused modules.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f356df1 and 78ea4c0.

📒 Files selected for processing (2)
  • apps/backend/package.json (1 hunks)
  • packages/stack-shared/src/config/schema.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backend/package.json
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: TypeScript with strict types, prefer type over interface
Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Files:

  • packages/stack-shared/src/config/schema.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: 2-space indentation, spaces in braces, semicolons required
Return promises with return await, no floating promises
Proper error handling for async code with try/catch
Use helper functions: yupXyz() for validation, getPublicEnvVar() for env
Switch cases must use blocks

Files:

  • packages/stack-shared/src/config/schema.ts
🧠 Learnings (1)
packages/stack-shared/src/config/schema.ts (3)

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: yupXyz() for validation, getPublicEnvVar() for env

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : TypeScript with strict types, prefer type over interface

⏰ 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). (5)
  • GitHub Check: docker
  • GitHub Check: restart-dev-and-test
  • GitHub Check: docker
  • GitHub Check: all-good
  • GitHub Check: Security Check
🔇 Additional comments (6)
packages/stack-shared/src/config/schema.ts (6)

36-187: LGTM! Well-structured schema definitions.

The schema definitions are comprehensive and well-organized. The removal of optional wrappers and enforcement of required keys for RBAC, API keys, auth, domains, and emails configurations improves schema strictness as intended.


190-304: LGTM! Excellent migration system implementation.

The migration functions are well-designed with:

  • Clear documentation about purpose and constraints
  • Proper handling of different config levels
  • Comprehensive test coverage for helper functions
  • Logical migration steps for historical schema changes

The separation of concerns and the emphasis on reproducibility are particularly good practices.


312-489: LGTM! Comprehensive default configuration system.

The default configuration objects are well-structured with explicit undefined values, and the applyDefaults function with dot notation support is excellently implemented with comprehensive test coverage.


520-578: LGTM! Well-implemented sanitization functions.

The sanitization functions properly handle:

  • Config level hierarchy with appropriate delegation
  • SourceOfTruth normalization based on type
  • Email theme/template merging with defaults
  • Proper validation using assertNormalized

The implementation follows good patterns and maintains type safety.


580-784: LGTM! Comprehensive validation system.

The validation functions implement sophisticated schema validation with:

  • Proper error handling using Result types
  • Advanced schema introspection and restriction
  • Appropriate handling of deprecated properties
  • Comprehensive validation for all schema types

The complexity is well-justified by the thorough validation requirements.


787-856: LGTM! Excellent TypeScript type system.

The type definitions are well-structured with:

  • Clear naming conventions for different config stages (override, incomplete, rendered)
  • Proper use of advanced TypeScript utility types
  • Comprehensive type assertions for validation
  • Appropriate config level hierarchy

The type system provides excellent type safety and follows TypeScript best practices.

@N2D4 N2D4 enabled auto-merge (squash) July 29, 2025 11:00
@N2D4 N2D4 requested a review from Copilot July 29, 2025 11:04
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: 0

♻️ Duplicate comments (2)
packages/stack-shared/src/config/schema.ts (2)

26-31: Avoid as any cast in canNoLongerBeOverridden function.


500-527: Avoid multiple as any casts.

🧹 Nitpick comments (1)
packages/stack-shared/src/config/schema.ts (1)

1-1: Consider proper refactoring instead of the self-deprecating comment.

While the humor is appreciated, this TODO comment is unprofessional. Consider breaking down this file into smaller, focused modules (e.g., schema-definitions.ts, migration-utils.ts, validation-utils.ts, etc.) to improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78ea4c0 and 51f8eb6.

📒 Files selected for processing (3)
  • packages/stack-shared/src/config/schema.ts (4 hunks)
  • packages/stack-shared/src/utils/objects.tsx (7 hunks)
  • turbo.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • turbo.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/stack-shared/src/utils/objects.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: TypeScript with strict types, prefer type over interface
Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Files:

  • packages/stack-shared/src/config/schema.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: 2-space indentation, spaces in braces, semicolons required
Return promises with return await, no floating promises
Proper error handling for async code with try/catch
Use helper functions: yupXyz() for validation, getPublicEnvVar() for env
Switch cases must use blocks

Files:

  • packages/stack-shared/src/config/schema.ts
🧠 Learnings (1)
packages/stack-shared/src/config/schema.ts (3)

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: yupXyz() for validation, getPublicEnvVar() for env

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{ts,tsx} : TypeScript with strict types, prefer type over interface

⏰ 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). (9)
  • GitHub Check: docker
  • GitHub Check: build (22.x)
  • GitHub Check: all-good
  • GitHub Check: restart-dev-and-test
  • GitHub Check: build (22.x)
  • GitHub Check: setup-tests
  • GitHub Check: docker
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: Security Check
🔇 Additional comments (6)
packages/stack-shared/src/config/schema.ts (6)

57-59: Clarify the intent of .isTrue().optional() pattern.

The combination of .isTrue().optional() is confusing. If a field is optional, it typically means it can be undefined. However, constraining it to true when present seems to indicate you want either true or undefined, never false. Consider using .oneOf([true]) or documenting why this pattern is necessary.

Also applies to: 69-69, 70-70


190-305: Well-structured migration functions with clear documentation.

The migration functions are well-implemented with:

  • Clear documentation about their purpose (database migrations only)
  • Comprehensive test coverage
  • Proper handling of nested properties with dot notation
  • Good separation of concerns between different migration operations

307-484: Excellent implementation of defaults system with strong type safety.

The defaults implementation demonstrates:

  • Clever use of TypeScript's type system to ensure type safety
  • Support for function-based defaults for dynamic key generation
  • Comprehensive test coverage for edge cases including dot notation
  • Clear separation between different config levels

530-588: Well-implemented sanitization functions with proper type safety.

The sanitization functions correctly:

  • Assert normalization before processing
  • Handle sourceOfTruth type narrowing with proper type guards
  • Merge default email themes/templates appropriately
  • Maintain type safety throughout the chain

590-794: Comprehensive validation system with clear error/warning separation.

The validation implementation excels in:

  • Clear distinction between blocking errors and non-blocking warnings
  • Thorough schema introspection with proper handling of nested types
  • Good error messages that guide users
  • Proper handling of the canNoLongerBeOverridden metadata
  • Smart decision to prefer records over arrays for config structures

796-866: Excellent type definitions with comprehensive compile-time checks.

The type system implementation:

  • Provides clear types for each stage of config processing
  • Uses Expand for better IDE tooltips and debugging
  • Includes compile-time assertions to catch type errors early
  • Maintains clear separation between override, incomplete, and rendered configs

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This pull request enhances the project configuration system with significant TypeScript utilities, improved validation mechanisms, and comprehensive support for currency/date operations. The changes modernize the config schema system with stricter type safety, better error handling, and granular control over configuration validation at different organizational levels.

  • Enhanced TypeScript utilities: Added sophisticated type manipulation helpers, config schema introspection, and validation utilities in types.tsx and schema-fields.ts
  • Improved configuration system: Refactored config override logic with migration support, sanitization functions, and stricter schema enforcement across project/branch/environment/organization levels
  • New domain-specific utilities: Added currency conversion support and date interval arithmetic functionality

Reviewed Changes

Copilot reviewed 25 out of 25 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
turbo.json Added new environment variables for Google AI, Discord integration
packages/stack-shared/src/utils/types.tsx Major expansion with advanced TypeScript type utilities and assertion helpers
packages/stack-shared/src/utils/strings.tsx Added typed string joining utilities with compile-time type safety
packages/stack-shared/src/utils/objects.tsx Enhanced object manipulation utilities and improved type definitions
packages/stack-shared/src/utils/dates.tsx New date interval arithmetic functions with schema validation
packages/stack-shared/src/utils/currencies.tsx New currency handling utilities with Stripe integration support
packages/stack-shared/src/schema-fields.ts Extensive schema system improvements with better introspection and validation
packages/stack-shared/src/helpers/emails.ts Updated email template structure to include theme ID fields
packages/stack-shared/src/config/schema.ts Massive refactor of config schema system with migration, validation, and sanitization
packages/stack-shared/src/config/format.ts Enhanced config normalization with better error handling options
packages/stack-shared/src/config/README.md Updated documentation with clearer technical explanations
docs/templates/overview.mdx Fixed broken navigation links
apps/backend/src/route-handlers/smart-request.tsx Fixed logic error in development key override validation
apps/backend/src/lib/projects.tsx Updated trusted domains structure to use unique IDs
apps/backend/src/lib/permissions.tsx Refactored to use new config override helpers
apps/backend/src/lib/email-rendering.tsx Removed debug logging and cleaned imports
apps/backend/src/lib/config.tsx Major refactor of config validation and override logic
apps/backend/src/app/api/latest/internal/email-themes/route.tsx Simplified theme handling by removing automatic updates
apps/backend/src/app/api/latest/internal/email-templates/route.tsx Updated to use new typed entry functions
apps/backend/src/app/api/latest/internal/email-templates/[templateId]/route.tsx Simplified template update logic
apps/backend/src/app/api/latest/emails/render-email/route.tsx Added error handling imports
apps/backend/scripts/verify-data-integrity.ts Added flag to skip Neon projects in verification
apps/backend/prisma/seed.ts Fixed missing brace in seeding logic
apps/backend/package.json Added migration imports watcher to development workflow
.vscode/settings.json Updated spell check dictionary

@N2D4 N2D4 disabled auto-merge July 29, 2025 11:13
@N2D4 N2D4 merged commit 7c0417d into dev Jul 29, 2025
15 of 18 checks passed
@N2D4 N2D4 deleted the improved-config branch July 29, 2025 11:13
@coderabbitai coderabbitai bot mentioned this pull request Jul 31, 2025
madster456 pushed a commit that referenced this pull request Aug 4, 2025
This was referenced Aug 12, 2025
This was referenced Aug 27, 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