diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4cc2948a..67f6e793 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,10 @@ on: push: branches: [main] pull_request: + # Weekly, so a new major of a peer that the README installs unpinned fails + # here before a customer's install does. + schedule: + - cron: '17 13 * * 1' # A newer commit on the same PR cancels the older run; each push to main keeps # its own run. @@ -36,3 +40,18 @@ jobs: - run: npm test -- --ci # scripts/validate-ios.sh compiles the native module inside a local Expo # app; it stays a manual pre-release step. + + install-lines: + # The README install lines, resolved with npm's strict peer rules against + # today's published versions. `test` above installs with + # --legacy-peer-deps and so cannot see a peer conflict. Lockfile only: no + # node_modules, no app build. + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - name: README install lines resolve without peer conflicts + run: node scripts/check-install-lines.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4abe0d55..91bea0ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,9 @@ All notable changes to the Datalyr React Native SDK will be documented in this f The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## Unreleased +## [1.9.0] - 2026-11-25 -Ships as a minor version (1.9.0). Read the install change below before upgrading. +Minor version. Read the install change below before upgrading. ### Added - `Datalyr.getPlayInstallReferrer()` on the bare React Native static facade (the instance and the Expo facade already had it). @@ -15,7 +15,7 @@ Ships as a minor version (1.9.0). Read the install change below before upgrading ### Changed - `uuid` is now `^11.1.1` (was `^10.0.0`). This clears the one production advisory. The SDK only uses `v4()`; ids keep the same format. `@types/uuid` is gone, since uuid 11 ships its own types. -- The Expo modules the SDK loads are now declared as optional peer dependencies: `expo-application`, `expo-device`, `expo-network`, `expo-router`, `expo` and `@expo/config-plugins` (Expo SDK 52 or later, the same floor as `expo-modules-core`). Your package manager now warns about a version it cannot work with. Nothing is installed for you. The unused `expo-tracking-transparency` entry is removed. +- The Expo modules the SDK loads are now declared as optional peer dependencies: `expo-application`, `expo-device`, `expo-network`, `expo` and `@expo/config-plugins` (Expo SDK 52 or later, the same floor as `expo-modules-core`). Your package manager now warns about a version it cannot work with. Nothing is installed for you. The unused `expo-tracking-transparency` entry is removed. `expo-router` is not declared: npm checks an optional peer against its newest version even when it is not installed, and expo-router's own peers then conflict with an older Expo SDK (`ERESOLVE`). The SDK loads it only when you use the Expo Router screen-tracking hook. - `debug: true` now turns on the SDK's debug logs in a release build. Before, they printed only in a development build (`__DEV__`) and the option did nothing else. - SKAdNetwork and AdAttributionKit success messages, and failed Apple Search Ads, advertiser-info and Play Install Referrer lookups in the native bridge, now log only when debug logging is on (`__DEV__` or `debug: true`). Warnings for a missing native module and failed SKAdNetwork updates are unchanged. - iOS: `setPostbackEnvironment` no longer writes an `NSLog` line; the JS side logs the result when debug logging is on. @@ -33,6 +33,10 @@ Ships as a minor version (1.9.0). Read the install change below before upgrading - Internal code that was never called: the private deferred deep link handlers in both entry points, the unused `src/utils-interface.ts` (not exported) and a commented-out AppState block. ### Fixed +- Expo: an app without `expo-router` can now bundle `@datalyr/react-native/expo`. The entry's lazy `require('expo-router')` had no try/catch, so Metro could not treat it as optional and stopped with `Unable to resolve module expo-router` (also in 1.8.0). Now only `useDatalyrScreenTracking()` needs expo-router, and without it the hook throws a clear error. +- iOS: the SDK now chooses the host for each event when it sends it, not when it builds it. An event goes to `tracking.datalyr.com` (the tracking domain in the SDK's privacy manifest) only when it carries the advertising id (IDFA) and tracking is allowed at send time (and was already allowed when the app started; see the next point). Otherwise it goes to the normal host, with `idfa` and `alart` removed and `att_status` / `advertiser_tracking_enabled` set to the status at send time. If the tracking host cannot be reached or answers an HTTP error twice in a row for one event, that event is sent to the normal host without its IDFA, and other IDFA events then skip the tracking host for 10 minutes. So an event built while tracking was allowed can no longer hold the queue after tracking is turned off. Android is unchanged. +- iOS: after the user allows tracking, the advertising id is sent from the next app launch. In the launch where the user taps Allow, events go to the normal host at once without it (`att_status` still reads 3). On the next launch the SDK sends `$att_status` once (`resent: true`) with the IDFA, under one fixed event id per grant, so a kill during that launch cannot count it twice. `alart` without an IDFA follows the same rule: tracking host or removed, never on the normal host. +- Why: in apps where iOS enforces tracking domains, requests to `tracking.datalyr.com` are refused until tracking is allowed and the app has started again. iOS enforces the list in the app's Info.plist. Xcode copies an SDK's list there for a Swift package. It does not copy this SDK's list, which CocoaPods installs as a resource bundle. So in a React Native or Expo app the host is refused only if the app lists it in its own Info.plist. The rules above deliver events in both cases. - Events are no longer dead-lettered by a server outage. A 5xx (503 included), 429, 408, a timeout or a network error keeps the event in the queue with the same `eventId`, uses none of its retry budget, and backs the whole queue off (5 s doubling to 5 minutes with 0.5x to 1.0x jitter; never sooner than the server's `Retry-After`, honoured up to 10 minutes, plus 0 to 25% jitter). Before, three failed flushes (about 1 to 2 minutes of 5xx or 429) moved events to the dead-letter store, and a timeout (`Aborted`) was not recognised as a connectivity failure. - `Retry-After` is now honoured on 5xx answers (ingest answers 503 with `Retry-After` when the fault is its own), not only on 429 and 408. A `Retry-After` longer than 30 s is no longer cut short in-request. - Any 2xx is a delivered event, whatever its body. Ingest answers 204 with no body for a filtered event; that used to count as a failed send and re-send the event. @@ -41,12 +45,16 @@ Ships as a minor version (1.9.0). Read the install change below before upgrading - When a flush stops on a temporary failure, the events it already delivered are removed from disk at once. ### Install change -- `@react-native-async-storage/async-storage` (1.17 or later, or 2.x) and `react-native-get-random-values` are now peer dependencies, not dependencies. Install them in your app: - - Bare React Native: `npm install @datalyr/react-native expo-modules-core @react-native-async-storage/async-storage@^2 react-native-get-random-values` (pin `@^2`: an unpinned install takes 3.x, which is outside the peer range) +- `@react-native-async-storage/async-storage` (1.17 or later, or 2.x) and `react-native-get-random-values` (1.11 or later, or 2.x) are now peer dependencies, not dependencies. Install them in your app: + - Bare React Native: `npx install-expo-modules@latest`, then `npx expo install @datalyr/react-native expo-modules-core @react-native-async-storage/async-storage react-native-get-random-values`, then `cd ios && pod install`. Run `install-expo-modules` first: it adds the Expo SDK that matches your React Native, and `npx expo install` then picks versions for it. A plain `npm install` takes the newest `expo-modules-core` (and AsyncStorage 3.x), which an older Expo SDK cannot use. - Expo: `npx expo install @datalyr/react-native expo-application expo-device expo-network @react-native-async-storage/async-storage react-native-get-random-values` Both are native modules. React Native CLI autolinking links only the packages listed in the app's own `package.json`, and Expo before SDK 54 does the same, so as nested dependencies they could load without their native code. An app that already lists both needs no change. AsyncStorage 3.x is not supported yet (it renames `multiRemove` to `removeMany`). + `react-native-get-random-values` 2.x works only on React Native 0.81 or later with the New Architecture on (Expo SDK 54 or later with it on). On an older React Native, or with the New Architecture off, install `react-native-get-random-values@^1`. On React Native older than 0.81, npm refuses 2.x (`ERESOLVE`); with the New Architecture off, 2.x installs without a warning, but its iOS native module is registered only for the New Architecture, so the SDK fails at start and sends no events. `npx expo install` picks the version your Expo SDK expects (1.11 for Expo SDK 52 to 57, 2.x for SDK 58). + + Bare apps on Expo SDK 53 or 54 (React Native 0.78 to 0.81): `install-expo-modules` does not add `bindReactNativeFactory(factory)` to `AppDelegate.swift`, and the app crashes at start without it. Add it after `reactNativeFactory = factory` (Expo's manual installation steps show it). + ## [1.8.0] - 2026-10-30 diff --git a/README.md b/README.md index c77b09e2..2bdc7123 100644 --- a/README.md +++ b/README.md @@ -26,12 +26,14 @@ Use the option that matches your app. **Bare React Native:** ```bash -npm install @datalyr/react-native expo-modules-core @react-native-async-storage/async-storage@^2 react-native-get-random-values npx install-expo-modules@latest +npx expo install @datalyr/react-native expo-modules-core @react-native-async-storage/async-storage react-native-get-random-values cd ios && pod install ``` -The SDK is built on Expo Modules. You must install `expo-modules-core` in a bare app too. AsyncStorage and `react-native-get-random-values` are native modules: React Native links only the packages your app lists, so install them in your app. +The SDK is built on Expo Modules. `install-expo-modules` adds the Expo SDK that matches your React Native version; run it first, so that `npx expo install` then picks versions for that Expo SDK. Do not use a plain `npm install` for these packages: it takes the newest `expo-modules-core`, which does not match an older Expo SDK, and `pod install` fails. AsyncStorage and `react-native-get-random-values` are native modules: React Native links only the packages your app lists, so install them in your app. + +On Expo SDK 53 or 54 (React Native 0.78 to 0.81), check that `AppDelegate.swift` calls `bindReactNativeFactory(factory)` after `reactNativeFactory = factory`. `install-expo-modules` does not add it, and without it the app crashes at start (`Missing factory in ExpoAppDelegate`). See Expo's [manual installation steps](https://docs.expo.dev/bare/installing-expo-modules/). **Expo:** @@ -39,6 +41,8 @@ The SDK is built on Expo Modules. You must install `expo-modules-core` in a bare npx expo install @datalyr/react-native expo-application expo-device expo-network @react-native-async-storage/async-storage react-native-get-random-values ``` +`npx expo install` picks the versions your Expo SDK expects, in both options above. If you add `react-native-get-random-values` another way, use 2.x only on React Native 0.81 or later (Expo SDK 54 or later) with the New Architecture on; otherwise install `react-native-get-random-values@^1`. On React Native older than 0.81, npm refuses 2.x (`ERESOLVE`). With the New Architecture off, 2.x installs without a warning, but its iOS native module is registered only for the New Architecture, so the SDK fails at start and sends no events. + Add the config plugin to `app.json`: ```json @@ -56,6 +60,8 @@ Add the config plugin to `app.json`: Use a development build (`npx expo run:ios` or EAS). Expo Go ignores the plugin and sends events only. +iOS: after the user allows tracking, the advertising ID is sent from the next app launch. Events in the launch where the user taps Allow are sent at once without it. + Find your API key in DATALYR under **Settings → API**. The key starts with `dk_`. ## Quick start diff --git a/ios/DatalyrNativeModule.swift b/ios/DatalyrNativeModule.swift index 96109e16..9b2f8077 100644 --- a/ios/DatalyrNativeModule.swift +++ b/ios/DatalyrNativeModule.swift @@ -3,11 +3,42 @@ import AdServices import AppTrackingTransparency import AdSupport +// The ATT status when this app process started. iOS lifts its block on the privacy +// manifest's tracking domains only for processes started after tracking was allowed, so the +// JS side may use the tracking host only when this reads authorized. Process-wide (a JS +// reload keeps it), in memory only. +final class DatalyrProcessStartATT: @unchecked Sendable { + static let shared = DatalyrProcessStartATT() + private let lock = NSLock() + private var status: Int? + + /// Records the status the first time it is called in this process; later calls keep it. + func record() { + lock.lock(); defer { lock.unlock() } + if status != nil { return } + if #available(iOS 14, *) { + status = Int(ATTrackingManager.trackingAuthorizationStatus.rawValue) + } else { + status = 3 + } + } + + var value: Int? { + lock.lock(); defer { lock.unlock() } + return status + } +} + public class DatalyrNativeModule: Module { public func definition() -> ModuleDefinition { Name("DatalyrNative") + // Created with the app's module registry at start-up, before the app can ask for ATT. + OnCreate { + DatalyrProcessStartATT.shared.record() + } + // MARK: - SDK Availability Check AsyncFunction("getSDKAvailability") { (promise: Promise) in @@ -59,6 +90,10 @@ public class DatalyrNativeModule: Module { } } + if let startStatus = DatalyrProcessStartATT.shared.value { + result["att_status_at_process_start"] = startStatus + } + promise.resolve(result) } diff --git a/package-lock.json b/package-lock.json index 1b0a1ffc..33fb9057 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@datalyr/react-native", - "version": "1.8.0", + "version": "1.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@datalyr/react-native", - "version": "1.8.0", + "version": "1.9.0", "license": "MIT", "dependencies": { "uuid": "^11.1.1" diff --git a/package.json b/package.json index b8b640ed..978f05c0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datalyr/react-native", - "version": "1.8.0", + "version": "1.9.0", "description": "DATALYR SDK for React Native and Expo: attribution and event tracking for iOS and Android apps", "main": "lib/index.js", "types": "lib/index.d.ts", @@ -63,11 +63,10 @@ "expo-device": ">=7.0.0", "expo-modules-core": ">=2.0.0", "expo-network": ">=7.0.0", - "expo-router": ">=4.0.0", "react": ">=18.0.0", "react-native": ">=0.72.0", "react-native-device-info": ">=12.0.0", - "react-native-get-random-values": "^1.8.0" + "react-native-get-random-values": "^1.11.0 || ^2.0.0" }, "dependencies": { "uuid": "^11.1.1" @@ -135,9 +134,6 @@ }, "@react-native-community/netinfo": { "optional": true - }, - "expo-router": { - "optional": true } } } diff --git a/scripts/check-install-lines.mjs b/scripts/check-install-lines.mjs new file mode 100644 index 00000000..a52ba833 --- /dev/null +++ b/scripts/check-install-lines.mjs @@ -0,0 +1,222 @@ +#!/usr/bin/env node +// Checks that the README install steps resolve with npm's strict peer rules +// (no --legacy-peer-deps), against today's published versions, in throwaway +// lockfile-only apps. The packed SDK stands in for @datalyr/react-native. +// +// - Bare: an app with the react-native (and react) that an Expo SDK bundles; +// then that Expo SDK's `expo` package, which is what +// `npx install-expo-modules` adds for that React Native; then the README's +// bare `npx expo install` line, each package at the version that expo's +// bundledNativeModules.json names (what `expo install` picks), or latest +// when it names none. Run for the newest Expo SDK, SDK 54 (React Native +// 0.81) and SDK 52 (React Native 0.76, the oldest the SDK supports). +// - Expo: an app with that Expo SDK's expo, react and react-native, then the +// README's Expo line the same way. Newest SDK and SDK 52. +// - The README's react-native-get-random-values@^1 advice, on Expo SDK 54. +// +// Each case fails on ERESOLVE (error or "overriding peer dependency"), on an +// invalid or missing package in `npm ls`, or on a second copy of +// expo-modules-core (an app copy that does not match its Expo SDK; pod +// install then fails). It logs the resolved versions. +// +// Not covered (needs a real app build): what install-expo-modules writes into +// the native projects, CocoaPods resolution in `pod install`, Gradle, and +// autolinking. Only a lockfile is written: nothing beyond package metadata is +// downloaded and no app is built. +// +// Usage: node scripts/check-install-lines.mjs +// INSTALL_CHECK_DIR sets the scratch directory (default: a new temp dir). + +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const repoRoot = resolve(import.meta.dirname, '..'); +const readme = readFileSync(join(repoRoot, 'README.md'), 'utf8').split('\n'); + +const INSTALL = 'npx expo install'; +const bareStart = readme.indexOf('**Bare React Native:**'); +const expoStart = readme.indexOf('**Expo:**'); +if (bareStart < 0 || expoStart < bareStart) { + console.error('README: could not find the Bare React Native and Expo sections'); + process.exit(1); +} +const bareSection = readme.slice(bareStart, expoStart); +const expoSection = readme.slice(expoStart); +const isInstallLine = (line) => line.startsWith(`${INSTALL} @datalyr/react-native `); +const bareLine = bareSection.find(isInstallLine); +const expoLine = expoSection.find(isInstallLine); +const addExpoAt = bareSection.findIndex((line) => line.startsWith('npx install-expo-modules')); +if (!bareLine || !expoLine) { + console.error(`README: could not find a "${INSTALL} @datalyr/react-native" line in both sections`); + process.exit(1); +} +if (addExpoAt < 0 || addExpoAt > bareSection.indexOf(bareLine)) { + console.error('README: the bare steps must run npx install-expo-modules before npx expo install'); + process.exit(1); +} +const pinOne = readme.join('\n').match(/`(react-native-get-random-values@\^1)`/); +if (!pinOne) { + console.error('README: could not find the react-native-get-random-values@^1 advice'); + process.exit(1); +} + +const base = process.env.INSTALL_CHECK_DIR + ? resolve(process.env.INSTALL_CHECK_DIR) + : mkdtempSync(join(tmpdir(), 'install-lines-')); +mkdirSync(base, { recursive: true }); + +function run(cmd, args, cwd) { + console.log(`$ (${cwd}) ${cmd} ${args.join(' ')}`); + return execFileSync(cmd, args, { cwd, stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8' }); +} + +const npmFlags = ['--package-lock-only', '--no-audit', '--no-fund', '--ignore-scripts']; + +// npm either stops on a peer conflict (`npm error ERESOLVE`) or, when the +// conflicting package is named in the same command, installs it anyway with +// `npm warn ERESOLVE overriding peer dependency`. Both are a broken install +// for a customer, so both fail here. +function npmInstall(args, cwd) { + console.log(`$ (${cwd}) npm install ${args.join(' ')}`); + const res = spawnSync('npm', ['install', ...npmFlags, ...args], { cwd, encoding: 'utf8' }); + const lines = `${res.stdout}\n${res.stderr}`.split('\n').filter((l) => !/npm warn deprecated/.test(l)); + console.log(lines.join('\n').trim()); + if (res.status !== 0) throw new Error(`npm install exited ${res.status}`); + if (lines.some((l) => l.includes('ERESOLVE'))) throw new Error('npm reported ERESOLVE (peer conflict)'); +} + +// Every dependency in the resulting lockfile must be valid, and there must be +// one expo-modules-core, the one the Expo SDK uses. +function checkTree(cwd) { + console.log(`$ (${cwd}) npm ls --all --package-lock-only`); + const res = spawnSync('npm', ['ls', '--all', '--package-lock-only'], { cwd, encoding: 'utf8' }); + const bad = `${res.stdout}\n${res.stderr}`.split('\n').filter((l) => /invalid|ERR|missing/.test(l)); + if (res.status !== 0 || bad.length) { + console.log(bad.join('\n')); + throw new Error('npm ls found an invalid or missing dependency'); + } + const lock = JSON.parse(readFileSync(join(cwd, 'package-lock.json'), 'utf8')); + const copies = Object.entries(lock.packages) + .filter(([path]) => path.endsWith('node_modules/expo-modules-core')) + .map(([path, meta]) => `${path}@${meta.version}`); + if (copies.length !== 1) { + console.log(copies.join('\n')); + throw new Error(`expected one expo-modules-core, found ${copies.length}`); + } +} + +// The versions the lockfile resolved, so the log shows what was checked. +function logResolved(dir) { + const lock = JSON.parse(readFileSync(join(dir, 'package-lock.json'), 'utf8')); + const names = [ + 'react-native', + 'expo', + 'expo-modules-core', + '@react-native-async-storage/async-storage', + 'react-native-get-random-values', + ]; + const found = names + .map((name) => [name, lock.packages[`node_modules/${name}`]?.version]) + .filter(([, version]) => version) + .map(([name, version]) => `${name}@${version}`); + console.log(`RESOLVED: ${found.join(' ')}`); +} + +// Pack the SDK as a customer receives it. +const packDir = join(base, 'pack'); +mkdirSync(packDir, { recursive: true }); +const packed = JSON.parse(run('npm', ['pack', '--json', '--ignore-scripts', '--pack-destination', packDir], repoRoot)); +const tarball = join(packDir, packed[0].filename); + +const packagesOf = (line) => line.slice(INSTALL.length).trim().split(/\s+/).filter((w) => w && !w.startsWith('-')); +const nameOf = (spec) => spec.replace(/(.)@[^/]*$/, '$1'); + +function newApp(name) { + const dir = join(base, name.replace(/[^\w.-]/g, '_')); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'app', version: '0.0.0', private: true }, null, 2)); + return dir; +} + +let failed = false; +function scenario(title, fn) { + console.log(`\n=== ${title} ===`); + try { + fn(); + console.log(`PASS: ${title}`); + } catch (err) { + failed = true; + console.error(`FAIL: ${title} (${err.message.split('\n')[0]})`); + } +} + +// expo's bundledNativeModules.json is a file in the package, not in its +// registry metadata: read that one file from a package CDN. +function fetchBundled(version) { + const urls = [ + `https://cdn.jsdelivr.net/npm/expo@${version}/bundledNativeModules.json`, + `https://unpkg.com/expo@${version}/bundledNativeModules.json`, + ]; + for (const url of urls) { + try { + return JSON.parse(execFileSync('curl', ['-fsSL', '--retry', '2', url], { encoding: 'utf8' })); + } catch { + console.log(`could not read ${url}`); + } + } + throw new Error(`could not read bundledNativeModules.json for expo@${version}`); +} + +function expoSdk(range, dir) { + const versions = JSON.parse(run('npm', ['view', `expo@${range}`, 'version', '--json'], dir)); + const version = Array.isArray(versions) ? versions[versions.length - 1] : versions; + const bundled = fetchBundled(version); + // `expo install` passes the bundled version, or the bare name when expo + // names none (npm then takes the latest). + const pin = (name) => (bundled[name] ? `${name}@${bundled[name]}` : name); + return { version, pin }; +} + +function installLine(line, dir, pin, replace = {}) { + const args = packagesOf(line).map((spec) => + spec === '@datalyr/react-native' ? tarball : (replace[nameOf(spec)] ?? pin(nameOf(spec))), + ); + console.log(`expo install picks: ${args.filter((a) => a !== tarball).join(' ')}`); + npmInstall(args, dir); + checkTree(dir); + logResolved(dir); +} + +function bareScenario(range) { + scenario(`bare README steps on the React Native of expo@${range}`, () => { + const dir = newApp(`bare-${range}`); + const { version, pin } = expoSdk(range, dir); + // The bare app as the customer has it. + npmInstall([pin('react-native'), pin('react')], dir); + // npx install-expo-modules: adds the expo package for that React Native. + npmInstall([`expo@${version}`], dir); + installLine(bareLine, dir, pin); + }); +} + +function expoScenario(range, replace = {}, label = '') { + scenario(`Expo README line on expo@${range}${label}`, () => { + const dir = newApp(`expo-${range}${label}`); + const { version, pin } = expoSdk(range, dir); + npmInstall([`expo@${version}`, pin('react'), pin('react-native')], dir); + installLine(expoLine, dir, pin, replace); + }); +} + +bareScenario('latest'); +bareScenario('^54.0.0'); +bareScenario('^52.0.0'); +expoScenario('latest'); +expoScenario('^52.0.0'); +// The README's advice for the New Architecture off (React Native 0.81 can +// still turn it off): the Expo line with react-native-get-random-values@^1. +expoScenario('^54.0.0', { 'react-native-get-random-values': pinOne[1] }, ` with ${pinOne[1]}`); + +process.exit(failed ? 1 : 0); diff --git a/src/event-queue.ts b/src/event-queue.ts index 4df2b48e..8c6d3964 100644 --- a/src/event-queue.ts +++ b/src/event-queue.ts @@ -15,6 +15,18 @@ export const TRANSIENT_BACKOFF_BASE_MS = 5000; export const TRANSIENT_BACKOFF_MAX_MS = 5 * 60 * 1000; /** Longest Retry-After the queue honours; a larger value is treated as this. */ export const MAX_RETRY_AFTER_MS = 10 * 60 * 1000; +/** + * Network failures in a row on the tracking host (tracking.datalyr.com) before the event + * is also tried on the normal host without its IDFA, so a host that keeps failing cannot + * hold the queue. During a real outage that try fails too and the event keeps its IDFA. + */ +export const TRACKING_HOST_FALLBACK_AFTER = 2; + +/** + * After the tracking host failed and the normal host answered, IDFA events go straight to + * the normal host (without the IDFA) for this long; then the tracking host is tried again. + */ +export const TRACKING_HOST_COOL_DOWN_MS = 10 * 60 * 1000; interface QueueConfig { maxQueueSize: number; @@ -258,7 +270,28 @@ export class EventQueue { for (const queuedEvent of eventsToProcess) { try { - const response = await this.httpClient.sendEvent(queuedEvent.payload); + let response = await this.httpClient.sendEvent(queuedEvent.payload); + if (!response.viaTrackingHost) { + // This attempt did not use the tracking host: the count is of failures in a row. + queuedEvent.trackingHostFailures = 0; + } + if (response.viaTrackingHost && !response.success && !response.authPending) { + // The tracking host failed: nothing answered (iOS blocks it unless tracking is + // authorized), or an HTTP error (a filter or proxy can answer for that host + // only). If it keeps failing, send to the normal host without the IDFA rather + // than hold every later event behind this one. + queuedEvent.trackingHostFailures = (queuedEvent.trackingHostFailures || 0) + 1; + if (queuedEvent.trackingHostFailures >= TRACKING_HOST_FALLBACK_AFTER) { + debugLog(`Tracking host keeps failing; sending without the IDFA to the normal host: ${queuedEvent.payload.eventName}`); + response = await this.httpClient.sendEvent(queuedEvent.payload, { avoidTrackingHost: true }); + if (response.success) { + // The normal host answered while the tracking host did not: send later IDFA + // events straight to the normal host for a while instead of failing each one + // twice first. Offline never gets here (the normal host must answer). + this.httpClient.avoidTrackingHostFor(TRACKING_HOST_COOL_DOWN_MS); + } + } + } if (response.success) { debugLog(`Event sent successfully: ${queuedEvent.payload.eventName}`); diff --git a/src/expo.ts b/src/expo.ts index c971a090..95b85f47 100644 --- a/src/expo.ts +++ b/src/expo.ts @@ -99,11 +99,20 @@ import type { ExpoRouterTrackingConfig as _ExpoRouterConfig } from './expo-route // Lazy-resolved expo-router hook. Resolved once at first call, not inside the // hook body, so that hook call count stays stable across renders. +// +// The require must stay inside try/catch: Metro resolves every literal +// require when it bundles, and only treats one inside a try block as optional +// (allowOptionalDependencies, on in Metro's, React Native's and Expo's default +// config). Without it, an app without expo-router cannot bundle this entry. let _usePathname: (() => string) | null = null; function getUsePathname(): () => string { if (!_usePathname) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - _usePathname = (require('expo-router') as { usePathname: () => string }).usePathname; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + _usePathname = (require('expo-router') as { usePathname: () => string }).usePathname; + } catch { + throw new Error('[Datalyr] useDatalyrScreenTracking needs expo-router. Install it, or call datalyr.screen() yourself.'); + } } return _usePathname; } diff --git a/src/http-client.ts b/src/http-client.ts index ce1053ae..0c09635f 100644 --- a/src/http-client.ts +++ b/src/http-client.ts @@ -33,8 +33,26 @@ interface HttpResponse { rejected?: boolean; // The server's Retry-After, in ms, when it sent one with a transient answer. retryAfterMs?: number; + // true when the request went to the tracking host (tracking.datalyr.com). + viaTrackingHost?: boolean; } +/** Options for one send. */ +export interface SendOptions { + // Send to the normal host with the tracking-only fields removed, even when tracking is + // authorized. The queue uses it when the tracking host keeps failing. + avoidTrackingHost?: boolean; +} + +/** + * Reads the app's App Tracking Transparency status NOW (0 notDetermined, 1 restricted, + * 2 denied, 3 authorized; undefined when unknown). Set on iOS only. + */ +export type TrackingAuthorizationProvider = () => Promise; + +/** Event fields that may be sent only while tracking is authorized. */ +const TRACKING_ONLY_KEYS = ['idfa', 'alart'] as const; + /** Longest a single in-request retry waits; a longer Retry-After goes to the queue. */ const MAX_INLINE_RETRY_WAIT_MS = 30000; @@ -88,21 +106,111 @@ export class HttpClient { // Apple privacy manifest: NSPrivacyTracking=true REQUIRES a non-empty // NSPrivacyTrackingDomains, and iOS fails every request to a listed host until the // user grants ATT. So the manifest lists ONLY tracking.datalyr.com, and only events - // that actually carry the IDFA (i.e. ATT already authorized) are sent there; all - // other events go to ingest.datalyr.com and are never blocked. Same backend handler. + // that carry the IDFA while ATT is authorized AT SEND TIME, and was already authorized + // when the app process started, are sent there (routeFor); + // all other events go to ingest.datalyr.com and are never blocked. Same backend handler. static readonly TRACKING_ENDPOINT = 'https://tracking.datalyr.com/track'; - private endpointFor(payload: EventPayload): string { - if (this.config.useServerTracking === false) return this.endpoint; - const idfa = (payload.eventData as Record | undefined)?.idfa; - return typeof idfa === 'string' && idfa.length > 0 ? HttpClient.TRACKING_ENDPOINT : this.endpoint; + // iOS: reads the live ATT status at send time. Null elsewhere (Android has no tracking + // domain block), which keeps the routing below exactly as it was. + private trackingAuthorizationProvider: TrackingAuthorizationProvider | null = null; + + setTrackingAuthorizationProvider(provider: TrackingAuthorizationProvider | null): void { + this.trackingAuthorizationProvider = provider; + } + + // iOS: the status when this app process started. iOS lifts the tracking-domain block only + // for processes started after tracking was allowed. Not set (or unknown) = not authorized + // at start, so the tracking host is never used. + private statusAtProcessStartProvider: TrackingAuthorizationProvider | null = null; + + setTrackingStatusAtProcessStartProvider(provider: TrackingAuthorizationProvider | null): void { + this.statusAtProcessStartProvider = provider; + } + + // While set and in the future, IDFA events skip the tracking host (sent to the normal host + // without the IDFA): it failed while the normal host answered (see avoidTrackingHostFor). + private trackingHostAvoidedUntil = 0; + + /** The tracking host failed and the normal host answered: skip it for `ms`, then try again. */ + avoidTrackingHostFor(ms: number): void { + this.trackingHostAvoidedUntil = Date.now() + ms; + } + + private async authorizedAtProcessStart(): Promise { + if (!this.statusAtProcessStartProvider) return false; + try { + return (await this.statusAtProcessStartProvider()) === 3; + } catch { + return false; + } + } + + /** + * Where to send `payload`, and what to send. iOS checks the tracking domain when the + * request is SENT, but the IDFA was copied into the event when it was BUILT: an event + * queued while tracking was allowed and sent after the user turned it off would go to a + * blocked host. So the tracking host is used only when the event carries an IDFA AND the + * live status is authorized (3); otherwise the event goes to the normal host with the + * IDFA and the other tracking-only fields removed (from a copy; the queued event keeps + * them for a later authorized send). + * + * iOS also keeps blocking the tracking host for the rest of the launch in which the user + * allowed tracking. So it is used only when tracking was ALREADY authorized when this + * process started; until the next launch an authorized event goes to the normal host + * without the IDFA (its status fields stay true). The same applies during the cool-down + * after the tracking host failed while the normal host answered. + */ + private async routeFor(payload: EventPayload, options?: SendOptions): Promise<{ url: string; payload: EventPayload; viaTrackingHost: boolean }> { + if (this.config.useServerTracking === false) return { url: this.endpoint, payload, viaTrackingHost: false }; + const data = payload.eventData as Record | undefined; + const idfa = data?.idfa; + const hasIdfa = typeof idfa === 'string' && idfa.length > 0; + const provider = this.trackingAuthorizationProvider; + if (!provider) { + return hasIdfa + ? { url: HttpClient.TRACKING_ENDPOINT, payload, viaTrackingHost: true } + : { url: this.endpoint, payload, viaTrackingHost: false }; + } + if (!data || !TRACKING_ONLY_KEYS.some((k) => data[k] !== undefined)) { + return { url: this.endpoint, payload, viaTrackingHost: false }; + } + let status: number | undefined; + try { + status = await provider(); + } catch { + status = undefined; // unknown can never read as authorized + } + // Authorization-only fields (a real IDFA, `alart`) go only to the tracking host. + if (status === 3 && !hasIdfa && data.alart === undefined) { + return { url: this.endpoint, payload, viaTrackingHost: false }; + } + if ( + status === 3 && + !options?.avoidTrackingHost && + Date.now() >= this.trackingHostAvoidedUntil && + (await this.authorizedAtProcessStart()) + ) { + return { url: HttpClient.TRACKING_ENDPOINT, payload, viaTrackingHost: true }; + } + const stripped: Record = { ...data }; + for (const key of TRACKING_ONLY_KEYS) delete stripped[key]; + if (status !== 3) { + // The event must not claim tracking is allowed: report the status at send time. + stripped.advertiser_tracking_enabled = false; + if (status === undefined) delete stripped.att_status; + else stripped.att_status = status; + } + return { url: this.endpoint, payload: { ...payload, eventData: stripped as EventPayload['eventData'] }, viaTrackingHost: false }; } /** * Send a single event with retry logic */ - async sendEvent(payload: EventPayload): Promise { - return this.sendWithRetry(payload, 0); + async sendEvent(payload: EventPayload, options?: SendOptions): Promise { + const route = await this.routeFor(payload, options); + const response = await this.sendWithRetry(route.payload, 0, route.url); + return route.viaTrackingHost ? { ...response, viaTrackingHost: true } : response; } /** @@ -117,7 +225,7 @@ export class HttpClient { /** * Send request with exponential backoff retry */ - private async sendWithRetry(payload: EventPayload, retryCount: number): Promise { + private async sendWithRetry(payload: EventPayload, retryCount: number, url: string): Promise { try { // Defense-in-depth: never fire a server-tracking request without an API key — it // would 401 and (after retries) permanently dead-letter the event. Signal the queue @@ -165,7 +273,7 @@ export class HttpClient { const body = JSON.stringify(requestBody); let response: Response; try { - response = await fetch(this.endpointFor(payload), { + response = await fetch(url, { method: 'POST', headers, body, @@ -263,7 +371,7 @@ export class HttpClient { await this.delay(delay); // Same payload object, so the same eventId: ingest dedupes a retry of an event // whose first answer was lost. - return this.sendWithRetry(payload, retryCount + 1); + return this.sendWithRetry(payload, retryCount + 1, url); } if (httpStatus === undefined) { diff --git a/src/native/DatalyrNativeBridge.ts b/src/native/DatalyrNativeBridge.ts index 9a31b759..22e2e7ca 100644 --- a/src/native/DatalyrNativeBridge.ts +++ b/src/native/DatalyrNativeBridge.ts @@ -59,6 +59,8 @@ interface DatalyrNativeModule { gaid?: string; att_status: number; advertiser_tracking_enabled: boolean; + // iOS, 1.9.0+ native code: the status when this app process started. + att_status_at_process_start?: number; } | null>; // Apple Search Ads Methods (iOS only) @@ -185,6 +187,45 @@ export const AdvertiserInfoBridge = { }, }; +// MARK: - ATT status at process start (iOS only) + +// iOS lifts its block on the privacy manifest's tracking domains only for app processes +// started AFTER the user allowed tracking: in the launch where the user taps "Allow", +// requests to tracking.datalyr.com still fail although the status reads authorized. So the +// tracking host may be used only when tracking was already authorized at process start. +// Kept in memory only, never stored: the next process reads its own. +let processStartRead: Promise | null = null; +const asAttStatus = (v: unknown): number | undefined => (v === 0 || v === 1 || v === 2 || v === 3 ? v : undefined); + +export const TrackingStartBridge = { + /** + * The ATT status when this process started, or undefined when unknown (never authorized). + * Prefers the native module's own value (captured when the module was created at app + * start, and it survives JS reloads). An older native binary lacks it: then the first read + * this JS runtime made, started when this file was loaded. + */ + statusAtProcessStart(): Promise { + if (!processStartRead) { + processStartRead = (async () => { + if (Platform.OS !== 'ios' || !DatalyrNative) return undefined; + try { + const info: any = await DatalyrNative.getAdvertiserInfo(); + if (!info) return undefined; + return info.att_status_at_process_start !== undefined + ? asAttStatus(info.att_status_at_process_start) + : asAttStatus(info.att_status); + } catch { + return undefined; + } + })(); + } + return processStartRead; + }, +}; + +// As early as the JS side can: when the SDK's code is first loaded. +if (Platform.OS === 'ios') void TrackingStartBridge.statusAtProcessStart(); + // MARK: - Play Install Referrer Bridge (Android only) export const PlayInstallReferrerNativeBridge = { diff --git a/src/sdk-core.ts b/src/sdk-core.ts index 84820f2d..c2200558 100644 --- a/src/sdk-core.ts +++ b/src/sdk-core.ts @@ -41,7 +41,7 @@ import { AutoEventsManager } from './auto-events'; import { ConversionValueEncoder, ConversionTemplates } from './ConversionValueEncoder'; import { SKAdNetworkBridge } from './native/SKAdNetworkBridge'; import { appleSearchAdsIntegration, playInstallReferrerIntegration } from './integrations'; -import { AppleSearchAdsAttribution, AdvertiserInfoBridge, isNativeModuleAvailable } from './native/DatalyrNativeBridge'; +import { AppleSearchAdsAttribution, AdvertiserInfoBridge, TrackingStartBridge, isNativeModuleAvailable } from './native/DatalyrNativeBridge'; import { networkStatusManager } from './network-status'; // Provider namespaces the server's webhooks join on `external_ids` (one list shared by // both entry points; MUST match the server's person-contract.js). @@ -84,6 +84,7 @@ export interface PlatformUtils { USER_ID_PROVISIONAL: string; LAST_IDENTITY_HASH: string; DEFERRED_LOOKUP_NEEDS_ATT_STATUS: string; + ATT_ID_WITHHELD: string; }; } @@ -276,6 +277,14 @@ export class DatalyrSDKCore { debug: this.state.config.debug || false, useServerTracking: this.state.config.useServerTracking ?? true, }); + // iOS blocks the privacy manifest's tracking domain unless tracking is authorized + // when the request is sent, so the client reads the status then (before the queue + // below loads and drains the stored events). Not on Android: no such block there. + if (Platform.OS === 'ios') { + this.httpClient.setTrackingAuthorizationProvider(() => this.liveTrackingStatus()); + // ...and lifts it only for processes started after tracking was allowed. + this.httpClient.setTrackingStatusAtProcessStartProvider(() => TrackingStartBridge.statusAtProcessStart()); + } // Initialize event queue this.eventQueue = new EventQueue(this.httpClient, { @@ -450,6 +459,8 @@ export class DatalyrSDKCore { console.warn('[Datalyr] Native modules not linked — SKAdNetwork, IDFA and Apple Search Ads are disabled. Expo Go does not support them; use a development build and re-run pod install.'); } + await this.resendAttStatusIfIdWithheld(); + // Handlers registered before initialize() finished get their first push now (ids // and any deferred web attribution are in place). this.notifyProviderAttributeHandlers(); @@ -1156,6 +1167,56 @@ export class DatalyrSDKCore { await this.runDeferredLookupIfEligible(); } + /** + * The ATT status right now, from the native module (a cheap read), for the send-time + * host choice. Also refreshes the cache, so events built next carry the current IDFA. + * Undefined when the module is unavailable or the read fails: never authorized. + */ + private async liveTrackingStatus(): Promise { + const info = await AdvertiserInfoBridge.getAdvertiserInfo(); + if (info) this.cachedAdvertiserInfo = info; + const status = attStatusFrom(info); + if (status === 3 && !this.idWithheldNoted && (await TrackingStartBridge.statusAtProcessStart()) !== 3) { + // Allowed during this launch: the IDFA is withheld until the next one (see routeFor). + // The stored value is the re-send's fixed event id, made once per grant. + this.idWithheldNoted = true; + const key = this.u.STORAGE_KEYS.ATT_ID_WITHHELD; + if (!(await this.u.Storage.getItem(key))) { + await this.u.Storage.setItem(key, `att_resend_${this.u.generateUUID()}`); + } + } + return status; + } + + private idWithheldNoted = false; + + /** + * The previous launch allowed tracking mid-session, so its events reached the server + * without the IDFA. If tracking was authorized when this process started, send + * `$att_status` once: it carries the IDFA (to the tracking host) for the same device ids. + */ + private async resendAttStatusIfIdWithheld(): Promise { + if (Platform.OS !== 'ios') return; + const key = this.u.STORAGE_KEYS.ATT_ID_WITHHELD; + try { + const grantId = await this.u.Storage.getItem(key); + if (!grantId) return; + const now = attStatusFrom(this.cachedAdvertiserInfo); + if (now === 3 && (await TrackingStartBridge.statusAtProcessStart()) === 3) { + // The flag is removed only after the event is queued (so it cannot be lost), and the + // event id is fixed per grant: if the app is killed in between, the next launch sends + // it again with the SAME id, which the server de-duplicates. + const eventId = typeof grantId === 'string' ? grantId : undefined; + await this.track('$att_status', { authorized: true, status: 3, status_name: ATT_STATUS_NAMES[3], att_status: 3, resent: true, ...(eventId ? { event_id: eventId } : {}) }); + await this.u.Storage.removeItem(key); + } else if (now !== undefined && now !== 3) { + await this.u.Storage.removeItem(key); // no longer allowed: nothing to send + } + } catch (error) { + errorLog('Failed to re-send the ATT status:', error as Error); + } + } + /** Re-read IDFA/IDFV/ATT status from the native module into the cache. */ private async refreshAdvertiserInfo(): Promise { try { diff --git a/src/types.ts b/src/types.ts index a2e6121c..42bdb9ac 100644 --- a/src/types.ts +++ b/src/types.ts @@ -234,6 +234,9 @@ export interface QueuedEvent { // Set on dead-letter entries that can never deliver (e.g. server 413 payload too // large). replayDeadLetter skips them; they are kept only for inspection. permanent?: boolean; + // Network failures in a row on the tracking host; past TRACKING_HOST_FALLBACK_AFTER the + // event is also tried on the normal host without its IDFA (see EventQueue). + trackingHostFailures?: number; } // App State - Updated for React Native 0.80 diff --git a/src/utils-expo.ts b/src/utils-expo.ts index 107f26fa..1c983806 100644 --- a/src/utils-expo.ts +++ b/src/utils-expo.ts @@ -51,6 +51,8 @@ export const STORAGE_KEYS = { // Set when the server declined the lookup for ATT while the native module was missing // (no ATT status to send); lookups are skipped until the module reports a status. DEFERRED_LOOKUP_NEEDS_ATT_STATUS: '@datalyr/deferred_lookup_needs_att_status', + // iOS: tracking was allowed mid-launch, so that launch's events went without the IDFA. + ATT_ID_WITHHELD: '@datalyr/att_id_withheld', } as const; // Debug logging: prints in a development build or with `debug: true`. diff --git a/src/utils.ts b/src/utils.ts index fd104e34..f5feb912 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -45,6 +45,8 @@ export const STORAGE_KEYS = { // Set when the server declined the lookup for ATT while the native module was missing // (no ATT status to send); lookups are skipped until the module reports a status. DEFERRED_LOOKUP_NEEDS_ATT_STATUS: '@datalyr/deferred_lookup_needs_att_status', + // iOS: tracking was allowed mid-launch, so that launch's events went without the IDFA. + ATT_ID_WITHHELD: '@datalyr/att_id_withheld', }; // Constants diff --git a/src/version.ts b/src/version.ts index 9c8348fb..d1202993 100644 --- a/src/version.ts +++ b/src/version.ts @@ -23,7 +23,7 @@ * it stays derived. Hardcoding a version there would make it a third drift site * and fail that test. */ -export const SDK_VERSION = '1.8.0'; +export const SDK_VERSION = '1.9.0'; /** * Library identifier sent as `context.library`. Server-side platform detection diff --git a/tests/dependency-declarations.test.ts b/tests/dependency-declarations.test.ts index 04d57bce..a48e2e8b 100644 --- a/tests/dependency-declarations.test.ts +++ b/tests/dependency-declarations.test.ts @@ -35,17 +35,26 @@ describe('W6 — uuid', () => { describe('W6 — optional Expo peers', () => { // src/utils-expo.ts imports these three statically (the Expo entry); - // src/expo.ts requires expo-router lazily; app.plugin.js requires - // expo/config-plugins, falling back to @expo/config-plugins. + // app.plugin.js requires expo/config-plugins, falling back to + // @expo/config-plugins. const expoPeers = [ 'expo-application', 'expo-device', 'expo-network', - 'expo-router', 'expo', '@expo/config-plugins', ]; + test('expo-router is not a peer (an optional peer still makes npm check the newest expo-router)', () => { + // npm resolves an optional peer that is not installed against its newest + // version: expo-router 58 wants expo-constants 58, and a bare app on Expo + // SDK 54 then fails `npx expo install @datalyr/react-native` with ERESOLVE. + // src/expo.ts requires expo-router only when the app calls + // useDatalyrScreenTracking, so only apps that have it load it. + expect(pkg.peerDependencies['expo-router']).toBeUndefined(); + expect(pkg.peerDependenciesMeta['expo-router']).toBeUndefined(); + }); + test.each(expoPeers)('%s is an optional peer dependency', (name) => { expect(typeof pkg.peerDependencies[name]).toBe('string'); expect(pkg.peerDependenciesMeta[name]).toEqual({ optional: true }); @@ -93,6 +102,14 @@ describe('W6 — native modules the app must list itself', () => { expect(pkg.peerDependencies['@react-native-async-storage/async-storage']).toBe('^1.17.0 || ^2.0.0'); }); + test('get-random-values peer range is 1.11+ or 2.x (the unpinned README lines take 2.x)', () => { + // 2.x needs React Native 0.81+ with the New Architecture; 1.11 is the first + // 1.x with bridgeless support, and Expo SDK 52-57 bundle ~1.11.0. The SDK + // only imports it for its crypto.getRandomValues polyfill, which 1.x and + // 2.x install the same way. + expect(pkg.peerDependencies['react-native-get-random-values']).toBe('^1.11.0 || ^2.0.0'); + }); + test.each(nativeModules)('the README install lines name %s', (name) => { const readme = readFileSync(join(repoRoot, 'README.md'), 'utf8'); const installLines = readme @@ -105,9 +122,21 @@ describe('W6 — native modules the app must list itself', () => { } }); - test('the bare install line pins AsyncStorage to 2.x (latest is 3.x, outside the peer range)', () => { + test('the bare steps add the matching Expo SDK first, then install with expo install (SDK-matched versions)', () => { + // A plain npm install takes the newest expo-modules-core (pod install then + // fails on an older Expo SDK) and AsyncStorage 3.x (outside the peer range). const readme = readFileSync(join(repoRoot, 'README.md'), 'utf8'); - const bare = readme.split('\n').find((line) => line.startsWith('npm install @datalyr/react-native')); - expect(bare?.split(' ')).toContain('@react-native-async-storage/async-storage@^2'); + const lines = readme.split('\n'); + const bareStart = lines.indexOf('**Bare React Native:**'); + const expoStart = lines.indexOf('**Expo:**'); + expect(bareStart).toBeGreaterThan(-1); + expect(expoStart).toBeGreaterThan(bareStart); + const bare = lines.slice(bareStart, expoStart); + const addExpo = bare.indexOf('npx install-expo-modules@latest'); + const install = bare.findIndex((line) => line.startsWith('npx expo install @datalyr/react-native ')); + expect(addExpo).toBeGreaterThan(-1); + expect(install).toBeGreaterThan(addExpo); + expect(bare[install].split(' ')).toContain('expo-modules-core'); + expect(lines.some((line) => /^(npm install|yarn add|pnpm add) .*@datalyr\/react-native/.test(line))).toBe(false); }); }); diff --git a/tests/expo-router-optional.test.ts b/tests/expo-router-optional.test.ts new file mode 100644 index 00000000..5e667f49 --- /dev/null +++ b/tests/expo-router-optional.test.ts @@ -0,0 +1,87 @@ +// The Expo entry must bundle in an app without expo-router. +// +// Metro resolves every literal require() when it bundles, wherever the call +// is, and treats one as optional only inside a try block +// (allowOptionalDependencies, on in Metro's, React Native's and Expo's default +// config). Metro reads src/expo.ts (the "react-native" export condition), and +// lib/expo.js is the tsc build of it. + +import { existsSync, readFileSync } from 'fs'; +import { join, resolve } from 'path'; +import * as ts from 'typescript'; + +jest.mock('expo-application', () => ({ + nativeApplicationVersion: '1.0.0', nativeBuildVersion: '1', + applicationId: 'com.datalyr.test', getInstallationTimeAsync: async () => new Date(0), +}), { virtual: true }); +jest.mock('expo-device', () => ({ + modelName: 'Test Device', deviceName: 'Test Device', manufacturer: 'Test', + osVersion: '17.0', isDevice: true, +}), { virtual: true }); +jest.mock('expo-network', () => ({ + NetworkStateType: { WIFI: 'WIFI' }, + getNetworkStateAsync: async () => ({ type: 'WIFI', isConnected: true }), +}), { virtual: true }); +// An app without expo-router: requiring it throws, as Metro's optional +// dependency stub does. +jest.mock('expo-router', () => { + throw new Error("Cannot find module 'expo-router'"); +}, { virtual: true }); + +const repoRoot = resolve(__dirname, '..'); + +// Each require('expo-router') call in the file, and whether it sits inside the +// try block of a try statement. +function expoRouterRequires(file: string): boolean[] { + const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true); + const found: boolean[] = []; + const visit = (node: ts.Node): void => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'require' && + node.arguments.length === 1 && + ts.isStringLiteral(node.arguments[0]) && + node.arguments[0].text === 'expo-router' + ) { + let inTry = false; + for (let child: ts.Node = node, parent = node.parent; parent; child = parent, parent = parent.parent) { + if (ts.isTryStatement(parent) && parent.tryBlock === child) { + inTry = true; + break; + } + if (ts.isFunctionLike(parent)) { + // A try outside the enclosing function does not guard the call. + if (ts.isTryStatement(parent.parent) && parent.parent.tryBlock === parent) inTry = true; + break; + } + } + found.push(inTry); + } + ts.forEachChild(node, visit); + }; + visit(source); + return found; +} + +describe('expo-router is optional for the Expo entry', () => { + test('every require of expo-router in src/expo.ts is inside a try block', () => { + const found = expoRouterRequires(join(repoRoot, 'src', 'expo.ts')); + expect(found.length).toBeGreaterThan(0); + expect(found.every(Boolean)).toBe(true); + }); + + const built = join(repoRoot, 'lib', 'expo.js'); + (existsSync(built) ? test : test.skip)('the same holds in the built lib/expo.js', () => { + const found = expoRouterRequires(built); + expect(found.length).toBeGreaterThan(0); + expect(found.every(Boolean)).toBe(true); + }); + + test('without expo-router the entry loads, and only the hook fails, with a clear message', () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const expo = require('../src/expo'); + expect(typeof expo.useDatalyrScreenTracking).toBe('function'); + expect(() => expo.useDatalyrScreenTracking()).toThrow(/needs expo-router/); + }); +}); diff --git a/tests/tracking-host-process-start.test.ts b/tests/tracking-host-process-start.test.ts new file mode 100644 index 00000000..81e15af5 --- /dev/null +++ b/tests/tracking-host-process-start.test.ts @@ -0,0 +1,571 @@ +// iOS lifts its block on the privacy manifest's tracking domain (tracking.datalyr.com) only +// for app PROCESSES STARTED AFTER the user allowed tracking. Proved on a real iPhone +// (2026-11-25): in the launch where the user taps "Allow", requests to the tracking host still +// fail (NSURLErrorDomain -1009) although the status reads authorized; after a relaunch they +// succeed. Choosing the host from the live status alone sent every event of that first launch +// to a host it could not reach, and it reached ingest only after two failures and a backoff, +// without the IDFA. +// +// Rule now: the tracking host is used only when tracking was ALREADY authorized when this +// process started AND is authorized now AND the event carries a real IDFA. Otherwise the event +// goes to ingest at once, with the IDFA removed. The next process re-sends `$att_status` once, +// so the IDFA still reaches the server. +// +// Each "process" here is a fresh module registry (jest.isolateModules): the SDK, its bridges +// and its in-memory state are created again, as in a new app launch. AsyncStorage is shared, +// as on a real device. The native module is a fake whose status the test changes. + +import AsyncStorageShared from '@react-native-async-storage/async-storage'; +import { HttpClient } from '../src/http-client'; +import { EventQueue } from '../src/event-queue'; +import type { EventPayload } from '../src/types'; + +const INGEST = 'https://ingest.datalyr.com/track'; +const TRACKING = 'https://tracking.datalyr.com/track'; +const IDFA = '6D92078A-8246-4BA4-AE5B-76104861E7DC'; + +type Sent = { url: string; body: any }; +let sent: Sent[] = []; + +// The phone. `status` is the live ATT status. `startStatus` is what iOS saw when the current +// process started: the tracking host answers only when both are authorized. +const phone = { status: 0 as number, startStatus: 0 as number, readable: true, platform: 'ios' as 'ios' | 'android' }; +let trackingHostFails = false; +let nativeReads = 0; + +const ok = () => ({ ok: true, status: 200, statusText: 'OK', headers: { get: () => null }, json: async () => ({}) }); +const answer = (status: number) => ({ ok: status < 400, status, statusText: String(status), headers: { get: () => null }, json: async () => ({}) }); + +const installFetch = () => { + (globalThis as any).fetch = async (url: string, init: any) => { + const u = String(url); + if (u.startsWith(INGEST) || u.startsWith(TRACKING)) { + sent.push({ url: u, body: JSON.parse(init.body) }); + if (u.startsWith(TRACKING) && (trackingHostFails || !(phone.startStatus === 3 && phone.status === 3))) { + return Promise.reject(new TypeError('Network request failed')); + } + } + return ok(); + }; +}; + +/** + * Start a new app process. `nativeStartField` = the native module reports the status it saw + * when the process started (this release's native code); false = an older native binary + * (for example new JS through an over-the-air update), where the JS side reads it at load. + */ +const startProcess = (opts: { nativeStartField?: boolean; jsReloadOnly?: boolean } = {}) => { + const nativeStartField = opts.nativeStartField !== false; + // A JS reload (over-the-air update, dev reload) restarts the JS side in the SAME process: + // iOS keeps the process's block, and the native module keeps its start value. + if (!opts.jsReloadOnly) phone.startStatus = phone.status; + const startStatus = phone.startStatus; + const fakeNative: any = { + getAdvertiserInfo: async () => { + nativeReads++; + if (!phone.readable) throw new Error('native read failed (test)'); + if (phone.platform === 'android') { + return { gaid: 'GAID-TEST', att_status: 3, advertiser_tracking_enabled: true }; + } + return { + idfv: 'IDFV-TEST', + att_status: phone.status, + advertiser_tracking_enabled: phone.status === 3, + ...(phone.status === 3 ? { idfa: IDFA } : {}), + ...(nativeStartField ? { att_status_at_process_start: startStatus } : {}), + }; + }, + getAppleSearchAdsAttribution: async () => null, + getSDKAvailability: async () => ({ appleSearchAds: false }), + }; + let mod: any; + jest.isolateModules(() => { + jest.doMock('@react-native-async-storage/async-storage', () => AsyncStorageShared); + jest.doMock('react-native', () => { + const rn = jest.requireActual('../test-mocks/react-native.js'); + return { + ...rn, + Platform: { ...rn.Platform, OS: phone.platform }, + NativeModules: phone.platform === 'android' ? { DatalyrNative: fakeNative } : {}, + AppState: { ...rn.AppState, addEventListener: () => ({ remove: () => {} }) }, + }; + }); + jest.doMock('expo-modules-core', () => ({ + ...jest.requireActual('../test-mocks/expo-modules-core.js'), + requireNativeModule: (name: string) => { + if (name === 'DatalyrNative') return fakeNative; + throw new Error('native module unavailable (test)'); + }, + })); + mod = require('../src/datalyr-sdk'); + }); + return new mod.DatalyrSDK(); +}; + +const init = async (sdk: any) => { + await sdk.initialize({ apiKey: 'dk_test', flushInterval: 999999, enableAutoEvents: false, enableWebToAppAttribution: false }); +}; +// Drain until empty or stuck. A drain started by track() may still be running (flush() +// returns at once then), so wait for it between tries. +const flush = async (sdk: any) => { + const q = sdk.eventQueue; + for (let i = 0; i < 50 && q.getStats().queueSize > 0; i++) { + q.retryNotBefore = 0; + await q.flush(); + await new Promise((r) => setTimeout(r, 5)); + } +}; +const named = (name: string) => sent.filter((s) => s.body.event === name); +const expectNoIdOnIngest = () => { + for (const s of sent) if (s.url === INGEST) expect(s.body.properties.idfa).toBeUndefined(); +}; + +beforeEach(async () => { + await (AsyncStorageShared as any).clear(); + sent = []; + phone.status = 0; + phone.startStatus = 0; + phone.readable = true; + phone.platform = 'ios'; + trackingHostFails = false; + nativeReads = 0; + installFetch(); +}); + +describe.each([ + ['native reports the process-start status', true], + ['older native binary (JS reads it at load)', false], +])('iOS, %s', (_name, nativeStartField) => { + test('not authorized at start, user allows mid-session → ingest at once, IDFA removed, no failed request first', async () => { + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + await sdk.track('paywall_viewed'); + phone.status = 3; // the user taps "Allow" + await sdk.updateTrackingAuthorization(true); + await sdk.track('purchase', { value: 9 }); + await flush(sdk); + + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + for (const name of ['$att_status', 'purchase']) { + const copies = named(name); + expect(copies).toHaveLength(1); // delivered on the first attempt + expect(copies[0].url).toBe(INGEST); + expect(copies[0].body.properties.idfa).toBeUndefined(); + // The status itself is true: the user did allow tracking. + expect(copies[0].body.properties.att_status).toBe(3); + } + expect(named('purchase')[0].body.properties.value).toBe(9); + expect(sdk.eventQueue.getStats().queueSize).toBe(0); + expectNoIdOnIngest(); + } finally { + sdk.destroy(); + } + }); + + test('authorized at start and still authorized → tracking host with the IDFA', async () => { + phone.status = 3; + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + await sdk.track('purchase', { value: 2 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(TRACKING); + expect(purchase[0].body.properties.idfa).toBe(IDFA); + expectNoIdOnIngest(); + } finally { + sdk.destroy(); + } + }); + + test('authorized at start, revoked mid-session → ingest, IDFA removed', async () => { + phone.status = 3; + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + sdk.eventQueue.isOnline = false; + await sdk.track('purchase', { value: 4 }); + phone.status = 2; // Settings → tracking off + sdk.eventQueue.isOnline = true; + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(purchase[0].body.properties.att_status).toBe(2); + } finally { + sdk.destroy(); + } + }); + + test('a new process after allowing → tracking host, and $att_status re-sent once with the IDFA', async () => { + const first = startProcess({ nativeStartField }); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + + sent = []; + const second = startProcess({ nativeStartField }); // kill and relaunch + try { + await init(second); + await second.track('screen_viewed'); + await flush(second); + const att = named('$att_status'); + expect(att).toHaveLength(1); + expect(att[0].url).toBe(TRACKING); + expect(att[0].body.properties.idfa).toBe(IDFA); + expect(att[0].body.properties.att_status).toBe(3); + expect(named('screen_viewed')[0].url).toBe(TRACKING); + expect(sent.every((s) => s.url === TRACKING)).toBe(true); + } finally { + second.destroy(); + } + + // Only once: a third launch sends no extra $att_status. + sent = []; + const third = startProcess({ nativeStartField }); + try { + await init(third); + await flush(third); + expect(named('$att_status')).toHaveLength(0); + } finally { + third.destroy(); + } + }); +}); + +describe('iOS: more launches', () => { + const resent = () => named('$att_status').filter((s) => s.body.properties.resent === true); + + test('authorized at start (for example an upgrade): no re-send, no flag', async () => { + phone.status = 3; + for (let i = 0; i < 2; i++) { + const sdk = startProcess(); + try { + await init(sdk); + await sdk.track('screen_viewed'); + await flush(sdk); + } finally { + sdk.destroy(); + } + } + expect(resent()).toHaveLength(0); + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + }); + + test('flag cleared on a launch where tracking is no longer allowed; no re-send later', async () => { + const first = startProcess(); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).not.toBeNull(); + + phone.status = 2; // turned off in Settings + const second = startProcess(); + try { + await init(second); + await flush(second); + } finally { + second.destroy(); + } + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + + phone.status = 3; // allowed again in Settings (iOS relaunches the app) + sent = []; + const third = startProcess(); + try { + await init(third); + await flush(third); + } finally { + third.destroy(); + } + expect(resent()).toHaveLength(0); + }); + + test('an IDFA event stored by an earlier launch, sent in a launch not authorized at start → ingest without it', async () => { + phone.status = 3; + const first = startProcess(); + try { + await init(first); + first.eventQueue.isOnline = false; + await first.track('purchase', { value: 7 }); + } finally { + first.destroy(); // killed with the event still queued + } + sent = []; + phone.status = 2; + const second = startProcess(); + try { + await init(second); + phone.status = 3; // allowed again during this launch + await flush(second); + } finally { + second.destroy(); + } + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(purchase[0].body.properties.value).toBe(7); + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + }); + + test('killed between the re-send and clearing its flag: sent again with the SAME event id', async () => { + const first = startProcess(); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + // Second launch: the re-send is queued, then the app dies before the flag is removed. + const realRemove = (AsyncStorageShared as any).removeItem; + (AsyncStorageShared as any).removeItem = async (k: string) => { + if (k === '@datalyr/att_id_withheld') throw new Error('killed (test)'); + return realRemove(k); + }; + const second = startProcess(); + try { + await init(second); + await flush(second); + } finally { + second.destroy(); + (AsyncStorageShared as any).removeItem = realRemove; + } + const third = startProcess(); + try { + await init(third); + await flush(third); + } finally { + third.destroy(); + } + const copies = resent(); + expect(copies.length).toBe(2); + expect(new Set(copies.map((c) => c.body.eventId)).size).toBe(1); + expect(copies.every((c) => c.url === TRACKING && c.body.properties.idfa === IDFA)).toBe(true); + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + }); + + test.each([ + ['new native: still not authorized at start → ingest at once', true], + ['older native: reads authorized (wrong) → tracking host fails, falls back, then skips it', false], + ])('JS reload in the same process after Allow, %s', async (_name, nativeStartField) => { + const first = startProcess({ nativeStartField }); + try { + await init(first); + phone.status = 3; // allowed, then the JS side reloads in the same process + } finally { + first.destroy(); + } + sent = []; + const reloaded = startProcess({ nativeStartField, jsReloadOnly: true }); + try { + await init(reloaded); + await reloaded.track('purchase', { value: 5 }); + await flush(reloaded); + await reloaded.track('later'); + await flush(reloaded); + expect(named('purchase').filter((s) => s.url === INGEST)).toHaveLength(1); + expect(named('later')).toEqual([expect.objectContaining({ url: INGEST })]); + expect(reloaded.eventQueue.getStats().queueSize).toBe(0); + if (nativeStartField) expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + expectNoIdOnIngest(); + } finally { + reloaded.destroy(); + } + }); +}); + +test('iOS: status unreadable at start → treated as not authorized at start (ingest, IDFA removed)', async () => { + phone.status = 3; + phone.readable = false; + const sdk = startProcess({ nativeStartField: false }); + phone.readable = true; // later reads work and say authorized + try { + await init(sdk); + await sdk.track('purchase', { value: 1 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + } finally { + sdk.destroy(); + } +}); + +test('Android: unchanged (ingest, GAID kept, no process-start or per-send status reads)', async () => { + phone.platform = 'android'; + const sdk = startProcess(); + try { + await init(sdk); + const reads = nativeReads; + await sdk.track('purchase', { value: 1 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.gaid).toBe('GAID-TEST'); + expect(purchase[0].body.properties.att_status).toBe(3); + expect(nativeReads).toBe(reads); + expect(named('$att_status')).toHaveLength(0); + } finally { + sdk.destroy(); + } +}); + +// Second line of defence (from 1.9.0's send-time fix): the tracking host fails for an +// authorized user (a DNS or company filter, a zone problem) while ingest works. +describe('tracking host unreachable while authorized', () => { + const payload = (name: string): EventPayload => ({ + workspaceId: 'ws_test', visitorId: 'anon', anonymousId: 'anon', sessionId: 'sess', + eventId: `evt_${name}`, eventName: name, source: 'mobile_app', timestamp: new Date(0).toISOString(), + eventData: { idfa: IDFA, idfv: 'IDFV-TEST', att_status: 3, advertiser_tracking_enabled: true }, + }); + const newClient = () => { + const client = new HttpClient(INGEST, { apiKey: 'test_key_not_real', maxRetries: 0, retryDelay: 1, timeout: 50, debug: false, useServerTracking: true }); + client.setTrackingAuthorizationProvider(async () => phone.status); + (client as any).setTrackingStatusAtProcessStartProvider?.(async () => phone.startStatus); + return client; + }; + const newQueue = async (client: HttpClient) => { + const q = new EventQueue(client, { maxQueueSize: 100, batchSize: 10, flushInterval: 999999, maxRetryCount: 3 }); + await new Promise((r) => setTimeout(r, 10)); + return q; + }; + const enqueueQuiet = async (q: EventQueue, p: EventPayload) => { + (q as any).isOnline = false; + await q.enqueue(p); + (q as any).isOnline = true; + }; + const flushNow = async (q: EventQueue) => { + (q as any).retryNotBefore = 0; + await q.flush(); + }; + + beforeEach(() => { + phone.status = 3; + phone.startStatus = 3; + }); + + test('the counter is "two in a row": an attempt that did not use the tracking host resets it', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('purchase')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + if (String(url).startsWith(INGEST)) return answer(503); // ingest busy for this test + return Promise.reject(new TypeError('Network request failed')); + }; + await flushNow(q); // tracking host fails (1) + phone.status = 2; // briefly revoked: this attempt goes to ingest (503), the row is broken + await flushNow(q); + phone.status = 3; + await flushNow(q); // tracking host fails (1 again): no fallback yet + expect(sent.map((s) => s.url)).toEqual([TRACKING, INGEST, TRACKING]); + expect(q.getStats().queueSize).toBe(1); + expect((q as any).queue[0].payload.eventData.idfa).toBe(IDFA); + }); + + test.each([403, 503])('an HTTP %i from the tracking host counts too: fallback after two, then the cool-down', async (code) => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + return String(url).startsWith(TRACKING) ? answer(code) : ok(); + }; + await flushNow(q); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['a', TRACKING], ['a', INGEST]]); + expect(sent[2].body.properties.idfa).toBeUndefined(); + expect(q.getStats().queueSize).toBe(0); + sent = []; + await enqueueQuiet(q, payload('b')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['b', INGEST]]); + }); + + test('a 2xx from the tracking host is sent once, with no fallback copy', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING]]); + expect(q.getStats().queueSize).toBe(0); + }); + + test('alart only: tracking host when authorized at start and now; otherwise ingest without it', async () => { + const client = newClient(); + const alartOnly = (name: string): EventPayload => ({ ...payload(name), eventData: { alart: 'applovin_user_1', att_status: 3, advertiser_tracking_enabled: true } }); + await client.sendEvent(alartOnly('x')); + phone.startStatus = 0; // a launch that was not authorized at start + await client.sendEvent(alartOnly('y')); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['x', TRACKING], ['y', INGEST]]); + expect(sent[0].body.properties.alart).toBe('applovin_user_1'); + expect(sent[1].body.properties.alart).toBeUndefined(); + expect(sent[1].body.properties.att_status).toBe(3); + }); + + test('after one fallback, IDFA events go straight to ingest for a cool-down, then the tracking host is tried again', async () => { + trackingHostFails = true; + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + await flushNow(q); + await flushNow(q); // second failure → fallback to ingest, delivered + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['a', TRACKING], ['a', INGEST]]); + + sent = []; + await enqueueQuiet(q, payload('b')); + await enqueueQuiet(q, payload('c')); + await flushNow(q); + // No tracking-host attempt during the cool-down: each delivered at once, without the IDFA. + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['b', INGEST], ['c', INGEST]]); + expect(sent.every((s) => s.body.properties.idfa === undefined)).toBe(true); + expect(sent.every((s) => s.body.properties.att_status === 3)).toBe(true); + expect(q.getStats().queueSize).toBe(0); + + // After the cool-down the tracking host is tried again (here it works again). + const realNow = Date.now; + const later = realNow() + 11 * 60 * 1000; + jest.spyOn(Date, 'now').mockImplementation(() => later); + try { + trackingHostFails = false; + sent = []; + await enqueueQuiet(q, payload('d')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['d', TRACKING]]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + } finally { + (Date.now as jest.Mock).mockRestore?.(); + } + }); + + test('both hosts down (offline-like) does not start the cool-down', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + return Promise.reject(new TypeError('Network request failed')); + }; + for (let i = 0; i < 3; i++) await flushNow(q); + installFetch(); + sent = []; + await flushNow(q); + expect(sent.map((s) => s.url)).toEqual([TRACKING]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + }); +}); diff --git a/tests/tracking-host-send-time.test.ts b/tests/tracking-host-send-time.test.ts new file mode 100644 index 00000000..7ffe9419 --- /dev/null +++ b/tests/tracking-host-send-time.test.ts @@ -0,0 +1,365 @@ +// iOS fails every request to a domain the privacy manifest lists under +// NSPrivacyTrackingDomains (tracking.datalyr.com) while the app's App Tracking Transparency +// status is not "authorized", checked when the request is SENT. The host used to be chosen +// from the IDFA copied into the event when it was BUILT, so an event queued while tracking +// was allowed and sent after the user turned it off went to a blocked host. The failure is a +// network error: no retry is spent, the drain backs off, and every later event from the +// device waits behind it for as long as tracking stays off. +// +// Now: the tracking host is used only when the event has an IDFA AND the live ATT status, +// read at send time, is authorized (3). Otherwise the event goes to ingest.datalyr.com with +// the IDFA and the other tracking-only fields removed. A tracking-host request that keeps +// failing with a network error falls back to ingest (without the IDFA) so it cannot hold the +// queue. Android has no tracking-domain block and is unchanged. + +jest.mock('expo-application', () => ({ + nativeApplicationVersion: '1.0.0', + nativeBuildVersion: '1', + applicationId: 'com.datalyr.test', + getInstallationTimeAsync: async () => new Date(0), +}), { virtual: true }); + +jest.mock('expo-device', () => ({ + modelName: 'Test Device', + deviceName: 'Test Device', + manufacturer: 'Test', + osVersion: '17.0', + isDevice: true, +}), { virtual: true }); + +jest.mock('expo-network', () => ({ + NetworkStateType: { WIFI: 'WIFI' }, + getNetworkStateAsync: async () => ({ type: 'WIFI', isConnected: true }), +}), { virtual: true }); + +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { AppState, Platform } from 'react-native'; +import { EventQueue } from '../src/event-queue'; +import { HttpClient } from '../src/http-client'; +import { DatalyrSDK } from '../src/datalyr-sdk'; +import { DatalyrSDKExpo } from '../src/datalyr-sdk-expo'; +import { attributionManager } from '../src/attribution'; +import { journeyManager } from '../src/journey'; +import { AdvertiserInfoBridge } from '../src/native/DatalyrNativeBridge'; +import type { EventPayload } from '../src/types'; + +const INGEST = 'https://ingest.datalyr.com/track'; +const TRACKING = 'https://tracking.datalyr.com/track'; +const IDFA = '6D92078A-8246-4BA4-AE5B-76104861E7DC'; + +type Sent = { url: string; body: any }; +let sent: Sent[] = []; +// The live ATT status the provider reports (undefined = unknown / no native module). +let liveStatus: number | undefined = 3; +let providerCalls = 0; +// When true, every request to the tracking host fails the way iOS fails a blocked +// tracking domain: React Native's fetch rejects with TypeError('Network request failed'). +let trackingHostFails = false; + +const ok = () => ({ ok: true, status: 200, statusText: 'OK', headers: { get: () => null }, json: async () => ({}) }); + +const installFetch = () => { + (globalThis as any).fetch = async (url: string, init: any) => { + const u = String(url); + if (u.startsWith(INGEST) || u.startsWith(TRACKING)) { + sent.push({ url: u, body: JSON.parse(init.body) }); + // iOS blocks the declared tracking domain unless ATT is authorized at send time. + if (u.startsWith(TRACKING) && (trackingHostFails || liveStatus !== 3)) { + return Promise.reject(new TypeError('Network request failed')); + } + } + return ok(); + }; +}; + +const makePayload = (name: string, data: Record = {}): EventPayload => ({ + workspaceId: 'ws_test', + visitorId: 'anon_test', + anonymousId: 'anon_test', + sessionId: 'sess_test', + eventId: `evt_${name}`, + eventName: name, + eventData: data, + source: 'mobile_app', + timestamp: new Date(0).toISOString(), +}); + +// What the SDK copies onto every event while ATT is authorized. +const authorizedFields = (extra: Record = {}) => ({ + idfa: IDFA, + idfv: 'IDFV-TEST', + att_status: 3, + advertiser_tracking_enabled: true, + ...extra, +}); + +const newClient = () => { + const client = new HttpClient(INGEST, { apiKey: 'test_key_not_real', maxRetries: 0, retryDelay: 1, timeout: 50, debug: false, useServerTracking: true }); + (client as any).setTrackingAuthorizationProvider?.(async () => { providerCalls++; return liveStatus; }); + // Tracking was already authorized when this process started (see + // tracking-host-process-start.test.ts for the other case). + (client as any).setTrackingStatusAtProcessStartProvider?.(async () => 3); + return client; +}; + +const newQueue = async (client: HttpClient) => { + const q = new EventQueue(client, { maxQueueSize: 100, batchSize: 10, flushInterval: 999999, maxRetryCount: 3 }); + await new Promise((r) => setTimeout(r, 10)); // initializeQueue settles + return q; +}; +const enqueueQuiet = async (q: EventQueue, p: EventPayload) => { + (q as any).isOnline = false; + await q.enqueue(p); + (q as any).isOnline = true; +}; +const flushNow = async (q: EventQueue) => { + (q as any).retryNotBefore = 0; + await q.flush(); +}; + +/** Neither leak: tracking host only with an IDFA and authorized; never an IDFA on ingest. */ +const expectNoLeak = () => { + for (const s of sent) { + if (s.url === TRACKING) { + expect(s.body.properties.idfa).toBe(IDFA); + } else { + expect(s.body.properties.idfa).toBeUndefined(); + } + } +}; + +beforeEach(async () => { + await (AsyncStorage as any).clear(); + sent = []; + liveStatus = 3; + providerCalls = 0; + trackingHostFails = false; + installFetch(); +}); + +afterEach(() => { + jest.restoreAllMocks(); +}); + +describe('host chosen from the live ATT status at send time', () => { + test('authorized + IDFA → tracking host, IDFA kept', async () => { + const client = newClient(); + const res = await client.sendEvent(makePayload('purchase', authorizedFields({ value: 5 }))); + expect(res.success).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0].url).toBe(TRACKING); + expect(sent[0].body.properties.idfa).toBe(IDFA); + expect(sent[0].body.properties.att_status).toBe(3); + expect(sent[0].body.properties.advertiser_tracking_enabled).toBe(true); + }); + + test.each([ + ['denied', 2], + ['restricted', 1], + ['not determined', 0], + ])('%s + stale IDFA → ingest, IDFA and tracking-only fields removed', async (_name, status) => { + liveStatus = status; + const client = newClient(); + const res = await client.sendEvent(makePayload('app_install', authorizedFields({ alart: 'applovin_user_1', value: 5 }))); + expect(res.success).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0].url).toBe(INGEST); + const props = sent[0].body.properties; + expect(props.idfa).toBeUndefined(); + expect(props.alart).toBeUndefined(); + // The event no longer claims tracking is allowed. + expect(props.att_status).toBe(status); + expect(props.advertiser_tracking_enabled).toBe(false); + // Everything else is kept. + expect(props.idfv).toBe('IDFV-TEST'); + expect(props.value).toBe(5); + }); + + test('status unknown (native read failed) + stale IDFA → ingest, IDFA removed', async () => { + liveStatus = undefined; + const client = newClient(); + await client.sendEvent(makePayload('purchase', authorizedFields())); + expect(sent[0].url).toBe(INGEST); + expect(sent[0].body.properties.idfa).toBeUndefined(); + expect(sent[0].body.properties.advertiser_tracking_enabled).toBe(false); + }); + + test('the stored event is not changed by the strip (a later authorized send keeps the IDFA)', async () => { + liveStatus = 2; + const client = newClient(); + const payload = makePayload('purchase', authorizedFields()); + await client.sendEvent(payload); + expect(payload.eventData!.idfa).toBe(IDFA); + }); + + test('no IDFA → ingest, and no native status read', async () => { + const client = newClient(); + await client.sendEvent(makePayload('screen', { screen: 'home', att_status: 2, advertiser_tracking_enabled: false })); + expect(sent[0].url).toBe(INGEST); + expect(sent[0].body.properties.att_status).toBe(2); + expect(providerCalls).toBe(0); + }); +}); + +describe('queue', () => { + test('queued while authorized, sent after tracking was turned off → ingest, no IDFA, later events not held', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields({ value: 9 }))); + liveStatus = 2; // user turns tracking off in Settings + await enqueueQuiet(q, makePayload('screen', { att_status: 2, advertiser_tracking_enabled: false })); + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.url)).toEqual([INGEST, INGEST]); + expect(sent[0].body.event).toBe('purchase'); + expect(sent[0].body.properties.value).toBe(9); + expectNoLeak(); + }); + + test('mixed batch, not authorized: nothing goes to the tracking host, no IDFA on ingest', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('a', authorizedFields())); + await enqueueQuiet(q, makePayload('b', { screen: 'home' })); + await enqueueQuiet(q, makePayload('c', authorizedFields())); + liveStatus = 1; + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.body.event)).toEqual(['a', 'b', 'c']); + expect(sent.every((s) => s.url === INGEST)).toBe(true); + expectNoLeak(); + }); + + test('mixed batch, authorized: IDFA events to the tracking host, the rest to ingest', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('a', authorizedFields())); + await enqueueQuiet(q, makePayload('b', { screen: 'home' })); + await enqueueQuiet(q, makePayload('c', authorizedFields())); + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['b', INGEST], ['c', TRACKING]]); + expectNoLeak(); + }); + + test('a tracking-host request that keeps failing does not hold later events', async () => { + // Authorized, but the tracking host fails every time (a block we cannot see, DNS, a + // zone rule). The ingest host works. + trackingHostFails = true; + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields({ value: 3 }))); + await enqueueQuiet(q, makePayload('later_1', { screen: 'a' })); + await enqueueQuiet(q, makePayload('later_2', { screen: 'b' })); + + for (let i = 0; i < 4 && q.getStats().queueSize > 0; i++) await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + const delivered = sent.filter((s) => s.url === INGEST).map((s) => s.body.event); + expect(delivered).toEqual(['purchase', 'later_1', 'later_2']); + // Delivered without the IDFA, same eventId (ingest de-duplicates a lost answer). + const purchase = sent.find((s) => s.url === INGEST && s.body.event === 'purchase')!; + expect(purchase.body.properties.idfa).toBeUndefined(); + expect(purchase.body.properties.value).toBe(3); + expect(purchase.body.eventId).toBe('evt_purchase'); + expectNoLeak(); + }); + + test('a real outage (both hosts down) keeps the event with its IDFA; delivered to the tracking host once back', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields())); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + return Promise.reject(new TypeError('Network request failed')); + }; + for (let i = 0; i < 4; i++) await flushNow(q); + expect(q.getStats().queueSize).toBe(1); + expect((q as any).queue[0].payload.eventData.idfa).toBe(IDFA); + + sent = []; + installFetch(); + await flushNow(q); + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.url)).toEqual([TRACKING]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + }); +}); + +// SDK wiring: the live status comes from the native module at send time on iOS; Android +// keeps its delivery exactly as before. +const sdkVariants: Array<[string, () => any]> = [ + ['bare React Native', () => new DatalyrSDK()], + ['Expo', () => new DatalyrSDKExpo()], +]; + +describe.each(sdkVariants)('%s SDK', (_variant, createSDK) => { + let native: any; + const resetManagers = async () => { + const { networkStatusManager } = require('../src/network-status'); + networkStatusManager.destroy(); + await attributionManager.clearAttributionData(); + (attributionManager as any).initialized = false; + (attributionManager as any).isFirstLaunch = false; + await journeyManager.clearJourney(); + }; + + beforeEach(async () => { + await resetManagers(); + (AppState as any).addEventListener = () => ({ remove: () => {} }); + jest.spyOn(AdvertiserInfoBridge, 'getAdvertiserInfo').mockImplementation(async () => native); + }); + + const init = async (sdk: any) => { + await sdk.initialize({ apiKey: 'dk_test', flushInterval: 999999, enableAutoEvents: false, enableWebToAppAttribution: false }); + }; + + test('iOS: event built while authorized, tracking turned off before the send → ingest without the IDFA', async () => { + native = { idfa: IDFA, idfv: 'IDFV-TEST', att_status: 3, advertiser_tracking_enabled: true }; + const sdk = createSDK(); + try { + await init(sdk); + const q = (sdk as any).eventQueue; + q.isOnline = false; + await sdk.track('purchase', { value: 1 }); + // Settings → tracking off. The app's cached advertiser info still says authorized. + native = { idfv: 'IDFV-TEST', att_status: 2, advertiser_tracking_enabled: false }; + liveStatus = 2; + sent = []; + q.isOnline = true; + q.retryNotBefore = 0; + await q.flush(); + + const purchase = sent.filter((s) => s.body.event === 'purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(purchase[0].body.properties.att_status).toBe(2); + expect(q.getStats().queueSize).toBe(0); + } finally { + sdk.destroy(); + } + }); + + test('Android: unchanged (GAID kept, ingest host, no extra native reads per send)', async () => { + const original = Platform.OS; + (Platform as any).OS = 'android'; + native = { gaid: 'GAID-TEST', att_status: 3, advertiser_tracking_enabled: true }; + const sdk = createSDK(); + try { + await init(sdk); + const reads = (AdvertiserInfoBridge.getAdvertiserInfo as jest.Mock).mock.calls.length; + sent = []; + await sdk.track('purchase', { value: 1 }); + await (sdk as any).eventQueue.flush(); + const purchase = sent.filter((s) => s.body.event === 'purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.gaid).toBe('GAID-TEST'); + expect(purchase[0].body.properties.att_status).toBe(3); + expect(purchase[0].body.properties.advertiser_tracking_enabled).toBe(true); + expect((AdvertiserInfoBridge.getAdvertiserInfo as jest.Mock).mock.calls.length).toBe(reads); + } finally { + sdk.destroy(); + (Platform as any).OS = original; + } + }); +});