Developer Resources

Comprehensive developer documentation, API references, and integration guides for Safari Reader Mode optimization and Apple Intelligence compatibility testing.

Developer Tools Overview

SurfaceScore provides a comprehensive suite of developer tools for integrating Safari Reader Mode optimization and Apple Intelligence compatibility testing into your development workflow.

🔌 REST API

Programmatic access to SurfaceScore analysis engine

  • Real-time compatibility scoring
  • Detailed optimization recommendations
  • Batch analysis capabilities

📚 JavaScript SDK

Client-side library for browser integration

  • Real-time Reader Mode testing
  • Content extraction simulation
  • Performance monitoring

🔧 CLI Tools

Command-line interface for CI/CD integration

  • Automated testing pipelines
  • Build process integration
  • Continuous monitoring

🎨 Browser Extension

Development tools for real-time testing

  • Live Reader Mode preview
  • Content structure analysis
  • Debugging assistance

API Documentation

Getting Started

The SurfaceScore API provides programmatic access to our Safari Reader Mode and Apple Intelligence compatibility analysis engine.

Base URL

https://api.surfacescore.com/v1

Authentication

API requests require authentication using an API key in the request header:

Authorization: Bearer YOUR_API_KEY

Rate Limits

  • Free Tier: 100 requests per hour
  • Pro Tier: 1,000 requests per hour
  • Enterprise: Custom limits

Endpoints

Analyze Website

POST /analyze

Analyzes a website for Safari Reader Mode and Apple Intelligence compatibility.

Request Body
{
  "url": "https://example.com/article",
  "options": {
    "includeRecommendations": true,
    "detailedAnalysis": true,
    "checkAccessibility": true
  }
}
Response
{
  "success": true,
  "data": {
    "url": "https://example.com/article",
    "timestamp": "2024-12-18T10:30:00Z",
    "scores": {
      "overall": 85,
      "readerMode": 92,
      "appleIntelligence": 78,
      "structuredData": 88,
      "accessibility": 95
    },
    "analysis": {
      "readerMode": {
        "contentExtracted": true,
        "headingStructure": "excellent",
        "semanticMarkup": "good",
        "issues": []
      },
      "appleIntelligence": {
        "summarizable": true,
        "topicClarity": "high",
        "contentDepth": "comprehensive",
        "metadataComplete": true
      },
      "structuredData": {
        "schemas": ["Article", "BreadcrumbList"],
        "validation": "passed",
        "coverage": 88
      }
    },
    "recommendations": [
      {
        "category": "readerMode",
        "priority": "high",
        "title": "Improve heading hierarchy",
        "description": "Use proper H1-H6 progression",
        "implementation": "Replace div.title with h2 elements"
      }
    ]
  }
}

Batch Analysis

POST /analyze/batch

Analyzes multiple URLs in a single request.

Request Body
{
  "urls": [
    "https://example.com/article-1",
    "https://example.com/article-2",
    "https://example.com/article-3"
  ],
  "options": {
    "includeRecommendations": false,
    "detailedAnalysis": false
  }
}
Response
{
  "success": true,
  "data": {
    "results": [
      {
        "url": "https://example.com/article-1",
        "scores": { "overall": 85, "readerMode": 92 },
        "status": "completed"
      },
      {
        "url": "https://example.com/article-2", 
        "scores": { "overall": 76, "readerMode": 84 },
        "status": "completed"
      }
    ],
    "summary": {
      "total": 3,
      "completed": 2,
      "failed": 1,
      "averageScore": 80.5
    }
  }
}

Get Analysis History

GET /history

Retrieves analysis history for your account.

Query Parameters
  • limit - Number of results (default: 50, max: 200)
  • offset - Pagination offset
  • url - Filter by specific URL
  • from - Start date (ISO 8601)
  • to - End date (ISO 8601)
Example Request
GET /history?limit=10&url=example.com

JavaScript SDK

Installation

npm install @surfacescore/sdk
yarn add @surfacescore/sdk
<script src="https://cdn.surfacescore.com/sdk/v1/surfacescore.min.js"></script>

Basic Usage

import SurfaceScore from '@surfacescore/sdk';

// Initialize with your API key
const surfaceScore = new SurfaceScore({
  apiKey: 'your-api-key-here',
  environment: 'production' // or 'sandbox'
});

// Analyze current page
const analysis = await surfaceScore.analyzePage();
console.log('Overall score:', analysis.scores.overall);

// Analyze specific URL
const result = await surfaceScore.analyze('https://example.com/article');
console.log('Reader Mode score:', result.scores.readerMode);

Real-time Reader Mode Testing

// Test Reader Mode compatibility in real-time
const readerModeTest = surfaceScore.createReaderModeTest({
  container: document.querySelector('#preview'),
  showIssues: true,
  highlightProblems: true
});

// Start monitoring
readerModeTest.start();

// Get live feedback
readerModeTest.on('issue', (issue) => {
  console.log('Reader Mode issue detected:', issue);
});

// Get compatibility score
const score = readerModeTest.getScore();
console.log('Live compatibility score:', score);

Content Structure Analysis

// Analyze content structure
const structureAnalysis = await surfaceScore.analyzeStructure({
  element: document.querySelector('article'),
  checkHeadings: true,
  checkSemantics: true,
  checkAccessibility: true
});

console.log('Structure analysis:', structureAnalysis);

// Get specific recommendations
const recommendations = structureAnalysis.getRecommendations();
recommendations.forEach(rec => {
  console.log(`${rec.priority}: ${rec.title}`);
});

Performance Monitoring

// Monitor Reader Mode performance
const monitor = surfaceScore.createMonitor({
  interval: 30000, // Check every 30 seconds
  threshold: 80,   // Alert if score drops below 80
  autoFix: false   // Don't auto-apply fixes
});

monitor.on('scoreChange', (newScore, oldScore) => {
  console.log(`Score changed: ${oldScore} → ${newScore}`);
});

monitor.on('threshold', (score) => {
  console.warn(`Score dropped below threshold: ${score}`);
});

monitor.start();

CLI Tools

Installation

# Install globally
npm install -g @surfacescore/cli

# Or use npx
npx @surfacescore/cli --version

Configuration

# Set up your API key
surfacescore config set apiKey YOUR_API_KEY

# Set default options
surfacescore config set defaultOptions.includeRecommendations true

Basic Commands

Analyze Single URL

# Basic analysis
surfacescore analyze https://example.com/article

# Detailed analysis with recommendations
surfacescore analyze https://example.com/article --detailed --recommendations

# Output to file
surfacescore analyze https://example.com/article --output report.json

Batch Analysis

# Analyze multiple URLs from file
surfacescore batch urls.txt

# Analyze sitemap
surfacescore sitemap https://example.com/sitemap.xml

# Analyze with custom options
surfacescore batch urls.txt --format csv --output results.csv

CI/CD Integration

# Check if score meets threshold
surfacescore check https://example.com/article --threshold 80

# Exit with error code if threshold not met
if ! surfacescore check $URL --threshold 85 --quiet; then
  echo "Safari compatibility check failed"
  exit 1
fi

GitHub Actions Integration

name: Safari Reader Mode Check
on: [push, pull_request]

jobs:
  safari-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Setup Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '16'
          
      - name: Install SurfaceScore CLI
        run: npm install -g @surfacescore/cli
        
      - name: Check Safari compatibility
        env:
          SURFACESCORE_API_KEY: ${{ secrets.SURFACESCORE_API_KEY }}
        run: |
          surfacescore check ${{ github.event.deployment.payload.web_url }} \
            --threshold 85 \
            --format github-actions

Browser Extension

Installation

Install the SurfaceScore Developer Extension from:

Features

Live Reader Mode Preview

See how your content appears in Safari Reader Mode in real-time:

  • ✅ Side-by-side comparison with original page
  • ✅ Highlight extracted content
  • ✅ Show content that's excluded
  • ✅ Test different viewport sizes

Content Structure Analysis

Visual analysis of your page structure:

  • 🏗️ Semantic HTML element highlighting
  • 📊 Heading hierarchy visualization
  • 🎯 Content-to-noise ratio analysis
  • ⚠️ Issue identification and suggestions

Apple Intelligence Simulation

Preview how Apple Intelligence interprets your content:

  • 📝 Generated content summaries
  • 🔍 Key topic identification
  • 📊 Content quality scoring
  • 💡 Optimization suggestions

Usage

  1. Navigate to any webpage
  2. Click the SurfaceScore extension icon
  3. Choose your analysis type:
    • Quick Scan - Basic compatibility check
    • Deep Analysis - Comprehensive review
    • Reader Mode Preview - Live preview
  4. Review results and implement suggestions

Code Examples

React Integration

import React, { useEffect, useState } from 'react';
import SurfaceScore from '@surfacescore/sdk';

const SafariCompatibilityChecker = ({ url }) => {
  const [score, setScore] = useState(null);
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    const checkCompatibility = async () => {
      setLoading(true);
      try {
        const surfaceScore = new SurfaceScore({
          apiKey: process.env.REACT_APP_SURFACESCORE_API_KEY
        });
        
        const result = await surfaceScore.analyze(url);
        setScore(result.scores);
      } catch (error) {
        console.error('Analysis failed:', error);
      } finally {
        setLoading(false);
      }
    };
    
    if (url) {
      checkCompatibility();
    }
  }, [url]);
  
  if (loading) return <div>Analyzing Safari compatibility...</div>;
  if (!score) return null;
  
  return (
    <div className="safari-score">
      <h3>Safari Compatibility Score</h3>
      <div className="score-display">
        <span className="overall-score">{score.overall}/100</span>
        <div className="breakdown">
          <div>Reader Mode: {score.readerMode}/100</div>
          <div>Apple Intelligence: {score.appleIntelligence}/100</div>
        </div>
      </div>
    </div>
  );
};

WordPress Plugin Integration

<?php
// WordPress plugin integration example

class SurfaceScorePlugin {
    private $api_key;
    
    public function __construct() {
        $this->api_key = get_option('surfacescore_api_key');
        add_action('save_post', array($this, 'analyze_post'));
        add_meta_box('surfacescore', 'Safari Compatibility', 
                    array($this, 'meta_box_callback'), 'post');
    }
    
    public function analyze_post($post_id) {
        if (wp_is_post_revision($post_id)) return;
        
        $url = get_permalink($post_id);
        $response = wp_remote_post('https://api.surfacescore.com/v1/analyze', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode(array(
                'url' => $url,
                'options' => array('includeRecommendations' => true)
            ))
        ));
        
        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            update_post_meta($post_id, '_surfacescore_data', $data);
        }
    }
    
    public function meta_box_callback($post) {
        $data = get_post_meta($post->ID, '_surfacescore_data', true);
        if ($data && isset($data['scores'])) {
            echo '<div class="surfacescore-results">';
            echo '<p>Overall Score: ' . $data['scores']['overall'] . '/100</p>';
            echo '<p>Reader Mode: ' . $data['scores']['readerMode'] . '/100</p>';
            echo '</div>';
        } else {
            echo '<p>No analysis data available. Save post to analyze.</p>';
        }
    }
}

new SurfaceScorePlugin();
?>

Node.js Server Integration

const express = require('express');
const SurfaceScore = require('@surfacescore/sdk');

const app = express();
const surfaceScore = new SurfaceScore({
  apiKey: process.env.SURFACESCORE_API_KEY
});

app.use(express.json());

// Middleware to check Safari compatibility
app.use('/api/content', async (req, res, next) => {
  if (req.method === 'POST' && req.body.url) {
    try {
      const analysis = await surfaceScore.analyze(req.body.url);
      
      // Add compatibility score to response
      req.safariScore = analysis.scores;
      
      // Log low scores for monitoring
      if (analysis.scores.overall < 80) {
        console.warn(`Low Safari score for ${req.body.url}: ${analysis.scores.overall}`);
      }
    } catch (error) {
      console.error('Safari analysis failed:', error);
    }
  }
  next();
});

// API endpoint with Safari score
app.post('/api/content', (req, res) => {
  res.json({
    success: true,
    data: req.body,
    safariCompatibility: req.safariScore || null
  });
});

app.listen(3000, () => {
  console.log('Server running with Safari compatibility checking');
});

Testing & Debugging

Local Development Testing

// Test local development server
const surfaceScore = new SurfaceScore({
  apiKey: 'your-api-key',
  environment: 'sandbox'
});

// Use ngrok or similar for local testing
const localUrl = 'https://abc123.ngrok.io/article';
const result = await surfaceScore.analyze(localUrl);

console.log('Local development score:', result.scores.overall);

Debug Mode

// Enable debug mode for detailed logging
const surfaceScore = new SurfaceScore({
  apiKey: 'your-api-key',
  debug: true,
  logLevel: 'verbose'
});

// Debug specific issues
const debugAnalysis = await surfaceScore.analyze(url, {
  debug: {
    captureScreenshots: true,
    logContentExtraction: true,
    validateStructuredData: true
  }
});

console.log('Debug info:', debugAnalysis.debug);

Common Issues & Solutions

❌ Low Reader Mode Score

Symptoms: Content not extracted properly in Safari Reader Mode

Solutions:

  • Use semantic HTML elements (<article>, <section>)
  • Ensure proper heading hierarchy
  • Move non-content elements to <aside>
  • Add role="main" to primary content area

❌ Poor Apple Intelligence Score

Symptoms: Content not summarized correctly by AI

Solutions:

  • Add comprehensive structured data
  • Use Apple Intelligence meta tags
  • Improve content depth and clarity
  • Ensure clear topic definition

❌ API Rate Limit Errors

Symptoms: 429 Too Many Requests responses

Solutions:

  • Implement exponential backoff retry logic
  • Cache analysis results locally
  • Use batch analysis for multiple URLs
  • Upgrade to higher tier plan

Community & Support

Open Source

SurfaceScore is committed to open source development:

Community Resources

Support Channels

  • 📧 Email: developers@surfacescore.com
  • 💬 Live Chat: Available in developer dashboard
  • 📞 Enterprise Support: Dedicated support for enterprise customers
  • 📖 Documentation: Comprehensive guides and tutorials

Contributing

We welcome contributions from the developer community:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests and documentation
  5. Submit a pull request

Ready to Get Started?

Sign up for a free developer account and start integrating Safari Reader Mode optimization into your workflow.

Get API Key