Building Platform Adapters
Guide for creating Idiomark platform adapters for data extraction.
Overview
A Idiomark Adapter fetches data from a platform and normalizes it for personality extraction.
Adapter Architecture
┌─────────────────────────────────────────────────────────────┐
│ Platform Adapter │
├─────────────────────────────────────────────────────────────┤
│ 1. OAuth authentication │
│ 2. Data fetching (posts, comments, reactions) │
│ 3. Normalization to intermediate format │
│ 4. Metadata enrichment │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Idiomark Core │
├─────────────────────────────────────────────────────────────┤
│ • Aggregates data from all adapters │
│ • Runs personality analysis │
│ • Generates .idiomark file │
└─────────────────────────────────────────────────────────────┘
Creating an Adapter
1. Package Structure
mkdir -p packages/adapters/myplatform/src
cd packages/adapters/myplatform
# package.json
cat > package.json << 'EOF'
{
"name": "@idiomark/adapter-myplatform",
"version": "1.0.0",
"description": "MyPlatform adapter for Idiomark extraction",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsup",
"dev": "tsup --watch"
},
"dependencies": {
"@idiomark/core": "workspace:*"
},
"devDependencies": {
"typescript": "^5.7.3",
"tsup": "^8.4.0"
}
}
EOF
2. Implement the Interface
// src/index.ts
import type { PlatformAdapter, NormalizedContent } from '@idiomark/core'
export interface MyPlatformAuth {
accessToken: string
userId: string
}
export class MyPlatformAdapter implements PlatformAdapter {
readonly name = 'myplatform'
private auth: MyPlatformAuth
constructor(auth: MyPlatformAuth) {
this.auth = auth
}
async authenticate(): Promise<boolean> {
// Validate auth tokens
try {
const response = await fetch('https://api.myplatform.com/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 posts, comments, reactions
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, // 'post' | 'comment' | 'reply'
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 // Keep original for debugging
}
}
private async fetchPosts(limit: number, start?: Date, end?: Date) {
// Platform-specific API calls
const response = await fetch(
`https://api.myplatform.com/users/${this.auth.userId}/posts?limit=${limit}`,
{
headers: {
'Authorization': `Bearer ${this.auth.accessToken}`
}
}
)
return response.json()
}
private async fetchComments(limit: number, start?: Date, end?: Date) {
// Similar implementation
}
}
3. Register with Core
// In your app or CLI
import { IdiomarkExtractor } from '@idiomark/core'
import { MyPlatformAdapter } from '@idiomark/adapter-myplatform'
const extractor = new IdiomarkExtractor({
sources: ['myplatform'],
sampleSize: 1000
})
// Register adapter
extractor.registerAdapter('myplatform', new MyPlatformAdapter({
accessToken: process.env.MYPLATFORM_TOKEN,
userId: 'user123'
}))
const result = await extractor.extract()
Adapter Interface
interface PlatformAdapter {
readonly name: string
// Authenticate with the platform
authenticate(): Promise<boolean>
// Fetch raw data from platform
fetchData(options: FetchOptions): Promise<RawContent[]>
// Normalize to Idiomark intermediate format
normalize(raw: RawContent): NormalizedContent
}
interface FetchOptions {
limit?: number
startDate?: Date
endDate?: Date
includeReplies?: boolean
includeReactions?: boolean
}
interface RawContent {
id: string
type: string
text: string
created_at: string
author: {
id: string
username: string
name: string
}
[key: string]: any
}
interface NormalizedContent {
id: string
platform: string
type: 'post' | 'comment' | 'reply'
text: string
timestamp: string
author: {
id: string
username: string
name: string
}
metrics?: {
likes?: number
shares?: number
replies?: number
}
raw: any
}
Platform-Specific Considerations
Twitter/X
// API v2
const response = await fetch('https://api.twitter.com/2/users/:id/tweets', {
headers: { 'Authorization': `Bearer ${token}` }
})
// Handle rate limits: 300 requests per 3 hours
// Pagination: use `next_token` from response meta
GitHub
// Issues and PRs include discussions
const issues = await fetch('https://api.github.com/user/issues', {
headers: { 'Authorization': `token ${token}` }
})
// Comments are in issue threads
// Rate limit: 5000 requests per hour
Reddit
// Use JSON API (no OAuth for public data)
const posts = await fetch('https://www.reddit.com/user/:username/posts.json')
// Rate limit handling via `x-ratelimit-remaining` header
LinkedIn
// Requires OAuth 2.0
const posts = await fetch('https://api.linkedin.com/v2/ugcPosts', {
headers: { 'Authorization': `Bearer ${token}` }
})
// Strict rate limits: 100+ requests per day
Best Practices
1. Rate Limiting
class MyPlatformAdapter implements PlatformAdapter {
private rateLimiter = new RateLimiter({
requests: 300,
window: 3 * 60 * 60 * 1000 // 3 hours
})
async fetchData(options: FetchOptions) {
await this.rateLimiter.wait()
return await this.fetchPosts(options)
}
}
2. Error Handling
async fetchData(options: FetchOptions) {
try {
const response = await this.fetchPosts(options)
if (response.status === 429) {
// Rate limited - wait and retry
const retryAfter = response.headers.get('Retry-After')
await sleep(parseInt(retryAfter) * 1000)
return this.fetchData(options)
}
if (response.status === 401) {
throw new AuthError('Token expired')
}
return response.json()
} catch (error) {
if (error instanceof AuthError) {
// Re-authenticate
}
throw error
}
}
3. Data Filtering
async fetchData(options: FetchOptions) {
let data = await this.fetchPosts(options)
// Filter by date range
if (options.startDate || options.endDate) {
data = data.filter(post => {
const date = new Date(post.created_at)
if (options.startDate && date < options.startDate) return false
if (options.endDate && date > options.endDate) return false
return true
})
}
// Remove reposts/shares
data = data.filter(post => !post.retweeted_status)
return data
}
4. Metadata Enrichment
normalize(raw: RawContent): NormalizedContent {
return {
// ... base fields
metadata: {
// Platform-specific metadata
language: raw.lang,
is_reply: !!raw.in_reply_to_status_id,
is_quote: !!raw.quoted_status_id,
hashtags: raw.entities?.hashtags?.map((h: any) => h.text),
mentions: raw.entities?.user_mentions?.map((m: any) => m.screen_name),
urls: raw.entities?.urls?.map((u: any) => u.expanded_url)
}
}
}
Testing
// src/__tests__/adapter.test.ts
import { MyPlatformAdapter } from '../index'
describe('MyPlatformAdapter', () => {
it('should authenticate successfully', async () => {
const adapter = new MyPlatformAdapter({
accessToken: 'test-token',
userId: 'test-user'
})
const isValid = await adapter.authenticate()
expect(isValid).toBe(true)
})
it('should normalize content correctly', () => {
const adapter = new MyPlatformAdapter(auth)
const normalized = adapter.normalize({
id: '123',
type: 'post',
text: 'Hello world',
created_at: '2026-02-10T00:00:00Z',
author: { id: '1', username: 'test', name: 'Test User' }
})
expect(normalized.platform).toBe('myplatform')
expect(normalized.text).toBe('Hello world')
})
})
Publishing
# Build
pnpm build
# Test
pnpm test
# Publish to npm (if publishing to public registry)
npm publish --access public
# Or install locally
pnpm install
Contributing
When contributing a new adapter to Idiomark:
- Follow the naming convention:
@idiomark/adapter-{platform} - Include tests and documentation
- Handle rate limits gracefully
- Support error recovery
- Follow the code style guide
See contributing.md for more details.