diff --git a/.cursor/commands/code-review.md b/.cursor/commands/code-review.md deleted file mode 100644 index 14dd499df1..0000000000 --- a/.cursor/commands/code-review.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -name: code-review -description: Automated PR review using comprehensive checklist tailored for modularized Contentstack CLI ---- - -# Code Review Command - -## Usage Patterns - -### Scope-Based Reviews -- `/code-review` - Review all current changes with full checklist -- `/code-review --scope typescript` - Focus on TypeScript configuration and patterns -- `/code-review --scope testing` - Focus on Mocha/Chai test patterns -- `/code-review --scope oclif` - Focus on command structure and OCLIF patterns -- `/code-review --scope packages` - Focus on package structure and organization - -### Severity Filtering -- `/code-review --severity critical` - Show only critical issues (security, breaking changes) -- `/code-review --severity high` - Show high and critical issues -- `/code-review --severity all` - Show all issues including suggestions - -### Package-Aware Reviews -- `/code-review --package contentstack-config` - Review changes in specific package -- `/code-review --package-type plugin` - Review plugin packages only (auth, config) -- `/code-review --package-type library` - Review library packages (command, utilities, dev-dependencies) - -### File Type Focus -- `/code-review --files commands` - Review command files only -- `/code-review --files tests` - Review test files only -- `/code-review --files utils` - Review utility files - -## Comprehensive Review Checklist - -### Monorepo Structure Compliance -- **Package organization**: Proper placement in `packages/` structure -- **pnpm workspace**: Correct `package.json` workspace configuration -- **Build artifacts**: No `lib/` directories committed to version control -- **Dependencies**: Proper use of shared utilities (`@contentstack/cli-command`, `@contentstack/cli-utilities`) -- **Scripts**: Consistent build, test, and lint scripts across packages - -### Package-Specific Structure -- **Plugin packages** (auth, config): Have `oclif.commands` configuration -- **Library packages** (command, utilities, dev-dependencies): Proper exports in package.json -- **Main package** (contentstack): Aggregates plugins correctly -- **Dependency versions**: Using beta versions appropriately (~version ranges) - -### TypeScript Standards -- **Configuration compliance**: Follows package TypeScript config (`strict: false`, `target: es2017`) -- **Naming conventions**: kebab-case files, PascalCase classes, camelCase functions -- **Import patterns**: ES modules with proper default/named exports -- **Type safety**: No unnecessary `any` types in production code - -### OCLIF Command Patterns -- **Base class usage**: Extends `@contentstack/cli-command` Command -- **Command structure**: Proper `static description`, `static examples`, `static flags` -- **Topic organization**: Uses `cm` topic structure (`cm:config:set`, `cm:auth:login`) -- **Error handling**: Uses `handleAndLogError` from utilities -- **Flag validation**: Early validation and user-friendly error messages -- **Service delegation**: Commands orchestrate, services implement business logic - -### Testing Excellence (Mocha/Chai Stack) -- **Framework compliance**: Uses Mocha + Chai (not Jest) -- **File patterns**: Follows `*.test.ts` naming convention -- **Directory structure**: Proper placement in `test/unit/` -- **Test organization**: Arrange-Act-Assert pattern consistently used -- **Isolation**: Proper setup/teardown with beforeEach/afterEach -- **No real API calls**: All external dependencies properly mocked - -### Error Handling Standards -- **Consistent patterns**: Use `handleAndLogError` from utilities -- **User-friendly messages**: Clear error descriptions for end users -- **Logging**: Proper use of `log.debug` for diagnostic information -- **Status messages**: Use `cliux` for user feedback (success, error, info) - -### Build and Compilation -- **TypeScript compilation**: Clean compilation with no errors -- **OCLIF manifest**: Generated for command discovery -- **README generation**: Commands documented in package README -- **Source maps**: Properly configured for debugging -- **No build artifacts in commit**: `.gitignore` excludes `lib/` directories - -### Testing Coverage -- **Test structure**: Tests in `test/unit/` with descriptive names -- **Command testing**: Uses @oclif/test for command validation -- **Error scenarios**: Tests for both success and failure paths -- **Mocking**: All dependencies properly mocked - -### Package.json Compliance -- **Correct metadata**: name, description, version, author -- **Script definitions**: build, compile, test, lint scripts present -- **Dependencies**: Correct versions of shared packages -- **Main/types**: Properly configured for library packages -- **OCLIF config**: Present for plugin packages - -### Security and Best Practices -- **No secrets**: No API keys or tokens in code or tests -- **Input validation**: Proper validation of user inputs and flags -- **Process management**: Appropriate use of error codes -- **File operations**: Safe handling of file system operations - -### Code Quality -- **Naming consistency**: Follow established conventions -- **Comments**: Only for non-obvious logic (no "narration" comments) -- **Error messages**: Clear, actionable messages for users -- **Module organization**: Proper separation of concerns - -## Review Execution - -### Automated Checks -1. **Lint compliance**: ESLint checks for code style -2. **TypeScript compiler**: Successful compilation to `lib/` directories -3. **Test execution**: All tests pass successfully -4. **Build verification**: Build scripts complete without errors - -### Manual Review Focus Areas -1. **Command usability**: Clear help text and realistic examples -2. **Error handling**: Appropriate error messages and recovery options -3. **Test quality**: Comprehensive test coverage for critical paths -4. **Monorepo consistency**: Consistent patterns across all packages -5. **Flag design**: Intuitive flag names and combinations - -### Common Issues to Flag -- **Inconsistent TypeScript settings**: Mixed strict mode without reason -- **Real API calls in tests**: Unmocked external dependencies -- **Missing error handling**: Commands that fail silently -- **Poor test organization**: Tests without clear Arrange-Act-Assert -- **Build artifacts committed**: `lib/` directories in version control -- **Unclear error messages**: Non-actionable error descriptions -- **Inconsistent flag naming**: Similar flags with different names -- **Missing command examples**: Examples not showing actual usage - -## Repository-Specific Checklist - -### For Modularized CLI -- [ ] Command properly extends `@contentstack/cli-command` Command -- [ ] Flags defined with proper types from `@contentstack/cli-utilities` -- [ ] Error handling uses `handleAndLogError` utility -- [ ] User feedback uses `cliux` utilities -- [ ] Tests use Mocha + Chai pattern with mocked dependencies -- [ ] Package.json has correct scripts (build, compile, test, lint) -- [ ] TypeScript compiles with no errors -- [ ] Tests pass: `pnpm test` -- [ ] No `.only` or `.skip` in test files -- [ ] Build succeeds: `pnpm run build` -- [ ] OCLIF manifest generated successfully - -### Before Merge -- [ ] All review items addressed -- [ ] No build artifacts in commit -- [ ] Tests added for new functionality -- [ ] Documentation updated if needed -- [ ] No console.log() statements (use log.debug instead) -- [ ] Error messages are user-friendly -- [ ] No secrets or credentials in code diff --git a/.cursor/commands/execute-tests.md b/.cursor/commands/execute-tests.md deleted file mode 100644 index fb473ecf26..0000000000 --- a/.cursor/commands/execute-tests.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -name: execute-tests -description: Run tests by scope, file, or module with intelligent filtering for this pnpm monorepo ---- - -# Execute Tests Command - -## Usage Patterns - -### Monorepo-Wide Testing -- `/execute-tests` - Run all tests across all packages -- `/execute-tests --coverage` - Run all tests with coverage reporting -- `/execute-tests --parallel` - Run package tests in parallel using pnpm - -### Package-Specific Testing -- `/execute-tests contentstack-config` - Run tests for config package -- `/execute-tests contentstack-auth` - Run tests for auth package -- `/execute-tests contentstack-command` - Run tests for command package -- `/execute-tests contentstack-utilities` - Run tests for utilities package -- `/execute-tests packages/contentstack-config/` - Run tests using path - -### Scope-Based Testing -- `/execute-tests unit` - Run unit tests only (`test/unit/**/*.test.ts`) -- `/execute-tests commands` - Run command tests (`test/unit/commands/**/*.test.ts`) -- `/execute-tests services` - Run service layer tests - -### File Pattern Testing -- `/execute-tests *.test.ts` - Run all TypeScript tests -- `/execute-tests test/unit/commands/` - Run tests for specific directory - -### Watch and Development -- `/execute-tests --watch` - Run tests in watch mode with file monitoring -- `/execute-tests --debug` - Run tests with debug output enabled -- `/execute-tests --bail` - Stop on first test failure - -## Intelligent Filtering - -### Repository-Aware Detection -- **Test patterns**: All use `*.test.ts` naming convention -- **Directory structures**: Standard `test/unit/` layout -- **Test locations**: `packages/*/test/unit/**/*.test.ts` -- **Build exclusion**: Ignores `lib/` directories (compiled artifacts) - -### Package Structure -The monorepo contains 6 packages: -- `contentstack` - Main CLI package -- `contentstack-auth` - Authentication plugin -- `contentstack-config` - Configuration plugin -- `contentstack-command` - Base Command class (library) -- `contentstack-utilities` - Utilities library -- `contentstack-dev-dependencies` - Dev dependencies - -### Monorepo Integration -- **pnpm workspace support**: Uses `pnpm -r --filter` for package targeting -- **Dependency awareness**: Understands package interdependencies -- **Parallel execution**: Leverages pnpm's parallel capabilities -- **Selective testing**: Can target specific packages or file patterns - -### Framework Detection -- **Mocha configuration**: Respects `.mocharc.json` files per package -- **TypeScript compilation**: Handles test TypeScript setup -- **Test setup**: Detects test helper initialization files -- **Test timeout**: 30 seconds standard (configurable per package) - -## Execution Examples - -### Common Workflows -```bash -# Run all tests with coverage -/execute-tests --coverage - -# Test specific package during development -/execute-tests contentstack-config --watch - -# Run only command tests across all packages -/execute-tests commands - -# Run unit tests with detailed output -/execute-tests --debug - -# Test until first failure (quick feedback) -/execute-tests --bail -``` - -### Package-Specific Commands Generated -```bash -# For contentstack-config package -cd packages/contentstack-config && pnpm test - -# For all packages with parallel execution -pnpm -r --filter './packages/*' run test - -# For specific test file -cd packages/contentstack-config && npx mocha "test/unit/commands/region.test.ts" - -# With coverage -pnpm -r --filter './packages/*' run test:coverage -``` - -## Configuration Awareness - -### Mocha Integration -- Respects individual package `.mocharc.json` configurations -- Handles TypeScript compilation via ts-node/register -- Supports test helpers and initialization files -- Manages timeout settings per package (default 30 seconds) - -### Test Configuration -```json -// .mocharc.json -{ - "require": [ - "test/helpers/init.js", - "ts-node/register", - "source-map-support/register" - ], - "recursive": true, - "timeout": 30000, - "spec": "test/**/*.test.ts" -} -``` - -### pnpm Workspace Features -- Leverages workspace dependency resolution -- Supports filtered execution by package patterns -- Enables parallel test execution across packages -- Respects package-specific scripts and configurations - -## Test Structure - -### Standard Test Organization -``` -packages/*/ -├── test/ -│ └── unit/ -│ ├── commands/ # Command-specific tests -│ ├── services/ # Service/business logic tests -│ └── utils/ # Utility function tests -└── src/ - ├── commands/ # CLI commands - ├── services/ # Business logic - └── utils/ # Utilities -``` - -### Test File Naming -- **Pattern**: `*.test.ts` across all packages -- **Location**: `test/unit/` directories -- **Organization**: Mirrors `src/` structure for easy navigation - -## Performance Optimization - -### Parallel Testing -```bash -# Run tests in parallel for faster feedback -pnpm -r --filter './packages/*' run test - -# Watch mode during development -/execute-tests --watch -``` - -### Selective Testing -- Run only affected packages' tests during development -- Use `--bail` to stop on first failure for quick iteration -- Target specific test files for focused debugging - -## Troubleshooting - -### Common Issues - -**Tests not found** -- Check that files follow `*.test.ts` pattern -- Verify files are in `test/unit/` directory -- Ensure `.mocharc.json` has correct spec pattern - -**TypeScript compilation errors** -- Verify `tsconfig.json` in package root -- Check that `ts-node/register` is in `.mocharc.json` requires -- Run `pnpm compile` to check TypeScript errors - -**Watch mode not detecting changes** -- Verify `--watch` flag is supported in your Mocha version -- Check that file paths are correct -- Ensure no excessive `.gitignore` patterns - -**Port conflicts** -- Tests should not use hard-coded ports -- Use dynamic port allocation or test isolation -- Check for process cleanup in `afterEach` hooks - -## Best Practices - -### Test Execution -- Run tests before committing: `pnpm test` -- Use `--bail` during development for quick feedback -- Run full suite before opening PR -- Check coverage for critical paths - -### Test Organization -- Keep tests close to source code structure -- Use descriptive test names -- Group related tests with `describe` blocks -- Clean up resources in `afterEach` - -### Debugging -- Use `--debug` flag for detailed output -- Add `log.debug()` statements in tests -- Run individual test files for isolation -- Use `--bail` to stop at first failure - -## Integration with CI/CD - -### GitHub Actions -- Runs `pnpm test` on pull requests -- Enforces test passage before merge -- May include coverage reporting -- Runs linting and build verification - -### Local Development -```bash -# Before committing -pnpm test -pnpm run lint -pnpm run build - -# Or use watch mode for faster iteration -pnpm test --watch -``` - -## Coverage Reporting - -### Coverage Commands -```bash -# Run tests with coverage -/execute-tests --coverage - -# Coverage output location -coverage/ -├── index.html # HTML report -├── coverage-summary.json # JSON summary -└── lcov.info # LCOV format -``` - -### Coverage Goals -- **Team aspiration**: 80% minimum coverage -- **Focus on**: Critical business logic and error paths -- **Not critical**: Utility functions and edge cases diff --git a/.cursor/rules/README.md b/.cursor/rules/README.md index 148ead7678..f5c1f87014 100644 --- a/.cursor/rules/README.md +++ b/.cursor/rules/README.md @@ -1,84 +1,5 @@ -# Cursor Rules +# Cursor (optional) -Context-aware rules that load automatically based on the files you're editing, optimized for this modularized Contentstack CLI. +**Cursor** users: start at **[AGENTS.md](../../AGENTS.md)**. All conventions live in **`skills/*/SKILL.md`**. -## Rule Files - -| File | Scope | Always Applied | Purpose | -|------|-------|----------------|---------| -| `dev-workflow.md` | `**/*.ts`, `**/*.js`, `**/*.json` | Yes | Monorepo TDD workflow, pnpm workspace patterns (6 packages) | -| `typescript.mdc` | `**/*.ts`, `**/*.tsx` | No | TypeScript configurations and naming conventions | -| `testing.mdc` | `**/test/**/*.ts`, `**/test/**/*.js`, `**/__tests__/**/*.ts`, `**/*.spec.ts`, `**/*.test.ts` | Yes | Mocha, Chai test patterns and test structure | -| `oclif-commands.mdc` | `**/commands/**/*.ts`, `**/base-command.ts` | No | OCLIF command patterns and CLI validation | -| `contentstack-core.mdc` | `packages/contentstack/src/**/*.ts`, `packages/contentstack/src/**/*.js` | No | Core package plugin aggregation, hooks, and entry point patterns | - -## Commands - -| File | Trigger | Purpose | -|------|---------|---------| -| `execute-tests.md` | `/execute-tests` | Run tests by scope, package, or module with monorepo awareness | -| `code-review.md` | `/code-review` | Automated PR review with CLI-specific checklist | - -## Loading Behaviour - -### File Type Mapping -- **TypeScript files** → `typescript.mdc` + `dev-workflow.md` -- **Command files** (`packages/*/src/commands/**/*.ts`) → `oclif-commands.mdc` + `typescript.mdc` + `dev-workflow.md` -- **Base command files** (`packages/*/src/base-command.ts`) → `oclif-commands.mdc` + `typescript.mdc` + `dev-workflow.md` -- **Core package files** (`packages/contentstack/src/**/*.ts`) → `contentstack-core.mdc` + `typescript.mdc` + `dev-workflow.md` -- **Test files** (`packages/*/test/**/*.{ts,js}`) → `testing.mdc` + `dev-workflow.md` -- **Utility files** (`packages/*/src/utils/**/*.ts`) → `typescript.mdc` + `dev-workflow.md` - -### Package-Specific Loading -- **Plugin packages** (with `oclif.commands`) → Full command and utility rules -- **Library packages** → TypeScript and utility rules only - -## Repository-Specific Features - -### Monorepo Structure -- **6 packages** under `packages/`: - - `contentstack` - Main CLI entry point (bin/run.js) - - `contentstack-auth` - Authentication plugin - - `contentstack-config` - Configuration plugin - - `contentstack-command` - Base Command class for plugins - - `contentstack-utilities` - Shared utilities and helpers - - `contentstack-dev-dependencies` - Development dependencies - -### Build Configuration -- **pnpm workspaces** configuration -- **Shared dependencies**: `@contentstack/cli-command`, `@contentstack/cli-utilities` -- **Build process**: TypeScript compilation → `lib/` directories -- **OCLIF manifest** generation for command discovery - -### Actual Patterns Detected -- **Testing**: Mocha + Chai (not Jest or Sinon-heavy) -- **TypeScript**: Mixed strict mode adoption -- **Commands**: Extend `@oclif/core` Command class -- **Build artifacts**: `lib/` directories (excluded from rules) - -## Performance Benefits - -- **Lightweight loading** - Only relevant rules activate based on file patterns -- **Precise glob patterns** - Avoid loading rules for build artifacts -- **Context-aware** - Rules load based on actual file structure - -## Design Principles - -### Validated Against Codebase -- Rules reflect **actual patterns** found in repository -- Glob patterns match **real file structure** -- Examples use **actual dependencies** and APIs - -### Lightweight and Focused -- Each rule has **single responsibility** -- Package-specific variations acknowledged -- `alwaysApply: true` only for truly universal patterns - -## Quick Reference - -For detailed patterns: -- **Testing**: See `testing.mdc` for Mocha/Chai test structure -- **Commands**: See `oclif-commands.mdc` for command development -- **Core Package**: See `contentstack-core.mdc` for plugin aggregation and hook patterns -- **Development**: See `dev-workflow.md` for TDD and monorepo workflow -- **TypeScript**: See `typescript.mdc` for type safety patterns +This folder only points contributors to **`AGENTS.md`** so editor-specific config does not duplicate the canonical docs. diff --git a/.cursor/rules/contentstack-core.mdc b/.cursor/rules/contentstack-core.mdc deleted file mode 100644 index 730daaa5f9..0000000000 --- a/.cursor/rules/contentstack-core.mdc +++ /dev/null @@ -1,358 +0,0 @@ ---- -description: "Contentstack core CLI package patterns — plugin aggregation, hooks, and entry point" -globs: ["packages/contentstack/src/**/*.ts", "packages/contentstack/src/**/*.js"] -alwaysApply: false ---- - -# Contentstack Core Package Standards - -## Overview - -The `@contentstack/cli` core package is the entry point for the entire CLI. Unlike plugin packages (auth, config), it: -- **Aggregates all plugins** — declared in `oclif.plugins` array in `package.json` -- **Implements hooks** — `init` and `prerun` hooks in `src/hooks/` for global behaviors -- **Shares interfaces** — Core types used across all plugins in `src/interfaces/` -- **Provides utilities** — Helper classes like `CsdxContext` in `src/utils/` -- **Has no command files** — Commands are provided by plugin packages - -## Architecture - -### Entry Point - -```typescript -// ✅ GOOD - bin/run.js (CommonJS) -// This is the executable entry point referenced in package.json "bin" -// Standard OCLIF entry point pattern -``` - -### Package Configuration - -The `oclif` configuration in `package.json`: -```json -{ - "oclif": { - "bin": "csdx", - "topicSeparator": ":", - "helpClass": "./lib/help.js", - "plugins": [ - "@oclif/plugin-help", - "@oclif/plugin-not-found", - "@oclif/plugin-plugins", - "@contentstack/cli-config", - "@contentstack/cli-auth" - // ... more plugins - ], - "hooks": { - "init": [ - "./lib/hooks/init/context-init", - "./lib/hooks/init/utils-init" - ], - "prerun": [ - "./lib/hooks/prerun/init-context-for-command", - "./lib/hooks/prerun/command-deprecation-check", - "./lib/hooks/prerun/default-rate-limit-check", - "./lib/hooks/prerun/latest-version-warning" - ] - }, - "topics": { - "auth": { "description": "Perform authentication-related activities" }, - "config": { "description": "Perform configuration related activities" }, - "cm": { "description": "Perform content management activities" } - } - } -} -``` - -## Hook Lifecycle - -### OCLIF Hook Execution Order - -1. **CLI initialization** → Node process starts -2. **`init` hooks** → Set up global context and utilities (executed once) -3. **Command detection** → OCLIF matches command name to plugin -4. **`prerun` hooks** → Validate state, check auth, prepare for command execution (per command) -5. **Command execution** → Plugin command's `run()` method executes - -### Init Hooks - -Init hooks run once during CLI startup. Use them for expensive setup operations. - -```typescript -// ✅ GOOD - src/hooks/init/context-init.ts -// Initialize CLI context that commands depend on -import { CsdxContext } from '../../utils'; -import { configHandler } from '@contentstack/cli-utilities'; - -export default function (opts): void { - // Store command ID for session-based log organization - if (opts.id) { - configHandler.set('currentCommandId', opts.id); - } - // Make context available to all commands via this.config.context - this.config.context = new CsdxContext(opts, this.config); -} -``` - -### Prerun Hooks - -Prerun hooks run before each command. Use them for validation and state checks. - -```typescript -// ✅ GOOD - src/hooks/prerun/auth-guard.ts -// Validate authentication before running protected commands - -import { cliux, isAuthenticated, managementSDKClient } from '@contentstack/cli-utilities'; - -export default async function (opts): Promise { - const { context: { region = null } = {} } = this.config; - - // Validate region is set (required for all non-region commands) - if (opts.Command.id !== 'config:set:region') { - if (!region) { - cliux.error('No region found, please set a region via config:set:region'); - this.exit(); - return; - } - } - - // Example: Validate auth for protected commands - if (isProtectedCommand(opts.Command.id)) { - if (!isAuthenticated()) { - cliux.error('Please log in to execute this command'); - this.exit(); - } - } -} -``` - -### Hook Patterns - -#### Accessing Configuration -```typescript -// ✅ GOOD - Access global config in hooks -export default function (opts): void { - const { config } = this; // OCLIF Config object - const { context, region } = config; // Custom properties set by other hooks -} -``` - -#### Async Hooks -```typescript -// ✅ GOOD - Async hooks for operations requiring I/O -export default async function (opts): Promise { - const client = await managementSDKClient({ host: this.config.region.cma }); - const user = await client.getUser(); - // Hook runs to completion before command starts -} -``` - -#### Early Exit -```typescript -// ✅ GOOD - Exit hook execution when validation fails -export default function (opts): void { - if (!isValid()) { - cliux.error('Validation failed'); - this.exit(); // Stops command from executing - return; - } -} -``` - -## Context Object - -The `CsdxContext` class wraps OCLIF config and adds CLI-specific state. - -```typescript -// ✅ GOOD - Accessing context in commands -import { CLIConfig } from '../interfaces'; - -export default class MyCommand extends Command { - async run(): Promise { - const config: CLIConfig = this.config; - const { context } = config; - - // Available context properties: - // - context.id: unique session identifier - // - context.user: authenticated user info (authtoken, email) - // - context.region: current region configuration - // - context.config: regional configuration - // - context.plugin: current plugin metadata - } -} -``` - -## Shared Interfaces - -Interfaces in `src/interfaces/index.ts` are exported and consumed by all plugins. - -```typescript -// ✅ GOOD - Define shared types -export interface Context { - id: string; - user: { - authtoken: string; - email: string; - }; - region: Region; - plugin: Plugin; - config: any; -} - -export interface CLIConfig extends Config { - context: Context; -} - -export interface Region { - name: string; - cma: string; // Content Management API endpoint - cda: string; // Content Delivery API endpoint -} -``` - -## Utilities - -Core utilities in `src/utils/` provide shared functionality. - -```typescript -// ✅ GOOD - src/utils/context-handler.ts -// Wrapper around context initialization and access -export class CsdxContext { - constructor(opts: any, config: any) { - this.id = opts.id || generateId(); - this.region = config.region; - this.user = extractUserFromToken(); - } -} - -// Export utilities for use in hooks and contexts -export { CsdxContext }; -``` - -## Plugin Registration - -Plugins are registered via `oclif.plugins` in `package.json`. Each plugin package must: - -1. **Provide commands** — via `oclif.commands` in its `package.json` -2. **Be installed** — as a dependency in the core package -3. **Be listed** — in `oclif.plugins` array for auto-discovery - -```json -{ - "dependencies": { - "@contentstack/cli-config": "~1.20.0-beta.1", - "@contentstack/cli-auth": "~1.8.0-beta.1" - }, - "oclif": { - "plugins": [ - "@contentstack/cli-config", - "@contentstack/cli-auth" - ] - } -} -``` - -### Plugin Discovery - -OCLIF automatically discovers commands in: -1. Built-in plugins (`@oclif/plugin-help`, etc.) -2. Core package commands (none in contentstack core) -3. Registered plugins (listed in `oclif.plugins`) - -## Differences from Plugin Packages - -| Aspect | Core Package | Plugin Package | -|--------|--------------|----------------| -| **OCLIF config** | No `commands` field | Has `oclif.commands: "./lib/commands"` | -| **Source structure** | `src/hooks/`, `src/interfaces/`, `src/utils/` | `src/commands/`, `src/services/` | -| **Entry point** | `bin/run.js` | None | -| **Dependencies** | References all plugins | Depends on `@contentstack/cli-command` | -| **Execution role** | Aggregates and initializes | Implements business logic | - -## Build Process - -The core package build includes hook compilation and OCLIF manifest generation. - -```bash -# In package.json scripts -"build": "pnpm compile && oclif manifest && oclif readme" -``` - -### Build Steps - -1. **compile** — TypeScript → JavaScript in `lib/` -2. **oclif manifest** — Generate `oclif.manifest.json` for plugin discovery -3. **oclif readme** — Generate README with available commands - -### Build Artifacts - -- `lib/` — Compiled hooks, utilities, interfaces -- `oclif.manifest.json` — Plugin and command registry -- `bin/run.js` — Executable entry point -- `README.md` — Generated command documentation - -## Testing Hooks - -Hooks cannot be tested with standard command testing. Test hook behavior by: - -1. **Unit test hook functions** — Import and invoke directly -2. **Integration test via CLI** — Run commands that trigger hooks -3. **Mock OCLIF config** — Provide mocked `this.config` object - -```typescript -// ✅ GOOD - Test hook function directly -import contextInit from '../src/hooks/init/context-init'; - -describe('context-init hook', () => { - it('should set context on config', () => { - const mockConfig = { context: null }; - const hookContext = { config: mockConfig }; - const opts = { id: 'test-command' }; - - contextInit.call(hookContext, opts); - - expect(mockConfig.context).to.exist; - }); -}); -``` - -## Error Handling in Hooks - -Hooks should fail fast and provide clear error messages to users. - -```typescript -// ✅ GOOD - Clear error messages with user guidance -export default function (opts): void { - if (!isRegionSet()) { - cliux.error('No region configured'); - cliux.print('Run: csdx config:set:region --region us', { color: 'blue' }); - this.exit(); - } -} -``` - -## Best Practices - -### Hook Organization -- Keep hooks focused on a single concern (validation, initialization, etc.) -- Use descriptive names that indicate when they run (`prerun-`, `init-`) -- Initialize dependencies in `init` hooks, not in `prerun` hooks - -### Performance -- Minimize work in `init` hooks (they run once per CLI session) -- Cache expensive operations in context for reuse -- Avoid repeated API calls across hooks - -### Ordering -- Place hooks that prepare data before hooks that consume it -- Auth validation (`auth-guard`) should run after region validation -- Version warnings can run last (non-critical) - -### Context Usage -- Store computed values in context to avoid recalculation -- Make context available to all commands via `this.config.context` -- Document context properties that plugins should expect - -### Plugin Development -- Ensure plugins depend on `@contentstack/cli-command`, not the core package -- Commands should extend the shared Command base class -- Plugins should not modify or depend on core hooks directly diff --git a/.cursor/rules/dev-workflow.md b/.cursor/rules/dev-workflow.md deleted file mode 100644 index 517867b0ef..0000000000 --- a/.cursor/rules/dev-workflow.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -description: "Core development workflow and TDD patterns - always applied" -globs: ["**/*.ts", "**/*.js", "**/*.json"] -alwaysApply: true ---- - -# Development Workflow - -## Monorepo Structure - -### Package Organization -This modularized CLI has 6 packages under `packages/`: - -1. **contentstack** - Main CLI package - - Entry point: `bin/run.js` - - Aggregates all plugins - -2. **contentstack-auth** - Authentication plugin - - Commands: `cm:auth:*` - - Handles login/logout flows - -3. **contentstack-config** - Configuration plugin - - Commands: `cm:config:*`, `cm:region:*`, etc. - - Manages CLI settings and preferences - -4. **contentstack-command** - Base Command class (library) - - Shared Command base for all plugins - - Utilities and helpers for command development - -5. **contentstack-utilities** - Utilities library - - Shared helpers and utilities - - Used by all packages - -6. **contentstack-dev-dependencies** - Dev dependencies - - Centralized development dependencies - -### pnpm Workspace Configuration -```json -{ - "workspaces": ["packages/*"] -} -``` - -### Development Commands -```bash -# Install dependencies for all packages -pnpm install - -# Run command across all packages -pnpm -r --filter './packages/*' - -# Work on specific package -cd packages/contentstack-config -pnpm test -``` - -## TDD Workflow - MANDATORY - -1. **RED** → Write ONE failing test in `test/unit/**/*.test.ts` -2. **GREEN** → Write minimal code in `src/` to pass -3. **REFACTOR** → Improve code quality while keeping tests green - -### Test-First Examples -```typescript -// ✅ GOOD - Write test first -describe('ConfigService', () => { - it('should load configuration', async () => { - // Arrange - Set up mocks - const mockConfig = { region: 'us', alias: 'default' }; - - // Act - Call the method - const result = await configService.load(); - - // Assert - Verify behavior - expect(result).to.deep.equal(mockConfig); - }); -}); -``` - -## Critical Rules - -### Testing Standards -- **NO implementation before tests** - Test-driven development only -- **Mock all external dependencies** - No real API calls in tests -- **Use Mocha + Chai** - Standard testing stack -- **Coverage aspiration**: 80% minimum - -### Code Quality -- **TypeScript configuration**: Varies by package -- **NO test.skip or .only in commits** - Clean test suites only -- **Proper error handling** - Clear error messages - -### Build Process -```bash -# Standard build process for each package -pnpm run build # tsc compilation + oclif manifest -pnpm run test # Run test suite -pnpm run lint # ESLint checks -``` - -## Package-Specific Patterns - -### Plugin Packages (auth, config) -- Have `oclif.commands` in `package.json` -- Commands in `src/commands/cm/**/*.ts` -- Built commands in `lib/commands/` -- Extend `@oclif/core` Command class -- Script: `build`: compiles TypeScript, generates OCLIF manifest and README - -### Library Packages (command, utilities, dev-dependencies) -- No OCLIF commands configuration -- Pure TypeScript/JavaScript libraries -- Consumed by other packages -- `main` points to `lib/index.js` - -### Main CLI Package (contentstack) -- Entry point through `bin/run.js` -- Aggregates plugin commands -- Package dependencies reference plugin packages - -## Script Conventions - -### Build Scripts -```json -{ - "build": "pnpm compile && oclif manifest && oclif readme", - "compile": "tsc -b tsconfig.json", - "prepack": "pnpm compile && oclif manifest && oclif readme", - "test": "mocha \"test/unit/**/*.test.ts\"", - "lint": "eslint src/**/*.ts" -} -``` - -### Key Build Steps -1. **compile** - TypeScript compilation to `lib/` -2. **oclif manifest** - Generate command manifest for discovery -3. **oclif readme** - Generate command documentation - -## Quick Reference - -For detailed patterns, see: -- `@testing` - Mocha, Chai test patterns -- `@oclif-commands` - Command structure and validation -- `@dev-workflow` (this document) - Monorepo workflow and TDD - -## Development Checklist - -### Before Starting Work -- [ ] Identify target package in `packages/` -- [ ] Check existing tests in `test/unit/` -- [ ] Understand command structure if working on commands -- [ ] Set up proper TypeScript configuration - -### During Development -- [ ] Write failing test first -- [ ] Implement minimal code to pass -- [ ] Mock external dependencies -- [ ] Follow naming conventions (kebab-case files, PascalCase classes) - -### Before Committing -- [ ] All tests pass: `pnpm test` -- [ ] No `.only` or `.skip` in test files -- [ ] Build succeeds: `pnpm run build` -- [ ] TypeScript compilation clean -- [ ] Proper error handling implemented - -## Common Patterns - -### Service/Class Architecture -```typescript -// ✅ GOOD - Separate concerns -export default class ConfigCommand extends Command { - static description = 'Manage CLI configuration'; - - async run(): Promise { - try { - const service = new ConfigService(); - await service.execute(); - this.log('Configuration updated successfully'); - } catch (error) { - this.error('Configuration update failed'); - } - } -} -``` - -### Error Handling -```typescript -// ✅ GOOD - Clear error messages -try { - await this.performAction(); -} catch (error) { - if (error instanceof ValidationError) { - this.error(`Invalid input: ${error.message}`); - } else { - this.error('Operation failed'); - } -} -``` - -## CI/CD Integration - -### GitHub Actions -- Uses workflow files in `.github/workflows/` -- Runs linting, tests, and builds on pull requests -- Enforces code quality standards - -### Pre-commit Hooks -- Husky integration for pre-commit checks -- Prevents commits with linting errors -- Located in `.husky/` diff --git a/.cursor/rules/oclif-commands.mdc b/.cursor/rules/oclif-commands.mdc deleted file mode 100644 index 7ca9bc25ab..0000000000 --- a/.cursor/rules/oclif-commands.mdc +++ /dev/null @@ -1,352 +0,0 @@ ---- -description: 'OCLIF command development patterns and CLI best practices' -globs: ['**/commands/**/*.ts', '**/base-command.ts'] -alwaysApply: false ---- - -# OCLIF Command Standards - -## Command Structure - -### Standard Command Pattern -```typescript -// ✅ GOOD - Standard command structure -import { Command } from '@contentstack/cli-command'; -import { cliux, flags, FlagInput, handleAndLogError } from '@contentstack/cli-utilities'; - -export default class ConfigSetCommand extends Command { - static description = 'Set CLI configuration values'; - - static flags: FlagInput = { - region: flags.string({ - char: 'r', - description: 'Set region (us/eu)', - }), - alias: flags.string({ - char: 'a', - description: 'Configuration alias', - }), - }; - - static examples = [ - 'csdx config:set --region eu', - 'csdx config:set --region us --alias default', - ]; - - async run(): Promise { - try { - const { flags: configFlags } = await this.parse(ConfigSetCommand); - // Command logic here - } catch (error) { - handleAndLogError(error, { module: 'config-set' }); - } - } -} -``` - -## Base Classes - -### Command Base Class -```typescript -// ✅ GOOD - Extend Command from @contentstack/cli-command -import { Command } from '@contentstack/cli-command'; - -export default class MyCommand extends Command { - async run(): Promise { - // Command implementation - } -} -``` - -### Custom Base Classes -```typescript -// ✅ GOOD - Create custom base classes for shared functionality -export abstract class BaseCommand extends Command { - protected contextDetails = { - command: this.id || 'unknown', - }; - - async init(): Promise { - await super.init(); - log.debug('Command initialized', this.contextDetails); - } -} -``` - -## OCLIF Configuration - -### Package.json Setup -```json -{ - "oclif": { - "commands": "./lib/commands", - "bin": "csdx", - "topicSeparator": ":" - } -} -``` - -### Command Topics -- All commands use `cm` topic: `cm:config:set`, `cm:auth:login` -- Built commands live in `lib/commands` (compiled from `src/commands`) -- Commands use nested directories: `src/commands/config/set.ts` → `cm:config:set` - -### Command Naming -- **Topic hierarchy**: `config/remove/proxy.ts` → `cm:config:remove:proxy` -- **Descriptive names**: Use verb-noun pattern (`set`, `remove`, `show`) -- **Grouping**: Related commands share parent topics - -## Flag Management - -### Flag Definition Patterns -```typescript -// ✅ GOOD - Define flags clearly -static flags: FlagInput = { - 'stack-api-key': flags.string({ - char: 'k', - description: 'Stack API key', - required: false, - }), - region: flags.string({ - char: 'r', - description: 'Set region', - options: ['us', 'eu'], - }), - verbose: flags.boolean({ - char: 'v', - description: 'Show verbose output', - default: false, - }), -}; -``` - -### Flag Parsing -```typescript -// ✅ GOOD - Parse and validate flags -async run(): Promise { - const { flags: parsedFlags } = await this.parse(MyCommand); - - // Validate flag combinations - if (!parsedFlags['stack-api-key'] && !parsedFlags.alias) { - this.error('Either --stack-api-key or --alias is required'); - } - - // Use parsed flags - const region = parsedFlags.region || 'us'; -} -``` - -## Error Handling - -### Standard Error Pattern -```typescript -// ✅ GOOD - Use handleAndLogError from utilities -try { - await this.executeCommand(); -} catch (error) { - handleAndLogError(error, { module: 'my-command' }); -} -``` - -### User-Friendly Messages -```typescript -// ✅ GOOD - Clear user feedback -import { cliux } from '@contentstack/cli-utilities'; - -// Success message -cliux.success('Configuration updated successfully', { color: 'green' }); - -// Error message -cliux.error('Invalid region specified', { color: 'red' }); - -// Info message -cliux.print('Setting region to eu', { color: 'blue' }); -``` - -## Validation Patterns - -### Early Validation -```typescript -// ✅ GOOD - Validate flags early -async run(): Promise { - const { flags } = await this.parse(MyCommand); - - // Validate required flags - if (!flags.region) { - this.error('--region is required'); - } - - // Validate flag values - if (!['us', 'eu'].includes(flags.region)) { - this.error('Region must be "us" or "eu"'); - } - - // Proceed with validated input -} -``` - -## Progress and Logging - -### User Feedback -```typescript -// ✅ GOOD - Provide user feedback -import { log, cliux } from '@contentstack/cli-utilities'; - -// Regular logging -this.log('Starting configuration update...'); - -// Debug logging -log.debug('Detailed operation information', { context: 'data' }); - -// Status messages -cliux.print('Processing...', { color: 'blue' }); -``` - -### Progress Indication -```typescript -// ✅ GOOD - Show progress for long operations -cliux.print('Processing items...', { color: 'blue' }); -let count = 0; -for (const item of items) { - await this.processItem(item); - count++; - cliux.print(`Processed ${count}/${items.length} items`, { color: 'blue' }); -} -``` - -## Command Delegation - -### Service Layer Separation -```typescript -// ✅ GOOD - Commands orchestrate, services implement -async run(): Promise { - try { - const { flags } = await this.parse(MyCommand); - const config = this.buildConfig(flags); - const service = new ConfigService(config); - - await service.execute(); - cliux.success('Operation completed successfully'); - } catch (error) { - this.handleError(error); - } -} -``` - -## Testing Commands - -### OCLIF Test Support -```typescript -// ✅ GOOD - Use @oclif/test for command testing -import { test } from '@oclif/test'; - -describe('cm:config:set', () => { - test - .stdout() - .command(['cm:config:set', '--help']) - .it('shows help', ctx => { - expect(ctx.stdout).to.contain('Set CLI configuration'); - }); - - test - .stdout() - .command(['cm:config:set', '--region', 'eu']) - .it('sets region to eu', ctx => { - expect(ctx.stdout).to.contain('success'); - }); -}); -``` - -## Log Integration - -### Debug Logging -```typescript -// ✅ GOOD - Use structured debug logging -import { log } from '@contentstack/cli-utilities'; - -log.debug('Command started', { - command: this.id, - flags: this.flags, - timestamp: new Date().toISOString(), -}); - -log.debug('Processing complete', { - itemsProcessed: count, - module: 'my-command', -}); -``` - -### Error Context -```typescript -// ✅ GOOD - Include context in error handling -try { - await operation(); -} catch (error) { - handleAndLogError(error, { - module: 'config-set', - command: 'cm:config:set', - flags: { region: 'eu' }, - }); -} -``` - -## Multi-Topic Commands - -### Nested Command Structure -```typescript -// File: src/commands/config/show.ts -export default class ShowConfigCommand extends Command { - static description = 'Show current configuration'; - static examples = ['csdx config:show']; - async run(): Promise { } -} - -// File: src/commands/config/set.ts -export default class SetConfigCommand extends Command { - static description = 'Set configuration values'; - static examples = ['csdx config:set --region eu']; - async run(): Promise { } -} - -// Generated commands: -// - cm:config:show -// - cm:config:set -``` - -## Best Practices - -### Command Organization -```typescript -// ✅ GOOD - Well-organized command -export default class MyCommand extends Command { - static description = 'Clear, concise description'; - - static flags: FlagInput = { - // Define all flags - }; - - static examples = [ - 'csdx my:command', - 'csdx my:command --flag value', - ]; - - async run(): Promise { - try { - const { flags } = await this.parse(MyCommand); - await this.execute(flags); - } catch (error) { - handleAndLogError(error, { module: 'my-command' }); - } - } - - private async execute(flags: Flags): Promise { - // Implementation - } -} -``` - -### Clear Help Text -- Write description as action-oriented statement -- Provide multiple examples for common use cases -- Document each flag with clear description -- Show output format or examples of results diff --git a/.cursor/rules/testing.mdc b/.cursor/rules/testing.mdc deleted file mode 100644 index daf6de1089..0000000000 --- a/.cursor/rules/testing.mdc +++ /dev/null @@ -1,323 +0,0 @@ ---- -description: 'Testing patterns and TDD workflow' -globs: ['**/test/**/*.ts', '**/test/**/*.js', '**/__tests__/**/*.ts', '**/*.spec.ts', '**/*.test.ts'] -alwaysApply: true ---- - -# Testing Standards - -## Framework Stack - -### Primary Testing Tools -- **Mocha** - Test runner (used across all packages) -- **Chai** - Assertion library -- **@oclif/test** - Command testing support (for plugin packages) - -### Test Setup -- TypeScript compilation via ts-node/register -- Source map support for stack traces -- Global test timeout: 30 seconds (configurable per package) - -## Test File Patterns - -### Naming Conventions -- **Primary**: `*.test.ts` (standard pattern across all packages) -- **Location**: `test/unit/**/*.test.ts` (most packages) - -### Directory Structure -``` -packages/*/ -├── test/ -│ └── unit/ -│ ├── commands/ # Command-specific tests -│ ├── services/ # Service/business logic tests -│ └── utils/ # Utility function tests -└── src/ # Source code - ├── commands/ # CLI commands - ├── services/ # Business logic - └── utils/ # Utilities -``` - -## Mocha Configuration - -### Standard Setup (.mocharc.json) -```json -{ - "require": [ - "test/helpers/init.js", - "ts-node/register", - "source-map-support/register" - ], - "recursive": true, - "timeout": 30000, - "spec": "test/**/*.test.ts" -} -``` - -### TypeScript Compilation -```json -// package.json scripts -{ - "test": "mocha \"test/unit/**/*.test.ts\"", - "test:coverage": "nyc mocha \"test/unit/**/*.test.ts\"" -} -``` - -## Test Structure - -### Standard Test Pattern -```typescript -// ✅ GOOD - Comprehensive test structure -describe('ConfigService', () => { - let service: ConfigService; - - beforeEach(() => { - service = new ConfigService(); - }); - - describe('loadConfig()', () => { - it('should load configuration successfully', async () => { - // Arrange - const expectedConfig = { region: 'us' }; - - // Act - const result = await service.loadConfig(); - - // Assert - expect(result).to.deep.equal(expectedConfig); - }); - - it('should handle missing configuration', async () => { - // Arrange & Act & Assert - await expect(service.loadConfig()).to.be.rejectedWith('Config not found'); - }); - }); -}); -``` - -### Async/Await Pattern -```typescript -// ✅ GOOD - Use async/await in tests -it('should process data asynchronously', async () => { - const result = await service.processAsync(); - expect(result).to.exist; -}); - -// ✅ GOOD - Explicit Promise handling -it('should return a promise', () => { - return service.asyncMethod().then(result => { - expect(result).to.be.true; - }); -}); -``` - -## Mocking Patterns - -### Class Mocking -```typescript -// ✅ GOOD - Mock class dependencies -class MockConfigService { - async loadConfig() { - return { region: 'us' }; - } -} - -it('should use mocked service', async () => { - const mockService = new MockConfigService(); - const result = await mockService.loadConfig(); - expect(result.region).to.equal('us'); -}); -``` - -### Function Stubs -```typescript -// ✅ GOOD - Stub module functions if needed -beforeEach(() => { - // Stub file system operations - // Stub network calls -}); - -afterEach(() => { - // Restore original implementations -}); -``` - -## Command Testing - -### OCLIF Test Pattern -```typescript -// ✅ GOOD - Test commands with @oclif/test -import { test } from '@oclif/test'; - -describe('cm:config:region', () => { - test - .stdout() - .command(['cm:config:region', '--help']) - .it('shows help message', ctx => { - expect(ctx.stdout).to.contain('Display region'); - }); - - test - .stdout() - .command(['cm:config:region']) - .it('shows current region', ctx => { - expect(ctx.stdout).to.contain('us'); - }); -}); -``` - -### Command Flag Testing -```typescript -// ✅ GOOD - Test command flags and arguments -describe('cm:config:set', () => { - test - .command(['cm:config:set', '--help']) - .it('shows usage information'); - - test - .command(['cm:config:set', '--region', 'eu']) - .it('sets region to eu'); -}); -``` - -## Error Testing - -### Error Handling -```typescript -// ✅ GOOD - Test error scenarios -it('should throw ValidationError on invalid input', async () => { - const invalidInput = ''; - await expect(service.validate(invalidInput)) - .to.be.rejectedWith('Invalid input'); -}); - -it('should handle network errors gracefully', async () => { - // Mock network failure - const result = await service.fetchWithRetry(); - expect(result).to.be.null; -}); -``` - -### Error Types -```typescript -// ✅ GOOD - Test specific error types -it('should throw appropriate error', async () => { - try { - await service.failingOperation(); - } catch (error) { - expect(error).to.be.instanceof(ValidationError); - expect(error.code).to.equal('INVALID_CONFIG'); - } -}); -``` - -## Test Data Management - -### Mock Data Organization -```typescript -// ✅ GOOD - Organize test data -const mockData = { - validConfig: { - region: 'us', - timeout: 30000, - }, - invalidConfig: { - region: '', - }, - users: [ - { email: 'user1@example.com', name: 'User 1' }, - { email: 'user2@example.com', name: 'User 2' }, - ], -}; -``` - -### Test Helpers -```typescript -// ✅ GOOD - Create reusable test utilities -export function createMockConfig(overrides?: Partial): Config { - return { - region: 'us', - timeout: 30000, - ...overrides, - }; -} - -export function createMockService( - config: Config = createMockConfig() -): ConfigService { - return new ConfigService(config); -} -``` - -## Coverage - -### Coverage Goals -- **Team aspiration**: 80% minimum coverage -- **Current enforcement**: Applied consistently across packages -- **Focus areas**: Critical business logic and error paths - -### Coverage Reporting -```bash -# Run tests with coverage -pnpm test:coverage - -# Coverage reports generated in: -# - coverage/index.html (HTML report) -# - coverage/coverage-summary.json (JSON report) -``` - -## Critical Testing Rules - -- **No real external calls** - Mock all dependencies -- **Test both success and failure paths** - Cover error scenarios completely -- **One assertion per test** - Focus each test on single behavior -- **Use descriptive test names** - Test name should explain what's tested -- **Arrange-Act-Assert** - Follow AAA pattern consistently -- **Test command validation** - Verify flag validation and error messages -- **Clean up after tests** - Restore any mocked state - -## Best Practices - -### Test Organization -```typescript -// ✅ GOOD - Organize related tests -describe('AuthCommand', () => { - describe('login', () => { - it('should authenticate user'); - it('should save token'); - }); - - describe('logout', () => { - it('should clear token'); - it('should reset config'); - }); -}); -``` - -### Async Test Patterns -```typescript -// ✅ GOOD - Handle async operations properly -it('should complete async operation', async () => { - const promise = service.asyncMethod(); - expect(promise).to.be.instanceof(Promise); - - const result = await promise; - expect(result).to.equal('success'); -}); -``` - -### Isolation -```typescript -// ✅ GOOD - Ensure test isolation -describe('ConfigService', () => { - let service: ConfigService; - - beforeEach(() => { - service = new ConfigService(); - }); - - afterEach(() => { - // Clean up resources - }); -}); -``` diff --git a/.cursor/rules/typescript.mdc b/.cursor/rules/typescript.mdc deleted file mode 100644 index ea4d82a265..0000000000 --- a/.cursor/rules/typescript.mdc +++ /dev/null @@ -1,246 +0,0 @@ ---- -description: 'TypeScript strict mode standards and naming conventions' -globs: ['**/*.ts', '**/*.tsx'] -alwaysApply: false ---- - -# TypeScript Standards - -## Configuration - -### Standard Configuration (All Packages) -```json -{ - "compilerOptions": { - "declaration": true, - "importHelpers": true, - "module": "commonjs", - "outDir": "lib", - "rootDir": "src", - "strict": false, // Relaxed for compatibility - "target": "es2017", - "sourceMap": false, - "allowJs": true, // Mixed JS/TS support - "skipLibCheck": true, - "esModuleInterop": true - }, - "include": ["src/**/*"] -} -``` - -### Root Configuration -```json -// tsconfig.json - Baseline configuration -{ - "compilerOptions": { - "strict": false, - "module": "commonjs", - "target": "es2017", - "declaration": true, - "outDir": "lib", - "rootDir": "src" - } -} -``` - -## Naming Conventions (Actual Usage) - -### Files -- **Primary pattern**: `kebab-case.ts` (e.g., `base-command.ts`, `config-handler.ts`) -- **Single-word modules**: `index.ts`, `types.ts` -- **Commands**: Follow OCLIF topic structure (`cm/auth/login.ts`, `cm/config/region.ts`) - -### Classes -```typescript -// ✅ GOOD - PascalCase for classes -export default class ConfigCommand extends Command { } -export class AuthService { } -export class ValidationError extends Error { } -``` - -### Functions and Methods -```typescript -// ✅ GOOD - camelCase for functions -export async function loadConfig(): Promise { } -async validateInput(input: string): Promise { } -createCommandContext(): CommandContext { } -``` - -### Constants -```typescript -// ✅ GOOD - SCREAMING_SNAKE_CASE for constants -const DEFAULT_REGION = 'us'; -const MAX_RETRIES = 3; -const API_BASE_URL = 'https://api.contentstack.io'; -``` - -### Interfaces and Types -```typescript -// ✅ GOOD - PascalCase for types -export interface CommandConfig { - region: string; - alias?: string; -} - -export type CommandResult = { - success: boolean; - message?: string; -}; -``` - -## Import/Export Patterns - -### ES Modules (Preferred) -```typescript -// ✅ GOOD - ES import/export syntax -import { Command } from '@oclif/core'; -import type { CommandConfig } from '../types'; -import { loadConfig } from '../utils'; - -export default class ConfigCommand extends Command { } -export { CommandConfig }; -``` - -### Default Exports -```typescript -// ✅ GOOD - Default export for commands and main classes -export default class ConfigCommand extends Command { } -``` - -### Named Exports -```typescript -// ✅ GOOD - Named exports for utilities and types -export async function delay(ms: number): Promise { } -export interface CommandOptions { } -export type ActionResult = 'success' | 'failure'; -``` - -## Type Definitions - -### Local Types -```typescript -// ✅ GOOD - Define types close to usage -export interface AuthOptions { - email: string; - password: string; - token?: string; -} - -export type ConfigResult = { - success: boolean; - config?: Record; -}; -``` - -### Type Organization -```typescript -// ✅ GOOD - Organize types in dedicated files -// src/types/index.ts -export interface CommandConfig { } -export interface AuthConfig { } -export type ConfigValue = string | number | boolean; -``` - -## Null Safety - -### Function Return Types -```typescript -// ✅ GOOD - Explicit return types -export async function getConfig(): Promise { - return await this.loadFromFile(); -} - -export function createDefaults(): CommandConfig { - return { - region: 'us', - timeout: 30000, - }; -} -``` - -### Null/Undefined Handling -```typescript -// ✅ GOOD - Handle null/undefined explicitly -function processConfig(config: CommandConfig | null): void { - if (!config) { - throw new Error('Configuration is required'); - } - // Process config safely -} -``` - -## Error Handling Types - -### Custom Error Classes -```typescript -// ✅ GOOD - Typed error classes -export class ValidationError extends Error { - constructor( - message: string, - public readonly code?: string - ) { - super(message); - this.name = 'ValidationError'; - } -} -``` - -### Error Union Types -```typescript -// ✅ GOOD - Model expected errors -type AuthResult = { - success: true; - data: T; -} | { - success: false; - error: string; -}; -``` - -## Strict Mode Adoption - -### Current Status -- Most packages use `strict: false` for compatibility -- Gradual migration path available -- Team working toward stricter TypeScript - -### Gradual Adoption -```typescript -// ✅ ACCEPTABLE - Comments for known issues -// TODO: Fix type issues in legacy code -const legacyData = unknownData as unknown; -``` - -## Package-Specific Patterns - -### Command Packages (auth, config) -- Extend `@oclif/core` Command -- Define command flags with `static flags` -- Use @oclif/core flag utilities -- Define command-specific types - -### Library Packages (command, utilities) -- No OCLIF dependencies -- Pure TypeScript interfaces -- Consumed by command packages -- Focus on type safety for exports - -### Main Package (contentstack) -- Aggregates command plugins -- May have common types -- Shared interfaces for plugin integration - -## Export Patterns - -### Package Exports (lib/index.js) -```typescript -// ✅ GOOD - Barrel exports for libraries -export { Command } from './command'; -export { loadConfig } from './config'; -export type { CommandConfig, AuthOptions } from './types'; -``` - -### Entry Points -- Libraries export from `lib/index.js` -- Commands export directly as default classes -- Type definitions included via `types` field in package.json diff --git a/.cursor/skills/SKILL.md b/.cursor/skills/SKILL.md deleted file mode 100644 index 422807ad04..0000000000 --- a/.cursor/skills/SKILL.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: contentstack-cli-skills -description: Collection of project-specific skills for Contentstack CLI monorepo development. Use when working with CLI commands, testing, framework utilities, or reviewing code changes. ---- - -# Contentstack CLI Skills - -Project-specific skills for the pnpm monorepo containing 6 CLI packages. - -## Skills Overview - -| Skill | Purpose | Trigger | -|-------|---------|---------| -| **testing** | Testing patterns, TDD workflow, and test automation for CLI development | When writing tests or debugging test failures | -| **framework** | Core utilities, configuration, logging, and framework patterns | When working with utilities, config, or error handling | -| **contentstack-cli** | CLI commands, OCLIF patterns, authentication and configuration workflows | When implementing commands or integrating APIs | -| **code-review** | PR review guidelines and monorepo-aware checks | When reviewing code or pull requests | - -## Quick Links - -- **[Testing Skill](./testing/SKILL.md)** — TDD patterns, test structure, mocking strategies -- **[Framework Skill](./framework/SKILL.md)** — Utilities, configuration, logging, error handling -- **[Contentstack CLI Skill](./contentstack-cli/SKILL.md)** — Command development, API integration, auth/config patterns -- **[Code Review Skill](./code-review/SKILL.md)** — Review checklist with monorepo awareness - -## Repository Context - -- **Monorepo**: 6 pnpm workspace packages under `packages/` -- **Tech Stack**: TypeScript, OCLIF v4, Mocha+Chai, pnpm workspaces -- **Packages**: `@contentstack/cli` (main), `@contentstack/cli-auth`, `@contentstack/cli-config`, `@contentstack/cli-command`, `@contentstack/cli-utilities`, `@contentstack/cli-dev-dependencies` -- **Build**: TypeScript → `lib/` directories, OCLIF manifest generation diff --git a/.cursor/skills/code-review/SKILL.md b/.cursor/skills/code-review/SKILL.md deleted file mode 100644 index bc647259c0..0000000000 --- a/.cursor/skills/code-review/SKILL.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -name: code-review -description: Automated PR review checklist covering security, performance, architecture, and code quality. Use when reviewing pull requests, examining code changes, or performing code quality assessments. ---- - -# Code Review Skill - -## Quick Reference - -For comprehensive review guidelines, see: -- **[Code Review Checklist](./references/code-review-checklist.md)** - Complete PR review guidelines with severity levels and checklists - -## Review Process - -### Severity Levels -- 🔴 **Critical**: Must fix before merge (security, correctness, breaking changes) -- 🟡 **Important**: Should fix (performance, maintainability, best practices) -- 🟢 **Suggestion**: Consider improving (style, optimization, readability) - -### Quick Review Categories - -1. **Security** - No hardcoded secrets, input validation, secure error handling -2. **Correctness** - Logic validation, error scenarios, data integrity -3. **Architecture** - Code organization, design patterns, modularity -4. **Performance** - Efficiency, resource management, concurrency -5. **Testing** - Test coverage, quality tests, TDD compliance -6. **Conventions** - TypeScript standards, code style, documentation -7. **Monorepo** - Cross-package imports, workspace dependencies, manifest validity - -## Quick Checklist Template - -```markdown -## Security Review -- [ ] No hardcoded secrets or tokens -- [ ] Input validation present -- [ ] Error handling secure (no sensitive data in logs) - -## Correctness Review -- [ ] Logic correctly implemented -- [ ] Edge cases handled -- [ ] Error scenarios covered -- [ ] Async/await chains correct - -## Architecture Review -- [ ] Proper code organization -- [ ] Design patterns followed -- [ ] Good modularity -- [ ] No circular dependencies - -## Performance Review -- [ ] Efficient implementation -- [ ] No unnecessary API calls -- [ ] Memory leaks avoided -- [ ] Concurrency handled correctly - -## Testing Review -- [ ] Adequate test coverage (80%+) -- [ ] Quality tests (not just passing) -- [ ] TDD compliance -- [ ] Both success and failure paths tested - -## Code Conventions -- [ ] TypeScript strict mode -- [ ] Consistent naming conventions -- [ ] No unused imports or variables -- [ ] Documentation adequate - -## Monorepo Checks -- [ ] Cross-package imports use published names -- [ ] Workspace dependencies declared correctly -- [ ] OCLIF manifest updated if commands changed -- [ ] No breaking changes to exported APIs -``` - -## Usage - -Use the comprehensive checklist guide for detailed review guidelines, common issues, severity assessment, and best practices for code quality in the Contentstack CLI monorepo. diff --git a/.cursor/skills/contentstack-cli/SKILL.md b/.cursor/skills/contentstack-cli/SKILL.md deleted file mode 100644 index f5a29a9a3b..0000000000 --- a/.cursor/skills/contentstack-cli/SKILL.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -name: contentstack-cli -description: Contentstack CLI development patterns, OCLIF commands, API integration, and authentication/configuration workflows. Use when working with Contentstack CLI plugins, OCLIF commands, CLI commands, or Contentstack API integration. ---- - -# Contentstack CLI Development - -## Quick Reference - -For comprehensive patterns, see: -- **[Contentstack Patterns](./references/contentstack-patterns.md)** - Complete CLI commands, API integration, and configuration patterns -- **[Framework Patterns](../framework/references/framework-patterns.md)** - Utilities, configuration, and error handling - -## Key Patterns Summary - -### OCLIF Command Structure -- Extend `BaseCommand` (package-level) or `Command` from `@contentstack/cli-command` -- Validate flags early: `if (!flags.region) this.error('Region is required')` -- Delegate to services/utils: commands handle CLI, utilities handle logic -- Show progress: `cliux.success('✅ Operation completed')` -- Include command examples: `static examples = ['$ csdx auth:login', '$ csdx auth:login -u email@example.com']` - -### Command Topics -- Auth commands: `auth:login`, `auth:logout`, `auth:whoami`, `auth:tokens:add`, `auth:tokens:remove`, `auth:tokens:index` -- Config commands: `config:get:region`, `config:set:region`, `config:remove:proxy`, etc. -- File pattern: `src/commands/auth/login.ts` → command `cm:auth:login` - -### Flag Patterns -```typescript -static flags: FlagInput = { - username: flags.string({ - char: 'u', - description: 'Email address', - required: false - }), - oauth: flags.boolean({ - description: 'Enable SSO', - default: false, - exclusive: ['username', 'password'] - }) -}; -``` - -### Logging and Error Handling -- Use structured logging: `log.debug('Message', { context: 'data' })` -- Include contextDetails: `handleAndLogError(error, { ...this.contextDetails, module: 'auth-login' })` -- User feedback: `cliux.success()`, `cliux.error()`, `throw new CLIError()` - -### I18N Messages -- Store user-facing strings in `messages/*.json` files -- Load with `messageHandler` from utilities -- Example: `messages/en.json` for English strings - -## Command Base Class Pattern - -```typescript -export abstract class BaseCommand extends Command { - protected contextDetails!: Context; - - async init(): Promise { - await super.init(); - this.contextDetails = { - command: this.context?.info?.command || 'unknown', - userId: configHandler.get('userUid'), - email: configHandler.get('email') - }; - } - - protected async catch(err: Error & { exitCode?: number }): Promise { - return super.catch(err); - } -} -``` - -## Authentication Patterns - -### Login Command Example -```typescript -async run(): Promise { - const { flags: loginFlags } = await this.parse(LoginCommand); - - if (loginFlags.oauth) { - await oauthHandler.oauth(); - } else { - const username = loginFlags.username || await interactive.askUsername(); - const password = loginFlags.password || await interactive.askPassword(); - await authHandler.login(username, password); - } - - cliux.success('✅ Authenticated successfully'); -} -``` - -### Check Authentication -```typescript -if (!configHandler.get('authenticationMethod')) { - throw new CLIError('Authentication required. Please login first.'); -} -``` - -## Configuration Patterns - -### Config Set/Get/Remove Commands -- Use `configHandler.get()` and `configHandler.set()` -- Support interactive mode when no flags provided -- Display results with `cliux.success()` or `cliux.print()` - -### Region Configuration -```typescript -const selectedRegion = args.region || await interactive.askRegions(); -const regionDetails = regionHandler.setRegion(selectedRegion); -cliux.success(`Region set to ${regionDetails.name}`); -cliux.success(`CMA host: ${regionDetails.cma}`); -``` - -## API Integration - -### Management SDK Client -```typescript -import { managementSDKClient } from '@contentstack/cli-utilities'; - -const client = await managementSDKClient({ - host: this.cmaHost, - skipTokenValidity: true -}); - -const stack = client.stack({ api_key: stackApiKey }); -const entries = await stack.entry().query().find(); -``` - -### Error Handling for API Calls -```typescript -try { - const result = await this.client.stack().entry().fetch(); -} catch (error) { - if (error.status === 401) { - throw new CLIError('Authentication failed. Please login again.'); - } else if (error.status === 404) { - throw new CLIError('Entry not found.'); - } - handleAndLogError(error, { - module: 'entry-fetch', - entryId: entryUid - }); -} -``` - -## Usage - -Reference the comprehensive patterns guide above for detailed implementations, examples, and best practices for CLI command development, authentication flows, configuration management, and API integration. diff --git a/.cursor/skills/framework/SKILL.md b/.cursor/skills/framework/SKILL.md deleted file mode 100644 index 80be284d90..0000000000 --- a/.cursor/skills/framework/SKILL.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -name: framework -description: Core utilities, configuration, logging, and framework patterns for CLI development. Use when working with utilities, configuration management, error handling, or core framework components. ---- - -# Framework Patterns - -## Quick Reference - -For comprehensive framework guidance, see: -- **[Framework Patterns](./references/framework-patterns.md)** - Complete utilities, configuration, logging, and framework patterns - -## Core Utilities from @contentstack/cli-utilities - -### Configuration Management -```typescript -import { configHandler } from '@contentstack/cli-utilities'; - -// Get config values -const region = configHandler.get('region'); -const email = configHandler.get('email'); -const authToken = configHandler.get('authenticationMethod'); - -// Set config values -configHandler.set('region', 'us'); -``` - -### Logging Framework -```typescript -import { log } from '@contentstack/cli-utilities'; - -// Use structured logging -log.debug('Debug message', { context: 'data' }); -log.info('Information message', { userId: '123' }); -log.warn('Warning message'); -log.error('Error message', { errorCode: 'ERR_001' }); -``` - -### Error Handling -```typescript -import { handleAndLogError, CLIError } from '@contentstack/cli-utilities'; - -try { - await operation(); -} catch (error) { - handleAndLogError(error, { - module: 'my-command', - command: 'cm:auth:login' - }); -} - -// Or throw CLI errors -throw new CLIError('User-friendly error message'); -``` - -### CLI UX / User Output -```typescript -import { cliux } from '@contentstack/cli-utilities'; - -// Success message -cliux.success('Operation completed successfully'); - -// Error message -cliux.error('Something went wrong'); - -// Print message with color -cliux.print('Processing...', { color: 'blue' }); - -// Prompt user for input -const response = await cliux.prompt('Enter region:'); - -// Show table -cliux.table([ - { name: 'Alice', region: 'us' }, - { name: 'Bob', region: 'eu' } -]); -``` - -### HTTP Client -```typescript -import { httpClient } from '@contentstack/cli-utilities'; - -// Make HTTP requests with built-in error handling -const response = await httpClient.request({ - url: 'https://api.contentstack.io/v3/stacks', - method: 'GET', - headers: { 'Authorization': `Bearer ${token}` } -}); -``` - -## Command Base Class - -```typescript -import { Command } from '@contentstack/cli-command'; - -export default class MyCommand extends Command { - static description = 'My command description'; - - static flags = { - region: flags.string({ - char: 'r', - description: 'Set region' - }) - }; - - async run(): Promise { - const { flags } = await this.parse(MyCommand); - // Command logic here - } -} -``` - -## Error Handling Patterns - -### With Context -```typescript -try { - const result = await this.client.stack().entry().fetch(); -} catch (error) { - handleAndLogError(error, { - module: 'auth-service', - command: 'cm:auth:login', - userId: this.contextDetails.userId, - email: this.contextDetails.email - }); -} -``` - -### Custom Errors -```typescript -if (response.status === 401) { - throw new CLIError('Authentication failed. Please login again.'); -} - -if (response.status === 429) { - throw new CLIError('Rate limited. Please try again later.'); -} -``` - -## Usage - -Reference the comprehensive patterns guide above for detailed implementations of configuration, logging, error handling, utilities, and dependency injection patterns. diff --git a/.cursor/skills/testing/SKILL.md b/.cursor/skills/testing/SKILL.md deleted file mode 100644 index d53591924e..0000000000 --- a/.cursor/skills/testing/SKILL.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -name: testing -description: Testing patterns, TDD workflow, and test automation for CLI development. Use when writing tests, implementing TDD, setting up test coverage, or debugging test failures. ---- - -# Testing Patterns - -## Quick Reference - -For comprehensive testing guidance, see: -- **[Testing Patterns](./references/testing-patterns.md)** - Complete testing best practices and TDD workflow -- See also `.cursor/rules/testing.mdc` for workspace-wide testing standards - -## TDD Workflow Summary - -**Simple RED-GREEN-REFACTOR:** -1. **RED** → Write failing test -2. **GREEN** → Make it pass with minimal code -3. **REFACTOR** → Improve code quality while keeping tests green - -## Key Testing Rules - -- **80% minimum coverage** (lines, branches, functions) -- **Class-based mocking** (no external libraries; extend and override methods) -- **Never make real API calls** in tests -- **Mock at service boundaries**, not implementation details -- **Test both success and failure paths** -- **Use descriptive test names**: "should [behavior] when [condition]" - -## Quick Test Template - -```typescript -describe('[ServiceName]', () => { - let service: [ServiceName]; - - beforeEach(() => { - service = new [ServiceName](); - }); - - afterEach(() => { - // Clean up any resources - }); - - it('should [expected behavior] when [condition]', async () => { - // Arrange - const input = { /* test data */ }; - - // Act - const result = await service.method(input); - - // Assert - expect(result).to.deep.equal(expectedOutput); - }); - - it('should throw error when [error condition]', async () => { - // Arrange & Act & Assert - await expect(service.failingMethod()) - .to.be.rejectedWith('Expected error message'); - }); -}); -``` - -## Common Mock Patterns - -### Class-Based Mocking -```typescript -// Mock a service by extending it -class MockContentstackClient extends ContentstackClient { - async fetch() { - return mockData; - } -} - -it('should use mocked client', async () => { - const mockClient = new MockContentstackClient(config); - const result = await mockClient.fetch(); - expect(result).to.deep.equal(mockData); -}); -``` - -### Constructor Injection -```typescript -class RateLimiter { - async execute(operation: () => Promise): Promise { - return operation(); - } -} - -class MyService { - constructor(private rateLimiter: RateLimiter) {} - - async doWork() { - return this.rateLimiter.execute(() => this.performWork()); - } -} - -it('should rate limit operations', () => { - const mockLimiter = { execute: () => Promise.resolve('result') }; - const service = new MyService(mockLimiter as any); - // test service behavior -}); -``` - -## Running Tests - -### Run all tests in workspace -```bash -pnpm test -``` - -### Run tests for specific package -```bash -pnpm --filter @contentstack/cli-auth test -pnpm --filter @contentstack/cli-config test -``` - -### Run tests with coverage -```bash -pnpm test:coverage -``` - -### Run tests in watch mode -```bash -pnpm test:watch -``` - -### Run specific test file -```bash -pnpm test -- test/unit/commands/auth/login.test.ts -``` - -## Test Organization - -### File Structure -- Mirror source structure: `test/unit/commands/auth/`, `test/unit/services/`, `test/unit/utils/` -- Use consistent naming: `[module-name].test.ts` -- Integration tests: `test/integration/` - -### Test Data Management -```typescript -// Create mock data factories in test/fixtures/ -const mockAuthToken = { token: 'abc123', expiresAt: Date.now() + 3600000 }; -const mockConfig = { region: 'us', email: 'test@example.com' }; -``` - -## Error Testing - -### Rate Limit Handling -```typescript -it('should handle rate limit errors', async () => { - const error = new Error('Rate limited'); - (error as any).status = 429; - - class MockClient { - fetch() { throw error; } - } - - try { - await new MockClient().fetch(); - expect.fail('Should have thrown'); - } catch (err: any) { - expect(err.status).to.equal(429); - } -}); -``` - -### Validation Error Testing -```typescript -it('should throw validation error for invalid input', () => { - expect(() => service.validateRegion('')) - .to.throw('Region is required'); -}); -``` - -## Coverage and Quality - -### Coverage Requirements -```json -"nyc": { - "check-coverage": true, - "lines": 80, - "functions": 80, - "branches": 80, - "statements": 80 -} -``` - -### Quality Checklist -- [ ] All public methods tested -- [ ] Error paths covered (success + failure) -- [ ] Edge cases included -- [ ] No real API calls -- [ ] Descriptive test names -- [ ] Minimal test setup -- [ ] Tests run < 5s per test file -- [ ] 80%+ coverage achieved - -## Usage - -Reference the comprehensive patterns guide above for detailed test structures, mocking strategies, error testing patterns, and coverage requirements. diff --git a/.github/config/release.json b/.github/config/release.json index 078a8824bf..db275fed62 100755 --- a/.github/config/release.json +++ b/.github/config/release.json @@ -5,18 +5,7 @@ "command": false, "config": false, "auth": false, - "export": false, - "import": false, - "clone": false, - "export-to-csv": false, - "migrate-rte": false, - "migration": false, - "seed": false, - "bootstrap": false, - "bulk-publish": false, "dev-dependencies": false, - "launch": false, - "branches": false, "core": false } } diff --git a/.github/workflows/release-production-pipeline.yml b/.github/workflows/release-production-pipeline.yml deleted file mode 100644 index a6914a3191..0000000000 --- a/.github/workflows/release-production-pipeline.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: CLI Production Release Pipeline - -on: - push: - branches: [main] - workflow_dispatch: # This enables manual triggering - -jobs: - plugins: - uses: ./.github/workflows/release-production-platform-plugins.yml - secrets: inherit - - core: - needs: plugins - uses: ./.github/workflows/release-production-core.yml - secrets: inherit diff --git a/.github/workflows/release-production-core.yml b/.github/workflows/release-v2-beta-core.yml similarity index 85% rename from .github/workflows/release-production-core.yml rename to .github/workflows/release-v2-beta-core.yml index e6e45eeb15..a6e0739603 100644 --- a/.github/workflows/release-production-core.yml +++ b/.github/workflows/release-v2-beta-core.yml @@ -1,4 +1,4 @@ -name: Release CLI Core (Production) +name: Release CLI Core (v2 Beta) on: workflow_call: @@ -37,15 +37,15 @@ jobs: filename: .github/config/release.json prefix: release - - name: Publishing core (Production) + - name: Publishing core (Beta) id: publish-core uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} package: ./packages/contentstack/package.json - tag: latest + tag: beta - - name: Create Core Production Release + - name: Create Core Beta Release id: create_release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -56,6 +56,7 @@ jobs: echo "Release $TAG already exists — skipping." else gh release create "$TAG" \ - --title "Core Production $VERSION" \ - --generate-notes + --title "Core Beta $VERSION" \ + --generate-notes \ + --prerelease fi diff --git a/.github/workflows/release-production-platform-plugins.yml b/.github/workflows/release-v2-beta-platform-plugins.yml similarity index 83% rename from .github/workflows/release-production-platform-plugins.yml rename to .github/workflows/release-v2-beta-platform-plugins.yml index 060a9f07d6..38b42b535b 100644 --- a/.github/workflows/release-production-platform-plugins.yml +++ b/.github/workflows/release-v2-beta-platform-plugins.yml @@ -1,4 +1,4 @@ -name: Release CLI Platform Plugins +name: Release CLI Platform Plugins (v2 Beta) on: workflow_call: @@ -38,33 +38,33 @@ jobs: prefix: release # Utilities - - name: Publishing utilities (Production) + - name: Publishing utilities (Beta) uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} package: ./packages/contentstack-utilities/package.json - tag: latest + tag: beta # Command - - name: Publishing command (Production) + - name: Publishing command (Beta) uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} package: ./packages/contentstack-command/package.json - tag: latest + tag: beta # Config - - name: Publishing config (Production) + - name: Publishing config (Beta) uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} package: ./packages/contentstack-config/package.json - tag: latest + tag: beta # Auth - - name: Publishing auth (Production) + - name: Publishing auth (Beta) uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} package: ./packages/contentstack-auth/package.json - tag: latest + tag: beta diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100755 index 0000000000..91a18956d8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,15 @@ +name: CLI Release Pipeline + +on: + push: + branches: [v2-beta] + +jobs: + plugins: + uses: ./.github/workflows/release-v2-beta-platform-plugins.yml + secrets: inherit + + core: + needs: plugins + uses: ./.github/workflows/release-v2-beta-core.yml + secrets: inherit diff --git a/.github/workflows/sca-scan.yml b/.github/workflows/sca-scan.yml index 2307d48902..639dd865c4 100644 --- a/.github/workflows/sca-scan.yml +++ b/.github/workflows/sca-scan.yml @@ -12,7 +12,7 @@ jobs: env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} with: - args: --all-projects --fail-on=all + args: --fail-on=all --all-projects json: true continue-on-error: true - uses: contentstack/sca-policy@main diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index 801e352ddb..c765444307 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -30,6 +30,7 @@ jobs: - name: Test contentstack-auth working-directory: ./packages/contentstack-auth run: pnpm test + # Commented out in v2-beta production - name: Test contentstack-utilities working-directory: ./packages/contentstack-utilities run: pnpm test diff --git a/.gitignore b/.gitignore index 9dcc968270..0e1ca7354a 100644 --- a/.gitignore +++ b/.gitignore @@ -21,4 +21,9 @@ contents-* *.todo talisman_output.log snyk_output.log -*.logs \ No newline at end of file +# Snyk Security Extension - AI Rules (auto-generated) +.cursor/rules/snyk_rules.mdc +**/migration-logs +**/migration-logs/** +*.logs +tsconfig.tsbuildinfo \ No newline at end of file diff --git a/.talismanrc b/.talismanrc index bedb52350d..8617ff4562 100644 --- a/.talismanrc +++ b/.talismanrc @@ -1,4 +1,8 @@ fileignoreconfig: - filename: pnpm-lock.yaml - checksum: ba838353c1277083cb35b5f69cbbe00f0dc5d7d69e49b44c71c3a7a79e95ee73 + checksum: 117b66122d3f3043f48724ff9755ec2d4a9dff3c156ceedef753df3014cafee6 + - filename: packages/contentstack/src/hooks/init/opt-in-plugin-guide.ts + checksum: 2b079a93988e2439a03c401f75695fcdbfeb138a75c84707e4bc892536680e9f + - filename: MIGRATION.md + checksum: 1f60cc104771b74b43bf1ed107606d2a54264687a0a5e4b229cda813b829dc45 version: '1.0' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..d44ff540c9 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,45 @@ +# Contentstack CLI – Agent guide + +**Universal entry point** for contributors and AI agents. Detailed conventions live in **`skills/*/SKILL.md`**. + +## What this repo is + +| Field | Detail | +| --- | --- | +| **Name:** | Contentstack CLI (pnpm monorepo; root package name `csdx`) | +| **Purpose:** | Command-line tool and plugins to manage Contentstack stacks (auth, import/export, bulk operations, and related workflows). | +| **Out of scope (if any):** | Individual plugin packages may scope their own features; see each package under `packages/`. | + +## Tech stack (at a glance) + +| Area | Details | +| --- | --- | +| **Language** | TypeScript / JavaScript, Node **>= 18** (`engines` in root `package.json`) | +| **Build** | pnpm workspaces (`packages/*`); per package: `tsc`, OCLIF manifest/readme where applicable → `lib/` | +| **Tests** | Mocha + Chai; patterns under `packages/*/test/` (see [skills/testing/SKILL.md](skills/testing/SKILL.md)) | +| **Lint / coverage** | ESLint per package (`src/**/*.ts`); nyc where configured for coverage | +| **Other** | OCLIF v4, Husky | + +## Commands (quick reference) + +| Command type | Command | +| --- | --- | +| **Build** | `pnpm build` | +| **Test** | `pnpm test` | +| **Lint** | `pnpm lint` | + +CI: [.github/workflows/unit-test.yml](.github/workflows/unit-test.yml), [.github/workflows/lint.yml](.github/workflows/lint.yml), and other workflows under [.github/workflows/](.github/workflows/). + +## Where the documentation lives: skills + +| Skill | Path | What it covers | +| --- | --- | --- | +| Development workflow | [skills/dev-workflow/SKILL.md](skills/dev-workflow/SKILL.md) | pnpm workspace commands, CI, TDD expectations, PR checklist | +| Contentstack CLI | [skills/contentstack-cli/SKILL.md](skills/contentstack-cli/SKILL.md) | OCLIF commands, plugins, integration patterns | +| Framework | [skills/framework/SKILL.md](skills/framework/SKILL.md) | Utilities, config, logging, errors | +| Testing | [skills/testing/SKILL.md](skills/testing/SKILL.md) | Mocha/Chai, coverage, mocks | +| Code review | [skills/code-review/SKILL.md](skills/code-review/SKILL.md) | PR review for this monorepo | + +## Using Cursor (optional) + +If you use **Cursor**, [.cursor/rules/README.md](.cursor/rules/README.md) only points to **`AGENTS.md`**—same docs as everyone else. diff --git a/BULK-OPERATIONS-MIGRATION.md b/BULK-OPERATIONS-MIGRATION.md new file mode 100644 index 0000000000..fecea2cb6c --- /dev/null +++ b/BULK-OPERATIONS-MIGRATION.md @@ -0,0 +1,510 @@ +# 🔄 Migration Guide: From Bulk Publish to Bulk Operations Commands + +> **Migrating from @contentstack/cli-cm-bulk-publish (v1.x) to New Unified Commands @contentstack/cli-bulk-operations (v1.x)** +--- + +## What Changed? + +We've consolidated **15 separate commands** into **2 simple commands** with flags: + +**Before (v1.x):** +- ❌ `cm:entries:publish` +- ❌ `cm:entries:publish-modified` +- ❌ `cm:entries:publish-only-unpublished` +- ❌ `cm:entries:unpublish` +- ❌ `cm:assets:publish` +- ❌ `cm:assets:unpublish` +- ❌ `cm:stacks:unpublish` +- ❌ `cm:bulk-publish:cross-publish` +- ❌ And 7 more commands... + +**After (v2.0):** +- `csdx cm:stacks:bulk-entries` (for all entry operations) +- `csdx cm:stacks:bulk-assets` (for all asset operations) + +--- + +## Quick Migration Examples + +### 1️⃣ **Basic Publish Entries** + +```bash +# OLD +csdx cm:entries:publish --content-types blog --environments prod --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-entries --operation publish --content-types blog --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed from `cm:entries:publish` to `cm:stacks:bulk-entries` +- Added required `--operation publish` flag + +--- + +### 2️⃣ **Publish Only Modified Entries** + +```bash +# OLD +csdx cm:entries:publish-modified --content-types blog --source-env staging --environments prod --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-entries --operation publish --filter modified --content-types blog --source-env staging --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-entries` +- Added `--filter modified` flag instead of separate command + +--- + +### 3️⃣ **Publish Only Unpublished Entries** + +```bash +# OLD +csdx cm:entries:publish-only-unpublished --content-types blog --environments prod --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-entries --operation publish --filter unpublished --content-types blog --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-entries` +- Added `--filter unpublished` flag + +--- + +### 4️⃣ **Publish Non-Localized Field Changes** + +```bash +# OLD +csdx cm:entries:publish-non-localized-fields --content-types blog --source-env staging --environments prod -k blt123 + +# NEW +csdx cm:stacks:bulk-entries --operation publish --filter non-localized --content-types blog --source-env staging --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-entries` +- Added `--filter non-localized` flag +- `--locales` flag is now required + +--- + +### 5️⃣ **Unpublish Entries** + +```bash +# OLD +csdx cm:entries:unpublish --content-types blog --environments staging --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-entries --operation unpublish --content-types blog --environments staging --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-entries` +- Added `--operation unpublish` flag + +--- + +### 6️⃣ **Publish Assets** + +```bash +# OLD +csdx cm:assets:publish --environments prod --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-assets --operation publish --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-assets` +- Added `--operation publish` flag + +--- + +### 7️⃣ **Publish Assets from Specific Folder** + +```bash +# OLD +csdx cm:assets:publish --folder-uid images_folder --environments prod --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-assets --operation publish --folder-uid images_folder --environments prod --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-assets` +- Added `--operation publish` flag +- `--folder-uid` flag remains the same + +--- + +### 8️⃣ **Unpublish Assets** + +```bash +# OLD +csdx cm:assets:unpublish --environments staging --locales en-us -k blt123 + +# NEW +csdx cm:stacks:bulk-assets --operation unpublish --environments staging --locales en-us -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-assets` +- Added `--operation unpublish` flag + +--- + +### 9️⃣ **Cross-Publish Entries** + +```bash +# OLD +csdx cm:bulk-publish:cross-publish --source-env staging --environments prod --locales en-us -k blt123 --delivery-token blt*** + +# NEW - Step 1: Add delivery token as alias +csdx auth:tokens:add \ + -a staging-delivery \ + --delivery-token blt*** \ + --api-key blt123 \ + --environment staging \ + --type delivery + +# NEW - Step 2: Use the alias for cross-publish +csdx cm:stacks:bulk-entries \ + --operation publish \ + --source-env staging \ + --source-alias staging-delivery \ + --content-types blog article \ + --environments prod \ + --locales en-us \ + -k blt123 +``` + +**What changed:** +- Command renamed to `cm:stacks:bulk-entries` +- Delivery token must be stored as an alias first +- Added `--source-alias` flag (required for cross-publish) +- `--delivery-token` flag no longer supported inline + +--- + +### 🔟 **Unpublish All Content (Entries + Assets)** + +```bash +# OLD +csdx cm:stacks:unpublish --environments staging --locales en-us -k blt123 + +# NEW - Run two commands: +# 1. Unpublish entries +csdx cm:stacks:bulk-entries --operation unpublish --content-types blog,article,page --environments staging --locales en-us -k blt123 + +# 2. Unpublish assets +csdx cm:stacks:bulk-assets --operation unpublish --environments staging --locales en-us -k blt123 +``` + +**What changed:** +- Split into two explicit commands for better control +- Must specify content types for entries + +--- + +## ⚠️ Missing Functionality in v2.0 + +The following features from v1.x are **NOT** available in v2.0: + +### **1. Interactive Menu Command** +```bash +# ❌ NOT AVAILABLE +csdx cm:stacks:publish +``` + +**Impact:** You must use explicit commands instead of an interactive selection menu. + +**Workaround:** Use the explicit `bulk-entries` or `bulk-assets` commands directly. + +--- + +### **2. Configuration Generator Command** +```bash +# ❌ NOT AVAILABLE +csdx cm:stacks:publish-configure +csdx cm:bulk-publish:configure +``` + +**Impact:** No command to generate configuration files interactively. + +**Workaround:** Create `config.json` files manually (see [Config File Support](#7-config-file-support) above). + +--- + +### **3. Clear Logs Command** +```bash +# ❌ NOT AVAILABLE +csdx cm:stacks:publish-clear-logs +csdx cm:bulk-publish:clear +``` + +**Impact:** No CLI command to clear log files. + +**Workaround:** Use OS commands: +```bash +# Unix/Linux/Mac +rm -rf ./bulk-operation/* + +# Windows +del /q bulk-operation\* +``` + +--- + +### **4. Publish All Content Types Flag** +```bash +# ❌ NOT AVAILABLE +--publish-all-content-types +``` + +**Impact:** If content-types flag isn't provided then it will automatically fetch all content types. + +```bash +csdx cm:stacks:bulk-entries --operation publish --environments prod --locales en-us -k blt123 +``` + +--- + +### **5. Direct Delivery Token Flag** +```bash +# ❌ NOT AVAILABLE +--delivery-token blt*** +``` + +**Impact:** Cannot pass delivery token directly for cross-publish. + +**Workaround:** Store delivery token as an alias first: +```bash +# Step 1: Add delivery token +csdx auth:tokens:add -a prod-delivery --delivery-token blt*** --api-key blt123 --environment production --type delivery + +# Step 2: Use the alias +csdx cm:stacks:bulk-entries --operation publish --source-env production --source-alias prod-delivery --environments staging --locales en-us -k blt123 +``` + +--- + +## 📝 Step-by-Step Migration Process + +### **Step 1: Find Your Current Command** + +Look at your existing scripts/CI-CD pipelines and identify which old commands you're using. + +Example: `csdx cm:entries:publish-modified` + +--- + +### **Step 2: Find the Equivalent in the Table Above** + +For `cm:entries:publish-modified`, the new command is: +```bash +csdx cm:stacks:bulk-entries --operation publish --filter modified +``` + +--- + +### **Step 3: Update Authentication for Cross-Publish** + +If you use cross-publish with delivery tokens, store them as aliases: + +```bash +# Old way (not supported) +csdx cm:bulk-publish:cross-publish --delivery-token blt*** ... + +# New way - Step 1: Store token +csdx auth:tokens:add \ + -a staging-delivery \ + --delivery-token blt*** \ + --api-key blt123 \ + --environment staging \ + --type delivery + +# New way - Step 2: Use alias +csdx cm:stacks:bulk-entries --operation publish --source-env staging --source-alias staging-delivery ... +``` + +--- + +### **Step 4: Update Your Script** + +Replace the old command with the new one: + +```bash +# Before +csdx cm:entries:publish-modified --content-types blog --source-env staging --environments prod --locales en-us -k $API_KEY + +# After +csdx cm:stacks:bulk-entries --operation publish --filter modified --content-types blog --source-env staging --environments prod --locales en-us -k $API_KEY +``` + +--- + +### **Step 5: Test Your New Command** + +Run the command in a test environment first: + +```bash +# Test with staging environment +csdx cm:stacks:bulk-entries --operation publish --filter modified --content-types blog --environments staging --locales en-us -k $API_KEY +``` + +--- + +### **Step 6: Update All Scripts** + +Find and replace all instances across your: +- CI/CD pipelines (GitHub Actions, Jenkins, etc.) +- Deployment scripts +- Documentation +- Team runbooks + +--- + +## ⚠️ Breaking Changes + +### **1. Operation Flag Now Required** + +**Old behavior:** +```bash +csdx cm:entries:publish --content-types blog --environments prod --locales en-us -k blt123 +# Command name implies the operation +``` + +**New behavior:** +```bash +csdx cm:stacks:bulk-entries --operation publish --content-types blog --environments prod --locales en-us -k blt123 +# Must explicitly specify --operation flag +``` + +--- + +### **2. Combined Unpublish Split into Separate Commands** + +**Old behavior:** +```bash +csdx cm:stacks:unpublish --environments staging --locales en-us -k blt123 +# Unpublishes both entries and assets in one command +``` + +**New behavior:** +```bash +# Must run two separate commands for full control +csdx cm:stacks:bulk-entries --operation unpublish --content-types blog article --environments staging --locales en-us -k blt123 +csdx cm:stacks:bulk-assets --operation unpublish --environments staging --locales en-us -k blt123 +``` + +**Benefits:** +- Better control over what gets unpublished +- Clearer logging and error handling +- Can unpublish entries and assets independently + +--- + +### **3. Publish all content types** + +**Old behavior:** +```bash +csdx cm:entries:publish --publish-all-content-types --environments prod --locales en-us -k blt123 +# Flag to publish all content types +``` + +**New behavior:** +```bash +csdx cm:stacks:bulk-entries --operation publish --environments prod --locales en-us -k blt123 +``` + +--- + +### **4. Delivery Token Must Be Stored as Alias** + +**Old behavior:** +```bash +csdx cm:bulk-publish:cross-publish --delivery-token blt*** --source-env prod --environments staging --locales en-us -k blt123 +# Pass delivery token directly +``` + +**New behavior:** +```bash +# Step 1: Store delivery token +csdx auth:tokens:add -a prod-delivery --delivery-token blt*** --api-key blt123 --environment production --type delivery + +# Step 2: Use the alias +csdx cm:stacks:bulk-entries --operation publish --source-env production --source-alias prod-delivery --content-types blog --environments staging --locales en-us -k blt123 +``` + +**Why?** +- More secure (tokens not in command history) +- Tokens can be reused across commands +- Better token management + +--- + +### **5. Filter Flags Replace Separate Commands** + +**Old behavior:** +```bash +# Different commands for different filters +csdx cm:entries:publish-modified ... +csdx cm:entries:publish-only-unpublished ... +csdx cm:entries:publish-non-localized-fields ... +``` + +**New behavior:** +```bash +# One command with --filter flag +csdx cm:stacks:bulk-entries --operation publish --filter modified ... +csdx cm:stacks:bulk-entries --operation publish --filter unpublished ... +csdx cm:stacks:bulk-entries --operation publish --filter non-localized ... +``` + +--- + +### **6. Multiple Values Format Changed** + +**Old behavior:** +```bash +# Comma-separated values +--environments dev,staging,prod +--locales en-us,es-es,fr-fr +``` + +**New behavior:** +```bash +# Space-separated values +--environments dev staging prod +--locales en-us es-es fr-fr +``` + +--- + +## 📝 Summary + +**Key Takeaways:** + +1. **Two commands replace 15 old commands**: `cm:stacks:bulk-entries` and `cm:stacks:bulk-assets` +2. **Operation flag is required**: Always specify `--operation publish` or `--operation unpublish` +3. **Filters replace separate commands**: Use `--filter` for modified, unpublished, draft, non-localized +4. **Delivery tokens must be stored as aliases**: Use `auth:tokens:add` before cross-publish +5. **Content types must be explicit**: No more `--publish-all-content-types` +6. **Config files recommended for complex operations**: Use JSON files with `--config` flag +7. **New features**: `--publish-mode`, `--revert`, `--include-variants`, `--api-version` + +**Migration is straightforward:** +- Replace old command names with new ones +- Add `--operation` flag +- Use `--filter` instead of separate commands +- Store delivery tokens as aliases for cross-publish +- Test in lower environments first + +**Need Help?** +- Check [official documentation](https://www.contentstack.com/docs/developers/cli/bulk-operations-in-cli) +- Contact [Contentstack Support](https://www.contentstack.com/support/) + + diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000000..cdd71252e3 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,663 @@ +# Contentstack CLI Migration Guide: 1.x.x to 2.x.x-beta + +## Overview + +This guide helps you migrate from Contentstack CLI 1.x.x to the new 2.x.x-beta version. The new version introduces significant improvements in performance, user experience, and functionality. + +## Major Changes + +### 1. 🚀 TypeScript Module Support (Default) + +**What Changed:** +- Removed `export-info.json` support +- TypeScript modules are now the default for export and import operations +- Improved performance and reliability + +**Before (1.x.x):** +```bash +csdx cm:stacks:export -d "./export-data" -k bltxxxxxx +``` +The CLI generated an export-info.json file containing a contentVersion field: +contentVersion: 2 for TypeScript modules +contentVersion: 1 for JavaScript modules (default) +This version indicator helped the import process select the appropriate module structure, as TypeScript and JavaScript modules have different structures for assets, entries, and other components. + +**After (2.x.x-beta):** +```bash +csdx cm:stacks:export -d "./export-data" -k bltxxxxxx +``` +No export-info.json file is generated +TypeScript modules are used by default for all operations +Simplified export structure with consistent module formatting + +**Migration Action:** Remove `export-info.json` file generation logic from export plugin. + +### 2. 🌿 Main Branch Export (Default) + +**What Changed:** +- By default, only the main branch content is exported +- Consistent behavior with import operations +- Faster exports for most use cases + +**Before (1.x.x):** +- Exported all branches by default + +**After (2.x.x-beta):** +- Exports main branch by default +- Specify `--branch` for specific branch export + +**Examples:** + +```bash +# Export main branch (default behavior) +csdx cm:stacks:export -d "./export-data" -k bltxxxxxx + +# Export specific branch +csdx cm:stacks:export --branch feature-branch -d "./export-data" -k bltxxxxxx + +# Export using branch alias +csdx cm:stacks:export --branch-alias production -d "./export-data" -k bltxxxxxx +``` + +**Migration Action:** To export specific branches, add the `--branch` flag to your commands. + +### 3. 📊 Progress Manager UI (Default) + +**What Changed:** +- Visual Progress Manager is now the default UI for export, import, clone & seed operations +- Enhanced user experience with real-time progress tracking +- Console logs are available as an optional mode + +## New Progress Manager Interface + +### Default Mode: Visual Progress Manager + +When you run the export or import commands, a visual progress interface appears. + +``` +STACK: + ├─ Settings |████████████████████████████████████████| 100% | 1/1 | ✓ Complete (1/1) + ├─ Locale |████████████████████████████████████████| 100% | 1/1 | ✓ Complete (1/1) + +LOCALES: + └─ Locales |████████████████████████████████████████| 100% | 2/2 | ✓ Complete (2/2) + +CONTENT TYPES: + └─ Content types |████████████████████████████████████████| 100% | 6/6 | ✓ Complete (6/6) + +ENTRIES: + ├─ Entries |████████████████████████████████████████| 100% | 12/12 | ✓ Complete (12/12) +``` + +### Optional Mode: Console Logs + +For debugging or detailed logging, switch to console log mode: + +**Enable Console Logs:** +```bash +csdx config:set:log --show-console-logs +``` + +**Disable Console Logs (back to Progress Manager):** +```bash +csdx config:set:log --no-show-console-logs +``` + +**Console Log Output Example:** +``` +[2025-08-22 16:12:23] INFO: Exporting content from branch main +[2025-08-22 16:12:23] INFO: Started to export content, version is 2 +[2025-08-22 16:12:23] INFO: Exporting module: stack +[2025-08-22 16:12:24] INFO: Exporting stack settings +[2025-08-22 16:12:25] SUCCESS: Exported stack settings successfully! +``` + +### 4. 🏷️ Taxonomy Migration Deprecation + +**What Changed:** +- Taxonomy migration functionality has been deprecated in 2.x.x +- The taxonomy migration script examples have been removed + +**Before (1.x.x):** +```bash +csdx cm:stacks:migration -k b*******9ca0 --file-path "../contentstack-migration/examples/taxonomies/import-taxonomies.js" --config data-dir:'./data/Taxonomy Stack_taxonomies.csv' +``` +- Taxonomy migration supports only in version 1.x.x + +**After (2.x.x-beta):** +- Taxonomy migration is no longer supported through the migration plugin +- Use the standard import/export commands for taxonomy data migration + +**Migration Action:** use the import/export commands instead. + +### 5. 📝 Migrate RTE Plugin Separation + +**What Changed:** +- The migrate-rte plugin has been separated into a standalone plugin +- Requires separate installation to use RTE migration features +- Provides more flexibility and modular architecture + +**Before (1.x.x):** +- RTE migration was built into the core CLI package +- Available by default with CLI installation + +**After (2.x.x-beta):** +- RTE migration is a separate plugin that must be installed explicitly +- Install using one of the following methods: + +**Installation Methods:** + + +**Option 1: Using npm** +```bash +npm install -g @contentstack/cli-cm-migrate-rte +``` + +**Option 2: Using CLI Plugin Manager** +```bash +csdx plugins:install @contentstack/cli-cm-migrate-rte@2.0.0-beta +``` + +**Usage:** +After installation, RTE migration commands will be available through the CLI: +```bash +csdx cm:migrate-rte --help +``` + +**Migration Action:** Install the `@contentstack/cli-cm-migrate-rte` plugin separately if you need RTE migration functionality. + +### 6. 📦 Bulk Operations Command Consolidation + +**What Changed:** +- The bulk publish plugin has been consolidated into unified bulk operations commands +- 15 separate commands have been simplified into 2 commands with operation flags +- Enhanced functionality with new filtering and cross-publish capabilities + +**Impact:** +- Commands like `cm:entries:publish`, `cm:entries:unpublish`, `cm:assets:publish` have been replaced +- New unified commands: `cm:stacks:bulk-entries` and `cm:stacks:bulk-assets` +- Operation flag (`--operation`) is now required + +**Migration Action:** Refer to the detailed [Bulk Operations Migration Guide](./BULK-OPERATIONS-MIGRATION.md) for complete command mappings and examples. + +**Quick Example:** +```bash +# Before (1.x.x) +csdx cm:entries:publish --content-types blog --environments prod --locales en-us -k blt123 + +# After (2.x.x-beta) +csdx cm:stacks:bulk-entries --operation publish --content-types blog --environments prod --locales en-us -k blt123 +``` + +### 7. 🚀 Launch Plugin Now Opt-In + +**What Changed:** +- The `launch` plugin (`@contentstack/cli-launch`) is no longer bundled with the CLI +- All `launch:*` commands now require installing the plugin explicitly before use +- Brings `launch` in line with the opt-in, modular plugin model used elsewhere in 2.x + +> ⚠️ **This is a change relative to the 2.x beta — not only relative to 1.x.** `@contentstack/cli-launch` was bundled throughout the 1.x releases **and** the entire 2.x beta period, so `launch:*` worked out of the box for beta users too. Starting with 2.x GA it becomes opt-in, so beta users who rely on `launch:*` are also affected when they upgrade. + +**Before (1.x.x and 2.x.x-beta):** +- `launch:*` commands were bundled with the CLI and available by default after installation + +**After (2.x.x GA):** +- `launch:*` commands are provided by a separate, opt-in plugin that must be installed explicitly +- Running any `launch:*` command without the plugin installed fails with a `command not found` error where it previously worked out of the box + +**Affected commands:** `launch`, `launch:deployments`, `launch:environments`, `launch:functions`, `launch:logs`, `launch:open`, `launch:rollback` + +**Installation Methods:** + + +**Option 1: Using CLI Plugin Manager** +```bash +csdx plugins:install @contentstack/cli-launch +``` + +**Option 2: Using npm** +```bash +npm install -g @contentstack/cli-launch +``` + +**Usage:** +After installation, launch commands will be available through the CLI: +```bash +csdx launch --help +``` + +**Migration Action:** If you use any `launch:*` command, install the `@contentstack/cli-launch` plugin before (or immediately after) upgrading to 2.x GA to avoid `command not found` errors. This applies to 2.x beta users as well, since `launch` was bundled during the beta. + +### 8. 🔁 Flag Renames on Export / Import / Export-to-CSV + +**What Changed:** +Several flags on `cm:stacks:export`, `cm:stacks:import`, and `cm:stacks:export-to-csv` were renamed or removed. Passing the old flag names now causes an **immediate error** — V2 does not silently fall back. + +**cm:stacks:export — Removed Flags:** + +| V1 Flag | V2 Replacement | +|---|---| +| `--data` | `--data-dir` | +| `--stack-uid` / `-s` | `--stack-api-key` | +| `--management-token-alias` | `--alias` | +| `--auth-token` / `-A` | use `csdx auth:login`, then `--alias` | +| `-m` | `--module` (long form only) | +| `-t` | `--content-types` (long form only) | +| `-B` | `--branch` (long form only) | + +**cm:stacks:import — Removed Flags:** + +| V1 Flag | V2 Replacement | +|---|---| +| `--data` | `--data-dir` | +| `--stack-uid` / `-s` | `--stack-api-key` | +| `--management-token-alias` | `--alias` | +| `--auth-token` / `-A` | use `csdx auth:login`, then `--alias` | +| `-m` | `--module` (long form only) | +| `-b` | `--backup-dir` (long form only) | +| `-B` | `--branch` (long form only) | +| `--skip-app-recreation` | **Removed — no replacement** | + +> ⚠️ `--skip-app-recreation` is gone entirely. Remove it from all import scripts. + +**cm:stacks:export-to-csv — Removed Flags:** + +| V1 Flag | V2 Replacement | +|---|---| +| `--data` | `--data-dir` | +| `--stack-uid` / `-s` | `--stack-api-key` | + +**Before (1.x.x):** +```bash +csdx cm:stacks:export -s blt123 --data ./export -B main +csdx cm:stacks:import -s blt123 --data ./export -b ./backup -B main +``` + +**After (2.x.x):** +```bash +csdx cm:stacks:export --stack-api-key blt123 --data-dir ./export --branch main +csdx cm:stacks:import --stack-api-key blt123 --data-dir ./export --backup-dir ./backup --branch main +``` + +**Also note — `--module studio` renamed:** +V1's `--module studio` is now `--module composable-studio`. Using the old value fails immediately: +```bash +# V1 +csdx cm:stacks:export --module studio + +# V2 +csdx cm:stacks:export --module composable-studio +``` + +**Migration Action:** Update all export and import scripts to use the new flag names above. Search your CI/CD configs for `--data`, `-s`, `-B`, `-b`, `-m`, `-t`, `--auth-token`, `--management-token-alias`, `--skip-app-recreation`, and `--module studio`. + +--- + +### 9. ⚠️ Export Directory Structure Changed (CRITICAL — Silent Data Loss Risk) + +**What Changed:** +V2 changes two structural aspects of the export directory that can cause **silent failures** in downstream pipelines and V1 import operations. + +#### 9.1 Global Fields: One File Per UID (was one combined file) + +V1 wrote all global field schemas into a single file. V2 writes one file per global field UID. + +``` +# V1 export layout +export/global_fields/globalfields.json ← all schemas in one array + +# V2 export layout +export/global_fields/my_header.json ← one file per UID +export/global_fields/my_footer.json +export/global_fields/shared_banner.json +``` + +#### 9.2 Content Types: Combined `schema.json` Removed + +V1 also wrote `content_types/schema.json` containing all content type schemas as an array. V2 removes this file — only individual `content_types/.json` files are written. + +```bash +cat export/content_types/schema.json # this file does not exist in V2 exports +ls export/content_types/*.json # correct: iterate per-UID files +``` + +#### 9.3 Branches: `branches.json` No Longer Written + +V1 wrote a `branches.json` to the export root. V2 does not write this file and raises no error. + +**Migration Action:** +- Update any tooling that reads `globalfields.json` or `content_types/schema.json` to iterate per-UID files. +- Remove any pipeline steps that check for or read `branches.json`. +- If you run a V2 export and then import with a **V1 CLI**, content types and global fields will be silently skipped (see section 10). + +--- + +### 10. 🚨 V2 Export Cannot Be Imported with V1 CLI — Silent Skip (CRITICAL) + +**What Changed:** +V2's importer (`cm:stacks:import`) reads only per-UID `.json` files for content types and global fields. It **explicitly ignores** the V1 aggregate files (`schema.json`, `globalfields.json`). There is no error or warning — the import completes "successfully" with zero content types and zero global fields created. + +The same silent-skip applies when running `cm:stacks:audit` against a V1 export directory — the audit reads per-UID files only and will report 0 schemas found. + +| Module | V1 file (not read by V2) | V2 file (required) | +|---|---|---| +| Content types | `content_types/schema.json` | `content_types/.json` (one per UID) | +| Global fields | `global_fields/globalfields.json` | `global_fields/.json` (one per UID) | + +**Scenario that breaks silently:** +```bash +# This appears to succeed but imports 0 content types and 0 global fields: +csdx cm:stacks:export --data-dir ./export -k bltV1stack # exported with V1 CLI +csdx cm:stacks:import --data-dir ./export -k bltV2stack # imported with V2 CLI +``` + +**Resolution:** Always re-export with the V2 CLI before importing with the V2 CLI. If you must work with a V1 export, split `schema.json` and `globalfields.json` into individual per-UID files first. + +**Migration Action:** Do not mix V1-exported data with a V2 import run. Add a step in your pipeline to verify exports were produced by the same CLI major version before importing. + +--- + +### 11. 🔗 Command Aliases Removed + +**What Changed:** +Several short-form command aliases that worked in V1 no longer exist in V2. Running them produces a `command not found` error. + +| Removed Alias (V1) | V2 Replacement | +|---|---| +| `csdx cm:export` | `csdx cm:stacks:export` | +| `csdx cm:import` | `csdx cm:stacks:import` | +| `csdx cm:import-setup` | `csdx cm:stacks:import-setup` | +| `csdx cm:seed` | `csdx cm:stacks:seed` | +| `csdx tokens` | `csdx auth:tokens:list` | +| `csdx audit` | `csdx cm:stacks:audit` | +| `csdx audit:fix` | `csdx cm:stacks:audit:fix` | + +> ✅ **Exception:** `csdx cm:migration` is the one V1 alias that **survived** — it still works in V2. + +**Before (1.x.x):** +```bash +csdx cm:export -s blt123 -d ./export +csdx audit --report-path ./my-export +``` + +**After (2.x.x):** +```bash +csdx cm:stacks:export --stack-api-key blt123 --data-dir ./export +csdx cm:stacks:audit --report-path ./my-export +``` + +**Migration Action:** Search your scripts and CI/CD configs for the removed aliases above and replace them with their full V2 equivalents. + +--- + +### 12. 🧩 `content-type:*` Deprecated Flags Removed + +**What Changed:** +All six `content-type:*` commands (`audit`, `compare`, `compare-remote`, `details`, `diagram`, `list`) had their deprecated V1 flags and multiple short chars removed. These flags printed deprecation warnings in V1 but now **fail with an error** in V2. + +**Removed across all `content-type:*` commands:** + +| Removed | V2 Replacement | +|---|---| +| `--stack` / `-s` | `--stack-api-key` / `-k` | +| `--token-alias` | `--alias` / `-a` | + +**Additional short chars removed per command:** + +| Command | Removed Short Chars | Long Flag | +|---|---|---| +| `content-type:audit` | `-c` | `--content-type` | +| `content-type:compare` | `-c`, `-l`, `-r` | `--content-type`, `--left`, `--right` | +| `content-type:compare-remote` | `-o`, `-r`, `-c` | `--origin-stack`, `--remote-stack`, `--content-type` | +| `content-type:details` | `-c`, `-p` | `--content-type`, `--path` | +| `content-type:diagram` | `-o`, `-d`, `-t` | `--output`, `--direction`, `--type` | +| `content-type:list` | `-o` | `--order` | + +**Before (1.x.x):** +```bash +csdx content-type:audit --stack blt123 --token-alias myalias -c blog +csdx content-type:compare --stack blt123 -c blog -l 1 -r 2 +``` + +**After (2.x.x):** +```bash +csdx content-type:audit --stack-api-key blt123 --alias myalias --content-type blog +csdx content-type:compare --stack-api-key blt123 --content-type blog --left 1 --right 2 +``` + +**Migration Action:** Replace `--stack` with `--stack-api-key`, `--token-alias` with `--alias`, and use long-form flags for all removed short chars. + +--- + +### 13. 🚫 `--api-version` Flag Removed from Bulk Operations + +**What Changed:** +The `--api-version` flag has been **removed** from `cm:stacks:bulk-entries` and `cm:stacks:bulk-taxonomies`. V2 hardcodes `api_version: 3.2` for all publish/unpublish calls. Passing `--api-version` now causes an immediate flag error. + +**Before (1.x.x):** +```bash +csdx cm:stacks:bulk-entries --operation publish --api-version 3.2 --environments prod --locales en-us -k blt123 +csdx cm:stacks:bulk-taxonomies --operation publish --api-version 3 --environments prod -k blt123 +``` + +**After (2.x.x):** +```bash +csdx cm:stacks:bulk-entries --operation publish --environments prod --locales en-us -k blt123 +csdx cm:stacks:bulk-taxonomies --operation publish --environments prod -k blt123 +``` + +**Migration Action:** Remove `--api-version` from all bulk-entries and bulk-taxonomies scripts. API version 3.2 is always used. + +--- + +### 14. ✂️ Short Char Removals Across Other Commands + +**What Changed:** +V2 resolved short char conflicts across multiple commands by removing ambiguous or deprecated single-letter flags. Long-form flags are unaffected. + +| Command | Removed Short Char | Long Flag (still works) | +|---|---|---| +| `cm:stacks:migration` | `-A` | `--authtoken` | +| `cm:stacks:migration` | `-n` | `--filePath` | +| `cm:stacks:migration` | `-B` | `--branch` | +| `migrate:convert` | `-o` | `--output` | +| `migrate:convert` | `-r` | `--rte` | +| `migrate:export` | `-b` | `--branch` | +| `migrate:export` | `-c` | `--config` | +| `migrate:export` | `-o` | `--org` | +| `app:create` | `-n` | `--name` | + +**Before (1.x.x):** +```bash +csdx cm:stacks:migration -n ./my-migration.js -A myAuthtoken +csdx app:create -n my-app +``` + +**After (2.x.x):** +```bash +csdx cm:stacks:migration --filePath ./my-migration.js --authtoken myAuthtoken +csdx app:create --name my-app +``` + +**Migration Action:** Replace removed short chars with their long-form equivalents in all scripts. + +--- + +### 15. ⚙️ Console Log Config Key Renamed + +**What Changed:** +The internal config key that stores the console log preference was renamed from hyphenated to camelCase. Your V1 log preference is **not carried over** to V2 — you must re-apply it after upgrading. + +| Config version | Key stored | +|---|---| +| V1 | `log["show-console-logs"]` | +| V2 | `log["showConsoleLogs"]` | + +This does not affect the CLI flag name (`--show-console-logs` still works), only the stored config key. If your setup reads the Contentstack CLI config file directly (e.g. in a dotfile or CI bootstrap script), update the key name. + +**Migration Action:** After upgrading to V2, re-run your log preference command: + +```bash +# If you use console log mode in CI: +csdx config:set:log --show-console-logs + +# If you use progress bar mode (default — run this to clear any stale V1 setting): +csdx config:set:log --no-show-console-logs +``` + +--- + +### 16. 📦 Bootstrap App Configs Removed (13 Removed, 8 Remain) + +**What Changed:** +`cm:bootstrap` no longer recognises 13 app name values that were valid in V1. Passing any of them now throws `CLI_BOOTSTRAP_INVALID_APP_NAME`. Additionally, the flag names themselves changed (see section 8 above). + +**Flag renames:** + +| V1 Flag | V2 Flag | +|---|---| +| `--appName` / `-a` | `--app-name` | +| `--directory` / `-d` | `--project-dir` | +| `--appType` / `-s` | `--app-type` | + +**Removed `--app-name` values (13 total):** + +| Removed App Name | Type | +|---|---| +| `reactjs` | Sample app | +| `nextjs` | Sample app | +| `gatsby` | Sample app | +| `angular` | Sample app | +| `reactjs-starter` | Deprecated starter | +| `nextjs-starter` | Deprecated starter | +| `gatsby-starter` | Deprecated starter | +| `angular-starter` | Deprecated starter | +| `nuxt-starter` | Deprecated starter | +| `vue-starter` | Deprecated starter | +| `stencil-starter` | Deprecated starter | +| `nuxt3-starter` | Deprecated starter | +| `nuxtjs-disabled` | Hidden config entry | + +**Valid `--app-name` values in V2 (8):** + +| App Name | Description | +|---|---| +| `compass-app` | Compass App | +| `kickstart-next` | Kickstart Next.js | +| `kickstart-next-ssr` | Kickstart Next.js SSR | +| `kickstart-next-ssg` | Kickstart Next.js SSG | +| `kickstart-next-graphql` | Kickstart Next.js GraphQL | +| `kickstart-next-middleware` | Kickstart Next.js Middleware | +| `kickstart-nuxt` | Kickstart NuxtJS | +| `kickstart-nuxt-ssr` | Kickstart NuxtJS SSR | + +**Before (1.x.x):** +```bash +csdx cm:bootstrap --appName reactjs --directory ./myapp --appType sampleapp +``` + +**After (2.x.x):** +```bash +csdx cm:bootstrap --app-name compass-app --project-dir ./myapp +``` + +**Migration Action:** Replace removed `--app-name` values with one of the 8 valid V2 app names. Update `--appName` → `--app-name`, `--directory` → `--project-dir`, `--appType` → `--app-type`. + +--- + +### 17. 🌱 Seed Stack List Is Now Curated (4 Stacks Only) + +**What Changed:** +In V1, running `csdx cm:stacks:seed` without `--repo` triggered a live GitHub API search and presented all matching Contentstack repositories. In V2, the list is fixed — only 4 curated repos are shown in the interactive picker. + +**V2 curated list:** +1. `contentstack/kickstart-stack-seed` — Kickstart stack seed +2. `contentstack/kickstart-veda-seed` — Kickstart Veda +3. `contentstack/compass-starter-stack` — Compass starter stack +4. `contentstack/stack-starter-app` — Starter app + +If you previously relied on the interactive list to discover repos, those repos no longer appear. Any script that passed a repo name not in this list via the interactive prompt will now time out or fail. + +**Migration Action:** Use `--repo owner/repo-name` directly if you need a repository that is not in the curated list: + +```bash +csdx cm:stacks:seed --repo contentstack/my-custom-seed-repo -k bltXXX +``` + +--- + +### 18. 🛑 Ctrl+C Now Exits with Code 130 (Was an Uncaught Exception) + +**What Changed:** +In V1, pressing Ctrl+C during an interactive prompt (e.g. environment selection, alias selection) caused an `ExitPromptError` to be thrown. Depending on how your shell or CI pipeline handled unhandled exceptions, this could produce a non-zero exit code or an error stack trace. + +In V2, SIGINT is caught and the process exits cleanly with **exit code 130** — the POSIX standard for SIGINT termination. No stack trace is printed. + +**Before (1.x.x):** +- Ctrl+C → `ExitPromptError` thrown → unpredictable exit code, possible stack trace in logs + +**After (2.x.x):** +- Ctrl+C → clean exit with code 130 + +**Migration Action:** If your CI pipeline checks the exit code of CLI commands that may be cancelled interactively, update the expected exit code from a non-zero exception code to `130`. If you catch `ExitPromptError` in any wrapper scripts, remove that handler. + +--- + +## Troubleshooting + +### Common Issues + +**1. Command not found errors:** +- Ensure you have installed the 2.x.x-beta version +- Clear npm cache: `npm cache clean --force` + +**2. Missing branch content:** +- Check if you need to specify the `--branch` flag for non-main branches +- Verify the branch exists in your stack + +**3. Progress display issues:** +- Try switching between console logs and progress manager modes +- Check terminal compatibility for progress bars + +**4. Performance differences:** +- The 2.x.x-beta version should be faster due to TypeScript modules +- If you are experiencing issues, switch to console log mode for debugging + +**5. `launch:*` command not found:** +- In 2.x GA, `launch` is an opt-in plugin and is no longer bundled (it was bundled in 1.x and during the 2.x beta) +- Install it with `csdx plugins:install @contentstack/cli-launch`, then re-run your `launch:*` command +- Verify it is installed with `csdx plugins` + +### Getting Help + +**Documentation:** +- [CLI Documentation](https://www.contentstack.com/docs/developers/cli) +- [API Reference](https://www.contentstack.com/docs/developers/apis) + +**Support:** +- [GitHub Issues](https://github.com/contentstack/cli/issues) + +## Benefits of 2.x.x-beta + +### 🚀 **Performance Improvements** +- Faster export/import operations with TypeScript modules +- Optimized branch handling +- Reduced memory usage + +### 🎯 **Better User Experience** +- Visual Progress Manager with real-time updates +- Cleaner command syntax +- More intuitive default behaviors + +### 🔧 **Enhanced Reliability** +- Improved error handling +- Better progress tracking +- More consistent behavior across commands + +### 📊 **Better Observability** +- Detailed progress information +- Clear success/failure indicators +- Optional detailed logging for debugging +--- + +**Need help with migration?** Contact our support team or visit our community forum for assistance. diff --git a/README.md b/README.md index 60eca7d5e3..b98bd98abc 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ CLI supports content management scripts through which you can perform the follow ## Installing CLI ### Prerequisites Contentstack account -Node.js version 16 or above +Node.js version 22 or above ### Installation To install CLI on your system, run the below command in your terminal: @@ -32,6 +32,18 @@ npm install -g @contentstack/cli To verify the installation, run `csdx` in the command window. +## Migration Guide + +If you're upgrading from CLI 1.x to 2.x.x-beta, please refer to our comprehensive [Migration Guide](./MIGRATION.md) for: + +- **Breaking changes** and new default behaviors +- **Step-by-step migration instructions** +- **New features** like TypeScript module support and Progress Manager UI +- **Command syntax updates** and configuration changes +- **Troubleshooting tips** for common migration issues + +📖 **[View Migration Guide →](./MIGRATION.md)** + ## Usage After the successful installation of CLI, use the `--help` parameter to display the help section of the CLI. You can even combine this parameter with a specific command to get the help section of that command. @@ -42,7 +54,7 @@ $ csdx --help ## Namespaces **auth**: To perform [authentication-related](/packages/contentstack-auth) activities -**cm**: To perform content management activities such as [bulk publish](/packages/contentstack-bulk-publish), [import](/packages/contentstack-import), and [export](/packages/contentstack-export), [export-to-csv] (/packages/contentstack-export-to-csv), [seed] (/packages/contentstack-seed) +**cm**: To perform content management activities such as [bulk operations](/packages/contentstack-bulk-operations), [import](/packages/contentstack-import), and [export](/packages/contentstack-export), [export-to-csv](/packages/contentstack-export-to-csv), [seed](/packages/contentstack-seed) **help**: To list the helpful commands in CLI @@ -50,8 +62,8 @@ $ csdx --help ## Documentation -To get a more detailed documentation for every command, visit the [CLI section](https://www.contentstack.com/docs/developers/cli) in our docs. +To get a more detailed documentation for every command, visit the [CLI section](https://www.contentstack.com/docs/headless-cms/cli) in our docs. ## Useful Plugins -- [Generate TypeScript typings from a Stack](https://github.com/Contentstack-Solutions/contentstack-cli-tsgen) +- [Generate TypeScript typings from a Stack](https://github.com/contentstack/cli-plugins/tree/main/packages/contentstack-cli-tsgen) diff --git a/packages/contentstack-auth/.mocharc.json b/packages/contentstack-auth/.mocharc.json index ce9aaa6a76..44aa246ea6 100644 --- a/packages/contentstack-auth/.mocharc.json +++ b/packages/contentstack-auth/.mocharc.json @@ -1,8 +1,9 @@ { "require": [ "test/helpers/init.js", - "ts-node/register/transpile-only", - "source-map-support/register" + "ts-node/register", + "source-map-support/register", + "test/helpers/mocha-root-hooks.js" ], "watch-extensions": ["ts"], "recursive": true, diff --git a/packages/contentstack-auth/README.md b/packages/contentstack-auth/README.md index 035e761299..c0329efa68 100644 --- a/packages/contentstack-auth/README.md +++ b/packages/contentstack-auth/README.md @@ -1,8 +1,8 @@ # @contentstack/cli-auth -It is Contentstack’s CLI plugin to perform authentication-related activities. To get started with authentication, refer to the [CLI’s Authentication documentation](https://www.contentstack.com/docs/developers/cli/authentication) +It is Contentstack’s CLI plugin to perform authentication-related activities. To get started with authentication, refer to the [CLI’s Authentication documentation](https://www.contentstack.com/docs/headless-cms/cli/authentication) -[![License](https://img.shields.io/npm/l/@contentstack/cli-auth)](https://github.com/contentstack/cli/blob/main/LICENSE) +[![License](https://img.shields.io/npm/l/@contentstack/cli)](https://github.com/contentstack/cli/blob/main/LICENSE) * [@contentstack/cli-auth](#contentstackcli-auth) @@ -18,7 +18,7 @@ $ npm install -g @contentstack/cli-auth $ csdx COMMAND running command... $ csdx (--version) -@contentstack/cli-auth/1.8.4 darwin-arm64 node-v22.21.1 +@contentstack/cli-auth/2.0.0-beta.15 darwin-arm64 node-v22.21.1 $ csdx --help [COMMAND] USAGE $ csdx COMMAND @@ -33,11 +33,11 @@ USAGE * [`csdx auth:logout`](#csdx-authlogout) * [`csdx auth:tokens`](#csdx-authtokens) * [`csdx auth:tokens:add [-a ] [--delivery] [--management] [-e ] [-k ] [-y] [--token ]`](#csdx-authtokensadd--a-value---delivery---management--e-value--k-value--y---token-value) +* [`csdx auth:tokens:list`](#csdx-authtokenslist) * [`csdx auth:tokens:remove`](#csdx-authtokensremove) * [`csdx auth:whoami`](#csdx-authwhoami) * [`csdx login`](#csdx-login) * [`csdx logout`](#csdx-logout) -* [`csdx tokens`](#csdx-tokens) * [`csdx whoami`](#csdx-whoami) ## `csdx auth:login` @@ -102,7 +102,7 @@ _See code: [src/commands/auth/logout.ts](https://github.com/contentstack/cli/blo ## `csdx auth:tokens` -Lists all existing tokens added to the session +Manage authentication tokens for API access ``` USAGE @@ -120,13 +120,14 @@ TABLE FLAGS --sort= Sort the table by a column. Use "-" for descending. DESCRIPTION - Lists all existing tokens added to the session - -ALIASES - $ csdx tokens + Manage authentication tokens for API access EXAMPLES - $ csdx auth:tokens + $ csdx auth:tokens:list + + $ csdx auth:tokens:add --alias mytoken + + $ csdx auth:tokens:remove --alias mytoken ``` _See code: [src/commands/auth/tokens/index.ts](https://github.com/contentstack/cli/blob/main/packages/contentstack-auth/src/commands/auth/tokens/index.ts)_ @@ -141,12 +142,12 @@ USAGE FLAGS -a, --alias= Alias (name) you want to assign to the token - -d, --delivery Set this flag to save delivery token -e, --environment= Environment name for delivery token -k, --stack-api-key= Stack API Key - -m, --management Set this flag to save management token - -t, --token= [env: TOKEN] Add the token name -y, --yes Use this flag to skip confirmation + --delivery Set this flag to save delivery token + --management Set this flag to save management token + --token= [env: TOKEN] Add the token name DESCRIPTION Adds management/delivery tokens to your session to use it with other CLI commands @@ -177,17 +178,44 @@ EXAMPLES _See code: [src/commands/auth/tokens/add.ts](https://github.com/contentstack/cli/blob/main/packages/contentstack-auth/src/commands/auth/tokens/add.ts)_ +## `csdx auth:tokens:list` + +Lists all existing tokens added to the session + +``` +USAGE + $ csdx auth:tokens:list [--columns ] [--sort ] [--filter ] [--csv] [--no-truncate] + [--no-header] [--output csv|json|yaml] + +TABLE FLAGS + --columns= Specify columns to display, comma-separated. + --csv Output results in CSV format. + --filter= Filter rows by a column value (e.g., name=foo). + --no-header Hide table headers in output. + --no-truncate Prevent truncation of long text in columns. + --output=