This is an automated email from the ASF dual-hosted git repository.

sergehuber pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/unomi-tracker.git


The following commit(s) were added to refs/heads/main by this push:
     new 2ee4da0  Update the documentation and licensing for the 2.0.0 release 
(#40)
2ee4da0 is described below

commit 2ee4da0fcb1705bc5ec292c66c5be3cfc9ea9de1
Author: Serge Huber <[email protected]>
AuthorDate: Wed Nov 4 15:33:00 2026 +0100

    Update the documentation and licensing for the 2.0.0 release (#40)
    
    * Update the documentation for the 2.0.0 release
    
    - CHANGES.md: the 2.0.0 release notes, for the vote: what is new, the
      fixes by ticket, compatibility, known limitations, what is tested.
    - README: what the tracker does with clicks and forms, supported
      browsers, the timeoutInMilliseconds default, every change a site
      upgrading from 1.x may notice, and the browser and Safari tests.
    - RELEASE.md: rewritten for 2.0.0 and later: the checks before a
      release (license headers, all servers in three browsers, Safari), the
      source package from the tag, a vote template, and publishing 1.x
      releases with their own npm tag once 2.x is out.
    - NOTICE: 2015-2026. src/types.ts, src/global.d.ts and .asf.yaml get the
      ASF license header.
    - JIRA_TICKETS.md and PROJECT_PLAN.md are removed: an early plan, with
      ticket keys that do not exist, now replaced by UNOMI-1032 and its
      sub-tasks in JIRA.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Align the release steps with the ASF release policy
    
    - The signing key: RSA of 2048 bits or more, never on an ASF machine, on
      a key server and in the KEYS of the distribution directory, which the
      vote and the users check (downloads.apache.org/unomi/KEYS).
    - A licensing check, and the vote email says how to verify the
      signature and checksum, on the voter's own machine.
    - After the vote: svn mv by a PMC member, only the latest release of
      each maintained line in dist/release, reporter.apache.org, at least an
      hour before the download page and the announcement, which links to the
      download page and comes from an apache.org address.
    - NOTICE uses https://www.apache.org/, as the release policy quotes it.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * List the third-party code the npm package bundles in its LICENSE
    
    The browser build bundles es6-crawler-detect and a @babel/runtime
    helper, both MIT, but the npm package's LICENSE only had the Apache
    License, and the bundle no notice. ASF policy wants each package's
    LICENSE to describe exactly what it contains, and the source package
    does not contain that code.
    
    - LICENSE-binary: the Apache License, then each bundled component with
      its version and license text, from the browser build's source map and
      the installed packages (scripts/npm-license.js generate). npm pack
      puts it in place of LICENSE, and puts LICENSE back afterwards.
    - yarn test checks that LICENSE-binary matches the build, so an upgrade
      of a bundled dependency cannot leave it out of date.
    - The browser build's header names the bundled packages and gives their
      licenses, so the notices stay with the file wherever it is copied.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Point the download page step of RELEASE.md to the site's tracker entry
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Correct four statements about click callbacks, UNOMI-1038 and the 
dependencies
    
    - README: a click with a modifier key waits when a callback is given, and
      no callback is called when tracking is off or Unomi could not be reached.
    - CHANGES.md: sourceLocalIdentifierMap matches a mapped part anywhere in
      the id, and es6-crawler-detect is part of the tracker pages load.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Wrap a line of CHANGES.md
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .asf.yaml              |  15 +
 .gitignore             |   3 +
 CHANGES.md             |  99 ++++++
 JIRA_TICKETS.md        | 311 ------------------
 LICENSE-binary         | 261 +++++++++++++++
 NOTICE                 |   4 +-
 PROJECT_PLAN.md        | 850 -------------------------------------------------
 README.md              |  58 +++-
 RELEASE.md             | 196 +++++++++---
 package.json           |   4 +-
 rollup.config.js       |  19 +-
 scripts/npm-license.js | 110 +++++++
 src/global.d.ts        |  17 +
 src/types.ts           |  17 +
 14 files changed, 743 insertions(+), 1221 deletions(-)

diff --git a/.asf.yaml b/.asf.yaml
index 09d93ec..50f7d38 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -1,3 +1,18 @@
+# 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.
+
 github:
   rulesets:
     - name: "Default Branch Protection"
diff --git a/.gitignore b/.gitignore
index 7a5ae32..df04a6a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -279,3 +279,6 @@ test/servers/.cache/
 
 # Build output, produced by the prepare script
 /dist
+
+# LICENSE while npm pack uses LICENSE-binary (scripts/npm-license.js)
+/.LICENSE-source
diff --git a/CHANGES.md b/CHANGES.md
new file mode 100644
index 0000000..aa35c9d
--- /dev/null
+++ b/CHANGES.md
@@ -0,0 +1,99 @@
+<!--
+  ~ 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.
+  -->
+
+Apache Unomi tracker: release notes
+===================================
+
+2.0.0
+-----
+Tracker 2.0.0 works with Unomi 2.x, 3.x and 4.x, including Unomi 4 
multi-tenant servers, and
+replaces 1.x without changes to the sites that use it. It also fixes clicks 
and forms that were not
+tracked, or stopped working for visitors, and ships TypeScript types.
+
+All the tickets: [JIRA release 
notes](https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12319220&version=12357743).
+
+### Compatibility
+| Unomi server | Configuration |
+|---|---|
+| 2.x, 3.x | As with tracker 1.x |
+| 4.x, single-tenant compatibility mode | As with tracker 1.x |
+| 4.x, multi-tenant | `apiKey`: the tenant's public API key |
+
+A site that works with tracker 1.x keeps working with the same Unomi server 
and the same
+configuration. What it may notice is listed in [Upgrading from 
1.x](README.md#upgrading-from-1x):
+all of it are fixes.
+
+### New
+- UNOMI-1019: `apiKey`, the tenant public API key Unomi 4 multi-tenant servers 
need, sent in the
+  `X-Unomi-Api-Key` header. Older servers ignore it.
+- UNOMI-1005: `sendCredentials: false` sends the requests without cookies, for 
sites that do not
+  need to recognise visitors (Unomi 4 then creates a profile per request).
+- UNOMI-891: TypeScript types (`dist/apache-unomi-tracker.d.ts`).
+- UNOMI-1019: the README explains how to configure the tracker for each Unomi 
version, and which
+  deployments keep the visitor's profile (the profile cookie is a third-party 
cookie when Unomi is
+  on another domain).
+
+### Fixes
+- UNOMI-1023: the browser build works without a `Buffer` polyfill; a page 
loading it directly got
+  no tracking at all.
+- UNOMI-1024: an empty page `attributes` is no longer sent, so sites set up 
with an older example
+  from the Unomi manual get their page views and clicks stored again on Unomi 
2.4 and later.
+- UNOMI-1037: every click on a tracked element is sent, not only the first 
one, also with
+  callbacks, and also a second click made before the first event is sent.
+- UNOMI-1047: a click on an image, an icon or some text inside a tracked link 
or button is sent on
+  the tracked element, and a link waits for its event before it is followed.
+- UNOMI-1046: clicks that do not leave the page are no longer held back nor 
dispatched again, so
+  the site's own click handlers run once per click (they ran twice). 
Single-page application
+  routers handle tracked links as before.
+- UNOMI-1040: links and forms keep working when Unomi cannot be reached, when 
tracking is turned
+  off, when the event cannot even be sent, and, without a timeout, when Unomi 
never answers (they
+  wait 1.5s at most). Links and forms that keep the page (new tab or window, 
download, `#` and
+  `javascript:` links) and clicks the site already handled do not wait for 
Unomi.
+- UNOMI-1041: Ctrl or Cmd+click on a tracked link opens it in a new tab again.
+- UNOMI-1042: a tracked form is submitted as a native submit would be, with 
the button that was
+  used: also a button named `submit` (the form was not submitted at all), an 
image button, and in
+  browsers without `requestSubmit` (the button's `formaction`, `formmethod`, 
`formenctype` and
+  `formtarget` are applied).
+- UNOMI-1043: without a usable `timeoutInMilliseconds` (missing, `0`, a blank 
string), the default
+  of 1500 ms is used; every request used to fail at once. A number given as a 
string works.
+- UNOMI-1038: `sourceLocalIdentifierMap` finds the elements whose id contains 
a mapped
+  part anywhere, also at its start (1.x missed those).
+
+### Build and tests
+- The dependencies are updated within their major versions, which fixes the 
security advisories
+  that did not need a major upgrade. `@babel/runtime`, whose helpers are part 
of the tracker that
+  pages load, now requires 7.26.10 or later. `es6-crawler-detect`, also part 
of it, stays at 3.3.0;
+  the others are build tools.
+- `dist` is no longer committed: it is built when the package is published, 
and when a project
+  installs a commit of this repository (the `prepare` script, for development 
only).
+- The npm package's `LICENSE` now lists the third-party code its browser build 
bundles
+  (`es6-crawler-detect` and a `@babel/runtime` helper, both MIT), and the 
browser build's header
+  gives their licenses. The 1.x packages had the Apache License only.
+- Tests: unit tests; browser tests against Unomi 2.3, 2.7, 3.0, 4.0 
multi-tenant and 4.0
+  single-tenant (Docker), in Chromium, Firefox and WebKit; a comparison of the 
requests with the
+  published 1.5.0; checks in the real Safari of a Mac. Pull requests must pass 
the tests against
+  Unomi 3 and 4 in the three browsers. See 
[test/servers](test/servers/README.md).
+
+### Known limitations
+Planned for later versions:
+- UNOMI-733: when Unomi is on another domain and the browser blocks its cookie 
(Safari does), the
+  visitor's profile only lasts a session (Unomi 2.x and 3.x) or a request 
(Unomi 4). The tracker
+  does not send its own copy of the profile ID yet.
+- UNOMI-1045: while Unomi is slow to answer, a tracked link or form waits up to
+  `timeoutInMilliseconds` before it goes on.
+- UNOMI-1044: events that cannot be sent while Unomi is briefly unreachable 
are lost.
+- UNOMI-1039: deployments where the website and Unomi are on different domains 
are not tested yet.
diff --git a/JIRA_TICKETS.md b/JIRA_TICKETS.md
deleted file mode 100644
index b1f3d8f..0000000
--- a/JIRA_TICKETS.md
+++ /dev/null
@@ -1,311 +0,0 @@
-# JIRA Tickets - Apache Unomi Tracker
-
-**Project:** UNOMI-TRACKER  
-**Version:** 1.5.0 → 2.0.0 (Modernization)  
-**Timeline:** 6 months (26 weeks, phased approach)  
-**Server Compatibility:** Unomi V2 + Unomi V4.0 (multi-tenancy)
-
-**PR Strategy:** Each ticket = 1 phase = 1 stacked PR. Strict linear 
dependency chain.
-
-```
-PR 1 → PR 2 → PR 3 → PR 4 → PR 5 → PR 6 → PR 7 → PR 8
-```
-
----
-
-## UNOMI-TRACKER-001: Phase 0 - Testing infrastructure ⭐ START HERE
-
-**PR 1** | **Depends on:** nothing  
-**Issue Type:** Epic  
-**Priority:** High (P1)  
-**Component:** Testing Infrastructure  
-**Labels:** testing, vitest, msw, quality-assurance
-
-**Description:**
-Establish comprehensive testing infrastructure with server mocks before any 
code changes begin. This is the foundation that guarantees backward 
compatibility and quality throughout the entire modernization process.
-
-**What will be done:**
-Set up Vitest test framework with jsdom, configure MSW for mocking Unomi 
server endpoints (both V2 and V4.0 modes), create bug verification tests 
proving the two critical bugs exist, create unit tests for all utility 
functions, create integration tests for all tracker flows, and create backward 
compatibility tests covering 100% of the public API. Achieve 80%+ code coverage.
-
-**Acceptance Criteria:**
-- [ ] Vitest configured with jsdom and coverage reporting
-- [ ] MSW set up with Unomi server mocks (V2 + V4.0 modes)
-- [ ] Bug verification tests created (proving bugs exist)
-- [ ] 80%+ code coverage achieved
-- [ ] All utility functions tested
-- [ ] All integration scenarios tested
-- [ ] 100% backward compatibility test coverage
-- [ ] CI/CD pipeline updated
-- [ ] Coverage reports generated
-
-**Technical Details:**
-- **Files:** `vitest.config.ts`, `test/setup.ts`, `test/mocks/`, test files
-- **Dependencies:** `vitest`, `@vitest/ui`, `@vitest/coverage-v8`, `msw`, 
`jsdom`
-- **Estimated Effort:** 40-60 hours
-
----
-
-## UNOMI-TRACKER-002: Phase 1 - Fix critical bugs and add Unomi V4.0 
compatibility
-
-**PR 2** | **Depends on:** PR 1 (UNOMI-TRACKER-001)  
-**Issue Type:** Epic  
-**Priority:** Critical (P0)  
-**Component:** Core Functionality  
-**Labels:** bug, critical, event-tracking, id-resolution, v3-compatibility
-
-**Description:**
-Fix two critical bugs and add Unomi V4.0 multi-tenancy support. These are all 
targeted changes to the existing codebase that should be completed before 
larger refactoring begins.
-
-**Problem (Bugs):**
-1. **Bug #1 (Line 448)**: `splice(eventIndex, 0)` doesn't actually remove 
elements from the `eventsPrevented` array. The code removes 0 elements instead 
of 1, causing incorrect event handling behavior.
-
-2. **Bug #2 (Lines 1420-1428)**: The `_resolveId` function has multiple logic 
errors:
-   - Uses array result from `filter()` as a string in `replace()` operation
-   - Incorrect index check (`> 0` instead of `!== -1`) misses matches at 
position 0
-   - Function is marked with `@ts-expect-error` acknowledging it's broken
-
-**What will be done:**
-Fix both bugs: correct the splice operation and rewrite `_resolveId`. Add 
Unomi V4.0 support: introduce optional `apiKey`/`tenantId` config fields and 
inject `X-Unomi-Api-Key`/`X-Unomi-Tenant-Id` headers in the `ajax()` method 
when configured. The tracker will work with both V2 (no API key) and V4.0 (with 
API key) servers, maintaining full backward compatibility.
-
-**Acceptance Criteria:**
-- [ ] Bug #1 fixed: `splice` correctly removes elements
-- [ ] Bug #2 fixed: `_resolveId` function rewritten with correct logic
-- [ ] Bug verification tests pass
-- [ ] V4.0 support: `apiKey` and `tenantId` optional config fields added
-- [ ] V4.0 support: `X-Unomi-Api-Key` header injected when `apiKey` is set
-- [ ] Tests for V2 mode (no API key) and V4.0 mode (with API key)
-- [ ] Tracker works against V2 servers with API key configured (header ignored)
-- [ ] Types updated in `types.ts`
-- [ ] No regression in existing functionality
-
-**Technical Details:**
-- **Files:** `src/apache-unomi-tracker.js`, `src/types.ts`
-- **V4.0 change scope:** ~20-30 lines of implementation code (additive only)
-- **Estimated Effort:** 8-12 hours
-
----
-
-## UNOMI-TRACKER-003: Phase 2 - Modernize build toolchain and config cleanup
-
-**PR 3** | **Depends on:** PR 2 (UNOMI-TRACKER-002)  
-**Issue Type:** Epic  
-**Priority:** Medium (P2)  
-**Component:** Build System, Dependencies, Configuration  
-**Labels:** modernization, build, dependencies, configuration
-
-**Description:**
-Modernize the build toolchain and upgrade all dependencies to 2026 standards. 
Also fix configuration issues (browserslist, XDomainRequest type) that are 
prerequisites for TypeScript migration.
-
-**What will be done:**
-Upgrade Rollup to 4.x, replace Babel with esbuild (removing 
`babel.config.json` entirely), upgrade runtime and dev dependencies, add modern 
`browserslist` configuration, fix incorrect `XDomainRequest` type definition, 
and configure TypeScript for incremental migration (`allowJs`, `checkJs`).
-
-**Acceptance Criteria:**
-- [ ] Rollup 4.x installed and configured
-- [ ] Babel removed, esbuild integrated
-- [ ] All dependencies upgraded (`es6-crawler-detect` v4, ESLint v9, TS ESLint 
plugins)
-- [ ] `browserslist` configuration added (deprecated Babel `browsers` field 
removed)
-- [ ] `XDomainRequest` type definition fixed in `global.d.ts`
-- [ ] TypeScript configured for incremental migration
-- [ ] All builds (CJS, ESM, UMD) produce correct output
-- [ ] Build time improved (target: 50% faster)
-- [ ] All tests passing
-
-**Technical Details:**
-- **Files:** `package.json`, `rollup.config.js`, `babel.config.json` 
(removed), `tsconfig.json`, `.eslintrc.json`, `src/global.d.ts`, 
`.browserslistrc`
-- **Estimated Effort:** 12-20 hours
-
----
-
-## UNOMI-TRACKER-004: Phase 3 - Extract and convert utility functions to 
TypeScript
-
-**PR 4** | **Depends on:** PR 3 (UNOMI-TRACKER-003)  
-**Issue Type:** Epic  
-**Priority:** Medium (P2)  
-**Component:** TypeScript Migration  
-**Labels:** modernization, typescript, utilities
-
-**Description:**
-Extract leaf-level utility functions from the monolithic main file and convert 
them to TypeScript modules. First step of the "edge → trunk" migration. 
Requires the build system from Phase 2 to support TypeScript compilation.
-
-**What will be done:**
-Extract and convert all utility functions to TypeScript modules: cookie 
utilities, event builders, AJAX utility, form utilities, and URL utilities. 
Update main file to import from new modules.
-
-**Acceptance Criteria:**
-- [ ] All utility functions extracted to `src/utils/*.ts`
-- [ ] All utilities converted to TypeScript with proper types
-- [ ] Unit tests pass for all utilities
-- [ ] Main file updated to import from new modules
-- [ ] Functionality verified unchanged
-- [ ] All tests passing
-
-**Technical Details:**
-- **Files:** `src/utils/cookies.ts`, `src/utils/events.ts`, 
`src/utils/ajax.ts`, `src/utils/form.ts`, `src/utils/url.ts`, 
`src/apache-unomi-tracker.js`
-- **Estimated Effort:** 15-21 hours
-
----
-
-## UNOMI-TRACKER-005: Phase 4 - Extract and convert feature modules to 
TypeScript
-
-**PR 5** | **Depends on:** PR 4 (UNOMI-TRACKER-004)  
-**Issue Type:** Epic  
-**Priority:** Medium (P2)  
-**Component:** TypeScript Migration  
-**Labels:** modernization, typescript, features
-
-**Description:**
-Extract higher-level feature modules from the main file and convert to 
TypeScript. These modules depend on the utility modules extracted in Phase 3, 
so they import from `src/utils/`.
-
-**What will be done:**
-Extract and convert all feature logic to TypeScript modules: personalization, 
optimization/A/B testing, and event tracking. Feature modules import from 
`src/utils/` established in the previous phase. Update main file to import from 
new modules.
-
-**Acceptance Criteria:**
-- [ ] All feature modules extracted to `src/features/*.ts`
-- [ ] All features converted to TypeScript with proper types
-- [ ] Features import from `src/utils/` (no duplication)
-- [ ] Integration tests pass
-- [ ] Main file updated to import from new modules
-- [ ] All tests passing
-
-**Technical Details:**
-- **Files:** `src/features/personalization.ts`, 
`src/features/optimization.ts`, `src/features/tracking.ts`, 
`src/apache-unomi-tracker.js`
-- **Estimated Effort:** 16-22 hours
-
----
-
-## UNOMI-TRACKER-006: Phase 5 - Convert core tracker to TypeScript class with 
facade layer
-
-**PR 6** | **Depends on:** PR 5 (UNOMI-TRACKER-005)  
-**Issue Type:** Epic  
-**Priority:** Medium (P2)  
-**Component:** TypeScript Migration, Extensibility  
-**Labels:** modernization, typescript, core, backward-compatibility, facade
-
-**Description:**
-Convert the now-slimmed-down main tracker to a TypeScript class with the 
facade layer for backward compatibility. Requires both utilities (Phase 3) and 
features (Phase 4) to be extracted first so the core only contains 
orchestration logic.
-
-**What will be done:**
-Create `UnomiTracker` class with proper encapsulation. Build a facade layer so 
`useTracker()` still returns a plain mutable `wem` object with the exact same 
shape -- delegating to the internal class. This ensures consumers who override 
methods, access state directly, or add custom properties are not broken. Add 
deprecation warnings on `_` prefixed methods. Define formal public API contract.
-
-**Acceptance Criteria:**
-- [ ] Core tracker converted to TypeScript class
-- [ ] Facade returns `wem` object with exact same shape as current API
-- [ ] Monkey-patching still works (e.g., `wem.ajax = customFn`)
-- [ ] Direct state access still works (e.g., `wem.cxs`, `wem.sessionID`)
-- [ ] `_` prefixed methods log deprecation warnings
-- [ ] Public API contract defined as TypeScript interface
-- [ ] `@ts-expect-error` comments reduced by 50%+
-- [ ] 80%+ TypeScript coverage achieved
-- [ ] All tests passing
-
-**Technical Details:**
-- **Files:** `src/core/tracker.ts`, `src/facade/wem.ts`, 
`src/types/public-api.ts`, `src/index.ts`
-- **Estimated Effort:** 16-22 hours
-
----
-
-## UNOMI-TRACKER-007: Phase 6 - Extension hooks + code quality
-
-**PR 7** | **Depends on:** PR 6 (UNOMI-TRACKER-006)  
-**Issue Type:** Epic  
-**Priority:** Medium (P2)  
-**Component:** Code Quality, Extensibility  
-**Labels:** modernization, refactoring, architecture, code-quality, 
extensibility
-
-**Description:**
-Implement the extension hooks API and address remaining code quality issues. 
Requires the facade/class architecture from Phase 5 so hooks can be wired into 
the tracker internals.
-
-**What will be done:**
-Build the extension hooks system (`beforeRequest`, `afterRequest`, 
`onContextLoaded`, `beforeEvent`, `afterEvent`) providing a clean alternative 
to monkey-patching. Replace deprecated event creation APIs with modern 
alternatives. Address remaining `@ts-expect-error` comments. Implement code 
splitting and lazy loading for optional features.
-
-**Acceptance Criteria:**
-- [ ] Extension hooks API implemented and documented
-- [ ] Hooks provide clean alternative for all common monkey-patching patterns
-- [ ] All deprecated event APIs replaced (`CustomEvent()`, `Event()` 
constructors)
-- [ ] Remaining `@ts-expect-error` comments addressed
-- [ ] Code splitting implemented for optional features
-- [ ] Final modular directory structure in place
-- [ ] All tests passing
-
-**Technical Details:**
-- **Files:** `src/core/hooks.ts`, `src/core/tracker.ts`, `src/facade/wem.ts`, 
`src/types/`, `src/index.ts`
-- **Estimated Effort:** 20-28 hours
-
----
-
-## UNOMI-TRACKER-008: Phase 7 - Documentation + DX + final polish
-
-**PR 8** | **Depends on:** PR 7 (UNOMI-TRACKER-007)  
-**Issue Type:** Epic  
-**Priority:** Low (P3)  
-**Component:** Documentation, Developer Experience  
-**Labels:** documentation, dx, tooling, refactoring
-
-**Description:**
-Final improvements to documentation, code quality, and developer experience. 
Done last so docs reflect the final API surface including hooks, facade, V4.0 
support, and public API contract.
-
-**What will be done:**
-Expand README with comprehensive documentation (installation, usage, API 
reference, V4.0 config, hooks API, migration guide for consumers). Refactor 
duplicated code patterns, standardize function styles. Set up ESLint + Prettier 
with pre-commit hooks (Husky, lint-staged). Update CI/CD pipeline.
-
-**Acceptance Criteria:**
-- [ ] README expanded with comprehensive documentation
-- [ ] V4.0 configuration documented with examples
-- [ ] Extension hooks API documented with migration examples
-- [ ] Public API contract documented
-- [ ] Duplicated code refactored (DRY)
-- [ ] Function styles standardized (KISS)
-- [ ] ESLint + Prettier configured with pre-commit hooks
-- [ ] CI/CD pipeline updated with type checking, linting, coverage
-- [ ] All checks passing
-
-**Technical Details:**
-- **Files:** `README.md`, `.eslintrc.json`, `.prettierrc`, `.husky/`, 
`.github/workflows/ci.yml`, source files
-- **Estimated Effort:** 12-20 hours
-
----
-
-## 📊 Summary
-
-### Dependency Chain (Stacked PRs)
-
-```
-PR 1  UNOMI-TRACKER-001  Phase 0: Testing Infrastructure         ⭐ START
- ↓
-PR 2  UNOMI-TRACKER-002  Phase 1: Bug Fixes + V4.0 Compatibility
- ↓
-PR 3  UNOMI-TRACKER-003  Phase 2: Build Modernization + Config
- ↓
-PR 4  UNOMI-TRACKER-004  Phase 3: TypeScript - Utilities
- ↓
-PR 5  UNOMI-TRACKER-005  Phase 4: TypeScript - Features
- ↓
-PR 6  UNOMI-TRACKER-006  Phase 5: TypeScript - Core + Facade
- ↓
-PR 7  UNOMI-TRACKER-007  Phase 6: Extension Hooks + Code Quality
- ↓
-PR 8  UNOMI-TRACKER-008  Phase 7: Documentation + DX + Polish
-```
-
-### Ticket Statistics
-- **Total Tickets:** 8
-- **Critical (P0):** 1 (Bug fixes + V4.0)
-- **High (P1):** 1 (Testing infrastructure)
-- **Medium (P2):** 5 (Build, TypeScript phases, Code Quality)
-- **Low (P3):** 1 (Documentation + Polish)
-
-### Estimated Effort
-- **Total:** 139-205 hours (~18-26 working days)
-- **Timeline:** 26 weeks (phased approach)
-
-### Key Principles
-
-- ✅ **DRY / KISS / SOLID**: All implementations follow these engineering 
principles
-- ✅ **Testing First**: Complete testing infrastructure before any code changes
-- ✅ **Backward Compatible**: Facade preserves exact API shape for consumers 
who extend/embed
-- ✅ **Extensible**: Official hooks API replaces need for monkey-patching
-- ✅ **Dual Server Support**: Works with both Unomi V2 and V4.0 (multi-tenancy)
-- ✅ **Incremental**: Gradual migration with deprecation warnings, not big bang
-- ✅ **Stacked PRs**: Each phase = 1 PR in a strict linear chain; every PR is 
reviewable and mergeable independently
-
----
-
-*Note: Ticket numbers (UNOMI-TRACKER-XXX) should be replaced with actual JIRA 
ticket numbers when creating tickets.*
diff --git a/LICENSE-binary b/LICENSE-binary
new file mode 100644
index 0000000..f7d334d
--- /dev/null
+++ b/LICENSE-binary
@@ -0,0 +1,261 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed 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.
+
+
+------------------------------------------------------------------------------------
+APACHE UNOMI TRACKER SUBCOMPONENTS
+
+The npm package of Apache Unomi tracker contains, in its browser build
+(dist/apache-unomi-tracker.umd.js and dist/apache-unomi-tracker.umd.js.map), 
the following
+components, under the licenses below. The other files of the package are under 
the
+Apache License 2.0 above.
+
+
+@babel/runtime 7.29.10 (MIT)
+
+MIT License
+
+Copyright (c) 2014-present Sebastian McKenzie and other contributors
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+es6-crawler-detect 3.3.0 (MIT)
+
+MIT License
+
+Copyright (c) 2017 Jeffery ThaGintoki
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/NOTICE b/NOTICE
index b4b8547..6301b0c 100644
--- a/NOTICE
+++ b/NOTICE
@@ -1,8 +1,8 @@
 Apache Unomi
-Copyright 2015-2022 The Apache Software Foundation
+Copyright 2015-2026 The Apache Software Foundation
 
 This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
+The Apache Software Foundation (https://www.apache.org/).
 
 Based on source code originally developed by
 Jahia Solutions Software (http://www.jahia.com/).
\ No newline at end of file
diff --git a/PROJECT_PLAN.md b/PROJECT_PLAN.md
deleted file mode 100644
index c12efa9..0000000
--- a/PROJECT_PLAN.md
+++ /dev/null
@@ -1,850 +0,0 @@
-# Apache Unomi Tracker - Project Analysis & Modernization Plan
-
-**Version:** 1.0  
-**Date:** 2026  
-**Status:** Planning Phase
-
----
-
-## Executive Summary
-
-This document provides a comprehensive analysis of the Apache Unomi Tracker 
project, identifies critical bugs, documents all issues, and outlines a 
modernization strategy for 2026. The plan prioritizes **testing first** to 
ensure backward compatibility throughout the modernization process, and 
includes support for **Unomi V4.0 multi-tenancy**.
-
-**Key Findings:**
-- 🔴 **2 Critical Bugs** requiring immediate fixes
-- ⚠️ **13 Issues** across documentation, code quality, and compatibility
-- 🚀 **Modernization Opportunity** to improve maintainability and type safety
-- 🔄 **V4.0 Compatibility** needed to support Unomi multi-tenancy alongside V2
-
-**Recommended Approach (8 phases, 8 stacked PRs):**
-1. **Phase 0**: Establish comprehensive test suite with server mocks (4 weeks)
-2. **Phase 1**: Fix critical bugs + add Unomi V4.0 compatibility (2 weeks)
-3. **Phase 2**: Modernize build toolchain + config cleanup (4 weeks)
-4. **Phase 3**: TypeScript migration -- extract utilities (2 weeks)
-5. **Phase 4**: TypeScript migration -- extract features (2 weeks)
-6. **Phase 5**: TypeScript migration -- core class + facade (4 weeks)
-7. **Phase 6**: Extension hooks + code quality (4 weeks)
-8. **Phase 7**: Documentation + DX + final polish (4 weeks)
-
-**Total Timeline:** 6 months (26 weeks)  
-**Risk Level:** Low-Medium (incremental, backward compatible)  
-**PR Strategy:** Each phase = 1 stacked PR. Strict linear dependency chain: PR 
N builds on PR N-1.
-
----
-
-## Part 1: Current State Analysis
-
-### Codebase Structure
-- **Main file**: `src/apache-unomi-tracker.js` (~1,500 lines) - monolithic 
structure
-- **Type definitions**: `src/types.ts` (exists, well-structured)
-- **Build system**: Rollup 2.x + Babel 7.x
-- **Testing**: Minimal (basic existence check only)
-- **Module format**: Supports ESM, CJS, and UMD outputs ✅
-
-### Dependencies Status (2026)
-| Package | Current | Latest (2026) | Status | Action |
-|---------|---------|---------------|--------|--------|
-| Rollup | 2.79.0 | 4.x | ⚠️ Outdated | Upgrade |
-| Babel | 7.18.x | 8.x | ⚠️ Outdated | Replace with esbuild |
-| TypeScript | 5.8.2 | 5.7.x+ | ✅ Current | Keep |
-| ESLint | 8.23.0 | 9.x | ⚠️ Outdated | Upgrade |
-| es6-crawler-detect | 3.3.0 | 4.x | ⚠️ Outdated | Upgrade (has types in v4) |
-
----
-
-## Part 2: Critical Bugs (Must Fix Immediately)
-
-### 🔴 Bug #1: Incorrect Array Splice Operation
-
-**Location:** `src/apache-unomi-tracker.js:448`  
-**Severity:** Critical - Logic Bug  
-**Status:** Verified ✅
-
-**Current Code:**
-```javascript
-var eventIndex = wem.eventsPrevented.indexOf(targetId);
-if (eventIndex !== -1) {
-    wem.eventsPrevented.splice(eventIndex, 0);  // ❌ BUG: Removes 0 elements
-}
-```
-
-**The Problem:**
-- `splice(index, 0)` removes **0 elements** - it does nothing!
-- Array element is never removed
-- Causes incorrect event handling behavior
-
-**Verification:**
-```javascript
-const arr = ['a', 'b', 'c'];
-arr.splice(1, 0); // Removes 0 elements
-console.log(arr); // ['a', 'b', 'c'] - unchanged!
-```
-
-**Fix:**
-```javascript
-if (eventIndex !== -1) {
-    wem.eventsPrevented.splice(eventIndex, 1);  // ✅ Remove 1 element
-}
-```
-
-**Impact:** Event prevention logic doesn't work correctly, potential memory 
issues.
-
----
-
-### 🔴 Bug #2: Broken `_resolveId` Function
-
-**Location:** `src/apache-unomi-tracker.js:1420-1428`  
-**Severity:** Critical - Multiple Logic Errors  
-**Status:** Verified ✅ (marked with `@ts-expect-error` in code)
-
-**Current Code:**
-```javascript
-_resolveId: function (id) {
-    if (wem.digitalData.sourceLocalIdentifierMap) {
-        var source = 
Object.keys(wem.digitalData.sourceLocalIdentifierMap).filter(function (source) {
-            return id.indexOf(source) > 0;  // ❌ BUG 1: > 0 misses index 0
-        });
-        // @ts-expect-error This code is broken, source is an array
-        return source ? id.replace(source, 
wem.digitalData.sourceLocalIdentifierMap[source]) : id;
-        // ❌ BUG 2: source is an array, not a string
-        // ❌ BUG 3: Can't use array in replace()
-    }
-    return id;
-}
-```
-
-**The Problems:**
-1. **`filter()` returns array, not string** - but used as string in `replace()`
-2. **`indexOf(source) > 0` misses matches at position 0** - should be `!== -1`
-3. **Type error** - array used where string expected
-
-**Verification:**
-```javascript
-// Issue 1: filter returns array
-const source = Object.keys(map).filter(...);
-console.log(Array.isArray(source)); // true - but used as string!
-
-// Issue 2: > 0 misses index 0
-const id = 'prefix-item'; // Match at index 0
-id.indexOf('prefix') > 0; // false - should be true!
-```
-
-**Fix:**
-```javascript
-_resolveId: function (id) {
-    if (wem.digitalData.sourceLocalIdentifierMap) {
-        var sources = Object.keys(wem.digitalData.sourceLocalIdentifierMap);
-        for (var i = 0; i < sources.length; i++) {
-            var source = sources[i];
-            if (id.indexOf(source) !== -1) {  // ✅ Fix: !== -1 finds all 
matches
-                return id.replace(source, 
wem.digitalData.sourceLocalIdentifierMap[source]);
-            }
-        }
-    }
-    return id;
-}
-```
-
-**Impact:** ID mapping fails, tracker can't find elements on page (forms, 
videos, clicks).
-
-**Tests:** fixed in UNOMI-1037 and UNOMI-1038; see 
`test/servers/tracker.spec.js` (clicks, against each Unomi server) and 
`test/spec.js` (`_resolveId`).
-
----
-
-## Part 3: Issues Found
-
-### 📚 Documentation Issues
-
-#### 1. Minimal README.md (High Priority)
-- ❌ No installation instructions
-- ❌ No usage examples
-- ❌ No API documentation
-- ❌ No configuration guide
-
-**Fix:** Expand README with installation, usage, API reference, examples.
-
----
-
-### ⚠️ Code Quality Issues
-
-#### 2. Excessive Type Suppression (Medium Priority)
-- 14 `@ts-expect-error` comments throughout codebase
-- Masks potential runtime errors
-- Reduces code reliability
-
-**Fix:** Address type issues properly, add type guards, update type 
definitions.
-
-#### 3. Deprecated Event Creation APIs (Medium Priority)
-- Uses `document.createEvent()` and `initCustomEvent()` (deprecated)
-- Should use modern `CustomEvent()` and `Event()` constructors
-
-**Fix:** Replace with modern APIs (lines 795-796, 1320-1322).
-
-#### 4. Inconsistent Function Styles (Low Priority)
-- Mixes arrow functions and function expressions
-- Should standardize on one style
-
-#### 5. Incomplete Null Checking (Low Priority)
-- `_isObject` function could be more explicit about null checking
-
----
-
-### 🔧 Compatibility Issues
-
-#### 6. Deprecated Babel Configuration (High Priority)
-- Uses deprecated `browsers` field
-- Should use modern `browserslist` format
-
-**Fix:** Add `.browserslistrc` or update `package.json`, remove deprecated 
field.
-
-#### 7. Incorrect TypeScript Type Definition (High Priority)
-- `XDomainRequest` incorrectly typed as `XMLHttpRequest` in `global.d.ts`
-- Should have proper interface definition
-
-**Fix:** Define proper `XDomainRequest` interface.
-
----
-
-### 🧪 Testing Issues
-
-#### 8. Minimal Test Coverage (High Priority)
-- Only basic existence check
-- No functional tests
-- No integration tests
-- No edge case coverage
-
-**Fix:** Establish comprehensive test suite (see Phase 0 below).
-
----
-
-## Part 4: Unomi V4.0 Compatibility
-
-### Context
-
-Apache Unomi V4.0 introduces **multi-tenancy**: all data (profiles, events, 
segments, rules, schemas) is now tenant-scoped. The main impact on the tracker 
is a new **authentication model** for API endpoints.
-
-### What Changed in V4.0
-
-| Aspect | Unomi V2 | Unomi V4.0 |
-|--------|----------|------------|
-| **Authentication** | Cookies + optional `X-Unomi-Peer` for protected events 
| `X-Unomi-Api-Key` header (public API key) |
-| **Multi-tenancy** | None (single tenant) | Full tenant isolation, per-tenant 
API keys |
-| **Endpoint paths** | `/context.json`, `/eventcollector` | **Same** -- no 
change |
-| **Request/response format** | `ContextRequest` / `ContextResponse` | 
**Same** -- no change |
-| **Protected events** | IP + `X-Unomi-Peer` header | API key scopes (or V2 
compat mode) |
-
-### V2 Compatibility Mode (Server-Side)
-
-Unomi V4.0 includes a built-in V2 compatibility mode (`UNOMI-904`) that allows 
V2 clients to work without changes:
-- Public endpoints (`/context.json`) accept requests without authentication
-- A default tenant is used for all operations
-- Protected events still use IP + `X-Unomi-Peer`
-- This is a **transitional feature**, not a permanent solution
-
-### Tracker Compatibility Strategy
-
-**Approach: Configuration-driven authentication** -- the tracker adds API key 
headers when configured, and works as-is (V2 mode) when not.
-
-#### Configuration Changes
-
-Two new optional fields in `wemInitConfig`:
-
-```typescript
-wemInitConfig: {
-    contextServerUrl: string;
-    // ... existing fields ...
-
-    // NEW: Unomi V4.0 multi-tenancy support
-    apiKey?: string;       // Public API key for V4.0 authentication
-    tenantId?: string;     // Tenant ID (for admin/private operations, 
optional)
-}
-```
-
-#### Implementation Changes
-
-The `ajax()` method conditionally injects the `X-Unomi-Api-Key` header:
-
-```javascript
-// In the ajax() function, after existing header setup:
-if (wem.apiKey) {
-    xhr.setRequestHeader('X-Unomi-Api-Key', wem.apiKey);
-}
-if (wem.tenantId) {
-    xhr.setRequestHeader('X-Unomi-Tenant-Id', wem.tenantId);
-}
-```
-
-#### CORS Preflight Consideration
-
-The current tracker uses `Content-Type: text/plain;charset=UTF-8` to **avoid 
CORS preflight**. Adding custom headers like `X-Unomi-Api-Key` **will trigger a 
CORS preflight** (`OPTIONS` request).
-
-**Impact:** One extra round-trip per unique URL (browser caches preflight via 
`Access-Control-Max-Age`).
-
-**Why this is acceptable:**
-- The Unomi V4.0 server already supports CORS for `X-Unomi-Api-Key`
-- Preflight is cached by browsers, so the overhead is minimal
-- This only affects V4.0 mode; V2 mode remains unchanged (no preflight)
-- The security benefit of proper API key authentication outweighs the minor 
overhead
-
-#### Compatibility Matrix
-
-| Tracker Config | Unomi V2 Server | V4.0 (V2 compat mode) | V4.0 (native) |
-|----------------|-----------------|------------------------|----------------|
-| No API key     | Works           | Works                  | 401 Unauthorized 
|
-| With API key   | Header ignored* | Works                  | Works          |
-
-\* V2 servers don't check for `X-Unomi-Api-Key`, so the extra header is 
silently ignored -- making the tracker safely backward compatible in both 
directions.
-
----
-
-## Part 5: Modernization Strategy
-
-### Stacked PR Model
-
-Each phase produces exactly one PR. Each PR depends only on the previous one, 
forming a strict linear chain suitable for stacked PR workflows.
-
-```
-PR 1 (Phase 0): Testing infrastructure
-  ↓
-PR 2 (Phase 1): Bug fixes + V4.0 support
-  ↓
-PR 3 (Phase 2): Build modernization + config cleanup
-  ↓
-PR 4 (Phase 3): Extract utilities → TypeScript
-  ↓
-PR 5 (Phase 4): Extract features → TypeScript
-  ↓
-PR 6 (Phase 5): Core TypeScript class + facade
-  ↓
-PR 7 (Phase 6): Extension hooks + code quality
-  ↓
-PR 8 (Phase 7): Documentation + DX + final polish
-```
-
----
-
-### Phase 0: Testing Infrastructure (Weeks 1-4) ⭐ START HERE
-
-**PR 1** | Depends on: nothing | Ticket: UNOMI-TRACKER-001
-
-**Critical:** Must be completed before any code changes.
-
-#### Goals
-- Establish comprehensive test suite with server mocks
-- Achieve 80%+ code coverage
-- Create bug verification tests
-- Ensure backward compatibility tests
-
-#### Implementation
-
-**1. Set up Vitest + MSW**
-```json
-{
-  "devDependencies": {
-    "vitest": "^2.0.0",
-    "@vitest/ui": "^2.0.0",
-    "@vitest/coverage-v8": "^2.0.0",
-    "msw": "^2.0.0",
-    "jsdom": "^25.0.0"
-  }
-}
-```
-
-**2. Mock Unomi Server Endpoints**
-- `/context.json` (POST) - context loading
-- `/eventcollector` (POST) - event collection
-- Support success, error, timeout, network failure scenarios
-- Both V2 (no auth) and V4.0 (API key) mock handlers
-
-**3. Test Coverage**
-- Unit tests: utilities, core logic
-- Integration tests: tracker initialization, context loading, event collection
-- Backward compatibility: 100% API coverage
-- Bug verification: prove bugs exist
-
-**Deliverables:**
-- ✅ Vitest configured
-- ✅ MSW with Unomi mocks (V2 + V4.0)
-- ✅ 80%+ code coverage
-- ✅ Bug verification tests
-- ✅ All tests passing
-
----
-
-### Phase 1: Fix Critical Bugs + Unomi V4.0 Compatibility (Weeks 5-6)
-
-**PR 2** | Depends on: PR 1 (Phase 0) | Ticket: UNOMI-TRACKER-002
-
-1. Fix Bug #1: Change `splice(eventIndex, 0)` to `splice(eventIndex, 1)`
-2. Fix Bug #2: Rewrite `_resolveId` function with correct logic
-3. Add Unomi V4.0 multi-tenancy support:
-   - Add optional `apiKey` and `tenantId` to `wemInitConfig` and types
-   - Modify `ajax()` to inject `X-Unomi-Api-Key` / `X-Unomi-Tenant-Id` headers 
when configured
-   - Add tests for both V2 (no API key) and V4.0 (with API key) modes
-
-**Verification:** Bug verification tests now pass. V4.0 authentication tests 
pass.
-
-**Deliverables:**
-- ✅ Both critical bugs fixed
-- ✅ V4.0 API key support added (~20-30 lines, additive only)
-- ✅ All tests passing
-
----
-
-### Phase 2: Modernize Build Toolchain + Config Cleanup (Weeks 7-10)
-
-**PR 3** | Depends on: PR 2 (Phase 1) | Ticket: UNOMI-TRACKER-003
-
-#### 2.1 Upgrade Rollup to 4.x
-- Better performance, improved TypeScript support, better tree-shaking
-
-#### 2.2 Replace Babel with esbuild
-- 10-100x faster builds, native TypeScript support, smaller bundles
-- Remove `babel.config.json` entirely
-
-#### 2.3 Upgrade Dependencies
-- `es6-crawler-detect`: 3.3.0 → 4.0.0 (has TypeScript types)
-- `eslint`: 8.23.0 → 9.0.0
-- Add TypeScript ESLint plugins
-
-#### 2.4 Fix Configuration Issues
-- Add modern `browserslist` format (replaces deprecated Babel `browsers` field)
-- Fix `XDomainRequest` type definition in `global.d.ts`
-- Configure TypeScript with `allowJs` and `checkJs` for incremental migration
-
-**Deliverables:**
-- ✅ Rollup 4.x + esbuild (Babel removed)
-- ✅ All dependencies upgraded
-- ✅ Config issues fixed (browserslist, XDomainRequest type)
-- ✅ Build produces same output, faster
-
----
-
-### Phase 3: TypeScript Migration -- Utilities (Weeks 11-12)
-
-**PR 4** | Depends on: PR 3 (Phase 2) | Ticket: UNOMI-TRACKER-004
-
-First step of the incremental "edge → trunk" migration strategy. Extract 
leaf-level utility functions that have no dependencies on other tracker code.
-
-- Create `src/utils/` directory
-- Extract cookie utilities (`setCookie`, `getCookie`, `removeCookie`) → 
`src/utils/cookies.ts`
-- Extract event builders (`buildEvent`, `buildTarget`, `buildSource`, etc.) → 
`src/utils/events.ts`
-- Extract AJAX utility → `src/utils/ajax.ts`
-- Extract form utilities (`_extractFormData`) → `src/utils/form.ts`
-- Extract URL utilities (`getUrlParameter`, `convertUrlParametersToObj`) → 
`src/utils/url.ts`
-- Update main file to import from new modules
-
-**Deliverables:**
-- ✅ All utility functions extracted and converted to TypeScript
-- ✅ Unit tests for all utilities
-- ✅ Main file imports from new modules
-- ✅ All tests passing
-
----
-
-### Phase 4: TypeScript Migration -- Features (Weeks 13-14)
-
-**PR 5** | Depends on: PR 4 (Phase 3) | Ticket: UNOMI-TRACKER-005
-
-Extract higher-level feature modules. These depend on the utility modules 
extracted in Phase 3.
-
-- Create `src/features/` directory
-- Extract personalization logic → `src/features/personalization.ts`
-- Extract optimization/A/B testing logic → `src/features/optimization.ts`
-- Extract event tracking logic → `src/features/tracking.ts`
-- Feature modules import from `src/utils/` (established in Phase 3)
-- Update main file to import from new modules
-
-**Deliverables:**
-- ✅ All feature modules extracted and converted to TypeScript
-- ✅ Integration tests for all features
-- ✅ All tests passing
-
----
-
-### Phase 5: TypeScript Migration -- Core Class + Facade (Weeks 15-18)
-
-**PR 6** | Depends on: PR 5 (Phase 4) | Ticket: UNOMI-TRACKER-006
-
-Convert the now-slimmed-down main tracker to a TypeScript class. Build the 
facade layer for backward compatibility. This requires both utilities (Phase 3) 
and features (Phase 4) to be extracted first so the core only contains 
orchestration logic.
-
-- Convert tracker object to `UnomiTracker` TypeScript class
-- Build facade: `useTracker()` returns plain `wem` object that delegates to 
the class
-- Facade exposes same public methods, same state access (via getters/setters), 
same mutability
-- Add deprecation warnings on `_` prefixed methods (not removed until v2.0)
-- Define formal public API contract as TypeScript interface
-- Remove `@ts-expect-error` comments (target: 50% reduction)
-
-**Deliverables:**
-- ✅ Core tracker in TypeScript with clean encapsulation
-- ✅ Facade preserves exact `wem` object shape
-- ✅ Public API contract defined and tested
-- ✅ 80%+ TypeScript coverage
-- ✅ All tests passing
-
----
-
-### Phase 6: Extension Hooks + Code Quality (Weeks 19-22)
-
-**PR 7** | Depends on: PR 6 (Phase 5) | Ticket: UNOMI-TRACKER-007
-
-Requires the facade/class architecture from Phase 5 to be in place so hooks 
can be wired into the tracker internals.
-
-#### 6.1 Extension Hooks API
-- Implement official hooks system (`beforeRequest`, `afterRequest`, 
`onContextLoaded`, `beforeEvent`, `afterEvent`)
-- Provides clean alternative to monkey-patching
-- Follows Open/Closed Principle
-
-#### 6.2 Code Quality
-- Replace deprecated `document.createEvent()` APIs with `CustomEvent()` and 
`Event()` constructors
-- Address remaining `@ts-expect-error` comments
-- Implement lazy loading for optional features (personalization, optimization)
-
-#### 6.3 Final Directory Structure
-```
-src/
-  ├── index.ts                    # Main entry point (useTracker facade)
-  ├── core/
-  │   ├── tracker.ts              # UnomiTracker class (internal)
-  │   ├── context.ts              # Context loading
-  │   ├── callbacks.ts            # Callback management
-  │   └── hooks.ts                # Extension hooks system
-  ├── facade/
-  │   └── wem.ts                  # Facade builder (plain object wrapping 
class)
-  ├── utils/                      # Utilities (converted in Phase 3)
-  ├── features/                   # Features (converted in Phase 4)
-  └── types/
-      ├── index.ts                # Type exports
-      └── public-api.ts           # Public API contract (interface)
-```
-
-**Deliverables:**
-- ✅ Extension hooks API implemented and tested
-- ✅ Deprecated APIs replaced
-- ✅ Code splitting implemented
-- ✅ Final modular structure in place
-- ✅ All tests passing
-
----
-
-### Phase 7: Documentation + DX + Final Polish (Weeks 23-26)
-
-**PR 8** | Depends on: PR 7 (Phase 6) | Ticket: UNOMI-TRACKER-008
-
-Done last so documentation reflects the final API surface, including hooks, 
facade, and V4.0 support.
-
-#### 7.1 Documentation
-- Expand README with installation, usage, API reference, examples
-- Document V4.0 configuration (`apiKey`, `tenantId`)
-- Document extension hooks API with migration examples
-- Document public API contract and migration guide for consumers
-
-#### 7.2 Code Cleanup
-- Refactor duplicated code patterns (DRY)
-- Standardize function declaration styles (KISS)
-- Improve `_isObject` and other utility functions
-
-#### 7.3 Developer Experience
-- ESLint + Prettier with pre-commit hooks (Husky, lint-staged)
-- CI/CD pipeline with type checking, linting, coverage reporting
-
-**Deliverables:**
-- ✅ Comprehensive documentation (including V4.0 + hooks)
-- ✅ Duplicated code refactored
-- ✅ ESLint + Prettier + pre-commit hooks configured
-- ✅ CI/CD pipeline updated
-- ✅ All checks passing
-
----
-
-## Part 6: Implementation Guidelines
-
-### Engineering Principles
-
-All implementation work must follow these principles:
-
-**DRY (Don't Repeat Yourself)**
-- Extract shared logic into reusable utilities and functions
-- Eliminate duplicated patterns (e.g., duplicated context loading checks, 
repeated null guards)
-- Use parameterized functions instead of copy-paste variants
-- Single source of truth for configuration, constants, and type definitions
-
-**KISS (Keep It Simple, Stupid)**
-- Prefer simple, readable solutions over clever abstractions
-- Don't over-engineer the plugin/extension system -- start minimal, expand as 
needed
-- Each function should do one thing and be easy to understand
-- Avoid premature optimization -- measure first, optimize second
-
-**SOLID Principles**
-- **Single Responsibility**: Each module/file handles one concern (e.g., 
`cookies.ts` only manages cookies, `ajax.ts` only handles HTTP)
-- **Open/Closed**: The tracker is open for extension (hooks, plugins, 
overrides) but closed for modification (stable public API contract)
-- **Liskov Substitution**: Any wrapped or extended tracker instance must work 
wherever the base tracker is expected
-- **Interface Segregation**: Consumers import only what they need; modular 
exports prevent forced dependency on unused features
-- **Dependency Inversion**: Internal modules depend on abstractions 
(interfaces/types), not concrete implementations; the `ajax` function should be 
injectable/overridable
-
-### Testing First Approach
-
-**Critical Principle:** All code changes must have tests first.
-
-1. Write tests demonstrating current behavior (including bugs)
-2. Write tests for desired behavior
-3. Make code changes
-4. Verify tests pass
-5. Ensure no regressions
-
-### Backward Compatibility & Extensibility
-
-#### The Problem
-
-The current library exports a factory function `useTracker()` that returns a 
**plain mutable object** (`wem`) with ~50 methods and directly accessible 
state. There is no encapsulation -- all methods and properties (including those 
prefixed with `_`) are publicly accessible and mutable.
-
-Consumers who embed/extend the library may rely on any of these patterns:
-
-| Extension Pattern | Example | Risk Level |
-|-------------------|---------|------------|
-| **Monkey-patching methods** | `wem.ajax = myCustomAjax` | High |
-| **Adding custom methods** | `wem.myCustomTrack = function() {...}` | Medium |
-| **Direct state access** | `wem.cxs`, `wem.sessionID`, `wem.digitalData` | 
High |
-| **Overriding internals** | `wem._onSuccess = myHandler` | High |
-| **Wrapping the factory** | `const wem = useTracker(); wem.extra = ...` | 
Medium |
-| **DOM event listeners** | `document.addEventListener('wem.event', ...)` | 
Low |
-| **Callback system** | `digitalData.loadCallbacks`, `personalizationCallback` 
| Low |
-
-If we convert to a TypeScript class with private members and split code into 
modules, **all high-risk patterns break**.
-
-#### The Solution: Facade + Hooks Architecture
-
-The cleanest approach follows the **Open/Closed Principle**: keep the existing 
API surface stable while building clean internals underneath.
-
-**Layer 1: Internal Modules (new, clean)**
-```
-src/core/        → Clean TypeScript classes and functions
-src/utils/       → Pure utility functions
-src/features/    → Feature modules
-src/types/       → Type definitions and interfaces
-```
-
-**Layer 2: Facade Object (backward compatible)**
-```typescript
-// src/index.ts
-export const useTracker = () => {
-    const tracker = new UnomiTracker();  // Clean internal implementation
-
-    // The wem facade: a plain object that delegates to the internal tracker
-    // This preserves the exact same shape consumers expect
-    const wem = {
-        // --- Public state (directly accessible, as before) ---
-        get cxs() { return tracker.cxs; },
-        set cxs(v) { tracker.cxs = v; },
-        get digitalData() { return tracker.digitalData; },
-        get sessionID() { return tracker.sessionID; },
-        // ...
-
-        // --- Public methods (same signatures as before) ---
-        initTracker: (d) => tracker.initTracker(d),
-        startTracker: (o) => tracker.startTracker(o),
-        loadContext: (...args) => tracker.loadContext(...args),
-        collectEvent: (...args) => tracker.collectEvent(...args),
-        buildEvent: (...args) => tracker.buildEvent(...args),
-        ajax: (opts) => tracker.ajax(opts),
-        // ... all ~25 public methods ...
-
-        // --- "Private" methods (deprecated, with warnings) ---
-        _onSuccess: (...args) => {
-            console.warn('[WEM] _onSuccess is internal and may change. Use 
loadCallbacks instead.');
-            return tracker._onSuccess(...args);
-        },
-        // ... other _ methods with deprecation warnings ...
-    };
-
-    return wem;
-};
-```
-
-**Key properties of this approach:**
-- The returned `wem` object has the **exact same shape** as today
-- Methods can still be monkey-patched (the object is mutable)
-- State is still directly accessible via getters/setters
-- Internal implementation is clean TypeScript with proper encapsulation
-- `_` prefixed methods log deprecation warnings, guiding consumers to official 
APIs
-- Follows **Liskov Substitution**: the facade is a drop-in replacement
-
-**Layer 3: Extension Hooks (new, opt-in)**
-
-For consumers who need to extend behavior, provide official hooks instead of 
requiring monkey-patching:
-
-```typescript
-// Official extension points (Open/Closed Principle)
-wem.hooks = {
-    // Middleware for ajax requests (replaces monkey-patching wem.ajax)
-    beforeRequest: (callback) => tracker.addHook('beforeRequest', callback),
-    afterRequest: (callback) => tracker.addHook('afterRequest', callback),
-
-    // Context lifecycle hooks (replaces overriding _onSuccess)
-    onContextLoaded: (callback) => tracker.addHook('contextLoaded', callback),
-    onContextError: (callback) => tracker.addHook('contextError', callback),
-
-    // Event hooks (replaces overriding collectEvent)
-    beforeEvent: (callback) => tracker.addHook('beforeEvent', callback),
-    afterEvent: (callback) => tracker.addHook('afterEvent', callback),
-};
-```
-
-**Usage example for consumers who currently monkey-patch:**
-```javascript
-// BEFORE (fragile monkey-patching):
-const { wem } = useTracker();
-const originalAjax = wem.ajax;
-wem.ajax = function(options) {
-    options.headers = { ...options.headers, 'X-Custom': 'value' };
-    return originalAjax.call(this, options);
-};
-
-// AFTER (official hooks API):
-const { wem } = useTracker();
-wem.hooks.beforeRequest((options) => {
-    options.headers = { ...options.headers, 'X-Custom': 'value' };
-    return options;
-});
-```
-
-#### Migration Path for Consumers
-
-| Version | What Changes | Consumer Impact |
-|---------|-------------|-----------------|
-| **v1.5.x** (current) | Bug fixes + V4.0 support | None -- additive only |
-| **v1.6.x** | Internal refactoring behind facade | None -- same API shape |
-| **v1.7.x** | `_` methods log deprecation warnings | Warnings in console for 
internal method usage |
-| **v1.8.x** | Hooks API available | Consumers can migrate off monkey-patching 
|
-| **v2.0.0** | `_` methods removed, class-only export option | Breaking for 
consumers using `_` methods |
-
-This gives consumers **at least 3 minor versions** of warning before anything 
breaks.
-
-#### Formal Public API Contract
-
-To make this explicit, the public API surface is defined as:
-
-**Stable (guaranteed across v1.x):**
-- `useTracker()` factory function
-- All methods without `_` prefix (~25 methods)
-- State properties: `cxs`, `digitalData`, `sessionID`, `fallback`, `DOMLoaded`
-- `wemInitConfig` shape (additive changes only)
-- DOM events dispatched by `dispatchJSEvent`
-- Callback system: `loadCallbacks`, `personalizationCallback`
-
-**Internal (may change with deprecation notice):**
-- All `_` prefixed methods (~15 methods)
-- Internal state: `contextLoaded`, `eventsPrevented`, `formNamesToWatch`
-
-### Versioning Strategy
-
-- **v1.5.x**: Current version + bug fixes + V4.0 support
-- **v1.6.x-v1.8.x**: Internal modernization behind facade, hooks API
-- **v2.0.0**: Future major version (can remove deprecated `_` methods, 
class-only export)
-
----
-
-## Part 7: Success Metrics
-
-### Code Quality
-- [ ] All code follows DRY, KISS, and SOLID principles
-- [ ] 80%+ TypeScript coverage
-- [ ] 0 `@ts-expect-error` comments (or documented)
-- [ ] 80%+ test coverage
-- [ ] All ESLint rules passing
-- [ ] No duplicated logic patterns
-
-### Performance
-- [ ] Bundle size maintained or reduced
-- [ ] Build time improved (target: 50% faster)
-- [ ] Runtime performance maintained
-
-### Compatibility
-- [ ] All existing tests pass
-- [ ] No breaking changes in public API
-- [ ] All output formats work (CJS, ESM, UMD)
-- [ ] Tracker works with Unomi V2 (no API key configured)
-- [ ] Tracker works with Unomi V4.0 (API key configured)
-- [ ] Tracker works with Unomi V4.0 in V2 compatibility mode
-
-### Extensibility
-- [ ] Facade preserves exact `wem` object shape for consumers who extend/embed
-- [ ] Monkey-patching still works on the facade object
-- [ ] Direct state access (`wem.cxs`, `wem.sessionID`) still works
-- [ ] Hooks API available for clean extensibility
-- [ ] `_` prefixed methods log deprecation warnings (not removed until v2.0)
-- [ ] Public API contract documented and tested
-
----
-
-## Part 8: Quick Wins (Can Start Immediately)
-
-1. **Set up Vitest and MSW** ⭐ START HERE
-2. **Create bug verification tests**
-3. **Fix critical bugs** (after tests are in place)
-4. **Upgrade es6-crawler-detect to v4** (has types)
-5. **Set up ESLint for TypeScript**
-
----
-
-## Appendix: Test Examples
-
-### Bug Verification Test
-The bugs are fixed (UNOMI-1037, UNOMI-1038); their tests are in 
`test/servers/tracker.spec.js` and `test/spec.js`.
-
-### Server Mock Examples
-
-#### V2 Mode (no authentication)
-```typescript
-// test/mocks/handlers-v2.ts
-import { http, HttpResponse } from 'msw';
-
-export const v2Handlers = [
-  http.post('*/context.json', () => {
-    return HttpResponse.json({
-      profileId: 'test-profile-123',
-      sessionId: 'test-session-456',
-    });
-  }),
-  http.post('*/eventcollector', () => {
-    return HttpResponse.json({ eventsProcessed: 1 });
-  })
-];
-```
-
-#### V4.0 Mode (API key authentication)
-```typescript
-// test/mocks/handlers-v3.ts
-import { http, HttpResponse } from 'msw';
-
-const VALID_API_KEY = 'test-public-api-key-123';
-
-export const v3Handlers = [
-  http.post('*/context.json', ({ request }) => {
-    const apiKey = request.headers.get('X-Unomi-Api-Key');
-    if (!apiKey || apiKey !== VALID_API_KEY) {
-      return new HttpResponse('Unauthorized', { status: 401 });
-    }
-    return HttpResponse.json({
-      profileId: 'test-profile-123',
-      sessionId: 'test-session-456',
-    });
-  }),
-  http.post('*/eventcollector', ({ request }) => {
-    const apiKey = request.headers.get('X-Unomi-Api-Key');
-    if (!apiKey || apiKey !== VALID_API_KEY) {
-      return new HttpResponse('Unauthorized', { status: 401 });
-    }
-    return HttpResponse.json({ eventsProcessed: 1 });
-  })
-];
-```
-
----
-
-**Document Version:** 1.3  
-**Last Updated:** January 2026  
-**Changelog:**
-- v1.3 - Restructured into 8 linear phases for stacked PR workflow; aligned 
phase/ticket numbering
-- v1.2 - Added extensibility/compatibility layer strategy (facade + hooks), 
DRY/KISS/SOLID principles, public API contract
-- v1.1 - Added Unomi V4.0 multi-tenancy compatibility analysis and plan
diff --git a/README.md b/README.md
index 97b7c4d..f7f76c9 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,7 @@ Apache Unomi tracker
 - [Apache Unomi website](https://unomi.apache.org)
 - [Apache Unomi Documentation](https://unomi.apache.org/manual/latest/)
 - [Versioning and release process](RELEASE.md)
+- [Release notes](CHANGES.md)
 
 A JavaScript tracker library for Apache Unomi.
 
@@ -31,6 +32,9 @@ yarn add apache-unomi-tracker
 
 Unomi also ships this tracker, repackaged, at 
`/tracker/unomi-web-tracker.min.js` on the server.
 
+A page can also load the browser build (`dist/apache-unomi-tracker.umd.js`) 
directly; it defines
+`window['apache-unomi-tracker']` and needs no polyfill.
+
 Usage
 -----
 ```javascript
@@ -125,7 +129,7 @@ Options in `wemInitConfig`:
 | Option | Default | Description |
 |---|---|---|
 | `contextServerUrl` | | Unomi server root URL, for example 
`https://cdp.example.com`, without `/cxs`: the tracker calls `/context.json` 
and `/eventcollector` there |
-| `timeoutInMilliseconds` | | Request timeout; `-1` for none |
+| `timeoutInMilliseconds` | `1500` | Request timeout: a positive number of 
milliseconds (a string such as `'3000'` works too), or `-1` for none. Any other 
value (missing, `0`, a blank string) uses the default |
 | `contextServerCookieName` | | Name of the profile cookie set by the server 
(`context-profile-id` on a default server) |
 | `activateWem` | | Whether the tracker is active |
 | `trackerSessionIdCookieName` | `wem-session-id` | Cookie holding the session 
ID |
@@ -137,6 +141,39 @@ Options in `wemInitConfig`:
 | `requiredProfileProperties`, `requiredSessionProperties` | | Properties to 
return in the context |
 | `requireSegments`, `requireScores` | | Return the profile segments and 
scores in the context |
 
+Tracking clicks and forms
+-------------------------
+The tracker sends a click event for the links and buttons whose clicks Unomi 
tracks (rules with a
+`clickOnLinkEventCondition`), and for the elements a site passes to 
`sendClickEvent`. It sends a
+form event for the forms Unomi tracks (rules with a `formEventCondition`). It 
does not change what
+the visitor's click or submit does:
+
+- A click that leaves the page (a link, a button that submits its form) waits 
until its event is
+  sent, or could not be, then goes on. Without a timeout (`-1`), it waits 1.5s 
at most.
+- Other clicks do not wait: buttons that stay on the page, links that open 
another tab or window,
+  downloads, `#` and `javascript:` links, clicks with Ctrl, Cmd, Shift or Alt 
(unless a callback
+  is given, see below), and clicks the site already handled 
(`preventDefault()`, as single-page
+  application routers do). The site's own click handlers run once per click, 
and routers handle
+  tracked links as usual.
+- A click on an image, an icon or some text inside a tracked element is sent 
on the tracked
+  element.
+- With callbacks, `sendClickEvent(event, onSent, onNotSent)` calls one of them 
once the event is
+  sent, or could not be; for a click that leaves the page, the site then 
handles it in the callback.
+  When tracking is off, or Unomi could not be reached, nothing is sent and 
neither callback is
+  called: the click goes on as if the tracker were not there.
+- A tracked form waits for its event, then is submitted as a native submit 
would be: the site's
+  submit handlers run once, and the button that was used is sent with the 
form. Forms that open in
+  another tab or window, and submits the site already handled, do not wait.
+- When Unomi could not be reached, or tracking is turned off, nothing is sent 
and clicks and forms
+  are left alone.
+
+Supported browsers
+------------------
+Current versions of Chrome, Edge, Firefox and Safari. The tests run in 
Chromium, Firefox and
+WebKit, and in Safari on macOS; mobile browsers are not tested. Like 1.x, the 
tracker needs a browser with
+ES2015 support; in browsers without `HTMLFormElement.requestSubmit` (Safari 
before 16), tracked
+forms are submitted another way, with the same data.
+
 Versions
 --------
 | Tracker | Unomi servers | Branch |
@@ -146,11 +183,23 @@ Versions
 
 Upgrading from 1.x
 ------------------
-Version 2.0 is a drop-in replacement: the same configuration sends the same 
requests, so a site that works with 1.x keeps working with the same Unomi 
server.
+Version 2.0 is a drop-in replacement: the same configuration works with the 
same Unomi server, and
+sends the same context requests. A site needs no change.
 
+New:
 - To use a Unomi 4 multi-tenant server, set `apiKey` (see above).
-- The package now ships TypeScript types (`dist/apache-unomi-tracker.d.ts`). 
The configurations shown here and in the Unomi manual compile with them. A 
project that declared its own types for `apache-unomi-tracker` can remove them.
 - New option `sendCredentials`, see above.
+- The package now ships TypeScript types (`dist/apache-unomi-tracker.d.ts`). 
The configurations shown here and in the Unomi manual compile with them. A 
project that declared its own types for `apache-unomi-tracker` can remove them.
+
+What a site may notice, all fixes (see [CHANGES.md](CHANGES.md) for the 
details):
+- The browser build works without a `Buffer` polyfill. With 1.5.0 and earlier, 
a page loading it directly got no tracking.
+- An empty page `attributes` is no longer sent, so the page views and clicks 
of sites set up with an older example from the Unomi manual are stored again 
(Unomi 2.4 and later rejected them).
+- Every click on a tracked element is sent: 1.x only sent the first click on 
each element.
+- A click on a child of a tracked element (an image, an icon, some text) is 
sent on the tracked element, where 1.x sent nothing, or an event on the child.
+- Clicks that do not leave the page are no longer held back, so the site's own 
click handlers run once per click (they ran twice).
+- Links and forms keep working when Unomi cannot be reached, when it never 
answers and there is no timeout, and when tracking is turned off; Ctrl or 
Cmd+click opens a new tab again.
+- A tracked form is submitted with the button that was used, also a button 
named `submit`.
+- A configuration without a usable `timeoutInMilliseconds` now tracks; with 
1.x, every request failed at once.
 
 Using an unreleased version
 ---------------------------
@@ -164,7 +213,8 @@ Releases of other projects must depend on a released 
version instead.
 Testing
 -------
 - `yarn test`: unit tests, and a check that the documented configurations 
compile against the TypeScript types
-- `yarn test:servers`: browser tests against Unomi 2.x, 3.x and 4.x started 
with Docker; Unomi 3 and 4 must pass on every pull request, in Chromium, 
Firefox and WebKit, see [test/servers](test/servers/README.md)
+- `yarn test:servers`: browser tests against Unomi 2.x, 3.x and 4.x started 
with Docker; Unomi 3 and 4 must pass on every pull request, in Chromium, 
Firefox and WebKit (`TRACKER_BROWSERS`), see 
[test/servers](test/servers/README.md)
+- `yarn test:safari`: the same questions in the real Safari of a Mac, against 
a simulated Unomi (no Docker)
 
 License
 -------
diff --git a/RELEASE.md b/RELEASE.md
index 72d37bb..b5b5539 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -15,52 +15,150 @@
   ~ limitations under the License.
   -->
 
-Unomi tracker: Versioning and release
-============
-
-Branches
--------
-Current repository is using Trunk based development.
-
-- `main`: Used for latest currently develop version
-- `1_x`: Used for maintenance branches of previous versions
-- `UNOMI-XXX`: feature or bug fix branches used to create pull request 
targeting the `main` branch
-
-Release example for 1.1.0
--------
-Checks before starting the release process:
-- Check headers and licenses
-- Check your GPG configuration is correct ! it will be required for signing 
the package.
-  - Follow: https://infra.apache.org/release-signing.html
-  - And: https://unomi.apache.org/contribute/release-guide.html
-- Check that you are logged into npm and you have permission to publish the 
package:
-  - Create an account on NpmJS registry: https://www.npmjs.com/
-  - Ask on Apache Unomi dev mailing list ([email protected]) to be added 
as a maintainer for the package to be able to push versions
-  - Login locally: `npm login` and your credentials
-- Do a final local check:
-  - `yarn lint`: ensure linter checks are passing
-  - `yarn test`: ensure tests are passing
-  - `yarn build`: ensure build is passing
-  - `yarn test:servers`: ensure the tracker works with every supported Unomi 
version (needs Docker, see [test/servers](test/servers/README.md))
-
-Start the release process:
-- Check version and create Git tag:
-  - Check `package.json` is using correct version: `1.1.0`
-  - Create Git tag: `git tag -s v1.1.0 -m 'create v1.1.0 tag'` (`-s` is used 
for signing using your local git GPG config)
-  - Push the tag: `git push origin v1.1.0`
-- Sign the package and upload the package to Apache SVN. 
-  - Download the `.tar.gz` source package from Git previously created tag.
-  - Sign the package: `gpg -ab unomi-tracker-1.1.0.tar.gz`.
-  - Verify the signature: `gpg --verify unomi-tracker-1.1.0.tar.gz.asc 
unomi-tracker-1.1.0.tar.gz` (Check that the signature is correctly using your 
Apache signature)
-  - SHA the package: `shasum -a 512 unomi-tracker-1.1.0.tar.gz > 
unomi-tracker-1.1.0.tar.gz.sha512`
-  - Upload the 3 files (`.tar.gz`, `.tar.gz.asc`, `.tar.gz.sha512`) to Apache 
SVN: `https://dist.apache.org/repos/dist/dev/unomi/unomi-tracker/1.1.0`
-    (Create the folder if it doesn't exist)
-- Start voting process, follow Unomi documentation it's the same: 
https://unomi.apache.org/contribute/release-guide.html
-- Wait for the vote to finnish then finalize the release on Apache side:
-  - move `https://dist.apache.org/repos/dist/dev/unomi/unomi-tracker/1.1.0` to 
`https://dist.apache.org/repos/dist/release/unomi/unomi-tracker/1.1.0`
-  - in JIRA mark the version `unomi-tracker-1.1.0` as released and add a 
release date
-- Publish the release package to NPM:
-  - Download the Apache released package: 
`https://dist.apache.org/repos/dist/release/unomi/unomi-tracker/1.1.0/unomi-tracker-1.1.0.tar.gz`
-  - Untar the package and publish it by running `yarn install 
--frozen-lockfile`, then `npm publish`.
-    `npm publish` builds `dist` from the released sources first (the `prepare` 
script), so the dependencies must be installed.
-- You can set the next version into `package.json` like `1.2.0` for example.
\ No newline at end of file
+Unomi tracker: versioning and release
+=====================================
+
+Branches and versions
+---------------------
+- `main`: the 2.x line, for Unomi 2.x, 3.x and 4.x.
+- `1_x`: the 1.x line, for Unomi 2.x and 3.x; fixes only.
+- `UNOMI-XXX`: a branch for one JIRA ticket, merged with a pull request.
+
+Each release has a JIRA version, `unomi-tracker-X.Y.Z`, and a tag, `vX.Y.Z`. A 
fix for both lines
+has both fix versions, and a pull request on each branch. Below, `X.Y.Z` is 
the version being
+released, for example `2.0.0`.
+
+Before the release
+------------------
+- In JIRA, every ticket with the fix version `unomi-tracker-X.Y.Z` is 
resolved, or moved to a later
+  version.
+- `CHANGES.md` has the release notes of `X.Y.Z`, and the README is up to date 
("Upgrading from 1.x"
+  for a 2.x release).
+- `NOTICE` has the current year.
+- The licensing is right 
(https://www.apache.org/legal/release-policy.html#licensing):
+  `LICENSE` and `NOTICE` describe exactly what each package contains. The 
source package has
+  `LICENSE` (the Apache License). The npm package bundles third-party code in 
its browser build, so
+  it has `LICENSE-binary` as its `LICENSE`, which also lists those components 
(`npm pack` puts it in
+  place, see `scripts/npm-license.js`; `yarn test` checks that it matches the 
build). Every bundled
+  component has a license of category A 
(https://www.apache.org/legal/resolved.html).
+- Every source file has the ASF license header. This lists the files without 
it (the result must
+  be empty):
+  ```shell
+  git ls-files -- '*.js' '*.ts' '*.md' '*.html' '*.yml' '*.yaml' 
':!:.github/*' | xargs grep -L "Licensed to the Apache Software Foundation"
+  ```
+- Your signing key: an RSA key of at least 2048 bits (4096 recommended) with 
your @apache.org
+  address, on your own machine (never on an ASF machine), published on a key 
server
+  (keys.openpgp.org), and in the `KEYS` files: in this repository, and in the 
distribution
+  directory, https://dist.apache.org/repos/dist/dev/unomi/KEYS and
+  https://dist.apache.org/repos/dist/release/unomi/KEYS (the one voters and 
users check, served as
+  https://downloads.apache.org/unomi/KEYS). See 
https://infra.apache.org/release-signing.html and
+  https://unomi.apache.org/contribute/release-guide.html
+- You can publish to npm: an account on https://www.npmjs.com/, added as a 
maintainer of
+  `apache-unomi-tracker` (ask on [email protected]), and `npm login`.
+- The checks pass on the commit to release:
+  - CI (all the required checks of the pull requests, `.asf.yaml`)
+  - `yarn install --frozen-lockfile`, `yarn lint`, `yarn test`
+  - `TRACKER_BROWSERS=chromium,firefox,webkit yarn test:servers`: the 
comparison with 1.5.0 and
+    every Unomi server, in the three browsers (Docker, see 
[test/servers](test/servers/README.md))
+  - `yarn test:safari` on a Mac, with Safari visible
+
+The release candidate
+---------------------
+- `package.json` has the version `X.Y.Z`.
+- Tag and push: `git tag -s vX.Y.Z -m 'Release X.Y.Z'` (signed with your GPG 
key), then
+  `git push origin vX.Y.Z`.
+- The source package, from the tag:
+  ```shell
+  git archive --format=tar.gz --prefix=unomi-tracker-X.Y.Z/ -o 
unomi-tracker-X.Y.Z.tar.gz vX.Y.Z
+  gpg -ab unomi-tracker-X.Y.Z.tar.gz
+  gpg --verify unomi-tracker-X.Y.Z.tar.gz.asc unomi-tracker-X.Y.Z.tar.gz
+  shasum -a 512 unomi-tracker-X.Y.Z.tar.gz > unomi-tracker-X.Y.Z.tar.gz.sha512
+  ```
+  Check that the signature uses your Apache key.
+- Check the package as voters will: untar it, then `yarn install 
--frozen-lockfile`, `yarn test`,
+  and `npm pack` (it builds `dist`; the package has `dist`, `NOTICE`, `KEYS`, 
and as `LICENSE` the
+  content of `LICENSE-binary`).
+- Upload the three files to 
https://dist.apache.org/repos/dist/dev/unomi/unomi-tracker/X.Y.Z/
+  (create the folder).
+
+The vote
+--------
+Send the vote to [email protected]; it lasts at least 72 hours, and needs 
at least three +1
+votes from PMC members (binding), and more binding +1 than -1 votes
+(https://www.apache.org/legal/release-policy.html#release-approval). Before a 
+1, voters download
+the package to their own machine, check its signature and checksum, its 
licensing, and build and
+test it there. For example:
+
+```
+Subject: [VOTE] Release Apache Unomi tracker X.Y.Z
+
+Hi all,
+
+I would like to release Apache Unomi tracker X.Y.Z, the JavaScript tracker for 
Apache Unomi.
+<One or two sentences on what the release brings, from CHANGES.md.>
+
+Release notes:
+https://github.com/apache/unomi-tracker/blob/vX.Y.Z/CHANGES.md
+JIRA: 
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12319220&version=<version
 id>
+
+Source package, signature and checksum:
+https://dist.apache.org/repos/dist/dev/unomi/unomi-tracker/X.Y.Z/
+
+Tag: https://github.com/apache/unomi-tracker/releases/tag/vX.Y.Z (commit <sha>)
+
+Signing keys: https://downloads.apache.org/unomi/KEYS
+
+To check the package, on your own machine:
+  gpg --import KEYS
+  gpg --verify unomi-tracker-X.Y.Z.tar.gz.asc unomi-tracker-X.Y.Z.tar.gz
+  shasum -a 512 -c unomi-tracker-X.Y.Z.tar.gz.sha512
+then untar it, check LICENSE and NOTICE, and run yarn install 
--frozen-lockfile, yarn test and
+npm pack --dry-run. The tests against Unomi servers need Docker: yarn 
test:servers.
+
+The vote is open for at least 72 hours.
+
+[ ] +1 Release this package as Apache Unomi tracker X.Y.Z
+[ ] +0 No opinion
+[ ] -1 Do not release this package because...
+
+Thanks,
+<name>
+```
+
+Send the result to the same list, with `[RESULT][VOTE]` in the subject, and 
the votes counted
+(binding and non-binding). If the vote fails, delete the tag, fix the 
problems, and start again with
+a new release candidate.
+
+After the vote
+--------------
+- Move the release: `svn mv 
https://dist.apache.org/repos/dist/dev/unomi/unomi-tracker/X.Y.Z
+  https://dist.apache.org/repos/dist/release/unomi/unomi-tracker/X.Y.Z -m 
"Apache Unomi tracker X.Y.Z
+  release"` (a PMC member does it). Then remove the previous release of the 
same line from
+  `dist/release`: it stays on 
https://archive.apache.org/dist/unomi/unomi-tracker/, and
+  `dist/release` keeps only the latest release of each line still maintained.
+- In JIRA, mark `unomi-tracker-X.Y.Z` as released, with the date, and record 
the release on
+  https://reporter.apache.org/addrelease.html?unomi
+- Publish to npm, from the released package:
+  ```shell
+  curl -O 
https://dist.apache.org/repos/dist/release/unomi/unomi-tracker/X.Y.Z/unomi-tracker-X.Y.Z.tar.gz
+  tar xzf unomi-tracker-X.Y.Z.tar.gz && cd unomi-tracker-X.Y.Z
+  yarn install --frozen-lockfile
+  npm publish
+  ```
+  `npm publish` builds `dist` from the released sources first (the `prepare` 
script), so the
+  dependencies must be installed. For a 1.x release once 2.x is published, use
+  `npm publish --tag latest-1`, so that `npm install apache-unomi-tracker` 
keeps installing 2.x.
+- Wait at least one hour after the move, so that https://downloads.apache.org 
has the release,
+  then update the Unomi download page 
(https://unomi.apache.org/download.html): in the
+  `unomi-site` repository, set `tracker.latest` (version, date, JIRA version 
id) in
+  `src/main/webapp/_data/unomi.yml`. The page then links to the source package 
through
+  
`https://www.apache.org/dyn/closer.lua/unomi/unomi-tracker/X.Y.Z/unomi-tracker-X.Y.Z.tar.gz`,
 its
+  signature and checksum on 
`https://downloads.apache.org/unomi/unomi-tracker/X.Y.Z/`, and KEYS;
+  older releases are on the archive.
+- Then announce the release on [email protected], [email protected] 
and [email protected],
+  from your apache.org address (announce@ only accepts that): a short 
description of the tracker,
+  what the release brings, and a link to the download page. Signing the email 
with your PGP key is
+  recommended.
+- Update the tracker that Unomi bundles 
(`extensions/web-tracker/wab/package.json` in
+  https://github.com/apache/unomi) to the released version.
+- Set the next version in `package.json`, for example `2.1.0`.
diff --git a/package.json b/package.json
index 3db8840..ee221bd 100644
--- a/package.json
+++ b/package.json
@@ -20,7 +20,9 @@
   "scripts": {
     "build": "rollup -c && tsc",
     "prepare": "npm run build",
-    "test": "node test/spec && tsc -p test/types",
+    "prepack": "npm run build && node scripts/npm-license.js use-binary",
+    "postpack": "node scripts/npm-license.js restore",
+    "test": "node test/spec && node scripts/npm-license.js check && tsc -p 
test/types",
     "test:servers": "node test/servers/run.js",
     "test:safari": "node test/servers/safari.js",
     "pretest": "yarn run build",
diff --git a/rollup.config.js b/rollup.config.js
index e06a9e4..352c31a 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -21,6 +21,20 @@ import babel from '@rollup/plugin-babel';
 import license from 'rollup-plugin-license';
 import pkg from './package.json';
 import * as path from 'path';
+import * as fs from 'fs';
+
+// The browser build bundles third-party code: its header names it, with its 
license (the npm package's
+// LICENSE-binary lists it too, see scripts/npm-license.js)
+// eslint-disable-next-line no-undef
+const header = fs.readFileSync(path.join(__dirname, 'LICENSE_HEADER'), 
'utf8').trim();
+const bundledHeader = header + `
+
+This file also contains code from the following packages, under their own 
licenses:
+<% _.forEach(_.sortBy(dependencies, 'name'), function (dependency) { %>
+<%= dependency.name %> <%= dependency.version %> (<%= dependency.license %>)
+
+<%= dependency.licenseText.replace(/\\r\\n/g, '\\n').trim() %>
+<% }) %>`;
 
 export default [
     {
@@ -35,10 +49,7 @@ export default [
             license({
                 banner: {
                     commentStyle: 'regular',
-                    content: {
-                        // eslint-disable-next-line no-undef
-                        file: path.join(__dirname, 'LICENSE_HEADER')
-                    }
+                    content: bundledHeader
                 }
             }),
             resolve(),
diff --git a/scripts/npm-license.js b/scripts/npm-license.js
new file mode 100644
index 0000000..9d43c25
--- /dev/null
+++ b/scripts/npm-license.js
@@ -0,0 +1,110 @@
+/*
+ * 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.
+ */
+
+/* eslint-env node */
+
+// The LICENSE of the npm package. Its browser build bundles third-party code 
that the source package
+// does not contain, and ASF policy wants each package's LICENSE to describe 
exactly what the package
+// contains (https://www.apache.org/legal/release-policy.html#licensing). So 
the source package has
+// LICENSE (the Apache License), and the npm package LICENSE-binary (the 
Apache License and the
+// bundled components), which npm pack puts in place of LICENSE.
+//
+//   node scripts/npm-license.js generate     writes LICENSE-binary from the 
build (dist)
+//   node scripts/npm-license.js check        fails if LICENSE-binary does not 
match the build
+//   node scripts/npm-license.js use-binary   before npm pack: LICENSE-binary 
becomes LICENSE
+//   node scripts/npm-license.js restore      after npm pack: LICENSE again
+const fs = require('fs');
+const path = require('path');
+
+const root = path.join(__dirname, '..');
+const LICENSE = path.join(root, 'LICENSE');
+const LICENSE_BINARY = path.join(root, 'LICENSE-binary');
+// Where LICENSE waits while npm packs the package (not in the package: 
"files" does not list it)
+const LICENSE_SOURCE = path.join(root, '.LICENSE-source');
+const BUNDLE = 'dist/apache-unomi-tracker.umd.js';
+
+// The third-party packages the browser build contains, from its source map: 
name, version,
+// license and license text, sorted by name
+function bundledPackages() {
+    const map = JSON.parse(fs.readFileSync(path.join(root, BUNDLE + '.map'), 
'utf8'));
+    const names = new Set(map.sources
+        .filter(source => source.includes('node_modules/'))
+        .map(source => {
+            const parts = source.split('node_modules/').pop().split('/');
+            return parts[0].startsWith('@') ? parts[0] + '/' + parts[1] : 
parts[0];
+        }));
+    return [...names].sort().map(name => {
+        const directory = path.join(root, 'node_modules', name);
+        const pkg = JSON.parse(fs.readFileSync(path.join(directory, 
'package.json'), 'utf8'));
+        const licenseFile = fs.readdirSync(directory).find(file => 
/^licen[cs]e/i.test(file));
+        if (!licenseFile) {
+            throw new Error(name + ' has no license file');
+        }
+        return {
+            name,
+            version: pkg.version,
+            license: pkg.license,
+            text: fs.readFileSync(path.join(directory, licenseFile), 
'utf8').replace(/\r\n/g, '\n').trim()
+        };
+    });
+}
+
+function binaryLicense() {
+    const apache = fs.readFileSync(LICENSE, 'utf8').replace(/\s+$/, '');
+    const lines = [
+        apache,
+        '',
+        '',
+        
'------------------------------------------------------------------------------------',
+        'APACHE UNOMI TRACKER SUBCOMPONENTS',
+        '',
+        'The npm package of Apache Unomi tracker contains, in its browser 
build',
+        '(' + BUNDLE + ' and ' + BUNDLE + '.map), the following',
+        'components, under the licenses below. The other files of the package 
are under the',
+        'Apache License 2.0 above.'
+    ];
+    for (const pkg of bundledPackages()) {
+        lines.push('', '', pkg.name + ' ' + pkg.version + ' (' + pkg.license + 
')', '', pkg.text);
+    }
+    return lines.join('\n') + '\n';
+}
+
+const command = process.argv[2];
+if (command === 'generate') {
+    fs.writeFileSync(LICENSE_BINARY, binaryLicense());
+    console.log('LICENSE-binary: ' + bundledPackages().map(pkg => pkg.name + ' 
' + pkg.version).join(', '));
+} else if (command === 'check' || command === 'use-binary') {
+    if (fs.existsSync(LICENSE_SOURCE)) {
+        throw new Error('.LICENSE-source exists: a previous npm pack did not 
finish. Run `node scripts/npm-license.js restore` first');
+    }
+    if (!fs.existsSync(LICENSE_BINARY) || fs.readFileSync(LICENSE_BINARY, 
'utf8') !== binaryLicense()) {
+        console.error('LICENSE-binary does not match the browser build (' + 
bundledPackages().map(pkg => pkg.name + ' ' + pkg.version).join(', ') +
+            '). Run `node scripts/npm-license.js generate` and commit it.');
+        process.exit(1);
+    }
+    if (command === 'use-binary') {
+        fs.renameSync(LICENSE, LICENSE_SOURCE);
+        fs.copyFileSync(LICENSE_BINARY, LICENSE);
+    }
+} else if (command === 'restore') {
+    if (fs.existsSync(LICENSE_SOURCE)) {
+        fs.renameSync(LICENSE_SOURCE, LICENSE);
+    }
+} else {
+    console.error('Usage: node scripts/npm-license.js 
generate|check|use-binary|restore');
+    process.exit(2);
+}
diff --git a/src/global.d.ts b/src/global.d.ts
index 3de3d87..cc3175b 100644
--- a/src/global.d.ts
+++ b/src/global.d.ts
@@ -1,3 +1,20 @@
+/*
+ * 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.
+ */
+
 declare namespace globalThis {
   // Help TypeScript with this object only available in IE 8-11
   let XDomainRequest = XMLHttpRequest;
diff --git a/src/types.ts b/src/types.ts
index 10796a5..581c509 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,3 +1,20 @@
+/*
+ * 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.
+ */
+
 export interface DigitalData {
   scope: string;
   site: {

Reply via email to