This is an automated email from the ASF dual-hosted git repository.
sergehuber pushed a commit to branch 1_x
in repository https://gitbox.apache.org/repos/asf/unomi-tracker.git
The following commit(s) were added to refs/heads/1_x by this push:
new 091aa84 UNOMI-1023, UNOMI-1024: Backport the browser build and page
"attributes" fixes to 1.x (#29)
091aa84 is described below
commit 091aa84bfe59aeddd720926edd9c9adbfaf5eecc
Author: Serge Huber <[email protected]>
AuthorDate: Tue Oct 27 09:08:51 2026 +0100
UNOMI-1023, UNOMI-1024: Backport the browser build and page "attributes"
fixes to 1.x (#29)
* UNOMI-1023, UNOMI-1024: Fix the browser build without Buffer, and stop
sending an empty page "attributes"
Backport for Unomi 2.x and 3.x users.
UNOMI-1023: when Buffer exists, es6-crawler-detect is called exactly as
before; otherwise it gets a Buffer.byteLength (same UTF-8 byte count)
for the duration of the synchronous call only.
UNOMI-1024: an empty "attributes" is left out of the page properties
sent (Unomi 2.4 and later drop such events, UNOMI-790); a non-empty one
is sent as before. digitalData.page is never changed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* UNOMI-1023, UNOMI-1024: Add browser tests against Unomi 2.x and 3.x, and
prepare 1.6.0
yarn test:servers (not part of CI) compares the tracker's requests with
the published 1.5.0, then runs it in Chromium against Unomi 2.3.0, 2.7.0
and 3.0.0 started with Docker Compose. Same harness as on main, without
the Unomi 4 servers and options.
Also: version 1.6.0, and actions/checkout@v5 in CI as on main.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.eslintrc.json | 7 +
.github/workflows/on-code-change.yml | 4 +-
.gitignore | 6 +-
package.json | 4 +-
src/apache-unomi-tracker.js | 83 ++++++++++-
test/servers/README.md | 81 +++++++++++
test/servers/compare-1.5.0.spec.js | 97 +++++++++++++
test/servers/docker-compose.yml | 78 +++++++++++
test/{spec.js => servers/global-setup.js} | 11 +-
test/servers/page/index.html | 121 +++++++++++++++++
.../playwright.compare.config.js} | 15 +-
test/servers/playwright.config.js | 41 ++++++
test/servers/run.js | 98 +++++++++++++
test/servers/serve.js | 49 +++++++
test/servers/tracker.spec.js | 104 ++++++++++++++
test/servers/unomi.js | 151 +++++++++++++++++++++
test/spec.js | 62 +++++++++
yarn.lock | 19 +++
18 files changed, 1013 insertions(+), 18 deletions(-)
diff --git a/.eslintrc.json b/.eslintrc.json
index 6f073a1..be90deb 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -6,6 +6,13 @@
"extends": "eslint:recommended",
"plugins": ["json"],
"overrides": [
+ {
+ "files": ["test/servers/**/*.js"],
+ "excludedFiles": ["test/servers/page/**"],
+ "env": {
+ "node": true
+ }
+ }
],
"parserOptions": {
"ecmaVersion": "latest",
diff --git a/.github/workflows/on-code-change.yml
b/.github/workflows/on-code-change.yml
index aa86768..7833335 100644
--- a/.github/workflows/on-code-change.yml
+++ b/.github/workflows/on-code-change.yml
@@ -8,7 +8,7 @@ jobs:
lint-tests:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v5
- name: Install dependencies
shell: bash
run: yarn install --frozen-lockfile
@@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
needs: lint-tests
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v5
- name: Install dependencies
shell: bash
run: yarn install --frozen-lockfile
diff --git a/.gitignore b/.gitignore
index ee8ecb9..608f0df 100644
--- a/.gitignore
+++ b/.gitignore
@@ -267,4 +267,8 @@ storybook-static/
yalc.lock
.yalc
-*.iml
\ No newline at end of file
+*.iml
+# Tracker server tests (test/servers)
+test/servers/test-results/
+test/servers/.cache/
+playwright-report/
diff --git a/package.json b/package.json
index b1a97fc..6eceb1f 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "apache-unomi-tracker",
"repository": "apache/unomi-tracker",
"author": "unomi <[email protected]>",
- "version": "1.5.0",
+ "version": "1.6.0",
"description": "A web tracker for Apache Unomi",
"main": "dist/apache-unomi-tracker.cjs.js",
"module": "dist/apache-unomi-tracker.esm.js",
@@ -14,6 +14,7 @@
"scripts": {
"build": "rollup -c",
"test": "node test/spec",
+ "test:servers": "node test/servers/run.js",
"pretest": "yarn run build",
"lint": "eslint --ext js,json ."
},
@@ -21,6 +22,7 @@
"@babel/core": "^7.18.13",
"@babel/plugin-transform-runtime": "^7.18.10",
"@babel/preset-env": "^7.18.10",
+ "@playwright/test": "1.64.1",
"@rollup/plugin-babel": "^5.3.1",
"@rollup/plugin-commonjs": "^22.0.2",
"@rollup/plugin-node-resolve": "^13.3.0",
diff --git a/src/apache-unomi-tracker.js b/src/apache-unomi-tracker.js
index dd5c6ee..f64abbf 100644
--- a/src/apache-unomi-tracker.js
+++ b/src/apache-unomi-tracker.js
@@ -62,8 +62,7 @@ export const newTracker = () => {
let noSessionID = !wem.sessionID || wem.sessionID === '';
let crawlerDetected = navigator.userAgent;
if (crawlerDetected) {
- const browserDetector = new Crawler();
- crawlerDetected =
browserDetector.isCrawler(navigator.userAgent);
+ crawlerDetected = wem._isCrawler(navigator.userAgent);
}
if (cookieDisabled || noSessionID || crawlerDetected) {
document.addEventListener('DOMContentLoaded', function () {
@@ -539,7 +538,7 @@ export const newTracker = () => {
* @returns {object} the target page
*/
buildTargetPage: function () {
- return wem.buildTarget(wem.digitalData.page.pageInfo.pageID,
'page', wem.digitalData.page);
+ return wem.buildTarget(wem.digitalData.page.pageInfo.pageID,
'page', wem._pageProperties());
},
/**
@@ -548,7 +547,7 @@ export const newTracker = () => {
* @returns {object} the source page
*/
buildSourcePage: function () {
- return wem.buildSource(wem.digitalData.page.pageInfo.pageID,
'page', wem.digitalData.page);
+ return wem.buildSource(wem.digitalData.page.pageInfo.pageID,
'page', wem._pageProperties());
},
/**
@@ -1440,6 +1439,82 @@ export const newTracker = () => {
*/
_isObject: function (obj) {
return obj && typeof obj === 'object';
+ },
+
+ /**
+ * The page properties sent with events: digitalData.page, without an
empty "attributes".
+ * Unomi rejects page "attributes" with content, and Unomi 2.4 and
later also reject an empty one,
+ * so an empty one would only get the event dropped. A non-empty one
is sent as before, for
+ * deployments that extended the page schema to accept it.
+ * digitalData.page itself is never changed.
+ *
+ * @private
+ * @return {object} the page properties
+ */
+ _pageProperties: function () {
+ var page = wem.digitalData.page;
+ var attributes = page ? page.attributes : undefined;
+ if (!attributes || typeof attributes !== 'object' ||
Object.keys(attributes).length > 0) {
+ return page;
+ }
+ var properties = {};
+ Object.keys(page).forEach(function (key) {
+ if (key !== 'attributes') {
+ properties[key] = page[key];
+ }
+ });
+ return properties;
+ },
+
+ /**
+ * Number of bytes of a string encoded in UTF-8, as Node's
Buffer.byteLength(value, 'utf8')
+ *
+ * @private
+ * @param {string} value the string
+ * @return {number} the number of bytes
+ */
+ _utf8ByteLength: function (value) {
+ var bytes = 0;
+ for (var i = 0; i < value.length; i++) {
+ var code = value.charCodeAt(i);
+ if (code < 0x80) {
+ bytes += 1;
+ } else if (code < 0x800) {
+ bytes += 2;
+ } else if (code >= 0xD800 && code <= 0xDBFF && i + 1 <
value.length && (value.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
+ bytes += 4;
+ i++;
+ } else {
+ // includes unpaired surrogates, which UTF-8 encoders
replace with U+FFFD
+ bytes += 3;
+ }
+ }
+ return bytes;
+ },
+
+ /**
+ * Whether the user agent is a web crawler, using es6-crawler-detect.
+ * The library calls Buffer.byteLength, which browsers do not have.
When Buffer exists (Node, or a
+ * bundler polyfill) the library is called as is. Otherwise it gets a
Buffer.byteLength for the
+ * duration of the call only: the call is synchronous, so no other
code can see it.
+ *
+ * @private
+ * @param {string} userAgent the user agent
+ * @return {boolean} true for a crawler
+ */
+ _isCrawler: function (userAgent) {
+ var detector = new Crawler();
+ /* global Buffer */
+ if (typeof Buffer !== 'undefined') {
+ return detector.isCrawler(userAgent);
+ }
+ var root = typeof window !== 'undefined' ? window : globalThis;
+ root.Buffer = { byteLength: wem._utf8ByteLength };
+ try {
+ return detector.isCrawler(userAgent);
+ } finally {
+ delete root.Buffer;
+ }
}
};
diff --git a/test/servers/README.md b/test/servers/README.md
new file mode 100644
index 0000000..241ea54
--- /dev/null
+++ b/test/servers/README.md
@@ -0,0 +1,81 @@
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one or more
+ ~ contributor license agreements. See the NOTICE file distributed with
+ ~ this work for additional information regarding copyright ownership.
+ ~ The ASF licenses this file to You under the Apache License, Version 2.0
+ ~ (the "License"); you may not use this file except in compliance with
+ ~ the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+Tracker tests against Unomi servers
+===================================
+
+These tests load the tracker in a real browser (Chromium, through Playwright)
and run it against
+the Unomi versions that tracker 1.x supports (2.x and 3.x), started with
Docker Compose. They check
+what unit tests cannot: cookies, requests from other origins and the events
actually stored by the
+server. They also compare the tracker's requests with those of the published
1.5.0.
+
+They are not part of CI. Run them before a release, and whenever you change
how the tracker talks
+to the server.
+
+Requirements
+------------
+- Docker with Compose, and about 4 GB of free memory (one server runs at a
time)
+- Chromium for Playwright, installed once with `npx playwright install
chromium`
+
+Running
+-------
+```shell
+yarn test:servers # the comparison with 1.5.0, then every
server
+yarn test:servers unomi2 unomi3 # only these servers
+yarn test:servers compare-1.5.0 # only the comparison with 1.5.0 (no Docker
needed)
+yarn test:servers --keep unomi3 # leave the server running afterwards
+```
+
+The command builds the tracker and compares its requests with those of the
published 1.5.0. Then,
+for each server, it starts the server, creates the scope `tracker-test`, runs
the tests and removes
+the server with its data. It exits with an error if anything fails.
+
+Servers
+-------
+| Name | Server | Search engine |
+|---|---|---|
+| `unomi2-legacy` | `apache/unomi:2.3.0`, the last version that accepts an
empty page `attributes` | Elasticsearch 7.17 |
+| `unomi2` | `apache/unomi:2.7.0` | Elasticsearch 7.17 |
+| `unomi3` | `apache/unomi:3.0.0` | Elasticsearch 9.1 |
+
+Unomi listens on http://localhost:8181. Override the images with
`UNOMI2_LEGACY_VERSION`,
+`UNOMI2_VERSION` and `UNOMI3_VERSION`, for example `UNOMI2_VERSION=2.6.1 yarn
test:servers unomi2`.
+
+What is tested
+--------------
+Compatibility with existing sites (`compare-1.5.0`): the current tracker and
the published 1.5.0 are
+loaded on the same page with the same configuration, and their requests are
compared (URLs, headers
+and bodies). They must be identical, except that an empty page `attributes` is
no longer sent.
+1.5.0 gets a `Buffer` polyfill, as sites using it always have one.
+
+For each server:
+- The context loads and a click event is stored.
+- The browser build runs without a `Buffer` polyfill.
+- With cookies, the profile is kept across page loads, also from another
origin.
+- A page with empty `attributes` (as the Unomi manual tutorial showed) gets
its events stored.
+ Non-empty `attributes` are sent as before; no default page schema accepts
them, so the server
+ drops the event, as with 1.5.0. Unomi 2.0 to 2.3 accept an empty one; 2.4
and later reject it
+ too (UNOMI-790).
+
+Files
+-----
+- `docker-compose.yml`: the servers, one Compose profile each
+- `run.js`: starts each server and runs the tests (`yarn test:servers`)
+- `unomi.js`: server setup (scope) and event queries
+- `tracker.spec.js`: the tests against each server
+- `compare-1.5.0.spec.js`: the comparison with the published 1.5.0
+- `page/index.html`, `serve.js`: the test page, configured through its query
string
diff --git a/test/servers/compare-1.5.0.spec.js
b/test/servers/compare-1.5.0.spec.js
new file mode 100644
index 0000000..1f49cdc
--- /dev/null
+++ b/test/servers/compare-1.5.0.spec.js
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Compares the requests of the current tracker with those of the published
1.5.0, for the same
+// page and configuration, so that existing sites keep sending the same data.
The test answers
+// the requests itself: no Unomi server is needed. Run through `yarn
test:servers`.
+const { test, expect } = require('@playwright/test');
+
+const UNOMI_URL = 'http://localhost:8181';
+const ORIGIN = 'http://localhost:8000';
+
+async function captureRequests(page, tracker, config) {
+ const requests = [];
+ await page.route(UNOMI_URL + '/**', async route => {
+ const request = route.request();
+ const headers = await request.allHeaders();
+ requests.push({
+ method: request.method(),
+ url: request.url(),
+ contentType: headers['content-type'],
+ accept: headers['accept'],
+ apiKey: headers['x-unomi-api-key'],
+ body: request.postData() ? JSON.parse(request.postData()) :
undefined
+ });
+ await route.fulfill({
+ status: 200,
+ headers: { 'Access-Control-Allow-Origin': ORIGIN,
'Access-Control-Allow-Credentials': 'true', 'Content-Type': 'application/json'
},
+ body: JSON.stringify({ profileId: 'compare-profile', sessionId:
'compare-session' })
+ });
+ });
+ if (tracker) {
+ await page.context().addCookies([{ name: 'tracker', value: tracker,
url: ORIGIN }]);
+ }
+ const params = new URLSearchParams(Object.assign({ unomi: UNOMI_URL,
sessionId: 'compare-session' }, config));
+ await page.goto(ORIGIN + '/?' + params);
+ const context = await page.evaluate(() => window.trackerTest.context);
+ expect(context.loaded).toBe(true);
+ const click = await page.evaluate(() =>
window.trackerTest.sendClick('compared-click'));
+ expect(click.sent).toBe(true);
+ return requests;
+}
+
+// Removes an empty "attributes" from the page items, the only change the
current tracker makes
+function withoutEmptyPageAttributes(value) {
+ if (Array.isArray(value)) {
+ return value.map(withoutEmptyPageAttributes);
+ }
+ if (value && typeof value === 'object') {
+ const copy = {};
+ for (const key of Object.keys(value)) {
+ copy[key] = withoutEmptyPageAttributes(value[key]);
+ }
+ if (copy.itemType === 'page' && copy.properties &&
copy.properties.attributes
+ && typeof copy.properties.attributes === 'object' &&
Object.keys(copy.properties.attributes).length === 0) {
+ delete copy.properties.attributes;
+ }
+ return copy;
+ }
+ return value;
+}
+
+const cases = [
+ { name: 'a page without attributes', config: {}, same: true },
+ { name: 'a page with non-empty attributes', config: { pageAttributes:
'{"color":"blue"}' }, same: true },
+ { name: 'a page with empty attributes', config: { pageAttributes: '{}' },
same: false }
+];
+
+for (const { name, config, same } of cases) {
+ test('sends the same requests as 1.5.0 for ' + name, async ({ browser })
=> {
+ const published = await browser.newPage();
+ const current = await browser.newPage();
+ const before = await captureRequests(published, '1.5.0', config);
+ const after = await captureRequests(current, undefined, config);
+ expect(before.map(request => request.url)).toEqual([UNOMI_URL +
'/context.json', UNOMI_URL + '/eventcollector']);
+ expect(after).toEqual(same ? before :
withoutEmptyPageAttributes(before));
+ if (!same) {
+ // The difference must be real: 1.5.0 sends the empty attributes,
the current tracker does not
+ expect(after).not.toEqual(before);
+ }
+ await published.close();
+ await current.close();
+ });
+}
diff --git a/test/servers/docker-compose.yml b/test/servers/docker-compose.yml
new file mode 100644
index 0000000..b3764c7
--- /dev/null
+++ b/test/servers/docker-compose.yml
@@ -0,0 +1,78 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Unomi servers for the tracker compatibility tests. Run them through
+# `yarn test:servers`, which starts one profile at a time on port 8181.
+# Each profile can also be started by hand, for example:
+# docker compose -f test/servers/docker-compose.yml --profile unomi3 up -d
+
+x-elasticsearch: &elasticsearch
+ environment:
+ - discovery.type=single-node
+ - xpack.security.enabled=false
+ - cluster.name=contextElasticSearch
+ - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
+ healthcheck:
+ test: ["CMD-SHELL", "curl -fs http://localhost:9200/_cluster/health ||
exit 1"]
+ interval: 5s
+ timeout: 5s
+ retries: 60
+
+services:
+ elasticsearch7:
+ <<: *elasticsearch
+ image:
docker.elastic.co/elasticsearch/elasticsearch:${ES7_VERSION:-7.17.28}
+ profiles: ["unomi2-legacy", "unomi2"]
+
+ elasticsearch9-1:
+ <<: *elasticsearch
+ image:
docker.elastic.co/elasticsearch/elasticsearch:${ES9_1_VERSION:-9.1.3}
+ profiles: ["unomi3"]
+
+ # Unomi 2.3 is the last version whose page schema allows an empty
"attributes" (UNOMI-790)
+ unomi2-legacy:
+ image: apache/unomi:${UNOMI2_LEGACY_VERSION:-2.3.0}
+ profiles: ["unomi2-legacy"]
+ environment:
+ - UNOMI_ELASTICSEARCH_ADDRESSES=elasticsearch7:9200
+ ports:
+ - "${UNOMI_PORT:-8181}:8181"
+ depends_on:
+ elasticsearch7:
+ condition: service_healthy
+
+ unomi2:
+ image: apache/unomi:${UNOMI2_VERSION:-2.7.0}
+ profiles: ["unomi2"]
+ environment:
+ - UNOMI_ELASTICSEARCH_ADDRESSES=elasticsearch7:9200
+ ports:
+ - "${UNOMI_PORT:-8181}:8181"
+ depends_on:
+ elasticsearch7:
+ condition: service_healthy
+
+ unomi3:
+ image: apache/unomi:${UNOMI3_VERSION:-3.0.0}
+ profiles: ["unomi3"]
+ environment:
+ - UNOMI_ELASTICSEARCH_ADDRESSES=elasticsearch9-1:9200
+ ports:
+ - "${UNOMI_PORT:-8181}:8181"
+ depends_on:
+ elasticsearch9-1:
+ condition: service_healthy
diff --git a/test/spec.js b/test/servers/global-setup.js
similarity index 72%
copy from test/spec.js
copy to test/servers/global-setup.js
index 7db513e..33df35d 100644
--- a/test/spec.js
+++ b/test/servers/global-setup.js
@@ -15,9 +15,10 @@
* limitations under the License.
*/
-const assert = require('assert');
-const unomi = require('..');
-const tracker = unomi.useTracker();
+// Prepares the Unomi server named by UNOMI_TARGET and passes its credentials
to the tests.
+const { target, setUp } = require('./unomi');
-assert(tracker !== null);
-console.log('Tests passed');
\ No newline at end of file
+module.exports = async () => {
+ const server = await setUp(target(process.env.UNOMI_TARGET));
+ process.env.UNOMI_READ_CREDENTIALS = server.credentials;
+};
diff --git a/test/servers/page/index.html b/test/servers/page/index.html
new file mode 100644
index 0000000..b7e35d8
--- /dev/null
+++ b/test/servers/page/index.html
@@ -0,0 +1,121 @@
+<!DOCTYPE html>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one or more
+ ~ contributor license agreements. See the NOTICE file distributed with
+ ~ this work for additional information regarding copyright ownership.
+ ~ The ASF licenses this file to You under the Apache License, Version 2.0
+ ~ (the "License"); you may not use this file except in compliance with
+ ~ the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Unomi tracker test page</title>
+ <script>
+ // A "tracker=1.5.0" cookie loads the published 1.5.0 tracker instead
of the current build (a cookie,
+ // because the tracker sends the URL parameters). Sites using 1.5.0
always have a Buffer polyfill
+ // (it fails without one), so add one for it only.
+ if (document.cookie.split('; ').indexOf('tracker=1.5.0') !== -1) {
+ window.Buffer = {
+ byteLength: function (value) {
+ return new TextEncoder().encode(value).length;
+ }
+ };
+ document.write('<script src="/tracker-1.5.0.js"><\/script>');
+ } else {
+ document.write('<script src="/tracker.js"><\/script>');
+ }
+ </script>
+</head>
+<body>
+<script>
+ // The test configures the tracker through the query string:
+ // unomi Unomi server root URL (required)
+ // noBufferShim load the tracker without the Buffer shim (optional)
+ // pageAttributes digitalData.page.attributes as JSON, for example {}
(optional)
+ // sessionId session ID to use instead of a new one (optional)
+ (function () {
+ const params = new URLSearchParams(document.location.search);
+ const wemInitConfig = {
+ contextServerUrl: params.get('unomi'),
+ timeoutInMilliseconds: 10000,
+ contextServerCookieName: 'context-profile-id',
+ activateWem: true,
+ trackerSessionIdCookieName: 'tracker-test-session-id',
+ trackerProfileIdCookieName: 'tracker-test-profile-id'
+ };
+ const digitalData = {
+ scope: 'tracker-test',
+ site: { siteInfo: { siteID: 'tracker-test' } },
+ page: {
+ pageInfo: {
+ pageID: 'tracker-test-page',
+ pageName: document.title,
+ pagePath: document.location.pathname,
+ destinationURL: document.location.origin +
document.location.pathname,
+ language: 'en',
+ categories: [],
+ tags: []
+ },
+ consentTypes: []
+ },
+ events: [],
+ wemInitConfig: wemInitConfig
+ };
+
+ if (params.has('pageAttributes')) {
+ digitalData.page.attributes =
JSON.parse(params.get('pageAttributes'));
+ }
+
+ const tracker = window['apache-unomi-tracker'].useTracker();
+ if (params.has('sessionId')) {
+ tracker.setCookie(wemInitConfig.trackerSessionIdCookieName,
params.get('sessionId'), 1);
+ } else if (tracker.getCookie(wemInitConfig.trackerSessionIdCookieName)
== null) {
+ tracker.setCookie(wemInitConfig.trackerSessionIdCookieName,
tracker.generateGuid(), 1);
+ }
+
+ // initTracker replaces the tracker configuration, so register the
callback after it
+ tracker.initTracker(digitalData);
+
+ window.trackerTest = {
+ // Resolves once the context is loaded, or once the tracker falls
back after an error
+ context: new Promise(function (resolve) {
+ tracker._registerCallback(function () {
+ // Load callbacks receive digitalData; the context answer
is in getLoadedContext()
+ const cxs = tracker.getLoadedContext();
+ resolve({
+ loaded: !tracker.fallback,
+ profileId: cxs ? cxs.profileId : undefined,
+ sessionId: cxs ? cxs.sessionId : undefined
+ });
+ }, 'tracker test', 10);
+ }),
+ sendClick: function (targetId) {
+ return new Promise(function (resolve) {
+ if (tracker.fallback) {
+ resolve({ sent: false });
+ return;
+ }
+ const event = tracker.buildEvent('click',
tracker.buildTarget(targetId, 'button'), tracker.buildSourcePage());
+ tracker.collectEvent(event, function (xhr) {
+ resolve({ sent: true, status: xhr.status });
+ }, function (xhr) {
+ resolve({ sent: false, status: xhr.status });
+ });
+ });
+ }
+ };
+
+ tracker.startTracker();
+ })();
+</script>
+</body>
+</html>
diff --git a/test/spec.js b/test/servers/playwright.compare.config.js
similarity index 62%
copy from test/spec.js
copy to test/servers/playwright.compare.config.js
index 7db513e..f29a32f 100644
--- a/test/spec.js
+++ b/test/servers/playwright.compare.config.js
@@ -15,9 +15,14 @@
* limitations under the License.
*/
-const assert = require('assert');
-const unomi = require('..');
-const tracker = unomi.useTracker();
+// Comparison with the published 1.5.0 tracker (compare-1.5.0.spec.js). No
Unomi server needed.
+// Run through `yarn test:servers`, which downloads 1.5.0 first.
+const path = require('path');
+const { defineConfig } = require('@playwright/test');
+const base = require('./playwright.config');
-assert(tracker !== null);
-console.log('Tests passed');
\ No newline at end of file
+module.exports = defineConfig(Object.assign({}, base, {
+ testMatch: 'compare-1.5.0.spec.js',
+ outputDir: path.join(__dirname, 'test-results', 'compare-1.5.0'),
+ globalSetup: undefined
+}));
diff --git a/test/servers/playwright.config.js
b/test/servers/playwright.config.js
new file mode 100644
index 0000000..579b376
--- /dev/null
+++ b/test/servers/playwright.config.js
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Browser tests of the tracker against one running Unomi server. Run them
through
+// `yarn test:servers`, which starts each server and sets UNOMI_TARGET.
+const path = require('path');
+const { defineConfig } = require('@playwright/test');
+
+module.exports = defineConfig({
+ testDir: __dirname,
+ testMatch: 'tracker.spec.js',
+ outputDir: path.join(__dirname, 'test-results'),
+ timeout: 60000,
+ workers: 1,
+ reporter: 'list',
+ globalSetup: require.resolve('./global-setup.js'),
+ use: {
+ browserName: 'chromium',
+ // The tracker treats a "HeadlessChrome" user agent as a crawler and
does not start
+ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36'
+ },
+ webServer: {
+ command: 'node ' + JSON.stringify(path.join(__dirname, 'serve.js')),
+ url: 'http://localhost:8000/',
+ reuseExistingServer: true
+ }
+});
diff --git a/test/servers/run.js b/test/servers/run.js
new file mode 100644
index 0000000..8d41235
--- /dev/null
+++ b/test/servers/run.js
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Runs the browser tests against each Unomi server version, one after the
other.
+//
+// yarn test:servers the comparison with 1.5.0, then all
servers
+// yarn test:servers unomi2 unomi4 only these servers
+// yarn test:servers compare-1.5.0 only the comparison with 1.5.0 (no
Docker needed)
+// yarn test:servers --keep unomi4 leave the server running afterwards
+//
+// Not part of CI: it needs Docker and takes several minutes.
+const { spawnSync } = require('child_process');
+const fs = require('fs');
+const path = require('path');
+const { TARGETS } = require('./unomi');
+
+const root = path.join(__dirname, '..', '..');
+const composeFile = path.join(__dirname, 'docker-compose.yml');
+const args = process.argv.slice(2);
+const keep = args.includes('--keep');
+const COMPARE = 'compare-1.5.0';
+const names = args.filter(arg => !arg.startsWith('--'));
+const selected = names.length > 0 ? names :
[COMPARE].concat(Object.keys(TARGETS));
+
+for (const name of selected) {
+ if (name !== COMPARE && !TARGETS[name]) {
+ console.error('Unknown name "' + name + '", expected one of: ' +
[COMPARE].concat(Object.keys(TARGETS)).join(', '));
+ process.exit(2);
+ }
+}
+
+function run(command, commandArgs, env) {
+ console.log('$ ' + command + ' ' + commandArgs.join(' '));
+ const result = spawnSync(command, commandArgs, { cwd: root, stdio:
'inherit', env: Object.assign({}, process.env, env) });
+ return result.status === 0;
+}
+
+function compose(name, ...commandArgs) {
+ return run('docker', ['compose', '-f', composeFile, '-p', 'unomi-tracker-'
+ name, '--profile', name, ...commandArgs]);
+}
+
+if (!run('yarn', ['build'])) {
+ process.exit(1);
+}
+
+// The published 1.5.0 tracker, for the comparison
+function downloadPublishedTracker() {
+ const directory = path.join(__dirname, '.cache',
'apache-unomi-tracker-1.5.0');
+ if (fs.existsSync(path.join(directory, 'package', 'dist',
'apache-unomi-tracker.umd.js'))) {
+ return true;
+ }
+ fs.mkdirSync(directory, { recursive: true });
+ return run('npm', ['pack', '[email protected]',
'--pack-destination', directory])
+ && run('tar', ['xzf', path.join(directory,
'apache-unomi-tracker-1.5.0.tgz'), '-C', directory]);
+}
+
+const results = [];
+if (selected.includes(COMPARE)) {
+ console.log('\n=== ' + COMPARE);
+ const passed = downloadPublishedTracker()
+ && run('npx', ['playwright', 'test', '-c', path.join(__dirname,
'playwright.compare.config.js')]);
+ results.push({ name: COMPARE, passed });
+}
+
+for (const name of selected.filter(name => name !== COMPARE)) {
+ console.log('\n=== ' + name);
+ let passed = false;
+ try {
+ if (compose(name, 'up', '-d')) {
+ passed = run('npx', ['playwright', 'test', '-c',
path.join(__dirname, 'playwright.config.js')], { UNOMI_TARGET: name });
+ }
+ } finally {
+ if (!keep) {
+ compose(name, 'down', '-v');
+ }
+ }
+ results.push({ name, passed });
+}
+
+console.log('\n=== Results');
+for (const result of results) {
+ console.log((result.passed ? 'PASS ' : 'FAIL ') + result.name);
+}
+process.exit(results.every(result => result.passed) ? 0 : 1);
diff --git a/test/servers/serve.js b/test/servers/serve.js
new file mode 100644
index 0000000..f702eb4
--- /dev/null
+++ b/test/servers/serve.js
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Serves the test page and the built tracker on two origins,
http://localhost:8000 and
+// http://localhost:8001, to test requests from different origins.
+const http = require('http');
+const fs = require('fs');
+const path = require('path');
+
+const PORTS = [8000, 8001];
+const files = {
+ '/': { file: path.join(__dirname, 'page', 'index.html'), type: 'text/html;
charset=utf-8' },
+ '/tracker.js': { file: path.join(__dirname, '..', '..', 'dist',
'apache-unomi-tracker.umd.js'), type: 'text/javascript; charset=utf-8' },
+ // Downloaded by run.js, for the comparison with the published 1.5.0
+ '/tracker-1.5.0.js': { file: path.join(__dirname, '.cache',
'apache-unomi-tracker-1.5.0', 'package', 'dist',
'apache-unomi-tracker.umd.js'), type: 'text/javascript; charset=utf-8' }
+};
+
+function handle(request, response) {
+ const entry = files[new URL(request.url, 'http://localhost').pathname];
+ if (!entry) {
+ response.writeHead(404).end();
+ return;
+ }
+ fs.readFile(entry.file, (error, content) => {
+ if (error) {
+ response.writeHead(500, { 'Content-Type': 'text/plain'
}).end(String(error));
+ return;
+ }
+ response.writeHead(200, { 'Content-Type': entry.type, 'Cache-Control':
'no-store' }).end(content);
+ });
+}
+
+for (const port of PORTS) {
+ http.createServer(handle).listen(port, () => console.log('Test page on
http://localhost:' + port));
+}
diff --git a/test/servers/tracker.spec.js b/test/servers/tracker.spec.js
new file mode 100644
index 0000000..36d3a2c
--- /dev/null
+++ b/test/servers/tracker.spec.js
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const { test, expect } = require('@playwright/test');
+const { UNOMI_URL, target, findClickEvents } = require('./unomi');
+
+const server = target(process.env.UNOMI_TARGET);
+const LISTED_ORIGIN = 'http://localhost:8000';
+const UNLISTED_ORIGIN = 'http://localhost:8001';
+// Tracker 1.x has no Unomi 4 options, so sites use no extra configuration
+const siteConfig = {};
+
+// Opens the test page and waits for the tracker to load the context or fall
back.
+async function openPage(page, origin, config, timeoutMs = 30000) {
+ const requests = [];
+ page.on('request', request => {
+ if (request.url().startsWith(UNOMI_URL) && request.method() !==
'OPTIONS') {
+ requests.push(request);
+ }
+ });
+ const params = new URLSearchParams(Object.assign({ unomi: UNOMI_URL },
config));
+ await page.goto(origin + '/?' + params);
+ const context = await page.evaluate(ms => Promise.race([
+ window.trackerTest.context,
+ new Promise((resolve, reject) => setTimeout(() => reject(new
Error('The tracker neither loaded the context nor fell back')), ms))
+ ]), timeoutMs);
+ return { context, requests };
+}
+
+async function sendClick(page, label) {
+ const targetId = label + '-' + Date.now() + '-' + Math.floor(Math.random()
* 1e6);
+ const result = await page.evaluate(id => window.trackerTest.sendClick(id),
targetId);
+ return Object.assign({ targetId }, result);
+}
+
+async function expectStoredClick(click) {
+ expect(click.sent).toBe(true);
+ const events = await findClickEvents(process.env.UNOMI_READ_CREDENTIALS,
click.targetId);
+ expect(events).toHaveLength(1);
+}
+
+test.describe(server.name, () => {
+ test('the browser build runs without a Buffer polyfill', async ({ page })
=> {
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ const { context } = await openPage(page, LISTED_ORIGIN, siteConfig);
+ expect(errors).toEqual([]);
+ expect(context.loaded).toBe(true);
+ });
+
+ test('collects events from a page with empty "attributes", as the Unomi
manual showed', async ({ page }) => {
+ const { context } = await openPage(page, LISTED_ORIGIN,
Object.assign({ pageAttributes: '{}' }, siteConfig));
+ expect(context.loaded).toBe(true);
+ await expectStoredClick(await sendClick(page,
'empty-page-attributes'));
+ });
+
+ test('sends non-empty page "attributes" as before', async ({ page }) => {
+ // No default page schema accepts attributes with content, so the
server drops the event, as with
+ // 1.5.0 (compare-1.5.0 checks that the request is the same). Unomi
2.0 to 2.3 accept an empty one.
+ await openPage(page, LISTED_ORIGIN, Object.assign({ pageAttributes:
'{"color":"blue"}' }, siteConfig));
+ const click = await sendClick(page, 'page-attributes');
+ expect(click.sent).toBe(true);
+ const events = await
findClickEvents(process.env.UNOMI_READ_CREDENTIALS, click.targetId, 5000);
+ expect(events).toHaveLength(0);
+ });
+
+ test('loads the context and collects an event with the site
configuration', async ({ page }) => {
+ const { context, requests } = await openPage(page, LISTED_ORIGIN,
siteConfig);
+ expect(context.loaded).toBe(true);
+ expect(context.profileId).toBeTruthy();
+ await expectStoredClick(await sendClick(page, 'site-config'));
+ expect(requests.length).toBeGreaterThan(0);
+ });
+
+ test('keeps the profile across page loads with cookies', async ({ page })
=> {
+ const first = await openPage(page, LISTED_ORIGIN, siteConfig);
+ const second = await openPage(page, LISTED_ORIGIN, siteConfig);
+ expect(first.context.loaded).toBe(true);
+ expect(second.context.loaded).toBe(true);
+ expect(first.context.profileId).toBeTruthy();
+ expect(second.context.profileId).toBe(first.context.profileId);
+ });
+
+ test('from another origin, with cookies', async ({ page }) => {
+ // Unomi 2.x and 3.x accept cookies from any origin
+ const { context } = await openPage(page, UNLISTED_ORIGIN, siteConfig);
+ expect(context.loaded).toBe(true);
+ });
+
+});
diff --git a/test/servers/unomi.js b/test/servers/unomi.js
new file mode 100644
index 0000000..bea6a2b
--- /dev/null
+++ b/test/servers/unomi.js
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// What each Unomi server under test is, and how to set it up and query it.
+const UNOMI_URL = process.env.UNOMI_URL || 'http://localhost:8181';
+const SCOPE = 'tracker-test';
+
+// Tracker 1.x supports Unomi 2.x and 3.x, which have no tenants and accept
cookies from any origin.
+// Unomi 2.0 to 2.3 accept an empty page "attributes"; 2.4 removed it from the
page schema (UNOMI-790).
+const TARGETS = {
+ 'unomi2-legacy': { admin: 'karaf:karaf' },
+ 'unomi2': { admin: 'karaf:karaf' },
+ 'unomi3': { admin: 'karaf:karaf' }
+};
+
+function target(name) {
+ const config = TARGETS[name];
+ if (!config) {
+ throw new Error('Unknown target "' + name + '", expected one of: ' +
Object.keys(TARGETS).join(', '));
+ }
+ return Object.assign({ name: name }, config);
+}
+
+function basic(credentials) {
+ return 'Basic ' + Buffer.from(credentials).toString('base64');
+}
+
+async function request(method, path, { credentials, body, headers,
allowNotFound } = {}) {
+ const response = await fetch(UNOMI_URL + path, {
+ method: method,
+ headers: Object.assign(
+ { 'Content-Type': 'application/json' },
+ credentials ? { Authorization: basic(credentials) } : {},
+ headers || {}),
+ body: body === undefined ? undefined : JSON.stringify(body)
+ });
+ const text = await response.text();
+ if (allowNotFound && (response.status === 404 || response.status === 204))
{
+ return undefined;
+ }
+ if (!response.ok) {
+ throw new Error(method + ' ' + path + ' answered ' + response.status +
': ' + text.slice(0, 300));
+ }
+ return text ? JSON.parse(text) : undefined;
+}
+
+async function sleep(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+// Waits until the server answers context.json.
+async function waitForServer(timeoutMs = 300000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ try {
+ const response = await fetch(UNOMI_URL + '/cxs/context.json', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ sessionId: 'tracker-test-probe' })
+ });
+ if (response.status === 200) {
+ return;
+ }
+ } catch (e) {
+ // not listening yet
+ }
+ if (Date.now() > deadline) {
+ throw new Error('Unomi did not start at ' + UNOMI_URL + ' within '
+ timeoutMs / 1000 + 's');
+ }
+ await sleep(3000);
+ }
+}
+
+// Retries a setup call while the server is still starting its services.
+async function retry(action, timeoutMs = 120000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ try {
+ return await action();
+ } catch (e) {
+ if (Date.now() > deadline) {
+ throw e;
+ }
+ await sleep(3000);
+ }
+ }
+}
+
+// Creates the scope if it is missing, and waits until the server returns it.
+async function ensureScope(credentials) {
+ await retry(async () => {
+ let scope = await request('GET', '/cxs/scopes/' + SCOPE, {
credentials: credentials, allowNotFound: true });
+ if (!scope) {
+ await request('POST', '/cxs/scopes', {
+ credentials: credentials,
+ body: { itemId: SCOPE, metadata: { id: SCOPE, name: 'Tracker
test' } }
+ });
+ console.log('Created scope ' + SCOPE);
+ scope = await request('GET', '/cxs/scopes/' + SCOPE, {
credentials: credentials, allowNotFound: true });
+ }
+ if (!scope || scope.itemId !== SCOPE) {
+ throw new Error('Scope ' + SCOPE + ' is not available yet');
+ }
+ });
+}
+
+// Prepares the server before the tests: the scope that the tracker events use.
+// Returns the credentials that can read the events.
+async function setUp(t) {
+ await waitForServer();
+ await ensureScope(t.admin);
+ console.log('Server ready: ' + t.name + ', scope ' + SCOPE);
+ return { credentials: t.admin };
+}
+
+// Polls until click events on the given target are indexed, and returns them.
+async function findClickEvents(credentials, targetId, timeoutMs = 15000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const result = await request('POST', '/cxs/events/search', {
+ credentials: credentials,
+ body: {
+ limit: 10,
+ condition: {
+ type: 'eventPropertyCondition',
+ parameterValues: { propertyName: 'target.itemId',
comparisonOperator: 'equals', propertyValue: targetId }
+ }
+ }
+ });
+ if ((result.list && result.list.length > 0) || Date.now() > deadline) {
+ return result.list || [];
+ }
+ await sleep(1000);
+ }
+}
+
+module.exports = { UNOMI_URL, TARGETS, target, setUp, findClickEvents };
diff --git a/test/spec.js b/test/spec.js
index 7db513e..d28dd4b 100644
--- a/test/spec.js
+++ b/test/spec.js
@@ -20,4 +20,66 @@ const unomi = require('..');
const tracker = unomi.useTracker();
assert(tracker !== null);
+
+globalThis.document = { cookie: 'wem-session-id=test-session' };
+
+// Crawler detection: the same result with and without Node's Buffer
+const crawlerTracker = unomi.useTracker();
+const edgeStrings = ['', 'abc', 'é漢字😀', '\uD800', 'a\uDC00b', '😀\uD800',
'x'.repeat(4096), 'é'.repeat(2048), 'é'.repeat(2049)];
+for (let i = 0; i < 500; i++) {
+ let value = '';
+ for (let j = 0; j < 30; j++) {
+ value += String.fromCharCode(Math.floor(Math.random() * 0x10000));
+ }
+ edgeStrings.push(value);
+}
+for (const value of edgeStrings) {
+ assert.strictEqual(crawlerTracker._utf8ByteLength(value),
globalThis.Buffer.byteLength(value, 'utf8'), 'UTF-8 length of ' +
JSON.stringify(value));
+}
+
+const userAgents = [
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
+ 'curl/8.4.0',
+ 'Googlebot/2.1 ' + 'x'.repeat(5000),
+ 'Googlebot/2.1 ' + 'é'.repeat(2045),
+ 'Googlebot/2.1 ' + 'é'.repeat(2040)
+];
+const withBuffer = userAgents.map(userAgent =>
crawlerTracker._isCrawler(userAgent));
+assert.deepStrictEqual(withBuffer.slice(0, 3), [false, true, true], 'crawlers
are detected');
+const nodeBuffer = globalThis.Buffer;
+delete globalThis.Buffer;
+try {
+ const withoutBuffer = userAgents.map(userAgent =>
crawlerTracker._isCrawler(userAgent));
+ assert.strictEqual(typeof globalThis.Buffer, 'undefined', 'no Buffer is
left behind');
+ assert.deepStrictEqual(withoutBuffer, withBuffer, 'the same result without
Buffer');
+} finally {
+ globalThis.Buffer = nodeBuffer;
+}
+
+// Page properties sent with events: an empty "attributes" is left out,
digitalData.page is unchanged
+function pagePropertiesFor(attributes) {
+ const page = { pageInfo: { pageID: 'home', pageName: 'Home' },
consentTypes: [] };
+ if (attributes !== undefined) {
+ page.attributes = attributes;
+ }
+ const t = unomi.useTracker();
+ t.initTracker({ scope: 'test', site: { siteInfo: { siteID: 'test' } },
page: page, events: [], wemInitConfig: { contextServerUrl: '',
timeoutInMilliseconds: -1 } });
+ return { page, source: t.buildSourcePage().properties, target:
t.buildTargetPage().properties };
+}
+
+let pageResult = pagePropertiesFor(undefined);
+assert.strictEqual(pageResult.source, pageResult.page, 'a page without
attributes is sent as is');
+assert.strictEqual(pageResult.target, pageResult.page, 'a page without
attributes is sent as is');
+
+pageResult = pagePropertiesFor({ color: 'blue' });
+assert.strictEqual(pageResult.source, pageResult.page, 'a page with non-empty
attributes is sent as is');
+assert.strictEqual(pageResult.target, pageResult.page, 'a page with non-empty
attributes is sent as is');
+
+pageResult = pagePropertiesFor({});
+assert.deepStrictEqual(Object.keys(pageResult.source), ['pageInfo',
'consentTypes'], 'empty attributes are left out');
+assert.deepStrictEqual(Object.keys(pageResult.target), ['pageInfo',
'consentTypes'], 'empty attributes are left out');
+assert.strictEqual(pageResult.source.pageInfo, pageResult.page.pageInfo,
'pageInfo is the same object');
+assert.deepStrictEqual(pageResult.page.attributes, {}, 'digitalData.page keeps
its attributes');
+
console.log('Tests passed');
\ No newline at end of file
diff --git a/yarn.lock b/yarn.lock
index 6e0735e..e5bf7da 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1014,6 +1014,13 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
+"@playwright/[email protected]":
+ version "1.64.1"
+ resolved
"https://registry.yarnpkg.com/@playwright/test/-/test-1.64.1.tgz#03d48b0cd135db5a70a6fbca54b2b91a597eed01"
+ integrity
sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==
+ dependencies:
+ playwright "1.64.1"
+
"@rollup/plugin-babel@^5.3.1":
version "5.3.1"
resolved
"https://registry.yarnpkg.com/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz#04bc0608f4aa4b2e4b1aebf284344d0f68fda283"
@@ -1972,6 +1979,18 @@ picomatch@^2.2.2, picomatch@^2.3.1:
resolved
"https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42"
integrity
sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==
[email protected]:
+ version "1.64.1"
+ resolved
"https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.64.1.tgz#ca9ec82d7da6ced1b2326ec59ef097aaa9a29f94"
+ integrity
sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==
+
[email protected]:
+ version "1.64.1"
+ resolved
"https://registry.yarnpkg.com/playwright/-/playwright-1.64.1.tgz#c174f48e17f5f3fba71726a9bcdeb8534d5c665d"
+ integrity
sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==
+ dependencies:
+ playwright-core "1.64.1"
+
prelude-ls@^1.2.1:
version "1.2.1"
resolved
"https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"