Skip to main content

Adapter Contribution Guide

Thank you for your interest in contributing a platform adapter to Idiomark! This guide will walk you through the process of creating, testing, and submitting a new adapter.

Table of Contents​

  1. Overview
  2. Choosing an Adapter to Build
  3. Using the Generator CLI
  4. Adapter Structure
  5. Implementation Guidelines
  6. Testing Your Adapter
  7. Submitting Your Adapter
  8. Code Review Process
  9. What Makes a "Good" Adapter

Overview​

Idiomark adapters connect the protocol to various platforms, enabling personality extraction from diverse sources. By contributing an adapter, you're helping make Idiomark more useful for everyone!

Why Contribute?​

  • Recognition: Your name in the Hall of Fame and adapter README
  • Bounty Rewards: Earn bounties for high-priority adapters (see bounties.yaml)
  • Impact: Help thousands of users extract their personality from your favorite platform
  • Learning: Gain experience with TypeScript, API integration, and open source contribution

Contribution Flowchart​

                    Start
|
v
Check [bounties.yaml] or open issues
|
v
Claim adapter (comment on issue)
|
v
Use generator CLI: pnpm cli generate adapter
|
v
Implement adapter logic
|
v
Write tests (>80% coverage)
|
v
Test locally: pnpm test --adapter <name>
|
v
Validate: pnpm adapter validate <name>
|
v
Submit PR
|
v
Code review (2+ approvals)
|
v
Merge!
|
v
Update Hall of Fame + Bounty

Choosing an Adapter to Build​

Check for Existing Adapters​

Before starting, check if an adapter already exists:

# List all adapters
pnpm ls --filter @idiomark/adapter-*

# Or check the adapters directory
ls packages/adapters/

Browse Open Adapter Requests​

See GitHub Issues with the adapter-request label.

Check Bounties​

High-priority adapters with bounties are listed in bounties.yaml:

# View available bounties
cat bounties.yaml

Claim an Adapter​

To avoid duplicate work:

  1. Find an open issue for the adapter you want to build
  2. Comment /claim to assign it to yourself
  3. If no issue exists, create one with the adapter request template

Using the Generator CLI​

The fastest way to create a new adapter is using our generator CLI:

# From project root
pnpm cli generate adapter

# Interactive prompts:
# ? Adapter name (e.g., reddit): _
# ? Platform display name (e.g., Reddit): _
# ? API documentation URL: _
# ? Authentication method: _
# - OAuth 2.0
# - API Key
# - Bearer Token
# - None (public scraping)
# ? Rate limit (requests per window): _
# ? Rate limit window (seconds): _
# ? Include example README in generated adapter? Yes

The generator will:

  • Create the adapter package structure
  • Generate TypeScript types for the API
  • Implement the PlatformAdapter interface
  • Add basic rate limiting
  • Create test scaffolding
  • Generate a README template

Adapter Structure​

A typical adapter has this structure:

packages/adapters/myplatform/
├── src/
│ ├── index.ts # Main adapter implementation
│ ├── types.ts # Platform-specific TypeScript types
│ ├── api.ts # API client wrapper
│ ├── auth.ts # Authentication logic
│ ├── normalizer.ts # Data normalization
│ └── __tests__/
│ ├── adapter.test.ts
│ ├── auth.test.ts
│ └── normalizer.test.ts
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── README.md
└── .env.example # Example credentials (NEAR commit real keys!)

Package.json Example​

{
"name": "@idiomark/adapter-myplatform",
"version": "1.0.0",
"description": "MyPlatform adapter for Idiomark extraction",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"test": "vitest",
"test:coverage": "vitest --coverage",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@idiomark/core": "workspace:*"
},
"devDependencies": {
"@idiomark/tsconfig": "workspace:*",
"typescript": "^5.7.3",
"tsup": "^8.4.0",
"vitest": "^2.0.0",
"@vitest/coverage-v8": "^2.0.0"
}
}

Implementation Guidelines​

1. Implement the PlatformAdapter Interface​

// src/index.ts
import type {
PlatformAdapter,
NormalizedContent,
RawContent,
FetchOptions
} from '@idiomark/core'

export interface MyPlatformAuth {
accessToken: string
userId?: string
}

export class MyPlatformAdapter implements PlatformAdapter {
readonly name = 'myplatform'
private auth: MyPlatformAuth
private baseUrl = 'https://api.myplatform.com'

constructor(auth: MyPlatformAuth) {
this.auth = auth
}

async authenticate(): Promise<boolean> {
try {
const response = await fetch(`${this.baseUrl}/verify`, {
headers: {
'Authorization': `Bearer ${this.auth.accessToken}`
}
})
return response.ok
} catch {
return false
}
}

async fetchData(options: FetchOptions): Promise<RawContent[]> {
const { limit = 100, startDate, endDate } = options

// Fetch data from the platform
const posts = await this.fetchPosts(limit, startDate, endDate)
const comments = await this.fetchComments(limit, startDate, endDate)

return [...posts, ...comments]
}

normalize(raw: RawContent): NormalizedContent {
return {
id: raw.id,
platform: this.name,
type: raw.type,
text: raw.text,
timestamp: raw.created_at,
author: {
id: raw.author.id,
username: raw.author.username,
name: raw.author.name
},
metrics: {
likes: raw.likes_count,
shares: raw.shares_count,
replies: raw.replies_count
},
raw: raw
}
}

private async fetchPosts(
limit: number,
start?: Date,
end?: Date
): Promise<RawContent[]> {
// Platform-specific implementation
}

private async fetchComments(
limit: number,
start?: Date,
end?: Date
): Promise<RawContent[]> {
// Platform-specific implementation
}
}

2. Add Proper TypeScript Types​

// src/types.ts
export interface MyPlatformUser {
id: string
username: string
display_name: string
avatar_url: string
created_at: string
}

export interface MyPlatformPost {
id: string
text: string
created_at: string
author: MyPlatformUser
likes_count: number
shares_count: number
replies_count: number
type: 'post' | 'comment' | 'reply'
}

export interface MyPlatformResponse<T> {
data: T[]
pagination?: {
next_cursor?: string
has_more: boolean
}
}

3. Handle Rate Limiting​

// src/rate-limiter.ts
export class RateLimiter {
private requests: number[] = []
private readonly maxRequests: number
private readonly windowMs: number

constructor(maxRequests: number, windowSeconds: number) {
this.maxRequests = maxRequests
this.windowMs = windowSeconds * 1000
}

async wait(): Promise<void> {
const now = Date.now()
this.requests = this.requests.filter(t => now - t < this.windowMs)

if (this.requests.length >= this.maxRequests) {
const oldestRequest = this.requests[0]
const waitTime = this.windowMs - (now - oldestRequest)
await new Promise(resolve => setTimeout(resolve, waitTime))
}

this.requests.push(Date.now())
}
}

// Usage in adapter
private rateLimiter = new RateLimiter(300, 900) // 300 requests per 15 minutes

async fetchData(options: FetchOptions): Promise<RawContent[]> {
await this.rateLimiter.wait()
// ... make request
}

4. Add Error Handling​

// src/errors.ts
export class AdapterError extends Error {
constructor(
message: string,
public code: string,
public retryable: boolean = false
) {
super(message)
this.name = 'AdapterError'
}
}

export class AuthError extends AdapterError {
constructor(message: string) {
super(message, 'AUTH_ERROR', false)
this.name = 'AuthError'
}
}

export class RateLimitError extends AdapterError {
constructor(retryAfter?: number) {
super('Rate limit exceeded', 'RATE_LIMIT', true)
this.name = 'RateLimitError'
this.retryAfter = retryAfter
}
retryAfter?: number
}

// Usage
if (response.status === 401) {
throw new AuthError('Invalid access token')
}

if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After')
throw new RateLimitError(retryAfter ? parseInt(retryAfter) : undefined)
}

5. Add Metadata Enrichment​

// src/normalizer.ts
export function enrichMetadata(
normalized: NormalizedContent,
raw: any
): NormalizedContent {
return {
...normalized,
metadata: {
language: raw.lang || 'en',
has_media: !!raw.media?.length,
hashtags: raw.entities?.hashtags?.map((h: any) => h.text) || [],
mentions: raw.entities?.mentions?.map((m: any) => m.username) || [],
urls: raw.entities?.urls?.map((u: any) => u.expanded_url) || [],
is_reply: !!raw.in_reply_to_id,
is_quote: !!raw.quoted_post_id,
platform_specific: {
// Add any platform-specific fields here
}
}
}
}

Testing Your Adapter​

Unit Tests​

Create comprehensive unit tests:

// src/__tests__/adapter.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { MyPlatformAdapter } from '../index'

describe('MyPlatformAdapter', () => {
let adapter: MyPlatformAdapter
let mockAuth = {
accessToken: 'test-token',
userId: 'test-user'
}

beforeEach(() => {
adapter = new MyPlatformAdapter(mockAuth)
vi.clearAllMocks()
})

describe('authenticate()', () => {
it('should return true for valid credentials', async () => {
const result = await adapter.authenticate()
expect(result).toBe(true)
})

it('should return false for invalid credentials', async () => {
const badAdapter = new MyPlatformAdapter({ accessToken: 'bad' })
const result = await badAdapter.authenticate()
expect(result).toBe(false)
})
})

describe('normalize()', () => {
it('should normalize a post correctly', () => {
const raw = {
id: '123',
type: 'post',
text: 'Hello world',
created_at: '2026-02-10T00:00:00Z',
author: {
id: '1',
username: 'testuser',
name: 'Test User'
},
likes_count: 10,
shares_count: 5,
replies_count: 2
}

const normalized = adapter.normalize(raw)

expect(normalized).toEqual({
id: '123',
platform: 'myplatform',
type: 'post',
text: 'Hello world',
timestamp: '2026-02-10T00:00:00Z',
author: {
id: '1',
username: 'testuser',
name: 'Test User'
},
metrics: {
likes: 10,
shares: 5,
replies: 2
},
raw: raw
})
})
})

describe('fetchData()', () => {
it('should fetch data within date range', async () => {
const start = new Date('2026-01-01')
const end = new Date('2026-01-31')

const data = await adapter.fetchData({
limit: 50,
startDate: start,
endDate: end
})

expect(data.length).toBeGreaterThan(0)
data.forEach(item => {
const date = new Date(item.created_at)
expect(date.getTime()).toBeGreaterThanOrEqual(start.getTime())
expect(date.getTime()).toBeLessThanOrEqual(end.getTime())
})
})

it('should handle rate limiting', async () => {
// Mock many requests to test rate limiting
const promises = Array.from({ length: 350 }, (_, i) =>
adapter.fetchData({ limit: 1 })
)

await expect(Promise.all(promises)).resolves.toBeDefined()
})
})
})

Test Coverage​

We require >80% test coverage for all adapters:

# Run tests with coverage
pnpm test:coverage

# View coverage report
open coverage/index.html

Integration Tests​

Test with real API credentials (locally only):

// src/__tests__/integration.test.ts
import { describe, it, expect } from 'vitest'

describe.runIf(process.env.TEST_ADAPTER === 'myplatform')(
'MyPlatformAdapter Integration',
() => {
it('should fetch real data from the platform', async () => {
const adapter = new MyPlatformAdapter({
accessToken: process.env.MYPLATFORM_TOKEN!,
userId: process.env.MYPLATFORM_USER_ID!
})

const isValid = await adapter.authenticate()
expect(isValid).toBe(true)

const data = await adapter.fetchData({ limit: 10 })
expect(data.length).toBeGreaterThan(0)
})
}
)

Submitting Your Adapter​

Pre-Flight Checklist​

Before submitting, verify:

  • Adapter implements PlatformAdapter interface
  • All TypeScript types are defined
  • Rate limiting is implemented
  • Error handling covers all edge cases
  • Test coverage is >80%
  • README with API docs and examples
  • No hardcoded credentials
  • Builds without warnings
  • Linting passes
  • All tests pass

Validation Command​

Run the adapter validation script:

# Validate your adapter
pnpm adapter validate myplatform

# Expected output:
# ✅ Adapter implements PlatformAdapter interface
# ✅ TypeScript types are complete
# ✅ Rate limiting is configured
# ✅ Error handling is implemented
# ✅ Test coverage: 87.5% (>80% required)
# ✅ README is complete
# ✅ No hardcoded credentials found
# ✅ Build succeeds
#
# Adapter is ready for submission! 🎉

Creating a Pull Request​

  1. Create a feature branch:

    git checkout -b adapter/myplatform
  2. Commit your changes:

    git add packages/adapters/myplatform
    git commit -m "feat: add MyPlatform adapter

    - Implements OAuth 2.0 authentication
    - Fetches posts and comments
    - Handles rate limiting (300 req/15min)
    - Test coverage: 87%

    Closes #123"
  3. Push to your fork:

    git push origin adapter/myplatform
  4. Create a PR using the adapter PR template

Code Review Process​

Review Timeline​

  • Initial review: 2-3 business days
  • Address feedback: 1 week
  • Final review: 2-3 business days
  • Merge: After 2+ maintainer approvals

Review Criteria​

Maintainers will check:

  1. Interface Compliance: Does it implement PlatformAdapter correctly?
  2. Type Safety: Are all types properly defined?
  3. Error Handling: Are edge cases covered?
  4. Rate Limiting: Does it respect API limits?
  5. Test Coverage: Is coverage >80%?
  6. Documentation: Is the README complete?
  7. Security: Are credentials handled safely?

Common Feedback​

IssueSolution
Missing error handlingAdd try/catch with specific error types
Low test coverageAdd tests for edge cases and error paths
Hardcoded credentialsUse environment variables or config files
Incomplete typesDefine all API response fields
Rate limiting issuesImplement proper rate limiter class

What Makes a "Good" Adapter​

Essential Qualities​

  • Reliable: Works consistently across different inputs
  • Performant: Minimizes API calls and uses caching
  • Resilient: Handles errors gracefully and recovers
  • Well-documented: Clear README with examples
  • Well-tested: Comprehensive test coverage
  • Type-safe: Full TypeScript definitions

Anti-Patterns to Avoid​

  • Hardcoding credentials
  • Ignoring rate limits
  • Swallowing errors silently
  • Making unnecessary API calls
  • Duplicating code (use shared utilities)
  • Inconsistent naming conventions

Best Practices​

  1. Use the shared rate limiter from @idiomark/core
  2. Follow the adapter template structure
  3. Add JSDoc comments for all public methods
  4. Provide example output in README
  5. Include troubleshooting section for common issues
  6. Link to official API docs with authentication guide
  7. Specify data retention policy (what gets cached)

Example Good Adapters​

Getting Help​

Resources​

Community​

  • GitHub Issues: Bug reports and feature requests
  • GitHub Discussions: General questions and ideas
  • Discord: (link to Discord server)

Contact​

For urgent issues or security concerns, email: dev.23.xyz@gmail.com


Ready to contribute? Check out bounties.yaml and claim an adapter today!