### Initial Project Setup Source: https://github.com/tryghost/ghost/blob/main/CLAUDE.md Performs the first-time setup, including dependency installation and submodule setup. ```bash pnpm run setup ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/tryghost/ghost/blob/main/apps/stats/README.md Install project dependencies using pnpm and start the development server from the monorepo root. ```bash pnpm install pnpm dev ``` -------------------------------- ### Install Dependencies and Initialize Submodules Source: https://github.com/tryghost/ghost/blob/main/docs/README.md Enable pnpm via Corepack and then run the setup script to install all project dependencies and initialize submodules. ```bash corepack enable pnpm pnpm run setup ``` -------------------------------- ### Quick Start Mock Server Setup Source: https://github.com/tryghost/ghost/blob/main/apps/posts/test/utils/MSW_USAGE_GUIDE.md Set up the mock server with declarative data for common API endpoints. This covers about 90% of use cases. ```typescript import {mockServer, mockData} from '../utils/msw-helpers'; // 90% of cases - just declare what data you want mockServer.setup({ posts: [mockData.post({title: 'My Post'})], feedback: [{id: '1', score: 1, message: 'Great!'}] }); ``` -------------------------------- ### Create Post Factory with Setup Helper Source: https://github.com/tryghost/ghost/blob/main/e2e/data-factory/README.md Recommended method for creating a PostFactory instance using setup helpers. This example uses API persistence. ```typescript import {createPostFactory, PostFactory} from '../data-factory'; // Create factory with API persistence const postFactory: PostFactory = createPostFactory(page.request); // Build in-memory only (not persisted) const draftPost = postFactory.build({ title: 'My Draft', status: 'draft' }); // Create and persist to database const publishedPost = await postFactory.create({ title: 'My Published Post', status: 'published' }); ``` -------------------------------- ### Create Setup Helper for New Factory Source: https://github.com/tryghost/ghost/blob/main/e2e/data-factory/README.md Example of creating a setup helper function for a new factory (e.g., MemberFactory) to simplify its usage in tests. ```typescript // In setup.ts export function createMemberFactory(httpClient: HttpClient): MemberFactory { const adapter = new GhostAdminApiAdapter(httpClient, 'members'); return new MemberFactory(adapter); } ``` -------------------------------- ### Start Development Environment Source: https://github.com/tryghost/ghost/blob/main/AGENTS.md Initiates the development environment using a hybrid Docker and host setup. Includes options for optional services. ```bash # Start everything (Docker + frontend dev servers) pnpm dev # With optional services (uses Docker Compose file composition) pnpm dev:analytics # Include Tinybird analytics pnpm dev:storage # Include MinIO S3-compatible object storage pnpm dev:all # Include all optional services ``` -------------------------------- ### Install Ghost for Production Source: https://github.com/tryghost/ghost/blob/main/README.md Installs Ghost on a server, including automatic SSL setup with LetsEncrypt. This is recommended for production environments. ```bash ghost install ``` -------------------------------- ### Install Ghost Locally Source: https://github.com/tryghost/ghost/blob/main/README.md Sets up a local Ghost instance for development or testing. This command uses the 'local' flag for a quick setup. ```bash ghost install local ``` -------------------------------- ### Install Dependencies and Run All Tests Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Installs project dependencies using pnpm and then runs all end-to-end tests. ```bash pnpm pnpm test ``` -------------------------------- ### Run Tinybird Locally Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/README.md Starts the local Tinybird service. Ensure the Tinybird CLI is installed first. ```bash pnpm tb ``` -------------------------------- ### Start Development Server Source: https://github.com/tryghost/ghost/blob/main/apps/admin/README.md Run this command from the monorepo root to start the development server for the Ghost Admin React application. ```bash pnpm dev ``` -------------------------------- ### Troubleshoot Ghost Setup Issues Source: https://github.com/tryghost/ghost/blob/main/docs/README.md Commands to help resolve common setup problems, including fixing dependency issues, updating to the latest main branch, and resetting development data. ```bash # Fix dependency issues pnpm fix # Update to latest main branch pnpm main # Reset running dev data pnpm reset:data ``` -------------------------------- ### Manually Setup Post Factory Source: https://github.com/tryghost/ghost/blob/main/e2e/data-factory/README.md Manual setup for creating a PostFactory instance. Requires explicit instantiation of the persistence adapter. ```typescript import {PostFactory} from '../data-factory/factories/post-factory'; import {GhostAdminApiAdapter} from '../data-factory/persistence/adapters/ghost-api'; const adapter = new GhostAdminApiAdapter(page.request, 'posts'); const postFactory = new PostFactory(adapter); // Now you can build or create const post = await postFactory.create({ title: 'My Published Post', status: 'published' }); ``` -------------------------------- ### Start Ghost Development Server Source: https://github.com/tryghost/ghost/blob/main/docs/README.md Start the development environment, which includes running Docker backend services and frontend development servers. Ghost will be accessible via localhost. ```bash # Start development (runs Docker backend services + frontend dev servers) pnpm dev ``` -------------------------------- ### Run Tinybird Local Container with Docker Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/README.md Starts the Tinybird local container, deploys datafiles, and configures the Analytics service. Ensure Docker and Docker Compose are installed. ```bash docker compose --profile analytics up -d ``` -------------------------------- ### Start Ghost Core Dev Docker with All Optional Services Source: https://github.com/tryghost/ghost/blob/main/docker/ghost-dev/README.md This command starts the Docker backend and frontend development servers, including all optional services. ```bash pnpm dev:all ``` -------------------------------- ### Test Setup for Shade Components Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Import and call shared setup functions in your app's test setup file to provide common mocks for responsive behavior and chart components used by shade components. ```typescript import '@testing-library/jest-dom'; import {setupShadeMocks, setupConsoleFilters} from '@tryghost/admin-x-framework/test/setup'; // Set up common mocks for shade components setupShadeMocks(); // Set up console filtering for common warnings (optional) setupConsoleFilters(); ``` -------------------------------- ### Install Monorepo Dependencies Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-settings/README.md Installs all necessary dependencies for the Ghost monorepo. This is a prerequisite for running development or testing commands. ```bash pnpm ``` -------------------------------- ### Manage Test Infrastructure Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Commands to start and stop the test infrastructure, including MySQL, Redis, Mailpit, and Tinybird. Use 'infra:up' to start and 'infra:down' to stop. ```bash pnpm infra:up ``` ```bash pnpm infra:down ``` -------------------------------- ### File Layout Example Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/contributing.mdx Illustrates the directory structure within the apps/shade/src/ folder. ```tree apps/shade/src/ ├── components/ │ ├── ui/ Generic controls + recipes │ ├── primitives/ Layout primitives (Stack, Inline, …) │ ├── patterns/ Product compositions (PageHeader, ListTable, …) │ └── posts-stats/ Interim shared between Posts and Stats ├── docs/ MDX + showcase stories rendered in Storybook ├── hooks/ Generic React hooks ├── lib/ Utilities (cn, formatters, chart helpers) └── providers/ Context providers ``` -------------------------------- ### Install Ghost CLI Globally Source: https://github.com/tryghost/ghost/blob/main/README.md Installs the Ghost Command Line Interface globally on your system. This tool is used for managing Ghost installations. ```bash npm install ghost-cli -g ``` -------------------------------- ### Start Ghost Core Dev Docker with S3 Storage Source: https://github.com/tryghost/ghost/blob/main/docker/ghost-dev/README.md Use this command to start the Docker backend and frontend development servers with MinIO S3-compatible object storage integration. ```bash pnpm dev:storage ``` -------------------------------- ### MSW API Testing Setup Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Leverage centralized MSW setup for API testing. Avoid manual handler setup. ```typescript // ✅ Good - Use centralized MSW setup const server = setupMswServer(); // ❌ Avoid - Manual MSW setup const server = setupServer(/* manual handlers */); ``` -------------------------------- ### Install Specific Ghost Version Source: https://github.com/tryghost/ghost/blob/main/ghost/core/test/utils/fixtures/export/README.md Installs a local version of Ghost using the specified version number. ```bash ghost install --version 3.0.0 ``` -------------------------------- ### Install Tinybird CLI Locally Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/README.md Installs the Tinybird CLI locally. Run this command once from the root folder of the Ghost repository. ```bash pnpm tb:install ``` -------------------------------- ### Start Ghost with Tinybird Analytics using Docker Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/README.md Starts the Ghost service and automatically configures it to use the bundled Tinybird and Analytics services. Access Ghost at http://localhost:2368. ```bash docker compose --profile split up ``` -------------------------------- ### Build Mode Setup and Test Execution Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Commands to set up the build environment, including building apps, Docker images, and running infra, followed by test execution in build mode. ```bash # From repository root pnpm build pnpm --filter @tryghost/e2e build:apps GHOST_E2E_BASE_IMAGE= pnpm --filter @tryghost/e2e build:docker GHOST_E2E_MODE=build pnpm --filter @tryghost/e2e infra:up # Run tests GHOST_E2E_MODE=build GHOST_E2E_IMAGE=ghost-e2e:local pnpm --filter @tryghost/e2e test ``` -------------------------------- ### Start Ghost Core Dev Docker with Analytics Source: https://github.com/tryghost/ghost/blob/main/docker/ghost-dev/README.md This command starts the Docker backend and frontend development servers, including support for Tinybird analytics. ```bash pnpm dev:analytics ``` -------------------------------- ### Setup Date Mocking and Get Date Range Source: https://github.com/tryghost/ghost/blob/main/apps/stats/test/utils/README.md Use setupDateMocking to ensure consistent test behavior by mocking the system date. GetExpectedDateRange calculates consistent date ranges for assertions. ```typescript import { setupDateMocking, getExpectedDateRange } from '../../utils/test-helpers'; beforeEach(() => { const dateMocking = setupDateMocking(); }); // Use consistent date ranges in assertions const { expectedDateFrom, expectedDateTo } = getExpectedDateRange(30); ``` -------------------------------- ### Install Node Inspector Source: https://github.com/tryghost/ghost/wiki/Node-inspector Install the node-inspector package globally using npm. ```bash npm install -g node-inspector ``` -------------------------------- ### Running Specific Tests Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Examples of how to run specific test files, tests matching a pattern, or run tests with the browser visible for debugging. ```bash # Specific test file pnpm test specific/folder/testfile.spec.ts # Matching a pattern pnpm test --grep "homepage" # With browser visible (for debugging) pnpm test --debug ``` -------------------------------- ### Define command-line arguments and help text Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/cli/README.md Optionally override the setup() method to define command-line arguments using sywac and provide help text. Arguments defined here are accessible in the handle() method via the argv object. ```javascript setup() { this.help('A brief explanation of what your command does, shown when the --help flag is used'); // arguments are passed to sywac - see https://sywac.io/docs/ this.argument('--color', {type: 'string', defaultValue: 'yellow'}); } ``` -------------------------------- ### App Configuration Example Source: https://github.com/tryghost/ghost/wiki/App-Ideas-Permissions Defines essential app data, including display name, identifier, description, API permissions, and certification details. This configuration is crucial for app activation and security. ```javascript { // App description displayname: 'Worpress Importer', identifier: 'wp-import' description: 'The Worpress Importer App ...', // App permissions permissions: { api.posts: ['create', 'edit'], api.settings: ['read'], helpers: ['create'] } // App certification checksum: certification: base64(signature( + date)) } ``` -------------------------------- ### Running E2E Tests and Development Environment Source: https://github.com/tryghost/ghost/blob/main/e2e/AGENTS.md Commands to start the development environment and run E2E tests. Ensure `pnpm dev` is running before executing tests. ```bash # Terminal 1 (or background): Start dev environment from the repo root pnpm dev # Wait for the admin dev server to be reachable (http://127.0.0.1:5174) # Terminal 2: Run e2e tests from the e2e/ directory pnpm test # Run all tests pnpm test tests/path/to/test.ts # Run specific test pnpm lint # Required after writing tests pnpm test:types # Check TypeScript errors pnpm build # Required after factory changes pnpm test --debug # See browser during execution, for debugging PRESERVE_ENV=true pnpm test # Debug failed tests (keeps containers) ``` -------------------------------- ### Admin Toolbar Development Commands Source: https://github.com/tryghost/ghost/blob/main/apps/admin-toolbar/README.md Run these commands to build, preview, or test the Admin Toolbar. 'pnpm dev' starts a watch server for development. ```bash pnpm build # one-off build pnpm dev # build + preview with watch (started automatically by pnpm dev from root) pnpm test # build + run tests against UMD bundle ``` -------------------------------- ### Install Juice2 for CSS Inlining Source: https://github.com/tryghost/ghost/wiki/HTML-email-template-generation Install the juice2 package globally using npm. This tool is recommended for in-lining CSS in HTML email templates. ```bash npm install -g juice2 ``` -------------------------------- ### Color Palette Example Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-design-system/src/docs/Colors.mdx Demonstrates how to use the ColorPalette and ColorItem components to display color swatches and their corresponding hex codes. This is useful for documenting color systems. ```javascript import { Meta, ColorPalette, ColorItem } from '@storybook/addon-docs/blocks';
# Colors

You'll find all the official Ghost colors and more in Tailwind, but here's a list of them in case you want to use them elsewhere.

``` -------------------------------- ### Typical Workflow for Analytics Management Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/scripts/README.md This sequence demonstrates a common workflow for setting up the analytics environment, generating data, and managing it. It includes starting the Docker environment, optionally resetting data, generating events, viewing stats, and clearing data. ```bash # 1. Start the Docker environment with analytics pnpm dev:analytics # 2. (Optional) Reset Ghost data if needed pnpm docker:reset:data # 3. Generate analytics data pnpm data:analytics:generate # 4. View analytics in Ghost admin # http://localhost:2368/ghost/#/stats # 5. Clear analytics when needed pnpm data:analytics:clear ``` -------------------------------- ### Automated Cleanup with MSW Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Utilize provided setup for automatic lifecycle management. Avoid manual cleanup procedures. ```typescript // ✅ Good - Use provided setup const server = setupMswServer(); // Handles lifecycle automatically // ❌ Avoid - Manual lifecycle management beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); ``` -------------------------------- ### Run Tests in Dev Environment Mode Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Starts the local admin dev server and then runs e2e tests. This mode is recommended for development. ```bash # Terminal 1: Start dev environment (from repository root) pnpm dev # Terminal 2: Run e2e tests (from e2e folder) pnpm test ``` -------------------------------- ### Example: api_top_pages Query Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/endpoints/README.md Demonstrates how to query top pages by joining hits with filtered sessions. Returns all pageviews from matching sessions. ```sql select post_uuid, pathname, uniqExact(session_id) as visits from _mv_hits h inner join filtered_sessions fs on fs.session_id = h.session_id ``` -------------------------------- ### Basic MSW API Mocking Setup Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Set up the Mock Service Worker server with all common Ghost API handlers. The server lifecycle is automatically managed, and common endpoints are pre-mocked. ```typescript import {setupMswServer} from '@tryghost/admin-x-framework/test/msw-utils'; // Set up MSW server with all common Ghost API handlers const server = setupMswServer(); describe('My Component', () => { // Server lifecycle is automatically managed // beforeAll, afterEach, afterAll are handled for you it('loads data from API', async () => { // Common endpoints like /config/, /settings/, /users/me/ are already mocked // Your test just works! }); }); ``` -------------------------------- ### CI-like Local Preflight Build Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Performs a local preflight check similar to CI, pulling necessary Docker images and starting the infrastructure in build mode. ```bash pnpm --filter @tryghost/e2e preflight:build ``` -------------------------------- ### Enable Corepack for pnpm Source: https://github.com/tryghost/ghost/blob/main/CLAUDE.md Ensures the correct pnpm version is used by enabling Corepack. Run this once before other setup commands. ```bash corepack enable pnpm ``` -------------------------------- ### Example Usage of ListPage and PageHeader Patterns Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/patterns-guide.mdx Demonstrates how to compose the ListPage and PageHeader patterns with components like Button and Table. This pattern is suitable for creating reusable list views across the application. ```tsx import {PageHeader, ListPage} from '@tryghost/shade/patterns'; import {Button, Table} from '@tryghost/shade/components'; Members{count} ...
``` -------------------------------- ### Setup PostAnalyticsProvider in Tests Source: https://github.com/tryghost/ghost/blob/main/apps/posts/test/utils/MSW_USAGE_GUIDE.md Use `setupPostAnalyticsProvider` to mock the analytics provider for a specific post ID in your tests. This ensures post data is available for the provider. ```typescript import {setupPostAnalyticsProvider} from '../utils/msw-helpers'; test('with analytics provider', () => { setupPostAnalyticsProvider('my-post-id'); // Provider will have post data available }); ``` -------------------------------- ### AAA Test Example Source: https://github.com/tryghost/ghost/blob/main/adr/0001-aaa-test-structure.md Demonstrates the Arrange-Act-Assert pattern in a test case. Use this structure to set up data, perform an action, and verify the outcome. ```typescript test('user can view their post', async ({ page }) => { // Arrange const user = await userFactory.create(); const post = await postFactory.create({ userId: user.id }); // Act await page.goto(`/posts/${post.id}`); // Assert await expect(page.getByText(post.title)).toBeVisible(); }); ``` -------------------------------- ### Example List Page Component Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/page-types.mdx Demonstrates the usage of the ListPage component from '@tryghost/shade/page-templates'. This snippet shows how to structure a list page with a header, optional view and filter bars, and a body that displays either content or an empty indicator. ```tsx import {ListPage} from '@tryghost/shade/page-templates'; import {PageHeader, ViewBar, FilterBar} from '@tryghost/shade/patterns'; import {Button, EmptyIndicator, Table} from '@tryghost/shade/components'; {/* Pass sticky={false} — ListPage.Header handles stickiness and blur */} Members{count} {/* optional */} {/* optional — auto-collapses when empty */} {items.length === 0 ? : ...
}
``` -------------------------------- ### Example JSON Result for api_top_pages Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/endpoints/README.md Illustrates the JSON output format for the `api_top_pages` endpoint, showing page paths and the number of matching sessions that visited them. ```json {"pathname":"/about/","visits":3} {"pathname":"/","visits":3} {"pathname":"/blog/hello/","visits":2} ``` -------------------------------- ### Basic Vitest Configuration Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Use this to create a default Vitest configuration for your project. It includes React support, jsdom environment, global test APIs, standard aliases, a setup file, and coverage reporting. ```typescript //vitest.config.ts import {createVitestConfig} from '@tryghost/admin-x-framework/test/vitest-config'; export default createVitestConfig(); ``` -------------------------------- ### Create and Customize MSW Server with Handlers and Fixtures Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Set up a mock server using `createMswServer` from `@tryghost/admin-x-framework/test/msw-utils`. You can add custom handlers or override default ones, and leverage provided fixtures for realistic data. ```typescript import {createMswServer, handlers, fixtures} from '@tryghost/admin-x-framework/test/msw-utils'; import {http, HttpResponse} from 'msw'; // Create server with additional custom handlers const server = createMswServer([ // Add your own custom handlers http.get('/custom/endpoint/', () => { return HttpResponse.json({custom: 'data'}); }), // Override default handlers http.get('/ghost/api/admin/config/', () => { return HttpResponse.json({ ...fixtures.config, version: '6.x' // Custom version }); }) ]); ``` -------------------------------- ### AAA Pattern in E2E Tests Source: https://github.com/tryghost/ghost/blob/main/e2e/AGENTS.md Example demonstrating the Arrange, Act, Assert (AAA) pattern in a test case. Uses page objects and factories for setup. ```typescript test('action performed - expected result', async ({page}) => { const analyticsPage = new AnalyticsGrowthPage(page); const postFactory = createPostFactory(page.request); const post = await postFactory.create({status: 'published'}); await analyticsPage.goto(); await analyticsPage.topContent.postsButton.click(); await expect(analyticsPage.topContent.contentCard).toContainText('No conversions'); }); ``` -------------------------------- ### Playwright Test Example Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md An example of a Playwright test written in TypeScript, demonstrating the Arrange-Act-Assert pattern for testing the Ghost homepage. ```typescript test.describe('Ghost Homepage', () => { test('loads correctly', async ({page}) => { // ARRANGE - setup fixtures, create helpers, prepare things that helps will need to be executed const homePage = new HomePage(page); // ACT - do the actions you need to do, to verify certain behaviour await homePage.goto(); // ASSERT await expect(homePage.title).toBeVisible(); }); }); ``` -------------------------------- ### Build Production Bundle Source: https://github.com/tryghost/ghost/blob/main/apps/admin/README.md Execute this command to build the production bundle for the Ghost Admin application. The output is placed in `apps/admin/dist/`. ```bash pnpm nx run @tryghost/admin:build ``` -------------------------------- ### Commit Message Format Example Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/contributing.mdx Example of the required commit message format, including a reference to an issue tracker and a description of the changes. ```git Added Avatar component ref https://linear.app/ghost/issue/DES-1234/avatar Builds on Radix Avatar with a size variant scale and a fallback initials slot. ``` -------------------------------- ### Start Node Debugger Source: https://github.com/tryghost/ghost/wiki/Node-inspector Run the node-debugger command in a separate terminal to start the debugging session. Use the --port flag if the default port is in use. ```bash node-debugger --port=#### ``` -------------------------------- ### Build Production Bundle Source: https://github.com/tryghost/ghost/blob/main/apps/portal/README.md Create a production-ready minified bundle of the Portal script. The output file will be located at umd/portal.min.js. ```bash pnpm build ``` -------------------------------- ### Post-Specific Analytics Endpoints Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/server/data/tinybird/ARCHITECTURE.md Get detailed analytics for individual posts, including performance, growth, and referrers. ```APIDOC ## GET /stats/posts/:id/stats ### Description Retrieves overall performance statistics for a specific post. ### Method GET ### Endpoint /stats/posts/:id/stats ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **date_from** (string) - Optional - Start date for filtering. - **date_to** (string) - Optional - End date for filtering. - **limit** (integer) - Optional - Maximum number of results to return. - **order** (string) - Optional - Field and direction to sort results. ### Response #### Success Response (200) - **data** (object) - Performance statistics for the post. - **meta** (object) - Metadata including totals. ``` ```APIDOC ## GET /stats/posts/:id/growth ### Description Retrieves member attribution data for a specific post. ### Method GET ### Endpoint /stats/posts/:id/growth ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **date_from** (string) - Optional - Start date for filtering. - **date_to** (string) - Optional - End date for filtering. - **limit** (integer) - Optional - Maximum number of results to return. - **order** (string) - Optional - Field and direction to sort results. ### Response #### Success Response (200) - **data** (object) - Member attribution data for the post. - **meta** (object) - Metadata including totals. ``` ```APIDOC ## GET /stats/posts/:id/top-referrers ### Description Retrieves a breakdown of top referrers for a specific post. ### Method GET ### Endpoint /stats/posts/:id/top-referrers ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **date_from** (string) - Optional - Start date for filtering. - **date_to** (string) - Optional - End date for filtering. - **limit** (integer) - Optional - Maximum number of results to return. - **order** (string) - Optional - Field and direction to sort results. ### Response #### Success Response (200) - **data** (object) - Top referrers for the post. - **meta** (object) - Metadata including totals. ``` -------------------------------- ### Fix Content Folder Permissions Source: https://github.com/tryghost/ghost/blob/main/ghost/core/test/utils/fixtures/export/README.md Changes ownership of the content folder to the current user, which is necessary for local setup. ```bash sudo chown -R $USER:$USER content ``` -------------------------------- ### Conditional Endpoint Overrides Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Override specific API endpoints when necessary. Avoid recreating the entire server setup. ```typescript // ✅ Good - Override specific endpoints server.use(createErrorHandler('put', '/api/endpoint/', 500)); // ❌ Avoid - Recreating entire server setup ``` -------------------------------- ### Storybook and Build Commands Source: https://github.com/tryghost/ghost/blob/main/apps/shade/AGENTS.md Common commands for running Storybook, building the library, exporting static Storybook, and running tests and linters. ```bash pnpm storybook pnpm build pnpm build-storybook pnpm test pnpm test:unit pnpm test:types pnpm lint ``` -------------------------------- ### Build All Packages Source: https://github.com/tryghost/ghost/blob/main/AGENTS.md Build all packages in the monorepo. Nx handles dependency management during the build process. ```bash pnpm build # Build all packages (Nx handles dependencies) pnpm build:clean # Clean build artifacts and rebuild ``` -------------------------------- ### Analytics Development Flow Source: https://github.com/tryghost/ghost/blob/main/e2e/README.md Commands for running analytics development, including starting the analytics dev server and running analytics tests. ```bash # Terminal 1 (repo root) pnpm dev:analytics # Terminal 2 pnpm test:analytics ``` -------------------------------- ### Clone Ghost Repository and Configure Remotes Source: https://github.com/tryghost/ghost/blob/main/docs/README.md Clone your forked Ghost repository and set up upstream and origin remote configurations. Ensure you use `--recurse-submodules` to include all necessary submodules. ```bash git clone --recurse-submodules git@github.com:/Ghost.git cd Ghost # Configure remotes git remote rename origin upstream git remote add origin git@github.com:/Ghost.git ``` -------------------------------- ### Run Ghost Core Unit Tests in Watch Mode Source: https://github.com/tryghost/ghost/blob/main/CLAUDE.md Starts a watch mode for ghost/core unit tests, re-running them on file changes. ```bash cd ghost/core pnpm test:watch ``` -------------------------------- ### Page Object Structure Example Source: https://github.com/tryghost/ghost/blob/main/e2e/AGENTS.md Illustrates the structure of a Page Object class, including public readonly locators and semantic action methods. ```typescript export class AnalyticsPage extends AdminPage { // Public readonly locators only public readonly saveButton = this.page.getByRole('button', {name: 'Save'}); public readonly emailInput = this.page.getByLabel('Email'); // Semantic action methods async saveSettings() { await this.saveButton.click(); } } ``` -------------------------------- ### Using Recipes in Components Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/recipes-guide.mdx Demonstrates two ways to apply recipe class strings: calling the recipe function for common cases and composing static atoms for edge cases where Tailwind needs to detect classes. ```tsx import {cn} from '@/lib/utils'; import {inputSurface, inputSurfaceClasses} from './input-surface'; // Common case — call the function // Edge case — compose atoms statically so Tailwind can detect them
``` -------------------------------- ### Importing Shade Components Source: https://github.com/tryghost/ghost/blob/main/apps/shade/src/docs/contributing.mdx Demonstrates how to import components and utilities from different layers of the Shade library using specific subpaths. ```typescript import {Button} from '@tryghost/shade/components'; import {Stack} from '@tryghost/shade/primitives'; import {PageHeader} from '@tryghost/shade/patterns'; import {cn} from '@tryghost/shade/utils'; ``` -------------------------------- ### Render Components and Hooks with Providers Source: https://github.com/tryghost/ghost/blob/main/apps/admin-x-framework/src/test/README.md Utilize `renderWithProviders` and `renderHookWithProviders` from `@tryghost/admin-x-framework/test/test-utils` to render components and hooks with necessary context and providers. You can also provide a custom `QueryClient` or framework-specific props. ```typescript import {renderWithProviders, renderHookWithProviders, createTestQueryClient} from '@tryghost/admin-x-framework/test/test-utils'; // Render components with all necessary providers const {getByText} = renderWithProviders(); // Render hooks with providers const {result} = renderHookWithProviders(() => useMyHook()); // Custom QueryClient for specific tests const queryClient = createTestQueryClient(); renderWithProviders(, {queryClient}); // Custom framework props renderWithProviders(, { frameworkProps: { ghostVersion: '4.x' } }); ``` -------------------------------- ### Build Docker Images Source: https://github.com/tryghost/ghost/blob/main/CLAUDE.md Builds the Docker images required for the Ghost development environment. ```bash pnpm docker:build ``` -------------------------------- ### Test Data Factory Usage Source: https://github.com/tryghost/ghost/blob/main/e2e/AGENTS.md Example of using factories to create test data, such as posts and users, for E2E tests. Requires importing factories. ```typescript import {PostFactory, UserFactory} from '../data-factory'; const postFactory = createPostFactory(page.request); const post = await postFactory.create({userId: user.id}); ``` -------------------------------- ### Get masked user input Source: https://github.com/tryghost/ghost/blob/main/ghost/core/core/cli/README.md Securely prompt the user for sensitive information, such as passwords, by masking the input as it's typed. The entered value is returned. ```javascript const password = await this.secret('Password:'); this.log(`Your password is: ${password}`); ``` -------------------------------- ### Build e2e Package Source: https://github.com/tryghost/ghost/blob/main/e2e/data-factory/README.md Builds the e2e package, which includes the data-factory. Navigate to the e2e directory before running. ```bash cd e2e && pnpm build ``` -------------------------------- ### Implement New Factory Class Source: https://github.com/tryghost/ghost/blob/main/e2e/data-factory/README.md Example of creating a new factory class by extending the base `Factory` class. Requires implementing `build()` and setting `entityType`. ```typescript import {Factory} from '../factory'; export class MemberFactory extends Factory, Member> { entityType = 'members'; build(options: Partial = {}): Member { return { id: generateId(), email: options.email || faker.internet.email(), name: options.name || faker.person.fullName(), // ... more fields }; } } ``` -------------------------------- ### Run CLI Tests with Watching Build Source: https://github.com/tryghost/ghost/blob/main/ghost/admin/README.md Run tests using the watching build. The '--reporter dot' option displays a dot for successful tests and 'F' for failed tests, rendering only the output of failed tests. ```bash TZ=UTC pnpm test 1 --reporter dot --path="dist-test" ```