@kawapress/plugin-analytics 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README-zh-CN.md +61 -0
- package/README.md +60 -2
- package/package.json +48 -3
- package/src/head.ts +38 -0
- package/src/index.ts +57 -0
- package/src/options.ts +160 -0
- package/src/runtime-options.ts +6 -0
- package/src/runtime-plugin.ts +75 -0
- package/src/virtual-modules.d.ts +4 -0
- package/src/vite-plugin.ts +31 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) KawaPress contributors
|
|
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-zh-CN.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# @kawapress/plugin-analytics
|
|
2
|
+
|
|
3
|
+
KawaPress 的网站统计:Google Analytics、Plausible、Umami 与 Cloudflare Web Analytics。
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@kawapress/plugin-analytics) · [English](https://github.com/kawapress/kawapress/blob/main/packages/plugin-analytics/README.md)
|
|
6
|
+
|
|
7
|
+
`@kawapress/plugin-analytics` 是 [KawaPress](https://github.com/kawapress/kawapress) 的一部分。KawaPress 是一个以 Vue 为核心的静态站点生成器。
|
|
8
|
+
|
|
9
|
+
## 特性
|
|
10
|
+
|
|
11
|
+
- 一个插件、一份配置接入四种服务,也可以同时使用多个。
|
|
12
|
+
- 站内页面之间的跳转会被统计为页面浏览,每个页面只计一次。
|
|
13
|
+
- 运行 `kawapress dev` 时默认不上报,需要时再打开。
|
|
14
|
+
- 所有脚本都带 `async` 或 `defer`,不会阻塞渲染。
|
|
15
|
+
- 不使用 Google 的站点,页面包里没有这个插件的任何统计代码。
|
|
16
|
+
|
|
17
|
+
## 安装
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install --save-dev @kawapress/plugin-analytics
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`pnpm add --save-dev @kawapress/plugin-analytics` 和 `yarn add --dev @kawapress/plugin-analytics` 同样可用。
|
|
24
|
+
|
|
25
|
+
## 使用
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import analyticsPlugin from '@kawapress/plugin-analytics'
|
|
29
|
+
import { nagi } from 'kawapress/nagi'
|
|
30
|
+
|
|
31
|
+
export default nagi({
|
|
32
|
+
plugins: [
|
|
33
|
+
analyticsPlugin({
|
|
34
|
+
google: { id: 'G-XXXXXXX' },
|
|
35
|
+
plausible: { domain: 'example.com' },
|
|
36
|
+
}),
|
|
37
|
+
],
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
至少要配置一个服务。选项写错时构建会中止,并指出是哪一项。
|
|
42
|
+
|
|
43
|
+
## 选项
|
|
44
|
+
|
|
45
|
+
| 选项 | 说明 |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `google.id` | GA4 的衡量 ID,以 `G-` 开头。不支持 Universal Analytics(`UA-`)。 |
|
|
48
|
+
| `plausible.domain / src` | 站点域名。`src` 默认 `https://plausible.io/js/script.js`,自托管时改写。 |
|
|
49
|
+
| `umami.websiteId / src` | 两项都必填。Umami 没有统一的脚本地址。 |
|
|
50
|
+
| `cloudflare.token` | Cloudflare Web Analytics 的站点 token。 |
|
|
51
|
+
| `dev` | `kawapress dev` 时也注入脚本。默认 `false`。 |
|
|
52
|
+
|
|
53
|
+
插件不提供 Cookie 同意弹窗。需要合规的站点请自行处理。
|
|
54
|
+
|
|
55
|
+
## 文档
|
|
56
|
+
|
|
57
|
+
[文档](https://kawapress.dev/plugins/analytics) · [反馈问题](https://github.com/kawapress/kawapress/issues)
|
|
58
|
+
|
|
59
|
+
## 许可证
|
|
60
|
+
|
|
61
|
+
[MIT](https://github.com/kawapress/kawapress/blob/main/LICENSE) © KawaPress contributors
|
package/README.md
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kawapress/plugin-analytics
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web analytics for KawaPress: Google Analytics, Plausible, Umami and Cloudflare Web Analytics.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@kawapress/plugin-analytics) · [简体中文](https://github.com/kawapress/kawapress/blob/main/packages/plugin-analytics/README-zh-CN.md)
|
|
6
|
+
|
|
7
|
+
`@kawapress/plugin-analytics` is part of [KawaPress](https://github.com/kawapress/kawapress), a Vue-first static site generator.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- One plugin and one config for four services. Several can run at the same time.
|
|
12
|
+
- Navigating between pages inside the site is counted as a page view, once per page.
|
|
13
|
+
- Nothing is reported while you run `kawapress dev`, unless you ask for it.
|
|
14
|
+
- Every script loads with `async` or `defer`, so rendering is never blocked.
|
|
15
|
+
- Sites that do not use Google ship no browser code from this plugin that tracks anything.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install --save-dev @kawapress/plugin-analytics
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`pnpm add --save-dev @kawapress/plugin-analytics` and `yarn add --dev @kawapress/plugin-analytics` work too.
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import analyticsPlugin from '@kawapress/plugin-analytics'
|
|
29
|
+
import { nagi } from 'kawapress/nagi'
|
|
30
|
+
|
|
31
|
+
export default nagi({
|
|
32
|
+
plugins: [
|
|
33
|
+
analyticsPlugin({
|
|
34
|
+
google: { id: 'G-XXXXXXX' },
|
|
35
|
+
plausible: { domain: 'example.com' },
|
|
36
|
+
}),
|
|
37
|
+
],
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
At least one service is required. A wrong option stops the build and names the option.
|
|
42
|
+
|
|
43
|
+
## Options
|
|
44
|
+
|
|
45
|
+
| Option | Description |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `google.id` | GA4 measurement ID, starts with `G-`. Universal Analytics (`UA-`) is not supported. |
|
|
48
|
+
| `plausible.domain / src` | Site domain. `src` defaults to `https://plausible.io/js/script.js`; change it for self-hosting. |
|
|
49
|
+
| `umami.websiteId / src` | Both required. Umami has no shared script address. |
|
|
50
|
+
| `cloudflare.token` | Site token of Cloudflare Web Analytics. |
|
|
51
|
+
| `dev` | Also inject the scripts during `kawapress dev`. Default `false`. |
|
|
52
|
+
|
|
53
|
+
This plugin shows no cookie consent banner. If your site needs one, add it yourself.
|
|
54
|
+
|
|
55
|
+
## Documentation
|
|
56
|
+
|
|
57
|
+
[Documentation](https://kawapress.dev/en/plugins/analytics) · [Report a problem](https://github.com/kawapress/kawapress/issues)
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
[MIT](https://github.com/kawapress/kawapress/blob/main/LICENSE) © KawaPress contributors
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kawapress/plugin-analytics",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "Web analytics for KawaPress: Google Analytics, Plausible, Umami and Cloudflare Web Analytics, with in-site navigation counted",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://kawapress.dev/",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/kawapress/kawapress.git",
|
|
11
|
+
"directory": "packages/plugin-analytics"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/kawapress/kawapress/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"kawapress",
|
|
18
|
+
"kawapress-plugin"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./src/index.ts",
|
|
23
|
+
"import": "./src/index.ts",
|
|
24
|
+
"default": "./src/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"./runtime-plugin": {
|
|
27
|
+
"types": "./src/runtime-plugin.ts",
|
|
28
|
+
"import": "./src/runtime-plugin.ts",
|
|
29
|
+
"default": "./src/runtime-plugin.ts"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"README-zh-CN.md",
|
|
35
|
+
"src/**/!(*.test.*)"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22.12.0"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public",
|
|
42
|
+
"registry": "https://registry.npmjs.org/"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"kawapress": ">=0.8.3 <0.10.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"vite": "^8.2.2",
|
|
49
|
+
"kawapress": "0.8.3"
|
|
50
|
+
}
|
|
6
51
|
}
|
package/src/head.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { HeadConfig } from 'kawapress'
|
|
2
|
+
import type { ResolvedAnalyticsOptions } from './options'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `<head>` tags of every configured service. All scripts are `async` or
|
|
6
|
+
* `defer`, so none of them blocks rendering.
|
|
7
|
+
*/
|
|
8
|
+
export function createAnalyticsHead(options: ResolvedAnalyticsOptions): HeadConfig[] {
|
|
9
|
+
const head: HeadConfig[] = []
|
|
10
|
+
|
|
11
|
+
if (options.google) {
|
|
12
|
+
const { id } = options.google
|
|
13
|
+
head.push(
|
|
14
|
+
['script', { async: true, src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}` }],
|
|
15
|
+
// `send_page_view: false`: the runtime plugin sends every page_view, the
|
|
16
|
+
// first page included, so a visit is never counted twice.
|
|
17
|
+
['script', {}, `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());gtag('config',${JSON.stringify(id)},{send_page_view:false})`],
|
|
18
|
+
)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (options.plausible) {
|
|
22
|
+
head.push(['script', { 'defer': true, 'data-domain': options.plausible.domain, 'src': options.plausible.src }])
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (options.umami) {
|
|
26
|
+
head.push(['script', { 'defer': true, 'src': options.umami.src, 'data-website-id': options.umami.websiteId }])
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (options.cloudflare) {
|
|
30
|
+
head.push(['script', {
|
|
31
|
+
'defer': true,
|
|
32
|
+
'src': 'https://static.cloudflareinsights.com/beacon.min.js',
|
|
33
|
+
'data-cf-beacon': JSON.stringify({ token: options.cloudflare.token, spa: true }),
|
|
34
|
+
}])
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return head
|
|
38
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { KawaPressPlugin } from 'kawapress'
|
|
2
|
+
import type { AnalyticsPluginOptions } from './options'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { definePlugin } from 'kawapress'
|
|
5
|
+
import { createAnalyticsHead } from './head'
|
|
6
|
+
import { resolveAnalyticsOptions } from './options'
|
|
7
|
+
import { analyticsOptionsPlugin } from './vite-plugin'
|
|
8
|
+
|
|
9
|
+
export const ANALYTICS_PLUGIN_NAME = '@kawapress/plugin-analytics'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Whether this process was started by `kawapress build`.
|
|
13
|
+
*
|
|
14
|
+
* The public plugin API does not tell `config()` which command is running
|
|
15
|
+
* (Vite's `command` only exists after the site head is frozen), so the CLI
|
|
16
|
+
* arguments decide. A program that calls the build in-process gets no scripts,
|
|
17
|
+
* which is the safe side for analytics.
|
|
18
|
+
*/
|
|
19
|
+
export function isBuildCommand(argv: readonly string[] = process.argv): boolean {
|
|
20
|
+
return argv.slice(2).includes('build')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Adds web analytics scripts to the site `<head>` and, for Google, reports a
|
|
25
|
+
* page view for every in-site navigation.
|
|
26
|
+
*/
|
|
27
|
+
export function analyticsPlugin(options: AnalyticsPluginOptions): KawaPressPlugin {
|
|
28
|
+
const resolved = resolveAnalyticsOptions(options)
|
|
29
|
+
|
|
30
|
+
return definePlugin({
|
|
31
|
+
name: ANALYTICS_PLUGIN_NAME,
|
|
32
|
+
setup(api) {
|
|
33
|
+
api.config((config) => {
|
|
34
|
+
if (!resolved.dev && !isBuildCommand()) {
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
config.head = [...(config.head ?? []), ...createAnalyticsHead(resolved)]
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
api.vite((config) => {
|
|
41
|
+
config.plugins ??= []
|
|
42
|
+
config.plugins.push(analyticsOptionsPlugin({ google: resolved.google !== undefined }))
|
|
43
|
+
})
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export default analyticsPlugin
|
|
49
|
+
|
|
50
|
+
export type {
|
|
51
|
+
AnalyticsPluginOptions,
|
|
52
|
+
CloudflareAnalyticsOptions,
|
|
53
|
+
GoogleAnalyticsOptions,
|
|
54
|
+
PlausibleOptions,
|
|
55
|
+
ResolvedAnalyticsOptions,
|
|
56
|
+
UmamiOptions,
|
|
57
|
+
} from './options'
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
export interface GoogleAnalyticsOptions {
|
|
2
|
+
/** Measurement ID of a GA4 property, for example `G-XXXXXXX`. */
|
|
3
|
+
id: string
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface PlausibleOptions {
|
|
7
|
+
/** Domain registered in Plausible, without protocol or path. */
|
|
8
|
+
domain: string
|
|
9
|
+
/** Script URL. Change it when you self-host Plausible. */
|
|
10
|
+
src?: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface UmamiOptions {
|
|
14
|
+
/** Website ID shown in the Umami dashboard. */
|
|
15
|
+
websiteId: string
|
|
16
|
+
/** Script URL. Umami has no shared official address, so it is required. */
|
|
17
|
+
src: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CloudflareAnalyticsOptions {
|
|
21
|
+
/** Site token of Cloudflare Web Analytics. */
|
|
22
|
+
token: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface AnalyticsPluginOptions {
|
|
26
|
+
google?: GoogleAnalyticsOptions
|
|
27
|
+
plausible?: PlausibleOptions
|
|
28
|
+
umami?: UmamiOptions
|
|
29
|
+
cloudflare?: CloudflareAnalyticsOptions
|
|
30
|
+
/** Inject the scripts during `kawapress dev` too. Defaults to `false`. */
|
|
31
|
+
dev?: boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ResolvedAnalyticsOptions {
|
|
35
|
+
google?: GoogleAnalyticsOptions
|
|
36
|
+
plausible?: Required<PlausibleOptions>
|
|
37
|
+
umami?: UmamiOptions
|
|
38
|
+
cloudflare?: CloudflareAnalyticsOptions
|
|
39
|
+
dev: boolean
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const PLAUSIBLE_DEFAULT_SRC = 'https://plausible.io/js/script.js'
|
|
43
|
+
|
|
44
|
+
const SERVICES = ['google', 'plausible', 'umami', 'cloudflare'] as const
|
|
45
|
+
const GOOGLE_ID_PATTERN = /^G-[A-Z0-9]+$/i
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Validates the options at config time. Every error names the option that is
|
|
49
|
+
* wrong, so a typo is fixed without reading the plugin source.
|
|
50
|
+
*/
|
|
51
|
+
export function resolveAnalyticsOptions(
|
|
52
|
+
options: AnalyticsPluginOptions | undefined,
|
|
53
|
+
): ResolvedAnalyticsOptions {
|
|
54
|
+
if (!options || typeof options !== 'object') {
|
|
55
|
+
throw new Error(
|
|
56
|
+
'KawaPress Analytics: analyticsPlugin() needs at least one service, '
|
|
57
|
+
+ 'for example analyticsPlugin({ plausible: { domain: "example.com" } }).',
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const resolved: ResolvedAnalyticsOptions = {
|
|
62
|
+
dev: resolveBoolean(options.dev, 'dev'),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (options.google !== undefined) {
|
|
66
|
+
const section = requireSection(options.google, 'google')
|
|
67
|
+
const id = requireText(section.id, 'google.id', 'For example "G-XXXXXXX".')
|
|
68
|
+
if (/^UA-/i.test(id)) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
'KawaPress Analytics: "google.id" looks like a Universal Analytics ID '
|
|
71
|
+
+ `(${JSON.stringify(id)}), which Google no longer processes. Use the GA4 measurement ID that starts with "G-".`,
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
if (!GOOGLE_ID_PATTERN.test(id)) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
`KawaPress Analytics: "google.id" must be a GA4 measurement ID such as "G-XXXXXXX", got ${JSON.stringify(id)}.`,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
resolved.google = { id }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (options.plausible !== undefined) {
|
|
83
|
+
const section = requireSection(options.plausible, 'plausible')
|
|
84
|
+
const domain = requireText(section.domain, 'plausible.domain', 'For example "example.com".')
|
|
85
|
+
if (/[/\s]/.test(domain)) {
|
|
86
|
+
throw new Error(
|
|
87
|
+
`KawaPress Analytics: "plausible.domain" must be a bare domain like "example.com", got ${JSON.stringify(domain)}.`,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
resolved.plausible = {
|
|
91
|
+
domain,
|
|
92
|
+
src: section.src === undefined
|
|
93
|
+
? PLAUSIBLE_DEFAULT_SRC
|
|
94
|
+
: requireUrl(section.src, 'plausible.src'),
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (options.umami !== undefined) {
|
|
99
|
+
const section = requireSection(options.umami, 'umami')
|
|
100
|
+
resolved.umami = {
|
|
101
|
+
websiteId: requireText(section.websiteId, 'umami.websiteId', 'Copy it from the Umami dashboard.'),
|
|
102
|
+
src: requireUrl(section.src, 'umami.src'),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (options.cloudflare !== undefined) {
|
|
107
|
+
const section = requireSection(options.cloudflare, 'cloudflare')
|
|
108
|
+
resolved.cloudflare = {
|
|
109
|
+
token: requireText(section.token, 'cloudflare.token', 'Copy the site token from Cloudflare Web Analytics.'),
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!SERVICES.some(service => resolved[service] !== undefined)) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
'KawaPress Analytics: configure at least one of '
|
|
116
|
+
+ `${SERVICES.map(service => `"${service}"`).join(', ')}.`,
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return resolved
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function requireSection<T extends object>(value: T, name: string): T {
|
|
124
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
125
|
+
throw new Error(`KawaPress Analytics: "${name}" must be an object, got ${JSON.stringify(value)}.`)
|
|
126
|
+
}
|
|
127
|
+
return value
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function requireText(value: unknown, name: string, hint: string): string {
|
|
131
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
132
|
+
throw new Error(`KawaPress Analytics: "${name}" is required and must be a non-empty string. ${hint}`)
|
|
133
|
+
}
|
|
134
|
+
return value.trim()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function requireUrl(value: unknown, name: string): string {
|
|
138
|
+
const text = requireText(value, name, 'Use the full script URL, starting with https://.')
|
|
139
|
+
let url: URL
|
|
140
|
+
try {
|
|
141
|
+
url = new URL(text)
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
throw new Error(`KawaPress Analytics: "${name}" must be an absolute URL, got ${JSON.stringify(text)}.`)
|
|
145
|
+
}
|
|
146
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
147
|
+
throw new Error(`KawaPress Analytics: "${name}" must start with https://, got ${JSON.stringify(text)}.`)
|
|
148
|
+
}
|
|
149
|
+
return text
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function resolveBoolean(value: unknown, name: string): boolean {
|
|
153
|
+
if (value === undefined) {
|
|
154
|
+
return false
|
|
155
|
+
}
|
|
156
|
+
if (typeof value !== 'boolean') {
|
|
157
|
+
throw new TypeError(`KawaPress Analytics: "${name}" must be true or false, got ${JSON.stringify(value)}.`)
|
|
158
|
+
}
|
|
159
|
+
return value
|
|
160
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { defineRuntimePlugin } from 'kawapress'
|
|
2
|
+
import options from './runtime-options'
|
|
3
|
+
|
|
4
|
+
interface GtagWindow {
|
|
5
|
+
gtag?: (command: 'event', name: string, params: Record<string, string>) => void
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export default defineRuntimePlugin({
|
|
9
|
+
name: '@kawapress/plugin-analytics',
|
|
10
|
+
setup(api) {
|
|
11
|
+
// Only Google needs a route hook: Plausible and Umami watch the History
|
|
12
|
+
// API themselves and Cloudflare is told `spa: true`.
|
|
13
|
+
if (!options.google) {
|
|
14
|
+
return
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
api.router((router) => {
|
|
18
|
+
// Per app. The router also runs the hook for a query or hash change and
|
|
19
|
+
// for the second `enter()` that adopts the requested URL; the path is
|
|
20
|
+
// what makes a page view.
|
|
21
|
+
let lastPath: string | undefined
|
|
22
|
+
let first = true
|
|
23
|
+
|
|
24
|
+
router.afterEach((to) => {
|
|
25
|
+
if (typeof window === 'undefined' || to.path === lastPath) {
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
lastPath = to.path
|
|
29
|
+
// Without the gtag snippet (`kawapress dev` unless `dev: true`) there is
|
|
30
|
+
// nothing to report to.
|
|
31
|
+
const gtag = (window as GtagWindow).gtag
|
|
32
|
+
if (typeof gtag !== 'function') {
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
const pageLocation = window.location.href
|
|
36
|
+
const send = (): void => {
|
|
37
|
+
gtag('event', 'page_view', {
|
|
38
|
+
page_location: pageLocation,
|
|
39
|
+
page_title: document.title,
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
if (first) {
|
|
43
|
+
// The document title is already the title of this page.
|
|
44
|
+
first = false
|
|
45
|
+
setTimeout(send, 0)
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
sendWhenTitleChanges(send)
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
})
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
/** The head manager rewrites `document.title` a moment after the route commits. */
|
|
56
|
+
const TITLE_WAIT_MS = 300
|
|
57
|
+
|
|
58
|
+
function sendWhenTitleChanges(send: () => void): void {
|
|
59
|
+
let done = false
|
|
60
|
+
const observer = new MutationObserver(() => finish())
|
|
61
|
+
const timer = setTimeout(finish, TITLE_WAIT_MS)
|
|
62
|
+
|
|
63
|
+
function finish(): void {
|
|
64
|
+
if (done) {
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
done = true
|
|
68
|
+
observer.disconnect()
|
|
69
|
+
clearTimeout(timer)
|
|
70
|
+
// One more tick: the title and the other head tags settle together.
|
|
71
|
+
setTimeout(send, 0)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
observer.observe(document.head, { childList: true, subtree: true, characterData: true })
|
|
75
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Plugin } from 'vite'
|
|
2
|
+
import { stringifyJson } from 'kawapress'
|
|
3
|
+
|
|
4
|
+
export const ANALYTICS_OPTIONS_MODULE_ID = 'virtual:kawapress-analytics-options'
|
|
5
|
+
|
|
6
|
+
const RESOLVED_MODULE_ID = `\0${ANALYTICS_OPTIONS_MODULE_ID}`
|
|
7
|
+
|
|
8
|
+
/** What the browser needs to know: whether Google page views must be sent. */
|
|
9
|
+
export interface AnalyticsRuntimeOptions {
|
|
10
|
+
google: boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function analyticsOptionsPlugin(options: AnalyticsRuntimeOptions): Plugin {
|
|
14
|
+
return {
|
|
15
|
+
name: 'kawapress:analytics-options',
|
|
16
|
+
resolveId(id) {
|
|
17
|
+
if (id === ANALYTICS_OPTIONS_MODULE_ID) {
|
|
18
|
+
return RESOLVED_MODULE_ID
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
load(id) {
|
|
22
|
+
if (id !== RESOLVED_MODULE_ID) {
|
|
23
|
+
return
|
|
24
|
+
}
|
|
25
|
+
return `export default ${stringifyJson(options, {
|
|
26
|
+
label: 'options of @kawapress/plugin-analytics',
|
|
27
|
+
path: 'analyticsPlugin',
|
|
28
|
+
})}`
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
}
|