journeyiq 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # Flow Analytics SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Browser event tracking for React, Angular and other JavaScript apps. This package contains the SDK only; a separately running Flow Analytics collector receives event batches.
4
+
5
+ ```ts
6
+ import { initFlowAnalytics } from "journeyiq";
7
+
8
+ // Initialize only after the visitor has granted the required consent.
9
+ const analytics = initFlowAnalytics({
10
+ siteId: "site_demo",
11
+ capturePath: true // Only if all pathnames are approved and non-sensitive.
12
+ });
13
+
14
+ analytics.track("add_to_cart", { product_id: "product-123" });
15
+ ```
16
+
17
+ Call `initFlowAnalytics` once in the browser, not during server-side rendering. Importing the package does not start tracking, but initialization starts it by default; initialize only after required consent. To initialize before consent, set `autoConsent: false` and call `analytics.setConsent(true)` only after consent is granted. Repeated initialization in the same window returns the existing instance; choose either this package or the script-tag integration, not both. Use `analytics.setConsent(false)` to stop tracking and clear queued events. Withdrawal is not persisted as a consent decision; the application must prevent automatic reactivation on reload unless consent is granted again.
18
+
19
+ The ingestion endpoint is built into the SDK; customers do not configure it. It currently points to `http://localhost:3000/v1/events` **for local testing only**. Before publishing for customers, the provider must replace `INGESTION_URL` in `sdk.ts` with the deployed HTTPS ingestion URL and rebuild. `localhost` refers to the end user's machine and will not reach your hosted collector. The optional `collectorUrl` selects the separate legacy log-collector protocol instead.
20
+
21
+ The collector must allow the frontend origin. Use an HTTPS collector URL outside local development; the site ID is public and is not authentication. The legacy `projectId` option remains supported; if both are supplied, their values must match. The package does not contain database credentials or write directly to ClickHouse.
22
+
23
+ Optional initialization settings include `autoConsent`, `capturePath`, `resolvePagePath`, `persistVisitor`, and `captureCampaign`. The default ingestion mode requires `capturePath: true` or an approved `resolvePagePath`, uses a 30-minute inactivity timeout, and limits a session to 24 hours. `authenticatedSession`, `sessionTimeoutMs`, and legacy-only signals require an explicit legacy `collectorUrl`. After consent, the session and visitor ID are stored in per-tab `sessionStorage`, so the same session survives reloads within the inactivity limit. The application must verify consent before initializing on each page load. Clearing or blocking storage prevents reliable restoration, and separate tabs generally have separate sessions. `persistVisitor` additionally enables a longer-lived visitor ID in local storage. Identifier storage, path collection, campaign data, and network instrumentation require a privacy review. Never put personal information, secrets, or field values in event names, IDs, or custom metadata.
24
+
25
+ After consent, the first page view of a session captures the referrer hostname and valid `utm_source`, `utm_medium` and `utm_campaign` values by default. Set `captureCampaign: false` to disable this. The SDK cannot determine whether campaign values contain personal information; review them before enabling collection.
26
+
27
+ ## ClickHouse ingestion API
28
+
29
+ To send to the separate ingestion service instead of the local log collector, provide the backend's site ID. The endpoint is built into the SDK:
30
+
31
+ ```ts
32
+ // Initialize only after required consent.
33
+ const analytics = initFlowAnalytics({
34
+ siteId: "site_demo", // Sent as site_id.
35
+ // Return only approved, non-sensitive route templates; suppress other routes.
36
+ resolvePagePath: (path) => path === "/products" ? "/products" : undefined
37
+ });
38
+ ```
39
+
40
+ For reviewed, non-sensitive static paths, `capturePath: true` can be used instead of `resolvePagePath`. It sends raw pathnames without query strings or fragments; it does not automatically remove personal data from paths. The backend must configure the site ID, frontend hostname and CORS origin. Obtain the real deployed URL and site ID from that team; this repository does not implement the ClickHouse service.
41
+
42
+ Ingestion mode uses the API's 30-minute inactivity timeout and 24-hour maximum session, not the legacy 15-minute default; `sessionTimeoutMs` and `authenticatedSession` cannot be used in this mode. Page views, click coordinates, scroll milestones and sanitized errors are automatic. Mark approved products with `data-track-product`; mark forms with `data-track` and selected fields with `data-track-field`. The optional click layout is the root element's `data-track-layout`. Values must be non-personal safe labels.
43
+
44
+ Ingestion events include available `viewport_width`, `viewport_height`, `screen_width`, `screen_height`, `device_pixel_ratio`, `viewport_width_percent` and `viewport_height_percent` in `properties.viewport`. Click and scroll events also have a `properties.heat_map` object containing display and page dimensions, scroll offsets, and (for pointer clicks) viewport and document coordinates. Nested scroll containers include their dimensions, offsets and click positions relative to their content. Scroll milestones of 25%, 50%, 75%, 90% and 100% are tracked once per document or container per page view. Optional `data-track-scroll-container` IDs make container grouping more stable; otherwise structural paths can change. Scrollable containers are tracked when scrolled, not scanned on load. Inputs and editable content are excluded from click capture; legacy events do not have `heat_map`.
45
+
46
+ **Update the backend before deploying:** The new event types, properties, optional common `release`, and nested `properties.viewport` and `properties.heat_map` extend the original strict ingestion contract. Its event/property validation and ClickHouse mapping must accept nested JSON, or the API can reject the entire batch with HTTP 400. The external backend is not included here. `api_request` replaces the previous `api_error`. Unavailable measurements are omitted. Percentages are viewport size divided by screen size, multiplied by 100 and rounded to two decimal places; they can exceed 100. Device-pixel ratio is not physical DPI or a reliable browser zoom percentage. Responsive layouts, sticky/fixed elements, CSS transforms, shadow DOM and iframes require additional handling. The SDK does not capture screenshots or render a heat map. Review location and display measurements for privacy and fingerprinting.
47
+
48
+ After consent, uncaught UI exceptions, unhandled promise rejections and resource-load failures produce sanitized `js_error` events. Failed browser `fetch` and XMLHttpRequest calls automatically produce `api_request` events containing the actual origin and pathname, including dynamic segments. Paths or hostnames can contain personal data or secrets; review them before collection. Paths longer than 2,048 characters or origins longer than 512 characters are dropped with the event. Optionally configure reviewed operations with `networkPaths: ["GET /api/products/:id", "POST /api/checkout"]` to receive success events using approved templates. A `:name` matches a single nonempty segment; a path without a method approves all methods. `properties` include `endpoint`, `endpoint_origin`, `method`, `outcome`, `duration_ms`, optional `status`, and optional best-effort `interaction_id`. Query strings, fragments, URL credentials, bodies, headers, exception messages and stacks are not collected. Cancellations, opaque fetch responses, framework-caught exceptions, requests before consent and application failures hidden in HTTP 200 responses are not automatically reported. Requests are attributed to the page current at completion; the SDK excludes its own ingestion requests. Legacy collector events retain their previous redacted/template behavior.
49
+
50
+ Form visibility (`form_view`), start and submission events require safe form/field attributes as above. Automatic `form_submit` creates an `attempt_id`; read `analytics.getFormAttemptId("checkout")` synchronously in the submit handler and retain it for the matching result. It returns only the most recent attempt per form in this tab, in memory, and clears on session reset or consent withdrawal. Emit confirmed outcomes explicitly, e.g. `analytics.track("form_success", { form_id: "checkout", attempt_id: attemptId })` when an ID is available. `form_error` requires a safe `error_code`; `form_step_complete` requires `step_id`; `validation_error` requires `form_id`, `field_id` and `category`, with optional `attempt_id`. Never include field values. A backend-confirmed result requires the app to pass the non-secret attempt ID to that backend; the SDK does not do this automatically. `form_attempt` is derived from `form_submit`, not emitted separately.
51
+
52
+ The SDK also emits supported initial-document `web_vital` events (`LCP`, `INP`, `CLS`), incremental approximate `engagement` events with observation interval timestamps, and `friction` events for the existing rage-click heuristic. Observation windows do not imply continuous activity. `release` and `pageVersion` initialization options supply safe labels. Ingestion clicks include the HTML `id` as `element_id` (falling back to `data-track`), the HTML `name` as `element_name` (falling back to `data-track-name`), plus `element_tag` and `element_role`. Only non-personal labels containing letters, digits, `.`, `_` or `-` (up to 80 characters) are eligible; the SDK cannot determine whether an otherwise valid label contains personal data, so review IDs and names. SPA-route vitals, dead-click detection and repeated-error friction are not implemented. Outcomes confirmed by the app or backend still require explicit tracking.
53
+
54
+ In ingestion mode, visible clicked text and form values are off by default. After consent, mark individually approved elements with `data-track-capture-text="true"` for `properties.element_text`, or fields with `data-track-field="category" data-track-capture-value="true"` for `properties.form_values` on a tracked form's submit event. Up to 20 values are sent per submission, at most 200 characters each; captured text is also capped at 200 characters. Passwords, hidden and unsupported types, disabled controls, multiple selects, unchecked checkboxes/radio buttons and fields with sensitive name/autocomplete hints are excluded. These safeguards cannot detect sensitive data entered into a marked free-text field or rendered in marked text. Only mark verified non-personal content and review privacy, consent, security and retention. The ingestion backend must accept the new properties; legacy collector events do not include them.
55
+
56
+ Only HTTP 204 acknowledges a batch. Network errors and retryable failures retain the same event IDs and payload, with backoff. Oversized batches are split; an unsplittable event is dropped. The queue is memory-only, capped at 200, and drops events older than 24 hours, so delivery is best-effort. A keepalive fetch is attempted on page hide; it is not proof of delivery. Consent withdrawal clears pending events and stored IDs.
57
+
58
+ For local debugging, set `debug: true` in `initFlowAnalytics` to print the exact outgoing ingestion JSON batch in the browser console. Debugging is off by default, only prints after consent and may print retries again. Printed batches can contain identifiers and paths; do not enable this in production. A console print is not an ingestion acknowledgement.
59
+
60
+ ## Authenticated sessions
61
+
62
+ To group events for the lifetime of an app login rather than an inactivity-based visit:
63
+
64
+ ```ts
65
+ // Initialize only after required consent.
66
+ const analytics = initFlowAnalytics({
67
+ projectId: "demo",
68
+ collectorUrl: "http://localhost:8081",
69
+ authenticatedSession: true
70
+ });
71
+
72
+ analytics.setAuthenticatedSession(analyticsSessionId); // From the app's backend.
73
+
74
+ // When the app logs out or the login session is confirmed invalid:
75
+ analytics.endAuthenticatedSession();
76
+ ```
77
+
78
+ The backend must return the same **separate, non-secret UUID v4** when it restores the same login session, and a new UUID after logout and a new login. Never pass an access token, refresh token, auth cookie, actual auth session ID or user ID. A successful token refresh should not end the session. Verify consent before initialization and supply the UUID again on each page load after verifying authentication. The SDK collects no authenticated-session events until the ID has been supplied and does not verify authentication itself.
79
+
80
+ The SDK stores session state in `sessionStorage` after consent for same-tab sequence continuity. There is no inactivity timeout in this mode. The application must signal logout in every tab; tabs may have duplicate sequences or `session_start` events, so sequence is not a global cross-tab ordering. Clearing or blocking storage can also reset the sequence. Session-end delivery is best-effort, and consent withdrawal clears stored state. The anonymous visitor ID is stored per tab unless `persistVisitor` additionally enables local storage. Default inactivity-based sessions remain available when `authenticatedSession` is not enabled.
81
+
82
+ Labels such as `data-track="add-to-cart"` provide names for automatically captured clicks. Events are queued in memory and sent in small batches; delivery is best-effort and duplicates are possible. This starter is not production-ready: the collector needs rate limiting, access controls, retention, and other safeguards before public exposure.
83
+
84
+ ## Session replay
85
+
86
+ After required consent, the SDK records strict, masked rrweb segments and links analytics events through `properties.replay_id`. The provider-owned segment endpoint is `REPLAY_URL` in `sdk.ts`, currently `http://localhost:3000/api/segments` for local testing; deploy it over HTTPS before publishing. The SDK host and the event ingestion API do not provide this endpoint automatically. No extra customer URL setting is needed. The backend must support the segmented JSON contract, CORS, validation, authorization and deduplication by site/replay/segment index. Site IDs must match `[A-Za-z0-9_-]{1,64}` for replay.
87
+
88
+ The replay ID and segment sequence survive reloads within the same stored analytics session; session rollover starts a new replay. Recording masks text and blocks inputs and media, but DOM structure, timing and coordinates can still be sensitive. Delivery is bounded and best-effort, especially during unload or network failures; there is no viewer or server implementation in this package. Consent withdrawal stops capture and clears pending data but cannot delete already uploaded data. See the starter README for the full segment contract and limitations.
@@ -0,0 +1,41 @@
1
+ import { type FlowMetadata } from "./shared.js";
2
+ export type FlowAnalyticsOptions = ({
3
+ siteId: string;
4
+ projectId?: string;
5
+ } | {
6
+ siteId?: undefined;
7
+ projectId: string;
8
+ }) & {
9
+ collectorUrl?: string;
10
+ /** Initialize only after consent; set false to wait for an explicit setConsent(true). */
11
+ autoConsent?: boolean;
12
+ /** Print outgoing ingestion batches to the browser console for local debugging. */
13
+ debug?: boolean;
14
+ capturePath?: boolean;
15
+ /** Return an approved route template, or undefined to suppress events for that route. */
16
+ resolvePagePath?: (pathname: string) => string | undefined;
17
+ persistVisitor?: boolean;
18
+ authenticatedSession?: boolean;
19
+ captureCampaign?: boolean;
20
+ release?: string;
21
+ pageVersion?: string;
22
+ networkPaths?: string[];
23
+ sessionTimeoutMs?: number;
24
+ rageIntervalMs?: number;
25
+ rageRadiusPx?: number;
26
+ };
27
+ export interface FlowAnalyticsApi {
28
+ setConsent(granted: boolean): void;
29
+ setAuthenticatedSession(id: string): void;
30
+ endAuthenticatedSession(): void;
31
+ /** Most recent automatically captured form submission in this tab and session. */
32
+ getFormAttemptId(formId: string): string | undefined;
33
+ track(name: string, metadata?: FlowMetadata): void;
34
+ flush(): Promise<void>;
35
+ }
36
+ declare global {
37
+ interface Window {
38
+ FlowAnalytics?: FlowAnalyticsApi;
39
+ }
40
+ }
41
+ export declare function initFlowAnalytics(options: FlowAnalyticsOptions): FlowAnalyticsApi;