Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Proposal: ScriptV2 bundler (#5449)
Karl-Aksel Puulmann426ae49ed11b
diff --git a/tracker/compiler/index.js b/tracker/compiler/index.jsindex beeb9ac0db..5afee27e7d 100644--- a/tracker/compiler/index.js+++ b/tracker/compiler/index.js@@ -1,4 +1,5 @@import { minifySync as swcMinify } from '@swc/core'+import { rollup } from 'rollup'import fs from 'fs'import path from 'path'import { fileURLToPath } from 'url'@@ -33,7 +34,7 @@ export async function compileAll(options = {}) {}const variants = getVariantsToCompile(options)- const baseCode = getCode()+ const bundledCode = await bundleCode()const startTime = Date.now();console.log(`Starting compilation of ${variants.length} variants...`)@@ -44,7 +45,7 @@ export async function compileAll(options = {}) {const workerPool = Pool(() => spawn(new Worker('./worker-thread.js')))variants.forEach(variant => {workerPool.queue(async (worker) => {- await worker.compileFile(variant, { ...options, baseCode })+ await worker.compileFile(variant, { ...options, bundledCode })bar.increment()})})@@ -56,11 +57,11 @@ export async function compileAll(options = {}) {console.log(`Completed compilation of ${variants.length} variants in ${((Date.now() - startTime) / 1000).toFixed(2)}s`);}-export function compileFile(variant, options) {- const baseCode = options.baseCode || getCode()+export async function compileFile(variant, options) {+ const wrappedCode = wrapInstantlyEvaluatingFunction(options.bundledCode || await bundleCode())const globals = { ...DEFAULT_GLOBALS, ...variant.globals }- const code = minify(baseCode, globals)+ const code = minify(wrappedCode, globals)if (options.returnCode) {return code@@ -69,6 +70,10 @@ export function compileFile(variant, options) {}}+function wrapInstantlyEvaluatingFunction(baseCode) {+ return `(function(){${baseCode}})()`+}+export function compileWebSnippet() {const code = fs.readFileSync(relPath('../src/web-snippet.js')).toString()return `@@ -95,9 +100,16 @@ function getVariantsToCompile(options) {return targetVariants}-function getCode() {- // Wrap the code in an instantly evaluating function- return `(function(){${fs.readFileSync(relPath('../src/plausible.js')).toString()}})()`+async function bundleCode() {+ const bundle = await rollup({+ input: 'src/plausible.js',+ })++ const { output } = await bundle.generate({+ format: 'esm',+ })++ return output[0].code}function minify(baseCode, globals) {diff --git a/tracker/package-lock.json b/tracker/package-lock.jsonindex 945738743f..cb39dadfb3 100644--- a/tracker/package-lock.json+++ b/tracker/package-lock.json@@ -10,6 +10,7 @@"chokidar": "^4.0.3","cli-progress": "^3.12.0","generatorics": "^1.1.0",+ "rollup": "^4.41.1","threads": "^1.7.0"},"devDependencies": {@@ -223,6 +224,266 @@"node": ">=18"}},+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.41.1.tgz",+ "integrity": "sha512-NELNvyEWZ6R9QMkiytB4/L4zSEaBC03KIXEghptLGLZWJ6VPrL63ooZQCOnlx36aQPGhzuOMwDerC1Eb2VmrLw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.41.1.tgz",+ "integrity": "sha512-DXdQe1BJ6TK47ukAoZLehRHhfKnKg9BjnQYUu9gzhI8Mwa1d2fzxA1aw2JixHVl403bwp1+/o/NhhHtxWJBgEA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.41.1.tgz",+ "integrity": "sha512-5afxvwszzdulsU2w8JKWwY8/sJOLPzf0e1bFuvcW5h9zsEg+RQAojdW0ux2zyYAz7R8HvvzKCjLNJhVq965U7w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.41.1.tgz",+ "integrity": "sha512-egpJACny8QOdHNNMZKf8xY0Is6gIMz+tuqXlusxquWu3F833DcMwmGM7WlvCO9sB3OsPjdC4U0wHw5FabzCGZg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.41.1.tgz",+ "integrity": "sha512-DBVMZH5vbjgRk3r0OzgjS38z+atlupJ7xfKIDJdZZL6sM6wjfDNo64aowcLPKIx7LMQi8vybB56uh1Ftck/Atg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.41.1.tgz",+ "integrity": "sha512-3FkydeohozEskBxNWEIbPfOE0aqQgB6ttTkJ159uWOFn42VLyfAiyD9UK5mhu+ItWzft60DycIN1Xdgiy8o/SA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.41.1.tgz",+ "integrity": "sha512-wC53ZNDgt0pqx5xCAgNunkTzFE8GTgdZ9EwYGVcg+jEjJdZGtq9xPjDnFgfFozQI/Xm1mh+D9YlYtl+ueswNEg==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.41.1.tgz",+ "integrity": "sha512-jwKCca1gbZkZLhLRtsrka5N8sFAaxrGz/7wRJ8Wwvq3jug7toO21vWlViihG85ei7uJTpzbXZRcORotE+xyrLA==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.41.1.tgz",+ "integrity": "sha512-g0UBcNknsmmNQ8V2d/zD2P7WWfJKU0F1nu0k5pW4rvdb+BIqMm8ToluW/eeRmxCared5dD76lS04uL4UaNgpNA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.41.1.tgz",+ "integrity": "sha512-XZpeGB5TKEZWzIrj7sXr+BEaSgo/ma/kCgrZgL0oo5qdB1JlTzIYQKel/RmhT6vMAvOdM2teYlAaOGJpJ9lahg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loongarch64-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.41.1.tgz",+ "integrity": "sha512-bkCfDJ4qzWfFRCNt5RVV4DOw6KEgFTUZi2r2RuYhGWC8WhCA8lCAJhDeAmrM/fdiAH54m0mA0Vk2FGRPyzI+tw==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-powerpc64le-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.41.1.tgz",+ "integrity": "sha512-3mr3Xm+gvMX+/8EKogIZSIEF0WUu0HL9di+YWlJpO8CQBnoLAEL/roTCxuLncEdgcfJcvA4UMOf+2dnjl4Ut1A==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.41.1.tgz",+ "integrity": "sha512-3rwCIh6MQ1LGrvKJitQjZFuQnT2wxfU+ivhNBzmxXTXPllewOF7JR1s2vMX/tWtUYFgphygxjqMl76q4aMotGw==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.41.1.tgz",+ "integrity": "sha512-LdIUOb3gvfmpkgFZuccNa2uYiqtgZAz3PTzjuM5bH3nvuy9ty6RGc/Q0+HDFrHrizJGVpjnTZ1yS5TNNjFlklw==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.41.1.tgz",+ "integrity": "sha512-oIE6M8WC9ma6xYqjvPhzZYk6NbobIURvP/lEbh7FWplcMO6gn7MM2yHKA1eC/GvYwzNKK/1LYgqzdkZ8YFxR8g==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.41.1.tgz",+ "integrity": "sha512-cWBOvayNvA+SyeQMp79BHPK8ws6sHSsYnK5zDcsC3Hsxr1dgTABKjMnMslPq1DvZIp6uO7kIWhiGwaTdR4Og9A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.41.1.tgz",+ "integrity": "sha512-y5CbN44M+pUCdGDlZFzGGBSKCA4A/J2ZH4edTYSSxFg7ce1Xt3GtydbVKWLlzL+INfFIZAEg1ZV6hh9+QQf9YQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.41.1.tgz",+ "integrity": "sha512-lZkCxIrjlJlMt1dLO/FbpZbzt6J/A8p4DnqzSa4PWqPEUUUnzXLeki/iyPLfV0BmHItlYgHUqJe+3KiyydmiNQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.41.1.tgz",+ "integrity": "sha512-+psFT9+pIh2iuGsxFYYa/LhS5MFKmuivRsx9iPJWNSGbh2XVEjk90fmpUEjCnILPEPJnikAU6SFDiEUyOv90Pg==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.41.1.tgz",+ "integrity": "sha512-Wq2zpapRYLfi4aKxf2Xff0tN+7slj2d4R87WEzqw7ZLsVvO5zwYCIuEGSZYiK41+GlwUo1HiR+GdkLEJnCKTCw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },"node_modules/@swc/core": {"version": "1.11.24","resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",@@ -437,10 +698,10 @@}},"node_modules/@types/estree": {- "version": "1.0.6",- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",- "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",- "dev": true+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",+ "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",+ "license": "MIT"},"node_modules/@types/json-schema": {"version": "7.0.15",@@ -1273,7 +1534,6 @@"version": "2.3.2","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz","integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",- "dev": true,"hasInstallScript": true,"license": "MIT","optional": true,@@ -1888,6 +2148,21 @@"node": ">=18"}},+ "node_modules/playwright/node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },"node_modules/prelude-ls": {"version": "1.2.1","resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",@@ -1980,6 +2255,45 @@"node": ">=4"}},+ "node_modules/rollup": {+ "version": "4.41.1",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.41.1.tgz",+ "integrity": "sha512-cPmwD3FnFv8rKMBc1MxWCwVQFxwf1JEmSX3iQXrRVVG15zerAIXRjMFVWnd5Q5QvgKF7Aj+5ykXFhUl+QGnyOw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.7"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.41.1",+ "@rollup/rollup-android-arm64": "4.41.1",+ "@rollup/rollup-darwin-arm64": "4.41.1",+ "@rollup/rollup-darwin-x64": "4.41.1",+ "@rollup/rollup-freebsd-arm64": "4.41.1",+ "@rollup/rollup-freebsd-x64": "4.41.1",+ "@rollup/rollup-linux-arm-gnueabihf": "4.41.1",+ "@rollup/rollup-linux-arm-musleabihf": "4.41.1",+ "@rollup/rollup-linux-arm64-gnu": "4.41.1",+ "@rollup/rollup-linux-arm64-musl": "4.41.1",+ "@rollup/rollup-linux-loongarch64-gnu": "4.41.1",+ "@rollup/rollup-linux-powerpc64le-gnu": "4.41.1",+ "@rollup/rollup-linux-riscv64-gnu": "4.41.1",+ "@rollup/rollup-linux-riscv64-musl": "4.41.1",+ "@rollup/rollup-linux-s390x-gnu": "4.41.1",+ "@rollup/rollup-linux-x64-gnu": "4.41.1",+ "@rollup/rollup-linux-x64-musl": "4.41.1",+ "@rollup/rollup-win32-arm64-msvc": "4.41.1",+ "@rollup/rollup-win32-ia32-msvc": "4.41.1",+ "@rollup/rollup-win32-x64-msvc": "4.41.1",+ "fsevents": "~2.3.2"+ }+ },"node_modules/safe-buffer": {"version": "5.2.1","resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",diff --git a/tracker/package.json b/tracker/package.jsonindex eb4308a3e2..ee3797a1e5 100644--- a/tracker/package.json+++ b/tracker/package.json@@ -1,5 +1,5 @@{- "tracker_script_version": 13,+ "tracker_script_version": 14,"type": "module","scripts": {"deploy": "node compile.js",@@ -13,6 +13,7 @@"chokidar": "^4.0.3","cli-progress": "^3.12.0","generatorics": "^1.1.0",+ "rollup": "^4.41.1","threads": "^1.7.0"},"devDependencies": {diff --git a/tracker/src/autocapture.js b/tracker/src/autocapture.jsnew file mode 100644index 0000000000..12f0883d4b--- /dev/null+++ b/tracker/src/autocapture.js@@ -0,0 +1,49 @@+import { config, location, document } from './config'++export function init(track) {+ var lastPage;++ function page(isSPANavigation) {+ if (!(COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting))) {+ if (isSPANavigation && lastPage === location.pathname) return;+ }++ lastPage = location.pathname+ track('pageview')+ }++ var onSPANavigation = function () { page(true) }++ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {+ window.addEventListener('hashchange', onSPANavigation)+ } else {+ var his = window.history+ if (his.pushState) {+ var originalPushState = his['pushState']+ his.pushState = function () {+ originalPushState.apply(this, arguments)+ onSPANavigation();+ }+ window.addEventListener('popstate', onSPANavigation)+ }+ }++ function handleVisibilityChange() {+ if (!lastPage && document.visibilityState === 'visible') {+ page()+ }+ }++ if (document.visibilityState === 'hidden' || document.visibilityState === 'prerender') {+ document.addEventListener('visibilitychange', handleVisibilityChange);+ } else {+ page()+ }++ window.addEventListener('pageshow', function (event) {+ if (event.persisted) {+ // Page was restored from bfcache - track a pageview+ page();+ }+ })+}diff --git a/tracker/src/config.js b/tracker/src/config.jsnew file mode 100644index 0000000000..e9081a7635--- /dev/null+++ b/tracker/src/config.js@@ -0,0 +1,39 @@+var location = window.location+var document = window.document++if (COMPILE_COMPAT) {+ var scriptEl = document.getElementById('plausible')+} else {+ var scriptEl = document.currentScript+}++var config = {}++function defaultEndpoint() {+ if (COMPILE_COMPAT) {+ var pathArray = scriptEl.src.split('/');+ var protocol = pathArray[0];+ var host = pathArray[2];+ return protocol + '//' + host + '/api/event';+ } else {+ return new URL(scriptEl.src).origin + '/api/event'+ }+}++export function init(overrides) {+ if (COMPILE_CONFIG) {+ // This will be dynamically replaced by a config json object in the script serving endpoint+ config = "<%= @config_js %>"+ Object.assign(config, overrides, {+ // Explicitly set domain before any overrides are applied as `plausible-web` does not support overriding it+ domain: config.domain,+ // autoCapturePageviews defaults to `true`+ autoCapturePageviews: overrides.autoCapturePageviews !== false+ })+ } else {+ config.endpoint = scriptEl.getAttribute('data-api') || defaultEndpoint()+ config.domain = scriptEl.getAttribute('data-domain')+ }+}++export { config, scriptEl, location, document }diff --git a/tracker/src/custom-events.js b/tracker/src/custom-events.jsnew file mode 100644index 0000000000..85290a6ba6--- /dev/null+++ b/tracker/src/custom-events.js@@ -0,0 +1,257 @@+// Code for tracking tagged events, form submissions, file downloads and outbound links+import { config, scriptEl, location, document } from './config'+import { track } from './track'++var MIDDLE_MOUSE_BUTTON = 1+var PARENTS_TO_SEARCH_LIMIT = 3+var defaultFileTypes = ['pdf', 'xlsx', 'docx', 'txt', 'rtf', 'csv', 'exe', 'key', 'pps', 'ppt', 'pptx', '7z', 'pkg', 'rar', 'gz', 'zip', 'avi', 'mov', 'mp4', 'mpeg', 'wmv', 'midi', 'mp3', 'wav', 'wma', 'dmg']+var fileTypesToTrack = defaultFileTypes++function getLinkEl(link) {+ while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {+ link = link.parentNode+ }+ return link+}++function isLink(element) {+ return element && element.tagName && element.tagName.toLowerCase() === 'a'+}++function shouldFollowLink(event, link) {+ // If default has been prevented by an external script, Plausible should not intercept navigation.+ if (event.defaultPrevented) { return false }++ var targetsCurrentWindow = !link.target || link.target.match(/^_(self|parent|top)$/i)+ var isRegularClick = !(event.ctrlKey || event.metaKey || event.shiftKey) && event.type === 'click'+ return targetsCurrentWindow && isRegularClick+}++function handleLinkClickEvent(event) {+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }++ var link = getLinkEl(event.target)+ var hrefWithoutQuery = link && link.href && link.href.split('?')[0]++ if (COMPILE_TAGGED_EVENTS) {+ if (isElementOrParentTagged(link, 0)) {+ // Return to prevent sending multiple events with the same action.+ // Clicks on tagged links are handled by another function.+ return+ }+ }++ if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {+ if (isOutboundLink(link)) {+ return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })+ }+ }++ if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {+ if (isDownloadToTrack(hrefWithoutQuery)) {+ return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })+ }+ }+}++function sendLinkClickEvent(event, link, eventAttrs) {+ var followedLink = false++ function followLink() {+ if (!followedLink) {+ followedLink = true+ window.location = link.href+ }+ }++ if (shouldFollowLink(event, link)) {+ var attrs = { props: eventAttrs.props, callback: followLink }+ if (COMPILE_REVENUE) {+ attrs.revenue = eventAttrs.revenue+ }+ track(eventAttrs.name, attrs)+ setTimeout(followLink, 5000)+ event.preventDefault()+ } else {+ var attrs = { props: eventAttrs.props }+ if (COMPILE_REVENUE) {+ attrs.revenue = eventAttrs.revenue+ }+ track(eventAttrs.name, attrs)+ }+}++function isOutboundLink(link) {+ return link && link.href && link.host && link.host !== location.host+}++function isDownloadToTrack(url) {+ if (!url) { return false }++ var fileType = url.split('.').pop();+ return fileTypesToTrack.some(function (fileTypeToTrack) {+ return fileTypeToTrack === fileType+ })+}++function isTagged(element) {+ var classList = element && element.classList+ if (classList) {+ for (var i = 0; i < classList.length; i++) {+ if (classList.item(i).match(/plausible-event-name(=|--)(.+)/)) { return true }+ }+ }+ return false+}++function isElementOrParentTagged(element, parentsChecked) {+ if (!element || parentsChecked > PARENTS_TO_SEARCH_LIMIT) { return false }+ if (isTagged(element)) { return true }+ return isElementOrParentTagged(element.parentNode, parentsChecked + 1)+}++// Finds event attributes by iterating over the given element's (or its+// parent's) classList. Returns an object with `name` and `props` keys.+function getTaggedEventAttributes(htmlElement) {+ var taggedElement = isTagged(htmlElement) ? htmlElement : htmlElement && htmlElement.parentNode+ var eventAttrs = { name: null, props: {} }+ if (COMPILE_REVENUE) {+ eventAttrs.revenue = {}+ }++ var classList = taggedElement && taggedElement.classList+ if (!classList) { return eventAttrs }++ for (var i = 0; i < classList.length; i++) {+ var className = classList.item(i)++ var matchList = className.match(/plausible-event-(.+)(=|--)(.+)/)+ if (matchList) {+ var key = matchList[1]+ var value = matchList[3].replace(/\+/g, ' ')++ if (key.toLowerCase() == 'name') {+ eventAttrs.name = value+ } else {+ eventAttrs.props[key] = value+ }+ }++ if (COMPILE_REVENUE) {+ var revenueMatchList = className.match(/plausible-revenue-(.+)(=|--)(.+)/)+ if (revenueMatchList) {+ var key = revenueMatchList[1]+ var value = revenueMatchList[3]+ eventAttrs.revenue[key] = value+ }+ }+ }++ return eventAttrs+}++export function init() {+ document.addEventListener('click', handleLinkClickEvent)+ document.addEventListener('auxclick', handleLinkClickEvent)++ if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {+ if (COMPILE_CONFIG) {+ if (Array.isArray(config.fileDownloads)) {+ fileTypesToTrack = config.fileDownloads+ }+ } else {+ var fileTypesAttr = scriptEl.getAttribute('file-types')+ var addFileTypesAttr = scriptEl.getAttribute('add-file-types')++ if (fileTypesAttr) {+ fileTypesToTrack = fileTypesAttr.split(",")+ }+ if (addFileTypesAttr) {+ fileTypesToTrack = addFileTypesAttr.split(",").concat(defaultFileTypes)+ }+ }++ }++ if (COMPILE_CONFIG && config.formSubmissions) {+ function trackFormSubmission(e) {+ if (e.target.hasAttribute('novalidate') || e.target.checkValidity()) {+ track('Form Submission', { props: { path: location.pathname } });+ }+ }++ document.addEventListener('submit', trackFormSubmission, true);+ }++ if (COMPILE_TAGGED_EVENTS) {+ function handleTaggedFormSubmitEvent(event) {+ var form = event.target+ var eventAttrs = getTaggedEventAttributes(form)+ if (!eventAttrs.name) { return }++ event.preventDefault()+ var formSubmitted = false++ function submitForm() {+ if (!formSubmitted) {+ formSubmitted = true+ form.submit()+ }+ }++ setTimeout(submitForm, 5000)++ var attrs = { props: eventAttrs.props, callback: submitForm }+ if (COMPILE_REVENUE) {+ attrs.revenue = eventAttrs.revenue+ }+ track(eventAttrs.name, attrs)+ }++ function isForm(element) {+ return element && element.tagName && element.tagName.toLowerCase() === 'form'+ }++ function handleTaggedElementClickEvent(event) {+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }++ var clicked = event.target++ var clickedLink+ var taggedElement+ // Iterate over parents to find the tagged element. Also search for+ // a link element to call for different tracking behavior if found.+ for (var i = 0; i <= PARENTS_TO_SEARCH_LIMIT; i++) {+ if (!clicked) { break }++ // Clicks inside forms are not tracked. Only form submits are.+ if (isForm(clicked)) { return }+ if (isLink(clicked)) { clickedLink = clicked }+ if (isTagged(clicked)) { taggedElement = clicked }+ clicked = clicked.parentNode+ }++ if (taggedElement) {+ var eventAttrs = getTaggedEventAttributes(taggedElement)++ if (clickedLink) {+ // if the clicked tagged element is a link, we attach the `url` property+ // automatically for user convenience+ eventAttrs.props.url = clickedLink.href+ sendLinkClickEvent(event, clickedLink, eventAttrs)+ } else {+ var attrs = {}+ attrs.props = eventAttrs.props+ if (COMPILE_REVENUE) {+ attrs.revenue = eventAttrs.revenue+ }+ track(eventAttrs.name, attrs)+ }+ }+ }++ document.addEventListener('submit', handleTaggedFormSubmitEvent)+ document.addEventListener('click', handleTaggedElementClickEvent)+ document.addEventListener('auxclick', handleTaggedElementClickEvent)+ }+}diff --git a/tracker/src/engagement.js b/tracker/src/engagement.jsnew file mode 100644index 0000000000..ea30f6ca9b--- /dev/null+++ b/tracker/src/engagement.js@@ -0,0 +1,166 @@+import { config } from './config'+import { sendRequest } from './networking'++/* Engagement tracking variables and functions */++// Multiple pageviews might be sent by the same script when the page+// uses client-side routing (e.g. hash or history-based). This flag+// prevents registering multiple listeners in those cases.+var listeningOnEngagement = false++var currentEngagementIgnored+var currentEngagementURL = location.href+var currentEngagementProps = {}+var currentEngagementMaxScrollDepth = -1++// Timestamp indicating when this particular page last became visible.+// Reset during pageviews, set to 0 when page is closed.+var runningEngagementStart = 0++// When page is hidden, this 'engaged' time is saved to this variable+var currentEngagementTime = 0++export function prePageviewTrack() {+ if (listeningOnEngagement) {+ // If we're listening on engagement already, at least one pageview+ // has been sent by the current script (i.e. it's most likely a SPA).+ // Trigger an engagement marking the "exit from the previous page".+ triggerEngagement()+ currentDocumentHeight = getDocumentHeight()+ maxScrollDepthPx = getCurrentScrollDepthPx()+ }+}++export function postPageviewTrack(payload) {+ currentEngagementIgnored = false+ currentEngagementURL = payload.u+ currentEngagementProps = payload.p+ currentEngagementMaxScrollDepth = -1+ currentEngagementTime = 0+ runningEngagementStart = Date.now()+ registerEngagementListener()+}++export function onPageviewIgnored() {+ currentEngagementIgnored = true+}++function triggerEngagement() {+ var engagementTime = getEngagementTime()++ /*+ We send engagements if there's new relevant engagement information to share:+ - If the user has scrolled more than the previously sent max scroll depth.+ - If the user has been engaged for more than 3 seconds since the last engagement event.++ The first engagement event is always sent due to containing at least the initial scroll depth.++ Also, we don't send engagements if the current pageview is ignored (onIgnoredEvent)+ */+ if (!currentEngagementIgnored && (currentEngagementMaxScrollDepth < maxScrollDepthPx || engagementTime >= 3000)) {+ currentEngagementMaxScrollDepth = maxScrollDepthPx++ var payload = {+ n: 'engagement',+ sd: Math.round((maxScrollDepthPx / currentDocumentHeight) * 100),+ d: config.domain,+ u: currentEngagementURL,+ p: currentEngagementProps,+ e: engagementTime,+ v: COMPILE_TRACKER_SCRIPT_VERSION+ }++ // Reset current engagement time metrics. They will restart upon when page becomes visible or the next SPA pageview+ runningEngagementStart = 0+ currentEngagementTime = 0++ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {+ payload.h = 1+ }++ sendRequest(config.endpoint, payload)+ }+}++function onVisibilityChange() {+ if (document.visibilityState === 'visible' && document.hasFocus() && runningEngagementStart === 0) {+ runningEngagementStart = Date.now()+ } else if (document.visibilityState === 'hidden' || !document.hasFocus()) {+ // Tab went back to background or lost focus. Save the engaged time so far+ currentEngagementTime = getEngagementTime()+ runningEngagementStart = 0++ triggerEngagement()+ }+}++function registerEngagementListener() {+ if (!listeningOnEngagement) {+ // Only register visibilitychange listener only after initial page load and pageview+ document.addEventListener('visibilitychange', onVisibilityChange)+ window.addEventListener('blur', onVisibilityChange)+ window.addEventListener('focus', onVisibilityChange)+ listeningOnEngagement = true+ }+}++function getEngagementTime() {+ if (runningEngagementStart) {+ return currentEngagementTime + (Date.now() - runningEngagementStart)+ } else {+ return currentEngagementTime+ }+}+++var currentDocumentHeight+var maxScrollDepthPx++function getDocumentHeight() {+ var body = document.body || {}+ var el = document.documentElement || {}+ return Math.max(+ body.scrollHeight || 0,+ body.offsetHeight || 0,+ body.clientHeight || 0,+ el.scrollHeight || 0,+ el.offsetHeight || 0,+ el.clientHeight || 0+ )+}++function getCurrentScrollDepthPx() {+ var body = document.body || {}+ var el = document.documentElement || {}+ var viewportHeight = window.innerHeight || el.clientHeight || 0+ var scrollTop = window.scrollY || el.scrollTop || body.scrollTop || 0++ return currentDocumentHeight <= viewportHeight ? currentDocumentHeight : scrollTop + viewportHeight+}++export function init() {+ currentDocumentHeight = getDocumentHeight()+ maxScrollDepthPx = getCurrentScrollDepthPx()++ window.addEventListener('load', function () {+ currentDocumentHeight = getDocumentHeight()++ // Update the document height again after every 200ms during the+ // next 3 seconds. This makes sure dynamically loaded content is+ // also accounted for.+ var count = 0+ var interval = setInterval(function () {+ currentDocumentHeight = getDocumentHeight()+ if (++count === 15) { clearInterval(interval) }+ }, 200)+ })++ document.addEventListener('scroll', function () {+ currentDocumentHeight = getDocumentHeight()+ var currentScrollDepthPx = getCurrentScrollDepthPx()++ if (currentScrollDepthPx > maxScrollDepthPx) {+ maxScrollDepthPx = currentScrollDepthPx+ }+ })+}diff --git a/tracker/src/networking.js b/tracker/src/networking.jsnew file mode 100644index 0000000000..535873f4a1--- /dev/null+++ b/tracker/src/networking.js@@ -0,0 +1,28 @@+export function sendRequest(endpoint, payload, options) {+ if (COMPILE_COMPAT) {+ var request = new XMLHttpRequest();+ request.open('POST', endpoint, true);+ request.setRequestHeader('Content-Type', 'text/plain');++ request.send(JSON.stringify(payload));++ request.onreadystatechange = function () {+ if (request.readyState === 4) {+ options && options.callback && options.callback({ status: request.status })+ }+ }+ } else {+ if (window.fetch) {+ fetch(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'text/plain'+ },+ keepalive: true,+ body: JSON.stringify(payload)+ }).then(function (response) {+ options && options.callback && options.callback({ status: response.status })+ }).catch(function () { })+ }+ }+}diff --git a/tracker/src/plausible.js b/tracker/src/plausible.jsindex ae829d4402..5982c8eaef 100644--- a/tracker/src/plausible.js+++ b/tracker/src/plausible.js@@ -1,307 +1,8 @@-var location = window.location-var document = window.document--if (COMPILE_COMPAT) {- var scriptEl = document.getElementById('plausible');-} else {- var scriptEl = document.currentScript;-}--var config = {}--if (COMPILE_CONFIG) {- config = "<%= @config_js %>"-}--var endpoint-var dataDomain-var autoCapturePageviews = !COMPILE_MANUAL--// Exported public function-function trigger(eventName, options) {- var isPageview = eventName === 'pageview'-- if (isPageview && listeningOnEngagement) {- // If we're listening on engagement already, at least one pageview- // has been sent by the current script (i.e. it's most likely a SPA).- // Trigger an engagement marking the "exit from the previous page".- triggerEngagement()- currentDocumentHeight = getDocumentHeight()- maxScrollDepthPx = getCurrentScrollDepthPx()- }-- if (!(COMPILE_LOCAL && (!COMPILE_CONFIG || config.captureOnLocalhost))) {- if (/^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(location.hostname) || location.protocol === 'file:') {- return onIgnoredEvent(eventName, options, 'localhost')- }- if ((window._phantom || window.__nightmare || window.navigator.webdriver || window.Cypress) && !window.__plausible) {- return onIgnoredEvent(eventName, options)- }- }- try {- if (window.localStorage.plausible_ignore === 'true') {- return onIgnoredEvent(eventName, options, 'localStorage flag')- }- } catch (e) {-- }- if (COMPILE_EXCLUSIONS) {- var dataIncludeAttr = scriptEl && scriptEl.getAttribute('data-include')- var dataExcludeAttr = scriptEl && scriptEl.getAttribute('data-exclude')--- function pathMatches(wildcardPath) {- var actualPath = location.pathname-- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {- actualPath += location.hash- }-- return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'))- }-- if (isPageview) {- var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))- var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)-- if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, 'exclusion rule', options)- }- }-- var payload = {}- payload.n = eventName- payload.v = COMPILE_TRACKER_SCRIPT_VERSION-- if (COMPILE_MANUAL || !autoCapturePageviews) {- var customURL = options && options.u-- payload.u = customURL ? customURL : location.href- } else {- payload.u = location.href- }-- payload.d = dataDomain- payload.r = document.referrer || null- if (options && options.meta) {- payload.m = JSON.stringify(options.meta)- }- if (options && options.props) {- payload.p = options.props- }- if (options && options.interactive === false) {- payload.i = false- }- if (COMPILE_REVENUE) {- if (options && options.revenue) {- payload.$ = options.revenue- }- }-- if (COMPILE_PAGEVIEW_PROPS) {- var propAttributes = scriptEl.getAttributeNames().filter(function (name) {- return name.substring(0, 6) === 'event-'- })-- var props = payload.p || {}-- propAttributes.forEach(function (attribute) {- var propKey = attribute.replace('event-', '')- var propValue = scriptEl.getAttribute(attribute)- props[propKey] = props[propKey] || propValue- })-- payload.p = props- }-- // Track custom properties for pageviews and other events- if (COMPILE_CUSTOM_PROPERTIES && config.customProperties) {- var props = config.customProperties- if (typeof props === 'function') {- props = config.customProperties(eventName)- }-- if (typeof props === 'object') {- payload.p = Object.assign({}, props, payload.p)- }- }-- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {- payload.h = 1- }-- if (isPageview) {- currentEngagementIgnored = false- currentEngagementURL = payload.u- currentEngagementProps = payload.p- currentEngagementMaxScrollDepth = -1- currentEngagementTime = 0- runningEngagementStart = Date.now()- registerEngagementListener()- }-- sendRequest(endpoint, payload, options)-}--function sendRequest(endpoint, payload, options) {- if (COMPILE_COMPAT) {- var request = new XMLHttpRequest();- request.open('POST', endpoint, true);- request.setRequestHeader('Content-Type', 'text/plain');-- request.send(JSON.stringify(payload));-- request.onreadystatechange = function () {- if (request.readyState === 4) {- options && options.callback && options.callback({ status: request.status })- }- }- } else {- if (window.fetch) {- fetch(endpoint, {- method: 'POST',- headers: {- 'Content-Type': 'text/plain'- },- keepalive: true,- body: JSON.stringify(payload)- }).then(function (response) {- options && options.callback && options.callback({ status: response.status })- }).catch(function () { })- }- }-}--/* Engagement tracking variables and functions */--// Multiple pageviews might be sent by the same script when the page-// uses client-side routing (e.g. hash or history-based). This flag-// prevents registering multiple listeners in those cases.-var listeningOnEngagement = false--var currentEngagementIgnored-var currentEngagementURL = location.href-var currentEngagementProps = {}-var currentEngagementMaxScrollDepth = -1--// Timestamp indicating when this particular page last became visible.-// Reset during pageviews, set to 0 when page is closed.-var runningEngagementStart = 0--// When page is hidden, this 'engaged' time is saved to this variable-var currentEngagementTime = 0--function triggerEngagement() {- var engagementTime = getEngagementTime()-- /*- We send engagements if there's new relevant engagement information to share:- - If the user has scrolled more than the previously sent max scroll depth.- - If the user has been engaged for more than 3 seconds since the last engagement event.-- The first engagement event is always sent due to containing at least the initial scroll depth.-- Also, we don't send engagements if the current pageview is ignored (onIgnoredEvent)- */- if (!currentEngagementIgnored && (currentEngagementMaxScrollDepth < maxScrollDepthPx || engagementTime >= 3000)) {- currentEngagementMaxScrollDepth = maxScrollDepthPx-- var payload = {- n: 'engagement',- sd: Math.round((maxScrollDepthPx / currentDocumentHeight) * 100),- d: dataDomain,- u: currentEngagementURL,- p: currentEngagementProps,- e: engagementTime,- v: COMPILE_TRACKER_SCRIPT_VERSION- }-- // Reset current engagement time metrics. They will restart upon when page becomes visible or the next SPA pageview- runningEngagementStart = 0- currentEngagementTime = 0-- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {- payload.h = 1- }-- sendRequest(endpoint, payload)- }-}--function onVisibilityChange() {- if (document.visibilityState === 'visible' && document.hasFocus() && runningEngagementStart === 0) {- runningEngagementStart = Date.now()- } else if (document.visibilityState === 'hidden' || !document.hasFocus()) {- // Tab went back to background or lost focus. Save the engaged time so far- currentEngagementTime = getEngagementTime()- runningEngagementStart = 0-- triggerEngagement()- }-}--function registerEngagementListener() {- if (!listeningOnEngagement) {- // Only register visibilitychange listener only after initial page load and pageview- document.addEventListener('visibilitychange', onVisibilityChange)- window.addEventListener('blur', onVisibilityChange)- window.addEventListener('focus', onVisibilityChange)- listeningOnEngagement = true- }-}--function getEngagementTime() {- if (runningEngagementStart) {- return currentEngagementTime + (Date.now() - runningEngagementStart)- } else {- return currentEngagementTime- }-}---var currentDocumentHeight-var maxScrollDepthPx--function getDocumentHeight() {- var body = document.body || {}- var el = document.documentElement || {}- return Math.max(- body.scrollHeight || 0,- body.offsetHeight || 0,- body.clientHeight || 0,- el.scrollHeight || 0,- el.offsetHeight || 0,- el.clientHeight || 0- )-}--function getCurrentScrollDepthPx() {- var body = document.body || {}- var el = document.documentElement || {}- var viewportHeight = window.innerHeight || el.clientHeight || 0- var scrollTop = window.scrollY || el.scrollTop || body.scrollTop || 0-- return currentDocumentHeight <= viewportHeight ? currentDocumentHeight : scrollTop + viewportHeight-}--function onIgnoredEvent(eventName, options, reason) {- if (reason) console.warn('Ignoring Event: ' + reason);- options && options.callback && options.callback()-- if (eventName === 'pageview') {- currentEngagementIgnored = true- }-}--function defaultEndpoint() {- if (COMPILE_COMPAT) {- var pathArray = scriptEl.src.split('/');- var protocol = pathArray[0];- var host = pathArray[2];- return protocol + '//' + host + '/api/event';- } else {- return new URL(scriptEl.src).origin + '/api/event'- }-}+import { init as initEngagementTracking } from './engagement'+import { init as initConfig, config } from './config'+import { init as initCustomEvents } from './custom-events'+import { init as initAutocapture } from './autocapture'+import { track } from './track'function init(overrides) {if (COMPILE_CONFIG && window.plausible && window.plausible.l) {@@ -309,353 +10,24 @@ function init(overrides) {return}- // Explicitly set dataDomain before any overrides are applied as `plausible-web` does not support overriding it- dataDomain = COMPILE_CONFIG ? config.domain : scriptEl.getAttribute('data-domain')+ initConfig(overrides)+ initEngagementTracking()- if (COMPILE_CONFIG) {- Object.assign(config, overrides)- autoCapturePageviews = config.autoCapturePageviews !== false+ if (!COMPILE_MANUAL || (COMPILE_CONFIG && config.autoCapturePageviews)) {+ initAutocapture(track)}- endpoint = COMPILE_CONFIG ? config.endpoint : (scriptEl.getAttribute('data-api') || defaultEndpoint())-- currentDocumentHeight = getDocumentHeight()- maxScrollDepthPx = getCurrentScrollDepthPx()-- window.addEventListener('load', function () {- currentDocumentHeight = getDocumentHeight()-- // Update the document height again after every 200ms during the- // next 3 seconds. This makes sure dynamically loaded content is- // also accounted for.- var count = 0- var interval = setInterval(function () {- currentDocumentHeight = getDocumentHeight()- if (++count === 15) { clearInterval(interval) }- }, 200)- })-- document.addEventListener('scroll', function () {- currentDocumentHeight = getDocumentHeight()- var currentScrollDepthPx = getCurrentScrollDepthPx()-- if (currentScrollDepthPx > maxScrollDepthPx) {- maxScrollDepthPx = currentScrollDepthPx- }- })-- if (!COMPILE_MANUAL || autoCapturePageviews) {- var lastPage;-- function page(isSPANavigation) {- if (!(COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting))) {- if (isSPANavigation && lastPage === location.pathname) return;- }-- lastPage = location.pathname- trigger('pageview')- }-- var onSPANavigation = function () { page(true) }-- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {- window.addEventListener('hashchange', onSPANavigation)- } else {- var his = window.history- if (his.pushState) {- var originalPushState = his['pushState']- his.pushState = function () {- originalPushState.apply(this, arguments)- onSPANavigation();- }- window.addEventListener('popstate', onSPANavigation)- }- }-- function handleVisibilityChange() {- if (!lastPage && document.visibilityState === 'visible') {- page()- }- }-- if (document.visibilityState === 'hidden' || document.visibilityState === 'prerender') {- document.addEventListener('visibilitychange', handleVisibilityChange);- } else {- page()- }-- window.addEventListener('pageshow', function (event) {- if (event.persisted) {- // Page was restored from bfcache - trigger a pageview- page();- }- })- }-- if (COMPILE_OUTBOUND_LINKS || COMPILE_FILE_DOWNLOADS || COMPILE_TAGGED_EVENTS) {- function getLinkEl(link) {- while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {- link = link.parentNode- }- return link- }-- function isLink(element) {- return element && element.tagName && element.tagName.toLowerCase() === 'a'- }-- function shouldFollowLink(event, link) {- // If default has been prevented by an external script, Plausible should not intercept navigation.- if (event.defaultPrevented) { return false }-- var targetsCurrentWindow = !link.target || link.target.match(/^_(self|parent|top)$/i)- var isRegularClick = !(event.ctrlKey || event.metaKey || event.shiftKey) && event.type === 'click'- return targetsCurrentWindow && isRegularClick- }-- var MIDDLE_MOUSE_BUTTON = 1-- function handleLinkClickEvent(event) {- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }-- var link = getLinkEl(event.target)- var hrefWithoutQuery = link && link.href && link.href.split('?')[0]-- if (COMPILE_TAGGED_EVENTS) {- if (isElementOrParentTagged(link, 0)) {- // Return to prevent sending multiple events with the same action.- // Clicks on tagged links are handled by another function.- return- }- }-- if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {- if (isOutboundLink(link)) {- return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })- }- }-- if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {- if (isDownloadToTrack(hrefWithoutQuery)) {- return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })- }- }- }-- function sendLinkClickEvent(event, link, eventAttrs) {- var followedLink = false-- function followLink() {- if (!followedLink) {- followedLink = true- window.location = link.href- }- }-- if (shouldFollowLink(event, link)) {- var attrs = { props: eventAttrs.props, callback: followLink }- if (COMPILE_REVENUE) {- attrs.revenue = eventAttrs.revenue- }- plausible(eventAttrs.name, attrs)- setTimeout(followLink, 5000)- event.preventDefault()- } else {- var attrs = { props: eventAttrs.props }- if (COMPILE_REVENUE) {- attrs.revenue = eventAttrs.revenue- }- plausible(eventAttrs.name, attrs)- }- }-- document.addEventListener('click', handleLinkClickEvent)- document.addEventListener('auxclick', handleLinkClickEvent)-- if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {- function isOutboundLink(link) {- return link && link.href && link.host && link.host !== location.host- }- }-- if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {- var defaultFileTypes = ['pdf', 'xlsx', 'docx', 'txt', 'rtf', 'csv', 'exe', 'key', 'pps', 'ppt', 'pptx', '7z', 'pkg', 'rar', 'gz', 'zip', 'avi', 'mov', 'mp4', 'mpeg', 'wmv', 'midi', 'mp3', 'wav', 'wma', 'dmg']- var fileTypesToTrack = defaultFileTypes-- if (COMPILE_CONFIG) {- if (Array.isArray(config.fileDownloads)) {- fileTypesToTrack = config.fileDownloads- }- } else {- var fileTypesAttr = scriptEl.getAttribute('file-types')- var addFileTypesAttr = scriptEl.getAttribute('add-file-types')-- if (fileTypesAttr) {- fileTypesToTrack = fileTypesAttr.split(",")- }- if (addFileTypesAttr) {- fileTypesToTrack = addFileTypesAttr.split(",").concat(defaultFileTypes)- }- }-- function isDownloadToTrack(url) {- if (!url) { return false }-- var fileType = url.split('.').pop();- return fileTypesToTrack.some(function (fileTypeToTrack) {- return fileTypeToTrack === fileType- })- }- }-- if (COMPILE_CONFIG && config.formSubmissions) {- function trackFormSubmission(e) {- if (e.target.hasAttribute('novalidate') || e.target.checkValidity()) {- plausible('Form Submission', { props: { path: location.pathname } });- }- }-- document.addEventListener('submit', trackFormSubmission, true);- }-- if (COMPILE_TAGGED_EVENTS) {- // Finds event attributes by iterating over the given element's (or its- // parent's) classList. Returns an object with `name` and `props` keys.- function getTaggedEventAttributes(htmlElement) {- var taggedElement = isTagged(htmlElement) ? htmlElement : htmlElement && htmlElement.parentNode- var eventAttrs = { name: null, props: {} }- if (COMPILE_REVENUE) {- eventAttrs.revenue = {}- }-- var classList = taggedElement && taggedElement.classList- if (!classList) { return eventAttrs }-- for (var i = 0; i < classList.length; i++) {- var className = classList.item(i)-- var matchList = className.match(/plausible-event-(.+)(=|--)(.+)/)- if (matchList) {- var key = matchList[1]- var value = matchList[3].replace(/\+/g, ' ')-- if (key.toLowerCase() == 'name') {- eventAttrs.name = value- } else {- eventAttrs.props[key] = value- }- }-- if (COMPILE_REVENUE) {- var revenueMatchList = className.match(/plausible-revenue-(.+)(=|--)(.+)/)- if (revenueMatchList) {- var key = revenueMatchList[1]- var value = revenueMatchList[3]- eventAttrs.revenue[key] = value- }- }- }-- return eventAttrs- }-- function handleTaggedFormSubmitEvent(event) {- var form = event.target- var eventAttrs = getTaggedEventAttributes(form)- if (!eventAttrs.name) { return }-- event.preventDefault()- var formSubmitted = false-- function submitForm() {- if (!formSubmitted) {- formSubmitted = true- form.submit()- }- }-- setTimeout(submitForm, 5000)-- var attrs = { props: eventAttrs.props, callback: submitForm }- if (COMPILE_REVENUE) {- attrs.revenue = eventAttrs.revenue- }- plausible(eventAttrs.name, attrs)- }-- function isForm(element) {- return element && element.tagName && element.tagName.toLowerCase() === 'form'- }-- var PARENTS_TO_SEARCH_LIMIT = 3-- function handleTaggedElementClickEvent(event) {- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }-- var clicked = event.target-- var clickedLink- var taggedElement- // Iterate over parents to find the tagged element. Also search for- // a link element to call for different tracking behavior if found.- for (var i = 0; i <= PARENTS_TO_SEARCH_LIMIT; i++) {- if (!clicked) { break }-- // Clicks inside forms are not tracked. Only form submits are.- if (isForm(clicked)) { return }- if (isLink(clicked)) { clickedLink = clicked }- if (isTagged(clicked)) { taggedElement = clicked }- clicked = clicked.parentNode- }-- if (taggedElement) {- var eventAttrs = getTaggedEventAttributes(taggedElement)-- if (clickedLink) {- // if the clicked tagged element is a link, we attach the `url` property- // automatically for user convenience- eventAttrs.props.url = clickedLink.href- sendLinkClickEvent(event, clickedLink, eventAttrs)- } else {- var attrs = {}- attrs.props = eventAttrs.props- if (COMPILE_REVENUE) {- attrs.revenue = eventAttrs.revenue- }- plausible(eventAttrs.name, attrs)- }- }- }-- function isTagged(element) {- var classList = element && element.classList- if (classList) {- for (var i = 0; i < classList.length; i++) {- if (classList.item(i).match(/plausible-event-name(=|--)(.+)/)) { return true }- }- }- return false- }-- function isElementOrParentTagged(element, parentsChecked) {- if (!element || parentsChecked > PARENTS_TO_SEARCH_LIMIT) { return false }- if (isTagged(element)) { return true }- return isElementOrParentTagged(element.parentNode, parentsChecked + 1)- }-- document.addEventListener('submit', handleTaggedFormSubmitEvent)- document.addEventListener('click', handleTaggedElementClickEvent)- document.addEventListener('auxclick', handleTaggedElementClickEvent)- }+ if (COMPILE_OUTBOUND_LINKS || COMPILE_FILE_DOWNLOADS || COMPILE_TAGGED_EVENTS || COMPILE_CONFIG) {+ initCustomEvents()}- // Call `trigger` for any events that were queued via plausible('event') before `init` was called+ // Call `track` for any events that were queued via plausible('event') before `init` was calledvar queue = (window.plausible && window.plausible.q) || []for (var i = 0; i < queue.length; i++) {- trigger.apply(this, queue[i])+ track.apply(this, queue[i])}- window.plausible = trigger+ window.plausible = trackwindow.plausible.init = initwindow.plausible.l = true}diff --git a/tracker/src/track.js b/tracker/src/track.jsnew file mode 100644index 0000000000..00919fb353--- /dev/null+++ b/tracker/src/track.js@@ -0,0 +1,125 @@+import { sendRequest } from './networking'+import { prePageviewTrack, postPageviewTrack, onPageviewIgnored } from './engagement'+import { config, scriptEl, location, document } from './config'++export function track(eventName, options) {+ var isPageview = eventName === 'pageview'++ if (isPageview) {+ prePageviewTrack()+ }++ if (!(COMPILE_LOCAL && (!COMPILE_CONFIG || config.captureOnLocalhost))) {+ if (/^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(location.hostname) || location.protocol === 'file:') {+ return onIgnoredEvent(eventName, options, 'localhost')+ }+ if ((window._phantom || window.__nightmare || window.navigator.webdriver || window.Cypress) && !window.__plausible) {+ return onIgnoredEvent(eventName, options)+ }+ }+ try {+ if (window.localStorage.plausible_ignore === 'true') {+ return onIgnoredEvent(eventName, options, 'localStorage flag')+ }+ } catch (e) {++ }+ if (COMPILE_EXCLUSIONS) {+ var dataIncludeAttr = scriptEl && scriptEl.getAttribute('data-include')+ var dataExcludeAttr = scriptEl && scriptEl.getAttribute('data-exclude')++ function pathMatches(wildcardPath) {+ var actualPath = location.pathname++ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {+ actualPath += location.hash+ }++ return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'))+ }++ if (isPageview) {+ var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))+ var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)++ if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, options, 'exclusion rule')+ }+ }++ var payload = {}+ payload.n = eventName+ payload.v = COMPILE_TRACKER_SCRIPT_VERSION++ if (COMPILE_MANUAL) {+ var customURL = options && options.u++ payload.u = customURL ? customURL : location.href+ } else {+ payload.u = location.href+ }++ payload.d = config.domain+ payload.r = document.referrer || null+ if (options && options.meta) {+ payload.m = JSON.stringify(options.meta)+ }+ if (options && options.props) {+ payload.p = options.props+ }+ if (options && options.interactive === false) {+ payload.i = false+ }+ if (COMPILE_REVENUE) {+ if (options && options.revenue) {+ payload.$ = options.revenue+ }+ }++ if (COMPILE_PAGEVIEW_PROPS) {+ var propAttributes = scriptEl.getAttributeNames().filter(function (name) {+ return name.substring(0, 6) === 'event-'+ })++ var props = payload.p || {}++ propAttributes.forEach(function (attribute) {+ var propKey = attribute.replace('event-', '')+ var propValue = scriptEl.getAttribute(attribute)+ props[propKey] = props[propKey] || propValue+ })++ payload.p = props+ }++ // Track custom properties for pageviews and other events+ if (COMPILE_CUSTOM_PROPERTIES && config.customProperties) {+ var props = config.customProperties+ if (typeof props === 'function') {+ props = config.customProperties(eventName)+ }++ if (typeof props === 'object') {+ payload.p = Object.assign({}, props, payload.p)+ }+ }++ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {+ payload.h = 1+ }++ if (isPageview) {+ postPageviewTrack(payload)+ }++ sendRequest(config.endpoint, payload, options)+}+++function onIgnoredEvent(eventName, options, reason) {+ if (reason) console.warn('Ignoring Event: ' + reason);+ options && options.callback && options.callback()++ if (eventName === 'pageview') {+ onPageviewIgnored()+ }+}diff --git a/tracker/test/plausible-web.spec.js b/tracker/test/plausible-web.spec.jsindex a148ce1a4a..368d6185c1 100644--- a/tracker/test/plausible-web.spec.js+++ b/tracker/test/plausible-web.spec.js@@ -191,7 +191,10 @@ test.describe('plausible-web.js', () => {test('autoCapturePageviews=false mode does not track pageviews', async ({ page }) => {await expectPlausibleInAction(page, {action: async () => {- await openPage(page, { autoCapturePageviews: false })+ await openPage(page, {}, { skipPlausibleInit: true })+ await page.evaluate(() => {+ plausible.init({ autoCapturePageviews: false })+ })await hideAndShowCurrentTab(page, { delay: 200 })},expectedRequests: [],@@ -202,7 +205,10 @@ test.describe('plausible-web.js', () => {test('autoCapturePageviews=false mode after manual pageview continues tracking', async ({ page }) => {await expectPlausibleInAction(page, {action: async () => {- await openPage(page, { autoCapturePageviews: false })+ await openPage(page, {}, { skipPlausibleInit: true })+ await page.evaluate(() => {+ plausible.init({ autoCapturePageviews: false })+ })await page.click('#manual-pageview')await hideAndShowCurrentTab(page, { delay: 200 })},diff --git a/tracker/test/support/server.js b/tracker/test/support/server.jsindex 01b0e5ef94..f84a05a0d2 100644--- a/tracker/test/support/server.js+++ b/tracker/test/support/server.js@@ -17,11 +17,11 @@ export const LOCAL_SERVER_ADDR = `http://localhost:${LOCAL_SERVER_PORT}`export function runLocalFileServer() {app.use(express.static(FIXTURES_PATH));- app.get('/tracker/js/:name', (req, res) => {+ app.get('/tracker/js/:name', async (req, res) => {const name = req.params.nameconst variant = VARIANTS.find((variant) => variant.name === name)- let code = compileFile(variant, { returnCode: true })+ let code = await compileFile(variant, { returnCode: true })if (name === 'plausible-web.js') {code = code.replace('"<%= @config_js %>"', req.query.script_config)