TypeSlayer Documentation

repository·main·Indexed 20 days ago

https://github.com/dimitropoulos/typeslayer

A diagnostic tool for identifying and fixing TypeScript performance problems. TypeSlayer analyzes TypeScript types to optimize redundant definitions and provides interactive visualizations, such as treemaps and force graphs, to help developers locate compilation and type-checking bottlenecks. It includes a CLI for analysis and a specialized `@typeslayer/validate` package for validating TypeScript compiler output files, including trace.json, types.json, and CPU profile data.

Tokens
37.3K
Snippets
141
Records
202
Agent score
70%

What's inside TypeSlayer

  1. What is the Type Graph feature?

    main

    The Type Graph is a feature that combines types.json output with trace.json information to create a list of relations between all types in a project. It compiles statistics such as "biggest union" and "most commonly included in an intersection".

    Note: This feature is currently only available in the Rust version of the tool.

  2. Data sensitivity and privacy

    main
    TypeSlayer trace files contain only information about the types in your code, not the actual source code itself. The data is stored as plaintext JSON. The only potentially sensitive information is the file paths of your source files and the names of your types.
  3. Understand TypeSlayer's approach to 3rd party types

    main

    TypeSlayer is designed for holistic performance diagnosis. When analyzing type performance, it is recommended not to filter out 3rd party dependencies (e.g., by using skipLibCheck in tsconfig.json).

    Because dependencies are part of your total build, their type complexity contributes to your project's overall type-checking performance. Treating them as separate from "your code" can lead to inaccurate performance profiles.

  4. Why types appear as `<anonymous>`

    main

    In the TypeSlayer UI, <anonymous> is used as a placeholder for types that do not have a formal name in the TypeScript trace.

    This most commonly occurs with:

    • Inlined literal types: For example, in type Colors = ["red", "green", "blue"], the individual string literals are anonymous types unless explicitly named (e.g., type Red = "red").
    • Template literal types: Currently, TypeScript does not record display values for template literal types in trace files, so TypeSlayer cannot always "spell" them out and falls back to <anonymous>.
  5. Understand analysis output features

    main

    The analyzer identifies several types of issues within your TypeScript compilation process:

    • Hot Spot Detection: Identifies events that consumed the most time during compilation. These are flagged as intensive areas worth investigating.
    • Duplicate Package Detection: Finds package versions appearing in multiple locations from the same package, which can cause unexpected behavior.
    • Unterminated Events: Flags events that were created by TypeScript's trace machinery but never terminated, which is a symptom of underlying issues.
    • Depth Limits: Identifies specific type-level limits hit during type checking (see Depth Limits Reference).
  6. Quickstart with TypeSlayer

    main

    To diagnose and fix TypeScript performance problems, run TypeSlayer in the root directory of the package you want to inspect (the directory containing your package.json).

    TypeSlayer will automatically:

    1. Start a local web UI.
    2. Execute TypeScript tooling to generate traces and CPU profiles.
    3. Provide interactive visualizations, including treemaps, force graphs, and speedscope/perfetto views, to help you identify performance bottlenecks.
    npx typeslayer
  7. How to start analyzing with TypeSlayer

    main

    If you are unsure where to begin your performance or type analysis, follow these investigative steps:

    1. Identify the problem scope: Gather evidence across multiple environments (e.g., local editor slowness, CI slowness, and tsc command-line slowness) to confirm the issue is systemic.
    2. Check the Treemap: Look for outlier rectangles that are significantly larger than others. Note that these files might be the importers of the problematic files rather than the source of the type issue.
    3. Inspect Perfetto (Flamegraphs): Look for large 'spans' (boxes) that dominate the graph. If you find a specific type causing issues, identify its ID in args under sourceId or targetId, then use the Search module to investigate that ID.
    4. Identify 'Award Winners': Look for type metrics or relation metrics with large red bars underneath, which indicate relative scale. Focus on unions or types that are considerably larger than the rest of the set, or types where @ts-ignore/@ts-expect-error are being used to bypass limits.
    5. Consult TypeScript Docs: If conceptually lost, refer to TypeScript's official documentation on performance tracing.
  8. Local Development Workflow

    main

    To develop and test the Analytics Worker locally:

    1. Start the Worker

    Run the development server (includes persistence):

    pnpm dev

    This typically runs on http://localhost:8787.

    2. Test Ingestion

    Send a test event to the local endpoint:

    curl -X POST http://localhost:8787/collect \
      -H "Content-Type: application/json" \
      -d '{
        "name": "test_event",
        "sessionId": "test-123",
        "timestamp": 1735318800000,
        "version": "0.1.0",
        "platform": "test",
        "mode": "CLI",
        "data": {"foo": "bar"}
      }'

    3. Query Local Data

    Inspect the local D1 database to verify the event was stored:

    pnpm wrangler d1 execute typeslayer --local --command="SELECT * FROM events"
    pnpm dev
  9. Initial Setup for TypeSlayer Analytics Worker

    main

    Follow these steps to set up the Analytics Worker with a Cloudflare D1 database.

    1. Identify your D1 Database ID

    Run the following command in packages/analytics to find your typeslayer database UUID:

    pnpm wrangler d1 list

    2. Configure wrangler.jsonc

    Update wrangler.jsonc with your database UUID in the d1_databases section:

    {
      "name": "typeslayer-analytics",
      "main": "src/index.ts",
      "compatibility_date": "2024-12-01",
      "routes": ["https://analytics.typeslayer.dev/collect"],
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "typeslayer",
          "database_id": "YOUR_UUID_HERE"
        }
      ],
      "vars": {
        "REQUIRE_INGESTION_SECRET": "0"
      }
    }

    3. Apply Migrations

    Create the necessary tables (including the events table) using the provided migration scripts.

    • Local development: pnpm migrate:local
    • Production (remote): pnpm migrate:apply

    4. Verify Setup

    Confirm the events table exists by querying the database:

    pnpm wrangler d1 execute typeslayer --remote --command="SELECT name FROM sqlite_master WHERE type='table'"
    pnpm migrate:apply
  10. Generate a TypeScript compiler trace

    main

    Before using @typeslayer/analyze-trace, you must generate a trace file from the TypeScript compiler (tsc). Use the --generateTrace flag followed by the desired output path.

    tsc --generateTrace ./trace-json-path
  11. Configure Ingestion Authentication

    main

    To prevent unauthorized event ingestion in production, you can enable a secret key requirement.

    1. Set the Secret

    Use Wrangler to store a strong random string as the INGESTION_SECRET:

    pnpm wrangler secret put INGESTION_SECRET

    2. Enable Requirement in Config

    In wrangler.jsonc, set REQUIRE_INGESTION_SECRET to "1":

    "vars": {
      "REQUIRE_INGESTION_SECRET": "1"
    }

    3. Use the Secret in Requests

    All POST requests must now include the X-Typeslayer-Analytics-Key header:

    curl -X POST http://localhost:8787/collect \
      -H "Content-Type: application/json" \
      -H "X-Typeslayer-Analytics-Key: your-secret-here" \
      -d '{"name":"test", ...}'
    pnpm wrangler secret put INGESTION_SECRET