@reopt-ai/data-contract 0.6.1 → 0.6.3

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.
Files changed (51) hide show
  1. package/dist/{chunk-GCQZNME3.js → chunk-7W33YGRO.js} +13 -6
  2. package/dist/chunk-7W33YGRO.js.map +1 -0
  3. package/dist/{chunk-JB4MJQX7.cjs → chunk-F2RNXJGO.cjs} +2 -2
  4. package/dist/{chunk-JB4MJQX7.cjs.map → chunk-F2RNXJGO.cjs.map} +1 -1
  5. package/dist/{chunk-33BCA2LH.js → chunk-JCEWUSUM.js} +1 -1
  6. package/dist/{chunk-33BCA2LH.js.map → chunk-JCEWUSUM.js.map} +1 -1
  7. package/dist/{chunk-PHPTCLRU.cjs → chunk-L3JPDRVG.cjs} +14 -7
  8. package/dist/chunk-L3JPDRVG.cjs.map +1 -0
  9. package/dist/{chunk-IY4MXH35.js → chunk-L4KBQAOO.js} +3 -3
  10. package/dist/{chunk-L3WJGIKD.js → chunk-NJ4JKNBX.js} +2 -2
  11. package/dist/{chunk-YSAEOYPD.cjs → chunk-ORNTN6AK.cjs} +1 -1
  12. package/dist/{chunk-YSAEOYPD.cjs.map → chunk-ORNTN6AK.cjs.map} +1 -1
  13. package/dist/{chunk-HLQAZ6JW.js → chunk-PSUINLW7.js} +2 -2
  14. package/dist/{chunk-HLQAZ6JW.js.map → chunk-PSUINLW7.js.map} +1 -1
  15. package/dist/{chunk-EZ2TA4S6.js → chunk-RU26QFM2.js} +2 -2
  16. package/dist/{chunk-FUGY5ANJ.cjs → chunk-XDH5QQYF.cjs} +13 -13
  17. package/dist/{chunk-FUGY5ANJ.cjs.map → chunk-XDH5QQYF.cjs.map} +1 -1
  18. package/dist/{chunk-LA5F5KR6.cjs → chunk-YCTGHWTP.cjs} +6 -6
  19. package/dist/{chunk-LA5F5KR6.cjs.map → chunk-YCTGHWTP.cjs.map} +1 -1
  20. package/dist/{chunk-VGB2VJO4.cjs → chunk-ZI6A3WQP.cjs} +4 -4
  21. package/dist/{chunk-VGB2VJO4.cjs.map → chunk-ZI6A3WQP.cjs.map} +1 -1
  22. package/dist/client.cjs +51 -51
  23. package/dist/client.cjs.map +1 -1
  24. package/dist/client.d.cts +10 -10
  25. package/dist/client.d.ts +10 -10
  26. package/dist/client.js +6 -6
  27. package/dist/client.js.map +1 -1
  28. package/dist/control.cjs +5 -5
  29. package/dist/control.js +4 -4
  30. package/dist/identity.cjs +3 -3
  31. package/dist/identity.d.cts +12 -5
  32. package/dist/identity.d.ts +12 -5
  33. package/dist/identity.js +2 -2
  34. package/dist/index.cjs +3 -3
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +2 -2
  38. package/dist/ingest.cjs +4 -4
  39. package/dist/ingest.js +3 -3
  40. package/dist/query.cjs +4 -4
  41. package/dist/query.d.cts +1 -1
  42. package/dist/query.d.ts +1 -1
  43. package/dist/query.js +3 -3
  44. package/dist/{version-BzeRTpta.d.ts → version-DJ2Grb_N.d.cts} +1 -1
  45. package/dist/{version-BzeRTpta.d.cts → version-DJ2Grb_N.d.ts} +1 -1
  46. package/package.json +1 -1
  47. package/dist/chunk-GCQZNME3.js.map +0 -1
  48. package/dist/chunk-PHPTCLRU.cjs.map +0 -1
  49. /package/dist/{chunk-IY4MXH35.js.map → chunk-L4KBQAOO.js.map} +0 -0
  50. /package/dist/{chunk-L3WJGIKD.js.map → chunk-NJ4JKNBX.js.map} +0 -0
  51. /package/dist/{chunk-EZ2TA4S6.js.map → chunk-RU26QFM2.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- export { C as CLIENT_ID_HEADER, a as CLIENT_SECRET_HEADER, b as CONTRACT_VERSION, c as CONTRACT_VERSION_HEADER, D as DEVICE_ID_HEADER, R as REQUEST_ID_HEADER, W as WRITE_KEY_HEADER } from './version-BzeRTpta.js';
2
+ export { C as CLIENT_ID_HEADER, a as CLIENT_SECRET_HEADER, b as CONTRACT_VERSION, c as CONTRACT_VERSION_HEADER, D as DEVICE_ID_HEADER, R as REQUEST_ID_HEADER, W as WRITE_KEY_HEADER } from './version-DJ2Grb_N.js';
3
3
 
4
4
  /**
5
5
  * `@reopt-ai/data-contract` — the wire contract between reopt-data and its
@@ -59,18 +59,18 @@ declare class DataApiError extends Error {
59
59
  readonly isDataApiError: true;
60
60
  readonly status: number;
61
61
  readonly code: string;
62
- readonly requestId?: string;
62
+ readonly requestId?: string | undefined;
63
63
  /** Parsed from `Retry-After`, in milliseconds. Only set on 429. */
64
- readonly retryAfterMs?: number;
64
+ readonly retryAfterMs?: number | undefined;
65
65
  /** zod issues for `validation_failed`, or the raw body when unparseable. */
66
- readonly details?: unknown;
66
+ readonly details?: unknown | undefined;
67
67
  constructor(init: {
68
68
  message: string;
69
69
  status: number;
70
70
  code: string;
71
- requestId?: string;
72
- retryAfterMs?: number;
73
- details?: unknown;
71
+ requestId?: string | undefined;
72
+ retryAfterMs?: number | undefined;
73
+ details?: unknown | undefined;
74
74
  });
75
75
  /** 429 and 5xx are worth retrying; 4xx are the caller's fault and are not. */
76
76
  get retryable(): boolean;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  DataApiError,
3
3
  zDate,
4
4
  zInstant
5
- } from "./chunk-33BCA2LH.js";
5
+ } from "./chunk-JCEWUSUM.js";
6
6
  import {
7
7
  CLIENT_ID_HEADER,
8
8
  CLIENT_SECRET_HEADER,
@@ -11,7 +11,7 @@ import {
11
11
  DEVICE_ID_HEADER,
12
12
  REQUEST_ID_HEADER,
13
13
  WRITE_KEY_HEADER
14
- } from "./chunk-HLQAZ6JW.js";
14
+ } from "./chunk-PSUINLW7.js";
15
15
  export {
16
16
  CLIENT_ID_HEADER,
17
17
  CLIENT_SECRET_HEADER,
package/dist/ingest.cjs CHANGED
@@ -18,9 +18,9 @@
18
18
 
19
19
 
20
20
 
21
- var _chunkVGB2VJO4cjs = require('./chunk-VGB2VJO4.cjs');
22
- require('./chunk-PHPTCLRU.cjs');
23
- require('./chunk-JB4MJQX7.cjs');
21
+ var _chunkZI6A3WQPcjs = require('./chunk-ZI6A3WQP.cjs');
22
+ require('./chunk-L3JPDRVG.cjs');
23
+ require('./chunk-F2RNXJGO.cjs');
24
24
 
25
25
 
26
26
 
@@ -55,5 +55,5 @@ var _chunk3EEANNYNcjs = require('./chunk-3EEANNYN.cjs');
55
55
 
56
56
 
57
57
 
58
- exports.AUTO_EVENT_NAMES = _chunk3EEANNYNcjs.AUTO_EVENT_NAMES; exports.AUTO_EVENT_PROPERTIES = _chunk3EEANNYNcjs.AUTO_EVENT_PROPERTIES; exports.AUTO_EVENT_ROLLUP_KEYS = _chunk3EEANNYNcjs.AUTO_EVENT_ROLLUP_KEYS; exports.INGEST_ERROR_CODES = _chunkVGB2VJO4cjs.INGEST_ERROR_CODES; exports.INGEST_MODES = _chunkVGB2VJO4cjs.INGEST_MODES; exports.INGEST_REJECTION_REASONS = _chunkVGB2VJO4cjs.INGEST_REJECTION_REASONS; exports.MAX_TRACK_PAYLOAD_BYTES = _chunkVGB2VJO4cjs.MAX_TRACK_PAYLOAD_BYTES; exports.RESERVED_EVENT_NAMES = _chunk3EEANNYNcjs.RESERVED_EVENT_NAMES; exports.SCROLL_DEPTH_BUCKETS = _chunk3EEANNYNcjs.SCROLL_DEPTH_BUCKETS; exports.reconcileIngestResponse = _chunkVGB2VJO4cjs.reconcileIngestResponse; exports.scrollDepthBucket = _chunk3EEANNYNcjs.scrollDepthBucket; exports.zDecrementPayload = _chunkVGB2VJO4cjs.zDecrementPayload; exports.zIdentifyPayload = _chunkVGB2VJO4cjs.zIdentifyPayload; exports.zIncrementPayload = _chunkVGB2VJO4cjs.zIncrementPayload; exports.zIngestAcceptedResponse = _chunkVGB2VJO4cjs.zIngestAcceptedResponse; exports.zIngestError = _chunkVGB2VJO4cjs.zIngestError; exports.zIngestErrorCode = _chunkVGB2VJO4cjs.zIngestErrorCode; exports.zIngestMode = _chunkVGB2VJO4cjs.zIngestMode; exports.zIngestOkResponse = _chunkVGB2VJO4cjs.zIngestOkResponse; exports.zIngestRejection = _chunkVGB2VJO4cjs.zIngestRejection; exports.zIngestRejectionReason = _chunkVGB2VJO4cjs.zIngestRejectionReason; exports.zIngestResponse = _chunkVGB2VJO4cjs.zIngestResponse; exports.zSessionCredential = _chunkVGB2VJO4cjs.zSessionCredential; exports.zTrackHandlerPayload = _chunkVGB2VJO4cjs.zTrackHandlerPayload; exports.zTrackPayload = _chunkVGB2VJO4cjs.zTrackPayload;
58
+ exports.AUTO_EVENT_NAMES = _chunk3EEANNYNcjs.AUTO_EVENT_NAMES; exports.AUTO_EVENT_PROPERTIES = _chunk3EEANNYNcjs.AUTO_EVENT_PROPERTIES; exports.AUTO_EVENT_ROLLUP_KEYS = _chunk3EEANNYNcjs.AUTO_EVENT_ROLLUP_KEYS; exports.INGEST_ERROR_CODES = _chunkZI6A3WQPcjs.INGEST_ERROR_CODES; exports.INGEST_MODES = _chunkZI6A3WQPcjs.INGEST_MODES; exports.INGEST_REJECTION_REASONS = _chunkZI6A3WQPcjs.INGEST_REJECTION_REASONS; exports.MAX_TRACK_PAYLOAD_BYTES = _chunkZI6A3WQPcjs.MAX_TRACK_PAYLOAD_BYTES; exports.RESERVED_EVENT_NAMES = _chunk3EEANNYNcjs.RESERVED_EVENT_NAMES; exports.SCROLL_DEPTH_BUCKETS = _chunk3EEANNYNcjs.SCROLL_DEPTH_BUCKETS; exports.reconcileIngestResponse = _chunkZI6A3WQPcjs.reconcileIngestResponse; exports.scrollDepthBucket = _chunk3EEANNYNcjs.scrollDepthBucket; exports.zDecrementPayload = _chunkZI6A3WQPcjs.zDecrementPayload; exports.zIdentifyPayload = _chunkZI6A3WQPcjs.zIdentifyPayload; exports.zIncrementPayload = _chunkZI6A3WQPcjs.zIncrementPayload; exports.zIngestAcceptedResponse = _chunkZI6A3WQPcjs.zIngestAcceptedResponse; exports.zIngestError = _chunkZI6A3WQPcjs.zIngestError; exports.zIngestErrorCode = _chunkZI6A3WQPcjs.zIngestErrorCode; exports.zIngestMode = _chunkZI6A3WQPcjs.zIngestMode; exports.zIngestOkResponse = _chunkZI6A3WQPcjs.zIngestOkResponse; exports.zIngestRejection = _chunkZI6A3WQPcjs.zIngestRejection; exports.zIngestRejectionReason = _chunkZI6A3WQPcjs.zIngestRejectionReason; exports.zIngestResponse = _chunkZI6A3WQPcjs.zIngestResponse; exports.zSessionCredential = _chunkZI6A3WQPcjs.zSessionCredential; exports.zTrackHandlerPayload = _chunkZI6A3WQPcjs.zTrackHandlerPayload; exports.zTrackPayload = _chunkZI6A3WQPcjs.zTrackPayload;
59
59
  //# sourceMappingURL=ingest.cjs.map
package/dist/ingest.js CHANGED
@@ -18,9 +18,9 @@ import {
18
18
  zSessionCredential,
19
19
  zTrackHandlerPayload,
20
20
  zTrackPayload
21
- } from "./chunk-EZ2TA4S6.js";
22
- import "./chunk-GCQZNME3.js";
23
- import "./chunk-HLQAZ6JW.js";
21
+ } from "./chunk-RU26QFM2.js";
22
+ import "./chunk-7W33YGRO.js";
23
+ import "./chunk-PSUINLW7.js";
24
24
  import {
25
25
  AUTO_EVENT_NAMES,
26
26
  AUTO_EVENT_PROPERTIES,
package/dist/query.cjs CHANGED
@@ -36,12 +36,12 @@
36
36
 
37
37
 
38
38
 
39
- var _chunkFUGY5ANJcjs = require('./chunk-FUGY5ANJ.cjs');
39
+ var _chunkXDH5QQYFcjs = require('./chunk-XDH5QQYF.cjs');
40
40
 
41
41
 
42
42
 
43
- var _chunkYSAEOYPDcjs = require('./chunk-YSAEOYPD.cjs');
44
- require('./chunk-JB4MJQX7.cjs');
43
+ var _chunkORNTN6AKcjs = require('./chunk-ORNTN6AK.cjs');
44
+ require('./chunk-F2RNXJGO.cjs');
45
45
 
46
46
 
47
47
 
@@ -82,5 +82,5 @@ require('./chunk-JB4MJQX7.cjs');
82
82
 
83
83
 
84
84
 
85
- exports.QUERY_API_PATHS = _chunkFUGY5ANJcjs.QUERY_API_PATHS; exports.QUERY_ERROR_CODES = _chunkFUGY5ANJcjs.QUERY_ERROR_CODES; exports.isValidTimeZone = _chunkFUGY5ANJcjs.isValidTimeZone; exports.zBucketStart = _chunkFUGY5ANJcjs.zBucketStart; exports.zChannelFilter = _chunkFUGY5ANJcjs.zChannelFilter; exports.zDate = _chunkYSAEOYPDcjs.zDate; exports.zEventPropertyFilter = _chunkFUGY5ANJcjs.zEventPropertyFilter; exports.zEventsTimeseriesData = _chunkFUGY5ANJcjs.zEventsTimeseriesData; exports.zEventsTimeseriesInput = _chunkFUGY5ANJcjs.zEventsTimeseriesInput; exports.zEventsTimeseriesResponse = _chunkFUGY5ANJcjs.zEventsTimeseriesResponse; exports.zFunnelData = _chunkFUGY5ANJcjs.zFunnelData; exports.zFunnelInput = _chunkFUGY5ANJcjs.zFunnelInput; exports.zFunnelResponse = _chunkFUGY5ANJcjs.zFunnelResponse; exports.zFunnelStep = _chunkFUGY5ANJcjs.zFunnelStep; exports.zGranularity = _chunkFUGY5ANJcjs.zGranularity; exports.zInstant = _chunkYSAEOYPDcjs.zInstant; exports.zQueryEnvelope = _chunkFUGY5ANJcjs.zQueryEnvelope; exports.zQueryError = _chunkFUGY5ANJcjs.zQueryError; exports.zQueryErrorCode = _chunkFUGY5ANJcjs.zQueryErrorCode; exports.zQueryMeta = _chunkFUGY5ANJcjs.zQueryMeta; exports.zQuerySource = _chunkFUGY5ANJcjs.zQuerySource; exports.zRetentionCell = _chunkFUGY5ANJcjs.zRetentionCell; exports.zRetentionData = _chunkFUGY5ANJcjs.zRetentionData; exports.zRetentionInput = _chunkFUGY5ANJcjs.zRetentionInput; exports.zRetentionInterval = _chunkFUGY5ANJcjs.zRetentionInterval; exports.zRetentionResponse = _chunkFUGY5ANJcjs.zRetentionResponse; exports.zTimeseriesBreakdown = _chunkFUGY5ANJcjs.zTimeseriesBreakdown; exports.zTimeseriesPoint = _chunkFUGY5ANJcjs.zTimeseriesPoint; exports.zTimezone = _chunkFUGY5ANJcjs.zTimezone; exports.zTrafficDimension = _chunkFUGY5ANJcjs.zTrafficDimension; exports.zTrafficOverviewData = _chunkFUGY5ANJcjs.zTrafficOverviewData; exports.zTrafficOverviewInput = _chunkFUGY5ANJcjs.zTrafficOverviewInput; exports.zTrafficOverviewResponse = _chunkFUGY5ANJcjs.zTrafficOverviewResponse; exports.zTrafficSeriesPoint = _chunkFUGY5ANJcjs.zTrafficSeriesPoint; exports.zTrafficSourceRow = _chunkFUGY5ANJcjs.zTrafficSourceRow; exports.zTrafficSourcesData = _chunkFUGY5ANJcjs.zTrafficSourcesData; exports.zTrafficSourcesInput = _chunkFUGY5ANJcjs.zTrafficSourcesInput; exports.zTrafficSourcesResponse = _chunkFUGY5ANJcjs.zTrafficSourcesResponse; exports.zTrafficTotals = _chunkFUGY5ANJcjs.zTrafficTotals;
85
+ exports.QUERY_API_PATHS = _chunkXDH5QQYFcjs.QUERY_API_PATHS; exports.QUERY_ERROR_CODES = _chunkXDH5QQYFcjs.QUERY_ERROR_CODES; exports.isValidTimeZone = _chunkXDH5QQYFcjs.isValidTimeZone; exports.zBucketStart = _chunkXDH5QQYFcjs.zBucketStart; exports.zChannelFilter = _chunkXDH5QQYFcjs.zChannelFilter; exports.zDate = _chunkORNTN6AKcjs.zDate; exports.zEventPropertyFilter = _chunkXDH5QQYFcjs.zEventPropertyFilter; exports.zEventsTimeseriesData = _chunkXDH5QQYFcjs.zEventsTimeseriesData; exports.zEventsTimeseriesInput = _chunkXDH5QQYFcjs.zEventsTimeseriesInput; exports.zEventsTimeseriesResponse = _chunkXDH5QQYFcjs.zEventsTimeseriesResponse; exports.zFunnelData = _chunkXDH5QQYFcjs.zFunnelData; exports.zFunnelInput = _chunkXDH5QQYFcjs.zFunnelInput; exports.zFunnelResponse = _chunkXDH5QQYFcjs.zFunnelResponse; exports.zFunnelStep = _chunkXDH5QQYFcjs.zFunnelStep; exports.zGranularity = _chunkXDH5QQYFcjs.zGranularity; exports.zInstant = _chunkORNTN6AKcjs.zInstant; exports.zQueryEnvelope = _chunkXDH5QQYFcjs.zQueryEnvelope; exports.zQueryError = _chunkXDH5QQYFcjs.zQueryError; exports.zQueryErrorCode = _chunkXDH5QQYFcjs.zQueryErrorCode; exports.zQueryMeta = _chunkXDH5QQYFcjs.zQueryMeta; exports.zQuerySource = _chunkXDH5QQYFcjs.zQuerySource; exports.zRetentionCell = _chunkXDH5QQYFcjs.zRetentionCell; exports.zRetentionData = _chunkXDH5QQYFcjs.zRetentionData; exports.zRetentionInput = _chunkXDH5QQYFcjs.zRetentionInput; exports.zRetentionInterval = _chunkXDH5QQYFcjs.zRetentionInterval; exports.zRetentionResponse = _chunkXDH5QQYFcjs.zRetentionResponse; exports.zTimeseriesBreakdown = _chunkXDH5QQYFcjs.zTimeseriesBreakdown; exports.zTimeseriesPoint = _chunkXDH5QQYFcjs.zTimeseriesPoint; exports.zTimezone = _chunkXDH5QQYFcjs.zTimezone; exports.zTrafficDimension = _chunkXDH5QQYFcjs.zTrafficDimension; exports.zTrafficOverviewData = _chunkXDH5QQYFcjs.zTrafficOverviewData; exports.zTrafficOverviewInput = _chunkXDH5QQYFcjs.zTrafficOverviewInput; exports.zTrafficOverviewResponse = _chunkXDH5QQYFcjs.zTrafficOverviewResponse; exports.zTrafficSeriesPoint = _chunkXDH5QQYFcjs.zTrafficSeriesPoint; exports.zTrafficSourceRow = _chunkXDH5QQYFcjs.zTrafficSourceRow; exports.zTrafficSourcesData = _chunkXDH5QQYFcjs.zTrafficSourcesData; exports.zTrafficSourcesInput = _chunkXDH5QQYFcjs.zTrafficSourcesInput; exports.zTrafficSourcesResponse = _chunkXDH5QQYFcjs.zTrafficSourcesResponse; exports.zTrafficTotals = _chunkXDH5QQYFcjs.zTrafficTotals;
86
86
  //# sourceMappingURL=query.cjs.map
package/dist/query.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  export { zDate, zInstant } from './index.cjs';
3
- import './version-BzeRTpta.cjs';
3
+ import './version-DJ2Grb_N.cjs';
4
4
 
5
5
  /**
6
6
  * `POST /api/v1/query/*` — the read contract.
package/dist/query.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  export { zDate, zInstant } from './index.js';
3
- import './version-BzeRTpta.js';
3
+ import './version-DJ2Grb_N.js';
4
4
 
5
5
  /**
6
6
  * `POST /api/v1/query/*` — the read contract.
package/dist/query.js CHANGED
@@ -36,12 +36,12 @@ import {
36
36
  zTrafficSourcesInput,
37
37
  zTrafficSourcesResponse,
38
38
  zTrafficTotals
39
- } from "./chunk-L3WJGIKD.js";
39
+ } from "./chunk-NJ4JKNBX.js";
40
40
  import {
41
41
  zDate,
42
42
  zInstant
43
- } from "./chunk-33BCA2LH.js";
44
- import "./chunk-HLQAZ6JW.js";
43
+ } from "./chunk-JCEWUSUM.js";
44
+ import "./chunk-PSUINLW7.js";
45
45
  export {
46
46
  QUERY_API_PATHS,
47
47
  QUERY_ERROR_CODES,
@@ -13,7 +13,7 @@
13
13
  * every publish is a wire bump: consumers that check for exact equality —
14
14
  * every SDK — must upgrade in lockstep with the server.
15
15
  */
16
- declare const CONTRACT_VERSION = "0.6.1";
16
+ declare const CONTRACT_VERSION = "0.6.3";
17
17
  /** Response header carrying the server's contract version. */
18
18
  declare const CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
19
19
  /** Request header names shared by the ingest and query planes. */
@@ -13,7 +13,7 @@
13
13
  * every publish is a wire bump: consumers that check for exact equality —
14
14
  * every SDK — must upgrade in lockstep with the server.
15
15
  */
16
- declare const CONTRACT_VERSION = "0.6.1";
16
+ declare const CONTRACT_VERSION = "0.6.3";
17
17
  /** Response header carrying the server's contract version. */
18
18
  declare const CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
19
19
  /** Request header names shared by the ingest and query planes. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reopt-ai/data-contract",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Wire contract (zod schemas + typed client) for the reopt-data ingest and query APIs",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/identity.ts"],"sourcesContent":["/**\n * `@reopt-ai/data-contract/identity` — the names and encodings that carry a\n * visitor's identity between the browser SDK, the server SDK, the Next.js\n * proxy and the ingest pipeline.\n *\n * Every one of those parties reads or writes the same cookies and headers.\n * None of them depends on another (ingest does not import the SDKs), so this\n * module is the only place a name may be spelled out. A party that hardcodes\n * `reopt_<key>_device` instead of calling `deviceCookieName()` fails silently:\n * the browser sets one cookie, the server looks for another, and every\n * visitor is counted as new. `packages/db/src/__tests__/redis-namespace.test.ts`\n * guards Redis key prefixes for exactly the same reason.\n *\n * Nothing here touches `document`, `fetch` or Node built-ins — it runs in\n * browsers, edge runtimes and Node alike.\n */\nimport { DEVICE_ID_HEADER } from \"./version.js\";\n\nexport {\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n WRITE_KEY_HEADER,\n} from \"./version.js\";\n\n/**\n * Request header carrying the browser's current session id. The browser SDK\n * adds it to same-origin requests so a server-side `track()` can land in the\n * session the user is actually in; the server SDK forwards it to ingest.\n *\n * Ingest treats it as a *hint*, never as authority — a browser can put any\n * value here.\n */\nexport const SESSION_ID_HEADER = \"reopt-session-id\";\n\n/** Every request header the identity protocol may carry, for CORS allow-lists. */\nexport const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER] as const;\n\n/**\n * 400 days — the longest lifetime Chrome will honour. Anything longer is\n * silently clamped to this, so asking for more only hides the real expiry.\n */\nexport const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;\n\n/** Consent category whose refusal means \"send nothing at all\". */\nexport const OPT_OUT_CONSENT_CATEGORY = \"analytics\";\n\nconst COOKIE_PREFIX = \"reopt_\";\n\n/**\n * Cookie names may not contain separators (`=`, `;`, `,`, whitespace) or\n * control characters. A write key is opaque to us, so anything outside the\n * safe set is folded to `_` — deterministically, so both ends agree.\n */\nfunction cookieSafe(writeKey: string): string {\n if (!writeKey) {\n throw new Error(\"[reopt] writeKey is required to derive cookie names\");\n }\n return writeKey.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/** `reopt_<writeKey>_device` — device id plus session/profile hints. */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. */\nexport function consentCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;\n}\n\n/** Everything the device cookie may carry. Only `deviceId` is required. */\nexport interface DeviceCookieState {\n deviceId: string;\n /** Current session, if the browser has one. */\n sessionId?: string;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string;\n}\n\n/** Per-category consent. `false` withdraws, `true` grants, absent = undecided. */\nexport type ConsentCookieState = Record<string, boolean>;\n\n/**\n * What the server hands the browser SDK so the first render already agrees\n * with the server about who the visitor is. Plain JSON — it crosses the\n * RSC → client component boundary as a prop.\n */\nexport interface ReoptBootstrap {\n /** From the device cookie (seeded by the proxy on first visit). */\n deviceId: string;\n /** Session hint, or `null` when the browser has not started one. */\n sessionId: string | null;\n /** Result of the server's `getProfileId` resolver, or `null`. */\n profileId: string | null;\n consent: ConsentCookieState;\n /** Server clock at render time, so a skewed device clock can be corrected. */\n serverTimeMs: number;\n}\n\n/**\n * Ids are opaque, but a cookie is attacker-controlled input (a sibling\n * subdomain can set one). The value ends up in an HTTP header, and\n * `Headers.set` throws on anything outside ISO-8859-1 — so a single odd\n * cookie would break every `fetch` the tracing patch touches. Only the URL\n * \"unreserved\" set is accepted; every id this SDK mints is a UUID.\n */\nexport const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;\n\nexport function isValidIdentityId(value: unknown): value is string {\n return typeof value === \"string\" && IDENTITY_ID_PATTERN.test(value);\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Reads a device cookie value. Accepts the JSON envelope written by\n * `serializeDeviceCookie` and, for cookies seeded before the envelope existed,\n * a bare device id. Returns `null` for anything else — a malformed cookie is\n * treated as absent, never as an error, so a corrupted value cannot take the\n * page down.\n */\nexport function parseDeviceCookie(raw: string | null | undefined): DeviceCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text) return null;\n\n if (!text.startsWith(\"{\")) {\n return isValidIdentityId(text) ? { deviceId: text } : null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const candidate = parsed as Record<string, unknown>;\n if (!isValidIdentityId(candidate.deviceId)) return null;\n\n const state: DeviceCookieState = { deviceId: candidate.deviceId };\n if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;\n if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;\n return state;\n}\n\n/**\n * Cookie values may not contain `;`, `,` or whitespace, and JSON contains\n * quotes and commas. The envelope is therefore URI-encoded; `parseDeviceCookie`\n * reverses it. Optional fields are omitted rather than written as `null` so\n * the cookie stays as small as the state it carries.\n */\nexport function serializeDeviceCookie(state: DeviceCookieState): string {\n if (!isValidIdentityId(state.deviceId)) {\n throw new Error(\"[reopt] deviceId must be a non-empty string without control characters\");\n }\n const envelope: DeviceCookieState = { deviceId: state.deviceId };\n if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;\n if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;\n return encodeURIComponent(JSON.stringify(envelope));\n}\n\n/**\n * Reads a consent cookie. Only boolean entries survive; anything else in the\n * object is dropped rather than failing the whole cookie, because one odd key\n * must not erase a user's recorded opt-out.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text.startsWith(\"{\")) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\n const state: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n state[category] = decision;\n }\n }\n return state;\n}\n\nexport function serializeConsentCookie(state: ConsentCookieState): string {\n const clean: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(state)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n clean[category] = decision;\n }\n }\n return encodeURIComponent(JSON.stringify(clean));\n}\n\n/**\n * \"Opted out\" means the visitor refused the `analytics` category. An absent\n * cookie or an undecided category is *not* an opt-out — it is the default\n * state of every first visit, and treating it as refusal would make consent\n * banners mandatory for every integration.\n */\nexport function isOptedOut(consent: ConsentCookieState | null | undefined): boolean {\n return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;\n}\n\n// ─── Session tokens ───────────────────────────────────────────────────────────\n\n/**\n * Sessions are assigned by ingest, not by the browser. To let a later request\n * — from the same browser, or from a server acting for it — join that session\n * with authority, ingest hands the browser its session id together with an\n * HMAC over it, and the browser sends both back as `reopt-session-id`. An\n * unsigned or wrongly signed value is a hint at most: ingest falls back to\n * deciding the session from the device, exactly as if the header were absent.\n *\n * The token is `base64url(HMAC-SHA256(secret, sessionId))`. The secret is\n * per project and never leaves the server. WebCrypto only, so this runs in\n * browsers, edge runtimes and Node alike.\n */\nexport const SESSION_HEADER_SEPARATOR = \".\";\n\nexport interface SessionCredential {\n id: string;\n token: string;\n}\n\n/** `<id>.<token>` — what travels in `reopt-session-id`. */\nexport function formatSessionHeader(credential: SessionCredential): string {\n return `${credential.id}${SESSION_HEADER_SEPARATOR}${credential.token}`;\n}\n\n/** Splits a `reopt-session-id` value. `null` unless both parts are well-formed. */\nexport function parseSessionHeader(value: string | null | undefined): SessionCredential | null {\n if (!value) return null;\n const at = value.lastIndexOf(SESSION_HEADER_SEPARATOR);\n if (at <= 0 || at === value.length - 1) return null;\n const id = value.slice(0, at);\n const token = value.slice(at + 1);\n return isValidIdentityId(id) && /^[A-Za-z0-9_-]{43}$/.test(token) ? { id, token } : null;\n}\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n let binary = \"\";\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);\n const b64 = typeof btoa === \"function\" ? btoa(binary) : Buffer.from(binary, \"binary\").toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n}\n\n/** Issues the token for `sessionId`. Server-side only — needs the project secret. */\nexport async function signSessionToken(secret: string, sessionId: string): Promise<string> {\n if (!secret) throw new Error(\"[reopt] a session signing secret is required\");\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(sessionId));\n return base64url(signature);\n}\n\n/**\n * Constant-time check of a presented token. Recomputes and compares the\n * digests byte by byte rather than using `subtle.verify` with a decoded\n * token, so a malformed token can never throw its way past the check.\n */\nexport async function verifySessionToken(secret: string, credential: SessionCredential): Promise<boolean> {\n if (!secret || !credential) return false;\n const expected = await signSessionToken(secret, credential.id);\n if (expected.length !== credential.token.length) return false;\n let diff = 0;\n for (let index = 0; index < expected.length; index++) {\n diff |= expected.charCodeAt(index) ^ credential.token.charCodeAt(index);\n }\n return diff === 0;\n}\n"],"mappings":";;;;;AAoCO,IAAM,oBAAoB;AAG1B,IAAM,2BAA2B,CAAC,kBAAkB,iBAAiB;AAMrE,IAAM,yBAAyB,MAAM,KAAK,KAAK;AAG/C,IAAM,2BAA2B;AAExC,IAAM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AAO;AACX,WAAS,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;AACpD,YAAQ,SAAS,WAAW,KAAK,IAAI,WAAW,MAAM,WAAW,KAAK;AAAA,EACxE;AACA,SAAO,SAAS;AAClB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-PHPTCLRU.cjs","../src/identity.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACgCO,IAAM,kBAAA,EAAoB,kBAAA;AAG1B,IAAM,yBAAA,EAA2B,CAAC,kCAAA,EAAkB,iBAAiB,CAAA;AAMrE,IAAM,uBAAA,EAAyB,IAAA,EAAM,GAAA,EAAK,GAAA,EAAK,EAAA;AAG/C,IAAM,yBAAA,EAA2B,WAAA;AAExC,IAAM,cAAA,EAAgB,QAAA;AAOtB,SAAS,UAAA,CAAW,QAAA,EAA0B;AAC5C,EAAA,GAAA,CAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,KAAA,CAAM,qDAAqD,CAAA;AAAA,EACvE;AACA,EAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAChD;AAGO,SAAS,gBAAA,CAAiB,QAAA,EAA0B;AACzD,EAAA,OAAO,CAAA,EAAA;AACT;AAGgB;AACP,EAAA;AACT;AAsCa;AAEG;AACP,EAAA;AACT;AAES;AACH,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACF;AASgB;AACT,EAAA;AACC,EAAA;AACD,EAAA;AAEA,EAAA;AACH,IAAA;AACF,EAAA;AAEI,EAAA;AACA,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACI,EAAA;AAEE,EAAA;AACD,EAAA;AAEC,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAQgB;AACT,EAAA;AACG,IAAA;AACR,EAAA;AACM,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAOgB;AACT,EAAA;AACC,EAAA;AACD,EAAA;AAED,EAAA;AACA,EAAA;AACF,IAAA;AACM,EAAA;AACN,IAAA;AACF,EAAA;AACI,EAAA;AAEE,EAAA;AACN,EAAA;AACM,IAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgB;AACR,EAAA;AACN,EAAA;AACM,IAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAQgB;AACP,EAAA;AACT;AAgBa;AAQG;AACP,EAAA;AACT;AAGgB;AACT,EAAA;AACC,EAAA;AACF,EAAA;AACE,EAAA;AACA,EAAA;AACC,EAAA;AACT;AAEM;AAEG;AACH,EAAA;AACJ,EAAA;AACM,EAAA;AACC,EAAA;AACT;AAEA;AACS,EAAA;AACT;AAGA;AACO,EAAA;AACC,EAAA;AACC,EAAA;AACT;AAOA;AACO,EAAA;AACC,EAAA;AACF,EAAA;AACA,EAAA;AACJ,EAAA;AACE,IAAA;AACF,EAAA;AACO,EAAA;AACT;AD/JU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-PHPTCLRU.cjs","sourcesContent":[null,"/**\n * `@reopt-ai/data-contract/identity` — the names and encodings that carry a\n * visitor's identity between the browser SDK, the server SDK, the Next.js\n * proxy and the ingest pipeline.\n *\n * Every one of those parties reads or writes the same cookies and headers.\n * None of them depends on another (ingest does not import the SDKs), so this\n * module is the only place a name may be spelled out. A party that hardcodes\n * `reopt_<key>_device` instead of calling `deviceCookieName()` fails silently:\n * the browser sets one cookie, the server looks for another, and every\n * visitor is counted as new. `packages/db/src/__tests__/redis-namespace.test.ts`\n * guards Redis key prefixes for exactly the same reason.\n *\n * Nothing here touches `document`, `fetch` or Node built-ins — it runs in\n * browsers, edge runtimes and Node alike.\n */\nimport { DEVICE_ID_HEADER } from \"./version.js\";\n\nexport {\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n WRITE_KEY_HEADER,\n} from \"./version.js\";\n\n/**\n * Request header carrying the browser's current session id. The browser SDK\n * adds it to same-origin requests so a server-side `track()` can land in the\n * session the user is actually in; the server SDK forwards it to ingest.\n *\n * Ingest treats it as a *hint*, never as authority — a browser can put any\n * value here.\n */\nexport const SESSION_ID_HEADER = \"reopt-session-id\";\n\n/** Every request header the identity protocol may carry, for CORS allow-lists. */\nexport const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER] as const;\n\n/**\n * 400 days — the longest lifetime Chrome will honour. Anything longer is\n * silently clamped to this, so asking for more only hides the real expiry.\n */\nexport const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;\n\n/** Consent category whose refusal means \"send nothing at all\". */\nexport const OPT_OUT_CONSENT_CATEGORY = \"analytics\";\n\nconst COOKIE_PREFIX = \"reopt_\";\n\n/**\n * Cookie names may not contain separators (`=`, `;`, `,`, whitespace) or\n * control characters. A write key is opaque to us, so anything outside the\n * safe set is folded to `_` — deterministically, so both ends agree.\n */\nfunction cookieSafe(writeKey: string): string {\n if (!writeKey) {\n throw new Error(\"[reopt] writeKey is required to derive cookie names\");\n }\n return writeKey.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/** `reopt_<writeKey>_device` — device id plus session/profile hints. */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. */\nexport function consentCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;\n}\n\n/** Everything the device cookie may carry. Only `deviceId` is required. */\nexport interface DeviceCookieState {\n deviceId: string;\n /** Current session, if the browser has one. */\n sessionId?: string;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string;\n}\n\n/** Per-category consent. `false` withdraws, `true` grants, absent = undecided. */\nexport type ConsentCookieState = Record<string, boolean>;\n\n/**\n * What the server hands the browser SDK so the first render already agrees\n * with the server about who the visitor is. Plain JSON — it crosses the\n * RSC → client component boundary as a prop.\n */\nexport interface ReoptBootstrap {\n /** From the device cookie (seeded by the proxy on first visit). */\n deviceId: string;\n /** Session hint, or `null` when the browser has not started one. */\n sessionId: string | null;\n /** Result of the server's `getProfileId` resolver, or `null`. */\n profileId: string | null;\n consent: ConsentCookieState;\n /** Server clock at render time, so a skewed device clock can be corrected. */\n serverTimeMs: number;\n}\n\n/**\n * Ids are opaque, but a cookie is attacker-controlled input (a sibling\n * subdomain can set one). The value ends up in an HTTP header, and\n * `Headers.set` throws on anything outside ISO-8859-1 — so a single odd\n * cookie would break every `fetch` the tracing patch touches. Only the URL\n * \"unreserved\" set is accepted; every id this SDK mints is a UUID.\n */\nexport const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;\n\nexport function isValidIdentityId(value: unknown): value is string {\n return typeof value === \"string\" && IDENTITY_ID_PATTERN.test(value);\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Reads a device cookie value. Accepts the JSON envelope written by\n * `serializeDeviceCookie` and, for cookies seeded before the envelope existed,\n * a bare device id. Returns `null` for anything else — a malformed cookie is\n * treated as absent, never as an error, so a corrupted value cannot take the\n * page down.\n */\nexport function parseDeviceCookie(raw: string | null | undefined): DeviceCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text) return null;\n\n if (!text.startsWith(\"{\")) {\n return isValidIdentityId(text) ? { deviceId: text } : null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const candidate = parsed as Record<string, unknown>;\n if (!isValidIdentityId(candidate.deviceId)) return null;\n\n const state: DeviceCookieState = { deviceId: candidate.deviceId };\n if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;\n if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;\n return state;\n}\n\n/**\n * Cookie values may not contain `;`, `,` or whitespace, and JSON contains\n * quotes and commas. The envelope is therefore URI-encoded; `parseDeviceCookie`\n * reverses it. Optional fields are omitted rather than written as `null` so\n * the cookie stays as small as the state it carries.\n */\nexport function serializeDeviceCookie(state: DeviceCookieState): string {\n if (!isValidIdentityId(state.deviceId)) {\n throw new Error(\"[reopt] deviceId must be a non-empty string without control characters\");\n }\n const envelope: DeviceCookieState = { deviceId: state.deviceId };\n if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;\n if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;\n return encodeURIComponent(JSON.stringify(envelope));\n}\n\n/**\n * Reads a consent cookie. Only boolean entries survive; anything else in the\n * object is dropped rather than failing the whole cookie, because one odd key\n * must not erase a user's recorded opt-out.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text.startsWith(\"{\")) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\n const state: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n state[category] = decision;\n }\n }\n return state;\n}\n\nexport function serializeConsentCookie(state: ConsentCookieState): string {\n const clean: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(state)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n clean[category] = decision;\n }\n }\n return encodeURIComponent(JSON.stringify(clean));\n}\n\n/**\n * \"Opted out\" means the visitor refused the `analytics` category. An absent\n * cookie or an undecided category is *not* an opt-out — it is the default\n * state of every first visit, and treating it as refusal would make consent\n * banners mandatory for every integration.\n */\nexport function isOptedOut(consent: ConsentCookieState | null | undefined): boolean {\n return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;\n}\n\n// ─── Session tokens ───────────────────────────────────────────────────────────\n\n/**\n * Sessions are assigned by ingest, not by the browser. To let a later request\n * — from the same browser, or from a server acting for it — join that session\n * with authority, ingest hands the browser its session id together with an\n * HMAC over it, and the browser sends both back as `reopt-session-id`. An\n * unsigned or wrongly signed value is a hint at most: ingest falls back to\n * deciding the session from the device, exactly as if the header were absent.\n *\n * The token is `base64url(HMAC-SHA256(secret, sessionId))`. The secret is\n * per project and never leaves the server. WebCrypto only, so this runs in\n * browsers, edge runtimes and Node alike.\n */\nexport const SESSION_HEADER_SEPARATOR = \".\";\n\nexport interface SessionCredential {\n id: string;\n token: string;\n}\n\n/** `<id>.<token>` — what travels in `reopt-session-id`. */\nexport function formatSessionHeader(credential: SessionCredential): string {\n return `${credential.id}${SESSION_HEADER_SEPARATOR}${credential.token}`;\n}\n\n/** Splits a `reopt-session-id` value. `null` unless both parts are well-formed. */\nexport function parseSessionHeader(value: string | null | undefined): SessionCredential | null {\n if (!value) return null;\n const at = value.lastIndexOf(SESSION_HEADER_SEPARATOR);\n if (at <= 0 || at === value.length - 1) return null;\n const id = value.slice(0, at);\n const token = value.slice(at + 1);\n return isValidIdentityId(id) && /^[A-Za-z0-9_-]{43}$/.test(token) ? { id, token } : null;\n}\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n let binary = \"\";\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);\n const b64 = typeof btoa === \"function\" ? btoa(binary) : Buffer.from(binary, \"binary\").toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n}\n\n/** Issues the token for `sessionId`. Server-side only — needs the project secret. */\nexport async function signSessionToken(secret: string, sessionId: string): Promise<string> {\n if (!secret) throw new Error(\"[reopt] a session signing secret is required\");\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(sessionId));\n return base64url(signature);\n}\n\n/**\n * Constant-time check of a presented token. Recomputes and compares the\n * digests byte by byte rather than using `subtle.verify` with a decoded\n * token, so a malformed token can never throw its way past the check.\n */\nexport async function verifySessionToken(secret: string, credential: SessionCredential): Promise<boolean> {\n if (!secret || !credential) return false;\n const expected = await signSessionToken(secret, credential.id);\n if (expected.length !== credential.token.length) return false;\n let diff = 0;\n for (let index = 0; index < expected.length; index++) {\n diff |= expected.charCodeAt(index) ^ credential.token.charCodeAt(index);\n }\n return diff === 0;\n}\n"]}