mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 08:30:25 +08:00
Integrate the reviewed change after successful current-head CI and focused validation against the latest main.
20 lines
1.3 KiB
TypeScript
20 lines
1.3 KiB
TypeScript
import { createTracker } from './core.ts';
|
|
import type { Registry } from './core.ts';
|
|
export function createBrowserTracking<const R extends Registry>(options: { endpoint: string; registry: R; enabled: boolean; flushIntervalMs?: number; isEnabled?: () => boolean }) {
|
|
const endpoint = new URL(options.endpoint, window.location.href);
|
|
if (endpoint.origin !== window.location.origin || endpoint.username || endpoint.password) throw new Error('SAME_ORIGIN_REQUIRED');
|
|
const context = new URLSearchParams(window.location.search).get('tracking_context');
|
|
if (context && /^[0-9a-f-]{36}$/i.test(context)) endpoint.searchParams.set('context', context);
|
|
const tracking = createTracker({ ...options, entrypoint: 'studio', send: async (events, signal) => {
|
|
try {
|
|
const response = await fetch(endpoint, { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ events }), keepalive: true, signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]) });
|
|
if (!response.ok) return response.status >= 500 || response.status === 429 ? 'retry' : 'drop';
|
|
const receipt = await response.json() as { enabled?: boolean };
|
|
if (receipt.enabled === false) tracking.setEnabled(false);
|
|
return 'accepted';
|
|
} catch { return 'retry'; }
|
|
} });
|
|
return tracking;
|
|
}
|