-
Notifications
You must be signed in to change notification settings - Fork 224
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add browser-plugin-web-vitals to track Web Vital metrics (close #1189)
- Loading branch information
Showing
13 changed files
with
343 additions
and
1 deletion.
There are no files selected for viewing
10 changes: 10 additions & 0 deletions
10
...ow/browser-plugin-web-vitals/feature-1189-browser-plugin-web-vitals_2023-05-16-09-13.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"changes": [ | ||
{ | ||
"packageName": "@snowplow/browser-plugin-web-vitals", | ||
"comment": "Create browser-plugin-web-vitals", | ||
"type": "none" | ||
} | ||
], | ||
"packageName": "@snowplow/browser-plugin-web-vitals" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush. | ||
{ | ||
"pnpmShrinkwrapHash": "acc89ec01200ab3281ee1b0320ec90dfd66db4fa", | ||
"pnpmShrinkwrapHash": "8ea954c84560fe87e65c19ed77cfe17487a85bb9", | ||
"preferredVersionsHash": "bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
BSD 3-Clause License | ||
|
||
Copyright (c) 2023 Snowplow Analytics Ltd | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are met: | ||
|
||
1. Redistributions of source code must retain the above copyright notice, this | ||
list of conditions and the following disclaimer. | ||
|
||
2. Redistributions in binary form must reproduce the above copyright notice, | ||
this list of conditions and the following disclaimer in the documentation | ||
and/or other materials provided with the distribution. | ||
|
||
3. Neither the name of the copyright holder nor the names of its | ||
contributors may be used to endorse or promote products derived from | ||
this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
{ | ||
"name": "@snowplow/browser-plugin-web-vitals", | ||
"version": "3.9.0", | ||
"description": "", | ||
"homepage": "http://bit.ly/sp-js", | ||
"bugs": "https://github.com/snowplow/snowplow-javascript-tracker/issues", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/snowplow/snowplow-javascript-tracker.git" | ||
}, | ||
"license": "BSD-3-Clause", | ||
"author": "Peter Perlepes", | ||
"sideEffects": false, | ||
"main": "./dist/index.umd.js", | ||
"module": "./dist/index.module.js", | ||
"types": "./dist/index.module.d.ts", | ||
"files": [ | ||
"dist" | ||
], | ||
"scripts": { | ||
"build": "rollup -c --silent --failAfterWarnings", | ||
"test": "jest" | ||
}, | ||
"dependencies": { | ||
"@snowplow/browser-tracker-core": "workspace:*", | ||
"@snowplow/tracker-core": "workspace:*", | ||
"tslib": "^2.3.1" | ||
}, | ||
"devDependencies": { | ||
"@ampproject/rollup-plugin-closure-compiler": "~0.27.0", | ||
"@rollup/plugin-commonjs": "~21.0.2", | ||
"@rollup/plugin-node-resolve": "~13.1.3", | ||
"@types/jest": "~27.4.1", | ||
"@types/jsdom": "~16.2.14", | ||
"@typescript-eslint/eslint-plugin": "~5.15.0", | ||
"@typescript-eslint/parser": "~5.15.0", | ||
"eslint": "~8.11.0", | ||
"jest": "~27.5.1", | ||
"jest-environment-jsdom": "~27.5.1", | ||
"jest-environment-jsdom-global": "~3.0.0", | ||
"jest-standard-reporter": "~2.0.0", | ||
"rollup": "~2.70.1", | ||
"rollup-plugin-cleanup": "~3.2.1", | ||
"rollup-plugin-license": "~2.6.1", | ||
"rollup-plugin-terser": "~7.0.2", | ||
"rollup-plugin-ts": "~2.0.5", | ||
"ts-jest": "~27.1.3", | ||
"typescript": "~4.6.2" | ||
}, | ||
"peerDependencies": { | ||
"@snowplow/browser-tracker": "~3.9.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { nodeResolve } from '@rollup/plugin-node-resolve'; | ||
import commonjs from '@rollup/plugin-commonjs'; | ||
import ts from 'rollup-plugin-ts'; // Preferred over @rollup/plugin-typescript as it bundles .d.ts files | ||
import { banner } from '../../banner'; | ||
import compiler from '@ampproject/rollup-plugin-closure-compiler'; | ||
import { terser } from 'rollup-plugin-terser'; | ||
import cleanup from 'rollup-plugin-cleanup'; | ||
import pkg from './package.json'; | ||
import { builtinModules } from 'module'; | ||
|
||
const umdPlugins = [nodeResolve({ browser: true }), commonjs(), ts()]; | ||
const umdName = 'snowplowWebVitals'; | ||
|
||
export default [ | ||
// CommonJS (for Node) and ES module (for bundlers) build. | ||
{ | ||
input: './src/index.ts', | ||
plugins: [...umdPlugins, banner()], | ||
treeshake: { moduleSideEffects: ['sha1'] }, | ||
output: [{ file: pkg.main, format: 'umd', sourcemap: true, name: umdName }], | ||
}, | ||
{ | ||
input: './src/index.ts', | ||
plugins: [...umdPlugins, compiler(), terser(), cleanup({ comments: 'none' }), banner()], | ||
treeshake: { moduleSideEffects: ['sha1'] }, | ||
output: [{ file: pkg.main.replace('.js', '.min.js'), format: 'umd', sourcemap: true, name: umdName }], | ||
}, | ||
{ | ||
input: './src/index.ts', | ||
external: [...builtinModules, ...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)], | ||
plugins: [ | ||
ts(), // so Rollup can convert TypeScript to JavaScript | ||
banner(), | ||
], | ||
output: [{ file: pkg.module, format: 'es', sourcemap: true }], | ||
}, | ||
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
import { BrowserPlugin, BrowserTracker, addEventListener } from '@snowplow/browser-tracker-core'; | ||
import { ReportCallback } from './types'; | ||
import { WEB_VITALS_SCHEMA } from './schemata'; | ||
import { dispatchToTrackersInCollection } from '@snowplow/browser-tracker-core'; | ||
import { LOG, buildSelfDescribingEvent } from '@snowplow/tracker-core'; | ||
|
||
const _trackers: Record<string, BrowserTracker> = {}; | ||
|
||
declare global { | ||
interface Window { | ||
webVitals: { | ||
onCLS(cb: ReportCallback): void; | ||
onFID(cb: ReportCallback): void; | ||
onLCP(cb: ReportCallback): void; | ||
onINP(cb: ReportCallback): void; | ||
onTTFB(cb: ReportCallback): void; | ||
}; | ||
} | ||
} | ||
|
||
const WEB_VITALS_SOURCE = 'https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js'; | ||
|
||
interface WebVitalsPluginOptions { | ||
loadWebVitalsScript: boolean; | ||
webVitalsSource: string; | ||
} | ||
|
||
const defaultPluginOptions = { | ||
loadWebVitalsScript: true, | ||
webVitalsSource: WEB_VITALS_SOURCE, | ||
}; | ||
|
||
/* Adds the web vitals measurements on the object used by the tracker. */ | ||
function webVitalsListener(webVitalsObject: Record<string, unknown>) { | ||
function addWebVitalsMeasurement(metricSchemaName: string): ReportCallback { | ||
return (arg) => { | ||
webVitalsObject[metricSchemaName] = arg.value; | ||
webVitalsObject.navigationType = arg.navigationType; | ||
}; | ||
} | ||
window.webVitals.onCLS(addWebVitalsMeasurement('cls')); | ||
window.webVitals.onFID(addWebVitalsMeasurement('fid')); | ||
window.webVitals.onLCP(addWebVitalsMeasurement('lcp')); | ||
window.webVitals.onINP(addWebVitalsMeasurement('inp')); | ||
window.webVitals.onTTFB(addWebVitalsMeasurement('ttfb')); | ||
} | ||
|
||
/** | ||
* Adds Web Vitals measurement events | ||
* | ||
* @param loadWebVitalsScript - Should the plugin immediately load the Core Web Vitals measurement script from UNPKG CDN. | ||
* @param webVitalsSource - The URL endpoint the Web Vitals script should be loaded from. | ||
* @remarks | ||
*/ | ||
export function WebVitalsPlugin(options: WebVitalsPluginOptions = defaultPluginOptions): BrowserPlugin { | ||
const webVitalsObject: Record<string, unknown> = {}; | ||
let trackerId: string; | ||
return { | ||
activateBrowserPlugin: (tracker) => { | ||
trackerId = tracker.id; | ||
_trackers[trackerId] = tracker; | ||
|
||
if (options.loadWebVitalsScript) { | ||
const webVitalsScript = document.createElement('script'); | ||
webVitalsScript.setAttribute('src', options.webVitalsSource); | ||
webVitalsScript.setAttribute('async', '1'); | ||
addEventListener( | ||
webVitalsScript, | ||
'error', | ||
() => { | ||
LOG.warn(`Failed to load ${options.webVitalsSource}`); | ||
}, | ||
true | ||
); | ||
|
||
addEventListener(webVitalsScript, 'load', () => webVitalsListener(webVitalsObject), true); | ||
|
||
document.head.appendChild(webVitalsScript); | ||
} | ||
|
||
function sendValues() { | ||
dispatchToTrackersInCollection(Object.keys(_trackers), _trackers, (t) => { | ||
t.core.track( | ||
buildSelfDescribingEvent({ | ||
event: { | ||
schema: WEB_VITALS_SCHEMA, | ||
data: webVitalsObject, | ||
}, | ||
}) | ||
); | ||
}); | ||
} | ||
|
||
// Safari does not fire "visibilitychange" on the tab close | ||
// So we have 2 options: loose Safari data, or loose LCP/CLS that depends on "visibilitychange" logic. | ||
// Current solution: if LCP/CLS supported, use `onHidden` otherwise, use `pagehide` to fire the callback in the end. | ||
// | ||
// More details: https://github.com/treosh/web-vitals-reporter/issues/3 | ||
const supportedEntryTypes = (PerformanceObserver && PerformanceObserver.supportedEntryTypes) || []; | ||
const isLatestVisibilityChangeSupported = supportedEntryTypes.indexOf('layout-shift') !== -1; | ||
|
||
if (isLatestVisibilityChangeSupported) { | ||
const onVisibilityChange = () => { | ||
if (document.visibilityState === 'hidden') { | ||
sendValues(); | ||
removeEventListener('visibilitychange', onVisibilityChange, true); | ||
} | ||
}; | ||
window.addEventListener('visibilitychange', onVisibilityChange, true); | ||
} else { | ||
window.addEventListener('pagehide', sendValues, { capture: true, once: true }); | ||
} | ||
|
||
return; | ||
}, | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export const WEB_VITALS_SCHEMA = 'iglu:com.snowplowanalytics.snowplow/web_vitals/jsonschema/1-0-0'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
export interface ReportCallback { | ||
(metric: Metric): void; | ||
} | ||
|
||
/** | ||
* @interface Metric | ||
* Partial metric interface from https://github.com/GoogleChrome/web-vitals | ||
*/ | ||
interface Metric { | ||
/** | ||
* The name of the metric (in acronym form). | ||
*/ | ||
name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB'; | ||
|
||
value: number; | ||
|
||
/** | ||
* A unique ID representing this particular metric instance. This ID can | ||
* be used by an analytics tool to dedupe multiple values sent for the same | ||
* metric instance, or to group multiple deltas together and calculate a | ||
* total. It can also be used to differentiate multiple different metric | ||
* instances sent from the same page, which can happen if the page is | ||
* restored from the back/forward cache (in that case new metrics object | ||
* get created). | ||
* | ||
*/ | ||
id: string; | ||
navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender' | 'restore'; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"extends": "../../tsconfig.json" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters