Custom Adapters
This guide explains how to create custom adapters for capo.js and validate them using the built-in test utilities.
Why custom adapters?
Section titled âWhy custom adapters?âCustom adapters allow you to use capo.js with different HTML parsers or AST formats, such as:
- JSX/React elements
- Vue template AST
- Svelte component AST
- Custom XML parsers
- Server-side rendering frameworks
Creating a custom adapter
Section titled âCreating a custom adapterâStep 1: Extend the AdapterInterface
Section titled âStep 1: Extend the AdapterInterfaceâimport { AdapterInterface } from '@rviscomi/capo.js/adapters';
export class MyCustomAdapter extends AdapterInterface { // Implement all 11 required methods
isElement(node) { return node && node.type === 'YourElementType'; }
getTagName(node) { return node.tagName?.toLowerCase() || ''; }
getAttribute(node, name) { // ... }
// Implement other required methods: // hasAttribute, getAttributeNames, getTextContent, // getChildren, getParent, getSiblings, stringify}Step 2: Use your adapter
Section titled âStep 2: Use your adapterâimport { MyCustomAdapter } from './my-custom-adapter.js';import { analyzeHead } from '@rviscomi/capo.js';
const adapter = new MyCustomAdapter();const results = analyzeHead(headNode, adapter);Node.js usage
Section titled âNode.js usageâWhile capo.js is designed for the browser, you can use it in Node.js by pairing it with a DOM simulation library like jsdom.
Since jsdom provides a standard DOM API, you can reuse the built-in BrowserAdapter instead of writing a custom one:
import { JSDOM } from 'jsdom';import { analyzeHead, BrowserAdapter } from '@rviscomi/capo.js';
const html = ` <!DOCTYPE html> <html> <head> <title>My Page</title> <meta charset="utf-8"> </head> <body></body> </html>`;
// 1. Create a JSDOM instanceconst dom = new JSDOM(html);const head = dom.window.document.querySelector('head');
// 2. Use the built-in BrowserAdapterconst adapter = new BrowserAdapter();
// 3. Analyzeconst results = analyzeHead(head, adapter);
console.log(results.weights);