@cherwell/emdash-plausible 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +223 -2
- package/assets/banner.png +0 -0
- package/assets/icon.png +0 -0
- package/assets/icon.svg +6 -0
- package/dist/helpers/astro.d.ts +48 -0
- package/dist/helpers/astro.js +229 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +154 -0
- package/dist/manifest.json +155 -0
- package/dist/plugin.d.mts +1698 -0
- package/dist/plugin.mjs +56 -0
- package/docs/faq.md +35 -0
- package/docs/install.md +41 -0
- package/docs/overview.md +14 -0
- package/docs/reference.md +142 -0
- package/docs/security.md +11 -0
- package/emdash-plugin.jsonc +64 -0
- package/llms.txt +20 -0
- package/package.json +78 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 0cbf15e: Published from GitHub Actions with npm trusted publishing, so each release carries a provenance statement linking it to its source commit.
|
|
8
|
+
|
|
9
|
+
## 0.1.0
|
|
10
|
+
|
|
11
|
+
First release.
|
|
12
|
+
|
|
13
|
+
- **Tracking:** Plausible's script on public pages through EmDash's page hooks, for both the per-site `pa-` script and the legacy `script.js`. Page type and collection go as custom properties. You can leave out paths, or switch tracking off for sites that send their own events.
|
|
14
|
+
- **Proxy:** `plausibleProxy` in `@cherwell/emdash-plausible/astro` serves the script and event endpoint from your own domain. It passes on the visitor headers Plausible's bot filter reads.
|
|
15
|
+
- **Sandboxed installs:** `plausibleTag` draws the same tag in a layout.
|
|
16
|
+
- **Reports:**
|
|
17
|
+
- visitors, visits, pageviews, bounce rate and visit duration
|
|
18
|
+
- a chart, top pages and top sources
|
|
19
|
+
- a dashboard widget and the `plausible_report` MCP tool
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cherwell Studio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,224 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Plausible Analytics for EmDash
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="assets/icon.png" alt="" width="96" align="right">
|
|
4
|
+
|
|
5
|
+
**Plausible's tracking script served from your own domain, and visitor reports in the EmDash admin.**
|
|
6
|
+
|
|
7
|
+
[Plausible](https://plausible.io) counts visitors without cookies. This plugin connects an EmDash site to it:
|
|
8
|
+
|
|
9
|
+
- **The script on every public page.** The plugin adds Plausible's tag through EmDash's page hooks, so you don't edit a layout. Paths you list, such as a members area, aren't tracked.
|
|
10
|
+
- **Served from your own domain.** A small site route passes Plausible's script and events through your site, at `/p/` by default. Blockers that drop third-party analytics hosts don't drop your visitors, and your Content Security Policy needs only `'self'`.
|
|
11
|
+
- **What kind of page it was.** Each pageview carries the page type and collection as custom properties, so Plausible can break visits down by walks, guides or articles.
|
|
12
|
+
- **Reports in the admin.** An **Analytics** page shows visitors, visits, pageviews, bounce rate and visit duration for 7 days, 30 days or 12 months. It also has a chart, the top pages and the top sources. A dashboard widget shows the last 7 days.
|
|
13
|
+
- **For AI agents.** An MCP tool, `plausible_report`, returns the same numbers.
|
|
14
|
+
- **Reports only, if you like.** A site that already sends its own events can switch tracking off and keep the reports.
|
|
15
|
+
|
|
16
|
+
## Documentation
|
|
17
|
+
|
|
18
|
+
- [Overview](docs/overview.md): what it does and who it is for
|
|
19
|
+
- [Installation](docs/install.md): add the plugin, the proxy route and the settings
|
|
20
|
+
- [FAQ](docs/faq.md): privacy, the two kinds of snippet, sandboxed installs, excluding your own visits
|
|
21
|
+
- [Reference](docs/reference.md): generated list of settings, routes, MCP tools and helpers
|
|
22
|
+
- [Security](docs/security.md): generated list of capabilities and hosts
|
|
23
|
+
- [llms.txt](llms.txt): a summary for AI agents
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm install @cherwell/emdash-plausible
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// astro.config.mjs
|
|
33
|
+
import plausible from "@cherwell/emdash-plausible";
|
|
34
|
+
emdash({ plugins: [plausible] });
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### In-process or sandboxed
|
|
38
|
+
|
|
39
|
+
| | In-process (`plugins: [...]`) | Sandboxed (`sandboxed: [...]`) |
|
|
40
|
+
|---|---|---|
|
|
41
|
+
| Tag added to pages | yes, by the plugin | no: add it with `plausibleTag` (below) |
|
|
42
|
+
| Reports, widget, MCP tool | yes | yes |
|
|
43
|
+
| Proxy route | yes | yes |
|
|
44
|
+
|
|
45
|
+
EmDash 1.6 runs page-fragment hooks for in-process plugins only, so a sandboxed install can't add the tag itself.
|
|
46
|
+
|
|
47
|
+
### The proxy route
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// src/pages/p/[...path].ts
|
|
51
|
+
import { plausibleProxy } from "@cherwell/emdash-plausible/astro";
|
|
52
|
+
|
|
53
|
+
export const prerender = false;
|
|
54
|
+
export const { GET, HEAD, POST } = plausibleProxy();
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
It answers two requests and refuses everything else with a 404:
|
|
58
|
+
|
|
59
|
+
| Request | What it does |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `GET` or `HEAD /p/js/<file>.js` | Fetches Plausible's script and serves it with `Cache-Control: public, max-age=21600`. Only `/js/` file names of letters, numbers, `.`, `_` and `-` are fetched. |
|
|
62
|
+
| `POST /p/api/event` | Passes the event to Plausible with the visitor's IP address in `X-Forwarded-For`, and the browser headers Plausible's bot filter reads (`User-Agent`, `Referer`, `Origin`, `Accept-Language`, `Sec-CH-UA*`, `Sec-Fetch-*`). Cookies and credentials are never passed on. Bodies over 8 KB are refused. |
|
|
63
|
+
|
|
64
|
+
Options:
|
|
65
|
+
|
|
66
|
+
| Option | Default | What it does |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| `host` | `https://plausible.io` | Plausible's address, for a self-hosted Plausible CE. |
|
|
69
|
+
| `scriptMaxAge` | `21600` | Seconds browsers and your CDN may keep the script. |
|
|
70
|
+
|
|
71
|
+
The visitor's IP address comes from Astro's `clientAddress`, then `CF-Connecting-IP`, then `X-Real-IP`. Without one, Plausible's filter drops the event and still answers `202`; the proxy passes on Plausible's `x-plausible-dropped: 1` header so you can see it.
|
|
72
|
+
|
|
73
|
+
If you put the route somewhere else, set **Proxy path** to match. To load the script straight from plausible.io instead, leave **Proxy path** empty and skip the route.
|
|
74
|
+
|
|
75
|
+
### The tag, for a sandboxed install
|
|
76
|
+
|
|
77
|
+
```astro
|
|
78
|
+
---
|
|
79
|
+
// In your layout's <head>
|
|
80
|
+
import { plausibleTag } from "@cherwell/emdash-plausible/astro";
|
|
81
|
+
const tag = plausibleTag(
|
|
82
|
+
{ domain: "example.com", scriptPath: "/js/pa-AbC123.js", nonce: Astro.locals.cspNonce },
|
|
83
|
+
{ path: Astro.url.pathname },
|
|
84
|
+
);
|
|
85
|
+
---
|
|
86
|
+
<Fragment set:html={tag} />
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`plausibleTag` takes the same options as the settings (`domain`, `scriptPath`, `proxyPath`, `skipPaths`, `pageProps`, `outbound`, `fileDownloads`), plus `nonce`. It returns the same HTML the plugin adds, or an empty string for a skipped path.
|
|
90
|
+
|
|
91
|
+
## The tag
|
|
92
|
+
|
|
93
|
+
Plausible has two kinds of snippet, and the plugin draws whichever your **Script file** names.
|
|
94
|
+
|
|
95
|
+
**Per-site script (`/js/pa-<id>.js`),** for sites added to Plausible since late 2025. Outbound links, file downloads and other options are switched on in Plausible's site settings.
|
|
96
|
+
|
|
97
|
+
```html
|
|
98
|
+
<script async src="/p/js/pa-AbC123.js"></script>
|
|
99
|
+
<script>window.plausible=…;plausible.init({"endpoint":"/p/api/event","customProperties":{"page_type":"walk","collection":"walks"}})</script>
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Legacy script (`/js/script.js`).** The plugin adds the extensions you turn on to the file name.
|
|
103
|
+
|
|
104
|
+
```html
|
|
105
|
+
<script defer src="/p/js/script.file-downloads.outbound-links.pageview-props.js"
|
|
106
|
+
data-domain="example.com" data-api="/p/api/event"
|
|
107
|
+
event-page_type="walk" event-collection="walks"></script>
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
If you enter a legacy file that already names its extensions (such as `/js/script.hash.js`), it's used as it is.
|
|
111
|
+
|
|
112
|
+
The page hook reads settings at most every 30 seconds, never throws, and adds nothing if settings can't be read. Everything written into the page is checked first:
|
|
113
|
+
|
|
114
|
+
- the domain must be a host name
|
|
115
|
+
- the script must be a `/js/…js` file
|
|
116
|
+
- the proxy path must be a plain same-site path
|
|
117
|
+
|
|
118
|
+
Inline JSON can't close the `<script>` element.
|
|
119
|
+
|
|
120
|
+
## Settings
|
|
121
|
+
|
|
122
|
+
| Setting | Key | Default | What it does |
|
|
123
|
+
|---|---|---|---|
|
|
124
|
+
| Site domain | `domain` | none | The site as Plausible knows it, such as `example.com`. `https://` and paths are removed. Required. |
|
|
125
|
+
| Tracking | `tracking` | `script` | `script` adds Plausible's tag. `off` adds nothing, for a site that sends its own events. Reports work either way. |
|
|
126
|
+
| Script file | `scriptPath` | `/js/script.js` | From your Plausible snippet: `/js/pa-<id>.js` or `/js/script.js`. |
|
|
127
|
+
| Proxy path | `proxyPath` | `/p` | Where the proxy route is. Empty loads the script from plausible.io. |
|
|
128
|
+
| Paths not tracked | `skipPaths` | `/_emdash` | Comma-separated prefixes. `/members` skips `/members` and `/members/…`, not `/membership`. |
|
|
129
|
+
| Page type and collection | `pageProps` | on | Sends `page_type` and `collection` as custom properties. |
|
|
130
|
+
| Outbound links | `outbound` | on | Legacy script only. |
|
|
131
|
+
| File downloads | `fileDownloads` | on | Legacy script only. |
|
|
132
|
+
| Stats API key | `apiKey` | none | Secret. Needed for reports. |
|
|
133
|
+
| Keep reports for | `cacheMinutes` | 15 | 1 to 1,440 minutes. |
|
|
134
|
+
| Dashboard link | `dashboardUrl` | none | Your Plausible dashboard or a shared link, linked from the reports. |
|
|
135
|
+
|
|
136
|
+
### Custom properties in Plausible
|
|
137
|
+
|
|
138
|
+
To see the page type and collection in Plausible's reports, add `page_type` and `collection` under **Site settings ▸ Custom properties** in Plausible. You can then filter any report by them, for example visitors to walks only.
|
|
139
|
+
|
|
140
|
+
## Reports
|
|
141
|
+
|
|
142
|
+
**Analytics** in the admin shows, for the last 7 days, 30 days or 12 months:
|
|
143
|
+
|
|
144
|
+
- **Totals:** visitors, visits, pageviews, bounce rate and average visit duration.
|
|
145
|
+
- **A chart:** visitors per day, or per month for 12 months.
|
|
146
|
+
- **Top pages and top sources:** the first ten of each.
|
|
147
|
+
|
|
148
|
+
The chosen period is remembered. **Refresh** asks Plausible straight away. Otherwise a report is kept for **Keep reports for** minutes, per period.
|
|
149
|
+
|
|
150
|
+
The **Visitors** dashboard widget shows the last 7 days.
|
|
151
|
+
|
|
152
|
+
Reports use Plausible's [Stats API v2](https://plausible.io/docs/stats-api), which is a Business-plan feature. Create a key in Plausible under **Account settings ▸ API keys**. Plausible allows 600 requests an hour across your whole team. A report is four requests, so with the 15-minute default one site uses at most 48 an hour for the three periods.
|
|
153
|
+
|
|
154
|
+
## Capabilities
|
|
155
|
+
|
|
156
|
+
| Capability | Why |
|
|
157
|
+
|---|---|
|
|
158
|
+
| `hooks.page-fragments:register` | To add Plausible's script tag to public pages. |
|
|
159
|
+
| `network:request` (host `plausible.io`) | To read reports from the Stats API. |
|
|
160
|
+
|
|
161
|
+
The plugin keeps no storage collections. Reports and the chosen period are kept in the plugin's KV.
|
|
162
|
+
|
|
163
|
+
## API
|
|
164
|
+
|
|
165
|
+
Private routes are under `/_emdash/api/plugins/plausible/` and need an editor's session or an API token. Every response is `{ ok: true, … }` or `{ ok: false, error: CODE }`.
|
|
166
|
+
|
|
167
|
+
| Route | Input | Returns |
|
|
168
|
+
|---|---|---|
|
|
169
|
+
| `report` | `range?` (`7d`, `30d` or `12mo`, default `30d`), `fresh?` (boolean) | `report` |
|
|
170
|
+
|
|
171
|
+
A report:
|
|
172
|
+
|
|
173
|
+
```json
|
|
174
|
+
{
|
|
175
|
+
"range": "30d",
|
|
176
|
+
"at": "2026-12-01T09:00:00.000Z",
|
|
177
|
+
"totals": { "visitors": 1200, "visits": 1500, "pageviews": 4100, "bounceRate": 52.4, "visitDuration": 95 },
|
|
178
|
+
"series": [[1795910400000, 40]],
|
|
179
|
+
"pages": [{ "page": "/walks/", "visitors": 500, "pageviews": 900 }],
|
|
180
|
+
"sources": [{ "source": "Google", "visitors": 300 }]
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`series` is `[UTC milliseconds, visitors]` pairs, oldest first. `bounceRate` is a percentage, and `visitDuration` is in seconds.
|
|
185
|
+
|
|
186
|
+
Error codes:
|
|
187
|
+
|
|
188
|
+
- `NO_DOMAIN`, `NO_KEY`: a setting is missing
|
|
189
|
+
- `KEY_REFUSED`: Plausible answered 401 or 403
|
|
190
|
+
- `RATE_LIMITED`: Plausible answered 429
|
|
191
|
+
- `PLAUSIBLE_ERROR`: any other error from Plausible
|
|
192
|
+
- `NO_NETWORK`: the install wasn't granted network access
|
|
193
|
+
- `INVALID_INPUT`, `INTERNAL`
|
|
194
|
+
|
|
195
|
+
### MCP tools
|
|
196
|
+
|
|
197
|
+
Turn them on in **Admin ▸ Plugins ▸ Plausible Analytics ▸ MCP**.
|
|
198
|
+
|
|
199
|
+
- **Read:** `plausible_report`, the same as the `report` route.
|
|
200
|
+
|
|
201
|
+
## Limits
|
|
202
|
+
|
|
203
|
+
- **Reports read plausible.io only.** The proxy works with a self-hosted Plausible CE (`host`), but the Stats API is limited to `plausible.io` by the plugin's declared hosts.
|
|
204
|
+
- **Fixed periods.** Reports cover the last 7 days, 30 days or 12 months, in your Plausible site's reporting time zone.
|
|
205
|
+
- **No goals yet.** Goals, conversion rates and custom properties are in Plausible's own dashboard. Link it with **Dashboard link**.
|
|
206
|
+
|
|
207
|
+
## Privacy
|
|
208
|
+
|
|
209
|
+
The plugin sets no cookies and stores nothing about visitors. The proxy passes each visitor's IP address and browser headers to Plausible and keeps nothing. Plausible combines the IP address and user agent with a salt it deletes every 24 hours, to count unique visitors. It never stores raw IP addresses or user agents (see [Plausible's data policy](https://plausible.io/data-policy)).
|
|
210
|
+
|
|
211
|
+
## Development
|
|
212
|
+
|
|
213
|
+
In this monorepo:
|
|
214
|
+
|
|
215
|
+
```sh
|
|
216
|
+
pnpm --filter @cherwell/emdash-plausible validate
|
|
217
|
+
pnpm --filter @cherwell/emdash-plausible typecheck
|
|
218
|
+
pnpm --filter @cherwell/emdash-plausible test
|
|
219
|
+
pnpm --filter @cherwell/emdash-plausible build
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## Licence
|
|
223
|
+
|
|
224
|
+
MIT © Cherwell Studio
|
|
Binary file
|
package/assets/icon.png
ADDED
|
Binary file
|
package/assets/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><g transform="translate(0 0)">
|
|
2
|
+
<defs><linearGradient id="t" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#5850EC"/><stop offset="1" stop-color="#3730A3"/></linearGradient></defs>
|
|
3
|
+
<rect width="512" height="512" rx="112.64" fill="url(#t)"/>
|
|
4
|
+
<rect x="1" y="1" width="510" height="510" rx="111.64" fill="none" stroke="#fff" stroke-opacity=".14" stroke-width="2"/>
|
|
5
|
+
<g transform="translate(102.4 102.4) scale(12.799999999999999)" fill="none" stroke="#fff" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M7 21V3h6a5 5 0 0 1 0 10H7"/><path d="M10 10l2.5-2.5 2 2 3-3"/></g>
|
|
6
|
+
</g></svg>
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//#region src/tag.d.ts
|
|
2
|
+
/** The part of a page the tag needs. EmDash's PublicPageContext has all of it. */
|
|
3
|
+
interface PageInfo {
|
|
4
|
+
path: string;
|
|
5
|
+
pageType?: string | null;
|
|
6
|
+
content?: {
|
|
7
|
+
collection: string;
|
|
8
|
+
} | null;
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/astro.d.ts
|
|
12
|
+
interface RouteContext {
|
|
13
|
+
params: Record<string, string | undefined>;
|
|
14
|
+
request: Request;
|
|
15
|
+
clientAddress?: string;
|
|
16
|
+
}
|
|
17
|
+
interface PlausibleProxyOptions {
|
|
18
|
+
/** Plausible's address, for a self-hosted Plausible CE. Default https://plausible.io. */
|
|
19
|
+
host?: string;
|
|
20
|
+
/** Seconds browsers and the CDN may keep the script. Default 21600 (six hours). */
|
|
21
|
+
scriptMaxAge?: number;
|
|
22
|
+
/** For tests. */
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
}
|
|
25
|
+
declare function plausibleProxy(opts?: PlausibleProxyOptions): {
|
|
26
|
+
GET: (ctx: RouteContext) => Promise<Response>;
|
|
27
|
+
HEAD: (ctx: RouteContext) => Promise<Response>;
|
|
28
|
+
POST: (ctx: RouteContext) => Promise<Response>;
|
|
29
|
+
};
|
|
30
|
+
interface PlausibleTagOptions {
|
|
31
|
+
/** The plugin's settings, or the same values from your own config. */
|
|
32
|
+
domain: string;
|
|
33
|
+
scriptPath?: string;
|
|
34
|
+
proxyPath?: string;
|
|
35
|
+
skipPaths?: string;
|
|
36
|
+
pageProps?: boolean;
|
|
37
|
+
outbound?: boolean;
|
|
38
|
+
fileDownloads?: boolean;
|
|
39
|
+
/** The Content Security Policy nonce, if the site uses one. */
|
|
40
|
+
nonce?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The same tag the plugin adds, as HTML, for a layout's <head> when the plugin
|
|
44
|
+
* runs sandboxed: `<Fragment set:html={plausibleTag(opts, { path: Astro.url.pathname })} />`.
|
|
45
|
+
*/
|
|
46
|
+
declare function plausibleTag(opts: PlausibleTagOptions, page: PageInfo): string;
|
|
47
|
+
//#endregion
|
|
48
|
+
export { type PageInfo, PlausibleProxyOptions, PlausibleTagOptions, plausibleProxy, plausibleTag };
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
//#region src/tag.ts
|
|
2
|
+
/**
|
|
3
|
+
* Plausible's script tag for one page.
|
|
4
|
+
*
|
|
5
|
+
* Two kinds of snippet exist. A site added to Plausible since late 2025 gets
|
|
6
|
+
* its own script, /js/pa-<id>.js, set up with `plausible.init({...})`; its
|
|
7
|
+
* outbound-link and download tracking are switched on in Plausible's site
|
|
8
|
+
* settings. Older sites use /js/script.js, with extensions named in the file
|
|
9
|
+
* (script.file-downloads.outbound-links.js) and the domain in data-domain.
|
|
10
|
+
*/
|
|
11
|
+
const PLAUSIBLE = "https://plausible.io";
|
|
12
|
+
const isPerSite = (path) => /\/pa-[A-Za-z0-9_-]+\.js$/.test(path);
|
|
13
|
+
/** Custom properties sent with each pageview: what kind of page it is. */
|
|
14
|
+
function pageProps(page) {
|
|
15
|
+
const out = {};
|
|
16
|
+
if (page.pageType) out.page_type = String(page.pageType).slice(0, 60);
|
|
17
|
+
if (page.content?.collection) out.collection = String(page.content.collection).slice(0, 60);
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
/** Whether a page is tracked at all. */
|
|
21
|
+
function tracked(c, page) {
|
|
22
|
+
if (!c.domain) return false;
|
|
23
|
+
const path = page.path || "/";
|
|
24
|
+
return !c.skip.some((p) => path === p || path.startsWith(p.endsWith("/") ? p : `${p}/`));
|
|
25
|
+
}
|
|
26
|
+
/** The legacy script with the extensions the settings ask for, unless the file already names its own. */
|
|
27
|
+
function legacyFile(c, props) {
|
|
28
|
+
if (!/\/script\.js$/.test(c.scriptPath)) return c.scriptPath;
|
|
29
|
+
const ext = [
|
|
30
|
+
c.fileDownloads && "file-downloads",
|
|
31
|
+
c.outbound && "outbound-links",
|
|
32
|
+
props && "pageview-props"
|
|
33
|
+
].filter(Boolean);
|
|
34
|
+
return ext.length ? c.scriptPath.replace(/script\.js$/, `script.${ext.join(".")}.js`) : c.scriptPath;
|
|
35
|
+
}
|
|
36
|
+
/** JSON that can sit inside a <script> element: no "<\/script>" or "<!--" can be formed. */
|
|
37
|
+
const scriptJson = (v) => JSON.stringify(v).replace(/</g, "\\u003c");
|
|
38
|
+
function fragments(c, page) {
|
|
39
|
+
if (!tracked(c, page)) return [];
|
|
40
|
+
const base = c.proxyPath || PLAUSIBLE;
|
|
41
|
+
const endpoint = c.proxyPath ? `${c.proxyPath}/api/event` : null;
|
|
42
|
+
const props = c.pageProps ? pageProps(page) : {};
|
|
43
|
+
const hasProps = Object.keys(props).length > 0;
|
|
44
|
+
if (isPerSite(c.scriptPath)) {
|
|
45
|
+
const options = {};
|
|
46
|
+
if (endpoint) options.endpoint = endpoint;
|
|
47
|
+
if (hasProps) options.customProperties = props;
|
|
48
|
+
return [{
|
|
49
|
+
kind: "external-script",
|
|
50
|
+
placement: "head",
|
|
51
|
+
src: `${base}${c.scriptPath}`,
|
|
52
|
+
async: true,
|
|
53
|
+
key: "plausible"
|
|
54
|
+
}, {
|
|
55
|
+
kind: "inline-script",
|
|
56
|
+
placement: "head",
|
|
57
|
+
key: "plausible-init",
|
|
58
|
+
code: `window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};plausible.init(${scriptJson(options)})`
|
|
59
|
+
}];
|
|
60
|
+
}
|
|
61
|
+
const attributes = { "data-domain": c.domain };
|
|
62
|
+
if (endpoint) attributes["data-api"] = endpoint;
|
|
63
|
+
for (const [k, v] of Object.entries(props)) attributes[`event-${k}`] = v;
|
|
64
|
+
return [{
|
|
65
|
+
kind: "external-script",
|
|
66
|
+
placement: "head",
|
|
67
|
+
src: `${base}${legacyFile(c, hasProps)}`,
|
|
68
|
+
defer: true,
|
|
69
|
+
attributes,
|
|
70
|
+
key: "plausible"
|
|
71
|
+
}];
|
|
72
|
+
}
|
|
73
|
+
const escAttr = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
74
|
+
/** The same tag as HTML, for a site whose plugin runs sandboxed (EmDash drops sandboxed page fragments). */
|
|
75
|
+
function fragmentsHtml(list, nonce) {
|
|
76
|
+
const n = nonce ? ` nonce="${escAttr(nonce)}"` : "";
|
|
77
|
+
return list.map((f) => {
|
|
78
|
+
if (f.kind === "inline-script") return `<script${n}>${f.code}<\/script>`;
|
|
79
|
+
const attrs = Object.entries(f.attributes ?? {}).map(([k, v]) => ` ${k}="${escAttr(v)}"`).join("");
|
|
80
|
+
return `<script${f.async ? " async" : ""}${f.defer ? " defer" : ""}${n} src="${escAttr(f.src)}"${attrs}><\/script>`;
|
|
81
|
+
}).join("");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/config.ts
|
|
86
|
+
/**
|
|
87
|
+
* The plugin's settings and the cleaned tag configuration. Plain code with no
|
|
88
|
+
* imports, so the site helper (src/astro.ts) can share it.
|
|
89
|
+
*/
|
|
90
|
+
/** "a, b ,c" → ["a","b","c"] */
|
|
91
|
+
const list = (s) => String(s).split(",").map((x) => x.trim()).filter(Boolean);
|
|
92
|
+
const SETTINGS = {
|
|
93
|
+
domain: "",
|
|
94
|
+
tracking: "script",
|
|
95
|
+
scriptPath: "/js/script.js",
|
|
96
|
+
proxyPath: "/p",
|
|
97
|
+
skipPaths: "/_emdash",
|
|
98
|
+
pageProps: true,
|
|
99
|
+
outbound: true,
|
|
100
|
+
fileDownloads: true,
|
|
101
|
+
apiKey: "",
|
|
102
|
+
cacheMinutes: 15,
|
|
103
|
+
dashboardUrl: ""
|
|
104
|
+
};
|
|
105
|
+
/** A Plausible script file: /js/<name>.js, nothing else. */
|
|
106
|
+
const SCRIPT_PATH = /^\/js\/[A-Za-z0-9._-]{1,120}\.js$/;
|
|
107
|
+
/** A same-site path for the proxy: /seg/seg, letters, numbers, - and _ only. */
|
|
108
|
+
const PROXY_PATH = /^(\/[A-Za-z0-9_-]{1,40}){1,4}$/;
|
|
109
|
+
/** "https://www.Example.com/" → "www.example.com". Plausible's site id is the bare host. */
|
|
110
|
+
function cleanDomain(raw) {
|
|
111
|
+
const s = String(raw ?? "").trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
112
|
+
return /^[a-z0-9.-]{1,253}$/.test(s) && s.includes(".") ? s : "";
|
|
113
|
+
}
|
|
114
|
+
function tagConfig(s) {
|
|
115
|
+
const proxy = String(s.proxyPath).trim().replace(/\/+$/, "");
|
|
116
|
+
return {
|
|
117
|
+
domain: cleanDomain(s.domain),
|
|
118
|
+
scriptPath: SCRIPT_PATH.test(s.scriptPath) ? s.scriptPath : SETTINGS.scriptPath,
|
|
119
|
+
proxyPath: PROXY_PATH.test(proxy) ? proxy : "",
|
|
120
|
+
skip: list(s.skipPaths).filter((p) => p.startsWith("/")),
|
|
121
|
+
pageProps: s.pageProps,
|
|
122
|
+
outbound: s.outbound,
|
|
123
|
+
fileDownloads: s.fileDownloads
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/astro.ts
|
|
129
|
+
/**
|
|
130
|
+
* Site side of Plausible Analytics.
|
|
131
|
+
*
|
|
132
|
+
* The proxy: Plausible's script and event endpoint on your own domain, so
|
|
133
|
+
* ad blockers' lists of third-party hosts don't drop your visitors.
|
|
134
|
+
*
|
|
135
|
+
* // src/pages/p/[...path].ts (the path matches the plugin's "proxyPath" setting, /p by default)
|
|
136
|
+
* import { plausibleProxy } from "@cherwell/emdash-plausible/astro";
|
|
137
|
+
* export const prerender = false;
|
|
138
|
+
* export const { GET, HEAD, POST } = plausibleProxy();
|
|
139
|
+
*
|
|
140
|
+
* It answers two things only: GET <proxy>/js/<file>.js (Plausible's script,
|
|
141
|
+
* cached for six hours) and POST <proxy>/api/event (passed on with the
|
|
142
|
+
* visitor's IP address and user agent, which Plausible needs to count unique
|
|
143
|
+
* visitors; it doesn't store either).
|
|
144
|
+
*
|
|
145
|
+
* The tag: the plugin adds it to every page when it runs in-process
|
|
146
|
+
* (`plugins: [plausible]`). EmDash drops page fragments from sandboxed
|
|
147
|
+
* plugins, so a sandboxed install draws it in the layout with `plausibleTag`.
|
|
148
|
+
*/
|
|
149
|
+
/** Request headers passed on with an event, as Plausible's proxy guide lists them. */
|
|
150
|
+
const PASSED = /^(user-agent|accept|accept-language|origin|referer|pragma|cache-control|sec-ch-ua(-[a-z-]+)?|sec-fetch-[a-z-]+)$/;
|
|
151
|
+
/** An event is a few hundred bytes; anything far larger isn't one. */
|
|
152
|
+
const MAX_EVENT = 8 * 1024;
|
|
153
|
+
const text = (status, body = "") => new Response(body, {
|
|
154
|
+
status,
|
|
155
|
+
headers: {
|
|
156
|
+
"content-type": "text/plain; charset=utf-8",
|
|
157
|
+
"cache-control": "no-store"
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
function clientIp(ctx) {
|
|
161
|
+
try {
|
|
162
|
+
if (ctx.clientAddress) return ctx.clientAddress;
|
|
163
|
+
} catch {}
|
|
164
|
+
return ctx.request.headers.get("cf-connecting-ip") ?? ctx.request.headers.get("x-real-ip");
|
|
165
|
+
}
|
|
166
|
+
function plausibleProxy(opts = {}) {
|
|
167
|
+
const host = (opts.host ?? PLAUSIBLE).replace(/\/+$/, "");
|
|
168
|
+
const maxAge = Math.max(0, Math.floor(opts.scriptMaxAge ?? 21600));
|
|
169
|
+
const go = opts.fetch ?? fetch;
|
|
170
|
+
const script = async (ctx) => {
|
|
171
|
+
const path = `/${ctx.params.path ?? ""}`;
|
|
172
|
+
if (!SCRIPT_PATH.test(path)) return text(404);
|
|
173
|
+
try {
|
|
174
|
+
const res = await go(`${host}${path}`, { headers: { accept: "application/javascript" } });
|
|
175
|
+
if (!res.ok) return text(res.status === 404 ? 404 : 502);
|
|
176
|
+
const body = ctx.request.method === "HEAD" ? null : await res.arrayBuffer();
|
|
177
|
+
return new Response(body, {
|
|
178
|
+
status: 200,
|
|
179
|
+
headers: {
|
|
180
|
+
"content-type": "application/javascript; charset=utf-8",
|
|
181
|
+
"cache-control": `public, max-age=${maxAge}`,
|
|
182
|
+
"x-content-type-options": "nosniff"
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
} catch {
|
|
186
|
+
return text(502);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const event = async (ctx) => {
|
|
190
|
+
if ((ctx.params.path ?? "") !== "api/event") return text(404);
|
|
191
|
+
const body = await ctx.request.text();
|
|
192
|
+
if (!body || body.length > MAX_EVENT) return text(400);
|
|
193
|
+
const headers = { "content-type": ctx.request.headers.get("content-type") ?? "application/json" };
|
|
194
|
+
for (const [name, value] of ctx.request.headers) if (value && PASSED.test(name)) headers[name] = value.slice(0, 1e3);
|
|
195
|
+
const ip = clientIp(ctx);
|
|
196
|
+
if (ip) headers["x-forwarded-for"] = ip;
|
|
197
|
+
try {
|
|
198
|
+
const res = await go(`${host}/api/event`, {
|
|
199
|
+
method: "POST",
|
|
200
|
+
headers,
|
|
201
|
+
body
|
|
202
|
+
});
|
|
203
|
+
const out = text(res.status, await res.text());
|
|
204
|
+
const dropped = res.headers.get("x-plausible-dropped");
|
|
205
|
+
if (dropped) out.headers.set("x-plausible-dropped", dropped);
|
|
206
|
+
return out;
|
|
207
|
+
} catch {
|
|
208
|
+
return text(502);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
GET: script,
|
|
213
|
+
HEAD: script,
|
|
214
|
+
POST: event
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* The same tag the plugin adds, as HTML, for a layout's <head> when the plugin
|
|
219
|
+
* runs sandboxed: `<Fragment set:html={plausibleTag(opts, { path: Astro.url.pathname })} />`.
|
|
220
|
+
*/
|
|
221
|
+
function plausibleTag(opts, page) {
|
|
222
|
+
return fragmentsHtml(fragments(tagConfig({
|
|
223
|
+
...SETTINGS,
|
|
224
|
+
...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== void 0))
|
|
225
|
+
}), page), opts.nonce);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
//#endregion
|
|
229
|
+
export { plausibleProxy, plausibleTag };
|