Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
feat(plausible): expose cursor and offset pagination
Rudy Celekli63ca199ffe1e
diff --git a/tests/clis/plausible-pagination.test.cjs b/tests/clis/plausible-pagination.test.cjsnew file mode 100644index 0000000..d797e29--- /dev/null+++ b/tests/clis/plausible-pagination.test.cjs@@ -0,0 +1,91 @@+const { test } = require('node:test')+const assert = require('node:assert/strict')+const { createServer } = require('node:http')+const { spawn } = require('node:child_process')+const path = require('node:path')+const cli = path.resolve(__dirname, '../../tools/clis/plausible.js')++async function run(args) {+ const requests = []+ const cursor = 'next+/= page'+ const server = createServer(async (req, res) => {+ let text = ''+ for await (const chunk of req) text += chunk+ const url = new URL(req.url, 'http://fixture.test')+ const body = text ? JSON.parse(text) : undefined+ requests.push({ method: req.method, url, body })+ let payload+ if (url.pathname === '/api/v2/query') {+ payload = { results: [{ dimensions: [body.pagination?.offset === 20 ? '/second-page' : '/first-page'], metrics: [1] }], meta: {} }+ } else {+ const collection = url.pathname.endsWith('/goals') ? 'goals' : 'sites'+ const next = url.searchParams.get('after') === cursor+ payload = { [collection]: [{ id: next ? 'second-page' : 'first-page' }], meta: { after: next ? null : cursor, before: next ? 'previous==' : null, limit: Number(url.searchParams.get('limit') || 100) } }+ }+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(payload))+ })+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))+ try {+ const child = spawn(process.execPath, [cli, ...args], { env: { ...process.env, PLAUSIBLE_API_KEY: 'owned-fixture-key', PLAUSIBLE_BASE_URL: `http://127.0.0.1:${server.address().port}` } })+ let stdout = '', stderr = ''+ child.stdout.on('data', data => { stdout += data })+ child.stderr.on('data', data => { stderr += data })+ const status = await new Promise(resolve => child.on('close', resolve))+ assert.equal(status, 0, stderr)+ return { payload: JSON.parse(stdout), requests, cursor }+ } finally { await new Promise(resolve => server.close(resolve)) }+}++for (const collection of ['sites', 'goals']) {+ const args = [collection, 'list', ...(collection === 'goals' ? ['--site-id', 'example.com'] : [])]+ test(`${collection} list honors an explicit page limit`, async () => {+ const result = await run([...args, '--limit', '20'])+ assert.equal(result.requests[0].url.searchParams.get('limit'), '20')+ assert.equal(result.payload.meta.limit, 20)+ })+ test(`${collection} list follows the returned opaque next cursor`, async () => {+ const first = await run([...args, '--limit', '20'])+ const second = await run([...args, '--after', first.payload.meta.after, '--limit', '20'])+ assert.equal(second.requests[0].url.searchParams.get('after'), first.cursor)+ assert.equal(second.payload[collection][0].id, 'second-page')+ assert.equal(second.payload.meta.after, null)+ if (collection === 'goals') assert.equal(second.requests[0].url.searchParams.get('site_id'), 'example.com')+ })+ test(`${collection} list encodes a previous cursor`, async () => {+ const result = await run([...args, '--before', 'previous+/= page'])+ assert.equal(result.requests[0].url.searchParams.get('before'), 'previous+/= page')+ })+ test(`${collection} default remains its first page`, async () => {+ const result = await run(args)+ assert.equal(result.payload[collection][0].id, 'first-page')+ assert.equal(result.payload.meta.limit, 100)+ assert.equal(result.requests[0].url.searchParams.has('after'), false)+ assert.equal(result.requests[0].url.searchParams.has('before'), false)+ })+ test(`${collection} page preview has the same encoded query and no request`, async () => {+ const result = await run([...args, '--after', 'next+/= page', '--limit', '20', '--dry-run'])+ assert.equal(result.requests.length, 0)+ const preview = new URL(result.payload.url)+ assert.equal(preview.searchParams.get('after'), 'next+/= page')+ assert.equal(preview.searchParams.get('limit'), '20')+ assert.equal(result.payload.headers.Authorization, '***')+ })+}+for (const sub of ['pages', 'sources', 'countries', 'devices', 'utm', 'query']) {+ test(`stats ${sub} requests the next offset instead of repeating the first rows`, async () => {+ const result = await run(['stats', sub, '--site-id', 'example.com', '--metrics', 'visitors', '--limit', '20', '--offset', '20'])+ assert.deepEqual(result.requests[0].body.pagination, { limit: 20, offset: 20 })+ assert.equal(result.payload.results[0].dimensions[0], '/second-page')+ })+}+test('stats page defaults preserve the existing request', async () => {+ const result = await run(['stats', 'pages', '--site-id', 'example.com'])+ assert.deepEqual(result.requests[0].body.pagination, { limit: 100 })+})+test('stats preview exposes an explicit zero offset without making a request', async () => {+ const result = await run(['stats', 'pages', '--site-id', 'example.com', '--offset', '0', '--dry-run'])+ assert.equal(result.requests.length, 0)+ assert.deepEqual(result.payload.body.pagination, { limit: 100, offset: 0 })+ assert.equal(result.payload.headers.Authorization, '***')+})diff --git a/tools/clis/plausible.js b/tools/clis/plausible.jsindex 3d2037c..4029bf5 100755--- a/tools/clis/plausible.js+++ b/tools/clis/plausible.js@@ -67,10 +67,22 @@ function statsDateRange(value) {return range}+function sitesPagination(siteId) {+ const params = new URLSearchParams()+ if (siteId !== undefined) params.set('site_id', siteId)+ if (args.limit !== undefined) params.set('limit', args.limit)+ if (args.after !== undefined) params.set('after', args.after)+ if (args.before !== undefined) params.set('before', args.before)+ const query = params.toString()+ return query ? `?${query}` : ''+}+async function main() {let resultconst siteId = args['site-id']const limit = args.limit ? Number(args.limit) : 100+ const pagination = { limit }+ if (args.offset !== undefined) pagination.offset = Number(args.offset)switch (cmd) {case 'stats':@@ -104,7 +116,7 @@ async function main() {metrics,date_range: dateRange,dimensions: ['event:page'],- pagination: { limit },+ pagination,})break}@@ -115,7 +127,7 @@ async function main() {metrics,date_range: dateRange,dimensions: ['visit:source'],- pagination: { limit },+ pagination,})break}@@ -126,7 +138,7 @@ async function main() {metrics,date_range: dateRange,dimensions: ['visit:country'],- pagination: { limit },+ pagination,})break}@@ -137,7 +149,7 @@ async function main() {metrics,date_range: dateRange,dimensions: ['visit:device'],- pagination: { limit },+ pagination,})break}@@ -149,7 +161,7 @@ async function main() {metrics,date_range: dateRange,dimensions: [`visit:${param}`],- pagination: { limit },+ pagination,})break}@@ -161,7 +173,7 @@ async function main() {if (args.filters) {try { body.filters = JSON.parse(args.filters) } catch { result = { error: '--filters must be valid JSON' }; break }}- body.pagination = { limit }+ body.pagination = paginationresult = await api('POST', '/api/v2/query', body)break}@@ -176,7 +188,7 @@ async function main() {case 'sites':switch (sub) {case 'list':- result = await api('GET', '/api/v1/sites')+ result = await api('GET', `/api/v1/sites${sitesPagination()}`)breakcase 'get': {if (!siteId) { result = { error: '--site-id required' }; break }@@ -205,7 +217,7 @@ async function main() {if (!siteId) { result = { error: '--site-id required' }; break }switch (sub) {case 'list':- result = await api('GET', `/api/v1/sites/goals?site_id=${encodeURIComponent(siteId)}`)+ result = await api('GET', `/api/v1/sites/goals${sitesPagination(siteId)}`)breakcase 'create': {const goalType = args['goal-type']@@ -247,9 +259,9 @@ async function main() {query: 'stats query --site-id <domain> --metrics <m1,m2> [--dimensions <d1,d2>] [--filters <json>]',realtime: 'stats realtime --site-id <domain>',},- sites: 'sites [list | get --site-id <domain> | create --domain <domain> | delete --site-id <domain>]',- goals: 'goals [list | create --goal-type <event|page> --event-name <name> | delete --goal-id <id>] --site-id <domain>',- options: '--date-range <preset|JSON array [start,end]> --limit <n>',+ sites: 'sites [list [--limit <n>] [--after <cursor> | --before <cursor>] | get --site-id <domain> | create --domain <domain> | delete --site-id <domain>]',+ goals: 'goals [list [--limit <n>] [--after <cursor> | --before <cursor>] | create --goal-type <event|page> --event-name <name> | delete --goal-id <id>] --site-id <domain>',+ options: '--date-range <preset|JSON array [start,end]> --limit <n>; stats breakdown/query: --offset <n>; sites/goals list: --after <cursor> | --before <cursor>',env: 'PLAUSIBLE_BASE_URL for self-hosted instances (default: https://plausible.io)',}}diff --git a/tools/integrations/plausible.md b/tools/integrations/plausible.mdindex 3361b0a..452bb57 100644--- a/tools/integrations/plausible.md+++ b/tools/integrations/plausible.md@@ -192,3 +192,36 @@ presets (such as `7d`) and the default `30d` remain strings. Malformed arrays orarrays without exactly two nonempty strings fail before the stats request;Plausible validates the date values. See the[Stats API date_range contract](https://plausible.io/docs/stats-api).++## Paginating CLI results++The CLI returns one page per invocation; it does not automatically fetch every+page. Use the pagination scheme of the endpoint you selected:++- **Sites and goals:** pass the response's opaque `meta.after` or `meta.before`+ cursor unchanged as `--after` or `--before`. Keep `--limit` unchanged between+ requests (or leave it unset for the default 100). A null cursor means there is+ no next or previous page. Do not supply both cursors in one request.+- **Stats breakdowns and query:** use `--limit` and `--offset` for `pages`,+ `sources`, `countries`, `devices`, `utm`, or `query`. Offset zero starts at the+ first result; increase it by the page size for the next page. Keep metrics,+ dimensions, filters, date range and ordering consistent while paging. These+ flags do not paginate aggregate, timeseries or realtime operations.++```bash+node tools/clis/plausible.js sites list --limit 20+# Copy meta.after from the response, without decoding or altering it:+node tools/clis/plausible.js sites list --limit 20 --after '<returned cursor>'++node tools/clis/plausible.js goals list --site-id example.com --limit 20 \+ --before '<returned cursor>'++node tools/clis/plausible.js stats pages --site-id example.com --limit 20 --offset 20+```++`--dry-run` previews the same encoded query or stats pagination body without+making a request. See the official [Sites API pagination](https://plausible.io/docs/sites-api#pagination)+and [Stats API pagination](https://plausible.io/docs/stats-api#pagination-optional)+contracts. Read-only Sites endpoints, including listing sites and goals, also+accept a Stats API key on plans that include that API; Sites API mutations+require the appropriate Enterprise permissions.