Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support site verification #14

Merged
merged 5 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ jobs:
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps

- run: pnpm run build

- name: Playwright tests
run: pnpm exec playwright test

Expand Down
2 changes: 1 addition & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"preview": "vite preview"
},
"dependencies": {
"@barbapapazes/plausible-tracker": "latest"
"@barbapapazes/plausible-tracker": "workspace:*"
},
"devDependencies": {
"typescript": "^5.6.2",
Expand Down
16 changes: 16 additions & 0 deletions playground/site-verification.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Site Verification
</title>
</head>
<body>
<!--
This playground page is meant to be used by the end-to-end tests. Please do not remove any of the following elements.
-->
<script type="module" src="/src/site-verification.ts"></script>
</body>
</html>
2 changes: 1 addition & 1 deletion playground/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createPlausibleTracker } from '@barbapapazes/plausible-tracker'
import { defaultFileTypes, useAutoFileDownloadsTracking, useAutoOutboundTracking, useAutoPageviews } from '@barbapapazes/plausible-tracker/extensions'

const plausible = createPlausibleTracker({ ignoreSubDomains: true })
const plausible = createPlausibleTracker()

const { install: installAutoPageviews, cleanup: cleanupAutoPageViews } = useAutoPageviews(plausible)
const { install: installAutoOutboundTracking, cleanup: cleanupAutoOutboundTracking } = useAutoOutboundTracking(plausible)
Expand Down
5 changes: 5 additions & 0 deletions playground/src/site-verification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createPlausibleTracker } from '@barbapapazes/plausible-tracker'

createPlausibleTracker({
ignoredHostnames: [],
})
9 changes: 2 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
packages:
- ./
- playground
8 changes: 4 additions & 4 deletions src/event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { EventData, EventPayload } from './types'
import type { CallbackArgs, EventData, EventPayload } from './types'

/**
* Check if the protocol is file
Expand Down Expand Up @@ -75,15 +75,15 @@ export function sendEvent(
apiHost: string,
/** The event payload */
payload: EventPayload,
callback?: () => void,
callback?: (args: CallbackArgs) => void,
) {
return fetch(`${apiHost}/api/event`, {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify(payload),
}).then(() => {
callback?.()
}).then((response: Response) => {
callback?.({ status: response.status })
}).catch(() => {})
}
11 changes: 8 additions & 3 deletions src/plausible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @see https://github.com/plausible/analytics/blob/master/tracker/src/customEvents.js#L77
*/

import type { EventName, EventOptions, EventPayload, Plausible, PlausibleOptions } from './types'
import type { CallbackArgs, EventName, EventOptions, EventPayload, Plausible, PlausibleOptions } from './types'
import { sendEvent as _sendEvent, createEventData, isFile, isIgnored, isUserSelfExcluded } from './event'
import { createPayload } from './payload'

Expand All @@ -30,7 +30,7 @@ export function createPlausibleTracker(initOptions?: Partial<PlausibleOptions>)
// Options does not change later.
const plausibleOptions = { ...defaultOptions, ...initOptions } satisfies PlausibleOptions

const sendEvent = (payload: EventPayload, callback?: () => void) => _sendEvent(plausibleOptions.apiHost, payload, callback)
const sendEvent = (payload: EventPayload, callback?: (args: CallbackArgs) => void) => _sendEvent(plausibleOptions.apiHost, payload, callback)

/**
* Send a custom event.
Expand All @@ -53,7 +53,7 @@ export function createPlausibleTracker(initOptions?: Partial<PlausibleOptions>)
console.info(`[Plausible] ${eventName}`, payload)

// Call the callback if it exists since we are not sending the event.
options?.callback?.()
options?.callback?.({ status: null })
}
else {
return sendEvent(payload, options?.callback)
Expand All @@ -67,6 +67,11 @@ export function createPlausibleTracker(initOptions?: Partial<PlausibleOptions>)
return trackEvent('pageview', options)
}

/**
* Add Plausible script to the page to enable site verification.
*/
window.plausible = trackEvent

return {
trackEvent,
trackPageview,
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,16 @@ export interface PlausibleOptions {
readonly logIgnored: boolean
}

export interface CallbackArgs {
readonly status: number | null
}

export interface EventOptions extends EventProps {
data?: Partial<EventData>
/**
* Callback to be called after the event is sent.
*/
callback?: () => void
callback?: (args: CallbackArgs) => void
}

/**
Expand Down
7 changes: 7 additions & 0 deletions src/window.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { EventOptions } from './types'

declare global {
interface Window {
plausible: (eventName: string, options?: EventOptions) => void
}
}
26 changes: 26 additions & 0 deletions test/e2e/site-verification.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { expect, test } from '@playwright/test'
import { plausibleEventRequest } from './utils'

test.describe('Site verification', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/site-verification')
})

test('should be able to verify the site', async ({ page }) => {
const requestPromise = plausibleEventRequest(page)

const status = await page.evaluate(async () => {
let status: number | undefined
// @ts-expect-error - Plausible is available in the browser
await window.plausible('site-verification', { callback: (args) => {
status = args.status
} })

return status
})

await requestPromise

expect(status).toBe(202)
})
})