journeyiq 0.2.0 → 0.2.1
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 +90 -88
- package/dist/index.d.ts +6 -0
- package/dist/index.js +289 -120
- package/dist/screenshots.d.ts +27 -0
- package/package.json +24 -23
package/README.md
CHANGED
|
@@ -1,88 +1,90 @@
|
|
|
1
|
-
# Flow Analytics SDK
|
|
2
|
-
|
|
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://
|
|
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
|
|
87
|
-
|
|
88
|
-
The
|
|
1
|
+
# Flow Analytics SDK
|
|
2
|
+
|
|
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://172.16.181.11:5192/v1/events` for internal network testing. Clients need access to that private network or VPN. Use HTTPS before integrating into HTTPS-hosted or public apps, and configure backend CORS for the frontend origin. 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 sanitized rrweb events and links analytics events through top-level `replay_id`. On replay end it requests a signed URL from `http://172.16.181.11:5192/v1/replays/uploads` and PUTs one JSON array of rrweb events to Azurite at `http://172.16.181.11:11000/devstoreaccount1/`. The API must generate the key, return a signed URL and make repeated requests for the same replay ID idempotent. Site IDs must match `[A-Za-z0-9_-]{1,64}`.
|
|
87
|
+
|
|
88
|
+
The default screenshot upload endpoint is `http://172.16.181.11:5192/api/replay-captures`. Screenshot capture remains opt-in and its security validation requires HTTPS for non-loopback hosts; configure a trusted HTTPS `screenshots.uploadUrl` before enabling it. This HTTP default is not accepted by screenshot capture.
|
|
89
|
+
|
|
90
|
+
SPA routes share a replay ID; reload and session rollover start a new replay ID. Recording masks text and blocks inputs and media, but DOM structure, timing and coordinates can still be sensitive. The in-memory replay is limited to approximately two million JSON characters. Upload occurs at replay end and is best-effort; reload or tab closure may interrupt the two-step request, and unsent recordings can be lost. Consent withdrawal clears pending data but cannot delete already uploaded data. Configure CORS and use HTTPS for public deployments. There is no viewer or server implementation in this package.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type FlowMetadata } from "./shared.js";
|
|
2
|
+
import { type ScreenshotOptions, type ScreenshotResult } from "./screenshots.js";
|
|
3
|
+
export type { ScreenshotOptions, ScreenshotResult } from "./screenshots.js";
|
|
2
4
|
export type FlowAnalyticsOptions = ({
|
|
3
5
|
siteId: string;
|
|
4
6
|
projectId?: string;
|
|
@@ -23,6 +25,8 @@ export type FlowAnalyticsOptions = ({
|
|
|
23
25
|
sessionTimeoutMs?: number;
|
|
24
26
|
rageIntervalMs?: number;
|
|
25
27
|
rageRadiusPx?: number;
|
|
28
|
+
/** Opt-in manual PNG capture; configure an authorized upload API before use. */
|
|
29
|
+
screenshots?: ScreenshotOptions;
|
|
26
30
|
};
|
|
27
31
|
export interface FlowAnalyticsApi {
|
|
28
32
|
setConsent(granted: boolean): void;
|
|
@@ -32,6 +36,8 @@ export interface FlowAnalyticsApi {
|
|
|
32
36
|
getFormAttemptId(formId: string): string | undefined;
|
|
33
37
|
track(name: string, metadata?: FlowMetadata): void;
|
|
34
38
|
flush(): Promise<void>;
|
|
39
|
+
/** Runtime authorization headers go only to the configured screenshot API. */
|
|
40
|
+
captureScreenshot(headers?: HeadersInit): Promise<ScreenshotResult>;
|
|
35
41
|
}
|
|
36
42
|
declare global {
|
|
37
43
|
interface Window {
|
package/dist/index.js
CHANGED
|
@@ -3998,136 +3998,143 @@ function cleanReplayEvent(event) {
|
|
|
3998
3998
|
|
|
3999
3999
|
// replay.ts
|
|
4000
4000
|
var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
4001
|
+
var storageOrigin = "http://172.16.181.11:11000";
|
|
4001
4002
|
function createReplay(siteId, endpoint, send, recorder = record) {
|
|
4002
|
-
|
|
4003
|
-
let
|
|
4004
|
-
let
|
|
4005
|
-
let generation = 0;
|
|
4006
|
-
let buffer = [], buffered = 0, queue = [], queued = 0;
|
|
4003
|
+
let context, replayId = "", started = "";
|
|
4004
|
+
let stopRecord, active = false, generation = 0;
|
|
4005
|
+
let events = [], bytes = 0, queue = [], queued = 0;
|
|
4007
4006
|
let sending = false, retry;
|
|
4008
4007
|
let controller = new AbortController();
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
} catch {
|
|
4013
|
-
}
|
|
4014
|
-
}
|
|
4015
|
-
function clear() {
|
|
4016
|
-
try {
|
|
4017
|
-
sessionStorage.removeItem(key);
|
|
4018
|
-
} catch {
|
|
4019
|
-
}
|
|
4020
|
-
}
|
|
4021
|
-
function halt() {
|
|
4022
|
-
active = false;
|
|
4023
|
-
failed = true;
|
|
4024
|
-
generation++;
|
|
4025
|
-
stopRecord?.();
|
|
4026
|
-
stopRecord = void 0;
|
|
4027
|
-
buffer = [];
|
|
4028
|
-
buffered = 0;
|
|
4029
|
-
clear();
|
|
4008
|
+
try {
|
|
4009
|
+
sessionStorage.removeItem(`flow:${siteId}:replay`);
|
|
4010
|
+
} catch {
|
|
4030
4011
|
}
|
|
4031
4012
|
async function drain() {
|
|
4032
4013
|
if (sending || !queue.length || controller.signal.aborted) return;
|
|
4033
4014
|
sending = true;
|
|
4034
|
-
const current = controller,
|
|
4015
|
+
const current = controller, item = queue[0];
|
|
4035
4016
|
const timeout = setTimeout(() => current.abort(), 1e4);
|
|
4017
|
+
let discard2 = false;
|
|
4036
4018
|
try {
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4019
|
+
if (!item.url) {
|
|
4020
|
+
const response2 = await send(endpoint, {
|
|
4021
|
+
method: "POST",
|
|
4022
|
+
headers: { "Content-Type": "application/json" },
|
|
4023
|
+
body: JSON.stringify({ site_id: siteId, replay_id: item.id, replay_started_at: item.started, format: "rrweb-json" }),
|
|
4024
|
+
credentials: "omit",
|
|
4025
|
+
redirect: "error",
|
|
4026
|
+
keepalive: true,
|
|
4027
|
+
signal: current.signal
|
|
4028
|
+
});
|
|
4029
|
+
if (!response2.ok) {
|
|
4030
|
+
if (response2.status >= 400 && response2.status < 500 && response2.status !== 429) discard2 = true;
|
|
4031
|
+
throw new Error("Replay upload URL request failed");
|
|
4032
|
+
}
|
|
4033
|
+
const result = await response2.json();
|
|
4034
|
+
if (current !== controller || current.signal.aborted) return;
|
|
4035
|
+
try {
|
|
4036
|
+
const url = new URL(String(result.upload_url));
|
|
4037
|
+
if (!uuid.test(String(result.upload_id)) || result.method !== "PUT" || typeof result.expires_in_seconds !== "number" || !Number.isFinite(result.expires_in_seconds) || result.expires_in_seconds <= 0 || url.origin !== storageOrigin || !url.pathname.startsWith("/devstoreaccount1/") || url.username || url.password || url.hash || !url.searchParams.get("sig")) throw new Error("Invalid upload response");
|
|
4038
|
+
const headers = { "content-type": "application/json", "x-ms-blob-type": "BlockBlob" };
|
|
4039
|
+
if (result.headers !== void 0) {
|
|
4040
|
+
if (!result.headers || typeof result.headers !== "object" || Array.isArray(result.headers)) throw new Error("Invalid headers");
|
|
4041
|
+
for (const [key, value] of Object.entries(result.headers)) {
|
|
4042
|
+
if (!/^(content-type|x-ms-[a-z0-9-]+)$/i.test(key) || typeof value !== "string" || /[\r\n]/.test(value)) {
|
|
4043
|
+
throw new Error("Invalid header");
|
|
4044
|
+
}
|
|
4045
|
+
headers[key.toLowerCase()] = value;
|
|
4046
|
+
}
|
|
4047
|
+
}
|
|
4048
|
+
item.url = url.href;
|
|
4049
|
+
item.headers = headers;
|
|
4050
|
+
item.expires = Date.now() + result.expires_in_seconds * 1e3;
|
|
4051
|
+
} catch {
|
|
4052
|
+
discard2 = true;
|
|
4053
|
+
throw new Error("Invalid replay upload response");
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
if (current !== controller || current.signal.aborted) return;
|
|
4057
|
+
if (Date.now() >= item.expires) {
|
|
4058
|
+
discard2 = true;
|
|
4059
|
+
throw new Error("Replay upload URL expired");
|
|
4060
|
+
}
|
|
4061
|
+
const response = await send(item.url, {
|
|
4062
|
+
method: "PUT",
|
|
4063
|
+
headers: item.headers,
|
|
4064
|
+
body: item.body,
|
|
4041
4065
|
credentials: "omit",
|
|
4042
4066
|
redirect: "error",
|
|
4043
|
-
keepalive: new TextEncoder().encode(body).length < 6e4,
|
|
4067
|
+
keepalive: new TextEncoder().encode(item.body).length < 6e4,
|
|
4044
4068
|
signal: current.signal
|
|
4045
4069
|
});
|
|
4046
4070
|
if (!response.ok) {
|
|
4047
|
-
if (response.status >= 400 && response.status < 500 && response.status !== 429)
|
|
4048
|
-
queue = [];
|
|
4049
|
-
queued = 0;
|
|
4050
|
-
halt();
|
|
4051
|
-
console.warn("FlowAnalytics replay stopped: segment rejected");
|
|
4052
|
-
return;
|
|
4053
|
-
}
|
|
4071
|
+
if (response.status >= 400 && response.status < 500 && response.status !== 429) discard2 = true;
|
|
4054
4072
|
throw new Error("Replay upload failed");
|
|
4055
4073
|
}
|
|
4056
4074
|
if (current === controller && !current.signal.aborted) {
|
|
4057
4075
|
queue.shift();
|
|
4058
|
-
queued -= body.length;
|
|
4076
|
+
queued -= item.body.length;
|
|
4059
4077
|
}
|
|
4060
4078
|
} catch {
|
|
4061
|
-
if (current === controller) {
|
|
4062
|
-
if (
|
|
4079
|
+
if (current === controller && !current.signal.aborted) {
|
|
4080
|
+
if (discard2) {
|
|
4081
|
+
queue.shift();
|
|
4082
|
+
queued -= item.body.length;
|
|
4083
|
+
console.warn("FlowAnalytics replay upload rejected");
|
|
4084
|
+
} else {
|
|
4085
|
+
retry = setTimeout(() => {
|
|
4086
|
+
retry = void 0;
|
|
4087
|
+
void drain();
|
|
4088
|
+
}, 3e3);
|
|
4089
|
+
}
|
|
4090
|
+
} else if (current === controller) {
|
|
4091
|
+
controller = new AbortController();
|
|
4063
4092
|
retry = setTimeout(() => {
|
|
4064
4093
|
retry = void 0;
|
|
4065
4094
|
void drain();
|
|
4066
4095
|
}, 3e3);
|
|
4067
4096
|
}
|
|
4068
|
-
return;
|
|
4069
4097
|
} finally {
|
|
4070
4098
|
clearTimeout(timeout);
|
|
4071
4099
|
sending = false;
|
|
4100
|
+
if (!retry) void drain();
|
|
4072
4101
|
}
|
|
4073
|
-
if (current === controller) void drain();
|
|
4074
4102
|
}
|
|
4075
4103
|
function flush() {
|
|
4076
|
-
if (active && context && buffer.length) {
|
|
4077
|
-
const body = JSON.stringify({
|
|
4078
|
-
siteId,
|
|
4079
|
-
sessionId: context.sessionId,
|
|
4080
|
-
visitorId: context.visitorId,
|
|
4081
|
-
pageViewId: context.pageViewId,
|
|
4082
|
-
captureMode: "strict",
|
|
4083
|
-
replayId,
|
|
4084
|
-
segmentIndex: nextIndex++,
|
|
4085
|
-
events: buffer
|
|
4086
|
-
});
|
|
4087
|
-
save();
|
|
4088
|
-
buffer = [];
|
|
4089
|
-
buffered = 0;
|
|
4090
|
-
if (queued + body.length > 2e6) {
|
|
4091
|
-
halt();
|
|
4092
|
-
console.warn("FlowAnalytics replay stopped: segment queue limit reached");
|
|
4093
|
-
} else {
|
|
4094
|
-
queue.push(body);
|
|
4095
|
-
queued += body.length;
|
|
4096
|
-
}
|
|
4097
|
-
}
|
|
4098
4104
|
if (!retry) void drain();
|
|
4099
4105
|
}
|
|
4100
|
-
function
|
|
4101
|
-
if (context?.sessionId === next.sessionId) {
|
|
4102
|
-
if (context.pageViewId !== next.pageViewId) {
|
|
4103
|
-
flush();
|
|
4104
|
-
context = next;
|
|
4105
|
-
}
|
|
4106
|
-
return active ? replayId : "";
|
|
4107
|
-
}
|
|
4108
|
-
flush();
|
|
4106
|
+
function end() {
|
|
4109
4107
|
active = false;
|
|
4110
4108
|
generation++;
|
|
4111
4109
|
stopRecord?.();
|
|
4112
4110
|
stopRecord = void 0;
|
|
4113
|
-
|
|
4114
|
-
|
|
4111
|
+
if (replayId && events.length) {
|
|
4112
|
+
const body = JSON.stringify(events);
|
|
4113
|
+
if (queued + body.length <= 2e6) {
|
|
4114
|
+
queue.push({ id: replayId, started, body });
|
|
4115
|
+
queued += body.length;
|
|
4116
|
+
} else console.warn("FlowAnalytics replay upload skipped: memory limit reached");
|
|
4117
|
+
}
|
|
4118
|
+
events = [];
|
|
4119
|
+
bytes = 0;
|
|
4120
|
+
context = void 0;
|
|
4115
4121
|
replayId = "";
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
} catch {
|
|
4122
|
+
started = "";
|
|
4123
|
+
flush();
|
|
4124
|
+
}
|
|
4125
|
+
function setContext(next) {
|
|
4126
|
+
if (context?.sessionId === next.sessionId) {
|
|
4127
|
+
context = next;
|
|
4128
|
+
return active ? replayId : "";
|
|
4124
4129
|
}
|
|
4125
|
-
|
|
4126
|
-
|
|
4130
|
+
end();
|
|
4131
|
+
context = next;
|
|
4132
|
+
replayId = crypto.randomUUID();
|
|
4133
|
+
started = (/* @__PURE__ */ new Date()).toISOString();
|
|
4127
4134
|
try {
|
|
4128
4135
|
active = true;
|
|
4129
4136
|
const currentGeneration = generation;
|
|
4130
|
-
|
|
4137
|
+
const stop = recorder({
|
|
4131
4138
|
maskAllInputs: true,
|
|
4132
4139
|
maskTextSelector: "*",
|
|
4133
4140
|
maskTextFn: (text) => text.slice(0, 4096).replace(/\S/g, "*"),
|
|
@@ -4143,34 +4150,40 @@ function createReplay(siteId, endpoint, send, recorder = record) {
|
|
|
4143
4150
|
try {
|
|
4144
4151
|
const safe = cleanReplayEvent(event);
|
|
4145
4152
|
if (!safe) return;
|
|
4146
|
-
const size = JSON.stringify(safe).length;
|
|
4153
|
+
const size = JSON.stringify(safe).length + 1;
|
|
4147
4154
|
if (size > 5e5) throw new Error("Replay event too large");
|
|
4148
|
-
if (
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
|
|
4152
|
-
|
|
4155
|
+
if (queued + bytes + size > 1999998) {
|
|
4156
|
+
end();
|
|
4157
|
+
context = next;
|
|
4158
|
+
console.warn("FlowAnalytics replay stopped: memory limit reached");
|
|
4159
|
+
return;
|
|
4160
|
+
}
|
|
4161
|
+
events.push(safe);
|
|
4162
|
+
bytes += size;
|
|
4153
4163
|
} catch {
|
|
4154
|
-
|
|
4164
|
+
active = false;
|
|
4165
|
+
generation++;
|
|
4166
|
+
stopRecord?.();
|
|
4167
|
+
stopRecord = void 0;
|
|
4168
|
+
events = [];
|
|
4169
|
+
bytes = 0;
|
|
4155
4170
|
console.warn("FlowAnalytics replay stopped: event could not be safely recorded");
|
|
4156
4171
|
}
|
|
4157
4172
|
}
|
|
4158
4173
|
});
|
|
4159
|
-
if (!
|
|
4174
|
+
if (!stop || !active) {
|
|
4175
|
+
stop?.();
|
|
4176
|
+
active = false;
|
|
4177
|
+
events = [];
|
|
4178
|
+
bytes = 0;
|
|
4179
|
+
} else stopRecord = stop;
|
|
4160
4180
|
} catch {
|
|
4161
|
-
|
|
4181
|
+
active = false;
|
|
4182
|
+
events = [];
|
|
4183
|
+
bytes = 0;
|
|
4162
4184
|
}
|
|
4163
4185
|
return active ? replayId : "";
|
|
4164
4186
|
}
|
|
4165
|
-
function end() {
|
|
4166
|
-
flush();
|
|
4167
|
-
active = false;
|
|
4168
|
-
generation++;
|
|
4169
|
-
stopRecord?.();
|
|
4170
|
-
stopRecord = void 0;
|
|
4171
|
-
context = void 0;
|
|
4172
|
-
clear();
|
|
4173
|
-
}
|
|
4174
4187
|
function discard() {
|
|
4175
4188
|
active = false;
|
|
4176
4189
|
generation++;
|
|
@@ -4183,25 +4196,165 @@ function createReplay(siteId, endpoint, send, recorder = record) {
|
|
|
4183
4196
|
retry = void 0;
|
|
4184
4197
|
queue = [];
|
|
4185
4198
|
queued = 0;
|
|
4186
|
-
|
|
4187
|
-
|
|
4188
|
-
|
|
4199
|
+
events = [];
|
|
4200
|
+
bytes = 0;
|
|
4201
|
+
replayId = "";
|
|
4202
|
+
started = "";
|
|
4189
4203
|
}
|
|
4190
|
-
return {
|
|
4191
|
-
|
|
4192
|
-
|
|
4204
|
+
return {
|
|
4205
|
+
setContext,
|
|
4206
|
+
flush,
|
|
4207
|
+
end,
|
|
4208
|
+
discard,
|
|
4209
|
+
get id() {
|
|
4210
|
+
return active ? replayId : "";
|
|
4211
|
+
},
|
|
4212
|
+
get reference() {
|
|
4213
|
+
return context && replayId ? { ...context, replayId } : void 0;
|
|
4214
|
+
}
|
|
4215
|
+
};
|
|
4216
|
+
}
|
|
4217
|
+
|
|
4218
|
+
// screenshots.ts
|
|
4219
|
+
var blocked = "input,textarea,select,option,[contenteditable],canvas,iframe,object,embed,video,audio,svg,script,[data-sensitive],[data-rr-block],[data-screenshot-block]";
|
|
4220
|
+
async function renderPage(rendererUrl) {
|
|
4221
|
+
const module = rendererUrl ? await import(
|
|
4222
|
+
/* @vite-ignore */
|
|
4223
|
+
rendererUrl
|
|
4224
|
+
) : await import("html2canvas");
|
|
4225
|
+
const html2canvas = module.default;
|
|
4226
|
+
const origin = location.origin;
|
|
4227
|
+
return html2canvas(document.body, {
|
|
4228
|
+
x: window.scrollX,
|
|
4229
|
+
y: window.scrollY,
|
|
4230
|
+
width: Math.min(window.innerWidth, 1920),
|
|
4231
|
+
height: Math.min(window.innerHeight, 1080),
|
|
4232
|
+
windowWidth: window.innerWidth,
|
|
4233
|
+
windowHeight: window.innerHeight,
|
|
4234
|
+
scale: 1,
|
|
4235
|
+
useCORS: false,
|
|
4236
|
+
allowTaint: false,
|
|
4237
|
+
imageTimeout: 5e3,
|
|
4238
|
+
logging: false,
|
|
4239
|
+
removeContainer: true,
|
|
4240
|
+
ignoreElements(element) {
|
|
4241
|
+
if (element.closest(blocked)) return true;
|
|
4242
|
+
if (element.tagName !== "IMG") return false;
|
|
4243
|
+
if (element.getAttribute("data-screenshot-public") !== "true") return true;
|
|
4244
|
+
try {
|
|
4245
|
+
const url = new URL(element.currentSrc || element.getAttribute("src") || "", location.href);
|
|
4246
|
+
return !["http:", "https:"].includes(url.protocol) || url.origin !== origin || !!(url.username || url.password || url.search || url.hash);
|
|
4247
|
+
} catch {
|
|
4248
|
+
return true;
|
|
4249
|
+
}
|
|
4250
|
+
},
|
|
4251
|
+
onclone(clone) {
|
|
4252
|
+
for (const element of clone.querySelectorAll("body, body *")) {
|
|
4253
|
+
element.style?.setProperty("background-image", "none", "important");
|
|
4254
|
+
element.style?.setProperty("list-style-image", "none", "important");
|
|
4255
|
+
element.style?.setProperty("mask-image", "none", "important");
|
|
4256
|
+
}
|
|
4257
|
+
const style = clone.createElement("style");
|
|
4258
|
+
style.textContent = "body *::before,body *::after{content:none!important;background-image:none!important}";
|
|
4259
|
+
clone.head.appendChild(style);
|
|
4260
|
+
const walker = clone.createTreeWalker(
|
|
4261
|
+
clone.body,
|
|
4262
|
+
4
|
|
4263
|
+
/* SHOW_TEXT */
|
|
4264
|
+
);
|
|
4265
|
+
while (walker.nextNode()) {
|
|
4266
|
+
const node2 = walker.currentNode;
|
|
4267
|
+
const parent = node2.parentElement;
|
|
4268
|
+
if (parent?.closest("style,script,noscript")) continue;
|
|
4269
|
+
node2.textContent = (node2.textContent || "").slice(0, 4096).replace(/\S/g, "*");
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
});
|
|
4273
|
+
}
|
|
4274
|
+
function createScreenshots(uploadUrl, getContext, send, render, rendererUrl) {
|
|
4275
|
+
const url = new URL(uploadUrl);
|
|
4276
|
+
if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
4277
|
+
throw new Error("Screenshot API requires HTTPS except localhost, without credentials/query/fragment");
|
|
4278
|
+
}
|
|
4279
|
+
if (rendererUrl) {
|
|
4280
|
+
const asset = new URL(rendererUrl);
|
|
4281
|
+
if (asset.username || asset.password || asset.search || asset.hash || asset.protocol !== "https:" && !(asset.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(asset.hostname))) {
|
|
4282
|
+
throw new Error("Screenshot renderer requires a trusted HTTPS module URL except localhost");
|
|
4283
|
+
}
|
|
4284
|
+
}
|
|
4285
|
+
let busy = false, generation = 0, lastSuccess = 0;
|
|
4286
|
+
let controller;
|
|
4287
|
+
function cancel() {
|
|
4288
|
+
generation++;
|
|
4289
|
+
controller?.abort();
|
|
4290
|
+
}
|
|
4291
|
+
async function capture(headers = {}) {
|
|
4292
|
+
const context = getContext();
|
|
4293
|
+
if (!context || !document.body || document.visibilityState !== "visible") {
|
|
4294
|
+
throw new Error("Screenshot requires consent, a visible page and an active SDK session");
|
|
4295
|
+
}
|
|
4296
|
+
if (busy) throw new Error("A screenshot is already in progress");
|
|
4297
|
+
if (Date.now() - lastSuccess < 1e4) throw new Error("Wait 10 seconds between screenshots");
|
|
4298
|
+
busy = true;
|
|
4299
|
+
const current = generation, signature = JSON.stringify(context), capturedAt = Date.now();
|
|
4300
|
+
const stillCurrent = () => current === generation && JSON.stringify(getContext()) === signature;
|
|
4301
|
+
try {
|
|
4302
|
+
const canvas = await (render ? render() : renderPage(rendererUrl));
|
|
4303
|
+
if (!stillCurrent()) throw new Error("Screenshot discarded: consent, session or page changed");
|
|
4304
|
+
if (!Number.isInteger(canvas.width) || !Number.isInteger(canvas.height) || canvas.width < 1 || canvas.height < 1 || canvas.width > 1920 || canvas.height > 1080) {
|
|
4305
|
+
throw new Error("Invalid screenshot dimensions");
|
|
4306
|
+
}
|
|
4307
|
+
const png = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
|
|
4308
|
+
if (!stillCurrent()) throw new Error("Screenshot discarded: consent, session or page changed");
|
|
4309
|
+
if (!png || png.type !== "image/png" || png.size < 33 || png.size > 5 * 1024 * 1024) {
|
|
4310
|
+
throw new Error("Screenshot is empty or exceeds 5 MB");
|
|
4311
|
+
}
|
|
4312
|
+
const target = new URL(url);
|
|
4313
|
+
for (const [key, value] of Object.entries(context)) target.searchParams.set(key, value);
|
|
4314
|
+
target.searchParams.set("capturedAt", String(capturedAt));
|
|
4315
|
+
const requestHeaders = new Headers(headers);
|
|
4316
|
+
requestHeaders.set("Content-Type", "image/png");
|
|
4317
|
+
controller = new AbortController();
|
|
4318
|
+
const timer = setTimeout(() => controller?.abort(), 15e3);
|
|
4319
|
+
try {
|
|
4320
|
+
const response = await send(target.href, {
|
|
4321
|
+
method: "POST",
|
|
4322
|
+
headers: requestHeaders,
|
|
4323
|
+
body: png,
|
|
4324
|
+
credentials: "omit",
|
|
4325
|
+
redirect: "error",
|
|
4326
|
+
signal: controller.signal
|
|
4327
|
+
});
|
|
4328
|
+
if (!response.ok) throw new Error(`Screenshot upload failed: HTTP ${response.status}`);
|
|
4329
|
+
const result = await response.json();
|
|
4330
|
+
if (!stillCurrent()) throw new Error("Screenshot upload ended after consent/session changed; request server deletion");
|
|
4331
|
+
if (typeof result.captureId !== "string" || !result.captureId || result.replayId !== context.replayId || typeof result.blobName !== "string" || !result.blobName || result.width !== canvas.width || result.height !== canvas.height || result.capturedAt !== capturedAt) {
|
|
4332
|
+
throw new Error("Invalid screenshot API response");
|
|
4333
|
+
}
|
|
4334
|
+
lastSuccess = Date.now();
|
|
4335
|
+
return result;
|
|
4336
|
+
} finally {
|
|
4337
|
+
clearTimeout(timer);
|
|
4338
|
+
controller = void 0;
|
|
4339
|
+
}
|
|
4340
|
+
} finally {
|
|
4341
|
+
busy = false;
|
|
4342
|
+
}
|
|
4343
|
+
}
|
|
4344
|
+
return { capture, cancel };
|
|
4193
4345
|
}
|
|
4194
4346
|
|
|
4195
4347
|
// sdk.ts
|
|
4196
|
-
var INGESTION_URL = "http://
|
|
4197
|
-
var REPLAY_URL = "http://
|
|
4348
|
+
var INGESTION_URL = "http://172.16.181.11:5192/v1/events";
|
|
4349
|
+
var REPLAY_URL = "http://172.16.181.11:5192/v1/replays/uploads";
|
|
4350
|
+
var SCREENSHOT_URL = "http://172.16.181.11:5192/api/replay-captures";
|
|
4198
4351
|
function initFlowAnalytics(options) {
|
|
4199
4352
|
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
4200
4353
|
throw new Error("FlowAnalytics must be initialized in a browser");
|
|
4201
4354
|
}
|
|
4202
4355
|
if (window.FlowAnalytics) return window.FlowAnalytics;
|
|
4203
4356
|
const siteId = options?.siteId ?? options?.projectId;
|
|
4204
|
-
if (!options || typeof siteId !== "string" || !siteId.trim() || options.siteId !== void 0 && options.projectId !== void 0 && options.siteId !== options.projectId || options.collectorUrl !== void 0 && typeof options.collectorUrl !== "string" || options.autoConsent !== void 0 && typeof options.autoConsent !== "boolean" || options.resolvePagePath !== void 0 && typeof options.resolvePagePath !== "function") {
|
|
4357
|
+
if (!options || typeof siteId !== "string" || !siteId.trim() || options.siteId !== void 0 && options.projectId !== void 0 && options.siteId !== options.projectId || options.collectorUrl !== void 0 && typeof options.collectorUrl !== "string" || options.autoConsent !== void 0 && typeof options.autoConsent !== "boolean" || options.screenshots !== void 0 && (!options.screenshots || typeof options.screenshots.enabled !== "boolean" || options.screenshots.uploadUrl !== void 0 && typeof options.screenshots.uploadUrl !== "string" || options.screenshots.rendererUrl !== void 0 && typeof options.screenshots.rendererUrl !== "string") || options.resolvePagePath !== void 0 && typeof options.resolvePagePath !== "function") {
|
|
4205
4358
|
throw new Error("FlowAnalytics requires a siteId (or legacy projectId), IDs must match, and options must be valid");
|
|
4206
4359
|
}
|
|
4207
4360
|
const projectId = siteId;
|
|
@@ -4218,6 +4371,17 @@ function initFlowAnalytics(options) {
|
|
|
4218
4371
|
}
|
|
4219
4372
|
const endpoint = endpointUrl.href;
|
|
4220
4373
|
const replay = /^[A-Za-z0-9_-]{1,64}$/.test(projectId) && typeof document.createElement === "function" && typeof MutationObserver !== "undefined" ? createReplay(projectId, REPLAY_URL, window.fetch.bind(window)) : void 0;
|
|
4374
|
+
const screenshots = options.screenshots?.enabled ? createScreenshots(
|
|
4375
|
+
options.screenshots.uploadUrl || SCREENSHOT_URL,
|
|
4376
|
+
() => {
|
|
4377
|
+
const reference = replay?.reference;
|
|
4378
|
+
const time = Date.now();
|
|
4379
|
+
return consent && sessionId && reference?.sessionId === sessionId && pageViewId && time >= Date.parse(lastActivityAt) && (authenticatedSession || time - Date.parse(lastActivityAt) < sessionTimeout) && (!ingestion || time - Date.parse(sessionStartedAt) < 864e5) ? { siteId: projectId, sessionId, visitorId, pageViewId, replayId: reference.replayId } : void 0;
|
|
4380
|
+
},
|
|
4381
|
+
window.fetch.bind(window),
|
|
4382
|
+
void 0,
|
|
4383
|
+
options.screenshots.rendererUrl
|
|
4384
|
+
) : void 0;
|
|
4221
4385
|
const capturePath = options.capturePath === true;
|
|
4222
4386
|
const persistVisitor = options.persistVisitor === true;
|
|
4223
4387
|
const authenticatedSession = options.authenticatedSession === true;
|
|
@@ -4339,7 +4503,7 @@ function initFlowAnalytics(options) {
|
|
|
4339
4503
|
page_view_id: pageViewId,
|
|
4340
4504
|
session_started_at: sessionStartedAt,
|
|
4341
4505
|
last_activity_at: lastActivityAt,
|
|
4342
|
-
sdk_version: "0.2.
|
|
4506
|
+
sdk_version: "0.2.1",
|
|
4343
4507
|
consent_status: "granted",
|
|
4344
4508
|
collection_mode: persisted ? "persistent" : "memory",
|
|
4345
4509
|
visibility: document.visibilityState,
|
|
@@ -4496,7 +4660,7 @@ function initFlowAnalytics(options) {
|
|
|
4496
4660
|
};
|
|
4497
4661
|
if (options.release) result.release = options.release;
|
|
4498
4662
|
if (options.pageVersion) properties.page_version = options.pageVersion;
|
|
4499
|
-
if (meta.replay_id)
|
|
4663
|
+
if (meta.replay_id) result.replay_id = String(meta.replay_id);
|
|
4500
4664
|
const viewport = {};
|
|
4501
4665
|
for (const key of [
|
|
4502
4666
|
"viewport_width",
|
|
@@ -5002,8 +5166,7 @@ function initFlowAnalytics(options) {
|
|
|
5002
5166
|
if (navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain" }))) queue.splice(0, batch.length);
|
|
5003
5167
|
});
|
|
5004
5168
|
setInterval(() => void flush(), 5e3);
|
|
5005
|
-
|
|
5006
|
-
window.addEventListener("pagehide", () => replay?.flush());
|
|
5169
|
+
window.addEventListener("pagehide", () => replay?.end());
|
|
5007
5170
|
{
|
|
5008
5171
|
let requestInfo2 = function(url, verb) {
|
|
5009
5172
|
if (!["http:", "https:"].includes(url.protocol) || url.origin + url.pathname === endpointUrl.origin + endpointUrl.pathname) return;
|
|
@@ -5152,6 +5315,7 @@ function initFlowAnalytics(options) {
|
|
|
5152
5315
|
watchImpressionChanges();
|
|
5153
5316
|
} else if (granted === false && consent) {
|
|
5154
5317
|
consent = false;
|
|
5318
|
+
screenshots?.cancel();
|
|
5155
5319
|
replay?.discard();
|
|
5156
5320
|
queue = [];
|
|
5157
5321
|
retryAt = 0;
|
|
@@ -5188,6 +5352,7 @@ function initFlowAnalytics(options) {
|
|
|
5188
5352
|
},
|
|
5189
5353
|
endAuthenticatedSession() {
|
|
5190
5354
|
if (!authenticatedSession) throw new Error("Enable authenticatedSession to manage the session");
|
|
5355
|
+
screenshots?.cancel();
|
|
5191
5356
|
if (consent && sessionId) {
|
|
5192
5357
|
finishEngagement();
|
|
5193
5358
|
emit("session_end", "", { outcome: "logout" });
|
|
@@ -5210,7 +5375,11 @@ function initFlowAnalytics(options) {
|
|
|
5210
5375
|
track(name, metadata = {}) {
|
|
5211
5376
|
if (typeof name === "string" && eventName.test(name) && validMetadata(metadata) && Object.keys(metadata).every((key) => customMetadataKeys.has(key))) track("custom", name, metadata);
|
|
5212
5377
|
},
|
|
5213
|
-
flush
|
|
5378
|
+
flush,
|
|
5379
|
+
async captureScreenshot(headers = {}) {
|
|
5380
|
+
if (!screenshots) throw new Error("Enable screenshots before calling captureScreenshot");
|
|
5381
|
+
return screenshots.capture(headers);
|
|
5382
|
+
}
|
|
5214
5383
|
};
|
|
5215
5384
|
if (options.autoConsent !== false) window.FlowAnalytics.setConsent(true);
|
|
5216
5385
|
return window.FlowAnalytics;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface ScreenshotOptions {
|
|
2
|
+
/** Disabled unless explicitly true; capture also requires current analytics consent. */
|
|
3
|
+
enabled: boolean;
|
|
4
|
+
/** Provider upload API, never an Azure connection string or account key. */
|
|
5
|
+
uploadUrl?: string;
|
|
6
|
+
/** Script integrations load this provider-owned module lazily; npm uses html2canvas. */
|
|
7
|
+
rendererUrl?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ScreenshotContext {
|
|
10
|
+
siteId: string;
|
|
11
|
+
sessionId: string;
|
|
12
|
+
visitorId: string;
|
|
13
|
+
pageViewId: string;
|
|
14
|
+
replayId: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ScreenshotResult {
|
|
17
|
+
captureId: string;
|
|
18
|
+
replayId: string;
|
|
19
|
+
blobName: string;
|
|
20
|
+
capturedAt: number;
|
|
21
|
+
width: number;
|
|
22
|
+
height: number;
|
|
23
|
+
}
|
|
24
|
+
export declare function createScreenshots(uploadUrl: string, getContext: () => ScreenshotContext | undefined, send: typeof fetch, render?: () => Promise<HTMLCanvasElement>, rendererUrl?: string): {
|
|
25
|
+
capture: (headers?: HeadersInit) => Promise<ScreenshotResult>;
|
|
26
|
+
cancel: () => void;
|
|
27
|
+
};
|
package/package.json
CHANGED
|
@@ -1,23 +1,24 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "journeyiq",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"description": "Consent-aware browser event tracking SDK",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"exports": {
|
|
7
|
-
".": {
|
|
8
|
-
"types": "./dist/index.d.ts",
|
|
9
|
-
"import": "./dist/index.js"
|
|
10
|
-
}
|
|
11
|
-
},
|
|
12
|
-
"types": "./dist/index.d.ts",
|
|
13
|
-
"files": [
|
|
14
|
-
"dist"
|
|
15
|
-
],
|
|
16
|
-
"license": "UNLICENSED",
|
|
17
|
-
"dependencies": {
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "journeyiq",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Consent-aware browser event tracking SDK",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"license": "UNLICENSED",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"html2canvas": "^1.4.1",
|
|
19
|
+
"web-vitals": "^6.2.3"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
}
|
|
24
|
+
}
|