analytics/tracker/compile.js
RobertJoonas 37116a2b12
Add tests for the pageleave script (#4744)
* move util function to util module

* move playwright config file to tracker dir root

* update Playwright + add gitignores

* Playwright: enable reuseExistingServer (non-CI env)

* store tracker src copies to avoid re-compilation in dev env

* test pageleave on simple navigation

* fix test util fn

* rename local_test npm script

* make test util able to expect multiple requests

* test pageleaves in SPAs

* test pageleave with manual URL

* test pageleave not sent in manual when pageview not triggered

* extend util fn to refute event requests

* test pageleaves not sent in excluded hash pages

* store hashes instead of file copies to detect /tracker/src changes

* drop async

* speed up test suite
2024-10-28 15:30:03 +00:00

44 lines
1.7 KiB
JavaScript

const uglify = require("uglify-js");
const fs = require('fs')
const path = require('path')
const Handlebars = require("handlebars");
const g = require("generatorics");
const { canSkipCompile } = require("./dev-compile/can-skip-compile");
if (process.env.NODE_ENV === 'dev' && canSkipCompile()) {
console.info('COMPILATION SKIPPED: No changes detected in tracker dependencies')
process.exit(0)
}
Handlebars.registerHelper('any', function (...args) {
return args.slice(0, -1).some(Boolean)
})
Handlebars.registerPartial('customEvents', Handlebars.compile(fs.readFileSync(relPath('src/customEvents.js')).toString()))
function relPath(segment) {
return path.join(__dirname, segment)
}
function compilefile(input, output, templateVars = {}) {
const code = fs.readFileSync(input).toString()
const template = Handlebars.compile(code)
const rendered = template(templateVars)
const result = uglify.minify(rendered)
if (result.code) {
fs.writeFileSync(output, result.code)
} else {
throw new Error(`Failed to compile ${output.split('/').pop()}.\n${result.error}\n`)
}
}
const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue", "pageleave"]
const variants = [...g.clone.powerSet(base_variants)].filter(a => a.length > 0).map(a => a.sort());
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
compilefile(relPath('src/p.js'), relPath('../priv/tracker/js/p.js'))
variants.map(variant => {
const options = variant.map(variant => variant.replace('-', '_')).reduce((acc, curr) => (acc[curr] = true, acc), {})
compilefile(relPath('src/plausible.js'), relPath(`../priv/tracker/js/plausible.${variant.join('.')}.js`), options)
})