From 81780ab7a9a7ddff27a62b865d6cd3c63367d694 Mon Sep 17 00:00:00 2001 From: Bas van den Aakster Date: Fri, 12 Sep 2025 15:35:44 +0200 Subject: [PATCH 1/2] Replace redundant components with updated feature flag hooks and views. Add comprehensive documentation and ESLint config for improved development workflow. --- CLAUDE.md | 105 + README.md | 98 +- dev/README.md | 88 + dev/app/(app)/layout.tsx | 99 + dev/app/(app)/page.tsx | 127 + dev/app/(payload)/admin/importMap.js | 54 +- dev/helpers/credentials.ts | 17 + dev/next.config.mjs | 12 +- dev/payload-types.ts | 332 +- dev/payload.config.ts | 184 +- dev/seed.ts | 131 +- dev/tsconfig.json | 3 + eslint.config.js | 71 +- eslint.config.payload.js | 46 + package.json | 13 +- pnpm-lock.yaml | 11348 ++++++++++++++++ src/components/BeforeDashboardClient.tsx | 29 - .../BeforeDashboardServer.module.css | 5 - src/components/BeforeDashboardServer.tsx | 19 - src/endpoints/customEndpointHandler.ts | 2 +- src/exports/client.ts | 11 +- src/exports/rsc.ts | 2 - src/exports/views.ts | 2 + src/hooks/client.ts | 238 + src/hooks/server.ts | 77 +- src/index.ts | 55 +- src/views/FeatureFlagsView.tsx | 418 + 27 files changed, 13326 insertions(+), 260 deletions(-) create mode 100644 CLAUDE.md create mode 100644 dev/README.md create mode 100644 dev/app/(app)/layout.tsx create mode 100644 dev/app/(app)/page.tsx create mode 100644 eslint.config.payload.js create mode 100644 pnpm-lock.yaml delete mode 100644 src/components/BeforeDashboardClient.tsx delete mode 100644 src/components/BeforeDashboardServer.module.css delete mode 100644 src/components/BeforeDashboardServer.tsx create mode 100644 src/exports/views.ts create mode 100644 src/hooks/client.ts create mode 100644 src/views/FeatureFlagsView.tsx diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2d8d48b --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,105 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +This is a Payload CMS v3 plugin for feature flags (@xtr-dev/payload-feature-flags). The plugin enables feature toggles, A/B testing, and gradual rollouts through a dedicated collection and server-side hooks. + +## Key Commands + +### Development +- `pnpm dev` - Start Next.js dev server with Payload CMS admin panel +- `pnpm dev:payload` - Run Payload CLI commands for development +- `pnpm dev:generate-types` - Generate TypeScript types from Payload config +- `pnpm dev:generate-importmap` - Generate import map for admin panel + +### Building +- `pnpm build` - Full production build (copies files, builds types, compiles with SWC) +- `pnpm build:types` - Generate TypeScript declarations only +- `pnpm build:swc` - Compile TypeScript to JavaScript using SWC +- `pnpm clean` - Remove dist directory and build artifacts +- `pnpm copyfiles` - Copy non-TS assets to dist + +### Testing & Quality +- `pnpm test` - Run all tests (integration + e2e) +- `pnpm test:int` - Run integration tests with Vitest +- `pnpm test:e2e` - Run end-to-end tests with Playwright +- `pnpm lint` - Run ESLint +- `pnpm lint:fix` - Run ESLint with auto-fix + +### Publishing +- `pnpm prepublishOnly` - Clean and build before publishing (runs automatically) + +## Architecture + +### Plugin Structure +The plugin follows Payload's plugin architecture with multiple exports: + +- **Main export (`src/index.ts`)**: Core plugin configuration function +- **RSC export (`src/exports/rsc.ts`)**: Server-side hooks for React Server Components +- **Client export (`src/exports/client.ts`)**: Client-side components (currently placeholder) + +### Core Components + +#### Plugin Configuration (`src/index.ts`) +- `PayloadFeatureFlagsConfig`: Main configuration type +- `payloadFeatureFlags()`: Plugin factory function that creates a Payload collection and optional API endpoints +- Collection overrides support for full customization +- Feature toggles for rollouts, variants, and API endpoints + +#### Server Hooks (`src/hooks/server.ts`) +- `getFeatureFlag()`: Fetch individual flag data +- `isFeatureEnabled()`: Simple boolean check +- `getAllFeatureFlags()`: Get all active flags +- `isUserInRollout()`: Check percentage-based rollouts with consistent hashing +- `getUserVariant()`: A/B testing variant selection +- `getFeatureFlagsByTag()`: Query flags by tags + +#### API Endpoints (`src/endpoints/customEndpointHandler.ts`) +- `GET /api/feature-flags` - List all active feature flags +- `GET /api/feature-flags/:flag` - Get specific flag data +- Only created when `enableApi: true` + +### Collection Schema +The plugin creates a feature flags collection with these key fields: +- `name` (unique): Flag identifier +- `enabled`: On/off toggle +- `rolloutPercentage`: 0-100% rollout control +- `variants`: Array for A/B testing with weights +- `tags`: Organization and filtering +- `metadata`: Additional JSON data + +### Development Environment +- Uses MongoDB Memory Server for testing +- Next.js for admin panel development +- SWC for fast compilation +- Vitest for integration testing +- Playwright for E2E testing + +### Export Strategy +The plugin publishes with different entry points: +- **Development**: Points to TypeScript sources (`src/`) +- **Production**: Points to compiled JavaScript (`dist/`) +- Supports both CommonJS and ESM through package.json exports + +## Important Notes + +### Plugin Integration +The plugin integrates with Payload by: +1. Creating a feature flags collection with configurable slug and fields +2. Adding optional REST API endpoints +3. Providing server-side hooks that work with any collection slug +4. Supporting full collection customization through `collectionOverrides` + +### Security Considerations +- REST API endpoints are disabled by default (`enableApi: false`) +- Server-side hooks are the preferred method for accessing feature flags +- Collection access can be restricted through `collectionOverrides.access` + +### Testing Setup +The development configuration (`dev/payload.config.ts`) includes: +- MongoDB Memory Server for isolated testing +- Test collections (posts, media) +- Example plugin configuration with collection overrides +- Seeding functionality for development data \ No newline at end of file diff --git a/README.md b/README.md index f29ac30..517b973 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,17 @@ # @xtr-dev/payload-feature-flags -A powerful feature flags plugin for Payload CMS v3 that enables you to manage feature toggles, A/B testing, and gradual rollouts directly from your Payload admin panel. +Feature flags plugin for Payload CMS v3. Manage feature toggles, A/B tests, and rollouts from your admin panel. + +โš ๏ธ **Pre-release Warning**: This package is currently in active development (v0.0.x). Breaking changes may occur before v1.0.0. Not recommended for production use. ## Features -- ๐Ÿš€ **Easy Integration** - Drop-in plugin with minimal configuration -- ๐Ÿ”„ **Gradual Rollouts** - Percentage-based feature deployment -- ๐Ÿงช **A/B Testing** - Built-in variant support -- ๐Ÿ›ฃ๏ธ **REST API** - Simple flag state endpoints +- ๐Ÿš€ **Easy setup** - Add to your Payload config and you're done +- ๐ŸŽ›๏ธ **Admin dashboard** - Manage flags from your Payload admin panel +- ๐Ÿ”„ **Gradual rollouts** - Roll out features to a percentage of users +- ๐Ÿงช **A/B testing** - Test different versions of features +- ๐Ÿ›ฃ๏ธ **REST API** - Check flag status via API endpoints +- ๐Ÿ—ƒ๏ธ **Quick demo** - Try it instantly with no database setup ## Installation @@ -15,21 +19,17 @@ A powerful feature flags plugin for Payload CMS v3 that enables you to manage fe npm install @xtr-dev/payload-feature-flags ``` -Or using pnpm: - ```bash +# or with pnpm pnpm add @xtr-dev/payload-feature-flags -``` -Or using yarn: - -```bash +# or with yarn yarn add @xtr-dev/payload-feature-flags ``` ## Requirements -- Payload CMS v3.37.0 or higher +- Payload CMS v3.37.0+ - Node.js 18.20.2+ or 20.9.0+ - React 19.1.0+ @@ -47,12 +47,12 @@ export default buildConfig({ // ... your existing config plugins: [ payloadFeatureFlags({ - // All options are optional - defaultValue: false, // Default state for new flags - enableRollouts: true, // Enable percentage-based rollouts - enableVariants: true, // Enable A/B testing variants - enableApi: false, // Enable REST API endpoints - disabled: false, // Disable plugin if needed + // All options are optional - these are the defaults + defaultValue: false, // New flags start disabled + enableRollouts: true, // Allow percentage rollouts + enableVariants: true, // Allow A/B testing + enableApi: false, // REST API endpoints + disabled: false, // Plugin enabled }), ], }) @@ -60,7 +60,7 @@ export default buildConfig({ ### Configuration Options -The plugin accepts the following configuration options: +Available plugin options: ```typescript export type PayloadFeatureFlagsConfig = { @@ -113,9 +113,9 @@ export type PayloadFeatureFlagsConfig = { } ``` -### Collection Overrides +### Custom Fields and Access -You can customize the feature flags collection using `collectionOverrides`: +Add custom fields or change permissions using `collectionOverrides`: ```typescript payloadFeatureFlags({ @@ -171,9 +171,29 @@ payloadFeatureFlags({ Once installed, the plugin automatically: 1. **Creates a dedicated collection** - A `feature-flags` collection (or custom name) for managing all flags -2. **Provides a clean admin interface** - Manage flags directly from the Payload admin panel -3. **Exposes REST API endpoints** - Simple endpoints for checking flag states -4. **Keeps your data clean** - No modifications to your existing collections +2. **Provides a clean admin interface** - Manage flags directly from the Payload admin panel +3. **Adds a custom dashboard view** - Enhanced UI for managing flags at `/admin/feature-flags-overview` +4. **Exposes REST API endpoints** - Simple endpoints for checking flag states +5. **Keeps your data clean** - No modifications to your existing collections + +### Admin Interface + +The plugin provides a custom admin view with enhanced UI for managing feature flags: + +**๐Ÿ“ Access:** `/admin/feature-flags-overview` + +**Features:** +- ๐Ÿ“Š **Dashboard Overview** - Visual stats showing total, enabled, and rolling out flags +- ๐Ÿ” **Search & Filter** - Find flags by name/description and filter by status +- ๐ŸŽ›๏ธ **Quick Toggle** - Enable/disable flags with visual toggle switches +- ๐Ÿท๏ธ **Smart Labels** - Visual indicators for rollout percentages, A/B tests, and environments +- ๐Ÿ“ฑ **Responsive Design** - Works seamlessly on desktop and mobile devices + +The custom view provides a more user-friendly interface compared to the standard collection view, with: +- Real-time status indicators +- One-click flag toggling +- Better visual organization +- Advanced filtering capabilities ### Using Feature Flags in React Server Components @@ -390,6 +410,24 @@ payloadFeatureFlags({ ## Development +### Try the Demo + +Test the plugin with zero setup: + +```bash +git clone https://github.com/xtr-dev/payload-feature-flags +cd payload-feature-flags +pnpm install +pnpm dev +# Visit http://localhost:3000 +``` + +**What you get:** +- ๐Ÿ—ƒ๏ธ **No database needed** - Uses in-memory MongoDB +- ๐ŸŽฏ **Sample data included** - Ready-to-test feature flag +- ๐Ÿ”‘ **Auto-login** - Use `dev@payloadcms.com / test` +- ๐Ÿ“ฑ **Working dashboard** - See flags in action + ### Building the Plugin ```bash @@ -406,20 +444,10 @@ pnpm test pnpm lint ``` -### Testing - -```bash -# Run integration tests -pnpm test:int - -# Run E2E tests -pnpm test:e2e -``` - ### Development Mode ```bash -# Start development server +# Start development server with hot reload pnpm dev # Generate types diff --git a/dev/README.md b/dev/README.md new file mode 100644 index 0000000..3ad57d1 --- /dev/null +++ b/dev/README.md @@ -0,0 +1,88 @@ +# Demo Environment + +Simple demo for testing the feature flags plugin. + +## Quick Start + +```bash +pnpm install +pnpm dev +# Visit http://localhost:3000 +``` + +**URLs:** +- **Home:** http://localhost:3000 +- **Admin:** http://localhost:3000/admin +- **API:** http://localhost:3000/api/feature-flags + +## Login + +**Admin:** `dev@payloadcms.com` / `test` (full access) +**Editor:** `editor@payloadcms.com` / `test123` (limited access) +**User:** `user@payloadcms.com` / `test123` (read-only) + +## What's included + +**Homepage:** Shows feature flag status and demo content +**Admin Panel:** Manage feature flags and users +**Sample Data:** One test feature flag ready to use + +## Testing the Plugin + +1. **Check the homepage** - See the feature flag in action +2. **Login to admin** - Use admin credentials above +3. **Toggle the flag** - Go to Feature Flags collection +4. **Refresh homepage** - See content appear/disappear + +## Plugin Config + +```typescript +payloadFeatureFlags({ + enableRollouts: true, // Percentage rollouts + enableVariants: true, // A/B testing + enableApi: true, // REST endpoints + defaultValue: false, // New flags start disabled + // + custom fields and permissions +}) +``` + +## API Testing + +```bash +# Get all flags +curl http://localhost:3000/api/feature-flags + +# Get specific flag +curl http://localhost:3000/api/feature-flags/new-feature +``` + + +## Database + +Uses in-memory MongoDB - no setup needed! Data resets on each restart. + +## Creating New Flags + +1. Login to `/admin/collections/feature-flags` +2. Click "Create New" +3. Add name, description, and toggle enabled/disabled +4. Check the homepage to see it working + +## Need Help? + +- Check the console for error messages +- Make sure port 3000 is available +- Try logging in as admin user + +## Next Steps + +Ready to use this in your project? + +1. **Add to your project:** Copy the plugin config +2. **Customize:** Add your own fields and permissions +3. **Go live:** Use a real MongoDB database +4. **Monitor:** Track how your flags perform + +--- + +This demo gives you everything needed to test feature flags with zero setup. diff --git a/dev/app/(app)/layout.tsx b/dev/app/(app)/layout.tsx new file mode 100644 index 0000000..0d0b63b --- /dev/null +++ b/dev/app/(app)/layout.tsx @@ -0,0 +1,99 @@ +import React from 'react' + +export default function AppLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + + + + + Feature Flags Demo - Payload CMS Plugin + + +