pagepublishedmdai-assisted

Content Layer: Current System Documentation

Reference doc for the SQLite migration. Captures exactly how the current filesystem-based content system works, where the pain points are, and what each function actually does.

Path
/notes/content-layer-docs
Published
May 7, 2026
Revised
—
Project
jaygriff-v3
Tags

On this page

Stored toc, derived from the body's headings on save. The body below isn't rendered yet, so these show the anchor ids rather than linking to them.

  • Overview #overview
  • posts.ts #poststs
  • What it does #what-it-does
  • The problem: duplicated filesystem scans #the-problem-duplicated-filesystem-scans
  • Key functions #key-functions
  • The scan cost #the-scan-cost
  • content-loader.ts #content-loaderts
  • What it does #what-it-does-1
  • Key types #key-types
  • Key functions #key-functions-1
  • routes.ts #routests
  • What it does #what-it-does-2
  • Key type #key-type
  • The problem: three scans per call #the-problem-three-scans-per-call
  • How it works #how-it-works
  • What it produces #what-it-produces
  • The core architectural problem #the-core-architectural-problem
  • Data Model Problems #data-model-problems
  • 1. No runtime validation #1-no-runtime-validation
  • 2. Inconsistent union types on author and updated #2-inconsistent-union-types-on-author-and-updated
  • 3. description is required but treated as optional #3-description-is-required-but-treated-as-optional
  • 4. type union is incomplete #4-type-union-is-incomplete
  • 5. relatedPosts is manual and unvalidated #5-relatedposts-is-manual-and-unvalidated
  • What maps to what in SQLite #what-maps-to-what-in-sqlite

Body

markdownbody.md
## Overview

The content layer lives in three files:

- `src/lib/posts.ts` — discovers and indexes all content by scanning the filesystem
- `src/lib/content-loader.ts` — loads individual content by slug
- `src/lib/routes.ts` — builds a flat route index for the Navigator search

Content lives in two directories:

- `content/tsx/` — React components with exported `metadata` objects
- `content/md/` — Markdown files with JSON frontmatter

---

## posts.ts

### What it does

Scans both content directories on every call and returns arrays of posts or docs with their metadata.

### The problem: duplicated filesystem scans

`getAllPosts()` and `getAllDocs()` are nearly identical — both scan `content/tsx/` and `content/md/`, import every file, parse metadata, deduplicate, and filter by type. The only difference is the final filter: posts check for `type === 'post'`, docs check for `type?.startsWith('doc')`.

This means any caller that needs both posts and docs triggers **two full filesystem scans**.

### Key functions

**`getAllPosts()`**
- Reads all `.tsx` files from `content/tsx/`, dynamically imports each one, extracts `module.metadata`
- Reads all `.md` files from `content/md/`, parses JSON frontmatter
- Deduplicates: TSX takes priority over MD for the same slug
- Filters to only return items where `type` is undefined or `'post'`

**`getAllDocs()`**
- Same scan as `getAllPosts()` — reads both directories, imports TSX, parses MD frontmatter
- Same deduplication logic
- Filters to only return items where `type` starts with `'doc'` (covers `doc`, `doc:commit`, etc.)

**`getPostBySlug(slug)`**
- Calls `getAllPosts()` (full scan) just to find one filename
- Returns the filename string or null

**`getDocBySlug(slug)`**
- Same as above but calls `getAllDocs()`

**`getAllAppRoutes()`**
- Recursively walks `src/app/` looking for `page.tsx` files
- Skips dynamic routes (directories containing `[`)
- Skips client components by checking if file starts with `'use client'`
- Imports each page and checks for a `routeMetadata` export
- Returns route entries for pages that have metadata

### The scan cost

Every call to `getAllPosts()` or `getAllDocs()` does:
1. `fs.readdirSync()` on both directories
2. `import()` on every TSX file (dynamic import, not cached between requests in dev)
3. `fs.readFileSync()` + frontmatter parse on every MD file

At 69 files this is acceptable. At 500+ files this becomes noticeably slow.

---

## content-loader.ts

### What it does

Loads a single piece of content by slug — returns either a TSX component or markdown string depending on what exists.

### Key types

```ts
export type ContentType = 'post' | 'doc';

export interface LoadedContent {
  type: 'tsx' | 'markdown';
  Component?: React.ComponentType;
  markdownContent?: string;
  metadata: PostMeta;
  filename: string;
}
```

The `type` field is a discriminated union — callers know whether to render a React component or a markdown string.

### Key functions

**`loadContentBySlug(slug, type)`**
- Calls `getAllPosts()` or `getAllDocs()` to find the matching item (full scan)
- Then checks if a TSX file exists at the expected path with `existsSync()`
- If TSX exists: dynamically imports it, returns the default export as `Component`
- If not: reads the MD file, parses frontmatter, returns `markdownContent`

Note: this does a full scan to find the filename, then separately checks if the file exists — redundant since the scan already confirmed it exists.

**`getAllPostSlugs()`** / **`getAllDocSlugs()`**
- Thin wrappers that call `getAllPosts()` / `getAllDocs()` and map to slug arrays
- Used by Next.js `generateStaticParams()` for static build-time pre-rendering

---

## routes.ts

### What it does

Builds a flat `RouteEntry[]` index used by the Navigator search feature. Combines sitemap entries with post/doc metadata to produce searchable route data.

### Key type

```ts
export interface RouteEntry {
  path: string;
  title: string;
  description?: string;
  keywords?: string[];
}
```

### The problem: three scans per call

`getAllRoutes()` calls:
1. `sitemap()` — generates the full sitemap (which itself may scan content)
2. `getAllPosts()` — full filesystem scan
3. `getAllDocs()` — full filesystem scan

All three happen on every call to `getAllRoutes()`.

### How it works

- Iterates sitemap entries, extracts the URL pathname
- For `/posts/:slug` routes: finds matching post metadata, uses title/description/tags as keywords
- For `/docs/:slug` routes: same but for docs
- For `/`: hardcoded Home entry
- Fallback for any other route: derives title from the last path segment

### What it produces

A flat array of `RouteEntry` objects — path, title, description, keywords. This is intentionally stripped down from the full `PostMeta` type. The Navigator only needs what it needs.

---

## The core architectural problem

Every data access goes through a full filesystem scan. There is no caching layer, no persistent index, no way to query a subset of content without loading everything.

This works fine at current scale. It breaks down as content grows because:

- Related posts require loading every post into memory and comparing manually
- Tag filtering requires loading everything and filtering in JS
- Chronological queries require loading everything and sorting
- Any feature that needs to "find posts where X" requires a full scan

The SQLite migration replaces these filesystem scans with actual queries. The three files above become thin wrappers around SQL — the shape of the API stays the same, the internals become fast and queryable.

---

## Data Model Problems

These are the design issues in the current `PostMeta` interface that should be fixed during the SQLite migration.

### 1. No runtime validation

TypeScript only enforces types at compile time. When frontmatter is parsed from a file:

```ts
const { metadata } = parseMarkdownWithJsonFrontmatter(fileContent);
return { filename, metadata };
```

You're casting the parsed object to `PostMeta` with zero runtime checks. The file could be missing required fields, have wrong types, or have typos in field names — TypeScript won't catch any of it. It all blows up at render time instead of at write time.

**Required fields that are routinely missing in practice:** `description` is typed as required `string` but the metadata scanner shows empty descriptions across many posts. Same risk with `date`. These should either be truly required (enforced at write time) or explicitly optional in the interface.

SQLite fixes this — `NOT NULL` constraints on `title`, `slug`, `date` mean bad data can't get in. You catch the problem when populating the DB, not when someone loads a page.

### 2. Inconsistent union types on `author` and `updated`

```ts
author?: string | string[]
updated?: string | string[]
```

Both fields are `string | string[]` — meaning every single consumer has to branch on `Array.isArray()` before using them. This pattern spreads defensive code everywhere and is easy to forget.

These should just always be arrays:

```ts
authors: string[]      // always an array, required, minimum 1
updatedDates: string[] // always an array, empty if never updated
```

A single author is just an array of length 1. A single update date is just an array of length 1. No branching needed anywhere downstream. This happened organically — single author came first, multi-author was bolted on later with `| string[]` to avoid a breaking change. The SQLite migration is the right time to normalize this.

### 3. `description` is required but treated as optional

The interface says:

```ts
description: string; // required, non-optional
```

But in practice many posts don't have one. This means TypeScript thinks it's always there, so any code doing `metadata.description.toLowerCase()` or passing it to a component won't complain at compile time but will throw at runtime for posts missing it.

Should be `description?: string` to match reality, or actually enforced as required at write time via SQLite schema.

### 4. `type` union is incomplete

```ts
type?: 'post' | 'doc' | 'doc:commit'
```

But `getAllDocs()` filters with `type?.startsWith('doc')` — implying there are or could be other `doc:*` variants beyond `doc:commit`. The type definition doesn't match the actual filtering logic. Either lock down the union to all known variants or widen it and document the convention.

### 5. `relatedPosts` is manual and unvalidated

```ts
relatedPosts?: string[] // Array of slugs for related posts
```

These are freehand slug strings in a file. No validation that the slugs actually exist. A typo or a renamed slug silently produces a broken related posts link with no error anywhere.

SQLite with a foreign key constraint fixes this — a `related_posts` junction table referencing `content.slug` will reject invalid slugs at insert time.

---

## What maps to what in SQLite

| Current | SQLite equivalent |
|---|---|
| `getAllPosts()` | `SELECT * FROM content WHERE type = 'post'` |
| `getAllDocs()` | `SELECT * FROM content WHERE type LIKE 'doc%'` |
| `getPostBySlug(slug)` | `SELECT filename FROM content WHERE slug = ?` |
| `loadContentBySlug(slug)` | `SELECT * FROM content WHERE slug = ? AND type = ?` |
| `getAllRoutes()` | `SELECT path, title, description, tags FROM content` |
| Related posts (not yet built) | `SELECT ... JOIN content_tags ... WHERE tag IN (...)` |
| Tag filtering (not yet built) | `SELECT * FROM content WHERE id IN (SELECT content_id FROM content_tags WHERE tag = ?)` |

The migration doesn't change the API surface. `getAllPosts()` still returns the same shape. The filesystem scan just becomes a query.

Raw row

jsoncontent-layer-docs.json
{
  "id": "4e2f4378-804d-4d74-ba59-71fe63d64fa2",
  "parentId": "b455ec91-16d1-41f1-a222-a7097ea66c25",
  "slug": "content-layer-docs",
  "path": "/notes/content-layer-docs",
  "type": "page",
  "status": "published",
  "title": "Content Layer: Current System Documentation",
  "description": "Reference doc for the SQLite migration. Captures exactly how the current filesystem-based content system works, where the pain points are, and what each function actually does.",
  "intro": null,
  "body": "## Overview\n\nThe content layer lives in three files:\n\n- `src/lib/posts.ts` — discovers and indexes all content by scanning the filesystem\n- `src/lib/content-loader.ts` — loads individual content by slug\n- `src/lib/routes.ts` — builds a flat route index for the Navigator search\n\nContent lives in two directories:\n\n- `content/tsx/` — React components with exported `metadata` objects\n- `content/md/` — Markdown files with JSON frontmatter\n\n---\n\n## posts.ts\n\n### What it does\n\nScans both content directories on every call and returns arrays of posts or docs with their metadata.\n\n### The problem: duplicated filesystem scans\n\n`getAllPosts()` and `getAllDocs()` are nearly identical — both scan `content/tsx/` and `content/md/`, import every file, parse metadata, deduplicate, and filter by type. The only difference is the final filter: posts check for `type === 'post'`, docs check for `type?.startsWith('doc')`.\n\nThis means any caller that needs both posts and docs triggers **two full filesystem scans**.\n\n### Key functions\n\n**`getAllPosts()`**\n- Reads all `.tsx` files from `content/tsx/`, dynamically imports each one, extracts `module.metadata`\n- Reads all `.md` files from `content/md/`, parses JSON frontmatter\n- Deduplicates: TSX takes priority over MD for the same slug\n- Filters to only return items where `type` is undefined or `'post'`\n\n**`getAllDocs()`**\n- Same scan as `getAllPosts()` — reads both directories, imports TSX, parses MD frontmatter\n- Same deduplication logic\n- Filters to only return items where `type` starts with `'doc'` (covers `doc`, `doc:commit`, etc.)\n\n**`getPostBySlug(slug)`**\n- Calls `getAllPosts()` (full scan) just to find one filename\n- Returns the filename string or null\n\n**`getDocBySlug(slug)`**\n- Same as above but calls `getAllDocs()`\n\n**`getAllAppRoutes()`**\n- Recursively walks `src/app/` looking for `page.tsx` files\n- Skips dynamic routes (directories containing `[`)\n- Skips client components by checking if file starts with `'use client'`\n- Imports each page and checks for a `routeMetadata` export\n- Returns route entries for pages that have metadata\n\n### The scan cost\n\nEvery call to `getAllPosts()` or `getAllDocs()` does:\n1. `fs.readdirSync()` on both directories\n2. `import()` on every TSX file (dynamic import, not cached between requests in dev)\n3. `fs.readFileSync()` + frontmatter parse on every MD file\n\nAt 69 files this is acceptable. At 500+ files this becomes noticeably slow.\n\n---\n\n## content-loader.ts\n\n### What it does\n\nLoads a single piece of content by slug — returns either a TSX component or markdown string depending on what exists.\n\n### Key types\n\n```ts\nexport type ContentType = 'post' | 'doc';\n\nexport interface LoadedContent {\n  type: 'tsx' | 'markdown';\n  Component?: React.ComponentType;\n  markdownContent?: string;\n  metadata: PostMeta;\n  filename: string;\n}\n```\n\nThe `type` field is a discriminated union — callers know whether to render a React component or a markdown string.\n\n### Key functions\n\n**`loadContentBySlug(slug, type)`**\n- Calls `getAllPosts()` or `getAllDocs()` to find the matching item (full scan)\n- Then checks if a TSX file exists at the expected path with `existsSync()`\n- If TSX exists: dynamically imports it, returns the default export as `Component`\n- If not: reads the MD file, parses frontmatter, returns `markdownContent`\n\nNote: this does a full scan to find the filename, then separately checks if the file exists — redundant since the scan already confirmed it exists.\n\n**`getAllPostSlugs()`** / **`getAllDocSlugs()`**\n- Thin wrappers that call `getAllPosts()` / `getAllDocs()` and map to slug arrays\n- Used by Next.js `generateStaticParams()` for static build-time pre-rendering\n\n---\n\n## routes.ts\n\n### What it does\n\nBuilds a flat `RouteEntry[]` index used by the Navigator search feature. Combines sitemap entries with post/doc metadata to produce searchable route data.\n\n### Key type\n\n```ts\nexport interface RouteEntry {\n  path: string;\n  title: string;\n  description?: string;\n  keywords?: string[];\n}\n```\n\n### The problem: three scans per call\n\n`getAllRoutes()` calls:\n1. `sitemap()` — generates the full sitemap (which itself may scan content)\n2. `getAllPosts()` — full filesystem scan\n3. `getAllDocs()` — full filesystem scan\n\nAll three happen on every call to `getAllRoutes()`.\n\n### How it works\n\n- Iterates sitemap entries, extracts the URL pathname\n- For `/posts/:slug` routes: finds matching post metadata, uses title/description/tags as keywords\n- For `/docs/:slug` routes: same but for docs\n- For `/`: hardcoded Home entry\n- Fallback for any other route: derives title from the last path segment\n\n### What it produces\n\nA flat array of `RouteEntry` objects — path, title, description, keywords. This is intentionally stripped down from the full `PostMeta` type. The Navigator only needs what it needs.\n\n---\n\n## The core architectural problem\n\nEvery data access goes through a full filesystem scan. There is no caching layer, no persistent index, no way to query a subset of content without loading everything.\n\nThis works fine at current scale. It breaks down as content grows because:\n\n- Related posts require loading every post into memory and comparing manually\n- Tag filtering requires loading everything and filtering in JS\n- Chronological queries require loading everything and sorting\n- Any feature that needs to \"find posts where X\" requires a full scan\n\nThe SQLite migration replaces these filesystem scans with actual queries. The three files above become thin wrappers around SQL — the shape of the API stays the same, the internals become fast and queryable.\n\n---\n\n## Data Model Problems\n\nThese are the design issues in the current `PostMeta` interface that should be fixed during the SQLite migration.\n\n### 1. No runtime validation\n\nTypeScript only enforces types at compile time. When frontmatter is parsed from a file:\n\n```ts\nconst { metadata } = parseMarkdownWithJsonFrontmatter(fileContent);\nreturn { filename, metadata };\n```\n\nYou're casting the parsed object to `PostMeta` with zero runtime checks. The file could be missing required fields, have wrong types, or have typos in field names — TypeScript won't catch any of it. It all blows up at render time instead of at write time.\n\n**Required fields that are routinely missing in practice:** `description` is typed as required `string` but the metadata scanner shows empty descriptions across many posts. Same risk with `date`. These should either be truly required (enforced at write time) or explicitly optional in the interface.\n\nSQLite fixes this — `NOT NULL` constraints on `title`, `slug`, `date` mean bad data can't get in. You catch the problem when populating the DB, not when someone loads a page.\n\n### 2. Inconsistent union types on `author` and `updated`\n\n```ts\nauthor?: string | string[]\nupdated?: string | string[]\n```\n\nBoth fields are `string | string[]` — meaning every single consumer has to branch on `Array.isArray()` before using them. This pattern spreads defensive code everywhere and is easy to forget.\n\nThese should just always be arrays:\n\n```ts\nauthors: string[]      // always an array, required, minimum 1\nupdatedDates: string[] // always an array, empty if never updated\n```\n\nA single author is just an array of length 1. A single update date is just an array of length 1. No branching needed anywhere downstream. This happened organically — single author came first, multi-author was bolted on later with `| string[]` to avoid a breaking change. The SQLite migration is the right time to normalize this.\n\n### 3. `description` is required but treated as optional\n\nThe interface says:\n\n```ts\ndescription: string; // required, non-optional\n```\n\nBut in practice many posts don't have one. This means TypeScript thinks it's always there, so any code doing `metadata.description.toLowerCase()` or passing it to a component won't complain at compile time but will throw at runtime for posts missing it.\n\nShould be `description?: string` to match reality, or actually enforced as required at write time via SQLite schema.\n\n### 4. `type` union is incomplete\n\n```ts\ntype?: 'post' | 'doc' | 'doc:commit'\n```\n\nBut `getAllDocs()` filters with `type?.startsWith('doc')` — implying there are or could be other `doc:*` variants beyond `doc:commit`. The type definition doesn't match the actual filtering logic. Either lock down the union to all known variants or widen it and document the convention.\n\n### 5. `relatedPosts` is manual and unvalidated\n\n```ts\nrelatedPosts?: string[] // Array of slugs for related posts\n```\n\nThese are freehand slug strings in a file. No validation that the slugs actually exist. A typo or a renamed slug silently produces a broken related posts link with no error anywhere.\n\nSQLite with a foreign key constraint fixes this — a `related_posts` junction table referencing `content.slug` will reject invalid slugs at insert time.\n\n---\n\n## What maps to what in SQLite\n\n| Current | SQLite equivalent |\n|---|---|\n| `getAllPosts()` | `SELECT * FROM content WHERE type = 'post'` |\n| `getAllDocs()` | `SELECT * FROM content WHERE type LIKE 'doc%'` |\n| `getPostBySlug(slug)` | `SELECT filename FROM content WHERE slug = ?` |\n| `loadContentBySlug(slug)` | `SELECT * FROM content WHERE slug = ? AND type = ?` |\n| `getAllRoutes()` | `SELECT path, title, description, tags FROM content` |\n| Related posts (not yet built) | `SELECT ... JOIN content_tags ... WHERE tag IN (...)` |\n| Tag filtering (not yet built) | `SELECT * FROM content WHERE id IN (SELECT content_id FROM content_tags WHERE tag = ?)` |\n\nThe migration doesn't change the API surface. `getAllPosts()` still returns the same shape. The filesystem scan just becomes a query.\n",
  "toc": [
    {
      "depth": 2,
      "text": "Overview",
      "id": "overview"
    },
    {
      "depth": 2,
      "text": "posts.ts",
      "id": "poststs"
    },
    {
      "depth": 3,
      "text": "What it does",
      "id": "what-it-does"
    },
    {
      "depth": 3,
      "text": "The problem: duplicated filesystem scans",
      "id": "the-problem-duplicated-filesystem-scans"
    },
    {
      "depth": 3,
      "text": "Key functions",
      "id": "key-functions"
    },
    {
      "depth": 3,
      "text": "The scan cost",
      "id": "the-scan-cost"
    },
    {
      "depth": 2,
      "text": "content-loader.ts",
      "id": "content-loaderts"
    },
    {
      "depth": 3,
      "text": "What it does",
      "id": "what-it-does-1"
    },
    {
      "depth": 3,
      "text": "Key types",
      "id": "key-types"
    },
    {
      "depth": 3,
      "text": "Key functions",
      "id": "key-functions-1"
    },
    {
      "depth": 2,
      "text": "routes.ts",
      "id": "routests"
    },
    {
      "depth": 3,
      "text": "What it does",
      "id": "what-it-does-2"
    },
    {
      "depth": 3,
      "text": "Key type",
      "id": "key-type"
    },
    {
      "depth": 3,
      "text": "The problem: three scans per call",
      "id": "the-problem-three-scans-per-call"
    },
    {
      "depth": 3,
      "text": "How it works",
      "id": "how-it-works"
    },
    {
      "depth": 3,
      "text": "What it produces",
      "id": "what-it-produces"
    },
    {
      "depth": 2,
      "text": "The core architectural problem",
      "id": "the-core-architectural-problem"
    },
    {
      "depth": 2,
      "text": "Data Model Problems",
      "id": "data-model-problems"
    },
    {
      "depth": 3,
      "text": "1. No runtime validation",
      "id": "1-no-runtime-validation"
    },
    {
      "depth": 3,
      "text": "2. Inconsistent union types on author and updated",
      "id": "2-inconsistent-union-types-on-author-and-updated"
    },
    {
      "depth": 3,
      "text": "3. description is required but treated as optional",
      "id": "3-description-is-required-but-treated-as-optional"
    },
    {
      "depth": 3,
      "text": "4. type union is incomplete",
      "id": "4-type-union-is-incomplete"
    },
    {
      "depth": 3,
      "text": "5. relatedPosts is manual and unvalidated",
      "id": "5-relatedposts-is-manual-and-unvalidated"
    },
    {
      "depth": 2,
      "text": "What maps to what in SQLite",
      "id": "what-maps-to-what-in-sqlite"
    }
  ],
  "format": "md",
  "componentKey": null,
  "contentHash": null,
  "authors": null,
  "authorship": "ai-assisted",
  "authorshipNote": null,
  "tags": [
    "content-system",
    "sqlite",
    "architecture",
    "docs",
    "posts",
    "filesystem"
  ],
  "projectId": "b3d6e577-4481-4477-9b9f-cea025e63e92",
  "sectionId": "37a65cdb-ba93-4072-b16c-754be6170279",
  "publishedAt": "2026-05-07T21:38:34.807Z",
  "revisedAt": null,
  "sortOrder": 0,
  "source": "db",
  "file": null,
  "missingSince": null,
  "createdAt": "2026-11-18T21:24:33.150Z",
  "updatedAt": "2026-12-01T03:56:01.766Z",
  "link": null,
  "project": {
    "slug": "jaygriff-v3",
    "title": "jaygriff-v3",
    "status": "published"
  },
  "section": {
    "slug": "docs",
    "title": "Docs"
  },
  "assets": []
}