Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

6.4 KB
Raw Blame
#!/usr/bin/env node

const rawArgs = process.argv.slice(2)
const API_KEY = process.env.SUPERMETRICS_API_KEY
const BASE_URL = 'https://api.supermetrics.com'

if ((!API_KEY) && rawArgs.length > 0) {
  console.error(JSON.stringify({ error: 'SUPERMETRICS_API_KEY environment variable required' }))
  process.exit(1)
}


function requestSignal() {
  const raw = args['timeout-ms'] ?? '120000'
  const ms = Number(raw)
  if (typeof raw !== 'string' || !/^\d+$/.test(raw) || !Number.isSafeInteger(ms) || ms < 1 || ms > 600000) {
    throw new Error('--timeout-ms must be an integer from 1 to 600000')
  }
  return AbortSignal.timeout(ms)
}


async function api(method, path, body) {
  const url = `${BASE_URL}${path}`
  const headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${API_KEY}`,
  }
  if (args['dry-run']) {
    return { _dry_run: true, method, url, headers: { ...headers, Authorization: 'Bearer ***' }, body: body || undefined }
  }
  const res = await fetch(url, { signal: requestSignal(),
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  })
  const text = await res.text()
  if (!res.ok) throw new Error(`Supermetrics request failed (${res.status}): ${text}`)
  try {
    return JSON.parse(text)
  } catch {
    return { status: res.status, body: text }
  }
}

function parseArgs(args) {
  const result = { _: [] }
  for (let i = 0; i < args.length; i++) {
    const arg = args[i]
    if (arg.startsWith('--')) {
      const key = arg.slice(2)
      const next = args[i + 1]
      if (next && !next.startsWith('--')) {
        result[key] = next
        i++
      } else {
        result[key] = true
      }
    } else {
      result._.push(arg)
    }
  }
  return result
}

const args = parseArgs(rawArgs)
const [cmd, sub, ...rest] = args._

async function main() {
  let result

  switch (cmd) {
    case 'query': {
      const dsId = args['ds-id']
      const dsAccounts = args['ds-accounts']
      const dateRange = args['date-range']
      const fields = args.fields
      if (!dsId) { result = { error: '--ds-id required (e.g., GA4, AW, FB, LI, GSC)' }; break }
      if (!dsAccounts) { result = { error: '--ds-accounts required' }; break }
      if (!dateRange) { result = { error: '--date-range required (e.g., last_28_days, last_month, this_month, custom)' }; break }
      if (!fields) { result = { error: '--fields required (comma-separated field names)' }; break }
      const fieldIds = fields.split(',').map(f => f.trim())
      if (fieldIds.some(f => !f)) { result = { error: '--fields must contain nonempty field IDs' }; break }
      if (dateRange === 'custom' && (!args['start-date'] || !args['end-date'])) {
        result = { error: '--start-date and --end-date required for a custom date range' }; break
      }
      const body = {
        ds_id: dsId,
        ds_accounts: dsAccounts,
        date_range_type: dateRange,
        fields: fieldIds.map(id => ({ id })),
      }
      if (dateRange === 'last_28_days') {
        body.date_range_type = 'custom'
        body.start_date = '-28 days'
        body.end_date = 'yesterday'
      }
      if (args.filter) body.filter = args.filter
      if (args['max-rows']) body.max_rows = parseInt(args['max-rows'], 10)
      if (args['start-date']) body.start_date = args['start-date']
      if (args['end-date']) body.end_date = args['end-date']
      result = await api('POST', '/query/data/json', body)
      break
    }

    case 'sources':
      switch (sub) {
        case 'list':
          result = await api('GET', '/datasource/search')
          break
        default:
          result = { error: 'Unknown sources subcommand. Use: list' }
      }
      break

    case 'accounts':
      switch (sub) {
        case 'list': {
          const dsId = args['ds-id']
          if (!dsId) { result = { error: '--ds-id required (e.g., GA4, AW, FB)' }; break }
          const params = new URLSearchParams({ ds_id: dsId })
          result = await api('GET', `/query/accounts?${params.toString()}`)
          break
        }
        default:
          result = { error: 'Unknown accounts subcommand. Use: list' }
      }
      break

    case 'teams':
      switch (sub) {
        case 'get': {
          const id = args['team-id']
          if (!id || !/^[1-9]\d*$/.test(id)) { result = { error: '--team-id required (positive integer team ID)' }; break }
          result = await api('GET', `/v1/teams/${id}`)
          break
        }
        case 'list':
          result = { error: 'The public API has no teams list endpoint. Use: teams get --team-id <id>' }
          break
        default:
          result = { error: 'Unknown teams subcommand. Use: get --team-id <id>' }
      }
      break

    case 'users':
      switch (sub) {
        case 'list': {
          const id = args['team-id']
          if (!id || !/^[1-9]\d*$/.test(id)) { result = { error: '--team-id required (positive integer team ID)' }; break }
          result = await api('GET', `/v1/teams/${id}/users`)
          break
        }
        default:
          result = { error: 'Unknown users subcommand. Use: list' }
      }
      break

    default:
      result = {
        error: 'Unknown command',
        usage: {
          query: 'query --ds-id <data-source> --ds-accounts <account-id> --date-range <range> --fields <f1,f2> [--filter <filter>] [--max-rows <n>] [--start-date <date>] [--end-date <date>]',
          sources: {
            list: 'sources list',
          },
          accounts: {
            list: 'accounts list --ds-id <data-source>',
          },
          teams: {
            get: 'teams get --team-id <id>',
          },
          users: {
            list: 'users list --team-id <id>',
          },
          'data-source-ids': {
            'GA4': 'Google Analytics 4',
            'GA4_PAID': 'Google Analytics (paid)',
            'AW': 'Google Ads',
            'FB': 'Facebook Ads',
            'LI': 'LinkedIn Ads',
            'TW_ADS': 'Twitter Ads',
            'IG_IA': 'Instagram',
            'FB_IA': 'Facebook Pages',
            'GSC': 'Google Search Console',
            'SE': 'Semrush',
            'MC': 'Mailchimp',
          },
          'date-ranges': ['last_28_days', 'last_month', 'this_month', 'custom'],
        }
      }
  }

  if (result?.error && rawArgs.length > 0) process.exitCode = 1
  console.log(JSON.stringify(result, null, 2))
}

main().catch(err => {
  console.error(JSON.stringify({ error: err.message }))
  process.exit(1)
})