Contributor Playbook & MDX Elements

This page is the living documentation for maintaining and expanding CSPrimer. It serves seven key functions:

  1. Local Scaffolding Tools: One-click visual dashboard and terminal CLI to generate courses, roadmaps, and articles.
  2. Metadata Architecture: Clear rules for how Categories, Series, and Roadmaps relate.
  3. Complete Schemas & Type Reference: Exhaustive specifications of all collection schemas, allowed values, and TypeScript types.
  4. Interactive Component Showcase: Live preview, props reference, and copy-pasteable snippets for custom MDX components.
  5. Algorithm Visualizer Playbook & AI Prompt Template: Copy-pasteable prompt and architecture guide to generate visualizers for any Java DSA problem using LLMs.
  6. Infrastructure, Hosting & Deployment Architecture: Production setup across Vercel, Cloudflare DNS, Cloudinary CDN, and domain canonicalization.
  7. Performance & Scale Engineering: Micro-chunking for 500+ visualizers, memory leak prevention under ViewTransitions, and build optimizations.

1. Automated Local Scaffolding

To eliminate tedious manual JSON updates and frontmatter mistakes, use our local scaffolding tools:

Visual Content Studio (npm run admin)

Run the local Dev Studio dashboard alongside your Astro dev server:

npm run admin

Open http://localhost:4322 in your browser.

  • Tab 1: Course Series Cards: Interactive card grid of all 45 courses to set status (🟢 Live, ⏳ In Progress, 🔒 Planned, 🔁 Revisiting), and edit details (title, description, time, weight).
  • Tab 2: Syllabus & Lessons: Organize chapters and lessons with ▲/▼ reordering, accurate status toggles, and detection of unassigned files on disk.
  • Tab 3: Create Lesson / Project: Smart switcher between Course Lesson (category strictly locked to course track), Hands-on Project (surfaced on /articles), and Standalone Deep Dive.
  • Tab 4: Reorder Roadmaps: Visual track manager with ▲ Up and ▼ Down buttons to reorder courses along learning paths, plus a 1-click Sync Weights to Courses button.
  • Tab 5: New Series: Form to scaffold a new course series and register it into roadmapOrder.json.
  • Tab 6: All Articles Explorer: Instant real-time search across all 300+ articles with track filtering and 1-click draft toggling.
  • Tab 7: Interview Bytes: Manage flashcard-style interview questions with syntax-highlighted code and topic filters.
  • Tab 8: Shorts Studio: Manage YouTube Shorts and micro-learning video explainers.
  • Tab 9: Images & WebP: Convert local source images to WebP and upload to Cloudinary.
  • Tab 10: Problems Studio: Full code editors, registries, and 1-click article tag inserters for interactive code exercises.

2. Architecture & Metadata Rules

The Core Hierarchy

The platform organizes content in a 3-tier hierarchy:

Category (Track) ➔ Series (Course) ➔ Articles (Lessons)

LevelWhere ConfiguredPurpose
1. Category / Tracksrc/config/roadmapOrder.jsonTop-level learning domain (Core-CS, DSA, Development, System-Design, AI-Engineering).
2. Series / Coursesrc/content/series/<id>.jsonStructured course with a syllabus (navbar). Defines "category": "<Track>".
3. Lessonssrc/content/articles/<slug>.mdThe actual educational lessons. Linked via series: "<id>".
Standalone Articlessrc/content/articles/<slug>.mdIndependent tutorials or build projects. Omit series; categorized via categories: [...].

Important Metadata Rules

  1. Course Lessons (series is set):
    • When an article has series: "docker", its learning category is inherited directly from the parent course.
    • Lessons are grouped in the course syllabus and do not clutter the general /articles project listing.
  2. Standalone Articles (series is omitted):
    • Must specify categories using one or more of the 5 canonical categories below.
    • These are surfaced on /articles (Projects & Deep Dives).
  3. The 5 Canonical Categories:
    • "Core-CS": Operating systems, computer networks, computer architecture, databases, compilers.
    • "DSA": Data structures, algorithms, complexity analysis, interview problem sets.
    • "Development": Frontend, backend, fullstack frameworks, APIs, databases, tooling.
    • "System-Design": Distributed systems, microservices, cloud architectures, scalability.
    • "AI-Engineering": Machine learning, LLM integrations, embeddings, AI agents.

3. Step-by-Step Creation Playbooks

Adding a Standalone Article or Project

Use this for single-topic deep dives, project write-ups, or tutorials that do not belong to a sequential course syllabus.

Step 1: Create the markdown or MDX file

Create src/content/articles/<your-article-slug>.md (or .mdx if using custom components).

Step 2: Add Frontmatter

Important: Do not add the series key for standalone articles.

---
title: "Building an LRU Cache from Scratch in TypeScript"
description: "Learn cache eviction policies by implementing a doubly linked list + hash map cache."
categories: ["Development"]
author: "Arjit Sharma"
draft: false
featured: false
---

Step 3: Write Content

Write in standard Markdown or import MDX components (e.g. <Notice>, <Badge>, <Accordion>).


4. Complete Schemas & Type Reference

This section provides the static field definitions, types, defaults, and allowed values for every content collection defined in src/content/config.ts.

4.1 Articles Collection Schema

Location: src/content/articles/*.md or *.mdx
Purpose: Standalone articles, project tutorials, and course lessons.

FieldTypeRequiredDefaultAllowed Values / ConstraintsDescription
titlestringYes—Non-empty stringArticle title shown in headings and cards
subtitlestringNoundefinedAny stringSecondary subhead for lessons or deep dives
meta_titlestringNoundefinedString (≤ 60 chars recommended)SEO <title> tag override
descriptionstringNoundefinedString (≤ 160 chars recommended)Meta and OpenGraph description
imagestringNoundefinedRelative path (e.g. /images/og-image.jpg)Card thumbnail and social share preview
authorstringNoundefinede.g. "Arjit Sharma"Content author
seriesstringNoundefinedFilename of series in src/content/series/Links lesson to a course. Omit for standalone articles
categoriesstring[]No["others"]Core-CS, DSA, Development, System-Design, AI-EngineeringSubject classification tag
draftbooleanNofalsetrue, falseExcludes article from production builds when true
yearnumberNoundefined4-digit year (e.g. 2025)Publishing / revision year
featuredbooleanNofalsetrue, falseHighlighted in hero card carousel

TypeScript Interface

export interface ArticleFrontmatter {
  title: string;
  subtitle?: string;
  meta_title?: string;
  description?: string;
  image?: string;
  author?: string;
  series?: string;
  categories: ("Core-CS" | "DSA" | "Development" | "System-Design" | "AI-Engineering" | "others")[];
  draft?: boolean;
  year?: number;
  featured?: boolean;
}

4.2 Series / Course Collection Schema

Location: src/content/series/<course-id>.json
Purpose: Course metadata, syllabus chapters, and sidebar navigation hierarchy.

FieldTypeRequiredDefaultAllowed Values / ConstraintsDescription
titlestringYes—Non-empty stringCourse display title
subtitlestringNoundefinedAny stringCourse tagline
descriptionstringYes—Any stringCourse summary on course overview cards
imagestringNoundefinedPath to thumbnailCover banner image
categorystringNo"Course""Core-CS", "DSA", "Development", "System-Design", "AI-Engineering"Learning track bucket
statusstringNoundefined'planned', 'in-progress', 're-visiting'Global course progress status (replaces legacy ongoing)
ongoingboolean | stringNofalsetrue, false(Deprecated) Replaced by status: "re-visiting" / "in-progress"
timestringNoundefinede.g. "4 hours", "12 lessons"Estimated completion time
weightnumberNo100IntegerSort weight (lower appears first)
navbarArray<Section>Yes—Array of syllabus sectionsOrdered chapters and lesson links (see below)
resourcesArray<Resource>No[]Array of supplementary referencesSpecial “Further Learnings & Resources” section shown exclusively on individual course pages; excluded from roadmaps

Each section inside navbar contains:

  • subheading: string (e.g. "1. Foundations")
  • link: Array of lesson links:
    • type: "articles" | "external"
    • url: string (article slug in src/content/articles/ without .md, or external URL)
    • title: string (lesson title)
    • status: 'planned' | 'in-progress' | 're-visiting' (optional; 'planned' displays a lock icon)

Resources Structure (resources)

Special section for supplementary external courses, official docs, books, or handwritten notes.

  • Where it appears: Exclusively on /courses/[course].
  • Roadmap exclusion: Excluded from roadmaps, drawer checklists, and completion percentages.
  • Editable in Studio: Tab 2 of npm run admin allows 1-click adding, editing, reordering, and saving.
  • Each entry contains:
    • title: string (e.g. "Alex Aiken - Stanford lectures")
    • url: string (External URL https://... or internal article path /articles/<slug>)
    • description: string (optional note or caption)

TypeScript Interface

export type CourseStatus = 'planned' | 'in-progress' | 're-visiting';

export interface SeriesNavbarLink {
  type: 'articles' | 'external';
  url: string;
  title: string;
  status?: CourseStatus;
}

export interface SeriesNavbarSection {
  subheading: string;
  link: SeriesNavbarLink[];
}

export interface CourseResource {
  title: string;
  url: string;
  description?: string;
}

export interface SeriesData {
  title: string;
  subtitle?: string;
  description: string;
  image?: string;
  category: string;
  ongoing?: boolean | string;
  status?: CourseStatus;
  time?: string;
  weight: number;
  navbar: SeriesNavbarSection[];
  resources?: CourseResource[];
}

4.3 Shorts Collection Schema

Location: src/content/shorts/<series>/<slug>.md
Purpose: Bite-sized video explainers and quick reference concepts.

FieldTypeRequiredDefaultDescription
titlestringYes—Title of the short
youtubeIdstringYes—11-character YouTube video ID (e.g. LbeV3TwK48s)
seriesstringYes—Series slug folder identifier (e.g. "oci-shorts")
seriesNamestringYes—Human-readable series title (e.g. "Oracle Cloud")
ordernumberNo0Progression sequence number within the shorts series

4.4 Interview Questions Schema

Location: src/content/interview-questions/<topic>.yaml
Purpose: Structured questions and answers powering Interview Bytes and Anki flashcard modal.

Root YAML property: questions: Array<InterviewQuestion>

FieldTypeRequiredDefaultDescription
idstring | numberYes—Unique numeric or string question ID
questionstringYes—The interview question text
answerstring[]Yes—Array of strings (rendered as bullet points or paragraphs)
codestringNoundefinedOptional code snippet or execution example
tagsstring[]No[]Category & topic filter tags (e.g. [javascript, async])
datedateNoundefinedDate added / updated
related_imagesstring[]No[]Asset paths relative to /src/assets/

4.5 TryCode Problem Schema

Location: src/problems/frontend/<problem-id>.ts
Purpose: Browser-based interactive JavaScript/TypeScript coding exercises.

FieldTypeRequiredDefaultAllowed Values / Description
idstringYes—Unique problem ID (must match filename)
titlestringYes—Problem title shown in the editor header
starterCodestringYes—Initial code stub provided to the student
testsTestCase[]Yes—Array of { input: any[], expected: any, customCheck?: string } test cases
modestringNo"function""function" (pure JS algorithm) or "dom" (interactive DOM manipulation)
htmlstringNo""Initial DOM markup for "dom" mode problems

TypeScript Interface

export interface TestCase {
  input: any[];
  expected: any;
  customCheck?: string; // JavaScript function string returning boolean or value
}

export interface Problem {
  id: string;
  title: string;
  mode?: "function" | "dom";
  starterCode: string;
  tests: TestCase[];
  html?: string;
}

4.6 Pages Collection Schema

Location: src/content/pages/*.md or *.mdx
Purpose: Standalone regular site pages (e.g. /about, /elements, /changelog).

FieldTypeRequiredDefaultDescription
titlestringYes—Page title
descriptionstringNoundefinedPage SEO description

5. Interactive MDX Component Catalog

All components below are auto-imported and immediately available in any .mdx file without manual import statements.

5.1 Notice Callouts (<Notice>)

Use callout boxes to draw attention to notes, best practices, tips, or critical warnings.

note

Note Callout: Use for contextual details, background information, or general notes.

tip

Tip Callout: Use for performance optimizations, helpful hints, or time-saving shortcuts.

info

Info Callout: Use for important informational updates or reference links.

warning

Warning Callout: Use for caveats, breaking changes, or restrictions (e.g., frontend-only constraints).

Usage Code

<Notice type="note">This is a note callout.</Notice>
<Notice type="tip">This is a helpful tip.</Notice>
<Notice type="info">This is an informational announcement.</Notice>
<Notice type="warning">This is a critical warning.</Notice>

5.2 Badges (<Badge>)

Inline status indicators for feature updates, changelogs, or requirements.

addedchangedremovedsecurity

Usage Code

<Badge type="added">added</Badge>
<Badge type="changed">changed</Badge>
<Badge type="removed">removed</Badge>
<Badge type="security">security</Badge>

5.3 Buttons (<Button>)

Styled call-to-action buttons for links, documentation, or resource downloads.

Usage Code

<Button href="/roadmaps" style="solid">Explore Roadmaps</Button>
<Button href="/courses" style="outline">Browse Courses</Button>

5.4 Accordions (<Accordion>)

Expandable accordion container for FAQs, solutions, or deep-dive collapsible explanations.

When should I use a Series instead of a Standalone Article?

Create a Series when:

  • The content consists of multiple sequential lessons or chapters.
  • You need a persistent sidebar navigation and previous/next chapter progression.
  • The course belongs to a categorized learning path on /roadmaps.

Create a Standalone Article when:

  • It is a single project, quick tutorial, or independent deep dive.
  • It does not require a sidebar syllabus.
How do I mark a lesson as planned/locked in a course?

In src/content/series/<id>.json, set "status": "planned" on the link object:

{
  "type": "articles",
  "url": "distributed-consensus",
  "title": "Distributed Consensus (Raft & Paxos)",
  "status": "planned"
}

This displays the lesson with a lock icon and disables navigation until it is published.

Usage Code

<Accordion title="Your Accordion Title Here">
  Your collapsible explanation, code snippets, or list items go here.
</Accordion>

5.5 Tabs (<Tabs> & <Tab>)

Clean multi-panel switcher for tabbed content (e.g. comparing languages, alternatives, or multi-step flows).

interface User {
  id: string;
  name: string;
  role: "admin" | "engineer";
}

const user: User = { id: "1", name: "Arjit", role: "engineer" };

Usage Code

<Tabs>

<Tab name="Tab 1">
Content for tab 1...
</Tab>

<Tab name="Tab 2">
Content for tab 2...
</Tab>

</Tabs>

5.6 Interactive TryCode Runner (<TryCode>)

Live, in-browser Monaco-based code editor and test runner for frontend JavaScript and DOM interview drills.

Deduplicate Cart Items While Preserving Order

Props Reference

PropTypeRequiredDefaultDescription
problemIdstringYes—Unique problem ID corresponding to a file in src/problems/frontend/<id>.ts

Usage Code

<!-- Function Mode (Pure JavaScript algorithms) -->
<TryCode problemId="array-unique" />

<!-- DOM Mode (Interactive UI & DOM manipulation) -->
<TryCode problemId="counter-dom" />

5.7 Video & YouTube Embeds (<Youtube> & <Video>)

Responsive 16:9 media embeds with lazy loading.

Usage Code

<!-- YouTube Embed (Responsive 16:9) -->
<Youtube id="uzR3VB1kfMw" title="Introduction to Distributed Systems" />

<!-- Local or Remote HTML5 Video -->
<Video src="https://joy1.videvo.net/videvo_files/video/free/video0467/large_watermarked/_import_61516692993d77.04238324_preview.mp4" title="System Demo" />

5.8 Algorithm Visualizer (<AlgoVisualizer>)

Interactive step-by-step algorithm visualizer supporting arrays, hash maps, sets, queues, deques, stacks, trees, heaps, linked lists, and DP tables with variable tracking and execution timeline controls.

Sample: Binary Search

Demonstrates halving the search space using low, mid, and high pointers along with an active subarray window bounding the candidate range.

Initialize Search Space

low: 0
high: 9
target: 23

Target is 23. The search interval is initially the entire array [0..9].

$ int low = 0, high = nums.length - 1;
nums[]
low
2
[0]
5
[1]
8
[2]
12
[3]
16
[4]
23
[5]
38
[6]
56
[7]
72
[8]
high
91
[9]
Window: [0..9]
Step 1 of 7
Speed

Props Reference

PropTypeRequiredDefaultDescription
problemIdstringYes—Unique problem ID corresponding to a file in src/problems/algorithms/<slug>.ts

Usage Code

<!-- Binary Search Visualization -->
<AlgoVisualizer problemId="sample-binary-search" />

<!-- Two Sum Array + Hash Map Visualization -->
<AlgoVisualizer problemId="02-two-sum" />

[!TIP] For the complete specification, step builder API, and AI prompt template to generate new DSA visualizers, see Section 7: Algorithm Visualizer Guide.


5.9 Interactive Git Visualizer (<GitVisualizer>)

Interactive visualizer demonstrating Git internals, staging phases, commit graphs, branch pointers, merges, rebases, and conflict resolutions.

Git Basic Workflow

Step 1 of 4: Initialize Repository
1 / 4
💻 Working Tree Disk Files

Active workspace where files are created & edited.

✓ Working tree clean
📦 Staging Area Index

Prepared files staged via git add.

✓ No files staged
🏛️ Git Repository .git / HEAD

Immutable snapshots created via git commit.

No commit snapshots yet
$ git init

Creates a new Git repository and sets up the internal .git database for tracking files.

Props Reference

PropTypeRequiredDefaultDescription
scenariostringYes—Scenario identifier from src/visualizations/git/scenarios.ts
titlestringNoScenario titleCustom display title override in header

Complete Supported Scenarios Catalog

Scenario IDTopicDefault View
intro-phasesThree Phases of Git Contentstages
intro-branchesBranches: Parallel Workflowsgraph
basic-workflowGit Basic Workflow (Modify $\rightarrow$ Stage $\rightarrow$ Commit)stages
diff-stagesInspecting Changes (git diff vs git diff --staged)stages
cloningRepository Cloninggraph
branchingBranch Creation & Switchinggraph
detached-headDetached HEAD Stategraph
merge-fast-forwardFast-Forward Mergegraph
merge-3way3-Way Recursive Merge Snapshotgraph
cherry-pickCherry-Picking Commitsgraph
merge-conflictResolving Merge Conflictsspecial
stashingGit Stashing Workspace Statestages
stash-stackManaging Multiple Stashes (LIFO Stack)stages
reset-modesGit Reset Comparison Matrix (Soft vs Mixed vs Hard)stages
reset-revertGit Revert: Safe Public History Undograph
reflogGit Reflog Safety Netgraph
rebaseGit Rebase: Linear History Reconstructiongraph
squashSquashing Commits with Interactive Rebasespecial
bisectGit Bisect: Binary Search Bug Huntingspecial
fetch-pull-pushRemote Synchronization (Fetch vs Pull vs Push)graph
pull-requestsGitHub Collaboration & PR Workflowgraph
submodulesGit Submodules: Pinned Dependenciesgraph

Usage Code

<GitVisualizer scenario="basic-workflow" />
<GitVisualizer scenario="merge-3way" title="3-Way Merge in Action" />
<GitVisualizer scenario="rebase" />

5.10 Changelog Entries (<Changelog>)

Timeline container for milestone releases, major curriculum additions, or platform changelog updates.

November 19, 2026
  • Performance Optimization: Configured dynamic algorithm micro-chunking for 500+ DSA visualizers.
  • Infrastructure: Automated Vercel edge caching and Cloudflare DNS alignment.
  • Image Pipeline: Auto-injected lazy-loading and WebP/AVIF transformations.

Props Reference

PropTypeRequiredDefaultDescription
datestringYes—Date string displayed on the left column (e.g. "November 19, 2026")

Usage Code

<Changelog date="November 19, 2026">
  - Added 50 new interactive DSA problem visualizers
  - Released System Design deep dive on distributed consensus
</Changelog>

6. Standard Typography & Layout Elements

Headings Hierarchy

Heading 1 (# Heading 1)

Heading 2 (## Heading 2)

Heading 3 (### Heading 3)

Heading 4 (#### Heading 4)


Formatted Tables

MethodEndpointDescriptionAuth Required
GET/api/questions.jsonReturns all interview questions with optimized imagesNo
POSThttp://localhost:4322/api/create-seriesScaffolds new series and updates roadmapsLocal Dev Only
POSThttp://localhost:4322/api/create-articleScaffolds article and updates syllabus navbarLocal Dev Only

Pre-Publish Checklist

Before committing or pushing new content:

  • File created in the designated folder (articles/, series/, shorts/, etc.).
  • Frontmatter strictly validated against the schemas in Section 4.
  • Category chosen from the 5 canonical values (Core-CS, DSA, Development, System-Design, AI-Engineering).
  • series field matches the exact JSON course ID (if part of a course).
  • roadmapOrder.json updated with new series ID (handled automatically by npm run admin / npm run scaffold).
  • draft: false set for all live content.

7. Algorithm Visualizer: AI Prompt & Generator Guide

This section provides the complete reference specification and copy-paste prompt template to generate interactive algorithm visualizers for any DSA problem (Sorting, Searching, HashMaps, Sets, Queues, Deques, Trees, Heaps, Stacks, Linked Lists, DP) using any AI assistant (ChatGPT, Claude, Gemini, Cursor, Antigravity).

7.1 Visualizer Architecture Overview

The visualizer system is composed of:

  • Engine Component: <AlgoVisualizer problemId="slug" /> in src/components/features/visualizer/AlgoVisualizer.astro.
  • Step Builder: StepBuilder class in src/problems/algorithms/builder.ts with a fluent .step({ ... }) API.
  • Type Definitions: src/problems/algorithms/types.ts defining all state models and render options.
  • Algorithm Directory: All algorithm definition files live in src/problems/algorithms/<slug>.ts.
  • Registry: src/problems/algorithms/index.ts (automatically updated via syncAlgorithmIndex()).

7.2 Representation of All DSA Problem Types

The visualization engine supports representing any DSA problem type through flexible combinations of data structures:

DSA Problem TypeHow to Represent with StepBuilderKey Properties Used
Merge SortSubarrays via arrays: [left, right, merged] or single array with window: [low, high] and merge pointers i, j, karrays or array.window, pointers
Quick SortSingle array with partition pointers (low, pivot, high, i, j), swap highlights, and sub-range windowspointers, highlights, window
Binary SearchSingle array with low, mid, high pointers, active search interval window: [low, high], and match highlightspointers: { low, mid, high }, window: [low, high]
Linear SearchScanning pointer i checking each element with match/visited state highlightspointers: { i }, highlights
Hash MapKey-Value dictionary with searchKey and status banner (found, not-found, searching)hashmap: Map or Record, searchKey, searchResult
Set / HashSetUnique element collection with searchElement and membership verification banner (contains(x))set: Set or string[] or number[], searchElement, searchResult
Queue (FIFO)First-In-First-Out queue with FRONT and REAR markers, showing enqueue at rear and dequeue at front (BFS)queue: { items: [...], action: 'enqueue' | 'dequeue', label: 'Queue (FIFO)' }
Deque (Double Queue)Double-ended queue with front (addFirst/removeFirst) and back (addLast/removeLast) markers (e.g. Monotonic Deque, Sliding Window Max)deque: { items: [...], action: 'addFirst' | 'removeFirst' | 'addLast' | 'removeLast', label: 'Double-Ended Queue (Deque)' }
Stack (LIFO)Last-In-First-Out container with vertical layout, TOP marker, depth count, and push/pop animations (brackets, monotonic stack)stack: { items: [...], action: 'push' | 'pop', label: 'Stack (LIFO)' }
Binary Tree & BSTNode hierarchy with parent-child links, traversal highlights, and search targetstree: { nodes: [...], rootId }
Tree + Array (Heaps)Both array and tree in the exact same step, mapping array index i to tree nodes with children at 2i + 1 and 2i + 2array: { ... }, tree: { ... }
Linked ListNode chains with next pointers, head/curr/prev markers, and node reversal indicatorslinkedList: { nodes: [...], headId }
Dynamic Programming1D or 2D state matrix with active computation cell, dependency cell highlights, and transition formula bannerdpTable: { grid, activeCell, highlightCells, formula }

[!TIP] Stack vs. Queue vs. Deque Selection

  • Stack (LIFO): Use step.stack. Renders as a vertical container with a TOP marker and push/pop operations.
  • Queue (FIFO): Use step.queue. Renders as a horizontal pipeline with ← FRONT (Out) on the left and REAR (In) ← on the right with enqueue/dequeue operations.
  • Deque (Double-Ended): Use step.deque. Renders with both FRONT and BACK markers, supporting addFirst, removeFirst, addLast, and removeLast. In the CMS Visual Step Builder, simply pick your desired data structure from the Container Type dropdown.

7.3 Core Authoring Rules

  1. Idiomatic Java in codeLine: Always display the actual, readable Java statement executed at that step.
  2. Pointers Only (No Window Text Badges): Arrays show labeled pointer arrows (i, j, low, mid, high, left, right). Windows outline the active subarray boundary (window: [start, end]). Never put text labels or badge strings on or inside windows.
  3. Variable Tracking in Header: Keep all numeric metrics, accumulators, sums, and status flags in variables: { ... }. They render in a clean, dedicated bar above the visualization.
  4. Freeform Categories: Category is an open string (e.g. 'Sorting', 'Sliding Window', 'Two Pointers', 'Trees & Heaps', or 'General DSA').
  5. No Forced Complexity / Difficulty Tags: The visualizer player stays clean, focused entirely on the execution flow and intuitive mental model.

7.4 Copy-Paste AI Prompt Template

Copy the prompt below and paste it into any LLM or AI coding agent alongside your Java solution:

You are an expert DSA educator and TypeScript engineer building algorithm visualizers for CSPrimer.

Given the Java solution and problem below, create a fully working TypeScript algorithm definition file for the CSPrimer Algorithm Visualizer Engine.

### Output Destination
File path: `src/problems/algorithms/<problem-slug>.ts`

### Requirements
1. Import `AlgorithmDefinition`, `ExecutionStep` from `./types` and `StepBuilder` from `./builder`.
2. Export an object adhering to `AlgorithmDefinition`:
   - `id`: `<problem-slug>`
   - `title`: Clean Problem Title
   - `category`: Freeform topic name (e.g. 'Sorting', 'Binary Search', 'Sliding Window', 'Hash Map', 'Set', 'Trees', 'Deques', or 'General DSA')
   - `description`: 1-2 sentence high-level explanation
   - `visualizationTypes`: Array of data structure renderers used: `['array']`, `['array', 'hashmap']`, `['set']`, `['deque']`, `['array', 'tree']`, etc.
   - `defaultInputs`: Object containing default parameters (e.g. `{ nums: [4, 2, 7, 1, 3] }`)
   - `inputSchema`: Array of input field schemas for the interactive "Customize" drawer
   - `generateSteps(inputs)`: Returns `ExecutionStep[]` using `StepBuilder`.

3. Visualizer Step Rules:
   - Use `const builder = new StepBuilder();`
   - Call `builder.step({ title, description, codeLine, variables, ...structures })` for each step.
   - `codeLine`: Exact line of standard Java code executed at this step.
   - `variables`: Key-value map of current variables (e.g. `{ low: 0, high: 5, mid: 2 }`).
   - `pointers`: Named indices pointing to array elements (e.g. `pointers: { low: 0, mid: 2, high: 5 }`).
   - `window`: Active subarray window `window: [start, end]`. Never place text labels or badge strings in the window.
   - `highlights`: Array of cell indices to highlight with visual states: `[0, 1]`.
   - Data Structure Renderers Supported:
     - **Array / Sorting / Searching**: `array: { values: [...], pointers: { ... }, highlights: [...], window: [start, end] }`
     - **Multiple Arrays**: `arrays: [ { values: [...], label: 'A' }, { values: [...], label: 'B' } ]`
     - **Hash Map**: `hashmap: map, searchKey: key, searchResult: 'found' | 'not-found'`
     - **Set / HashSet**: `set: Array.from(set), searchElement: val, searchResult: 'found' | 'not-found'`
     - **Queue**: `queue: [...queueItems]`
     - **Deque (Double Queue)**: `deque: [...dequeItems]`
     - **Stack**: `stack: [...stackItems]`
     - **Binary Tree**: `tree: { nodes: [...], rootId: 'root' }`
     - **Tree + Array (Heap)**: combine `array` and `tree` in the same step
     - **Linked List**: `linkedList: { nodes: [...], headId: '0' }`
     - **Dynamic Programming**: `dpTable: { grid: [...], activeCell: { row, col }, formula: '...' }`

4. Registration & MDX Embed:
   - Provide the 1-line command to register the problem:
     `node -e "import('./scripts/scaffold.mjs').then(m => m.syncAlgorithmIndex())"`
   - Provide the MDX embed snippet:
     `<AlgoVisualizer problemId="<problem-slug>" />`

---

### Java Code & Problem Details:
[PASTE YOUR JAVA SOLUTION AND PROBLEM DESCRIPTION HERE]

7.5 Reference Implementation Blueprints

Blueprint 1: Binary Search (Array + Pointers + Search Window)

import type { AlgorithmDefinition, ExecutionStep } from './types';
import { StepBuilder } from './builder';

export const binarySearch: AlgorithmDefinition = {
  id: 'binary-search',
  title: 'Binary Search',
  category: 'Searching',
  description: 'Searches for a target value within a sorted array by halving the search space each step.',
  visualizationTypes: ['array'],
  defaultInputs: {
    nums: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91],
    target: 23,
  },
  inputSchema: [
    {
      name: 'nums',
      label: 'Sorted Array (comma-separated)',
      type: 'number-array',
      defaultValue: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91],
      placeholder: '2, 5, 8, 12, 16, 23, 38, 56, 72, 91',
      description: 'Ascending sorted array',
    },
    {
      name: 'target',
      label: 'Target Value',
      type: 'number',
      defaultValue: 23,
      placeholder: '23',
      description: 'Number to search for',
    },
  ],
  generateSteps: (inputs: Record<string, any>): ExecutionStep[] => {
    const rawNums = inputs.nums;
    const nums: number[] = Array.isArray(rawNums)
      ? rawNums.map(Number).filter((n) => !isNaN(n))
      : [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
    const target = Number(inputs.target ?? 23);

    const builder = new StepBuilder();
    let low = 0;
    let high = nums.length - 1;

    builder.step({
      title: 'Initialize Binary Search',
      description: `Target is ${target}. Set low = 0 and high = ${high}.`,
      codeLine: 'int low = 0, high = nums.length - 1;',
      variables: { low, high, target },
      array: {
        values: [...nums],
        pointers: { low, high },
        window: [low, high],
        label: 'nums[]',
      },
    });

    while (low <= high) {
      const mid = Math.floor((low + high) / 2);
      const midVal = nums[mid];

      builder.step({
        title: `Calculate Midpoint: mid = ${mid} (nums[mid] = ${midVal})`,
        description: `Inspect middle element at index ${mid}.`,
        codeLine: 'int mid = low + (high - low) / 2;',
        variables: { low, mid, high, 'nums[mid]': midVal, target },
        array: {
          values: [...nums],
          pointers: { low, mid, high },
          highlights: [mid],
          window: [low, high],
          label: 'nums[]',
        },
      });

      if (midVal === target) {
        builder.step({
          title: `Target Found at Index ${mid}!`,
          description: `nums[${mid}] == ${target}. Return index ${mid}.`,
          codeLine: 'if (nums[mid] == target) return mid;',
          variables: { low, mid, high, resultIndex: mid, status: 'FOUND' },
          array: {
            values: [...nums],
            pointers: { mid },
            highlights: [{ index: mid, state: 'match' }],
            label: 'nums[]',
          },
        });
        return builder.build();
      } else if (midVal < target) {
        builder.step({
          title: `nums[mid] = ${midVal} < ${target}: Discard Left Half`,
          description: `Target must lie in the right half. Move low to mid + 1.`,
          codeLine: 'low = mid + 1;',
          variables: { low: mid + 1, mid, high, target },
          array: {
            values: [...nums],
            pointers: { low: mid + 1, high },
            window: [mid + 1, high],
            label: 'nums[]',
          },
        });
        low = mid + 1;
      } else {
        builder.step({
          title: `nums[mid] = ${midVal} > ${target}: Discard Right Half`,
          description: `Target must lie in the left half. Move high to mid - 1.`,
          codeLine: 'high = mid - 1;',
          variables: { low, mid, high: mid - 1, target },
          array: {
            values: [...nums],
            pointers: { low, high: mid - 1 },
            window: [low, Math.max(low, mid - 1)],
            label: 'nums[]',
          },
        });
        high = mid - 1;
      }
    }

    builder.step({
      title: 'Target Not Found',
      description: `Search space exhausted (low > high). Target ${target} is not in the array.`,
      codeLine: 'return -1;',
      variables: { low, high, target, status: 'NOT FOUND' },
      array: { values: [...nums], label: 'nums[]' },
    });

    return builder.build();
  },
};

export default binarySearch;

Blueprint 2: Sliding Window Maximum (Array + Double Queue / Deque)

import type { AlgorithmDefinition, ExecutionStep } from './types';
import { StepBuilder } from './builder';

export const slidingWindowMax: AlgorithmDefinition = {
  id: 'sliding-window-maximum',
  title: 'Sliding Window Maximum',
  category: 'Deques & Sliding Window',
  description: 'Maintains a monotonic decreasing deque storing indices to find the maximum in each sliding window in O(N) time.',
  visualizationTypes: ['array', 'deque'],
  defaultInputs: {
    nums: [1, 3, -1, -3, 5, 3, 6, 7],
    k: 3,
  },
  inputSchema: [
    {
      name: 'nums',
      label: 'Array',
      type: 'number-array',
      defaultValue: [1, 3, -1, -3, 5, 3, 6, 7],
      placeholder: '1, 3, -1, -3, 5, 3, 6, 7',
      description: 'Input numbers array',
    },
    {
      name: 'k',
      label: 'Window Size (k)',
      type: 'number',
      defaultValue: 3,
      placeholder: '3',
      description: 'Sliding window width',
    },
  ],
  generateSteps: (inputs: Record<string, any>): ExecutionStep[] => {
    const rawNums = inputs.nums;
    const nums: number[] = Array.isArray(rawNums)
      ? rawNums.map(Number).filter((n) => !isNaN(n))
      : [1, 3, -1, -3, 5, 3, 6, 7];
    const k = Math.max(1, Number(inputs.k ?? 3));

    const builder = new StepBuilder();
    const deque: number[] = []; // Stores indices
    const result: number[] = [];

    builder.step({
      title: 'Initialize Monotonic Deque',
      description: `Create an ArrayDeque to store indices of potential maximum elements in decreasing value order.`,
      codeLine: 'Deque<Integer> deque = new ArrayDeque<>();',
      variables: { k, dequeSize: 0 },
      array: { values: [...nums], pointers: { i: 0 }, label: 'nums[]' },
      deque: [],
    });

    for (let i = 0; i < nums.length; i++) {
      // Remove elements outside current window
      while (deque.length > 0 && deque[0] < i - k + 1) {
        const removed = deque.shift()!;
        builder.step({
          title: `deque.removeFirst(): Out of Window`,
          description: `Index ${removed} falls outside window [${i - k + 1}, ${i}]. Remove from front.`,
          codeLine: 'if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) deque.pollFirst();',
          variables: { i, removedIndex: removed, 'deque.size()': deque.length },
          array: { values: [...nums], pointers: { i }, window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
          deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
        });
      }

      // Remove smaller elements from back
      while (deque.length > 0 && nums[deque[deque.length - 1]] < nums[i]) {
        const removed = deque.pop()!;
        builder.step({
          title: `deque.removeLast(): Monotonic Violation`,
          description: `nums[${removed}] (${nums[removed]}) < nums[${i}] (${nums[i]}). Pop from back.`,
          codeLine: 'while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();',
          variables: { i, poppedIndex: removed, currentVal: nums[i] },
          array: { values: [...nums], pointers: { i }, highlights: [i, removed], window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
          deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
        });
      }

      deque.push(i);
      builder.step({
        title: `deque.addLast(${i}): Added Current Index`,
        description: `Pushed index ${i} (value ${nums[i]}) to back of deque.`,
        codeLine: 'deque.offerLast(i);',
        variables: { i, currentVal: nums[i], windowMax: nums[deque[0]] },
        array: { values: [...nums], pointers: { i }, window: [Math.max(0, i - k + 1), i], label: 'nums[]' },
        deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
      });

      if (i >= k - 1) {
        result.push(nums[deque[0]]);
        builder.step({
          title: `Record Window Maximum: ${nums[deque[0]]}`,
          description: `Window [${i - k + 1}, ${i}] maximum is at front of deque: nums[${deque[0]}] = ${nums[deque[0]]}.`,
          codeLine: 'result[i - k + 1] = nums[deque.peekFirst()];',
          variables: { windowStart: i - k + 1, windowEnd: i, max: nums[deque[0]], resultSoFar: [...result] },
          array: { values: [...nums], pointers: { max: deque[0] }, window: [i - k + 1, i], highlights: [deque[0]], label: 'nums[]' },
          deque: deque.map((idx) => `idx ${idx} (${nums[idx]})`),
        });
      }
    }

    return builder.build();
  },
};

export default slidingWindowMax;

8. Infrastructure, Hosting & Deployment Architecture

This section documents the production hosting, CDN, domain canonicalization, and deployment setup powering CSPrimer.

8.1 Canonical Production Domain & 308 Redirection

The single authoritative canonical production domain is:

https://csprimer.org

All domain routing and search authority are unified under this domain:

DomainStatus in VercelHTTP BehaviorPurpose
csprimer.orgProduction (Primary)200 OKThe canonical domain for all visitors, search engines, and social cards
www.csprimer.orgValid Configuration308 Permanent Redirect $\rightarrow$ csprimer.orgStandard www subdomain redirect
csprimer.inValid Configuration308 Permanent Redirect $\rightarrow$ csprimer.orgLegacy domain alias redirect
www.csprimer.inValid Configuration308 Permanent Redirect $\rightarrow$ csprimer.orgLegacy www alias redirect
*.vercel.appValid ConfigurationDirect / Preview DeploymentsStaging and internal deployment previews

Core Repository Configuration:

  • astro.config.mjs: site: "https://csprimer.org" (generates clean sitemaps and canonical tags).
  • src/config/config.json: "base_url": "https://csprimer.org".
  • public/robots.txt: Sitemap: https://csprimer.org/sitemap-index.xml.
  • src/layouts/Base.astro: Canonical tags (<link rel="canonical">) and OpenGraph (og:url, og:image) automatically resolve to https://csprimer.org, preventing canonical redirect loops.

8.2 Vercel Edge Hosting Configuration (vercel.json)

Edge caching, routing rules, and security headers are configured at the repository root via vercel.json:

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "cleanUrls": true,
  "trailingSlash": false,
  "headers": [
    {
      "source": "/_astro/(.*)",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=31536000, immutable"
        }
      ]
    },
    {
      "source": "/images/(.*)",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=86400, stale-while-revalidate=604800"
        }
      ]
    },
    {
      "source": "/pdfs/(.*)",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=604800, stale-while-revalidate=86400"
        }
      ]
    },
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Content-Type-Options", "value": "nosniff" },
        { "key": "X-Frame-Options", "value": "SAMEORIGIN" },
        { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
      ]
    }
  ]
}
  • Hashed Assets (/_astro/*): Given 1-year immutable caching (max-age=31536000, immutable). Browsers and edge caches never re-fetch fingerprinted JS and CSS.
  • Clean URLs: cleanUrls: true with trailingSlash: false matches Astro SSG routing perfectly.
  • Security Headers: Standard nosniff, SAMEORIGIN, and strict referrer protection across all routes.

8.3 Node.js Runtime Version Requirement

  • Requirement: Node.js >= 22.0.0 (Active LTS).
  • In package.json:
    "engines": {
      "node": ">=22.0.0"
    }
    
  • In Vercel Project Settings:
    • Navigate to Settings $\rightarrow$ General $\rightarrow$ Node.js Version.
    • Select 22.x or 24.x (never legacy 20.x which is discontinued).

8.4 Cloudflare DNS & Proxy Guidelines

DNS for csprimer.org is managed in Cloudflare with the following configuration:

csprimer.org        CNAME  b3e9b5f5fbc27da1.vercel-dns-017.com  DNS only (Grey Cloud)
www.csprimer.org    CNAME  b3e9b5f5fbc27da1.vercel-dns-017.com  DNS only (Grey Cloud)
_vercel             TXT    vc-domain-verify=...                  DNS only
  • Why: Cloudflare operates purely as a lightning-fast authoritative DNS provider. Requests resolve directly to Vercel’s global Anycast Edge Network.
  • Advantages:
    1. Zero risk of proxy interference with client module hydration or ViewTransitions.
    2. Eliminates double-proxy latency (Browser $\rightarrow$ Cloudflare $\rightarrow$ Vercel).
    3. Vercel automatically manages TLS certificates, HTTP/2, HTTP/3, and edge routing.

If Switching to “Proxied” (Orange Cloud):

If you ever enable Cloudflare’s HTTP proxy for WAF or custom page rules, you must configure these settings:

  1. SSL/TLS Encryption Mode: Set to Full (Strict). (Flexible mode causes an infinite 301/308 redirect loop).
  2. Rocket Loader: OFF. (Rocket Loader intercepts module scripts and breaks Astro ViewTransitions lifecycle events).
  3. Auto Minify (HTML/JS/CSS): OFF. (Vite already minifies; Cloudflare’s HTML minifier strips inline visualizer JSON payloads).
  4. Polish / Mirage: OFF. (Images are hosted on Cloudinary and should not be re-compressed).

8.5 Cloudinary Image Pipeline & Automatic Lazy-Loading

All article screenshots, architectural diagrams, and illustrations are hosted on Cloudinary:

URL Transformation Pattern:

https://res.cloudinary.com/dwa6rcttw/image/upload/f_auto,q_auto,w_800/<public-id>
  • f_auto: Delivers modern AVIF to Chrome, Firefox, and Safari 16+ (saving ~30–50% bandwidth compared to WebP), with automatic WebP/PNG fallbacks.
  • q_auto: AI-driven perceptual compression balancing visual clarity and payload size.
  • w_800: Responsive width constraint preventing desktop-resolution downloads on mobile devices.
  • CMS Automation: Tab 9 of npm run admin and scripts/scaffold.mjs automatically inject /f_auto,q_auto,w_800/ into generated Markdown image tags.

AST Lazy Loading Plugin (rehypeLazyImages):

Configured in astro.config.mjs across both MDX and Markdown AST pipelines:

  • Every <img> tag rendered from markdown automatically receives loading="lazy" and decoding="async".
  • Prevents off-screen article images from competing with critical CSS/JS during page load.
  • Preconnect hints (<link rel="preconnect" href="https://res.cloudinary.com" />) are embedded in Base.astro for instant TLS handshakes.

9. Performance & Scale Engineering Guide

This section explains how the platform achieves sub-second builds and fluid client transitions while scaling from 300 to 800+ articles and 200–500 DSA problem visualizers.

9.1 Dynamic Micro-Chunking for 200–500 DSA Visualizers

The Problem:

If an Astro site statically imports hundreds of algorithm definitions, Vite bundles them into a single monolithic JavaScript file (index.*.js). Every page visitor would download the code for all 500 algorithms, causing massive bundle bloat and sluggish first-contentful paint.

The Architectural Solution:

In src/components/features/visualizer/engine/visualizer-controller.ts:

  • Negative globs exclude internal builder utilities from the loader:
    const modules = import.meta.glob([
      '../../../../problems/algorithms/*.ts',
      '!**/index.ts',
      '!**/builder.ts',
      '!**/types.ts'
    ]);
    
  • Each algorithm compiles into its own independent micro-chunk (~2–3 KB each, e.g. 02-two-sum.*.js).
  • When a user navigates to an article containing <AlgoVisualizer problemId="two-sum" />, only that single micro-chunk is fetched asynchronously on demand.
  • Adding 500 new DSA articles has zero impact on the base client bundle size.

9.2 Main-Thread Infinite Loop & Memory Guardrails

To protect against browser lockups during user testing or complex recursions:

  • MAX_STEPS = 300: Enforced in StepBuilder.addStep() (src/problems/algorithms/builder.ts).
  • If an algorithm enters a runaway loop or excessive state transitions on custom user inputs, step generation halts safely with a console warning rather than crashing the visitor’s browser tab.

9.3 Client-Side SPA Lifecycle & ViewTransitions Safety

Astro’s <ViewTransitions /> turns navigation into a client-side Single Page Application (SPA). The HTML <body> is swapped while JavaScript globals (window, document) persist.

Contributor Rules for Client Scripts:

  1. Always Listen to astro:page-load:

    • ❌ Never use document.addEventListener("DOMContentLoaded", init) alone (it will not fire when navigating between pages).
    • ❌ Never run init() at module top-level AND in astro:page-load (causes double-initialization).
    • ✅ Always use:
      document.addEventListener("astro:page-load", () => {
        initComponent();
      });
      
  2. Always Clean Up Global Window & Document Listeners:

    • Attaching anonymous listeners to window or document inside an astro:page-load hook creates memory leaks and duplicate triggers on every page visit.
    • Pattern A: AbortController (Recommended)
      let abortController = new AbortController();
      
      document.addEventListener("astro:before-swap", () => {
        abortController.abort();
        abortController = new AbortController();
      });
      
      window.addEventListener("resize", handleResize, { signal: abortController.signal });
      
    • Pattern B: Named Handler Unmounting
      window.removeEventListener("keydown", window.__myHandlerRef);
      window.__myHandlerRef = handleKeyDown;
      window.addEventListener("keydown", handleKeyDown);
      
  3. Debounce Scroll & Resize with requestAnimationFrame:

    • In components like TableOfContents.astro, scroll calculations are wrapped in requestAnimationFrame to eliminate layout thrashing and maintain 60 FPS scrolling.

9.4 Google Analytics 4 (GA4) Virtual Pageview Tracking

Because Astro swaps page content without a full document reload:

  • Standard GA4 tracking tags only fire on the initial hard page load.
  • In src/layouts/Base.astro, an astro:page-load listener dispatches virtual page_view events:
    let isFirstLoad = true;
    document.addEventListener("astro:page-load", () => {
      NProgress.done();
      if (isFirstLoad) {
        isFirstLoad = false;
        return;
      }
      if (typeof window.gtag === "function") {
        window.gtag("event", "page_view", {
          page_location: window.location.href,
          page_title: document.title,
        });
      }
    });
    
  • This ensures 100% accurate traffic analytics across all 500+ articles without double-counting the initial visit.

10. Client State & LocalStorage Schema

The platform persists user progress and interactive states directly in browser localStorage. Below is the complete specification:

Storage KeyData TypePurposeWhere Used
roadmap_progressRecord<string, boolean>Map of completed article slugs (e.g. {"arrays-intro": true})Roadmaps, Course Drawer, and Article completion buttons
ib_starredstring[]Array of starred interview question IDs (e.g. ["101", "102"])Interview Bytes, Filter pills, and Anki Revision Modal
anki_historyRecord<string, any>Spaced repetition flashcard session scores, intervals, and datesAnki Revision Modal (/revision)
revision_planner_dataRecord<string, any>User’s custom revision schedule, checkboxes, and notesRevision Planner (/revision)