@temps-sdk/analytics-core 0.0.2 → 0.0.6

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/dist/utils.js CHANGED
@@ -1,3 +1,7 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ import { INGEST_KEY_HEADER, INGEST_KEY_QUERY_PARAM } from "./constants";
4
+ import { getOrCreateSessionId, getOrCreateVisitorId } from "./identity";
1
5
  export function getRequestId() {
2
6
  if (typeof document === "undefined")
3
7
  return undefined;
@@ -38,25 +42,64 @@ export function isTestEnvironment() {
38
42
  return (isPhantom || isNightmare || isWebdriver || isCypress) && !allowTemps;
39
43
  }
40
44
  /**
41
- * Returns a new object with request_id and session_id attached if available.
42
- * When they are unavailable, the keys are set to `undefined` so `JSON.stringify`
43
- * omits them entirely (matching legacy @temps-sdk/react-analytics behavior).
45
+ * Returns a new object with request_id, visitorId and sessionId attached.
46
+ * `visitorId`/`sessionId` are the client-generated fallback identity (see
47
+ * `./identity`) — the server only uses them when it has no Temps-issued
48
+ * `_temps_visitor_id`/`_temps_sid` cookie of its own to prefer. When a value
49
+ * is unavailable, the key is set to `undefined` so `JSON.stringify` omits it
50
+ * entirely (matching legacy @temps-sdk/react-analytics behavior).
44
51
  */
45
52
  function enrich(data) {
46
53
  const enriched = {
47
54
  ...data,
48
55
  request_id: getRequestId(),
49
- session_id: typeof localStorage !== "undefined"
50
- ? localStorage.getItem("session_id") || undefined
51
- : undefined,
56
+ visitorId: getOrCreateVisitorId(),
57
+ sessionId: getOrCreateSessionId(),
52
58
  };
53
59
  return enriched;
54
60
  }
55
- export async function sendAnalytics(endpoint, data, method = "POST", basePath) {
61
+ /**
62
+ * Request headers for a `fetch`-based ingest call. Returns an empty object
63
+ * when no ingest key is configured, so a Temps-hosted app sends exactly the
64
+ * headers it always has and keeps resolving by `Host`.
65
+ */
66
+ export function ingestKeyHeaders(ingestKey) {
67
+ return ingestKey ? { [INGEST_KEY_HEADER]: ingestKey } : {};
68
+ }
69
+ /**
70
+ * Appends the ingest key to a URL as `?temps_key=…` for transports that cannot
71
+ * set headers (`navigator.sendBeacon`). Returns the URL untouched when no key
72
+ * is configured.
73
+ */
74
+ export function withIngestKey(url, ingestKey) {
75
+ if (!ingestKey)
76
+ return url;
77
+ const separator = url.includes("?") ? "&" : "?";
78
+ return `${url}${separator}${INGEST_KEY_QUERY_PARAM}=${encodeURIComponent(ingestKey)}`;
79
+ }
80
+ /**
81
+ * Wraps a JSON payload for `navigator.sendBeacon`.
82
+ *
83
+ * Beacons always use credentials mode `include`. A beacon whose Blob type is
84
+ * not CORS-safelisted (`application/json` is not) is preflighted, and a
85
+ * cross-origin preflight for a credentialed request fails unless the server
86
+ * answers with a credentialed grant — so on keyed, cross-origin ingest the
87
+ * unload events (`page_leave`, late Web Vitals, the final replay batch) were
88
+ * silently dropped. `text/plain` is safelisted: the beacon goes out with no
89
+ * preflight, and the server parses its body as JSON exactly as before.
90
+ *
91
+ * Only keyed requests are sent as `text/plain`. The server accepts that type
92
+ * on the keyed path alone, and an app without a key is served by Temps on its
93
+ * own origin, where `application/json` was never a problem.
94
+ */
95
+ export function beaconBlob(payload, ingestKey) {
96
+ return new Blob([payload], { type: ingestKey ? "text/plain" : "application/json" });
97
+ }
98
+ export async function sendAnalytics(endpoint, data, method = "POST", basePath, ingestKey) {
56
99
  try {
57
100
  await fetch(`${basePath}/${endpoint}`, {
58
101
  method,
59
- headers: { "Content-Type": "application/json" },
102
+ headers: { "Content-Type": "application/json", ...ingestKeyHeaders(ingestKey) },
60
103
  body: JSON.stringify(enrich(data)),
61
104
  });
62
105
  }
@@ -65,16 +108,29 @@ export async function sendAnalytics(endpoint, data, method = "POST", basePath) {
65
108
  console.error("Failed to send analytics:", error);
66
109
  }
67
110
  }
68
- export function sendAnalyticsReliable(endpoint, data, basePath) {
111
+ export function sendAnalyticsReliable(endpoint, data, basePath, ingestKey) {
69
112
  try {
70
- const url = `${basePath}/${endpoint}`;
113
+ // The key goes in the query string rather than a header for *both*
114
+ // branches below. sendBeacon cannot set headers at all, and the fetch
115
+ // fallback shares this URL — putting a custom header on it would force a
116
+ // CORS preflight during unload, which browsers routinely drop. The server
117
+ // accepts either transport (ADR-040).
118
+ const url = withIngestKey(`${basePath}/${endpoint}`, ingestKey);
71
119
  const payload = JSON.stringify(enrich(data));
72
- // Try sendBeacon first (most reliable for page unload)
120
+ // Try sendBeacon first (most reliable for page unload). It returns false
121
+ // when the browser refuses to queue the request (its beacon quota is full)
122
+ // and can throw (e.g. in a context where beacons are not allowed); either
123
+ // way the event would be lost, so fall through to fetch.
73
124
  if (typeof navigator !== "undefined" &&
74
125
  navigator.sendBeacon &&
75
126
  typeof navigator.sendBeacon === "function") {
76
- const blob = new Blob([payload], { type: "application/json" });
77
- return navigator.sendBeacon(url, blob);
127
+ try {
128
+ if (navigator.sendBeacon(url, beaconBlob(payload, ingestKey)))
129
+ return true;
130
+ }
131
+ catch {
132
+ // fall through to fetch
133
+ }
78
134
  }
79
135
  // Fallback to fetch with keepalive
80
136
  fetch(url, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/analytics-core",
3
- "version": "0.0.2",
3
+ "version": "0.0.6",
4
4
  "description": "Framework-agnostic core for Temps analytics, engagement, Web Vitals, and session replay.",
5
5
  "private": false,
6
6
  "type": "module",