Skip to content

Several project config improvements#811

Merged
N2D4 merged 31 commits intodevfrom
improved-config
Jul 29, 2025
Merged

Several project config improvements#811
N2D4 merged 31 commits intodevfrom
improved-config

Conversation

@N2D4
Copy link
Copy Markdown
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
@vercel
Copy link
Copy Markdown

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

@coderabbitai
Copy link
Copy Markdown
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
Copy Markdown
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

Comment thread apps/backend/scripts/verify-data-integrity.ts
Comment thread packages/stack-shared/src/utils/strings.tsx Outdated
Comment thread apps/backend/src/lib/config.tsx Outdated
Comment thread packages/stack-shared/src/utils/currencies.tsx
Comment thread packages/stack-shared/src/config/format.ts Outdated
Comment thread packages/stack-shared/src/config/format.ts
Comment thread packages/stack-shared/src/schema-fields.ts
Comment thread apps/backend/package.json Outdated
Comment thread packages/stack-shared/src/utils/dates.tsx
Comment thread apps/backend/prisma/seed.ts
Comment thread apps/backend/scripts/verify-data-integrity.ts
This was referenced Aug 12, 2025
This was referenced Aug 27, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 23, 2025
This was referenced Jan 4, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Feb 5, 2026
This was referenced Mar 9, 2026
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.

2 participants