Idiomark Adapter Framework
A scalable, plugin-based architecture for connecting 500+ platforms to the Idiomark
Table of Contents
- Overview
- Design Principles
- Architecture
- Base Adapter Class
- Adapter Templates
- Config-Driven Adapters
- Adapter Registry
- Adapter Generator CLI
- Testing Framework
- Performance Optimization
- Migration Guide
- Examples
Overview
The Idiomark Adapter Framework is a comprehensive system for creating and managing platform adapters that extract personality data from any source. It scales to support 500+ services while maintaining simplicity for developers.
Key Features
- Convention over Configuration - Default behaviors that work for 80% of services
- Plugin Architecture - Drop-in adapters with minimal setup
- Unified Interface - All adapters output the same
NormalizedContentformat - Built-in Rate Limiting - Automatic rate limit handling per service
- Error Recovery - Graceful degradation when services fail
- Intelligent Caching - Reduce API calls by caching results
- Type Safety - Full TypeScript support with generated types
- Testing Infrastructure - Automated testing for all adapters
Why This Architecture Matters
Traditional Approach:
┌─────────────────────────────────────────────────────────────────┐
│ Twitter Adapter │ GitHub Adapter │ Reddit Adapter │ ... 497 more │
│ ├─fetch() │ ├─fetch() │ ├─fetch() │ │
│ ├─normalize() │ ├─normalize() │ ├─normalize() │ │
│ ├─rate limit │ ├─rate limit │ ├─rate limit │ │
│ ├─cache │ ├─cache │ ├─cache │ │
│ ├─retry │ ├─retry │ ├─retry │ │
│ └─auth │ └─auth │ └─auth │ │
└─────────────────────────────────────────────────────────────────┘
Result: 500 x 6 = 3,000 implementations to maintain
Idiomark Framework Approach:
┌─────────────────────────────────────────────────────────────────┐
│ BaseAdapter (Core) │
│ ├─ Rate Limiter ├─ Cache Manager ├─ Retry Handler ├─ Auth │
│ └─ Error Handler └─ Metrics └─ Logger └─ ... │
└─────────────────────────────────────────────────────────────────┘
↓ ↓ ↓ ↓
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Twitter │ │ GitHub │ │ Reddit │ │ ... 497 more │
│ ├─fetch() │ │ ├─fetch() │ │ ├─fetch() │ │ │
│ └─normalize()│ │ └─normalize()│ │ └─normalize()│ │ │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
Result: 1 core + 500 x 2 = 1,001 implementations to maintain
Design Principles
1. Convention Over Configuration
The framework provides smart defaults for common patterns:
// Automatic behavior for 80% of APIs
class MyAdapter extends RESTAdapterTemplate {
// Only specify what's different
baseURL = 'https://api.example.com'
defaultLimit = 100
// Everything else (auth, rate limiting, caching) works out of the box
}
2. Progressive Enhancement
Start simple, add complexity only when needed:
// Level 1: Config-only (simplest)
export const redditAdapter = defineAdapter({
name: 'reddit',
api: 'https://www.reddit.com/r/${subreddit}/hot.json',
extract: { /* ... */ }
})
// Level 2: Template-based (most common)
export const githubAdapter = class extends RESTAdapterTemplate {
// Custom fetch logic
}
// Level 3: Full custom (complex APIs)
export const twitterAdapter = class extends BaseAdapter {
// Complete custom implementation
}
3. Fail-Safe by Default
// Adapters never crash the extraction process
try {
const content = await adapter.fetchData()
} catch (error) {
// Log error, return partial results, continue extraction
return adapter.fetchFallbackData()
}
4. Observable Everything
// All adapter operations are observable
adapter.on('rateLimit', (waitTime) => console.log(`Waiting ${waitTime}ms`))
adapter.on('error', (error) => console.error(error))
adapter.on('fetch', (item) => metrics.increment('items.fetched'))
Architecture
Component Diagram
┌─────────────────────────────────────────────────────────────────────────────┐
│ Idiomark Adapter Framework │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Adapter Registry │ │
│ │ - Discover adapters │ │
│ │ - Load adapters dynamically │ │
│ │ - Manage adapter lifecycle │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Base Adapter │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐ │ │
│ │ │ Rate Limiter │ │ Cache Mgr │ │ Retry Handler│ │ Auth Mgr │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────┘ │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐ │ │
│ │ │ Error Handler│ │ Metrics │ │ Logger │ │ Events │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Adapter Templates │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────┐ │ │
│ │ │ REST │ │ GraphQL │ │ Scraping │ │ RSS │ │ Email │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └───────────┘ │ │
│ │ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Forum │ │ Custom │ │ │
│ │ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Config-Driven Adapters │ │
│ │ - YAML/JSON definitions │ │
│ │ - Auto-generate adapter code │ │
│ │ - Hot-reload configs │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Platform Adapters │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────┐ │ │
│ │ │ Twitter │ │ GitHub │ │ Reddit │ │ LinkedIn │ │ ... │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └───────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Data Flow
┌──────────────────────────────────────────────────────────────────────────────┐
│ Data Extraction Flow │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ User Request │
│ ↓ │
│ ┌──────────────────┐ │
│ │ Adapter Registry │ → Get/Load adapter │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ Base Adapter │ → Initialize (auth, rate limiter, cache) │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ fetchContent() │ → Fetch from platform (with retry, rate limit) │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ normalize() │ → Transform to NormalizedContent │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ validate() │ → Validate output format │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ enrich() │ → Add metadata, metrics │
│ └──────────────────┘ │
│ ↓ │
│ NormalizedContent[] → Return to extractor │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
Base Adapter Class
The BaseAdapter class provides all common functionality. Platform-specific adapters only need to implement the fetch and normalize logic.
Class Definition
/**
* Base adapter class with built-in functionality
*
* Provides:
* - Rate limiting (token bucket algorithm)
* - Response caching (TTL-based)
* - Request retry (exponential backoff)
* - Authentication management
* - Error handling and recovery
* - Metrics and logging
* - Event emission
*/
export abstract class BaseAdapter implements PlatformAdapter {
// ============================================================
// Abstract methods (must be implemented by subclasses)
// ============================================================
/**
* Fetch raw content from the platform
* @param options - Fetch options (limit, date range, etc.)
* @returns Promise of raw content array
*/
abstract fetchContent(options: FetchOptions): Promise<RawContent[]>
/**
* Normalize raw content to Idiomark format
* @param raw - Raw content from platform
* @returns Normalized content in Idiomark format
*/
abstract normalize(raw: RawContent): NormalizedContent
// ============================================================
// Optional overrides (provide sensible defaults)
// ============================================================
/**
* Authenticate with the platform
* Default: Returns true (no auth required)
*/
async authenticate(): Promise<boolean> {
return true
}
/**
* Validate configuration before fetching
* Default: Checks required auth fields
*/
async validate(): Promise<boolean> {
return true
}
// ============================================================
// Built-in functionality (no implementation needed)
// ============================================================
/**
* Rate limiter instance (auto-configured)
*/
protected readonly rateLimiter: RateLimiter
/**
* Cache manager instance (auto-configured)
*/
protected readonly cache: CacheManager
/**
* Retry handler instance (auto-configured)
*/
protected readonly retry: RetryHandler
/**
* Authentication manager instance (auto-configured)
*/
protected readonly auth: AuthManager
/**
* Event emitter for adapter lifecycle events
*/
protected readonly emitter: EventEmitter
// ============================================================
// High-level methods (use built-in functionality)
// ============================================================
/**
* Main extraction method with automatic retry, caching, and rate limiting
*/
async extract(options: FetchOptions): Promise<NormalizedContent[]> {
// 1. Check cache
const cached = await this.cache.get(options)
if (cached) {
this.emitter.emit('cacheHit', { options })
return cached
}
// 2. Rate limit
await this.rateLimiter.throttle()
// 3. Fetch with retry
const raw = await this.retry.execute(() => this.fetchContent(options))
// 4. Normalize
const normalized = raw.map(item => this.normalize(item))
// 5. Cache result
await this.cache.set(options, normalized)
// 6. Return
return normalized
}
/**
* Fetch with progress callback for large datasets
*/
async extractWithProgress(
options: FetchOptions,
onProgress: (progress: ExtractionProgress) => void
): Promise<NormalizedContent[]> {
let fetched = 0
const total = options.limit || 100
const results: NormalizedContent[] = []
// Fetch in batches
for await (const batch of this.fetchInBatches(options)) {
results.push(...batch.map(item => this.normalize(item)))
fetched += batch.length
onProgress({
fetched,
total,
percent: (fetched / total) * 100,
currentBatch: batch
})
}
return results
}
/**
* Health check for adapter
*/
async healthCheck(): Promise<AdapterHealth> {
const start = Date.now()
try {
const isAuthenticated = await this.authenticate()
const latency = Date.now() - start
return {
healthy: isAuthenticated,
latency,
rateLimit: this.rateLimiter.getStatus(),
cache: this.cache.getStats(),
retry: this.retry.getStats()
}
} catch (error) {
return {
healthy: false,
latency: Date.now() - start,
error: error instanceof Error ? error.message : String(error)
}
}
}
// ============================================================
// Utility methods
// ============================================================
/**
* Get adapter metrics
*/
getMetrics(): AdapterMetrics {
return {
requests: this.rateLimiter.getRequestCount(),
cacheHits: this.cache.getHitCount(),
cacheMisses: this.cache.getMissCount(),
retries: this.retry.getRetryCount(),
errors: this.errorHandler.getErrorCount(),
avgLatency: this.metrics.getAverageLatency()
}
}
/**
* Reset adapter state (clear cache, reset rate limits, etc.)
*/
async reset(): Promise<void> {
await this.cache.clear()
this.rateLimiter.reset()
this.retry.reset()
this.emitter.emit('reset')
}
/**
* Dispose of adapter resources
*/
async dispose(): Promise<void> {
await this.cache.close()
this.emitter.removeAllListeners()
this.emitter.emit('dispose')
}
}
Rate Limiter
/**
* Token bucket rate limiter
*
* Features:
* - Token bucket algorithm
* - Per-endpoint limits
* - Dynamic limit adjustment based on headers
* - Wait time prediction
*/
export class RateLimiter {
private tokens: number
private lastRefill: number
private config: RateLimiterConfig
constructor(config: RateLimiterConfig) {
this.config = config
this.tokens = config.maxTokens
this.lastRefill = Date.now()
}
/**
* Wait until a token is available
*/
async throttle(): Promise<void> {
this.refill()
if (this.tokens >= 1) {
this.tokens--
return
}
// Calculate wait time
const waitTime = this.calculateWaitTime()
this.emitter.emit('rateLimitWait', { waitTime })
await sleep(waitTime)
await this.throttle() // Retry after waiting
}
/**
* Update limits from response headers (e.g., X-RateLimit-Remaining)
*/
updateFromHeaders(headers: Headers): void {
const remaining = headers.get('x-ratelimit-remaining')
const reset = headers.get('x-ratelimit-reset')
const limit = headers.get('x-ratelimit-limit')
if (remaining !== null) {
this.tokens = parseInt(remaining, 10)
}
if (reset !== null) {
this.lastRefill = parseInt(reset, 10) * 1000
}
if (limit !== null) {
this.config.maxTokens = parseInt(limit, 10)
}
}
/**
* Get current rate limit status
*/
getStatus(): RateLimitStatus {
return {
tokensRemaining: this.tokens,
maxTokens: this.config.maxTokens,
resetAt: new Date(this.lastRefill + this.config.refillInterval),
waitTime: this.calculateWaitTime()
}
}
}
Cache Manager
/**
* Multi-level cache manager
*
* Features:
* - In-memory L1 cache (fast)
* - Persistent L2 cache (Redis/filesystem)
* - TTL-based expiration
* - Cache key generation
* - Cache stampede prevention
*/
export class CacheManager {
private l1Cache: LRUCache<string, CachedData>
private l2Cache?: RedisCache | FileCache
constructor(config: CacheConfig) {
this.l1Cache = new LRUCache({ max: 1000, ttl: config.ttl })
this.l2Cache = config.persistent ? createPersistentCache(config) : undefined
}
/**
* Get cached data
*/
async get(key: string | FetchOptions): Promise<NormalizedContent[] | null> {
const cacheKey = this.generateKey(key)
// Try L1 cache
const l1Data = this.l1Cache.get(cacheKey)
if (l1Data && !this.isExpired(l1Data)) {
this.metrics.recordHit('l1')
return l1Data.data
}
// Try L2 cache
if (this.l2Cache) {
const l2Data = await this.l2Cache.get(cacheKey)
if (l2Data && !this.isExpired(l2Data)) {
this.metrics.recordHit('l2')
// Promote to L1
this.l1Cache.set(cacheKey, l2Data)
return l2Data.data
}
}
this.metrics.recordMiss()
return null
}
/**
* Set cached data
*/
async set(key: string | FetchOptions, data: NormalizedContent[]): Promise<void> {
const cacheKey = this.generateKey(key)
const cachedData: CachedData = {
data,
cachedAt: Date.now(),
ttl: this.config.ttl
}
// Set in L1
this.l1Cache.set(cacheKey, cachedData)
// Set in L2
if (this.l2Cache) {
await this.l2Cache.set(cacheKey, cachedData)
}
}
/**
* Generate cache key from options
*/
private generateKey(key: string | FetchOptions): string {
if (typeof key === 'string') return key
return crypto
.createHash('sha256')
.update(JSON.stringify(key))
.digest('hex')
}
}
Retry Handler
/**
* Exponential backoff retry handler
*
* Features:
* - Exponential backoff with jitter
* - Maximum retry limit
* - Retryable error detection
* - Retry condition callbacks
*/
export class RetryHandler {
private config: RetryConfig
private attemptCount: number = 0
async execute<T>(
fn: () => Promise<T>,
options?: { isRetryable?: (error: Error) => boolean }
): Promise<T> {
let lastError: Error | undefined
for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
this.attemptCount++
try {
return await fn()
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error))
// Check if error is retryable
const isRetryable = options?.isRetryable
? options.isRetryable(lastError)
: this.isRetryableError(lastError)
if (!isRetryable || attempt === this.config.maxRetries - 1) {
throw lastError
}
// Calculate backoff with jitter
const backoff = this.calculateBackoff(attempt)
this.emitter.emit('retry', { attempt, backoff, error: lastError })
await sleep(backoff)
}
}
throw lastError
}
/**
* Check if error is retryable
*/
private isRetryableError(error: Error): boolean {
// Retry on network errors, rate limits, and server errors
const retryablePatterns = [
/ECONNRESET/,
/ETIMEDOUT/,
/ENOTFOUND/,
/429/, // Rate limit
/50[0-4]/ // Server errors
]
return retryablePatterns.some(pattern =>
pattern.test(error.message) || pattern.test(error.name)
)
}
/**
* Calculate exponential backoff with jitter
*/
private calculateBackoff(attempt: number): number {
const baseDelay = this.config.baseDelay
const maxDelay = this.config.maxDelay
// Exponential backoff
const exponentialDelay = baseDelay * Math.pow(2, attempt)
// Add jitter (random +/- 25%)
const jitter = exponentialDelay * 0.25 * (Math.random() * 2 - 1)
return Math.min(exponentialDelay + jitter, maxDelay)
}
}
Adapter Templates
Templates provide pre-built implementations for common API patterns. Just extend and customize.
REST API Template
For standard REST APIs with pagination:
/**
* REST API Adapter Template
*
* For: Standard REST APIs with JSON responses
* Features: Automatic pagination, query building, response parsing
*/
export abstract class RESTAdapterTemplate extends BaseAdapter {
protected abstract baseURL: string
protected abstract endpoints: Record<string, string>
/**
* Default fetch implementation with pagination
*/
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const results: RawContent[] = []
let page = 1
let hasMore = true
while (hasMore && results.length < (options.limit || 100)) {
const response = await this.makeRequest({
endpoint: this.endpoint,
params: {
page,
per_page: Math.min(100, (options.limit || 100) - results.length),
...this.buildQueryParams(options)
}
})
results.push(...response.data)
hasMore = response.data.length > 0 && this.hasMorePages(response)
page++
}
return results
}
/**
* Make authenticated request
*/
protected async makeRequest(config: RequestConfig): Promise<ApiResponse> {
const headers = await this.getHeaders()
const response = await fetch(
this.buildURL(config.endpoint, config.params),
{ headers, ...config.options }
)
// Update rate limits from headers
this.rateLimiter.updateFromHeaders(response.headers)
if (!response.ok) {
throw new APIError(response.statusText, response.status)
}
return response.json()
}
/**
* Build URL from endpoint and params
*/
protected buildURL(endpoint: string, params?: Record<string, any>): string {
const url = new URL(endpoint, this.baseURL)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
}
return url.toString()
}
/**
* Check if response has more pages
*/
protected hasMorePages(response: ApiResponse): boolean {
// Check for common pagination patterns
return !!(
response.links?.next ||
response.meta?.has_more ||
response.pagination?.hasNext
)
}
/**
* Build query params from fetch options
*/
protected buildQueryParams(options: FetchOptions): Record<string, any> {
const params: Record<string, any> = {}
if (options.startDate) {
params.since = options.startDate.toISOString()
}
if (options.endDate) {
params.until = options.endDate.toISOString()
}
return params
}
}
Example Usage:
// GitHub adapter using REST template
export class GitHubAdapter extends RESTAdapterTemplate {
protected baseURL = 'https://api.github.com'
protected endpoints = {
user: '/user',
repos: '/users/{username}/repos',
commits: '/repos/{owner}/{repo}/commits'
}
normalize(raw: RawContent): NormalizedContent {
// GitHub-specific normalization
return {
id: raw.id,
platform: 'github',
type: raw.type,
text: raw.message || raw.body || raw.content,
timestamp: raw.created_at,
author: {
id: raw.author?.id,
username: raw.author?.login,
name: raw.author?.name
},
raw
}
}
}
GraphQL Template
For GraphQL APIs:
/**
* GraphQL Adapter Template
*
* For: GraphQL endpoints
* Features: Query building, response parsing, automatic pagination via cursors
*/
export abstract class GraphQLAdapterTemplate extends BaseAdapter {
protected abstract baseURL: string
protected abstract queryBuilder: QueryBuilder
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const results: RawContent[] = []
let cursor: string | null = null
let hasMore = true
while (hasMore && results.length < (options.limit || 100)) {
const query = this.queryBuilder.build({
cursor,
first: Math.min(100, (options.limit || 100) - results.length),
...this.buildQueryVariables(options)
})
const response = await this.makeRequest(query)
const data = this.queryBuilder.parse(response)
results.push(...data.items)
hasMore = data.pageInfo.hasNextPage
cursor = data.pageInfo.endCursor
}
return results
}
protected async makeRequest(query: string): Promise<any> {
const response = await fetch(this.baseURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(await this.getHeaders())
},
body: JSON.stringify({ query })
})
if (!response.ok) {
throw new APIError(response.statusText, response.status)
}
const json = await response.json()
if (json.errors) {
throw new GraphQLError(json.errors[0].message)
}
return json.data
}
}
Scraping Template
For sites without APIs:
/**
* Scraping Adapter Template
*
* For: Websites without public APIs
* Features: HTML parsing, pagination, rate limiting, JavaScript rendering
*/
export abstract class ScrapingAdapterTemplate extends BaseAdapter {
protected abstract baseURL: string
protected abstract selectors: Record<string, string>
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const results: RawContent[] = []
let page = 1
let hasMore = true
while (hasMore && results.length < (options.limit || 100)) {
const url = this.buildURL(page, options)
const html = await this.fetchHTML(url)
const items = this.parseHTML(html)
results.push(...items)
hasMore = this.hasNextPage(html)
page++
// Be extra polite when scraping
await sleep(this.getPoliteDelay())
}
return results
}
protected async fetchHTML(url: string): Promise<string> {
const response = await fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; Idiomark-Protocol/1.0)',
...(await this.getHeaders())
}
})
if (!response.ok) {
throw new ScrapingError(`Failed to fetch ${url}`, response.status)
}
return response.text()
}
protected parseHTML(html: string): RawContent[] {
const $ = cheerio.load(html)
const items: RawContent[] = []
$(this.selectors.item).each((_, element) => {
const $item = $(element)
items.push({
id: $item.attr(this.selectors.id) || generateId(),
type: 'post',
text: $item.find(this.selectors.text).text().trim(),
created_at: $item.find(this.selectors.timestamp).attr('datetime') || new Date().toISOString(),
author: {
id: $item.find(this.selectors.authorId).text() || 'unknown',
username: $item.find(this.selectors.authorName).text() || 'unknown',
name: $item.find(this.selectors.authorName).text() || 'unknown'
},
raw: $.html($item)
})
})
return items
}
protected getPoliteDelay(): number {
// Random delay between 1-3 seconds to be polite
return 1000 + Math.random() * 2000
}
}
RSS/Feed Template
For RSS/Atom feeds:
/**
* RSS/Feed Adapter Template
*
* For: RSS and Atom feeds
* Features: Feed parsing, automatic encoding handling, feed discovery
*/
export abstract class RSSTemplate extends BaseAdapter {
protected abstract feedURL: string
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const feed = await this.fetchFeed()
const items = this.parseFeed(feed)
return items
.filter(item => this.filterByDate(item, options))
.slice(0, options.limit || 100)
}
protected async fetchFeed(): Promise<string> {
const response = await fetch(this.feedURL, {
headers: {
'Accept': 'application/rss+xml, application/atom+xml, application/xml, text/xml'
}
})
if (!response.ok) {
throw new FeedError(`Failed to fetch feed: ${response.statusText}`)
}
return response.text()
}
protected parseFeed(xml: string): RawContent[] {
const feed = parser.parse(xml)
return feed.items.map(item => ({
id: item.guid || item.link || generateId(),
type: 'post',
text: `${item.title}\n\n${item.content || item.contentSnippet || ''}`,
created_at: item.pubDate || item.isoDate || new Date().toISOString(),
author: {
id: item.creator || 'unknown',
username: item.creator || 'unknown',
name: item.creator || 'unknown'
},
metadata: {
link: item.link,
categories: item.categories || [],
enclosure: item.enclosure
},
raw: item
}))
}
private filterByDate(item: RawContent, options: FetchOptions): boolean {
const date = new Date(item.created_at)
if (options.startDate && date < options.startDate) return false
if (options.endDate && date > options.endDate) return false
return true
}
}
Email Template
For email providers (IMAP/Gmail API):
/**
* Email Adapter Template
*
* For: Email providers via IMAP or API
* Features: Folder scanning, attachment handling, threading
*/
export abstract class EmailTemplate extends BaseAdapter {
protected abstract connection: EmailConnection
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const emails = await this.fetchEmails(options)
return emails.map(email => this.emailToRawContent(email))
}
protected async fetchEmails(options: FetchOptions): Promise<Email[]> {
const limit = options.limit || 100
const startDate = options.startDate || new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)
return this.connection.search({
since: startDate,
limit
})
}
protected emailToRawContent(email: Email): RawContent {
// Extract text from email (prefer plain text, fallback to HTML)
const text = email.text || email.html?.replace(/<[^>]*>/g, '') || ''
return {
id: email.messageId,
type: 'email',
text: `${email.subject}\n\n${text}`,
created_at: email.date.toISOString(),
author: {
id: email.from.address,
username: email.from.address,
name: email.from.name || email.from.address
},
metadata: {
subject: email.subject,
to: email.to.map(t => t.address),
cc: email.cc?.map(t => t.address) || [],
hasAttachments: email.attachments?.length > 0
},
raw: email
}
}
}
Forum Template
For forum software (Discourse, phpBB, etc.):
/**
* Forum Adapter Template
*
* For: Forum software (Discourse, phpBB, xenForo, etc.)
* Features: Thread scanning, post parsing, user context
*/
export abstract class ForumTemplate extends BaseAdapter {
protected abstract baseURL: string
protected abstract forumType: 'discourse' | 'phpbb' | 'xenforo' | 'custom'
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const results: RawContent[] = []
// Fetch user's posts
const posts = await this.fetchPosts(options)
results.push(...posts)
// Fetch threads started by user
if (options.includeThreads !== false) {
const threads = await this.fetchThreads(options)
results.push(...threads)
}
return results
}
protected async fetchPosts(options: FetchOptions): Promise<RawContent[]> {
// Implementation varies by forum type
switch (this.forumType) {
case 'discourse':
return this.fetchDiscoursePosts(options)
case 'phpbb':
return this.fetchPhpBBPosts(options)
default:
return this.fetchCustomPosts(options)
}
}
protected async fetchDiscoursePosts(options: FetchOptions): Promise<RawContent[]> {
const username = this.auth.username
const url = `${this.baseURL}/user_actions.json?username=${username}&filter=5`
const response = await fetch(url)
const data = await response.json()
return data.user_actions.map(action => ({
id: `post_${action.post_id}`,
type: 'post',
text: action.cooked?.replace(/<[^>]*>/g, '') || action.raw || '',
created_at: action.created_at,
author: {
id: action.user_id.toString(),
username: action.username,
name: action.username
},
metadata: {
topicId: action.topic_id,
postId: action.post_id
},
raw: action
}))
}
}
Config-Driven Adapters
For simple APIs, define everything in a config file - no code needed.
Config Schema
# adapters/reddit/config.yml
name: reddit
displayName: Reddit
description: Reddit adapter for Idiomark extraction
# API Configuration
api:
baseURL: https://www.reddit.com
format: json
# Authentication
auth:
type: none # none, bearer_token, oauth2, api_key, basic
# Rate Limiting
rateLimit:
requests: 30
window: minute
strategy: token_bucket
# Endpoints
endpoints:
userPosts:
path: /user/${username}/submitted.json
method: GET
userComments:
path: /user/${username}/comments.json
method: GET
# Extraction Configuration
extraction:
# How to extract data from responses
mapping:
userPosts:
arrayPath: data.children[*].data
fields:
id:
source: id
required: true
text:
source: selftext
fallback: title
timestamp:
source: created_utc
transform: timestamp_to_iso
author:
id:
source: author
username:
source: author
name:
source: author
metrics:
likes:
source: score
replies:
source: num_comments
userComments:
arrayPath: data.children[*].data
fields:
id:
source: id
required: true
text:
source: body
timestamp:
source: created_utc
transform: timestamp_to_iso
type:
value: comment
# Post-processing
postProcess:
# Remove [deleted] posts
filter: text != '[deleted]' && author != '[deleted]'
# Decode HTML entities
transforms:
- name: decode_html_entities
field: text
# Remove URLs
transforms:
- name: remove_urls
field: text
# Caching
cache:
enabled: true
ttl: 300 # 5 minutes
Config Loader
/**
* Load adapter from config file
*/
export async function loadConfigAdapter(configPath: string): Promise<BaseAdapter> {
const config = await parseAdapterConfig(configPath)
// Generate adapter class from config
const adapterClass = generateAdapterClass(config)
// Instantiate with auth if needed
const auth = await resolveAuth(config.auth)
return new adapterClass(auth)
}
/**
* Generate adapter class from config
*/
function generateAdapterClass(config: AdapterConfig): new (auth?: any) => BaseAdapter {
return class extends RESTAdapterTemplate {
protected baseURL = config.api.baseURL
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const results: RawContent[] = []
for (const [endpointName, endpointConfig] of Object.entries(config.endpoints)) {
const mapping = config.extraction.mapping[endpointName]
const url = this.interpolateURL(endpointConfig.path, options)
const response = await fetch(url)
const data = await response.json()
const items = this.extractData(data, mapping)
results.push(...items)
}
return applyPostProcessing(results, config.postProcess)
}
normalize(raw: RawContent): NormalizedContent {
return raw as unknown as NormalizedContent
}
private extractData(data: any, mapping: ExtractionMapping): RawContent[] {
// Navigate to array using JSON path
const items = JSONPath({ path: mapping.arrayPath, json: data })
return items.map((item: any) => {
const result: any = {}
for (const [field, fieldConfig] of Object.entries(mapping.fields)) {
result[field] = this.extractField(item, fieldConfig)
}
return result as RawContent
})
}
private extractField(item: any, config: FieldConfig): any {
let value
// Get value from source
if (config.source) {
value = get(item, config.source)
} else if (config.value !== undefined) {
value = config.value
}
// Apply transform
if (config.transform) {
value = applyTransform(value, config.transform)
}
// Fallback
if (value === undefined && config.fallback) {
value = this.extractField(item, config.fallback as FieldConfig)
}
return value
}
}
}
Transform Functions
Built-in transforms for common data manipulations:
const transforms = {
timestamp_to_iso: (value: number) => new Date(value * 1000).toISOString(),
iso_to_timestamp: (value: string) => new Date(value).getTime() / 1000,
decode_html_entities: (value: string) => he.decode(value),
encode_html_entities: (value: string) => he.encode(value),
strip_html: (value: string) => value.replace(/<[^>]*>/g, ''),
strip_markdown: (value: string) => marked(value).replace(/<[^>]*>/g, ''),
remove_urls: (value: string) => value.replace(/https?:\/\/\S+/g, ''),
truncate: (value: string, maxLength: number) =>
value.length > maxLength ? value.slice(0, maxLength) + '...' : value,
lowercase: (value: string) => value.toLowerCase(),
uppercase: (value: string) => value.toUpperCase(),
trim: (value: string) => value.trim(),
split: (value: string, delimiter: string) => value.split(delimiter),
join: (value: string[], delimiter: string) => value.join(delimiter),
first: (value: any[]) => value[0],
last: (value: any[]) => value[value.length - 1],
length: (value: any[] | string) => value.length,
default: (value: any, defaultValue: any) =>
value !== undefined && value !== null ? value : defaultValue
}
Adapter Registry
Central registry for discovering, loading, and managing adapters.
Registry Implementation
/**
* Adapter Registry
*
* Manages adapter discovery, loading, and lifecycle.
*/
export class AdapterRegistry {
private adapters: Map<string, AdapterInfo> = new Map()
private instances: Map<string, PlatformAdapter> = new Map()
/**
* Register an adapter
*/
register(info: AdapterInfo): void {
this.adapters.set(info.name, info)
this.emitter.emit('register', info)
}
/**
* Register multiple adapters
*/
registerMany(adapters: AdapterInfo[]): void {
adapters.forEach(adapter => this.register(adapter))
}
/**
* Get adapter instance
*/
async get(name: string, auth?: any): Promise<PlatformAdapter> {
// Check if already instantiated
if (this.instances.has(name)) {
return this.instances.get(name)!
}
// Load adapter
const info = this.adapters.get(name)
if (!info) {
throw new AdapterNotFoundError(name)
}
const adapter = await this.loadAdapter(info, auth)
this.instances.set(name, adapter)
return adapter
}
/**
* List all registered adapters
*/
list(options?: { filter?: { category?: string; authType?: string } }): AdapterInfo[] {
let adapters = Array.from(this.adapters.values())
if (options?.filter) {
adapters = adapters.filter(adapter => {
if (options.filter?.category && adapter.category !== options.filter.category) {
return false
}
if (options.filter?.authType && adapter.authType !== options.filter.authType) {
return false
}
return true
})
}
return adapters
}
/**
* Search adapters by query
*/
search(query: string): AdapterInfo[] {
const lowerQuery = query.toLowerCase()
return Array.from(this.adapters.values()).filter(adapter =>
adapter.name.toLowerCase().includes(lowerQuery) ||
adapter.displayName.toLowerCase().includes(lowerQuery) ||
adapter.description?.toLowerCase().includes(lowerQuery)
)
}
/**
* Load adapters from directory
*/
async loadFromDirectory(directory: string): Promise<void> {
const files = await fs.readdir(directory, { recursive: true })
for (const file of files) {
if (file.match(/config\.(ya?ml|json)$/)) {
const config = await this.loadAdapterConfig(path.join(directory, file))
this.register({
name: config.name,
displayName: config.displayName,
description: config.description,
version: config.version || '1.0.0',
type: 'config',
category: config.category || 'social',
authType: config.auth?.type || 'none'
})
}
}
}
/**
* Load adapters from npm packages
*/
async loadFromPackages(patterns: string[]): Promise<void> {
for (const pattern of patterns) {
const packageNames = await this.findPackages(pattern)
for (const packageName of packageNames) {
try {
const adapterModule = await import(packageName)
const adapter = adapterModule.default || adapterModule
this.register({
name: adapter.name,
displayName: adapter.displayName || adapter.name,
description: adapter.description,
version: adapter.version || '1.0.0',
type: 'code',
category: adapter.category || 'social',
authType: adapter.authType || 'custom'
})
} catch (error) {
console.warn(`Failed to load adapter ${packageName}:`, error)
}
}
}
}
/**
* Get adapter health
*/
async healthCheck(name: string): Promise<AdapterHealth> {
const adapter = await this.get(name)
return adapter.healthCheck()
}
/**
* Get all adapter metrics
*/
getAllMetrics(): Record<string, AdapterMetrics> {
const metrics: Record<string, AdapterMetrics> = {}
for (const [name, adapter] of this.instances) {
metrics[name] = adapter.getMetrics()
}
return metrics
}
/**
* Unload adapter
*/
async unload(name: string): Promise<void> {
const adapter = this.instances.get(name)
if (adapter) {
await adapter.dispose()
this.instances.delete(name)
}
}
/**
* Unload all adapters
*/
async unloadAll(): Promise<void> {
await Promise.all(
Array.from(this.instances.keys()).map(name => this.unload(name))
)
}
}
Registry Usage
// Create registry
const registry = new AdapterRegistry()
// Register adapters manually
registry.register({
name: 'twitter',
displayName: 'Twitter/X',
description: 'Twitter adapter for Idiomark extraction',
version: '1.0.0',
type: 'code',
category: 'social',
authType: 'bearer_token'
})
// Load from directory
await registry.loadFromDirectory('./adapters')
// Load from npm packages
await registry.loadFromPackages(['@idiomark/adapter-*'])
// List all adapters
const allAdapters = registry.list()
// Search adapters
const socialAdapters = registry.list({ filter: { category: 'social' } })
// Get adapter instance
const twitter = await registry.get('twitter', { bearerToken: 'xxx' })
// Fetch content
const content = await twitter.extract({ limit: 100 })
// Health check
const health = await registry.healthCheck('twitter')
Adapter Generator CLI
CLI tool to scaffold new adapters quickly.
CLI Implementation
#!/usr/bin/env node
/**
* Idiomark Adapter Generator CLI
*
* Usage:
* idiomark adapter create my-service --template rest
* idiomark adapter create my-service --template graphql --auth oauth2
*/
import { Command } from 'commander'
import inquirer from 'inquirer'
import ora from 'ora'
import fs from 'fs-extra'
import path from 'path'
const program = new Command()
program
.name('idiomark-adapter')
.description('Generate new Idiomark adapters')
.version('1.0.0')
program
.command('create')
.description('Create a new adapter')
.argument('<name>', 'Adapter name (e.g., twitter, github)')
.option('-t, --template <type>', 'Template type (rest, graphql, scraping, rss, email, forum)', 'rest')
.option('-a, --auth <type>', 'Auth type (none, bearer_token, oauth2, api_key, basic)', 'none')
.option('-b, --base-url <url>', 'Base URL for API')
.option('-d, --directory <path>', 'Output directory', './packages/adapters')
.option('--config-only', 'Generate config-only adapter')
.action(createAdapter)
program.parse()
async function createAdapter(name: string, options: any) {
const spinner = ora('Creating adapter...').start()
try {
// Normalize name
const adapterName = name.toLowerCase().replace(/[^a-z0-9]/g, '-')
const className = toPascalCase(adapterName) + 'Adapter'
// If no options provided, prompt for them
if (!process.stdin.isTTY) {
const answers = await inquirer.prompt([
{
type: 'list',
name: 'template',
message: 'Select template type:',
choices: ['rest', 'graphql', 'scraping', 'rss', 'email', 'forum', 'config']
},
{
type: 'list',
name: 'auth',
message: 'Select auth type:',
choices: ['none', 'bearer_token', 'oauth2', 'api_key', 'basic']
},
{
type: 'input',
name: 'baseURL',
message: 'Enter base URL:',
when: (answers) => ['rest', 'graphql', 'scraping'].includes(answers.template),
validate: (input) => isValidURL(input) || 'Please enter a valid URL'
}
])
Object.assign(options, answers)
}
const adapterDir = path.join(options.directory, adapterName)
await fs.ensureDir(adapterDir)
// Generate files
if (options.template === 'config' || options.configOnly) {
await generateConfigAdapter(adapterName, adapterDir, options, spinner)
} else {
await generateCodeAdapter(className, adapterName, adapterDir, options, spinner)
}
spinner.succeed(`Adapter created at ${adapterDir}`)
console.log('\nNext steps:')
console.log(` 1. cd ${adapterDir}`)
console.log(` 2. Implement the fetchContent() and normalize() methods`)
console.log(` 3. Run tests: npm test`)
console.log(` 4. Build: npm run build`)
} catch (error) {
spinner.fail('Failed to create adapter')
console.error(error)
process.exit(1)
}
}
async function generateCodeAdapter(
className: string,
adapterName: string,
dir: string,
options: any,
spinner: Ora
) {
// Generate package.json
spinner.text = 'Generating package.json...'
await fs.writeJson(
path.join(dir, 'package.json'),
{
name: `@idiomark/adapter-${adapterName}`,
version: '1.0.0',
description: `${adapterName} adapter for Idiomark extraction`,
main: './dist/index.js',
types: './dist/index.d.ts',
scripts: {
build: 'tsup',
dev: 'tsup --watch',
test: 'vitest',
lint: 'eslint src/'
},
dependencies: {
'@idiomark/core': 'workspace:*'
},
devDependencies: {
typescript: '^5.7.3',
tsup: '^8.4.0',
vitest: '^3.0.7'
}
},
{ spaces: 2 }
)
// Generate tsconfig.json
spinner.text = 'Generating tsconfig.json...'
await fs.writeJson(
path.join(dir, 'tsconfig.json'),
{
extends: '../../tsconfig.json',
compilerOptions: {
outDir: './dist',
rootDir: './src'
},
include: ['./src']
},
{ spaces: 2 }
)
// Generate source files
const srcDir = path.join(dir, 'src')
await fs.ensureDir(srcDir)
// Generate types.ts
spinner.text = 'Generating types...'
await fs.writeFile(
path.join(srcDir, 'types.ts'),
generateTypesFile(adapterName, options.auth)
)
// Generate index.ts
spinner.text = 'Generating index.ts...'
await fs.writeFile(
path.join(srcDir, 'index.ts'),
generateIndexFile(className, adapterName, options)
)
// Generate test file
spinner.text = 'Generating tests...'
const testDir = path.join(srcDir, '__tests__')
await fs.ensureDir(testDir)
await fs.writeFile(
path.join(testDir, 'adapter.test.ts'),
generateTestFile(className, adapterName, options)
)
// Generate README
spinner.text = 'Generating README...'
await fs.writeFile(
path.join(dir, 'README.md'),
generateReadme(adapterName, options)
)
}
function generateTypesFile(name: string, authType: string): string {
return `/**
* ${toPascalCase(name)} Adapter Types
*/
export interface ${toPascalCase(name)}Auth {
${getAuthInterface(authType)}
}
export interface ${toPascalCase(name)}Post {
id: string
text: string
created_at: string
author: {
id: string
username: string
name: string
}
[key: string]: any
}
`
}
function generateIndexFile(className: string, name: string, options: any): string {
const templateImports = {
rest: 'RESTAdapterTemplate',
graphql: 'GraphQLAdapterTemplate',
scraping: 'ScrapingAdapterTemplate',
rss: 'RSSTemplate',
email: 'EmailTemplate',
forum: 'ForumTemplate'
}
const template = templateImports[options.template] || 'RESTAdapterTemplate'
return `/**
* ${toPascalCase(name)} Adapter for Idiomark
*/
import type {
PlatformAdapter,
NormalizedContent,
FetchOptions,
RawContent
} from '@idiomark/core'
import type { ${toPascalCase(name)}Auth, ${toPascalCase(name)}Post } from './types'
${options.template === 'rest' || options.template === undefined ? `import { RESTAdapterTemplate } from '@idiomark/core/adapters'` : ''}
export type { ${toPascalCase(name)}Auth, ${toPascalCase(name)}Post }
export { ${className} }
/**
* ${toPascalCase(name)} Adapter
*/
export class ${className} extends ${options.template === 'rest' || options.template === undefined ? 'RESTAdapterTemplate' : 'BaseAdapter'} implements PlatformAdapter {
readonly name = '${name}'
${options.template === 'rest' || options.template === undefined ? ` protected baseURL = '${options.baseURL || 'https://api.' + name + '.com'}'` : ''}
private auth: ${toPascalCase(name)}Auth
constructor(auth: ${toPascalCase(name)}Auth) {
super()
this.auth = auth
}
/**
* Fetch content from ${name}
*/
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
// TODO: Implement fetch logic
const { limit = 100 } = options
${getFetchImplementation(options.template)}
}
/**
* Normalize raw content to Idiomark format
*/
normalize(raw: RawContent): NormalizedContent {
const post = raw as ${toPascalCase(name)}Post
return {
id: post.id,
platform: this.name,
type: 'post',
text: post.text,
timestamp: post.created_at,
author: {
id: post.author.id,
username: post.author.username,
name: post.author.name
},
raw: post
}
}
}
`
}
function getAuthInterface(authType: string): string {
switch (authType) {
case 'bearer_token':
return ' bearerToken: string\n userId?: string\n username?: string'
case 'oauth2':
return ' accessToken: string\n refreshToken?: string\n clientId: string\n clientSecret: string'
case 'api_key':
return ' apiKey: string\n apiSecret?: string'
case 'basic':
return ' username: string\n password: string'
default:
return ' // No auth required'
}
}
function getFetchImplementation(template: string): string {
switch (template) {
case 'rest':
return ` const endpoint = \`/posts?limit=\${limit}\`
const response = await this.makeRequest({ endpoint })
return response.data || []`
case 'graphql':
return ` const query = \`query { posts(limit: \${limit}) { id text created_at author } }\`
const response = await this.makeRequest(query)
return response.posts || []`
case 'scraping':
return ` const html = await this.fetchHTML(\`/posts\`)
return this.parseHTML(html)`
default:
return ` // Fetch posts from ${name}\n return []`
}
}
function generateTestFile(className: string, name: string, options: any): string {
return `import { describe, it, expect, vi } from 'vitest'
import { ${className} } from '../index'
describe('${className}', () => {
it('should have correct name', () => {
const adapter = new ${className}({})
expect(adapter.name).toBe('${name}')
})
it('should normalize content correctly', () => {
const adapter = new ${className}({})
const raw = {
id: '123',
text: 'Test post',
created_at: '2026-02-10T00:00:00Z',
author: {
id: '456',
username: 'testuser',
name: 'Test User'
}
}
const normalized = adapter.normalize(raw as any)
expect(normalized.id).toBe('123')
expect(normalized.text).toBe('Test post')
expect(normalized.platform).toBe('${name}')
})
// TODO: Add more tests
// - Test authentication
// - Test fetchContent
// - Test error handling
// - Test rate limiting
})
`
}
function generateReadme(name: string, options: any): string {
return `# ${toPascalCase(name)} Adapter
Idiomark adapter for ${name}.
## Installation
\`\`\`bash
npm install @idiomark/adapter-${name}
\`\`\`
## Usage
\`\`\`\`typescript
import { ${toPascalCase(name)}Adapter } from '@idiomark/adapter-${name}'
const adapter = new ${toPascalCase(name)}Adapter({
${getAuthExample(options.auth)}
})
const content = await adapter.extract({
limit: 100,
startDate: new Date('2026-01-01'),
endDate: new Date()
})
\`\`\`\`
## Configuration
${getAuthConfigDocs(options.auth)}
## Rate Limits
TODO: Add rate limit information for ${name}
## License
MIT
`
}
function getAuthExample(authType: string): string {
switch (authType) {
case 'bearer_token':
return ' bearerToken: process.env.${NAME.toUpperCase()}_TOKEN'
case 'oauth2':
return ' accessToken: process.env.${NAME.toUpperCase()}_ACCESS_TOKEN,\n clientId: process.env.${NAME.toUpperCase()}_CLIENT_ID,\n clientSecret: process.env.${NAME.toUpperCase()}_CLIENT_SECRET'
case 'api_key':
return ' apiKey: process.env.${NAME.toUpperCase()}_API_KEY'
case 'basic':
return ' username: process.env.${NAME.toUpperCase()}_USERNAME,\n password: process.env.${NAME.toUpperCase()}_PASSWORD'
default:
return ' // No auth required'
}
}
function getAuthConfigDocs(authType: string): string {
switch (authType) {
case 'bearer_token':
return `Requires a bearer token. Set the \`${name.toUpperCase()}_TOKEN\` environment variable.`
case 'oauth2':
return `Requires OAuth2 credentials. Set the following environment variables:\n- \`${name.toUpperCase()}_ACCESS_TOKEN\`\n- \`${name.toUpperCase()}_CLIENT_ID\`\n- \`${name.toUpperCase()}_CLIENT_SECRET\``
case 'api_key':
return `Requires an API key. Set the \`${name.toUpperCase()}_API_KEY\` environment variable.`
case 'basic':
return `Requires basic auth credentials. Set the following environment variables:\n- \`${name.toUpperCase()}_USERNAME\`\n- \`${name.toUpperCase()}_PASSWORD\``
default:
return 'No authentication required.'
}
}
// Helper functions
function toPascalCase(str: string): string {
return str
.split(/[-_]/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('')
}
function isValidURL(str: string): boolean {
try {
new URL(str)
return true
} catch {
return false
}
}
CLI Usage Examples
# Interactive mode (prompts for options)
idiomark adapter create my-service
# Quick REST API adapter
idiomark adapter create stripe --template rest --auth api_key --base-url https://api.stripe.com/v1
# GraphQL API
idiomark adapter create shopify --template graphql --auth oauth2
# Web scraping
idiomark adapter create news-site --template scraping --base-url https://example.com
# Config-only adapter (simplest)
idiomark adapter create reddit --template config --config-only
Testing Framework
Comprehensive testing infrastructure for adapters.
Test Utilities
/**
* Adapter testing utilities
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
/**
* Mock HTTP server for testing
*/
export class MockServer {
private server: any
constructor(private config: MockServerConfig) {}
async start(): Promise<string> {
this.server = await createTestServer((req, res) => {
const route = this.config.routes.find(r =>
r.method === req.method && r.path === req.url
)
if (route) {
res.statusCode = route.status || 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(route.response))
} else {
res.statusCode = 404
res.end(JSON.stringify({ error: 'Not found' }))
}
})
return `http://localhost:${this.server.port}`
}
async stop(): Promise<void> {
await this.server.close()
}
}
/**
* Adapter test suite builder
*/
export function createAdapterTestSuite(options: {
adapterName: string
adapterFactory: (auth: any) => PlatformAdapter
mockConfig: MockServerConfig
validAuth: any
sampleResponse: any
sampleNormalized: NormalizedContent
}) {
describe(options.adapterName, () => {
let adapter: PlatformAdapter
let serverUrl: string
beforeAll(async () => {
const server = new MockServer(options.mockConfig)
serverUrl = await server.start()
// Override base URL
adapter = options.adapterFactory({
...options.validAuth,
baseURL: serverUrl
})
})
afterAll(async () => {
if (adapter.dispose) {
await adapter.dispose()
}
})
describe('authentication', () => {
it('should authenticate successfully', async () => {
const isAuthenticated = await adapter.authenticate()
expect(isAuthenticated).toBe(true)
})
it('should fail with invalid credentials', async () => {
const badAdapter = options.adapterFactory({
...options.validAuth,
token: 'invalid'
})
const isAuthenticated = await badAdapter.authenticate()
expect(isAuthenticated).toBe(false)
})
})
describe('fetching', () => {
it('should fetch content', async () => {
const content = await adapter.fetchContent({ limit: 10 })
expect(content).toBeDefined()
expect(content.length).toBeGreaterThan(0)
})
it('should respect limit option', async () => {
const content = await adapter.fetchContent({ limit: 5 })
expect(content.length).toBeLessThanOrEqual(5)
})
it('should handle rate limits gracefully', async () => {
// Make multiple requests
const requests = Array.from({ length: 10 }, () =>
adapter.fetchContent({ limit: 1 })
)
const results = await Promise.all(requests)
expect(results).toHaveLength(10)
})
it('should retry on failure', async () => {
// Test retry logic
const content = await adapter.fetchContent({ limit: 1 })
expect(content).toBeDefined()
})
})
describe('normalization', () => {
it('should normalize content correctly', () => {
const normalized = adapter.normalize(options.sampleResponse)
expect(normalized).toMatchObject(options.sampleNormalized)
})
it('should include required fields', () => {
const normalized = adapter.normalize(options.sampleResponse)
expect(normalized.id).toBeDefined()
expect(normalized.platform).toBeDefined()
expect(normalized.type).toBeDefined()
expect(normalized.text).toBeDefined()
expect(normalized.timestamp).toBeDefined()
expect(normalized.author).toBeDefined()
})
})
describe('rate limiting', () => {
it('should respect rate limits', async () => {
const start = Date.now()
await adapter.fetchContent({ limit: 100 })
const duration = Date.now() - start
// Should take at least as long as rate limit requires
expect(duration).toBeGreaterThan(0)
})
})
describe('caching', () => {
it('should cache responses', async () => {
const options = { limit: 10 }
// First call
await adapter.fetchContent(options)
// Second call should be faster (cached)
const start = Date.now()
await adapter.fetchContent(options)
const duration = Date.now() - start
expect(duration).toBeLessThan(100)
})
})
describe('error handling', () => {
it('should handle network errors gracefully', async () => {
// Test with invalid URL
const badAdapter = options.adapterFactory({
...options.validAuth,
baseURL: 'http://invalid-url-that-does-not-exist.local'
})
const content = await badAdapter.fetchContent({ limit: 10 })
expect(content).toEqual([])
})
it('should handle invalid responses', async () => {
// Test with malformed response
const content = await adapter.fetchContent({ limit: 10 })
expect(content).toBeDefined()
})
})
})
}
/**
* Performance test utilities
*/
export async function benchmarkAdapter(
adapter: PlatformAdapter,
options: {
requests: number
concurrency: number
}
): Promise<BenchmarkResult> {
const { requests, concurrency } = options
const start = Date.now()
// Create batches
const batchSize = Math.ceil(requests / concurrency)
const batches = Array.from({ length: concurrency }, () =>
Array.from({ length: batchSize }, () => adapter.fetchContent({ limit: 10 }))
)
// Execute batches concurrently
const results = await Promise.all(
batches.map(batch => Promise.all(batch))
)
const duration = Date.now() - start
const totalRequests = results.flat().length
return {
totalRequests,
duration,
avgLatency: duration / totalRequests,
requestsPerSecond: (totalRequests / duration) * 1000
}
}
Test Example
// packages/adapters/twitter/src/__tests__/adapter.test.ts
import { describe, it, expect } from 'vitest'
import { TwitterAdapter } from '../index'
import { createAdapterTestSuite, MockServer } from '@idiomark/core/testing'
describe('TwitterAdapter', () => {
createAdapterTestSuite({
adapterName: 'twitter',
adapterFactory: (auth) => new TwitterAdapter(auth),
mockConfig: {
routes: [
{
path: '/2/users/me',
method: 'GET',
response: {
data: {
id: '123',
username: 'testuser',
name: 'Test User'
}
}
},
{
path: '/2/users/123/tweets',
method: 'GET',
response: {
data: [
{
id: '456',
text: 'Hello world!',
created_at: '2026-02-10T00:00:00Z',
author_id: '123',
public_metrics: {
like_count: 10,
retweet_count: 5,
reply_count: 2
}
}
]
}
}
]
},
validAuth: {
bearerToken: 'test-token'
},
sampleResponse: {
id: '456',
text: 'Hello world!',
created_at: '2026-02-10T00:00:00Z',
author_id: '123',
public_metrics: {
like_count: 10,
retweet_count: 5,
reply_count: 2
}
},
sampleNormalized: {
id: '456',
platform: 'twitter',
type: 'post',
text: 'Hello world!',
timestamp: '2026-02-10T00:00:00Z',
author: {
id: '123',
username: 'testuser',
name: 'Test User'
}
}
})
// Twitter-specific tests
describe('Twitter-specific features', () => {
it('should extract hashtags', () => {
const adapter = new TwitterAdapter({ bearerToken: 'test' })
const tweet = {
id: '123',
text: 'Hello #world!',
entities: {
hashtags: [{ tag: 'world' }]
}
}
const normalized = adapter.normalize(tweet as any)
expect(normalized.metadata?.hashtags).toEqual(['world'])
})
it('should detect replies', () => {
const adapter = new TwitterAdapter({ bearerToken: 'test' })
const tweet = {
id: '123',
text: '@user Hello!',
in_reply_to_user_id: '456'
}
const normalized = adapter.normalize(tweet as any)
expect(normalized.type).toBe('reply')
})
})
})
Performance Optimization
Strategies for handling 500+ adapters efficiently.
Lazy Loading
/**
* Lazy load adapters
*/
export class LazyAdapterRegistry extends AdapterRegistry {
private lazyAdapters: Map<string, () => Promise<PlatformAdapter>> = new Map()
registerLazy(name: string, loader: () => Promise<PlatformAdapter>): void {
this.lazyAdapters.set(name, loader)
}
override async get(name: string, auth?: any): Promise<PlatformAdapter> {
if (this.instances.has(name)) {
return this.instances.get(name)!
}
const loader = this.lazyAdapters.get(name)
if (loader) {
const adapter = await loader()
this.instances.set(name, adapter)
return adapter
}
return super.get(name, auth)
}
}
Connection Pooling
/**
* Connection pool for HTTP requests
*/
export class ConnectionPool {
private pools: Map<string, Pool> = new Map()
async getConnection(url: string): Promise<Connection> {
const origin = new URL(url).origin
if (!this.pools.has(origin)) {
this.pools.set(origin, new Pool({
maxConnections: 100,
maxFree: 10,
keepAlive: true
}))
}
return this.pools.get(origin)!.acquire()
}
release(connection: Connection): void {
connection.release()
}
}
Batch Processing
/**
* Batch processor for multiple adapters
*/
export class BatchProcessor {
async process(
adapters: PlatformAdapter[],
options: FetchOptions,
concurrency: number = 10
): Promise<Map<string, NormalizedContent[]>> {
const results = new Map<string, NormalizedContent[]>()
const queue = [...adapters]
const workers: Promise<void>[] = []
for (let i = 0; i < concurrency; i++) {
workers.push(this.worker(queue, options, results))
}
await Promise.all(workers)
return results
}
private async worker(
queue: PlatformAdapter[],
options: FetchOptions,
results: Map<string, NormalizedContent[]>
): Promise<void> {
while (queue.length > 0) {
const adapter = queue.shift()
if (!adapter) break
try {
const content = await adapter.extract(options)
results.set(adapter.name, content)
} catch (error) {
console.error(`Failed to process ${adapter.name}:`, error)
results.set(adapter.name, [])
}
}
}
}
Migration Guide
Migrating GitHub Adapter
// Before: GitHub adapter with duplicated code
export class GitHubAdapter implements PlatformAdapter {
readonly name = 'github'
private auth: GitHubAuth
private rateLimiter = new RateLimiter({ /* ... */ })
private cache = new CacheManager({ /* ... */ })
private retry = new RetryHandler({ /* ... */ })
// ... lots of duplicated code
}
// After: Using REST template
export class GitHubAdapter extends RESTAdapterTemplate {
protected baseURL = 'https://api.github.com'
protected endpoints = {
user: '/user',
repos: '/users/{username}/repos',
commits: '/repos/{owner}/{repo}/commits'
}
// Only implement what's unique to GitHub
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
// GitHub-specific fetch logic
}
normalize(raw: RawContent): NormalizedContent {
// GitHub-specific normalization
}
}
Migrating Twitter Adapter
// Before: Custom rate limiter, retry, cache implementation
export class TwitterAdapter implements PlatformAdapter {
// ... 800+ lines of boilerplate
}
// After: Focus on Twitter-specific logic
export class TwitterAdapter extends RESTAdapterTemplate {
protected baseURL = 'https://api.twitter.com/2'
// Only Twitter-specific rate limit handling
protected async handleRateLimit(headers: Headers): Promise<void> {
const tierLimits = {
free: { requests: 15, window: 15 * 60 * 1000 },
basic: { requests: 100, window: 24 * 60 * 60 * 1000 }
}
// Update rate limiter from Twitter headers
const remaining = headers.get('x-rate-limit-remaining')
if (remaining) {
this.rateLimiter.updateFromHeaders(headers)
}
}
normalize(raw: RawContent): NormalizedContent {
// Twitter-specific normalization (hashtags, mentions, etc.)
}
}
Examples
Example 1: Simple REST API Adapter
import { RESTAdapterTemplate } from '@idiomark/core/adapters'
export class ProductHuntAdapter extends RESTAdapterTemplate {
protected baseURL = 'https://api.producthunt.com/v2'
protected endpoints = {
posts: '/posts'
}
async authenticate(): Promise<boolean> {
const response = await fetch(`${this.baseURL}/api/v2/me`, {
headers: {
'Authorization': `Bearer ${this.auth.token}`
}
})
return response.ok
}
async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const response = await this.makeRequest({
endpoint: this.endpoints.posts,
params: {
per_page: options.limit || 100
}
})
return response.posts.map((post: any) => ({
id: post.id,
type: 'post',
text: `${post.name}\n\n${post.tagline}\n\n${post.description}`,
created_at: post.created_at,
author: {
id: post.user.id,
username: post.user.username,
name: post.user.name
},
metrics: {
likes: post.votes_count
},
raw: post
}))
}
normalize(raw: RawContent): NormalizedContent {
return raw as unknown as NormalizedContent
}
}
Example 2: Config-Driven Adapter
# adapters/hackernews/config.yml
name: hackernews
displayName: Hacker News
description: Hacker News adapter for Idiomark extraction
api:
baseURL: https://hacker-news.firebaseio.com/v0
format: json
auth:
type: none
rateLimit:
requests: 1000
window: hour
extraction:
userPosts:
endpoint: /user/{id}/submitted
isArray: true
fields:
id:
source: (item) => item
required: true
text:
source: title
timestamp:
source: time
transform: timestamp_to_iso
type:
value: post
author:
id:
source: by
username:
source: by
name:
source: by
metadata:
url:
source: url
score:
source: score
Example 3: Using Multiple Adapters
import { AdapterRegistry } from '@idiomark/core/adapters'
import { GitHubAdapter } from '@idiomark/adapter-github'
import { TwitterAdapter } from '@idiomark/adapter-twitter'
import { RedditAdapter } from '@idiomark/adapter-reddit'
// Create registry
const registry = new AdapterRegistry()
// Register adapters
registry.registerMany([
{ name: 'github', factory: (auth) => new GitHubAdapter(auth) },
{ name: 'twitter', factory: (auth) => new TwitterAdapter(auth) },
{ name: 'reddit', factory: (auth) => new RedditAdapter(auth) }
])
// Get all adapters
const github = await registry.get('github', { token: process.env.GITHUB_TOKEN })
const twitter = await registry.get('twitter', { bearerToken: process.env.TWITTER_TOKEN })
const reddit = await registry.get('reddit') // No auth needed
// Fetch from all
const options = { limit: 100 }
const [githubData, twitterData, redditData] = await Promise.all([
github.extract(options),
twitter.extract(options),
reddit.extract(options)
])
// Combine for extraction
const allContent = [
...githubData,
...twitterData,
...redditData
]
// Extract personality
const extractor = new IdiomarkExtractor({
sources: ['github', 'twitter', 'reddit'],
sampleSize: allContent.length
})
const result = await extractor.extractFromContent(allContent)
Summary
The Idiomark Adapter Framework provides:
- Base Adapter Class - All common functionality built-in
- Adapter Templates - Pre-built for REST, GraphQL, scraping, RSS, email, forums
- Config-Driven - YAML/JSON for simple APIs
- Adapter Registry - Discovery and loading of 500+ adapters
- Generator CLI - Scaffold new adapters in seconds
- Testing Framework - Comprehensive test utilities
- Performance Optimization - Lazy loading, pooling, batching
This architecture makes adding new adapters trivial while maintaining consistency across all 500+ services.